text stringlengths 8 267k | meta dict |
|---|---|
Q: jQuery Fancybox & Loading file using location.hash both not working http://www.alphenweer.nl/index.php#page:alphen-afgelopenuur.php
The first thing you will see is the first bug.
I use the function getdata() located in my index.js file to call the page, and put it in the main DIV. That could be a problem, if anyone wants to link to a certain page people still have to click on another link. So i came up with this solution (that is also located in my index.js file:
function getdataonload(){
var page = window.location.hash;
if(window.location.hash != ""){
page = page.replace('#page:', '');
getdata('nosub/content/'.page);
}
}
// and for the links:
<a href="#page:alphen-afgelopenuur.php">..</a>
But that doesn't seem to work properly. The div now gets filled with my main index.php file again. Why is this happening, what am i doing wrong?
And i also seem to have another bug wwith jQuery Fancybox.
For example, go to the same link, click on "Ontladingen" and then select one of the links popping up. The source of those pages are almoast identical, but its like this:
<a href="link/to/image.png" class="fancybox">
<img src="link/to/image.png" alt="example">
</a>
And then on the bottom of my page i have this piece of code:
<script type="text/javascript">
$("a.fancybox").fancybox();
</script>
Now it should work. But it isn't working. Why is that, and how can i solve that problem?
Could you please all help me with both my problems?
A: For first problem-
you have to build full URL at getdata('nosub/content/'.page); . It should be like 'http:// ... nosub/content/'
For the 2nd problem -
You can try to write the code as follows -
<script type="text/javascript">
$(document).ready(function() {
$("a.fancybox").fancybox();
});
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is it possible to use a String instead of a variable name in Java I've created 3 variables
radio1
radio2
radio3
is it possible to use a for loop and from a String called "radio" to add the counter in the end in order to get the variable?
for instance something like this
for(i=1;i<=3;i++)
if(("radio" + i).method())
do something
thanks in advance
A: You can use a Radio object and use arrays instead:
Radio[] radios = new Radio[] {radio1, radio2, radio3};
for(i=0;i<3;i++)
if(radios[i].method())
do something
If you want to access variable by forming their names, you can also use Java's reflection API. But it is an expensive operation and is not advisable in general.
A: It looks to me like you want to use a Dictionary or similar data structure, which lets you store objects indexed by, for example, a string.
EDIT
As several people noted, HashMap is a more modern and better alternative.
A: You should be using an array so you can easily iterate over all of them.
You could also play with Lists if you do not know how many items there wil be.
A: The most convenient way is to use an intermediate array like this:
Radio radio1, radio2, radio3;
for(Radio radio: Arrays.asList(radio1, radio2, radio3))
if( radio.method() )
doSomething();
The java.util.Arrays is provided by the JDK.
This works. But please think about it, how many times you really want three separate Radio instances vs. how many times you are not interested in one of them but in all of them. In the later case put the three instances into a Collection or into an array right from the start and forget about the three individual instances.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Where should I put my static text files in order to be OTPy? I'm building a server with cowboy, and I've got some static HTML pages that I want to serve. Is there an OTP friendly place to put that sort of thing? Is there an established way to tell rebar where to look for this sort of thing?
A: If the pages are part of the application, then typically under the priv directory, for example priv/docroot or similar. I don't know about rebar, but in general, filename:join(code:priv_dir(?APPNAME), "docroot") could be used to compute the full directory name at runtime.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to pop a layer in cocos2d please look the following picture
i want to do this function,when i click some button,it pop out a layer
my code is
-(id)init{
if (self = [super init]) {
CCMenuItem *successbtn = [CCMenuItemImage itemFromNormalImage:@"success.png"
selectedImage:@"success.png"
target:self
selector:@selector(successgame:)];
CCMenu *ccMenu = [CCMenu menuWithItems:successbtn, nil];
ccMenu.position=ccp(950,700);
[self addChild:ccMenu z:1 tag:2];
}
return self;
}
-(void)successgame:(id)sender{
//how can i write here?
}
so how can i write?
A: There is two possibilities. Either just add the button when you really want to show it and remove it from the Scenegraph as soon as it is not needed anymore.
Alternatively just make it invisible with the visible-property.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is it possible to display 2 video on 2 different surface view within an android activity? I've done some research on display 2 different videos on 2 different surface view, but didn't manage to find any.
Is this possible in android?
I'm want to use android MediaPlayer to stream the videos.
Found something similar but is in iphone. Is it possible to play 2 video file simultaneously in the same view?
Thanks in advance. :)
A: Yes you can do this by using fragment.Though it will be better in tablet.Look it out if it can work in your case.Here example is different but the concept is same. :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to center a relatively positioned element with jquery? I am trying to make a function which returns "what the left value should be to center the current element". This allows me to animate to the center (and back) or to simply center an item.
I am having trouble with the relative positioning part though. What did I miss?
Thanks!
jQuery.fn.centerHorizontalOffset = function () {
var position = $(this).css("position");
if (position == "relative"){
return (($(window).width() - $(this).width()) / 2) - $(this).parent().offset().left;
} else if (position == "absolute"){
return ($(window).width() - $(this).width()) / 2;
}
return ($(window).width() - $(this).width()) / 2;
}
jQuery.fn.centerHorizontalDistance = function () {
return $(this).centerHorizontalOffset()-$(this).position().left;
}
$('#myDiv').css('left', $('#myDiv').centerHorizontalDistance());
A: I would look into using jQuery UI's new "Position" plugin: http://jqueryui.com/demos/position/ - it's great at doing exactly what you're after.
...not a direct answer to your question I know, but this has saved me a ton of time, and why re-invent the wheel? =). Good luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Help with basic reading user input in C I am currently just learning C and for a project I need to read in integer inputs from the user. Currently I am using code that looks like this:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int a, b;
printf("Please enter your first number");
while((a = getchar()) != '\n') {
}
printf("test");
return 0;
}
Im not sure how to get the number with getchar and then store it in a variable i can use.
Also I'm using = '\n' in the while statement because I don't really understand how EOF works (as in the K&R book) because whenever i use EOF i go into this loop i cant get out of.
Thanks for any advice anyone can offer.
A: You can use scanf.
Have a look at this example:
printf("Please enter your first number ");
int number=0;
scanf ("%d",&number);
A: The scanf answer above mine is correct, but if you haven't read about addresses or format strings, it may be difficult to grok.
You can convert your character to its integer equivalent by subtracting '0' from it:
char c = getchar();
int n = c - '0';
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: jQuery - If ( "A" left value is equal to "B" width minus "C" width ) Title says it well:
If ( element-A's left value is equal to element-B's width minus element-C's width )
http://jsfiddle.net/UAKXq/1
What am I doing wrong?
A: This one is correct
if (parseInt(A.css('left')) == B.width() - C.width()) {
http://jsfiddle.net/UAKXq/14/
A: use this
if(parseInt(A.css('left')) == (B.width() - C.width()))
A: if( parseInt(A.css('left'),10) === parseInt(B.css('width'), 10) - parseInt(C.css('width'), 10)) {
$('body').css({ background: 'red' });
}
http://jsfiddle.net/UAKXq/20/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Read dataset in R in which comma is used for field separator and decimal point How could you read this dataset in R, the problem is
that the numbers are floats and are like 4,000000059604644E+16
and they are separated by a ,
4,000000059604644E-16 , 7,999997138977056E-16, 9,000002145767216E-16
4,999999403953552E-16 , 6,99999988079071E-16 , 0,099999904632568E-16
9,999997615814208E-16 , 4,30000066757202E-16 , 3,630000114440918E-16
0,69999933242798E-16 , 0,099999904632568E-16, 55,657576767799999E-16
3,999999761581424E-16, 1,9900000095367432E-16, 0,199999809265136E-16
How would you load this kinf of dataset in R so it has 3 columns.
If I do
dataset <- read.csv("C:\\data.txt",header=T,row.names=NULL)
it would return 6 columns instead 3...
A: It might be best to transform that input data to use decimal points, rather than commas, in the floating point numbers. One way you could do this is to use sed (it looks like you are using Windows, so you would likely need to sed to use this approach):
sed 's/\([0-9]\),\([0-9]\)/\1.\2/g' data.txt > data2.txt
File data2 looks like this:
4.000000059604644E-16 , 7.999997138977056E-16, 9.000002145767216E-16
4.999999403953552E-16 , 6.99999988079071E-16 , 0.099999904632568E-16
9.999997615814208E-16 , 4.30000066757202E-16 , 3.630000114440918E-16
0.69999933242798E-16 , 0.099999904632568E-16, 55.657576767799999E-16
3.999999761581424E-16, 1.9900000095367432E-16, 0.199999809265136E-16
Then in R:
dataset <- read.csv("data2.txt",row.names=NULL)
A: Here is an all R solution that uses three read.table calls. The first read.table statement reads each data row as 6 fields; the second read.table statement puts the fields back together properly and reads them and the third grabs the names from the header.
fn <- "data.txt"
# create a test file
Lines <- "A , B , C
4,000000059604644E-16 , 7,999997138977056E-16, 9,000002145767216E-16
4,999999403953552E-16 , 6,99999988079071E-16 , 0,099999904632568E-16
9,999997615814208E-16 , 4,30000066757202E-16 , 3,630000114440918E-16
0,69999933242798E-16 , 0,099999904632568E-16, 55,657576767799999E-16
3,999999761581424E-16, 1,9900000095367432E-16, 0,199999809265136E-16"
cat(Lines, "\n", file = fn)
# now read it back in
DF0 <- read.table(fn, skip = 1, sep = ",", colClasses = "character")
DF <- read.table(
file = textConnection(do.call("sprintf", c("%s.%s %s.%s %s.%s", DF0))),
col.names = names(read.csv(fn, nrow = 0))
)
which gives:
> DF
A B C
1 4.000000e-16 7.999997e-16 9.000002e-16
2 4.999999e-16 7.000000e-16 9.999990e-18
3 9.999998e-16 4.300001e-16 3.630000e-16
4 6.999993e-17 9.999990e-18 5.565758e-15
5 4.000000e-16 1.990000e-16 1.999998e-17
Note: The read.csv statement in the question implies that there is a header but the sample data does not show one. I assumed that there is a header but if not then remove the skip= and col.names= arguments.
A: It's not pretty, but it should work:
x <- matrix(scan("c:/data.txt", what=character(), sep=","), byrow=TRUE, ncol=6)
y <- t(apply(x, 1, function(a) { left <- seq(1, length(a), by=2)
as.numeric(paste(a[left], a[left+1], sep="."))
} ))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: file's owner of xib is not what i expect i'm using xcode4.
i have a xib window (perhaps copyed by another one, i forgot because i have made it some times ago) named: chooseCharacter.xib
i have the chooseCharacter.h and .m as view controller (i thought)
i have added
-(IBAction)doneButtonClick;
on the chooseCharacter.h but i've not seen it in interface builder actions...
i have added this on HighScoreViewController.h and it now shows up...
however, if i put it on HighScoreViewController.h i must put the implementation in chooseCharacter.m or i get
-[ChooseCharacter doneButtonClick]: unrecognized selector sent to instance 0xcc0d9b0'
seems that the window is binded with a file's owner that is HighScoreViewController.h but search implementation in ChooseCharacter.m!!!
how can i bind the xib to the right file?
thanks
A: found it.
selecting in interface builder, file's owner and clicking in identity inspector under class was HighScoreViewController, changed to chooseCharacter now it works
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get more encapsulation in C#? I have recently learned C# fully, approximately. However, in C++ I could implement a better encapsulation when passing objects to methods, with const modifier. But in C#, objects can be modified through the reference parameter, such as Dispose on Graphics object.
I need sometimes more encapsulation. Properties can give a better solution. However, I have found that, for example, the modification to Form.Location property or even to its X member is not allowed. Although Form.Location is get; set; property, its members can not be modified. I tried to do as it with a Point {get; set;} property but I can still modify X member.
This is also an issue when a method for example Disposes an object, as eariler mentioned.
How can I implement more encapsulation in C#?
A: You cannot the X property of Form.Location, because Form.Location is a property that returns a value type (Point). As soon as you access Form.Location, you get a copy of the location; thus, changing something in this copy is meaningless. Since this.Location.X = ... is an obvious mistake, the C# compiler prevents you from doing it.
You can, however, replace the complete value of Form.Location, since its property setter is public:
private void button1_Click(object sender, EventArgs e)
{
// move window to the left edge of the screen
this.Location = new Point(0, this.Location.Y);
}
or, alternatively,
private void button1_Click(object sender, EventArgs e)
{
// move window to the left edge of the screen
var loc = this.Location;
loc.X = 0; // yes, it's a mutable struct
this.Location = loc;
}
To get back to your original question: If you want to make an object accessible, but do not want it to be modified, you will need to encapsulate it yourself. For example, if you want the consumers of your class to be able to Draw on your Graphics object but do not want them to call Dispose, just cannot expose the Graphics object directly. Instead, you need to wrap every method that the consumer is allowed to call:
// bad, consumer can do anything with the Graphics object
public Graphics Graphics
{
get { return graphics; }
}
// good, consumer can only do specific stuff
public void Draw(...)
{
graphics.Draw(...);
}
A: Here are two articles discussing why there is no "const" modifier in C#:
http://blogs.msdn.com/b/ericgu/archive/2004/04/22/118238.aspx
http://blogs.msdn.com/b/slippman/archive/2004/01/22/61712.aspx
Designing classes as immutable is sometimes a solution to your problem, but is not always an option, since it does only work on the "class" level, not on the method level. And sometimes you may have to expose a member variable of your class which is not of an immutable type and could therefore be modified from outside.
Best option: live with that, in practice the importance of const-ness is often overrated.
A: You need Point { get; }. It's the set that allows modification.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Javascript procedural image Is it possible to create in javascript(without connecting to server) image, that after creation can be placed on website? In example, I send only formula from server, and client creates image based on it which I can use as jpg/png/bmp background(and do repeating etc).
A: Yes. There is a canvas element in HTML5. It can be used for 2d images and 3d animations etc.
Here is a set of tutorials about it.
Do you mean something like this:
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
var centerX = 70;
var centerY = 70;
var radius = 70;
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = "#8ED6FF";
context.fill();
context.lineWidth = 5;
context.strokeStyle = "black";
context.stroke();
var img = canvas.toDataURL("image/png");
/*
returns "data:image/png;base64,iVBORw0KGg...."
it can be used wherever you want:
-images
-style
-etc
*/
var b = document.getElementById("foo");
b.style.backgroundImage = "url(" + img + ")";
Demo and with text
A: If you want a cross browser solution look into Raphael.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I combine this two htaccess rules? I have two conditions for the pages /portfolio and /portfolio/
RewriteRule ^portfolio$ index.php?p=portfolio&%{QUERY_STRING}
RewriteRule ^portfolio/$ index.php?p=portfolio&%{QUERY_STRING}
Is there a possibility to combine this conditions?
A: RewriteRule ^portfolio/?$ index.php?p=portfolio&%{QUERY_STRING}
the ? says "exactly 0 or 1 '/'"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I maximize HTTP network throughput? I was running a benchmark on CouchDB when I noticed that even with large bulk inserts, running a few of them in parallel is almost twice as fast. I also know that web browsers use a number of parallel connections to speed up page loading.
What is the reason multiple connections are faster than one? They go over the same wire, or even to localhost.
How do I determine the ideal number of parallel requests? Is there a rule of thumb, like "threadpool size = # cores + 1"?
A: The gating factor is not the wire itself which, after all, runs pretty quick (ignoring router delays) but the software overhead at each end. Each physical transfer has to be set up, the data sent and stored, and then completely handled before anything can go the other way. So each connection is effectively synchronous, no matter what it claims to be at the socket level: one socket operating asynchronously is still moving data back and forth in a synchronous way because the software demands synchronicity.
A second connection can take advantage of the latency -- the dead time on the wire -- that arises from the software doing its thing for first connection. So, even though each connection is synchronous, multiple connections let things happen much faster. Things seem (but of course only seem) to happen in parallel.
You might want to take a look at RFC 2616, the HTTP spec. It will tell you about the interchanges that happen to get an HTTP connection going.
I can't say anything about optimal number of parallel requests, which is a matter between the browser and the server.
A: Each connection consume one own thread. Each thread, have a quantum for consume CPU, network and other resources. Mainly, CPU.
When you start a parallel call, thread will dispute CPU time and run things "at the same time".
It's a high level overview of the things. I suggest you to read about asynchronous calls and thread programming to understand it better.
[]'s,
And Past
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Thread safe adding of subitem to a ListView control I'm trying to convert an old Windows Forms Application to a WPF application.
The following code no longer compiles under C# .NET 4.0:
// Thread safe adding of subitem to ListView control
private delegate void AddSubItemCallback(
ListView control,
int item,
string subitemText
);
private void AddSubItem(
ListView control,
int item,
string subitemText
) {
if (control.InvokeRequired) {
var d = new AddSubItemCallback(AddSubItem);
control.Invoke(d, new object[] { control, item, subitemText });
} else {
control.Items[item].SubItems.Add(subitemText);
}
}
Please help to convert this code.
A: Hopefully the following blog post will help you. In WPF you use Dispatcher.CheckAccess/Dispatcher.Invoke:
if (control.Dispatcher.CheckAccess())
{
// You are on the GUI thread => you can access and modify GUI controls directly
control.Items[item].SubItems.Add(subitemText);
}
else
{
// You are not on the GUI thread => dispatch
AddSubItemCallback d = ...
control.Dispatcher.Invoke(
DispatcherPriority.Normal,
new AddSubItemCallback(AddSubItem)
);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery UI tabs positioned about 50% of their height below eachother This is quite odd, and I can't get it to stop happening.
Here's the relevant code. I'm using a Google CDN host for the UI-lightness theme.
<div id="prof_div">
<ul>
<li><a href="#prof_home">Profile</a></li><br/>
<li><a href="#prof_details">Details</a></li><br/>
<li><a href="#prof_settings">Settings</a></li><br/>
</ul>
That's the only relevant HTML. Here's jQuery/JavaScript
$(document).ready(function() {
$('#prof_div').tabs({
fx: { height: 'toggle', opacity: 'toggle' }
});
});
And it's displaying like this:
TAB 1
TAB 2
TAB 3
Instead of like this:
TAB 1 - TAB 2 - TAB 3
I have no custom CSS acting on them at all (I even blanked my stylesheets to check).
Any idea why this is happening? I'll post a screenshot if necessary.
Thanks! :)
EDIT
Here's my CDN requests
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/ui-lightness/jquery-ui.css" type="text/css" media="all" />
<script type="text/javascript" src="https://www.google.com/jsapi?key=very long string"></script>
<script type="text/javascript" src="/JSFunctions.js"></script>
<script type="text/javascript">
google.load("jquery", "1.6.4");
google.load("jqueryui", "1.8.16");
....
</script>
A: Remove those ending <br/>s from your <li>s. They shouldn't be there.
<div id="prof_div">
<ul>
<li><a href="#prof_home">Profile</a></li><br/>
<li><a href="#prof_details">Details</a></li><br/>
<li><a href="#prof_settings">Settings</a></li><br/>
</ul>
Here's a fiddle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Which strategy to use with multiprocessing in python I am completely new to multiprocessing. I have been reading documentation about multiprocessing module. I read about Pool, Threads, Queues etc. but I am completely lost.
What I want to do with multiprocessing is that, convert my humble http downloader, to work with multiple workers. What I am doing at the moment is, download a page, parse to page to get interesting links. Continue until all interesting links are downloaded. Now, I want to implement this with multiprocessing. But I have no idea at the moment, how to organize this work flow. I had two thoughts about this. Firstly, I thought about having two queues. One queue for links that needs to be downloaded, other for links to be parsed. One worker, downloads the pages, and adds them to queue which is for items that needs to be parsed. And other process parses a page, and adds the links it finds interesting to the other queue. Problems I expect from this approach are; first of all, why download one page at a time and parse a page at a time. Moreover, how do one process know that there are items to be added to queue later, after it exhausted all items from queue.
Another approach I thought about using is that. Have a function, that can be called with an url as an argument. This function downloads the document and starts parsing it for the links. Every time it encounters an interesting link, it instantly creates a new thread running identical function as itself. The problem I have with this approach is, how do I keep track of all the processes spawned all around, how do I know if there is still processes to running. And also, how do I limit maximum number of processes.
So I am completely lost. Can anyone suggest a good strategy, and perhaps show some example codes about how to go with the idea.
A: Here is one approach, using multiprocessing. (Many thanks to @Voo, for suggesting many improvements to the code).
import multiprocessing as mp
import logging
import Queue
import time
logger=mp.log_to_stderr(logging.DEBUG) # or,
# logger=mp.log_to_stderr(logging.WARN) # uncomment this to silence debug and info messages
def worker(url_queue,seen):
while True:
url=url_queue.get()
if url not in seen:
logger.info('downloading {u}'.format(u=url))
seen[url]=True
# Replace this with code to dowload url
# urllib2.open(...)
time.sleep(0.5)
content=url
logger.debug('parsing {c}'.format(c=content))
# replace this with code that finds interesting links and
# puts them in url_queue
for i in range(3):
if content<5:
u=2*content+i-1
logger.debug('adding {u} to url_queue'.format(u=u))
time.sleep(0.5)
url_queue.put(u)
else:
logger.debug('skipping {u}; seen before'.format(u=url))
url_queue.task_done()
if __name__=='__main__':
num_workers=4
url_queue=mp.JoinableQueue()
manager=mp.Manager()
seen=manager.dict()
# prime the url queue with at least one url
url_queue.put(1)
downloaders=[mp.Process(target=worker,args=(url_queue,seen))
for i in range(num_workers)]
for p in downloaders:
p.daemon=True
p.start()
url_queue.join()
*
*A pool of (4) worker processes are created.
*There is a JoinableQueue, called url_queue.
*Each worker gets a url from the url_queue, finds new urls and adds
them to the url_queue.
*Only after adding new items does it call url_queue.task_done().
*The main process calls url_queue.join(). This blocks the main
process until task_done has been called for every task in the
url_queue.
*Since the worker processes have the daemon attribute set to True,
they too end when the main process ends.
All the components used in this example are also explained in Doug Hellman's excellent Python Module of the Week tutorial on multiprocessing.
A: What you're describing is essentially graph traversal; Most graph traversal algorithms (That are more sophisticated than depth first), keep track of two sets of nodes, in your case, the nodes are url's.
The first set is called the "closed set", and represents all of the nodes that have already been visited and processed. If, while you're processing a page, you find a link that happens to be in the closed set, you can ignore it, it's already been handled.
The second set is unsurprisingly called the "open set", and includes all of the edges that have been found, but not yet processed.
The basic mechanism is to start by putting the root node into the open set (the closed set is initially empty, no nodes have been processed yet), and start working. Each worker takes a single node from the open set, copies it to the closed set, processes the node, and adds any nodes it discovers back to the open set (so long as they aren't already in either the open or closed sets). Once the open set is empty, (and no workers are still processing nodes) the graph has been completely traversed.
Actually implementing this in multiprocessing probably means that you'll have a master task that keeps track of the open and closed sets; If a worker in a worker pool indicates that it is ready for work, the master worker takes care of moving the node from the open set to the closed set and starting up the worker. the workers can then pass all of the nodes they find, without worrying about if they are already closed, back to the master; and the master will ignore nodes that are already closed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Click binding not working I'm having trouble with the click binding. I'm trying to run some sample code from the Knockout website, which isn't working. The number of clicks isn't updating. I'm not getting any javascript errors in Firefox. Can someone help?
This is the code I have:
<head runat="server">
<script type="text/javascript" src="/Scripts/jquery-1.6.4.js"></script>
<script type="text/javascript" src="/Scripts/jquery.tmpl.js"></script>
<script type="text/javascript" src="/Scripts/knockout-1.2.1.js"></script>
<script type="text/javascript">
var clickCounterViewModel = function () {
this.numberOfClicks = ko.observable(0);
this.registerClick = function () {
this.numberOfClicks(this.numberOfClicks() + 1);
}
this.hasClickedTooManyTimes = ko.dependentObservable(function () {
return this.numberOfClicks() >= 3;
}, this);
};
ko.applyBindings(new clickCounterViewModel());
</script>
</head>
<body>
<div>You've clicked <span data-bind="text: numberOfClicks"> </span> times</div>
<button data-bind="click: registerClick, enable: !hasClickedTooManyTimes()">Click me</button>
<div data-bind="visible: hasClickedTooManyTimes">
That's too many clicks! Please stop before you wear out your fingers.
<button data-bind="click: function() { numberOfClicks(0) }">Reset clicks</button>
</div>
</body>
A: You want to move your script tag to the bottom of the document or put it in a an onload/ready function. You need at least ko.applyBindings to execute after the rest of the DOM has been loaded.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rotate, then translate in three.js I would like to rotate then a plane created with THREE.PlaneGeometry, but I have some problems.
*
*What's the axis in front of the camera with FirstPersonCamera ?
My own tests have revealed a X-front/back, Y-top/bottom, Z-left/right, am I right ?
*In order to make a cube with these plane, I use the following code (cut for display only X-axis faces). For a reason I don't understand, there is a small space between the block and the orthogonal basis. It seems that rotation is applied after translation. How can I fix it ?
function lol() {
var mesh = new THREE.Mesh(xFacesGeometry, material);
mesh.matrix.setRotationFromEuler(new THREE.Vector3(0, ath.PI / 2), 'XYZ');
mesh.matrix.setPosition(new THREE.Vector3(x * 20 + 10, y * 20 + 10, z * 20 + 10));
mesh.matrixAutoUpdate = false;
}
lol(0, 0, 0);
lol(1, 0, 0);
Full code here (use ctrl+click to move backward) : http://jsfiddle.net/u8ZHC/
A: Just to answer this : the best way to specify the order in which translations / rotations have to be applied is to use multiple nodes.
var pitchNode = new THREE.Object3D( );
var yawNode = new THREE.Object3D( );
var rollNode = new THREE.Object3D( );
var positionNode = new THREE.Object3D( );
// here come the order
scene.add( pitchNode );
pitchNode.add( yawNode );
yawNode.add( rollNode );
rollNode.add( positionNode );
A: Try to update matrix before translate the position:
mesh.matrix.setRotationFromEuler(new THREE.Vector3(0, Math.PI / 2), 'XYZ');
mesh.updateMatrix();
mesh.translate(...);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How can I set default parameter value to BigInteger type? I need to have a class that has a constructor with BigInteger type. I'd like to set a default value to 0 to it with this code, but I got compile error.
public class Hello
{
BigInteger X {get; set;}
public Hello(BigInteger x = 0)
{
X = x;
}
}
public class MyClass
{
public static void RunSnippet()
{
var h = new Hello(); // Error <--
What's wrong? Is there way to set default value to BigInteger parameter?
A: Default parameters only work compile time constants (and value types where the parameter can be default(ValType) or new ValType()), and as such don't work for BigInteger. For your case, you could perhaps do something like this; providing a constructor overload that takes int, and make that have a default parameter:
public Hello(int x = 0) : this(new BigInteger(x)) {}
public Hello(BigInteger x)
{
X = x;
}
In case you are wondering, the x = 0 doesn't count as a constant when the type is a BigInteger, because converting 0 to BigInteger would involve invoking the implicit conversion operator for int to BigInteger.
A: In this particular case, since the default value you want is zero, you can use the default BigInteger constructor because BigInteger is a value type:
public class Hello
{
BigInteger X { get; set; }
public Hello(BigInteger x = new BigInteger())
{
X = x;
}
}
This will not work with values besides zero because the expression must be a compile time constant:
Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. A default value must be one of the following types of expressions:
*
*a constant expression;
*an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;
*an expression of the form default(ValType), where ValType is a value type.
A: Use an overloaded constructor
public class Hello
{
BigInteger X {get; set;}
public Hello(BigInteger x)
{
X = x;
}
public Hello()
{
X = new BigInteger(0);
}
}
A: From §10.6.1 of the C# 4 spec:
The expression in a default-argument must be one of the following:
*
*a constant-expression
*an expression of the form new S() where S is a value type
*an expression of the form default(S) where S is a value type
The expression must be implicitly convertible by an identity or nullable conversion to the type of the parameter.
What this means for BigInteger is that the only option for default argument is to use 0, expressed either as new BigInteger() or default(BigInteger).
BigInteger x = 0 doesn't work, because 0 is of type int and the implicit conversion from int to BigInteger is not “an identity or nullable conversion”.
If you want the default argument to be anything else other than 0, you have several options:
*
*use BigInteger?, let the default be null and at the beginning of the method check for that. If the parameter is null, set it to the default value.
*create another overload of the method that takes e.g. int with the default argument specified. This method in turn calls the BigInteger overload that doesn't have the default argument. This assumes the default value fits in an int, but I think that should be the case most of the time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Segmentation Fault on creating an array in C I have recently migrated to a new laptop - HP dv6119tx (Intel Core i5, 4 GB RAM). It has Windows 7 Home Premium 64 bit installed.
I am trying to create an array of type int of length 10^6 in C++ (Dev C++), which I used to create comfortably on my last laptop (32 bit Windows 7 Ultimate/Ubuntu Linux, 2GB RAM) and every other environment I have programmed on (It should take around 3.5 MB of RAM). But with the current setup, I am getting a "Segmentation Fault" error in Debug Mode.
SCREENSHOTS (EDIT) :
The first screenshot shows 10^5 working on the current setup and 10^6 not. I do not have a screenshot for 10^6 working on my last machine but I have used it many times.
EDIT:
The program would work just fine if I declared the array as global instead or created it dynamically on the heap as
int* a = new int[MAX];
But what I fail to understand is that when the local array is taking a meager 3.5 MB of memory on the stack (and was working fine on a 2 GB machine), why should this issue surface with a 4GB machine? Is this a user stack space issue? Can it be increased manually?
EDIT 2:
I am particularly asking this question because I have submitted numerous solutions on SPOJ with 10^6 sized arrays created on the stack. With my current setup, I feel crippled not being able to do that. I prefer stack over heap whenever possible because it has no memory leak issues; and local variables over global variables because they are neat and do not mess up the namespace.
A: A four megabyte stack is pretty big. The default size on Windows is 1MB. You need to use the /STACK option to the linker to ask for a larger size.
A: Arrays created like that are stored on the stack. However, the stack has very limited size, therefore you are hitting a stackoverflow and a crash.
The way to do it is to allocate it on the heap:
int *a = (int*)malloc(MAX * sizeof(int));
// Do what you need to do.
// Free it when you're done using "a".
free(a);
A: Instead of malloc'ating memory you can specify your buffer as static. E.g.:
static int a[MAX];
Advantage of this approach is that you need not to track your memory allocation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: iOS Reachability error will not display I have created an error message that should display if the user can not connect to google.com by either WI-FI or WWAN. I do not get any coding errors, so nothing seems to be wrong. I am using a UIWebview that goes to twitter.com. The issue may be that I am trying to get the error to display when the view loads and not the UIWebview, but I am not sure. Another issue that I am having is that I can not get "reachability" recognized as a name in the TwitterViewController.h file. Here is the code:
TwitterViewController.h
#import <UIKit/UIKit.h>
#import "Reachability.h"
@interface TwitterViewController : UIViewController {
Reachability *reachability;
}
@end
TwitterViewController.m
#import "TwitterViewController.h"
#import <SystemConfiguration/SystemConfiguration.h>
#include <netinet/in.h>
#import "TwitterView.h"
@implementation TwitterViewController
- (void)viewDidLoad {
[super viewDidLoad];
Reachability *r = [Reachability reachabilityWithHostName:@"http://www.google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) {
UIAlertView *NEalert = [[UIAlertView alloc] initWithTitle: @"Error"
message: @"Could not load the webpage. Please check your internet connection."
delegate: nil
cancelButtonTitle: @"Dismiss"
otherButtonTitles: nil];
[NEalert show];
[NEalert release];
}
}
#pragma mark -
#pragma mark Memory Management
- (void)dealloc {
[super dealloc];
}
#pragma mark -
#pragma mark Initialisation
- (id)init {
self = [super init];
if (self) {
self.hidesBottomBarWhenPushed = YES;
UINavigationBar objects
self.title = @"Twitter";
UIView *twitterView = [[TwitterView alloc] initWithParentViewController:self];
self.view = twitterView;
[twitterView release];
}
return self;
}
#pragma mark -
#pragma mark Action Methods
- (void)twitterBUTTONAction {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"NFAGaming's Twitter"
message: @"To follow NFAGaming on twitter, go to: twitter.com/NFAGaming"
delegate: nil
cancelButtonTitle: nil
otherButtonTitles: @"Ok", nil];
[alert show];
[alert release];
}
#pragma mark -
#pragma mark UIViewController Delegates
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
@end
EDIT:
This is what ended up working perfectly for me
{{Reachability *r = [Reachability reachabilityForInternetConnection];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if (internetStatus == NotReachable) {
UIAlertView *tNEalert = [[UIAlertView alloc] initWithTitle: @"Error"
message: @"Internet Connection Required"
delegate: self
cancelButtonTitle: @"Dismiss"
otherButtonTitles: nil];
[tNEalert show];
[tNEalert release];
}
else {
UIView *twitterView = [[TwitterView alloc] initWithParentViewController:self];
self.view = twitterView;
[twitterView release];
}
}}
A: I used to use reachability like this:
self.reachability = [Reachability reachabilityForInternetConnection];
if ( [self.reachability currentReachabilityStatus] == NotReachable) {
UIAlertView *noConnectionAlert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",@"Alert Title")
message:@"Internet connection is required." delegate:self
cancelButtonTitle:nil
otherButtonTitles:@"Ok", nil];
[noConnectionAlert show];
[noConnectionAlert release];
}
Use should use reachabilityWithHostName: only if you need to determine reachability to a specific host. See if this will work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rewriting URL based on who is logged in Im looking for the best way to change the URL to pages based on who is logged on, the limitation is all the pages are PRE generated so the actual html will already be generated and cannot be generated again on a pr user basis.
Posible solutions
A posible solution might be to use javascript to basicly add to the end of all URL ?=MyUserName , but im unsure if this will work with all spiders ( By all i mean the major search engines). This solution feels a bit dirty to me..
There might also be some way of of when the request comes in to then basicly say that response is from Default.aspx=?Username with doing a response.Redirect?
Its also importent to remember i will be changing the cache settings based on this, like saying if your not logged in the page can be cached.
A: I'm not sure if you must use .html files or another specific extension, but you could always create your own handler and process what you want to do on every request that way. Your handler would determine who is accessing the page and then do a Response.Redirect (or whatever action is necessary).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Put two monadic values into a pair and return it I am playing with Parsec and I want to combine two parsers into one with the result put in a pair, and then feed it another function to operate on the parse result to write something like this:
try (pFactor <&> (char '*' *> pTerm) `using` (*))
So I wrote this:
(<&>) :: (Monad m) => m a -> m b -> m (a, b)
pa <&> pb = do
a <- pa
b <- pb
return (a, b)
And
using :: (Functor f) => f (a, b) -> (a -> b -> c) -> f c
p `using` f = (uncurry f) <$> p
Is there anything similar to (<&>) which has been implemented somewhere? Or could this be written pointfree? I tried fmap (,) but it seems hard to match the type.
A:
Is there anything similar to (<&>) which has been implemented somewhere? Or could this be written pointfreely? I tried fmap (,) but it seems hard to match the type.
I don't now if it's implemented anywhere, but <&> should be the same as liftM2 (,). The difference to fmap is, that liftM2 lifts a binary function into the monad.
A: Using applicative style, there is no need to put the intermediate results into a tuple just to immediately apply an uncurried function. Just apply the function "directly" using <$> and <*>.
try ((*) <$> pFactor <*> (char '*' *> pTerm))
In general, assuming sane instances of Monad and Applicative,
do x0 <- m0
x1 <- m1
...
return $ f x0 x1 ...
is equivalent to
f <$> m0 <*> m1 <*> ...
except that the latter form is more general and only requires an Applicative instance. (All monads should also be applicative functors, although the language does not enforce this).
A: Note, that if you go the opposite direction from Applicative you'll see that the way you want to combine parsers fits nicely into Arrow paradigm and Arrow parsers implementation.
E.g.:
import Control.Arrow
(<&>) = (&&&)
p `using` f = p >>^ uncurry f
A: Better than <&> or liftM2 would be
(,) <$> a <*> b
since Applicative style seems to be gaining popularity and is very succinct. Using applicative style for things like this will eliminate the need for <&> itself, since it is much clearer than (,) <$> a <*> b.
Also this doesn't even require a monad - it will work for Applicatives too.
A: Yes, you could use applicative style but I don't believe that answers either of your questions.
Is there some already defined combinator that takes two arbitrary monads and sticks their value types in a pair and then sticks that pair in the context?
Not in any of the standard packages.
Can you do that last bit point free?
I'm not sure if there is a way to make a curried function with an arity greater than 1 point free. I don't think there is.
Hope that answers your questions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to update foreign key value in mysql database I have three tables: categories, languages and categories_languages. Categories_languages is many to many table which links together categories and languages. I would like to update a foregin key value in table languages but it throws me error #1451 - Cannot delete or update a parent row: a foreign key constraint fails!
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(11) unsigned NOT NULL auto_increment,
`name` varchar(20) NOT NULL,
`modified` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `languages` (
`id` char(2) NOT NULL,
`name` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `categories_languages` (
`id` int(11) unsigned NOT NULL auto_increment,
`category_id` int(11) unsigned NOT NULL,
`language_id` char(2) NOT NULL,
`translation` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_category_id_language_id` (`category_id`,`language_id`),
KEY `fk_language_id` (`language_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
ALTER TABLE `categories_languages`
ADD CONSTRAINT `categories_languages_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `categories_languages_ibfk_2` FOREIGN KEY (`language_id`) REFERENCES `languages` (`id`) ON DELETE CASCADE;
The error is clear to me, but how can I update a key value in this case? I tried adding ON UPDATA CASCADE:
ALTER TABLE `categories_languages`
ADD CONSTRAINT `categories_languages_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `categories_languages_ibfk_2` FOREIGN KEY (`language_id`) REFERENCES `languages` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
but that also fails with message: MySQL said: Documentation #1005 - Can't create table './db_dodo/#sql-c2f_80e6f.frm' (errno: 121)
A: You can temporarily suspend foreign key checking:
SET foreign_key_checks = 0;
UPDATE languages SET id='xyz' WHERE id='abc';
UPDATE categories_languages SET language_id='xyz' WHERE language_id='abc';
SET foreign_key_checks = 1;
EDIT: As for the foreign key problem: is the data stored on a local or a remote file system? errno 121 is EREMOTEIO (Remote I/O error). Perhaps there are permission problems on the target file system or it doesn't support the # character in filenames?
A: If you are looking for a temp solution you can also change the ON UPDATE action to CASCADE and modify your ids
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: .append jquery, limit to one character per I have these two functions:
jQuery.fn.enterText = function(e){
if( $("#cursor").val() && e.keyCode != 32 ){
var character = $("#cursor").val();
$("#cursor").val("");
this.append("<span class = 'text'>"+character+"</span>");
$("#cursor").insertAfter(".text:last");
$("#cursor").focus();
}
};
jQuery.fn.markCursor = function(e){
$(this).focus();
$(this).keyup(function(e) {
$("#cursor-start").enterText(e);
});
};
What my problem is that if I text is entered rapidly, some elements will have more than one character, for example (abc). I wanted to know how to limit to one character in an efficient manner, I thought of using an array, but would that not be too efficient?
A: This should do:
character = character.split("").join("</span><span class='text'>");
this.append("<span class='text'>" + character + "</span>");
I recommend changing some JQuery functions in ordinary JavaScript functions:
document.getElementById("cursor-start") is universally supported, so use it instead of $("#cursor-start"). Optimized code:
jQuery.fn.enterText = function(e){
var cursor = document.getElementById("cursor");
var character = cursor.value;
if(character && e.keyCode != 32){
cursor.value = "";
character = character.split("").join("</span><span class='text'>");
this.append("<span class = 'text'>"+character+"</span>");
$("#cursor").insertAfter(".text:last");
cursor.focus();
}
};
jQuery.fn.markCursor = function(e){
$(this).focus();
$(this).keyup(function(e) {
$("#cursor-start").enterText(e);
});
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: help with script path how do i reference my script properly so when deployed application won't have a problem finding it?
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js "></script>
<script type="text/javascript" src="/Public/Scripts/jqModal.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
I'm using VS2008 Web Forms
I keep getting warnings saying:
Warning 3 Error updating JScript IntelliSense: C:\Documents and Settings\myusername\Local Settings\Temporary Internet Files\Content.IE5\2N4L8DWB\jquery.min-fds90[1]..js: Object doesn't support this property or method @ 1:17179 C:\Applications\xxx\xxx\index.aspx 1 1
A: You could use the ResolveUrl method for scripts that are local to your application:
<script type="text/javascript" src="<%= ResolveUrl("~/Public/Scripts/jqModal.js") %>"></script>
The other 2 scripts are absolute urls referenced from external CDNs so they should be fine and you should leave them as is.
As far as the warning is concerned, simply ignore it. Visual Studio Intellisense in web pages is far from perfect. FWIW in VS2010 it's no better. Hopefully they will fix it in vNext.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I get an instruction trace on Mac OS X 10.5 PPC? Apple used to ship a tool called amber as part of CHUD with Xcode 2.5, which would allow you to get an instruction trace for a process. You could then feed the instruction trace to simg5. The simg5 tool shipped with Xcode 3 but without amber, which makes it kind of worthless (unless you have a bunch of traces lying around).
How do I get an instruction trace of an OS X / PowerPC process?
(I tried installing amber from the Xcode 2.5 packages, but the package refused to run. I tried extracting the executable manually, but I get a bus error after I attach to a running process, killing both amber and the target process.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to combine asterix syntax with table abbreviations Is it possible to combine * syntax with table abbreviations?
I want to do something like:
"SELECT subfunds.* FROM subfunds S" +
" INNER JOIN funds F ON S.id_fund = F.id" +
" WHERE F.fund_short IN('" + stSQLFundList + "')"
The above code gets a syntax error
"invalid reference to FROM-clause entry for table "subfunds".
I already found that if I do
"SELECT * FROM subfunds S" +
" INNER JOIN funds F ON S.id_fund = F.id" +
" WHERE F.fund_short IN('" + stSQLFundList + "')"
then I get all fields from both tables rather than from the subfunds table only.
So how do I get all fields from the first table (and none of the other tables' fields) in my answer set while also being able to use the single-letter table abbreviations?
A: Change your code to this and you will get all fields from subfunds.
"SELECT S.* FROM subfunds S" +
" INNER JOIN funds F ON S.id_fund = F.id" +
" WHERE F.fund_short IN('" + stSQLFundList + "')"
If you are using an alias, then you want to reference that table by it's alias.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java RegExp escape repeated single quote I'm trying to split a string by single quotes, but taking into account that a repeated single quote represents a escaped quote. So for example the following string
String ss ="aaa''bbb'ccc''ddd'eee";
would be splitted in
aaa''bbb
ccc''ddd
eee
so the regular expression should be something like "Any single quote that is not preceded by a single quote and its not followed by a single quoted". The expression to avoid the single quote not followed by a single quote is simple:
String regexp= "'(?!')";
But I was unable to apply the condition "not preceded by a single quote". Any ideas?
TIA
JL
A: are u looking for this?
"(?<!')'(?!')"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to build Android NDK .so without STL? I'm using the newest Android NDK r6b to build my shared object. This library does not use any kind of STL at all, but resulting .so includes many STL stuff like std::bad_alloc_what(void) and many more, which increases size of binary greatly. Also release builds include this garbage. APP_STL not defined anywhere, also the NDK r5b produces small binary with used functions only. Is it a bug of r6b? How can I build with r6b without STL stuff?
A: It seems that there is a bug in NDK r6b and it always builds libraries with exceptions support, even if -fno-exceptions is explicitly specified.
See this question for details: Android NDK produce unreasonable big binaries, how to optimize .so size?
A: If you are using, say, new then you are implicitly using the standard library for the std::bad_alloc exception. Unless you call the no-throw version of new, which would instead use std::nothrow. If you don't use the standard library, then it won't get linked. Just make sure you don't, if that's what you want, or perhaps just move to C?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Problem running Heroku's Facebook app tutorial with Python I am testing Heroku's ability to write a Facebook app with Python. I'm having a problem running the basic tutorial. It seemed like this question was worth asking on StackOverflow in case there's an answer that helps other people who run into the exact same problem.
I followed the instructions on heroku's facebook development page (http://devcenter.heroku.com/articles/facebook). Deploying to Heroku worked fine.
However, running the app locally does not. When I follow the instructions and bring up
http://localhost:5000
I get to the Facebook Login screen. But when I click Log In on that screen, I get:
SSL connection error Unable to make a secure connection to the
server. This may be a problem with the server, or it may be requiring
a client authentication certificate that you don't have. Error 107
(net::ERR_SSL_PROTOCOL_ERROR): SSL protocol error.
and the console output is
09:55:07 web.1 | https://localhost:5000/ 09:55:07 web.1 |
https://www.facebook.com/dialog/oauth?client_id=179852202088814&redirect_uri=https://localhost:5000/&scope=user_likes,user_photos,user_photo_video_tags
09:55:07 web.1 | 127.0.0.1 - - [24/Sep/2011 09:55:07] "GET / HTTP/1.1"
302 - 09:59:02 web.1 | 127.0.0.1 - - [24/Sep/2011 09:59:02] code 400,
message Bad request syntax
('\x16\x03\x00\x00U\x01\x00\x00Q\x03\x00N}\xe2&\xf9\xf7"\x15\xd5\xb6\xf6\xa6\x0f\xb01\x97N\xcc\xb3l\xed\x97\xd1!-\x91c?\x1f\xac\xa2h\x00\x00*\x00\xff\x00\x88\x00\x87\x009\x008\x00\x84\x005\x00E\x00D\x00f\x003\x002\x00\x96\x00A\x00\x04\x00\x05\x00/\x00\x16\x00\x13\xfe\xff\x00')
09:59:02 web.1 | 127.0.0.1 - - [24/Sep/2011 09:59:02]
"UQN}?&??"ն??1?N̳l??!-?c???h*???98?5EDf32?A/??" 400 -
When I try it in Safari, the address bar shows the following very long URL:
https://localhost:5000/?code=AQBPWpkbRdL2bt7KER0fcUS9ZnheXiGApkaF5MXbNgyIJqzw46SGve1iVyLIx1sDltNh0PkXPDdxhjAxoa1YED1cpcaflCXCkqzO27A-rhgjBpXwWUClpGRpRmDD2eIXcOyIczo_qGf45tbpvDZO5hFa0gmUeSHri4vY3bqw-5jBjZRoZfEB7pI8cLPOIsnNICI#_=_
Safari compains that it can't establish a secure connection.
This is running on OS X 10.6.8.
A: This is because https is not enabled locally on your machine, you could enable this or you could alternatively run without the SSL on your localhost. To do this you would edit the function to look something like:
def get_home():
return 'http://' + request.host + '/'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Is it possible to SIMULATE a mouse click using a mouse down and up events? A previous question has gotten me thinking. Is it possible to simulate a MouseEvent.CLICK to get fired by just firing first a MOUSE_DOWN followed by a MOUSE_UP.
As per Adobe's doumentation.
"... For a click event to occur, it must always follow this series of events in the order of occurrence: mouseDown event, then mouseUp. The target object must be identical for both of these events; otherwise the click event does not occur. Any number of other mouse events can occur at any time between the mouseDown or mouseUp events; the click event still occurs." http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/InteractiveObject.html#event:click
From my tests it shows that the CLICK event is NOT constructed from the ActionScript 3 event queue. Or is something wrong with the code?
See:
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
[SWF(backgroundColor="0xFFFFFF", frameRate="30", width="800", height="600")]
public class Test extends Sprite
{
private var spr:Sprite = new Sprite();
public function Test()
{
trace("Test()");
this.addEventListener(Event.ADDED_TO_STAGE,init);
}
public function init(e:Event):void
{
trace("init()");
spr.graphics.beginFill(0xFF0000);
spr.graphics.drawRect(0,0,200,80);
spr.graphics.endFill();
addChild(spr);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
spr.addEventListener(MouseEvent.CLICK, onClick);
}
private var tick:int = 0;
private function onEnterFrame(e:Event):void
{
if (tick == 1) spr.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_DOWN,true,false));
if (tick == 2) spr.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_UP,true,false));
if (tick == 3) spr.dispatchEvent(new MouseEvent(MouseEvent.CLICK,true,false));
tick++;
}
private function onClick(e:MouseEvent):void
{
trace("onClick() MouseEvent.CLICK dispatched");
}
}
}
I should get TWO 'onClick()' events instead of one.
A: The reason you cannot is that all three types are created by the plugin, and are not dependent upon each other.
MouseEvent.MOUSE_DOWN is fired as soon as you press on an interactive object.
MouseEvent.MOUSE_UP is fired as soon as you release the mouse, it does not depend upon the mouse click having started a MOUSE_DOWN within the same InteractiveObject.
MouseEvent.CLICK will only be fired when both events take place in the same object without the cursor leaving the object between the itnerval of mouse down and mouse up.
So you can see that there is a simple case, or two even, in which both MOUSE_DOWN and MOUSE_UP are fired, but CLICK is not called because the event is not a CLICK.
Furthermore, the ability to simply dispatch a MouseEvent.CLICK event makes it unnecesasry to create fake user interaction by firing multiple mouse events, when only one is called for. It would be awkward to have to track each object clicked in the mouse down listener, in order to check that the moue up should also trigger a click. You would also need to remove references when a ROLL_OUT event happened.
In short, the CLICK event is really a lot more than the MOUSE_DOWN and MOUSE_UP events. It is also managing that the events happened in succession and on the same display object without leaving the object. When that happens, and ONLY when that happens flash dispatches a CLICK event.
A: it's impossible, this code:
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
/**
* ...
* @author www0z0k
*/
public class Main extends Sprite {
public function Main():void {
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
stage.addEventListener(MouseEvent.CLICK, onClick);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onStageKeyDown);
}
private function onStageKeyDown(e:KeyboardEvent):void {
trace('pressed');
stage.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_DOWN));
stage.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_UP));
stage.dispatchEvent(new MouseEvent(MouseEvent.CLICK));
}
private function onClick(e:MouseEvent):void{
trace('clicked');
}
}
}
outputs just:
pressed
clicked
after a key is pressed on the keyboard
A: not sure about this for flash. But when i was learning windows MFC and was clueless. What i did was that I sent WM_MOUSEDOWN followed by WM_MOUSEUP after a short delay. It did work and the button's visual states also changed - without any mouse click!
A: If I understand what you're asking then the answer is YES.
I am curious if I have over simplified the solution here especially after reading your code attempt. It is very simple to "simulate" a mouse click. The code below outputs two "I have been clicked" statements when the object is clicked and none when you mouse down then move out of the objects boundaries.
This class extended a MovieClip I created on the stage so I didn't have to code a box.
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class clickMe extends MovieClip {
public function clickMe() {
// constructor code
this.addEventListener(MouseEvent.CLICK, clicked);
this.addEventListener(MouseEvent.MOUSE_DOWN, mDown);
}
private function clicked(e:MouseEvent):void{
trace("I have been clicked");
this.removeEventListener(MouseEvent.MOUSE_UP, clicked);
}
private function mDown(e:MouseEvent):void{
this.addEventListener(MouseEvent.MOUSE_UP, clicked);
}
}
}
In your code I believe the problem is that you are trying to run event listener dispatches through an "onEnterFrame" which will only ever fire one event per frame - never two. Also after testing your code I'm not sure what your were trying to accomplish with the "tick" variable because you never reset it. So the the MOUSE_UP event fires once (when tick = 2, unless your holding the mouse down) then none of the other dispatches will ever fire again.
A: Not quite sure why everybody's making these complex spikes. Or maybe I'm just overseeing something.
Anyway, here's a very easy way to check it:
import flash.events.MouseEvent;
stage.addEventListener(MouseEvent.CLICK, function(){
trace( 'clicked' );
} );
stage.dispatchEvent( new MouseEvent( MouseEvent.MOUSE_DOWN ) );
stage.dispatchEvent( new MouseEvent( MouseEvent.MOUSE_UP ) );
And the answer would be, "no, it's not possible"...
...and probably should be followed by a counter-question: WHY would I want to simulate a click event using a sequence of mousedown and mouseup, when I can dispatch a click event just as well?
Am I a button, having an existential crisis?
Or is it a question out of mere curiosity? But you know what happened to the cat... Right, but maybe it's schrödinger's cat, which means that at the end of this completely irrelevant train of thought, curiosity REALLY did and did NOT kill the cat.
Except if the cat's out of a box.
Then it probably just got wasted.
See, thinking out of the box can get you killed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Spawning a kernel mode thread - Windows I have intensive processing that I need to perform in a device driver, at DISPATCH_LEVEL or lower IRQL.
*
*How do I create a kernel-thread?
*What IRQL does it run at? Can I control this?
*How is it scheduled? Because I am thinking from a user-mode perspective here, what priority does it run at?
*What kernel functions can I use to provide locking / synchronization?
A: you can create system thread with this As you can see one of its parameters is a start routine which can hold custom code - in it you can use KeRaiseIrql and KeLowerIrql. By default threads will run in PASSIVE_LEVEL. "Locks, Deadlocks, and Synchronization" is a very helpful paper regarding synchronization in kernel on windows and everyone who has to do some tinkering with the windows kernel should read or at least skim it
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Delete TableViewRow in Titanium mobile I have a TableView, but don't want to use the builtin swipe-to-delete functionality for various reasons. So, I have a button in that row that should delete the containing row. How would I do that? The TableView object has a deleteRow() function, but it requires the index of the row to be deleted, and as far as I know, there isn't a way to get that from a TableViewRow object.
A: you could set the row index as a property of the button when you create the button
you could put the event listener on the whole row, detect when the source object is the button and then you would have the index and the button click event for the delete.
there are multiple approaches, some code would help me to direct you to the best solution
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: presentmodalviewcontroller - how to not to make it cover entire screen? I have a tab bar and a search button on its toolbar. So now whenever the user clicks the search i would like a view to come up (presenetmodalviewcontroller) but present modal view controller covers entire screen is there any way that it covers only the present view (ie view in the current tab bar)? now how can I accomplish this?
thanks,
Tushar Chutani
A: By definition, a modal view controller is meant to "interrupt" the current flow of an application for something else (requesting a user/pass, asking for a contact to send an email, etc). You can read more about this in the View Controller Programming Guide.
You are better off using a navigation stack (UINavigationController) inside the current tab to handle other viewControllers that must be presented to the user. Here's another stack overflow question on how to place navigation controllers in a tab bar application. With a navigation stack, you can push view controllers (pushViewController:animated:), and manage an indefinite depth of viewControllers for a single tab item.
A: One option is for the view that's inside the tabbar to be within a NavigationController. Then , instead of presentModalViewController, you would pushViewController onto the stack. That would leave the tabBar at the bottom visible and it allows you to navigate back.
That does however add a navigationBar to the top. Not sure if that's a problem for your app.
A: So this is how I was able to do not the best code but it works What I have pretty much done is addsubview to a uiimageview (should have used UIWindow but who cares?)
-(void)revers{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
NSLog(@"Revenre is called");
otherViewImage.transform = CGAffineTransformMakeTranslation(0,-380);
[otherViewImage addSubview:hup.view];
[UIView commitAnimations];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Creating named relations in Rails 3 models I'm trying to learn Rails and I'm struggling to understand how self relations are declared using the ActiveRecord component.
If I have something like this:
class Comment < ActiveRecord::Base
has_many :comments
belongs_to :comments
end
Being the related comments the comment's replies and the comment's parent, how am I supposed to access them if they have the same name? I can't just do comment.comments, they would need to have different names.
Thanks.
A: For one, belongs_to is a singular association, so it would be:
belongs_to :comment
... and you would have no name conflict.
But for cases where you do have conflicts, you can always rename relations, for example:
has_many :comments
has_many :recent_comments, :class_name => 'Comment', :limit => 10, :order => 'id DESC'
See more examples of options for associations in the docs.
A: You need to use singular for belongs_to associations:
belongs_to :comment
It looks like you are trying to create a tree-like structure of Comments. You might want to take a look at gems like paginary.
A: The first symbol passed to the has_many method is the name you want to specify. Rails uses the Convention over configuration principle, so it takes the related class' name from it to, but you can specify it like this:
has_many :rel, :class_name => "Class"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to synchronize sliders' values? I use jquery mobile sliders:
<div data-role="fieldcontain">
<input type="range" name="slider1" id="slider1" value="0" min="0" max="255" />
</div><br><br>
<div data-role="fieldcontain">
<select name="switcher1" id="switcher1" data-role="slider">
<option value="0">Off</option>
<option value="255">On</option>
</select>
</div>
It should work in the following way:
*
*if switcher1 is touched, then slider1 value should be set either to 0 or to 255;
*if slider1 value is changed, then (a) if it is = 0, then switcher1 should be set to 0, (b) else switcher1 value should be set to 255.
I've tried to do so with change event (the same is used for switcher1 change()):
var slider1_val = "0";
$('#slider1').change(function () {
sVal = $(this).val();
if (slider1_val !== sVal) {
$("#slider1").val(sVal).slider("refresh");
if (sVal == 0) {
$("#switcher1").val(0).slider("refresh");
} else {
$("#switcher1").val(255).slider("refresh");
}
slider1_val = sVal;
}
});
But looks like each call of refresh calls change event, so I am getting infinite loop.
A:
It should work in the following way:
*
*if switcher1 is touched, then slider1 value should be set either to 0 or to 255;
*if slider1 value is changed, then (a) if it is = 0, then switcher1 should be set to 0, (b) else switcher1 value should be set to 255.
I've tried to do so with change event (the same is used for switcher1 change()):
The fact that you have two very different criteria for changing each control should tip you off that the change event handlers should be different as well. Using the same handlers leads to the infinite loop you are experiencing. The code below accounts for the strict change criteria you've provided. Note that the slider1 change handler changes switcher1 only if it needs to be changed (based on your criteria), not every time it is called. Also, note that in the slider1 change handler, switcher1_val is set before calling refresh, so that in case .slider('refresh') does call the change handler, the change handler will not do anything, because switcher1_val is already updated.
var linkSliders = function(sliderId, switcherId){
var slider = $('#'+sliderId),
switcher = $('#'+switcherId);
var min = Math.min(switcher[0].options[0].value, switcher[0].options[1].value),
max = Math.max(switcher[0].options[0].value, switcher[0].options[1].value);
var sliderVal = switcherVal = min;
// set the slider min/max to be the same as the switcher's, just in case they're different
slider.attr('max', max).attr('min', min).slider('refresh');
slider.change(function(){
var sVal = $(this).val();
if(sliderVal != sVal){
if( sVal == min && switcherVal!=min){
switcherVal=min;
switcher.val(min).slider('refresh');
}else if(sVal>min && switcherVal!=max){
switcherVal=max;
switcher.val(max).slider('refresh');
}
sliderVal = sVal;
}
});
switcher.change(function(){
var sVal = $(this).val();
if(switcherVal != sVal){
slider.val(sVal).slider('refresh');
switcherVal = sVal;
}
});
};
linkSliders('slider1','switcher1');
See the live example.
Hope this helps.
Update: As requested, the example has been modified to make it more general.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why isn't my div content showing? I have a #info div element which shows some text strings like below:
<body>
...
<div id="info">
ABCDEFGHIJKLMNOPQRSTUVWXYZ ...
</div>
</body>
I would like to CSS the #info div to position it at the bottom center of the page, so I did the following thing:
#info{
width:100px;
margin:0px auto;
}
With the above CSS, the #info div is on the bottom center of the page, BUT only part of the text strings are showing (only shows '...' without the 'ABCDE..' showing).
I thought it maybe because of the width:100px is not enough to show all the texts, so I change to width:200px, but surprisingly after I increase the width, nothing was showing on the bottom center at all. Why?
-------------------- UPDATE ------------------
I have another div above the #info div, if this is the reason, then I would like to ask how to CSS the #info div to locate it below the upper div?
A: My best guess is that you have something above it that is overlapping and hiding part of the DIV. With the current text, it is splitting on the space between the letters and the dots, putting the dots on a second line. That part of the DIV is displaying below something else with the first part being hidden. When you increase the width to 200px it's wide enough to fit everything on one line and all of it disappears. You might want to try adding a clear: both and see if that pushes it below whatever is hiding the text. Sometimes adding a border (or using outlining of elements with a browser developer plugin) can help diagnose what is going on. Check your z-index as well to make sure that you have things in the proper plane to do what you want.
A: <html>
<head>
<link rel="stylesheet" href="css.css" type="text/css">
</head>
<body>
<section>
<div id="info1">
asdgfawregawregawregawregawregawregaweg
</div>
<div id="info2">
asdgfawregawregawregawregawregawregaweg
</div>
</section>
</body>
</html>
css file:
#info1 {
color: red;
}
#info2 {
width:100px;
margin:0px auto;
}
So... all displayed.
Maybe you give not enough information...
A: I had this issue, I accidentally set font-size:0 to zero in body and Html , once I removed it text where visible
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: can you use jqmodal ajax with web forms is there a way to use jqmodal's ajax property with asp.net webforms?
<script type="text/javascript">
$(document).ready(function() {
$('#Button1').click(function() {
$('#modalContent').jqm({
ajax: "~/ShelterCreateForm.ascx"
});
$('#modalContent').jqmShow(this);
return false;
});
});
</script>
A: jqModal is server side technology agnostic meaning that it can be used with absolutely any language on the server including WebForms in condition that it points to a server side url which returns the partial html:
<script type="text/javascript">
$(function() {
$('#Button1').click(function() {
$('#modalContent').jqm({
ajax: '<%= ResolveUrl("~/Foo.ashx") %>'
});
$('#modalContent').jqmShow(this);
return false;
});
});
</script>
And the server side url that returns this partial (Foo.ashx) might be a generic handler as shown in this answer:
public class FooHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
context.Response.Write(RenderPartialToString("ShelterCreateForm.ascx"));
}
private string RenderPartialToString(string controlName)
{
var page = new Page();
var control = page.LoadControl(controlName);
page.Controls.Add(control);
using (var writer = new StringWriter())
{
HttpContext.Current.Server.Execute(page, writer, false);
return writer.ToString();
}
}
public bool IsReusable
{
get { return false; }
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Obstacle avoidance using 2 fixed cameras on a robot I will be start working on a robotics project which involves a mobile robot that has mounted 2 cameras (1.3 MP) fixed at a distance of 0.5m in between.I also have a few ultrasonic sensors, but they have only a 10 metter range and my enviroment is rather large (as an example, take a large warehouse with many pillars, boxes, walls .etc) .My main task is to identify obstacles and also find a roughly "best" route that the robot must take in order to navigate in a "rough" enviroment (the ground floor is not smooth at all). All the image processing is not made on the robot, but on a computer with NVIDIA GT425 2Gb Ram.
My questions are :
*
*Should I mount the cameras on a rotative suport, so that they take pictures on a wider angle?
*It is posible creating a reasonable 3D reconstruction based on only 2 views at such a small distance in between? If so, to what degree I can use this for obstacle avoidance and a best route construction?
*If a roughly accurate 3D representation of the enviroment can be made, how can it be used as creating a map of the enviroment? (Consider the following example: the robot must sweep an fairly large area and it would be energy efficient if it would not go through the same place (or course) twice;however when a 3D reconstruction is made from one direction, how can it tell if it has already been there if it comes from the opposite direction )
I have found this response on a similar question , but I am still concerned with the accuracy of 3D reconstruction (for example a couple of boxes situated at 100m considering the small resolution and distance between the cameras).
I am just starting gathering information for this project, so if you haved worked on something similar please give me some guidelines (and some links:D) on how should I approach this specific task.
Thanks in advance,
Tamash
A: If you want to do obstacle avoidance, it is probably easiest to use the ultrasonic sensors. If the robot is moving at speeds suitable for a human environment then their range of 10m gives you ample time to stop the robot. Keep in mind that no system will guarantee that you don't accidentally hit something.
(2) It is posible creating a reasonable 3D reconstruction based on only 2 views at such a small distance in between? If so, to what degree I can use this for obstacle avoidance and a best route construction?
Yes, this is possible. Have a look at ROS and their vSLAM. http://www.ros.org/wiki/vslam and http://www.ros.org/wiki/slam_gmapping would be two of many possible resources.
however when a 3D reconstruction is made from one direction, how can it tell if it has already been there if it comes from the opposite direction
Well, you are trying to find your position given a measurement and a map. That should be possible, and it wouldn't matter from which direction the map was created. However, there is the loop closure problem. Because you are creating a 3D map at the same time as you are trying to find your way around, you don't know whether you are at a new place or at a place you have seen before.
CONCLUSION
This is a difficult task!
Actually, it's more than one. First you have simple obstacle avoidance (i.e. Don't drive into things.). Then you want to do simultaneous localisation and mapping (SLAM, read Wikipedia on that) and finally you want to do path planning (i.e. sweeping the floor without covering area twice).
I hope that helps?
A: *
*I'd say no if you mean each eye rotating independently. You won't get the accuracy you need to do the stereo correspondence and make calibration a nightmare. But if you want the whole "head" of the robot to pivot, then that may be doable. But you should have some good encoders on the joints.
*If you use ROS, there are some tools which help you turn the two stereo images into a 3d point cloud. http://www.ros.org/wiki/stereo_image_proc. There is a tradeoff between your baseline (the distance between the cameras) and your resolution at different ranges. large baseline = greater resolution at large distances, but it also has a large minimum distance. I don't think i would expect more than a few centimeters of accuracy from a static stereo rig. and this accuracy only gets worse when you compound there robot's location uncertainty.
2.5. for mapping and obstacle avoidance the first thing i would try to do is segment out the ground plane. the ground plane goes to mapping, and everything above is an obstacle. check out PCL for some point cloud operating functions: http://pointclouds.org/
*if you can't simply put a planar laser on the robot like a SICK or Hokuyo, then i might try to convert the 3d point cloud into a pseudo-laser-scan then use some off the shelf SLAM instead of trying to do visual slam. i think you'll have better results.
Other thoughts:
now that the Microsoft Kinect has been released, it is usually easier (and cheaper) to simply use that to get a 3d point cloud instead of doing actual stereo.
This project sounds a lot like the DARPA LAGR program. (learning applied to ground robots). That program is over, but you may be able to track down papers published from it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: iOS only CSS file? Is there a way to include a CSS file that only works for iOS? Thanks.
It would be preferred if this is done browser side, although server side detection could be a viable option if it works well enough (server is python flask based)
A: You can use CSS media queries:
http://www.mobilexweb.com/blog/iphone4-ios4-detection-safari-viewport
A: You could use some javascript
if((navigator.userAgent.match(/iPhone/i)) //Lines split for easy reading only
|| (navigator.userAgent.match(/iPod/i))
|| (navigator.userAgent.match(/iPad/i))){
//LINK TO YOUR STYLESHEET
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Not able to make an HTTP access to SQL Server Analysis services 2008 on Windows Server 2008 via IIS 7 My intention is to access the SSAS Database without Windows authentication. The user outside the domain should be able to access the cube and built PIVOT tables around it. Thus I found that we can use HTTP access for this purpose.
I followed each and every step mentioned on the following links
http://msdn.microsoft.com/en-us/library/gg492140.aspx
http://bloggingabout.net/blogs/mglaser/archive/2008/08/15/configuring-http-access-to-sql-server-2008-analysis-services-on-microsoft-windows-server-2008.aspx
When I try to hit the URL in Mgmt Studio --> Analysis Services
http://localhost/olap/msmdpump.dll. I am getting the "Connection time out" and "404 error"
I went to MSDN forums for the same problem but no concrete results.
How do I test whether my SSAS 2008 is accessible with HTTP access.
Please help!!
A: I don't have a lot to go on from your question, but if I had to guess I'd say you probably didn't switch from integrated to classic in the application pool settings which left your handler mapping disabled giving you the 404.
I would start simple on your local development machine and follow the instructions allowing anonymous access to the site. Make sure that your site uses an application pool that has access to the cube in analysis services. Additionally, you cannot use the integrated pipeline in IIS, you will hve to use classic. When you create your script mapping (under Handler Mappings) in IIS, make sure that you follow the directions carefully from the following URL:
http://msdn.microsoft.com/en-us/library/gg492140.aspx
I just followed the instructions and it worked for me.
A: Switching on Anonymous authentication will work to grant access to the site, however I would suggest you use at least Basic HTTP authentication or even Windows Authentication. Just note, if you're using a remote SSAS instance (not on the same host), a double-hop authentication is required. For that, you will have to register SPNs and enable Kerberos authentication.
You find out how to do that by following the links referred to under
Microsoft - Configure HTTP Access to SSAS
Greetings,
Remo
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error message: "identifier expected" I´m doing an exercise from the learning book "Java, how to program". I am supposed to write a program that makes the user type in miles driven, and liters of gasoline used for a not decided number of trips.
The program is supposed to print miles pr liter for each trip, and an average miles pr liter at the end.
I am supposed to use sentinel-controlled repetition, and to print the miles pr liter as floating point values.
I keep getting an error message when I try to compile:
GasolineUsage.java:39: expected
milPrLiter = (double) totalMil / totalLiters;
^ GasolineUsage.java:40:
expected
System.out.printf( "The car drives %.2f miles pr liter
gasoline\n\n", milPrLiter );
^ GasolineUsage.java:40: illegal start
of type
System.out.printf( "The car drives %.2f miles pr liter
gasoline\n\n", milPrLiter );
^ GasolineUsage.java:40:
expected
System.out.printf( "The car drives %.2f miles pr liter
gasoline\n\n", milPrLiter );
^ GasolineUsage.java:42: class, interface, or enum expected } ^ 5
errors
The code is the following:
import java.util.Scanner;
public class GasolineUsage
{
public static void main( String[] args )
{
int totalMil = 0;
int totalLiters = 0;
double milPrLiter1 = 0;
double milPrLiter;
Scanner inputMil = new Scanner(System.in);
Scanner inputLiters = new Scanner( System.in);
System.out.print( "Type in miles first trip, to end type: -1 " );
int mil = inputMil.nextInt();
System.out.print( "Type in liters of gasoline used on first trip " );
int liters = inputLiters.nextInt();
totalMil = totalMil + mil;
totalLiters = totalLiters + liters;
milPrLiter1 = (double) mil / liters;
System.out.printf( "(%.2f miles pr liter this trip.)\n", milPrLiter1 );
System.out.print( "Type in miles on next trip " );
while (mil != -1)
{
mil = inputMil.nextInt();
if (mil != -1)
{totalMil = totalMil+ mil;
System.out.print( "Type in lters used on next trip: " );
liters = inputLiters.nextInt();}
totalLiters = totalLiters + liters;
milPrLiter1 = (double) mil / liters;
System.out.printf( "(%.2f miles pr liter this trip.)\n", milPrLiter1 );}
}
milPrLiter = (double) totalMil / totalLiters;
System.out.printf( "The car drives %.2f miles pr liter gasoline\n\n", milPrLiter );
}
}
Can anyone please help me?
A: Count your opening and closing braces as they should match. You've got an extra closing brace hiding in your code that you'll find if you search for it. Note that with this type of error it's always good to look above the line that is throwing the error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Welcome aboard ActiveRecord::ConnectionNotEstablished I'm using Ubuntu, with Rails 3.0.1 with mysql2 socket.
When i do runing install, rake db:create and after rails server, my Welcome aboard, shows ActiveRecord::ConnectionNotEstablished in About your application’s environment
What i do?
A: Had the same problem on rails 3.1.1:
rake db:create - ok
rails console and some DMLs - ok
but accessing info from the web-page resulted in ActiveRecord::ConnectionNotEstablished.
A rails server restart helped.
A: You'll need to do some more debugging to work it out.
How are you running your server?
Make yourself a model.
rails generate model Something name:string
Then try running rake db:migrate
Does this work?
If it does, then you must be running your server in a different way (maybe you're running it in production mode?)
Try rails console and try to do Something.count
If all of those work
then I'd suggest you try restarting your server.
rails server
A: It sounds like your MySQL server isn't running. You'll need to install MySQL if you haven't already (apt-get install mysql-server should do it). Once it's running, you'll need to set up a user and database for your app, and note the username and password so that you can put that information in config/database.yml within your app.
This link will be useful if you need any help with those steps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is sencha touch / jquery mobile mature enough for production? Last week i've been busy with mobile html5 frameworks like sencha touch and jquery mobile.
I bumped into a few bugs and strange things when testing on real android phones. (from slow to missing components to even not displaying anything)
Is it correct to say that html5 frameworks for mobile platforms aren't ready for production when one of the requirements is that it must function on most android/iphones?
A: If you plan to support most android phones, you should be aware of that performance will not be satisfying on middle to low-end devices. This is because that both libraries depend heavily on javascript( especially sencha ), and javascript and the whole webkit performance are not great on these phones. The situation is a bit better on the iphones.
A: I don't know about jquery, but sencha touch sure is.
See if the android bugs you found are mention here because they will or already are solved in the next release.
http://www.sencha.com/forum/showthread.php?135798-List-of-Known-Android-Issues-Fixed-in-Upcoming-Release
The sencha touch 2 is going to have all other improvements especially, bugs and performance related to android OS. Read it here:
http://www.sencha.com/blog/sencha-touch-2-what-to-expect
In the end test and see it yourself some of the apps that are built with sencha touch:
http://www.sencha.com/apps/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Proper way to initialize gettext in runtime in asp.net / monodevelop I am trying to get localization to work in an asp.net mvc project using monodevelop on mac. I have added a translation project and translated the text 'Welcome' in danish.
public class HomeController : Controller
{
public ActionResult Index ()
{
var culture = CultureInfo.CreateSpecificCulture("da");
System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
System.Threading.Thread.CurrentThread.CurrentCulture = culture;
Mono.Unix.Catalog.Init("i8n1", "./locale");
ViewData ["Message"] = Mono.Unix.Catalog.GetString("Welcome");
return View ();
}
}
But the text does not get translated.
Any ideas?
A: You'll need the full path to your locale folder.
MonoDevelop does something like this (edited for brevity)
string location = System.Reflection.Assembly.GetExecutingAssembly().Location;
location = Path.GetDirectoryName(location);
string catalogPath = Path.Combine (location, "locale");
Catalog.Init ("monodevelop", catalogPath);
A: Mono.Unix.Catalog is not suitable for ASP.NET. It uses a 'per environment' approach whereas for ASP.NET you need a 'per thread' approach.
This library is definitely worth a look as an alternative http://sourceforge.net/p/gettextnet/
For reference: http://lists.ximian.com/pipermail/mono-devel-list/2008-March/027174.html
A: The answer is here: http://mono.1490590.n4.nabble.com/Mono-Unix-Catalog-Init-where-does-it-get-the-locale-from-td1532586.html
public static void Main (string[] args)
{
var culture = CultureInfo.CreateSpecificCulture ("de");
Thread.CurrentThread.CurrentCulture = culture;
Environment.SetEnvironmentVariable ("LANGUAGE", "de_DE");
Catalog.Init ("i8n1", "./locale");
Console.WriteLine (Catalog.GetString("Hello World!"));
}
And it works for me on Ubuntu/Mono. Thanks to Vladimir for good question and to Jonathan for great answer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery sliders calculator Hi I want to create some sliders, what i need to do is to make a slider which has 3 options in it:
*
*the amount the user wants to borrow (from 12,500 upto 100,000) - will display a value from where the selector is here
*over how long (from five yrs upto 25yrs) - will display a value from where the selector is here
*Estimate based on the values the monthly repayment.
i have looked at others on here but don't quite understand how they work logically so if anyone could help would be great.
I have added a quick image i made to dropbox: http://dl.dropbox.com/u/12506430/sliders.jpg
A: Demo here.
<h2>How much would you like to borrow?</h2>
<div id="amount"></div>
<h2>Over how long?</h2>
<div id="period"></div>
<h2>Result</h2>
Your monthly payment will be $<span id="monthly">204.86</span>
function update() {
var amount = $('#amount').slider('value');
var period = $('#period').slider('value');
var monthly = (amount + amount * 0.03 * period) / (period * 12);
$("#monthly").text(monthly.toFixed(2));
}
$("#amount").slider({
value: 12500,
min: 12500,
max: 100000,
step: 50,
slide: function() {
update();
}
});
$("#period").slider({
value: 5,
min: 5,
max: 25,
step: 1,
slide: function() {
update();
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: drupal insert or update DB record with only one function similar quest is here: Help with db query in drupal - if exists update else insert
But drupal_write_record() third argument is to determine update or insert. Maybe drupal has another function, who self determine insert or update by primary key? Or I should it to program my self?
A: Have a look at the db_merge() function, I think it has the features you're looking for.
A: If you really don't know if there's a record there already, you probably need to check a bit earlier in your program flow. Normally I'd start the function or whatever with a call to the DB and if I don't get an existing record object, I make a new one from stdClass.
This has two benefits: first, it means that you know about existing data, so you can use it if needs be and not overwrite it blindly. Second: when you get to the point where you write to the DB, you know whether it's INSERT or UPDATE based on whether the object has an id property.
A: I implemented function myself:
function drupal_write_record2($table, $data, $primaryKeys) {
$data = (array)$data;
$query = db_select($table)
->fields($table);
if (is_array($primaryKeys))
foreach ($primaryKeys as $key)
$query->condition($key, $data[$key]);
else
$query->condition($primaryKeys, $data[$primaryKeys]);
$update = (bool)$query->execute()->fetchAssoc();
if ($update)
return drupal_write_record($table, $data, $primaryKeys);
else
return drupal_write_record($table, $data);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to create a Prouhet–Thue–Morse sequence in Haskell? I'm a noob in Haskell, but some experience with ActionScript 3.0 Object Orientated. Thus working on a major programming transition. I've read the basic knowledge about Haskel, like arithmetics. And I can write simple functions.
As a practical assignment I have to generate the Thue-Morse sequence called tms1 by computer in Haskell. So it should be like this:
>tms1 0
0
>tms1 1
1
>tms1 2
10
>tms1 3
1001
>tms1 4
10010110
and so on... According to wikipedia I should use the formula.
t0 = 0
t2n = tn
t2n + 1 = 1 − tn
I have no idea how I can implement this formula in Haskell. Can you guide me to create one?
This is what I got so far:
module ThueMorse where
tms1 :: Int -> Int
tms1 0 = 0
tms1 1 = 1
tms1 2 = 10
tms1 3 = 1001
tms1 x = tms1 ((x-1)) --if x = 4 the output will be 1001, i don't know how to make this in a recursion function
I did some research on the internet and found this code.
Source:
http://pastebin.com/Humyf6Kp
Code:
module ThueMorse where
tms1 :: [Int]
tms1 = buildtms1 [0] 1
where buildtms1 x n
|(n `rem` 2 == 0) = buildtms1 (x++[(x !! (n `div` 2))]) (n+1)
|(n `rem` 2 == 1) = buildtms1 (x++[1- (x !! ((n-1) `div` 2))]) (n+1)
custinv [] = []
custinv x = (1-head x):(custinv (tail x))
tms3 :: [Int]
tms3 = buildtms3 [0] 1
where buildtms3 x n = buildtms3 (x++(custinv x)) (n*2)
intToBinary :: Int -> [Bool]
intToBinary n | (n==0) = []
| (n `rem` 2 ==0) = intToBinary (n `div` 2) ++ [False]
| (n `rem` 2 ==1) = intToBinary (n `div` 2) ++ [True]
amountTrue :: [Bool] -> Int
amountTrue [] = 0
amountTrue (x:xs) | (x==True) = 1+amountTrue(xs)
| (x==False) = amountTrue(xs)
tms4 :: [Int]
tms4= buildtms4 0
where buildtms4 n
|(amountTrue (intToBinary n) `rem` 2 ==0) = 0:(buildtms4 (n+1))
|(amountTrue (intToBinary n) `rem` 2 ==1) = 1:(buildtms4 (n+1))
But this code doesn't give the desired result. Any help is well appreciated.
A: Your definition of the sequence seems to be as a sequence of bit sequences:
0 1 10 1001 10010110 ... etc.
t0 t1 t2 t3 t4
but the wikipedia page defines it as a single bit sequence:
0 1 1 0 1 ... etc
t0 t1 t2 t3 t4
This is the formulation that the definitions in Wikipedia refer to. With this knowledge, the definition of the recurrence relation that you mentioned is easier to understand:
t0 = 0
t2n = tn
t2n + 1 = 1 − tn
In English, this can be stated as:
*
*The zeroth bit is zero.
*For an even, non-zero index, the bit is the same as the bit at half the index.
*For an odd index, the bit is 1 minus the bit at half the (index minus one).
The tricky part is going from subscripts 2n and 2n+1 to odd and even, and understanding what n means in each case. Once that is done, it is straightforward to write a function that computes the *n*th bit of the sequence:
lookupMorse :: Int -> Int
lookupMorse 0 = 0;
lookupMorse n | even n = lookupMorse (div n 2)
| otherwise = 1 - lookupMorse (div (n-1) 2)
If you want the whole sequence, map lookupMorse over the non-negative integers:
morse :: [Int]
morse = map lookupMorse [0..]
This is the infinite Thue-Morse sequence. To show it, take a few of them, turn them into strings, and concatenate the resulting sequence:
>concatMap show $ take 10 morse
"0110100110"
Finally, if you want to use the "sequence of bit sequences" definition, you need to first drop some bits from the sequence, and then take some. The number to drop is the same as the number to take, except for the zero-index case:
lookupMorseAlternate :: Int -> [Int]
lookupMorseAlternate 0 = take 1 morse
lookupMorseAlternate n = take len $ drop len morse
where
len = 2 ^ (n-1)
This gives rise to the alternative sequence definition:
morseAlternate :: [[Int]]
morseAlternate = map lookupMorseAlternate [0..]
which you can use like this:
>concatMap show $ lookupMorseAlternate 4
"10010110"
>map (concatMap show) $ take 5 morseAlternate
["0", "1", "10", "1001", "10010110"]
A: I would suggest using a list of booleans for your code; then you don't need to explicitly convert the numbers. I use the sequence defined like this:
0
01
0110
01101001
0110100110010110
01101001100101101001011001101001
...
Notice that the leading zeros are quite important!
A recursive definition is now easy:
morse = [False] : map step morse where step a = a ++ map not a
This works because we never access an element that is not yet defined. Printing the list is left as an excercise to the reader.
Here is another definition, using the fact that one can get the next step by replacing 1 with 10 and 0 with 01:
morse = [False] : map (concatMap step) morse where step x = [x,not x]
Edit
Here are easier definitions by sdcvvc using the function iterate. iterate f x returns a list of repeated applications of f to x, starting with no application:
iterate f x = [x,f x,f (f x),f (f (f x)),...]
And here are the definitions:
morse = iterate (\a -> a ++ map not a) [False]
morse = iterate (>>= \x -> [x,not x]) [False]
A: Easy like this:
invertList :: [Integer] -> [Integer]
invertList [] = []
invertList (h:t)
|h == 1 = 0:invertList t
|h == 0 = 1:invertList t
|otherwise = error "Wrong Parameters: Should be 0 or 1"
thueMorse :: Integer -> [Integer]
thueMorse 1 = [0]
thueMorse n = thueMorse (n - 1) ++ invertList (thueMorse (n - 1))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Predict time to fully load page in javascript In javascript, is there anyway to query how large css/js files are, and how large image files are? I have a unique situation where I give a user a preview of a page, and that page can either be the full page, or google's cached text-only version of the page. The text only version loads instantly.
Don't think there is, but figured I would ask.
Maybe Google's index also holds information on page load times, would anyone know how to query this load time?
I want to make my app consider loading the text version of a page if it recognizes that it will take a long time to load the full page.
What I might do is search through the html string for a page, and just count the number of http requests that will be made (each css link, script tag, and img tag) via string manipulation. If there are more than X requests that would be made by inserting and loading that page's full html for the preview, then I'll opt for the instant text version of the page.
A: You can try using AJAX like author of an answer done in THIS TOPIC.
Making HEAD HTTP AJAX request can give you header information about given file without downloading its content.
Here is the example from the link:
var xhr = new XMLHttpRequest();
xhr.open('HEAD', 'img/test.jpg', true);
xhr.onreadystatechange = function(){
if ( xhr.readyState == 4 ) {
if ( xhr.status == 200 ) {
alert('Size in bytes: ' + xhr.getResponseHeader('Content-Length'));
} else {
alert('ERROR');
}
}
};
xhr.send(null);
For more info please visit the source where author did a great job showing that solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Submit multiple form using jquery Is there any way to submit multiple forms using ajax ?
for eg form id="form1" and form id="form2"
both the forms will be submitted separately as needed.
to be more specific i am using this for my form submission.
thanks
A: Sure:
$('#form1, #form2').submit();
after having AJAXified them of course:
$(function() {
$('#form1, #form2').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
alert('thanks for submitting');
}
});
return false;
});
});
UPDATE:
After your update it seem that you are using the jquery form plugin. In this case you could force the AJAX submission by invoking the ajaxSubmit method on the 2 forms like this:
$('#form1, #form2').ajaxSubmit();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: org.aopalliance.intercept.MethodInterceptor not found despite being in Classpath - Spring + JBoss AS 7 I am trying to use Java Persistence API (JPA) with Spring in a JSF 2.0 application with Hibernate 3 on JBoss Application Server 7 Web Profile. Upon startup, I get the following error:
21:24:12,880 WARN [org.jboss.modules] (MSC service thread 1-4) Failed to define class org.springframework.orm.hibernate3.HibernateInterceptor in Module "deployment.PlayingDatabase.war:main" from Service Module Loader: java.lang.LinkageError: Failed to link org/springframework/orm/hibernate3/HibernateInterceptor (Module "deployment.PlayingDatabase.war:main" from Service Module Loader)
at org.jboss.modules.ModuleClassLoader.defineClass(ModuleClassLoader.java:401)
at org.jboss.modules.ModuleClassLoader.loadClassLocal(ModuleClassLoader.java:261)
at org.jboss.modules.ModuleClassLoader$1.loadClassLocal(ModuleClassLoader.java:76)
at org.jboss.modules.Module.loadModuleClass(Module.java:588)
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:183)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:358)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:307)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:101)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:257) [org.springframework.core-3.0.6.RELEASE.jar:]
at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:408) [org.springframework.beans-3.0.6.RELEASE.jar:]
at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1282) [org.springframework.beans-3.0.6.RELEASE.jar:]
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1253) [org.springframework.beans-3.0.6.RELEASE.jar:]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:576) [org.springframework.beans-3.0.6.RELEASE.jar:]
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1330) [org.springframework.beans-3.0.6.RELEASE.jar:]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:317) [org.springframework.beans-3.0.6.RELEASE.jar:]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:396) [org.springframework.beans-3.0.6.RELEASE.jar:]
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:594) [org.springframework.context-3.0.6.RELEASE.jar:]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:407) [org.springframework.context-3.0.6.RELEASE.jar:]
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:282) [org.springframework.web-3.0.6.RELEASE.jar:]
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:204) [org.springframework.web-3.0.6.RELEASE.jar:]
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) [org.springframework.web-3.0.6.RELEASE.jar:]
at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:3368) [jbossweb-7.0.1.Final.jar:7.0.1.Final]
at org.apache.catalina.core.StandardContext.start(StandardContext.java:3821) [jbossweb-7.0.1.Final.jar:7.0.1.Final]
at org.jboss.as.web.deployment.WebDeploymentService.start(WebDeploymentService.java:70) [jboss-as-web-7.0.1.Final.jar:7.0.1.Final]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1765)
at org.jboss.msc.service.ServiceControllerImpl$ClearTCCLTask.run(ServiceControllerImpl.java:2291)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [:1.6.0_22]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [:1.6.0_22]
at java.lang.Thread.run(Thread.java:679) [:1.6.0_22]
Caused by: java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor
at java.lang.ClassLoader.defineClass1(Native Method) [:1.6.0_22]
at java.lang.ClassLoader.defineClass(ClassLoader.java:634) [:1.6.0_22]
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) [:1.6.0_22]
at org.jboss.modules.ModuleClassLoader.defineClass(ModuleClassLoader.java:397)
... 28 more
Caused by: java.lang.ClassNotFoundException: org.aopalliance.intercept.MethodInterceptor from [Module "deployment.PlayingDatabase.war:main" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:191)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:358)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:330)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:330)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:307)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:101)
... 32 more
I have researched that I need the file aopalliance-1.0.jar. I do. My classpath contains the file noted here, I took it from the "required" folder in the Hibernate 3. I added it to the Java Build Path in Eclipse. The error persists. Similarly, the MySQL driver in the build path is not found.
21:24:12,970 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/PlayingDatabase]] (MSC service thread 1-4) Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/web-application-config.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [com.mysql.jdbc.Driver]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1361) [org.springframework.beans-3.0.6.RELEASE.jar:]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086) [org.springframework.beans-3.0.6.RELEASE.jar:]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) [org.springframework.beans-3.0.6.RELEASE.jar:]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) [org.springframework.beans-3.0.6.RELEASE.jar:]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293) [org.springframework.beans-3.0.6.RELEASE.jar:]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) [org.springframework.beans-3.0.6.RELEASE.jar:]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290) [org.springframework.beans-3.0.6.RELEASE.jar:]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192) [org.springframework.beans-3.0.6.RELEASE.jar:]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585) [org.springframework.beans-3.0.6.RELEASE.jar:]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895) [org.springframework.context-3.0.6.RELEASE.jar:]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425) [org.springframework.context-3.0.6.RELEASE.jar:]
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:282) [org.springframework.web-3.0.6.RELEASE.jar:]
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:204) [org.springframework.web-3.0.6.RELEASE.jar:]
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) [org.springframework.web-3.0.6.RELEASE.jar:]
at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:3368) [jbossweb-7.0.1.Final.jar:7.0.1.Final]
at org.apache.catalina.core.StandardContext.start(StandardContext.java:3821) [jbossweb-7.0.1.Final.jar:7.0.1.Final]
at org.jboss.as.web.deployment.WebDeploymentService.start(WebDeploymentService.java:70) [jboss-as-web-7.0.1.Final.jar:7.0.1.Final]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1765)
at org.jboss.msc.service.ServiceControllerImpl$ClearTCCLTask.run(ServiceControllerImpl.java:2291)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [:1.6.0_22]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [:1.6.0_22]
at java.lang.Thread.run(Thread.java:679) [:1.6.0_22]
Caused by: org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [com.mysql.jdbc.Driver]
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:102) [org.springframework.beans-3.0.6.RELEASE.jar:]
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58) [org.springframework.beans-3.0.6.RELEASE.jar:]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1358) [org.springframework.beans-3.0.6.RELEASE.jar:]
... 21 more
I am using Eclipse Indigo on Kubuntu 11.04. The server and the workspace are both in my home partition, I don't see a rights issue here.
My full list of jars:
antlr-2.7.6.jar
**aopalliance-1.0.jar**
commons-beanutils-1.8.3.jar
commons-beanutils-1.8.3-javadoc.jar
commons-beanutils-1.8.3-sources.jar
commons-beanutils-bean-collections-1.8.3.jar
commons-beanutils-core-1.8.3.jar
commons-collections-3.1.jar
commons-collections-3.2.1.jar
commons-collections-3.2.1-javadoc.jar
commons-collections-3.2.1-sources.jar
commons-collections-testframework-3.2.1.jar
commons-digester-2.1.jar
commons-digester-2.1-javadoc.jar
commons-digester-2.1-sources.jar
commons-logging-1.1.1.jar
commons-logging-1.1.1-javadoc.jar
commons-logging-1.1.1-sources.jar
commons-logging-adapters-1.1.1.jar
commons-logging-api-1.1.1.jar
commons-logging-tests.jar
dom4j-1.6.1.jar
hibernate3.jar
hibernate-testing.jar
hibernate-validator-4.2.0.Final.jar
hibernate-validator-annotation-processor-4.2.0.Final.jar
javassist-3.12.0.GA.jar
jta-1.1.jar
mysql-connector-java-5.1.17-bin.jar
org.springframework.aop-3.0.6.RELEASE.jar
org.springframework.asm-3.0.6.RELEASE.jar
org.springframework.aspects-3.0.6.RELEASE.jar
org.springframework.beans-3.0.6.RELEASE.jar
org.springframework.context-3.0.6.RELEASE.jar
org.springframework.context.support-3.0.6.RELEASE.jar
org.springframework.core-3.0.6.RELEASE.jar
org.springframework.expression-3.0.6.RELEASE.jar
org.springframework.instrument-3.0.6.RELEASE.jar
org.springframework.instrument.tomcat-3.0.6.RELEASE.jar
org.springframework.jdbc-3.0.6.RELEASE.jar
org.springframework.jms-3.0.6.RELEASE.jar
org.springframework.orm-3.0.6.RELEASE.jar
org.springframework.oxm-3.0.6.RELEASE.jar
org.springframework.test-3.0.6.RELEASE.jar
org.springframework.transaction-3.0.6.RELEASE.jar
org.springframework.web-3.0.6.RELEASE.jar
org.springframework.web.portlet-3.0.6.RELEASE.jar
org.springframework.web.servlet-3.0.6.RELEASE.jar
org.springframework.web.struts-3.0.6.RELEASE.jar
primefaces-2.2.1.jar
slf4j-api-1.6.1.jar
validation-api-1.0.0.GA.jar
My web.xml:
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>PlayingDatabase</display-name>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/web-application-config.xml </param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>500000</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
web-application-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource"
p:driverClassName="com.mysql.jdbc.Driver" p:password="" p:url="jdbc:mysql://localhost/"
p:username=""> </bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="dataSource">
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
</value>
</property>
<property name="annotatedClasses">
<list>
<!-- -->
</list>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
A: Well i would recommend you to change the version of your Spring mvc because Spring 3.0 is not supporting Hibernate 4.2 you can read the manual in that they have maintain this as Issue means BUG. so i would like to suggest you that switch spring version to Spring 3.1.1 or above and even Spring 3.2 will be better. and ya then change your code like this.
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource">
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
</value>
</property>
<property name="annotatedClasses">
<list>
annoted Classes.
</list>
</property>
</bean>
A:
My classpath contains the file noted here
If you get a ClassNotFoundException, it means the JAR isn't in the CLASSPATH. You aren't doing it properly. You need to lose the mindset that says "I did everything right" and figure out what you did wrong.
A: Instead of adding it in your build path via Eclipse build config, add it directly in your WEB-INF/lib/ folder.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Issues registering C++ COM DLL on 64-bit Windows 7 I have a simple C++ ATL COM DLL and a 32-bit Visual Studio Setup installer. All is well on 32-bit Windows but there are some issues on 64-bit Windows 7.
In addition to HKCR, my RGS script adds some registry entries to HKCU as well. After inspection with Registry Editor it turns out my keys aimed at HKCU ended up in HKEY_USERS\.Default. What went wrong? I can't seem to get to the bottom of this.
[Edit]
When I do a manual c:\windows\syswow64\regsvr32 on my COM DLL, I finally get proper keys in the HKCU registry. Does this mean Windows Setup project is broken on 64-bit Windows?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Building web based interface for mssql I am maintaining the databases for my organization in mssql. I have many tables for my database. Now I have to develop a web based service so that any user without the knowledge of sql could access the tables and pull the information they want. I have little knowledge in php...can I build the web based interface in php? Or should I do the web interface using other programming language? Sorry if my question sounds silly..Can anyone please suggest me regarding this?
A: Are the tables fixed or may there be new ones often?
http://www.php.net/manual/en/function.mssql-query.php
http://php.net/manual/en/function.mssql-fetch-array.php
If the tables are fixed you could make pages for each database which will select the data you need and then echo it in a table. You could also build forms and then use that data to do INSERT statements so the users can update the tables
I use MySQL but these manuals will help you to use mssql queries within PHP to select rows in the database and then loop though them echoing the Divs and Tables using $row['column name'] to use the variables.
If the tables could change and you can't find a suitable msSQL equivalent to PHPmyAdmin I would seriously consider changing to MySQL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Ocean 2010.1 with VS2010 Can I use Ocean for petrel 2010.1 with VS.2010 to write petrel plug ins?
I ask because I need to use some specific features on the .NET 4.0.
Thanks
A: You can use VS 2010 if you do not need the Wizard to generate Ocean stub code.
Petrel 2010 uses .Net 2.0. This means you can use features up to 3.5, but not 4.0.
Rumor is that Petrel 2012 might use .Net 4.0 when it ships.
A: The wizard that comes with the Ocean SDK for Petrel 2011.1 actually works with Visual Studio 2010 as well as Visual Studio 2008. You can take advantage of .NET 3.5 and .NET 4.0 features in your plug-in, but depending on which version of Petrel you are targeting you need to make sure the dependent .NET assemblies are available for your plug-in at runtime.
A: Actually you can use and wizards also. You just need to change Projects and Items templates location in VS Tools->Options... to appropriate location where your Ocean templates was installed. It should be like C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ProjectTemplates. By default it may contain path to ...Documents and Settings.. which is wrong.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: RoR Routes Error: From a link_to built URL, route appears in rake routes routes.rb
resources :project_associations, :only => [:update]
rake routes
project_association PUT /project_associations/:id(.:format) {:action=>"update", :controller=>"project_associations"}
ERB
<%= link_to membership_command[:text], project_association_path(membership_command[:id], :command => membership_command[:command])%>
Resulting HTML
<a href="/project_associations/2011?command=suspend">Suspend</a>
Click result:
Routing Error
No route matches "/project_associations/2011"
I kicked the server, same result
Thanks in advance for any assistance.
A: Add this to the link_to: :method => :put.
So:
<%= link_to membership_command[:text], project_association_path(membership_command[:id], :command => membership_command[:command]), :method => :put %>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: C++ class has no member named 'blah' I have a .h file with this in it:
#ifndef CS240_LINKED_LIST_H
#define CS240_LINKED_LIST_H
#include <string>
//! LLNode implements a doubly-linked list node
class LLNode {
friend class LinkedList;
public:
LLNode(const std::string & v, LLNode * p, LLNode * n) :
value(v), prev(p), next(n)
{
}
private:
std::string value; //!< value stored in the node
LLNode * prev; //!< pointer to previous node in the list
LLNode * next; //!< pointer to next node in the list
};
//! LinkedList implements a doubly-linked list
class LinkedList
{
public:
//! No-arg constructor. Initializes an empty linked list
LinkedList();
//! Copy constructor. Makes a complete copy of its argument
LinkedList(const LinkedList & other);
private:
//! two dummy nodes to keep track of the beginning and end of the list.
LLnode beginning;
LLnode end;
int size;
};
#endif
In a cpp file I have:
#include "LinkedList.h"
LinkedList::LinkedList(){
this->beginning.prev = NULL;
this->beginning.next = this->end;
this->end.prev = this->beginning;
this->end.next = NULL;
}
Here's the output:
>g++ -o LinkedList.o LinkedList.cpp
In file included from LinkedList.cpp:1:
LinkedList.h:37: error: 'LLnode' does not name a type
LinkedList.h:38: error: 'LLnode' does not name a type
LinkedList.cpp: In constructor 'LinkedList::LinkedList()':
LinkedList.cpp:4: error: 'class LinkedList' has no member named 'beginning'
LinkedList.cpp:5: error: 'class LinkedList' has no member named 'beginning'
LinkedList.cpp:5: error: 'class LinkedList' has no member named 'end'
LinkedList.cpp:6: error: 'class LinkedList' has no member named 'end'
LinkedList.cpp:6: error: 'class LinkedList' has no member named 'beginning'
LinkedList.cpp:7: error: 'class LinkedList' has no member named 'end'
I don't know how to fix this. How else would I set the beginning and end objects? Just so you know, I'm a Java programmer learning C++.
A: *
*You have misspelt LLNode as LLnode.
*You need to add a default constructor to the LLNode class
*you need to take the address of the this->beginning and this->end members in the LinkedList constructor:
.
LinkedList::LinkedList(){
this->beginning.prev = NULL;
this->beginning.next = &this->end;
this->end.prev = &this->beginning;
this->end.next = NULL;
}
A: You need to declare the constructor. Try:
class LinkedList
{
private:
LLnode beginning;
LLnode end;
public:
LinkedList();
};
A: You don't have a declaration of LinkedList::LinkedList() in the class declaration.
That should give you a different error; g++ gave me
error: definition of implicitly-declared ‘LinkedList::LinkedList()’
Are you sure you've posted the exact code you're compiling? Narrow your code down to something small but complete, and copy-and-paste the exact source files into your question. (For example, there's no declaration of LLnode). Show us something we can try ourselves.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Remove the extension of a file Given a filename like:
package.zip image.jpeg video.avi etc
I'd like to remove the extension if exists. How can I make this in Java? THanks!
A: Here is a slightly more robust version:
public static String stripExtension(final String s)
{
return s != null && s.lastIndexOf(".") > 0 ? s.substring(0, s.lastIndexOf(".")) : s;
}
Gracefully handles null, cases where there is nothing that looks like an extension and doesn't molest files that start with a ., this also handles the .kitty.jpg problem as well.
This will handle most general cases in a controlled environment, if the suffix isn't actually an extension, just something . separated then you need to add some checking to see if the trailing part actually is an extension you recognize.
A: Something like
if (name.indexOf(".") > 0)
name = name.substring(0, name.lastIndexOf("."));
The index check avoids turning hidden files like ".profile" into "", and the lastIndexOf() takes care of names like cute.kitty.jpg.
A: myString = myString.replaceAll("\\.\\w+", "");
A: String result = filename.substring(0, filename.lastIndexOf("."))
Do check to see if the filename has a . before calling substring().
A: Use Apache Commons IO, FilenameUtils.getBaseName(String filename)
or removeExtension(String filename), if you need the path too.
A: String name = filename.lastIndexOf('.') > filename.lastIndexOf(File.separatorChar) ?
filename.substring(0, filename.lastIndexOf('.'))
: filename;
The comparison checks that the filename itself contains a ., otherwise the string is returned unchanged.
A: Pattern suffix = Pattern.compile("\\.\\p{Alnum}+$");
Matcher m = suffix.matcher(filename);
String clearFilename = m.replaceAll("");
The problem of this solution is that, depending of your requirements, you need to extend it to support composed extensions, like filename.tar.gz, filename.tar.bz2
[]'s
And Past
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Is a binary JSON javascript library available for browsers? In order for efficient server side parsing I am looking into a BSON solution directly for the browser javascript environment. The idea is to utilize the entire ASCII space by means of binary websockets. Any suggestions?
(Any nodejs suggestions are welcome as well)
See also:
http://bsonspec.org/
A: This might be incomplete but the goal of the project line up with what you want: https://github.com/muhmi/javascript-bson It doesn't look like that encodes directly to typed arrays which would be the most useful for sending over WebSocket.
A: For what it's worth, it appears that the MongoDB team now have a supported Javascript BSON project:
https://github.com/mongodb/js-bson
I'm no expert with the library, but the project claims to work in both Node and the browser. Below is a modified sample from their site:
<head>
<!-- Originally https://raw.github.com/mongodb/js-bson/master/browser_build/bson.js -->
<!-- But downloaded and hosted locally -->
<script src="./bson.js"></script>
</head>
<body onload="start();">
<script>
function start() {
var BSON = bson().BSON;
var Long = bson().Long;
var doc = {
oid: bson().ObjectID(),
long: Long.fromNumber(100),
date: new Date(),
string: "js-bson sample",
obj: {
string: "Object within an object"
}
}
console.log("doc %o", doc);
// Serialize a document
var data = BSON.serialize(doc, false, true, false);
console.log("data %o", data);
// De serialize it again
var doc_2 = BSON.deserialize(data);
console.log("doc_2 %o", doc_2);
}
</script>
</body>
Below are my results in Chrome:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: HTML Resizing Text I want to have a div stay at 500 height. Text is dynamically inserted into this div. Different text lengths are inserted. Right now, my div expands to accomodate the full text. How can I instead have text shrink so it always fits within the bounds?
A: You cannot use HTML and CSS to dynamically re-size text. You can set the div height to 500px, and either have scroll or hide any extra text.
You can use JavaScript to re-size the text dynamically, but the solution may not be practical if the text length varies widely. Your text will be unreadable if under 10px.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Remove Specific Information from a String - PHP I'm working on a php script for work, I've got most of it figured out and spent hours,
trying to get this working. Here's the deal. I've got this information.
</i>xxxx at \<a href=\"http://xxx/xxx/xxxx/11205xxx3887\" data-hovercard=\"/ajax/xxxx/xxx.php?id=112054175xxx3887\">xxxxx\</a>\</span>\
Ofcourse i'm trying to format this to be readable, something like,
xxxx at xxxxx
problem is the url changes constantly or i could just use a easy substr or something.
Any suggestions???
A: Use the the following:
$str = strip_tags($str);
See php.net/strip_tags
A: Here is my best attempt. It would be helpful if you could provide a larger section of code to work with, and if you could explain what the xxxx stands for it would make it much easier to solve your problem. Are they characters, numbers, times, prices? And do you know the origin of all the kooky forward slashes? Very unsettling...
I used the code as it was provided, so you may want to watch out for the last trailing \.
When I copied your code into my text editor it pasted as \n rather than \.
$string = "</i>xxxx at \<a href=\"http://xxx/xxx/xxxx/11205xxx3887\" data-hovercard=\"/ajax/xxxx/xxx.php?id=112054175xxx3887\">xxxxx\</a>\</span>\\";
$modified_string = trim(stripslashes(strip_tags($string)), '\\');
echo $modified_string;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google Maps Javascript API: Multiple Markers at One Location Because of "Sub Stores" I'm building a site that uses this api to look for some specific stores. One of them is Target. The problem is my searches usually return 2 to 3 markers at the locations showing "Target", "Target Optics" and "Target Pharmacy". Does anyone know of a good way to have it show only the main "Target" marker?
Just as a reference here's my code:
<script type="text/javascript">
var geocoder;
var map;
var service;
var infowindow;
var markers = new Array();
function initialize() {
var latlng = new google.maps.LatLng(<?=$lat ?>, <?=$long ?>);
infowindow = new google.maps.InfoWindow();
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var request = {
location: latlng,
radius: '22000',
types: ['store'],
name: 'Target'
};
service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place=results[i];
var marker = new google.maps.Marker({
map: map,
position: results[i].geometry.location
});
markers[i] = marker;
markers[i].reference = place.reference;
}
//alert(markers.length);
}
for(j=0;j<markers.length;j++){
google.maps.event.addListener(markers[j],'click',function(){
var me = this;
var request={reference:this.reference};
service.getDetails(request,function(newplace,status){
var myContent = "<h3>" + newplace.name + "</h3>" + newplace.formatted_address;
infowindow.setContent(myContent);
infowindow.open(map,me);
});
});
}
}
A: I am guessng you would hv to take a look at map clustering to get the job done. Here are some links that will help you achieve this:
http://www.appelsiini.net/2008/11/introduction-to-marker-clustering-with-google-maps or
http://www.svennerberg.com/2009/01/handling-large-amounts-of-markers-in-google-maps/
Both are client side clustering examples though and I am guessing you would need server side clustering to group them together and give them the right name. You could probably right an algo to do the same.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: While-loop in Java not working Alright, so the problem is this:
I want to enter a bunch of numbers, a random set, of say 5 numbers. At the end of that number, I'll add a sixth number, 0, which will be a signal for my loop to end.
To achieve this, this is what I'll do.
I run my program and this is my input:
1 3 4 2 5 0
So I want the program to print
1
3
4
2
5 "End of sequence"
Here's my code that will purportedly do such a thing (all of this is in main method):
Scanner input = new Scanner(System.in);
System.out.println("Alright, what?");
boolean notZero = true;
while (notZero)
{
System.out.println(input.nextInt());
if (input.nextInt() == 0)
System.out.println("End of sequence");
notZero = false;
}
These, however, are the results I get:
http://i.imgur.com/4Th43.jpg
Interestingly, if I don't have the while-loop stop, and I input the same number list again (1 3 4 2 5 0) it'll output 3 and 2, which are the even numbers in my number list - and all this vexes me further.
Any ideas?
A: Wrap all your blocks including if blocks in curly braces!
This:
if (foo)
doSomething();
doSomethingElse();
is not working as you think it is as it's behaving as
if (foo) {
doSomething();
}
doSomethingElse();
Instead wrap all blocks in curly braces so that there is no doubt:
if (foo) {
doSomething();
doSomethingElse();
}
A: This looks like a learning exercise, so I'll give you a few hints rather than tell you outright.
*
*In your IDE of choice, tell it to auto-indent your code. Look closely at where the if statement and its results fall.
*Think carefully about what nextInt() does and about where and how often you want to call it.
A: You are calling input.nextInt() twice in the loop, only printing one of them. In effect, that is like skipping every other number in the input. Change your code to store the next input into a variable, then check the variable. I suspect this isn't your actual code as without setting notZero to false as a result of checking the condition, it will only execute the loop once. FWIW, notZero is a lousy variable name. It should be semantic, not indicate its expected value. You'll also want to only print the input value if it isn't the end of input indicator.
Scanner input = new Scanner(System.in);
System.out.println("Alright, what?");
boolean endOfInput = false;
while (!endOfInput) {
int next = input.nextInt();
if (next == 0) {
System.out.println("End of sequence");
endOfInput = true;
}
else {
System.out.println(next);
}
}
A: Your problem is here:
if (input.nextInt() == 0)
When you call nextInt() twice it removes two numbers. You need to only call it once per iteration.
while (notZero)
{
int num = input.nextInt();
System.out.println(num);
if (num == 0) {
System.out.println("End of sequence");
notZero = false;
}
}
Fix that along with the problem that Hovercraft Full of Eels pointed out and you should be good.
A: You're calling nextInt() twice each time through the loop. That means that each time around, you'll consume two numbers, doing different things with each one -- i.e., the one you print and the one you compare to 0 are two different numbers. You need to call nextInt() just once and store the result in a variable, then operate on it.
A: Besides the two reads inside your loop, I assume you want to have a block after your if-statement
if (input.nextInt() == 0) {
System.out.println("End of sequence");
notZero = false;
}
A: Far as i see, notZero's only purpose is to terminate the loop. You don't need it if you use a loop that terminates on the loop condition. You also don't need to print the "End of sequence" inside the loop, since by definition, it prints once the sequence is ended.
If we test for the condition directly instead,
int n;
while ((n = input.nextInt()) != 0)
{
System.out.println(n);
}
System.out.println("End of sequence");
You could also say for (int n = input.nextInt(); n != 0; n = input.nextInt()) instead of the while. It ensures that n is only visible within the loop, but it also means repeating yourself -- and leaving open the possibility that someone could make the two 'initialization' and 'increment' sections different later.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to find the cause for blocked threads found via jstack? I ran jstack on my java application (runs on tomcat and ubuntu server edition) because it seems to consume a lot of memory after a while.
So, with jstack I found out that many threads seem to be blocked:
Console log: http://dl.dropbox.com/u/17844821/zeug/threaddumpexception.txt
Threaddump: http://dl.dropbox.com/u/17844821/zeug/threaddump.txt
So, I know that threads are blocked but how can I find out which java class causes this and even more important: How can I force these threads to terminate?
Any help would be greatly appreciated.
A: It came out that the threaddump produced by jstack was not correct.
I had to do two things to get the correct dump:
*
*Replaced OpenJDK with sun's original sun-6-jdk and sun-6-jre packages
*I modified the jstack call to use 64-bit mode and run it as tomcat-user like this: sudo -u tomcat6 jstack -J-d64 -m pid
That gave me a threaddump which looks correct now (no blocked threads).
A: I think that these threads are waiting for some normal IO (sockets, loggers, and others).
Normally, when a thread came blocked, jstack shows full stack until block call.
You can analyses the stack and check the call trace and decide if this thread was blocked from some bug/problem or it's normal execution of the server or application.
[]'s,
And Past
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do the Windows DDK samples deal with being paged out? I don't see much code dealing with it in the samples How come the Windows DDK samples do not deal with being paged out? Are they non-pageable?
A: Pageable code is marked with #pragma code_seg("PAGE"). That's why the drivers are not dealing with paging. They are by default all non-pagable.
A: Not speaking specifically of Windows drivers, but only for device drivers in general:
Don't have large drivers.
Don't do that much work in kernel mode and certainly don't do that much work at high interrupt priority levels. Do only what's needed at these levels, then delegate the rest of the work to code that runs at the lowest level (0).
A: Paged code is wrapped by #pragma code_seg("PAGExxx"), paged data by #pragma data_seg("PAGExxx"). It's also possible to specify paged functions (only c-linkage) with #pragma alloc_text. Classes can also be paged by using declspec(allocate()) starting with WDK 8. There is also an API to lock and unlock pages in memory, allowing runtime control. See more here: http://social.msdn.microsoft.com/Forums/en-US/wdk/thread/ba75e766-6a8f-4fe8-9d03-b69be85655d9
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to track messages on an outlook server i'm writting a program, and some of its features is to track email messages sent to a specific email addresse.
the server is MS exchange, and i'm wondering how to make this feature.
the purpose is :
whenever an email is sent to a specific addressse : admin@domain.com, this program will detect this, and grab the body, subject, and some basic properties like time date and priority.
is there any exchange API that could help me doing this ? thank you very much. the program is in c# language. any hint about libraries in .net or even java would be appreciated. Have a great Day !!
A: Use the EWS Managed API. It allows you to access a mailbox.
Now, depending on your reaction time (time between message arrival and processing), you can either poll the mailbox from time to time and process all new mails. Or you can use push/pull/streaming subscriptions to get notifications about new mails. See my article on MSDN for a description of the different models.
EWS Managed API - Download: http://www.microsoft.com/download/en/details.aspx?id=13480
EWS Managed API - SDK: http://msdn.microsoft.com/en-us/library/dd633710(v=exchg.80).aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: andengine empty TextureRegion I want to create a Sprite with its children. The Sprite will be empty but the children will not. So I need a TextureRegion to create the sprite. Such as sprite itself is empty, I don't need to create a texture from assets, but I need a Texture to create the sprite
new Sprite(pX, pY, pTextureRegion)
How can I create an empty TextureRegion for this operation?
A: You can use Entity and Entity.attachChild().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery Plugins and the Rails 3 Asset Pipeline -- What am i doing wrong? I'm working on a web app in Rails 3.1, fully (I think) utilizing the asset pipeline for css, images, and js. I'm running into a pretty consistent issue when I try to implement jQuery plugins. I've been able to solve it in one case, but not in another, and I'm trying to figure out what the key issue is.
Essentially, I'll load a jQuery plugin and then call it in my document.ready method, only to find that pulling up the site results in (for example, in the case of the jScrollPane plugin)
Uncaught TypeError: Object #<Object> has no method 'jScrollPane'
I have received the same error for several other plugins. I thought the case might be that jQuery/jQuery-UI wasn't being loaded before my plugins, so they weren't instantiated properly, but that doesn't seem to be the case. The necessary scripts are in app/assets/javascripts/... In my app/assets/application.js I have the following:
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require jquery.mousewheel
//= require mwheelIntent
//= require jquery.jscrollpane.min
//= require_tree .
The resultant application.js appears to be correct, other than the errors; that is, everything I would expect to be there is there.
What am I doing wrong? I'm happy to provide any additional information necessary.
A: One gotcha with the asset pipeline if you're not using it regularly is that if you have assets pre-compiled and dumped into public/assets/application.js then it that precompiled file can clobber the files as they're generated by the development asset pipeline, so plugins you've included in /app/assets/application.js are overwritten.
In other words, the previous, all singing, all-dancing jquery object you're meticulously building with this snippet here:
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require jquery.mousewheel
//= require mwheelIntent
//= require jquery.jscrollpane.min
//= require_tree .
Is overwritten by the already compiled code describing a jQuery object in public/assets/application.js.
Well, that's what just bit me, when a page I was debugging was exhibiting very similar behaviour to this one.
A: Compressors that work on Javascript can be fussy about the coding style of plugins.
I have found in a couple of cases code isn't found if the plugin is missing a closing ; at the end. The compressor can rename the next function if it thinks it is inside the precceding block.
Try reordering your plugins and see if that changes the missing method. That might give you clue as to where the missing ; is, if that is the problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Spring 3.0 with default servlet 2.3 Just out of curiosity I want to know why does the spring releases comes with servlet 2.3 api and not with servlet 2.5 spec? I downloaded spring 3.0 and I see servlet 2.3 api.
A: I guess Spring 3.0 is compatible with servlet 2.3 onwards. You can always use newer version since Servlet specification is backward compatible.
E.g. when using maven simply add servlet 3.0 dependency explicitly (necessarily with provided scope), it will override transitive 2.3 dependency.
A: You'll often see that Spring specifies dependencies on all manner of libraries, and that - a lot of times - in the framework itself, Spring uses reflection to invoke any of a multitude of APIs across a range of versions for a library. The lengths the framework goes to make it easy for you as the consumer in the face of inconsistent APIs is .. amazing.
It's one thing when the two APIs are different enough that they can be treated as two different imports, e.g., Hibernate 2 vs. Hibernate 3. But even among Hibernate 3.x versions, there are subtle API breaks that Spring knows about and works with. In Spring 3.1, there should be Hibernate 4 support, which is yet another drastically different API than Hibernate 2 or 3, so you can expect it'll support that version, too. Good thing most if Spring's dependencies are "optional" in the Maven descriptor!
By working with Spring's Hibernate 3 support, though, you get a sane, common interface no matter which Hibernate 3 impl you've got. So, if you see a situation where Spring specifies an old version of a stable API like the servlet spec, don't worry, it probably supports the newer versions, too. Spring 3.1 will more fully support servlet 3, for example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do you install paramiko on Mac OSX? I'm having a lot of problems with this one.
When I try using easy_install, I get this error:
warning: GMP library not found; Not building Crypto.PublicKey._fastmath.
unable to execute gcc-4.0: No such file or directory
error: Setup script exited with error: command 'gcc-4.0' failed with exit status 1
How do you install paramiko? I get the same error when I try to install PyCrypto.
A: You need to install Xcode (on the OSX install DVD or online in the AppStore).
It includes the gcc compileer you are apprantly missing. It also includes other stuff like make that you probably need to build it. Maybe homebrew or fink also have gcc and the like included.
A: If it helps any, I solved this issue with sym links, and I think it will work for you. I wrote this with my version of gcc in mind, which is 4.2:
cd /usr/bin
rm cc gcc c++ g++
ln -s gcc-4.2 cc
ln -s gcc-4.2 gcc
ln -s c++-4.2 c++
ln -s g++-4.2 g++
ln -s gcc-4.2 gcc-4.0
There ya go!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: strongly typed model /need output in model format actually i'm new to this technology, i am using mvc2 architecture. l cant able to load the data from my model to view page. i used strongly typed model EventListing.Models.EventInfo. i need output in model format. how can i use my select function
Model
public class EventInfo
{
public int OPR { get; set; }
public int EVENT_ID { get; set; }
public string SUBSITE { get; set; }
public static DataTable Select()
{
DataTable myDataTable = new DataTable();
Dbhelper DbHelper = new Dbhelper();
DbCommand cmd = DbHelper.GetSqlStringCommond("SELECT * FROM WS_EVENTINFO");
myDataTable.Load(DbHelper.ExecuteReader(cmd));
return myDataTable;
}
Controller
public ActionResult List()
{
return View(EventModel.EventList());
}
View
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<EventListing.Models.EventInfo>" %>
<% foreach (var model in EventListing.Models.EventModel.EventList())
{ %>
<tr>
<td>
<%= Html.ActionLink(model.TITLE, "Detail", new { id = model.EVENT_ID })%>
A: Let me try to clean up your code a little:
public class EventInfo
{
public int OPR { get; set; }
public int EVENT_ID { get; set; }
public string SUBSITE { get; set; }
... some other properties that you might want to use
public static IEnumerable<EventInfo> Select()
{
var helper = new Dbhelper();
using (var cmd = helper.GetSqlStringCommond("SELECT * FROM WS_EVENTINFO"))
using (var reader = helper.ExecuteReader(cmd))
{
while (reader.Read())
{
yield return new EventInfo
{
OPR = reader.GetInt32(reader.GetOrdinal("OPR")),
EVENT_ID = reader.GetInt32(reader.GetOrdinal("EVENT_ID")),
SUBSITE = reader.GetString(reader.GetOrdinal("SUBSITE"))
}
}
}
}
}
then in the controller action:
public ActionResult List()
{
var model = EventInfo.Select().ToList();
return View(model);
}
and finally in the view:
<%@ Page
Language="C#"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<EventInfo>>" %>
<% foreach (var item in Model) { %>
<tr>
<td>
<%= Html.ActionLink(item.TITLE, "Detail", new { id = item.EVENT_ID }) %>
</td>
...
The next improvement that should be done to this is to externalize the data access (the Select static method) into a separate repository and have the controller use this repository instead of directly invoking the Select method to query the database.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create one to many in SQLITE3? How to create one to many in SQLITE3?
I have 2 tables:
Mans:
_id name
1 antony
2 fred
and
point
_id date point
1 23 77
24 99
2 25 78
5 0
I don't know SQL syntax, help me , please.
A: The syntax for this is as follows....
CREATE TABLE (MySecondTable) Foo INT FOREIGN KEY(Foo) REFERENCES MyFirstTable(PrimaryKeyField) ON DELETE CASCASDE ON UPDATE CASCASDE
only works on v3.6.1+
Here are the docs http://sqlite.org/foreignkeys.html
A: Going by what iamkrillin wrote:
CREATE TABLE (points) points_id INT
FOREIGN KEY(man_id) REFERENCES mans(PrimaryKeyField)
ON DELETE CASCADE ON UPDATE CASCADE
Here is a real-world example. Let's say you have some people who refer business to you: your staff, your friends, local businesses where you do advertising, etc. Customers who come in are called 'referal' business. Each person only counts as one referal, but a referer may refer many referals (for example, an employee may refer 20 new customers; the employee is your referer, and the employee has made 20 referals). So, you have 1 referer and 20 referals (one-to-many):
CREATE TABLE referal(
referal_id INTEGER UNIQUE NOT NULL PRIMARY KEY, //A customer can only be 1 referal.
referal_method TEXT, //How were they refered? By phone?
referer_id INTEGER , //Who refered them?
FOREIGN KEY(referer_id) REFERENCES referer(referer_id)); //Trace more about referer.
Now, it is possible that more than one person refers a referal, but I think that it is standard business practice to only compensate a single referer. So, you never need to list two referers. This will always be a 1-to-1 or a 1-to-many relationship; therefore, you should make it a 1-to-many table. I'm not very proficient in the CASCADE stuff, but I'll try to figure out how that fits.
At first glance, it appears ON UPDATE CASCADE ON DELETE CASCADE does not belong in my answer because removing the last referal should not remove the referer.
Looking at a different example:
CREATE TABLE all_candy
(candy_num SERIAL PRIMARY KEY,
candy_maker CHAR(25));
CREATE TABLE hard_candy
(candy_num INT,
candy_flavor CHAR(20),
FOREIGN KEY (candy_num) REFERENCES all_candy
ON DELETE CASCADE)
If you delete a hard candy from the hard_candy table, then you are also deleting it from the all_candy table because a hard candy is a type of candy, and if the type of candy has changed (for example, to discontinued candies), then a new INSERT command needs to be executed, anyway.
I ran a test case for ON UPDATE CASCADE and ON UPDATE DELETE in sqlite3, and it seems it has no effect. Perhaps they do not work with the default db engine for sqlite3, but the functionality IS listed at the official SQLite website: a very descriptive, easy-to-follow example of ON UPDATE CASCADE by sqlite.org. Have a read and see what you think.
This is the schema I used for my test case:
BEGIN TRANSACTION;
CREATE TABLE candy(id integer primary key not null, name text, description text);
INSERT INTO candy VALUES(1,'Laffy Taffy', 'Delicious, soft candy.');
INSERT INTO candy VALUES(2,'Pop Rocks', 'A candy that explodes in your mouth.');
COMMIT;
BEGIN TRANSACTION;
CREATE TABLE hard_candy(id integer primary key not null, name text, description text, foreign key(id,name,description) references hard_candy ON DELETE CASCADE ON UPDATE CASCADE);
INSERT INTO hard_candy VALUES(2,'Pop Rocks', 'A candy that explodes in your mouth.');
COMMIT;
Ran various updates on either table's id-2 description field.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: What HTML5 Canvas based Mapping libraries exist? The Bing Maps and Google Maps JavaScript/Ajax Mapping Controls/Libraries use <img/> tags for rending map tiles and such.
Are there any mapping controls/libraries available that utilize the HTML5 Canvas element for rendering the map tiles?
A more modern control would be nice, especially since it'll utilize hardware acceleration in the new browsers for rendering the map display.
A: My current favourite Javascript Maps API is Leaflet (http://leaflet.cloudmade.com). It's still only a very young control (first public release was a few months ago) and it's got a few bugs to be ironed out but it's got a lovely clean, lightweight API.
Best of all, all the map objects are designed to be easily extendable so, starting from the abstract ILayer interface, you can...:
*
*create regular tile layers that load images referenced by tile x/y/z
coordinates (http://leaflet.cloudmade.com/reference.html#tilelayer)
*create tile layers that load data from a WMS server
(http://leaflet.cloudmade.com/reference.html#tilelayer-wms)
*(and this is the specific answer to your question), create tile layers that are drawn using canvas elements on the client side (http://leaflet.cloudmade.com/reference.html#tilelayer-canvas)
And because it's open source, you can (unlike Bing or Google controls) extend these tile layers still further if you desire....
A: OpenLayers3 will offer WebGL, Canvas and DOM rendering support, in addition an extensive set of "connectors" for tile providers, OGC compliant servers, and support for vector features.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Using regex to insert a space in a string in php I have a string that is not properly formed and am attempting to correct it. An example of the string is: -
A Someone(US)B Nobody(US)
I am attempting to correct it to: -
A Someone(US) B Nobody(US)
I am using the below code to match ")" followed by a capital letter and using php's preg_replace function to do the match and add the space. However I'm completely rubbish at regex and cannot get the space added in the correct place.
$regex = "([\)][A-Z])";
$replacement = ") $0";
$str = preg_replace($regex, $replacement, $output);
Can anyone suggest a better method? I realise the space is not adding correclty because $0 contains the data I am matching, is there a way to manipulate $0?
A: $str = preg_replace('/(?<=\))(?=\p{Lu})/u', ' ', $output);
inserts a space between a closing parenthesis (\)) and an uppercase letter (\p{Lu}). You don't need $0 (or $1 etc.) at all since you're just inserting something at a position between two characters, and this regex matches exactly this (zero-width) position. Check out lookaround assertions.
A: how about regex="(?<=\))[A-Z]"
and replacement=" $0"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Android video recording app nuiances I have just started Android development.And my goal is to create an android webcam app.
I have taken the base code from here:API Demos
and my modified code is included below..
recording happens on click event.But the first time i click,
logcat shows me could not connect to camera..
09-25 01:29:58.580: WARN/CameraService(27788): CameraService::connect X (pid 27788) rejected (existing client).
09-25 01:29:58.580: ERROR/StagefrightRecorder(27788): Camera connection could not be established.
09-25 01:29:58.580: WARN/AACEncoder(27788): Call stop() when encoder has not started
09-25 01:29:58.580: WARN/AACEncoder(27788): [ 09-25 01:29:58.580 27788:0x6cd9 F/MPEG4Writer ]
09-25 01:29:58.580: WARN/AACEncoder(27788): frameworks/base/media/libstagefright/MPEG4Writer.cpp:2263 mCodecSpecificData
09-25 01:30:01.130: WARN/IMediaDeathNotifier(28022): media server died
09-25 01:30:01.130: WARN/AudioSystem(1351): AudioFlinger server died!
09-25 01:30:01.140: WARN/Camera(28022): ICamera died
09-25 01:30:01.140: WARN/AudioSystem(1351): AudioPolicyService server died!
09-25 01:30:01.140: WARN/Camera(28022): Camera server died!
09-25 01:30:01.150: ERROR/Camera(28022): Error 100
09-25 01:30:02.639: ERROR/AudioService(1351): Media server started.
09-25 01:30:02.639: ERROR/AudioService(1351): Media server died.
09-25 01:30:02.649: WARN/AudioPolicyManagerBase(28039): setPhoneState() setting same state 0
The second click starts the recording, but on the third click when the recording stops,the screen goes black..though the fourth click does start recording again..
So i have no idea about two things..
*
*why the camera fails to connect on first click?
*why does the screen go black after stopping the recording?
My Modified Code:
public class blueCam extends Activity implements OnClickListener {
private Preview mPreview;
Camera mCamera;
int numberOfCameras;
int cameraCurrentlyLocked;
MediaRecorder recorder;
boolean recording = false;
// The first rear facing camera
int defaultCameraId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide the window title.
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Create a RelativeLayout container that will hold a SurfaceView,
// and set it as the content of our activity.
mPreview = new Preview(this);
setContentView(mPreview);
// Find the total number of cameras available
numberOfCameras = Camera.getNumberOfCameras();
// Find the ID of the default camera
CameraInfo cameraInfo = new CameraInfo();
for (int i = 0; i < numberOfCameras; i++) {
Camera.getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
defaultCameraId = i;
}
}
mPreview.mSurfaceView.setClickable(true);
mPreview.mSurfaceView.setOnClickListener(this);
initRecording();
}
@Override
protected void onResume() {
super.onResume();
// Open the default i.e. the first rear facing camera.
mCamera = Camera.open();
cameraCurrentlyLocked = defaultCameraId;
mPreview.setCamera(mCamera);
}
@Override
protected void onPause() {
super.onPause();
// Because the Camera object is a shared resource, it's very
// important to release it when the activity is paused.
if (mCamera != null) {
mPreview.setCamera(null);
mCamera.release();
mCamera = null;
}
}
public void onClick(View v) {
if (recording) {
recorder.stop();
recorder.reset();
recording = false;
// Let's initRecorder so we can record again
} else {
initRecording();
prepareRecorder();
recording = true;
recorder.start();
}
}
public void prepareRecorder() {
recorder.setPreviewDisplay(mPreview.mHolder.getSurface());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
public void initRecording()
{
String PATH_NAME="/mnt/sdcard/AshVrec.mp4";
recorder = new MediaRecorder();
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
CamcorderProfile cpHigh = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
recorder.setProfile(cpHigh);
recorder.setOutputFile(PATH_NAME);
recorder.setMaxDuration(50000); // 50 seconds
recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
}
class Preview extends ViewGroup implements SurfaceHolder.Callback {
private final String TAG = "Preview";
SurfaceView mSurfaceView;
SurfaceHolder mHolder;
Size mPreviewSize;
List<Size> mSupportedPreviewSizes;
Camera mCamera;
Preview(Context context) {
super(context);
//initRecording();
mSurfaceView = new SurfaceView(context);
addView(mSurfaceView);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = mSurfaceView.getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void setCamera(Camera camera) {
mCamera = camera;
if (mCamera != null) {
mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
requestLayout();
}
}
public void switchCamera(Camera camera) {
setCamera(camera);
try {
camera.setPreviewDisplay(mHolder);
} catch (IOException exception) {
Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
}
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
requestLayout();
camera.setParameters(parameters);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// We purposely disregard child measurements because act as a
// wrapper to a SurfaceView that centers the camera preview instead
// of stretching it.
final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(width, height);
if (mSupportedPreviewSizes != null) {
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (changed && getChildCount() > 0) {
final View child = getChildAt(0);
final int width = r - l;
final int height = b - t;
int previewWidth = width;
int previewHeight = height;
if (mPreviewSize != null) {
previewWidth = mPreviewSize.width;
previewHeight = mPreviewSize.height;
}
// Center the child SurfaceView within the parent.
if (width * previewHeight > height * previewWidth) {
final int scaledChildWidth = previewWidth * height / previewHeight;
child.layout((width - scaledChildWidth) / 2, 0,
(width + scaledChildWidth) / 2, height);
} else {
final int scaledChildHeight = previewHeight * width / previewWidth;
child.layout(0, (height - scaledChildHeight) / 2,
width, (height + scaledChildHeight) / 2);
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, acquire the camera and tell it where
// to draw.
try {
if (mCamera != null) {
mCamera.setPreviewDisplay(holder);
}
} catch (IOException exception) {
Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
}
//prepareRecorder();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
if (mCamera != null) {
mCamera.stopPreview();
}
recorder.stop();
recorder.reset();
recorder.release();
}
private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) w / h;
if (sizes == null) return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
// Try to find an size match aspect ratio and size
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio, ignore the requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
requestLayout();
mCamera.setParameters(parameters);
mCamera.startPreview();
}
}
}
Any help would be worth.
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: django - what's the proper way of passing the "request" parameter to a custom template tag I created a custom template tag that I want to use on every page on my web site. I have a function get_ip inside the custom template tag that needs the request parameter in order to get the IP address from the user. See below:
myapp/templatetags/header_tags.py
from django import template
register = template.Library()
...
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
@register.inclusion_tag('template.html', takes_context = True)
def user_ip(context):
request = context['request']
ip = get_ip(request)
return render_to_response('template.html',locals(), context_instance=RequestContext(request))
template.html
{{ ip }}
my_main_template.html
{% load header_tags %}
{% user_ip %}
For some reason my the ip is not sowing on my main template. My function get_ip works if used the regular way on views.py page a template but for some reason is not showing when is used from the custom template tag above. Any ideas?
A: You're not supposed to actually render the template in an inclusion tag - the decorator does that for you. You just return the context that should be used to render the template you've specified.
A: Try somenting like this.
@register.inclusion_tag('template.html', takes_context = True)
def user_ip(context):
return {'ip': get_ip(context['request'])}
A: Your inclusion tag should return a context to be rendered to a template, not render_to_response. Might look like this:
def user_ip(context):
my_context = {}
request = context['request']
my_context['ip'] = get_ip(request)
return my_context
register.inclusion_tag('template.html', takes_context = True)(user_ip)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does Monodevelop ask me for a ssh key password when it is registered in ssh-agent I can commit it fine using the command line and monodevelop has no issue with the public repo but when i try to push it to github it keeps asking me for the password to idrsa, I have tried using ssh-add to verify the key and it verifys fine.
A: Assuming:
*
*you can push from the command line without being asked for your password, and
*you're not using Windows, then
Monodevelop probably does not have the correct value of the SSH_AUTH_SOCK environment variable. Try starting Monodevelop from the command prompt so that it will inherit the same environment variables used by the git command.
A: I see this too. Did you ever resolve it? Even if you set up passwordless key auth, this fails. It seems like a bug in the way Monodevelop uses LibGit2Sharp. Trying to build a workaround. Strange this has been an issue for so long. I had better luck in 5.9 before 5.10. Maybe now that Microsoft is buying it things will improve.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to delete the first row of a dataframe in R? I have a dataset with 11 columns with over a 1000 rows each. The columns were labeled V1, V2, V11, etc..
I replaced the names with something more useful to me using the "c" command.
I didn't realize that row 1 also contained labels for each column and my actual data starts on row 2.
Is there a way to delete row 1 and decrement?
A: I am not expert, but this may work as well,
dat <- dat[2:nrow(dat), ]
A: dat <- dat[-1, ] worked but it killed my dataframe, changing it into another type. Had to instead use
dat <- data.frame(dat[-1, ]) but this is possibly a special case as this dataframe initially had only one column.
A: You can use negative indexing to remove rows, e.g.:
dat <- dat[-1, ]
Here is an example:
> dat <- data.frame(A = 1:3, B = 1:3)
> dat[-1, ]
A B
2 2 2
3 3 3
> dat2 <- dat[-1, ]
> dat2
A B
2 2 2
3 3 3
That said, you may have more problems than just removing the labels that ended up on row 1. It is more then likely that R has interpreted the data as text and thence converted to factors. Check what str(foo), where foo is your data object, says about the data types.
It sounds like you just need header = TRUE in your call to read in the data (assuming you read it in via read.table() or one of it's wrappers.)
A: While I agree with the most voted answer, here is another way to keep all rows except the first:
dat <- tail(dat, -1)
This can also be accomplished using Hadley Wickham's dplyr package.
dat <- dat %>% slice(-1)
A: Keep the labels from your original file like this:
df = read.table('data.txt', header = T)
If you have columns named x and y, you can address them like this:
df$x
df$y
If you'd like to actually delete the first row from a data.frame, you can use negative indices like this:
df = df[-1,]
If you'd like to delete a column from a data.frame, you can assign NULL to it:
df$x = NULL
Here are some simple examples of how to create and manipulate a data.frame in R:
# create a data.frame with 10 rows
> x = rnorm(10)
> y = runif(10)
> df = data.frame( x, y )
# write it to a file
> write.table( df, 'test.txt', row.names = F, quote = F )
# read a data.frame from a file:
> read.table( df, 'test.txt', header = T )
> df$x
[1] -0.95343778 -0.63098637 -1.30646529 1.38906143 0.51703237 -0.02246754
[7] 0.20583548 0.21530721 0.69087460 2.30610998
> df$y
[1] 0.66658148 0.15355851 0.60098886 0.14284576 0.20408723 0.58271061
[7] 0.05170994 0.83627336 0.76713317 0.95052671
> df$x = x
> df
y x
1 0.66658148 -0.95343778
2 0.15355851 -0.63098637
3 0.60098886 -1.30646529
4 0.14284576 1.38906143
5 0.20408723 0.51703237
6 0.58271061 -0.02246754
7 0.05170994 0.20583548
8 0.83627336 0.21530721
9 0.76713317 0.69087460
10 0.95052671 2.30610998
> df[-1,]
y x
2 0.15355851 -0.63098637
3 0.60098886 -1.30646529
4 0.14284576 1.38906143
5 0.20408723 0.51703237
6 0.58271061 -0.02246754
7 0.05170994 0.20583548
8 0.83627336 0.21530721
9 0.76713317 0.69087460
10 0.95052671 2.30610998
> df$x = NULL
> df
y
1 0.66658148
2 0.15355851
3 0.60098886
4 0.14284576
5 0.20408723
6 0.58271061
7 0.05170994
8 0.83627336
9 0.76713317
10 0.95052671
A: No one probably really wants to remove row one. So if you are looking for something meaningful, that is conditional selection
#remove rows that have long length and "0" value for vector E
>> setNew<-set[!(set$length=="long" & set$E==0),]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "98"
} |
Q: Inserting linebreak in the title attribute using javascript/jquery Question:
I need to put a linebreak inside my tooltip so it's not all on one line. I use tooltipsy to generate my tooltips. It works by using the title attribute on any anchor tags with the class "hastipy" as the content of the tooltip.
So the code:
<a href="http://tooltipsy.com/" class="hastipy" title="Click here to go to the tooltipsy website">
tooltipsy
</a>
Would be a link showing the text "tooltipsy" and when you hover over it, it would show "Click here to go to the tooltipsy website" in a tooltip.
However, what if I want to put a linebreak inside the tooltip?
This code:
<a href="http://tooltipsy.com/" class="hastipy" title="Click here to <br /> go to the tooltipsy website">
tooltipsy
</a>
returns a bunch of errors when you validate it at http://validator.w3.org
So I came up with this javascript/jQuery (written by Jason Gennaro):
$('a').each(function(){
var a = $(this).attr('title');
var b = a.replace('lineBreak','\n');
$(this).attr('title', b);
});
this code uses a keyword (lineBreak in this case) and replaces it with \n(<-- linebreak?) so my code passes validation and still has the linebreak in it.
And this code works on jsfiddle (here is the example), but on my website inside the tooltip, it doesn't. It inserts the \n, but it doesn't remove the "lineBreak" like it's supposed to.
Can anyone offer an explanation for this or even a possible fix for it?
Note:
I don't want a suggestion for another tooltip method, tooltipsy is working perfectly for everything I need.
Result:
As it turns out, just using <br /> instead of <br /> worked perfectly.
A: Use a global replace call: .replace(/lineBreak/g,'\n');.
If you want to add <br /> in your title attribute, use: <br /> (html entities).
Also, JQuery automatically wraps the JavaScript inside $(document).ready(...). You should do the same:
$(document).ready(function(){
//HTML-modifying code here.
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to find files with same size? I have a file structure like so
a/file1
a/file2
a/file3
a/...
b/file1
b/file2
b/file3
b/...
...
where within each dir, some files have the same file size, and I would like to delete those.
I guess if the problem could be solved for one dir e.g. dir a, then I could wrap a for-loop around it?
for f in *; do
???
done
But how do I find files with same size?
A: ls -l|grep '^-'|awk '{if(a[$5]){ a[$5]=a[$5]"\n"$NF; b[$5]++;} else a[$5]=$NF} END{for(x in b)print a[x];}'
this will only check files, no directories.
$5 is the size of ls command
test:
kent@ArchT60:/tmp/t$ ls -l
total 16
-rw-r--r-- 1 kent kent 51 Sep 24 22:23 a
-rw-r--r-- 1 kent kent 153 Sep 24 22:24 all
-rw-r--r-- 1 kent kent 51 Sep 24 22:23 b
-rw-r--r-- 1 kent kent 51 Sep 24 22:23 c
kent@ArchT60:/tmp/t$ ls -l|grep '^-'|awk '{if(a[$5]){ a[$5]=a[$5]"\n"$NF; b[$5]++;} else a[$5]=$NF} END{for(x in b)print a[x];}'
a
b
c
kent@ArchT60:/tmp/t$
update based on Michał Šrajer 's comment:
Now filenames with spaces are also supported
command:
ls -l|grep '^-'|awk '{ f=""; if(NF>9)for(i=9;i<=NF;i++)f=f?f" "$i:$i; else f=$9;
if(a[$5]){ a[$5]=a[$5]"\n"f; b[$5]++;} else a[$5]=f}END{for(x in b)print a[x];}'
test:
kent@ArchT60:/tmp/t$ l
total 24
-rw-r--r-- 1 kent kent 51 Sep 24 22:23 a
-rw-r--r-- 1 kent kent 153 Sep 24 22:24 all
-rw-r--r-- 1 kent kent 51 Sep 24 22:23 b
-rw-r--r-- 1 kent kent 51 Sep 24 22:23 c
-rw-r--r-- 1 kent kent 51 Sep 24 22:40 x y
kent@ArchT60:/tmp/t$ ls -l|grep '^-'|awk '{ f=""
if(NF>9)for(i=9;i<=NF;i++)f=f?f" "$i:$i; else f=$9;
if(a[$5]){ a[$5]=a[$5]"\n"f; b[$5]++;} else a[$5]=f} END{for(x in b)print a[x];}'
a
b
c
x y
kent@ArchT60:/tmp/t$
A: Solution working with "file names with spaces" (based on Kent (+1) and awiebe (+1) posts):
for FILE in *; do stat -c"%s/%n" "$FILE"; done | awk -F/ '{if ($1 in a)print $2; else a[$1]=1}' | xargs echo rm
to make it remove duplicates, remove echo from xargs.
A: Here is code if you need the size of a file:
FILESIZE=$(stat -c%s "$FILENAME")
echo "Size of $FILENAME = $FILESIZE bytes."
Then use a for loop to get the first item in your structure,
Store the size of that file in a variable.
Nest a for loop in that for loop to each item in your structure(excluding the current item) to the current item.
Route all the names of identical files into a text file to ensure you have written you script correctly(insteed of executing rm immediately) .
Execute rm on the contents of this file.
A: Based on the accepted answer, the following provides a list of all the files of the same size in the current directory (so you can choose which one to keep), sorted by size:
for FILE in *; do stat -c"%s/%n" "$FILE"; done | awk -F/ '{if ($1 in a)print a[$1]"\n"$2; else a[$1]=$2}' | sort -u | tr '\n' '\0' | xargs -0 ls -lS
To determine if the files are actually the same, not just the contain the same number of bytes, do an shasum or md5sum on each file:
for FILE in *; do stat -c"%s/%n" "$FILE"; done | awk -F/ '{if ($1 in a)print a[$1]"\n"$2; else a[$1]=$2}' | sort -u | tr '\n' '\0' | xargs -0 -n1 shasum
A: Plain bash solution
find -not -empty -type f -printf "%s\n" |
sort -rn | uniq -d |
xargs -I{} -n1 find -type f -size {}c -print0 |
xargs -0 du | sort
A: It sounds like this has been answered several times and in several different ways, so I may be beating a dead horse but here goes...
find DIR_TO_RUN_ON -size SIZE_OF_FILE_TO_MATCH -exec rm {} \;
find is an awesome command and I highly recommend reading its manpage.
A: Looks like what you really want is a duplicate file finder?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Rails get title How can I get the title of my page using Rails? content_for will set it, so is there a better way than to assign it to an instance variable?
A: If your'e using content_for to set it, you can simply use content_for to get it as well.
<% content_for :title, "My Title" %>
Some time later ...
<title><%= content_for :title %></title>
...
<h1><%= content_for :title %></h1>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Do I need to try/catch on opendir in PHP due to E_WARNING? I'm making a little file browser for homework - and I have it working as well as I need to, but I'm a little confused on handling error scenarios in PHP now that I'm trying to refactor my coding.
I'm used to C++/C# try/catch error handling, which PHP seems to have some variant of. What's confusing me is this:
resource opendir ( string $path [, resource $context ] )
Returns a directory handle resource on success, or FALSE on failure.
If path is not a valid directory or the directory can not be opened
due to permission restrictions or filesystem errors, opendir() returns
FALSE and generates a PHP error of level E_WARNING. You can suppress
the error output of opendir() by prepending '@' to the front of the
function name.
from http://php.net/manual/en/function.opendir.php.
Do I need to catch the generated PHP error of level E_WARNING mentioned there, or is it silly to? I don't understand why it would return false and throw an error - shouldn't the error throwing make it so you don't return normally anyway?
A: Errors/warnings produced in this way cannot therefore be handled using try/catch because the language infrastructure that handles them dates back to before PHP supported exceptions or try/catch.
You'll only really be able to use try/catch when you're using the more modern PHP modules, which use classes and generate exceptions instead of errors and warnings.
Most of PHP's core functionality is still based around the old error handling mechanism.
The first thing you should be doing with opendir() is checking that the directory exists and can be opened before you attempt to open it; this will prevent you needing to handle error conditions with opendir() itself.
If you are still cautious about warnings being thrown, you can suppress the warnings using the @ symbol. Be aware that this will suppress genuine errors as well.
Alternatively, if you're really bored, you could create a wrapper for the whole thing, which changes the error_reporting() level before making the call and sets it back again afterward. You could even have it throw an exception for you if necessary.
So these things can be done, but it's unlikely to be worth the hassle; you may as well just live with the fact that PHP's error handling isn't great, and has evolved over time rather than being carefully thought out in the first place as C++/C#'s was.
A: You would use catch in order to deal with a raised Exception. A PHP error is something different. PHP errors have different levels, or severity. You can modify which of these errors is outputted using error_reporting(). In order to suppress an individual PHP error on a statement, use @, like: @opendir(..)
A: Warnings should only be thrown in test/acceptation environments. You can safely check if the directory exists by strong compared it with false
if (opendir($dir) === false)
echo "it failed!";
The waring can be caught with a custom error handler which can write it to a log file instead showing it on the screen.
A: You may suppress the warning with the @ simbol like @opendir(). This is common to suppress resource handler warnings, since there are cases when the resource in unavailable, but these should be handled with care.
In live environment you should have error display off, so it is only useful in developement, but it may break your generated page, so it may be useful to suppress it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Sending info from UITableView to SuperView I have a UITableViewController that I pragmatically call into my superview when needed. When I tap a table view I want the info to be placed in a UITextField. now I can get it to log correctly from the superview but the text never gets placed in its correct field.
Coming from the UITablViewController:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
NSLog(@"Index %i Touched:",indexPath.row);
self.MainView = [[TwitterViewController alloc] init];
self.MainView.view = super.view;
selectedFriend = [(Tweet*)[friends objectAtIndex:indexPath.row]followingScreenName];
self.MainView.selectedFriendForTweet = self.selectedFriend;
[self.MainView setSelectedFriendInBody:self.selectedFriend
into:self.MainView.TweetBody
with:self];
//NSLog(@"selected name on tblview = %@",selectedFriend);
self.MainView.TweetBody.text = self.selectedFriend;
}
as you see my method is called when a user taps the tblview
[self.MainView setSelectedFriendInBody:self.selectedFriend
into:self.MainView.TweetBody
with:self];
Here is that method : Now this log Works and the info is correct but just will not go into the textview!
-(void)setSelectedFriendInBody:(NSString*)aString into:(UITextView*)atextView with:(id)sender
{
aString = friendsTbl.selectedFriend;
friendsTbl.selectedFriend = self.selectedFriendForTweet;
atextView = self.TweetBody;
[self.TweetBody setText:selectedFriendForTweet];
NSLog(@"superviews name = %@", selectedFriendForTweet);
[selectedFriendForTweet retain];
}
Any Help would be greatly appreciated! Thank you
A: you are doing some strange stuff in your code. Just an example: your method setSelectedFriendInBody:into: gets two parameters which your are not using in your implementation. Even worse: you are assinging some values to that parameters which has definatly no effect. There has to be sth wrong...
your code does sth like this: a=2; b=3; c=10; d=20;=> f(x,y)=c+d => f(a,b)=30
And it is a bad idea (with respect to reuseability) to force that the superview is a special view. The right way to do this is to use the delegate-pattern. just define a protocol which should contain your method setSelectedFriendInBody:into: and implement that protocol in your MainView. The TablView only get and call a delegate (an id which implements the protocol).
@protocol MyTablViewDelegate
-(void)setSelectedFriendInBody:(NSString*)aString;
@end
@interface MyTablView : UITableView<UITableViewDelegate>
{
id<MyTablViewDelegate> myDelegate;
}
@property (assign) id<MyTablViewDelegate> myDelegate; //I use assign here for avoiding mem-leaks due to circular retain-chains
@end
@implementation MyTablView
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
....
NSString *someString = [(Tweet*)[friends objectAtIndex:indexPath.row]followingScreenName];
NSLog(@"someString: %@", someString); // maybe there is an error in getting that object from array or in followingScreenName
[self.myDelegate setSelectedFriendInBody: someString];
}
@end
@interface MainView : UIView<MyTablViewDelegate>
...
@end
@implementation MainView
...
-(void) sthAtLoadTime
{
MyTablView *mySubView = [[MyTablView alloc] init...];
mySubView.myDelegate = self;
}
-(void)setSelectedFriendInBody:(NSString*)aString
{
if(!self.TweetBody)
NSLog(@"ERR: TweetBody not set");
self.TeetBody.text = aString;
}
@end
Note another thing: I assume that your myTablView also implements the UITableViewDelegate which is also not the best way to do
this should do the work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C# - How to Rretrieve Background Color of Window I have searched in this forum and I have not found anything that would help me with the following. Please help if possible. Thank you.
I have set the background of a window to black (or any other color I like). As part of the calculations done by the app, I plot different regions in color on that window. The color of the regions is dynamic and I would like to find and store the starting color of the region before the color change so that I can return to that base color. For example, if the starting background color is black, and the app changes the color to green, I would like to return the color back to the base color black when needed without having to remember that the base color was black.
I tried using
private Color backgroundColor = (Color)System.Drawing.SystemColors.Window;
and then later on
BackColor = backgroundColor;
This does work but the color goes back to white rather than the black I had specified in my preferences.
Can anyone please suggest a solution? Thank you very much for any help you may be bale to provide.
A: Yes, SystemColors.Window is white by default. You probably want this:
private Color backgroundColor;
private void startPlotting()
{
backgroundColor = BackColor;
BackColor = Color.Black;
// etc..
}
private void restoreWindow()
{
BackColor = backgroundColor;
}
A: Color.FromArgb(System.Drawing.SystemColors.WindowFrame.ToArgb());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting objects in a Guice object graph I'm trying to make a facade for a library I'm giving out. In my facade I use Guice to contruct the object graph. Deep in the object graph is a Proxy object, that has getURL/setURL methods.
In my facade, how do I get the Proxy instance used to create my root object? I want my facade to have url getter and setter.
I tried something like this:
public class SomeThingFacade() {
private final SomeThing thing;
private final HTTPProxy proxy;
public SomeThingFacade() {
MyModule module = new MyModule();
Injector injector = Guice.createInjector(module);
// this is the main class I'm making a facade for
this.thing = injector.getInstance(SomeThing.class);
// deep in the "thing" object graph is a Proxy implementation
this.proxy = injector.getInstance(HTTPProxy.class);
}
public void setURL(URL url) {
this.proxy.setURL(url);
}
}
but the injector.getInstance created a new instance.
Binding in MyModule:
bind(Proxy.class).to(HTTPProxy.class).asEagerSingleton();
I had previously hardcoded the object graph in the facade constructor, but it got unwieldly with 30 objects.
Basically, I need to configure an instance deep in the object graph after creation, but I'm not sure how I get a hold of that instance.
A: This totally looks like a good serious question. However, I can't figure out what's being asked exactly.
My answer, looking at the code and ignoring the fascaded object graph talk (so let me know if I misunderstood you completely), is:
If thing's SomeThing depends somewhere on a deep internal proxy, the module should configure it to be bound to HTTPProxy for thing. The second getInstance does not affect the first. The only way you could somehow be doing something that makes proxy affect thing is if HTTPProxy were bound in(Singleton.class), then by calling methods on proxy that affect the members and behavior of HTTPProxy which would also be the same instance deep inside thing you might be doing what you're looking for. I don't see why you'd want to do it this way though. Consider instead writing a provider that configures HTTPProxy and/or making a special module just for the facade's use.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Skipping text while reading files in C++ I'm learning C++, and I'm doing work with data loaded from external text files using cin.
I'm trying to recognize certain strings in large amounts of data that I need to skip through.
How would I write a function that skips through a certain number of characters in a file / on a line, either as I'm importing them from a file? Does such a thing already exist in iostream or similar?
Google has let me down so far.
A: On general skipping: seekg
On the real issue:
It seems like you would want to be matching patterns against a large body of (semi?) text. Since the pattern is long enough that you can gain from skipping input stretches, it really seems you are trying to invent optimized string search all over.
It has been done:
*
*http://en.wikipedia.org/wiki/Boyer_Moore_string_search_algorithm
*http://volnitsky.com/project/str_search/index.html
Implementations exist in the wild (I assume Boost String Algorithm should have it... but maybe it too general-purpose to have it. I'd have a look anyways)
PS.: Boost Spirit
This parser is currently reviewing an enhancement that implements the qi::seek[] directive:
*
*https://github.com/jamboree/boost-jamboree-spirit/blob/master/libs/spirit/repository/example/qi/seek.cpp
*http://boost.2283326.n4.nabble.com/Proposal-for-qi-seek-directive-td3830251.html
This allows blazingly fast skipping inside a Spirit grammar. So if you have a case for a full parser (perhaps even scanner/parser), Spirit Qi could really be your match in performance.
Be sure to:
*
*avoid buffering input iterator adaptors if you can (depends on grammar)
*imbue "C" locale if you can
*operate on the input streambuf's iterators as opposed to input streams iterators
A: #include <iostream>
#include <string>
using std::ifstream;
using std::string;
using std::getline;
ifstream ifs(filename);
if ( ! ifs ) {
/* ERROR CODE IN HERE */
}
string line;
while ( getline(ifs, line) )
{
// line now contains one line from the input file
if ( /* want to skip */ ) {
continue;
}
/* Do something with the line */
}
edit: some of the boost string predicates (starts_with, ends_with) might be useful for that conditional inside the while loop. For instance, if you only want to process lines that start with 'FOO', you would write
#include <boost/algorithm/string/predicate.hpp>
using boost::starts_with;
while ( getline(ifs,line) )
{
if ( starts_with(line, "FOO") ) {
/* DO SOMETHING */
}
}
http://www.boost.org/doc/libs/1_41_0/doc/html/string_algo.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: My sub query is adding 20 seconds to the execution time. How can I speed it up? I have a table of sent SMS text messages which must join to a delivery receipt table to get the latest status of a message.
There are 997,148 sent text messages.
I am running this query:
SELECT
m.id,
m.user_id,
m.api_key,
m.to,
m.message,
m.sender_id,
m.route,
m.submission_reference,
m.unique_submission_reference,
m.reason_code,
m.timestamp,
d.id AS dlrid,
d.dlr_status
FROM
messages_sent m
LEFT JOIN
delivery_receipts d
ON
d.message_id = m.id
AND
d.id = (SELECT MAX(id) FROM delivery_receipts WHERE message_id = m.id)
Which returns 997,148 results including the latest status of each message.
This takes 22.8688 seconds to execute.
Here is the SQL for messages_sent:
CREATE TABLE IF NOT EXISTS `messages_sent` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(10) unsigned NOT NULL,
`api_key` varchar(40) NOT NULL,
`to` varchar(15) NOT NULL,
`message` text NOT NULL,
`type` enum('sms','mms') NOT NULL DEFAULT 'sms',
`sender_id` varchar(15) NOT NULL,
`route` tinyint(1) unsigned NOT NULL,
`supplier` tinyint(1) unsigned NOT NULL,
`submission_reference` varchar(40) NOT NULL,
`unique_submission_reference` varchar(40) NOT NULL,
`reason_code` tinyint(1) unsigned NOT NULL,
`reason` text NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
KEY `api_key` (`api_key`),
KEY `sender_id` (`sender_id`),
KEY `route` (`route`),
KEY `submission_reference` (`submission_reference`),
KEY `reason_code` (`reason_code`),
KEY `timestamp` (`timestamp`),
KEY `to` (`to`),
KEY `unique_submission_reference` (`unique_submission_reference`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1000342 ;
And for delivery_receipts:
CREATE TABLE IF NOT EXISTS `delivery_receipts` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`message_id` int(10) unsigned NOT NULL,
`dlr_id` bigint(20) unsigned NOT NULL,
`dlr_status` tinyint(2) unsigned NOT NULL,
`dlr_substatus` tinyint(2) unsigned NOT NULL,
`dlr_final` tinyint(1) unsigned NOT NULL,
`dlr_refid` varchar(40) NOT NULL,
`dlr_phone` varchar(12) NOT NULL,
`dlr_charge` tinyint(3) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `message_id` (`message_id`),
KEY `dlr_status` (`dlr_status`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1468592 ;
Here is an EXPLAIN of the SQL:
A: There is a trick.
Instead with picking MAX element with subquery you join with interesting table twice like this:
SELECT
m.id,
m.user_id,
m.api_key,
m.to,
m.message,
m.sender_id,
m.route,
m.submission_reference,
m.unique_submission_reference,
m.reason_code,
m.timestamp,
d.id AS dlrid,
d.dlr_status
FROM
messages_sent m
JOIN
delivery_receipts d
ON
d.message_id = m.id
LEFT JOIN
delivery_receipts d1
ON
d1.message_id = m.id
AND
d1.id > d.id
WHERE
d1.id IS NULL
The second time table is joined it has additional condition that field that you want to pick MAX of should be higher than in the first table. And filter out all rows except the ones that do not have other row that's higher.
This way only max rows remain.
I changed your LEFT JOIN to JOIN. I'm not sure if you need LEFT JOIN there. Even if you it should still work.
Amazingly this is much faster than subquery.
You might want to try out other variant of the same idea:
SELECT
m.id,
m.user_id,
m.api_key,
m.to,
m.message,
m.sender_id,
m.route,
m.submission_reference,
m.unique_submission_reference,
m.reason_code,
m.timestamp,
d.id AS dlrid,
d.dlr_status
FROM
messages_sent m
JOIN
(
SELECT d0.* FROM
delivery_receipts d0
LEFT JOIN
delivery_receipts d1
ON
d1.message_id = d0.message_id
AND
d1.id > d0.id
WHERE
d1.id IS NULL
) d
ON
d.message_id = m.id
Make sure you have multicolumn index for fields message_id and id in table delivery_receipts maybe such:
ALTER TABLE `delivery_receipts`
ADD INDEX `idx` ( `message_id` , `id` );
A: The slowdown seems large, but I'm afraid there is not much room for improvement if you need to stick with this query.
One problem is the reporting of d.dlr_status. Try to remove this from the list of reported columns and see if the query time improves.
You would get the best possible performance if everything was stored in messages_sent. This won't be NF anymore, but it's an option if you need performance. To achieve this, create id and dlr_status columns in messages_sent and add appropriate INSERT, UPDATE and DELETE triggers to delivery_receipts. The triggers would update the corresponding columns in messages_sent -- it's a trade-off between query time and update time.
A: You can "cache" part of the computation in the delivery_receipts table, just add is_last_status boolean to the delivery_receipts table. Using simple triggers you can change the value every insert of new receipt.
Than the select query becomes much simpler:
SELECT
m.id,
m.user_id,
m.api_key,
m.to,
m.message,
m.sender_id,
m.route,
m.submission_reference,
m.unique_submission_reference,
m.reason_code,
m.timestamp,
d.id AS dlrid,
d.dlr_status
FROM
messages_sent m
LEFT JOIN
delivery_receipts d
ON
d.message_id = m.id
WHERE
d.is_last_status = true
If mysql would support partial indexes the query could be speed up even more.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Telerik MVC Grid Ajax Parameters? I am kind of fed up with trying to figure Ajax Grid parameters. I have created several grids and the parameters just kind of seem to be willy-nilly, I try one thing, it doesn't work for one, then works for another.
My understanding is that you really don't have to put the parameters in the .DataBinding if those parameters exist in the .DataKeys collection? This seems to be arbitrary when it works and when it doesn't.
Can someone give me a short overview about Ajax grid binding and passing parameters to a controller so I can select data to populate it with? Why is it I need to define the parameters and other times it works like magic?
Lately, every little think seems to be a battle with the Telerik MVC controls, even stuff I have done 5-6 times before.
In this case:
LineItemID is the primary key and JobID is a foreign key. I really want to pass the JobID to the select binding. I want to grab all line items with a specific JobID.
View:
@{ Grid<viaLanguage.Jams.Data.tblJobManagementLineItem> grid = Html.Telerik().Grid<viaLanguage.Jams.Data.tblJobManagementLineItem>()
.Name("InvoiceLineItemsGrid")
.DataKeys(keys =>
{
keys.Add(i => i.LineItemID);//.RouteKey("LineItemID");
keys.Add(i => i.JobID);//.RouteKey("jobID");
})
.DataBinding(dataBinding => dataBinding.Ajax()
.Select("_SelectInvoiceLineItems", "Job", new { jobID = "<#= JobID #>" })
.Insert("_InsertJobInvoice", "Job")
.Update("_UpdateJobInvoice", "Job")
.Delete("_DeleteJobInvoice", "Job"))
.ToolBar(commands => commands.Insert().HtmlAttributes(new { style = "margin-left:0" }))
.Columns(columns =>
{
columns.Bound(l => l.JobID);
columns.Bound(l => l.LineItemDescr).Width(180).HeaderTemplate("Task");
columns.Bound(l => l.LanguagePairID).Width(100).HeaderTemplate("Language Pair").ClientTemplate("<#= LanguagePair #>");
columns.Bound(l => l.SourceWordCount).Width(100).HeaderTemplate("Source Words");
columns.Bound(l => l.QtyToInvoice).Width(100).HeaderTemplate("Quantity to Invoice");
columns.Bound(l => l.Rate).Width(50).Format("${0:0.000}").HeaderHtmlAttributes(new { style = "text-align: center;" }).HtmlAttributes(new { style = "text-align: center;" });
columns.Bound(l => l.SubTotal).Width(100).Format("{0:c}");
columns.Command(commands =>
{
commands.Edit().ButtonType(GridButtonType.Image);
commands.Delete().ButtonType(GridButtonType.Image);
}).Width(80).HtmlAttributes(new { style = "white-space: nowrap;" });
})
.Resizable(resizing => resizing.Columns(true))
.Sortable()
.Selectable()
.Pageable(paging => paging.PageSize(10))
.Scrollable(c => c.Height("233px"))
.Filterable();
StringWriter sw = new StringWriter();
grid.Render();
grid.WriteInitializationScript(sw);
}
@Html.Hidden("InvoiceLineItemsGrid_tGrid", sw.GetStringBuilder().ToString())
Controller:
[GridAction]
public ActionResult _SelectInvoiceLineItems(int jobID)
{
logLogic.logger.Debug(logLogic.GetMethodName() + ": User '" + User.Identity.Name);
return View(new GridModel(jobLogic.GetInvoiceLineItems(jobID, User.Identity.Name)));
}
Thanks in advance for any insight.
Steve
A: Saw a similar question on Teleriks forum.
I used OnDataBinding event as explained in this article:
On passing parameters to controller from AJAX binding call.
Works for me. Using Telerik extensions 2012 Q2.
A: Try specifying .RouteKey("someName") for each dataKey that you want(need) to get automatically on controller, "someName" should be same with action parameter name.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Destroy a record before it's saved in rails 3 In my model I have specified a before_save method to run, and check the new record against some data. If the new record isn't what I want - how can I stop it from being saved?
Here is essentially what I'm trying to do (and failing):
before_save :itemCheck
def itemCheck
if self.item_type_id == 1
if self.num > 6
self.destroy
end
end
end
NOTE: my code is more complicated than this - just making a simple example.
A: Return false from your before_save and the record won't be saved.
As a sidenote: don't use camelcase for functions, but use: item_check.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Repository pattern with foreign key relationships in EF I've constructed a database and used the Entity Framework to generate some domain model classes. Basically VideCollection is a collection of Videos and I'd like to display the each Video Collection along with it's Videos on some page. Following the repository pattern I've made a repository for the video collection. I can pull the VideoCollection objects from the database. The problem is I need to 'fix' the objects to add their corresponding videos. Is this the correct way of doing it? If so then I need to 'fix' the videos to bring in their comments etc etc causing a huge chain. I understand about LINQ deferred queries but this seems unnecessary to pull so much information out of the database. I'm using ASP.NET MVC3.
If anyone can point me in the right direction it would be much appreciated!
using System;
using System.Linq;
using VideoCart.Domain.Abstract;
using VideoCart.Domain.Entities;
namespace VideoCart.Domain.Concrete
{
public class EFVideoRepository : IVideoRepository
{
private readonly EFDbContext _context = new EFDbContext();
public IQueryable<VideoCollection> GetVideoCollections()
{
IQueryable<VideoCollection> videoCollections = _context.VideoCollections;
foreach (var videoCollection in videoCollections)
{
videoCollection.Videos = _context.Videos.Where(x => x.VideoCollectionId == videoCollection.Id);
}
return videoCollections;
}
}
}
A: I'm not sure if this is what you want, but, you can use the include method to specify the related objects you want to pull out and include with the query results.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is it necessary temporary variable when allocating ivar used only in that class? If ivar is used by other classes, I use @property (noatomic, retain) and @synthesize.
And I add it to the view like this. label is ivar.
UILabel *aLabel = [UILabel alloc] initWithFrame:frame];
self.label = aLabel;
[aLabel release];
[self.view addSubview:label];
But if it is not used by other classes, I do not use @property and @synthesize.
And I add it to the view like this.
label = [UILabel alloc] initWithFrame:frame];
[self.view addSubview:label];
Am I right?
A: Yes, but the last line of the first example should be
[self.view addSubview:self.label];
A: yes, don't forget the release in dealloc. properties are primarily necessary to allow access to values from outside your class. The are essentially methods, a getter and a setter that pass through the value. Retaining and copying properties additionally retain the value or make a copy of it. So often they are used to simplify your code if you need to retain something, because then you can simply set self.property = value and don't need to explicitly retain it and release the previous value.
A: You should use @property in both cases. The difference is that you should move the @property definition into a private extension if you don't want it public. For example, consider the following pubName and privName properties.
// MYObject.h -- Public Interface
@interface MYObject : NSObject
@property (nonatomic, readwrite, retain) NSString *pubName;
@end
// MYObject.m
@interface MYObject () // Private Interface
@property (nonatomic, readwrite, retain) NSString *privName;
@end
@implementation MYObject
@synthesize pubName=pubName_;
@synthesize privName=privName_;
- (void)dealloc {
[pubName_ release];
[privName_ release];
}
You should then always use accessors for all properties, whether they are public or private (except in init and dealloc). Doing this consistently is the best defense against memory management mistakes (leading to leaks and crashes).
A: label = [UILabel alloc] initWithFrame:frame];
[self.view addSubview:label];
That's possibly correct but dangerous. It's fine if the previous value of label was nil. If label had a different value before, then that's a memory leak, because you didn't release the object previously pointed to by label, but that object afterwards has one less reference, and possibly no references left.
Properties are useful for things like that even if they are not used by other classes. However they are not required.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Access a Div inside a Div (JQuery) I got a problem with accessing a Div's attribute inside another Div.
I'm using the JQuery Plugin QuickFlip and want to change the background image
of the back.
<div class="quickFlip">
<div class="blackPanel"> </div>
<div class="redPanel">
<p class="quickFlipCta">Click to Flip</p>
</div>
</div>
This is the structure of one of my panel. (I got more of them all with the same class name).
With this code I loaded one of the panels into the variable "div".
$(div).quickFlipper();
div = $(".quickFlip").get().sort(function(){
return Math.round(Math.random())-0.5;
}).slice(0,1);
Now I want to access the background image... I already tried this:
$(div).$('redPanel')({'background': 'url(tiles/' + images[Math.floor(Math.random() * images.length)] + ')'});
which was actually not working... ^^
I was able to change the background of the quickFlip class with this code but not the background of the redpanel...
Hope you guys can help me!
A: Don't be afraid to use more local variables.
var i = Math.floor(Math.random() * images.length),
bg = 'url(tiles/' + images[i] + ')';
$(div).find('div.redpanel').css('background-image', bg);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Snake Game Program - Making the Body of the Snake EDIT: (QUESTION ANSWERED)
So I have a Thread controlling x and y and making it change. My problem is that when the snakes body gets put up in the GUI it puts it directly on top of the head instead of 12 spaces behind it. I know why it's doing it but I am not sure how to fix this problem.
From what I understand, it's drawing the body and then the head but it's using the same x and y spaces...what really needs to happen is that it needs to draw the head, go through the Thread, then draw the body parts so that it does it a space behind the head (because the head will have moved forward)...so on and so forth... I just can't figure out how to do it.
Here is the Thread runner which i highly doubt you will really need but just to be sure
class ThreadRunnable extends Thread implements Runnable {
private boolean allDone = false;
private boolean RIGHT;
private boolean LEFT;
private boolean UP;
private boolean DOWN;
public ThreadRunnable (boolean up, boolean right, boolean down, boolean left){
UP = up;
RIGHT = right;
DOWN = down;
LEFT = left;
}
public void run() {
if(UP == true) {
try {
while(UP) {
if (y <= yBase && y >= 0) {
y = y - 12;
}
else {
y = yBase;
}
Thread.sleep(40);
repaint();
if (allDone) {
return;
}
}
}
catch (InterruptedException exception) {
}
finally {
}
}
if(RIGHT == true) {
try {
while(RIGHT) {
if (x <= xBase && x >= 0) {
x = x+12;
}
else {
x = 0;
}
Thread.sleep(40);
repaint();
if(allDone) {
return;
}
}
}
catch (InterruptedException exception) {
}
finally {
}
}
if(DOWN == true) {
try {
while(DOWN) {
if (y <= yBase && y >= 0) {
y = y+12;
}
else {
y = 0;
}
Thread.sleep(40);
repaint();
if (allDone) {
return;
}
}
}
catch (InterruptedException exception) {
}
finally {
}
}
if(LEFT == true) {
try {
while(LEFT) {
if (x <= xBase && x >= 0) {
x = x-12;
}
else {
x = xBase;
}
Thread.sleep(40);
repaint();
if (allDone) {
return;
}
}
}
catch (InterruptedException exception) {
}
finally {
}
}
}
}
Here is the "Drawing" part of the code
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBorder(BorderFactory.createLineBorder(Color.WHITE));
this.setBackground(Color.black);
if (numOfFood == 1) {
g.setColor(Color.BLUE);
g.fillRect(foodX,foodY,12,12); //Paints the food
}
else {
foodX = random.nextInt(105)*12; //Random x for food position after snake eats
foodY = random.nextInt(59)*12; //Random y for food position after snake eats
numOfFood = 1;
}
Rectangle headRect = new Rectangle( x, y, 12, 12 ); //The head (not painted)
Rectangle foodRect = new Rectangle(foodX, foodY, 12, 12); //The food (not painted)
if ( body.size() >= 0) {
body.add(new BodyPart( x, y, 12, 12));
body = new ArrayList<BodyPart>( body.subList( body.size() - n, body.size() ) );
g.setColor(Color.RED);
for ( int i = body.size() - 1; i >= body.size() - (n-1); i-- ) {
g.fillRect( body.get( i ).getX(), body.get( i ).getY(), body.get( i ).getWidth(), body.get( i ).getHeight() ); //This is calling a class that will get these parts of the array list (x,y,width,height)
}
}
g.setColor(Color.RED);
g.fillRect(x,y,12,12); //Draws head
g.setColor(Color.WHITE);
g.fillRect(x+2,y+2,8,8); //This is a white square in the middle of the head to show that it is the head
if (headRect.intersects(foodRect)) {
numOfFood = 0;
n++;
}
}
EDIT: QUESTION ANSWERED BELOW
All that was required was to move the
setBorder(BorderFactory.createLineBorder(Color.WHITE));
and the
this.setBackground(Color.black);
to an earlier part of the code and not in the drawing method there...
I also changed my ArrayList into a normal Array and just made it insert the head location into the beginning of the Array and then made it print the next time around (after the head had moved)
g.setColor(Color.RED);
//Prints the body parts
if (n > 0) {
for (int i = 0;i < n; ++i) {
g.fillRect(body[i][0],body[i][1],12,12);
}
}
//Inserts the head location
for (int i = n-1;i >= 0; --i) {
body[i+1][0] = body[i][0];
body[i+1][1] = body[i][1];
if (i == 0) {
body[i][0] = x;
body[i][1] = y;
}
}
Thank you so much for all the help
A: *
*Move the head forward one.
*Put a body segment where the head was.
*Erase the last body segment.
None of the other body segments need move.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Website and Service Sharing Bin Directory I have an ASP.NET Website and Windows Service that I'm installing with a Wix msi.
They have the exact same dll references. I'm trying to decide if we should just have the Windows Service share the Website's bin directory and get its assemblies from there.
My gut says this is a bad idea, since we'd be abusing the purpose of the bin directory...but on the other hand duplicating the assembly installation seems kind of silly and a potential versioning problem.
Same thing with the config file. We have a custom named OurApplicationName.config file (not a regular web.confg/exe.config). Should we just have both the Web App and Windows Service share the config file and have it sit in the web root? If not, it seems like this could introduce configuration problems where the site is pointing to different databases/servers than the Windows Service.
Advice?
A: I agree with your gut feeling - keep them seperate - there are also security considerations as typically a Windows Service will run with higher/different security permissions than the IIS AppPool account.
A: A single dll file could be a command line app, windows form, web site, and web service. I see no problem with that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Animation: specify speed, not time I have a draggable element $myElement with revert: true. Now specifying revertDuration will determine the time the reverting animation will take to complete.
My problem is that the speed of the animation will vary greatly depending on how far $myElement is dropped from the original location.
Is there a way of specifying the speed of the animation (as opposed to the total time)?
A: What you need is position plugin for jQuery UI found here: http://jqueryui.com/demos/position/
You can get offset of the draggable element. Or simply use:
var x = $myElement.offset().left
var y = $myElement.offset().top
Solution which comes to my mind:
Save position of the element when start event of draggable object is fired. Then do the same when 'stop' event occurs and animate the element back to starting offset. The difference in offsets is a line which its length will be proportional to the time required to travel back.
var x,y;
$myElement.draggable({
start: function(event, ui) {
x = $myElement.offset().left;
y = $myElement.offset().top;
},
stop: function(event, ui) {
// count the length of the line from starting point
// and trigger back animation
}
});
You can try to set revert duration when stop event is called to avoid animate but I don't know if it make it before revert animation.
$( ".selector" ).draggable( "option", "revertDuration", 1000 );
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: href attribute of not being set In my application, I send an AJAX request to a server, and based on some data, I have to change the href attribute of element. Here's my code:
$('#unclaimed_codes_list li').map(function(){
$(this).children("a:first").text(fname + ' ' + lname + '(' + key + ')');
}
$.get('/accs/get_val/' + key, function(data){
var edit_href = '/ak_access_levels/' + id + '/edit';
alert(edit_href);
$(this).children("a:first").attr('href', 'edit_href');
});
But its not working. I can see that my edit_href value is correct, but still, the href attribute is not being set. Am I missing something? Thanks.
A: Replace the second occurence of $(this).children('a:first') by $('#unclaimed_codes_list li a:first'). Secondly, change 'edit_href' to edit_href.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Handle time of received interrupt in windows I have an external controller with only one button connected to PC with RS232.
Operating in Windows, I want to know the time of hardware interrupt being received.
Time of control being received by user application process is incorrect here.
I want to know the way of redefining the primary ISR (like asm "int 14h") in Windows?
Or maybe there is also a way how to this already catched time in user application (so no redefinition is required)?
A: int 14H is right for actually handling the UART on COM1 or COM2: see here. But setting up an ISR is a different matter and for that I would look around for a BIOS listing. It might be hard to find, but I don't believe there's any way around it. Try googling "pc BIOS listing"; you might get lucky.
There is a way to chain ISRs together so that you don't put too much hurt on the Windows driver.
Oh, here you go. Google "pc interrupt service routine" to find a whole bunch of references.
And, hey! Good luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: rails -double negative of variable * warning - newbie alert *
I'm reading a book called RailsSpace to learn Ruby on Rails framework. The author built user profiles which the user can edit, and now he's building the public facing profiles based off the other user profiles. The only change he has to make is to basically hide the edit links on the public facing profile. He uses this function to hide it, but I don't understand how it works...hide_edit_links is a variable
# Return true if hiding the edit links for spec, FAQ, etc.
def hide_edit_links?
not @hide_edit_links.nil?
end
He also writes
By the way, the reason hide_edit_links? works in general is that
instance variables are nil if not defined, so the function returns
false unless @hide_edit_links is set explicitly.
but I don't really get it.
Can you explain in a bit more detail for a newbie?
He implements it later with this
<div class="sidebar_box"> <h2>
<% unless hide_edit_links? %> <span class="edit_link">
<%= link_to "(edit)", :controller => "faq", :action => "edit" %> </span>
<% end %>
A: I think the key to understand that code (I haven't read the book) is that @hide_edit_links is not a boolean, it's just some kind of tag. If @hide_edit_links is not nil ( it doesn't matter which object type it's) then hide_edit_links?` will return true.
I have to say that the code is not at all straight forward, it's definitely convoluted and complicated (probably without any reason)
Example 1 (New instance, without @hide_edit_links set, so it shows link).
*
*The class is instantiated (this code is not in the original question, but I assume it's there), and since there's not reference to @hide_edit_links, the value of the instace variable is nil
*When hide_edit_links? is invoked from the page, @hide_edit_links is nil, so @hide_edit_links.nil? returns true, and thus not @hide_edit_links.nil? is false.
*Since the page uses unless hide_edit_links?, it shows the link.
Example 2 (New instance, with @hide_edit_links set with an object, so it doesn't show the link).
*
*The class is instantiated and @hide_edit_links is set to a value which is not nil.
*When hide_edit_links? is invoked from the page, @hide_edit_links is not nil, so @hide_edit_links.nil? returns false, and thus not @hide_edit_links.nil? is true.
*Since the page uses unless hide_edit_links?, it doesn't show the link.
Sorry about the trivial examples... the 'feature' is not complicated, but the solution used by the author looks terribly complicated to my dumb brain.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Self hosted WCF Service not working when i type url in browser? I'm new to wcf. I have Made simple self hosted service and added app.config but when I type address in the browser it is not showing me the service page that we get when we create our service http://localhost:8067/WCFService it is not displaying the service as it shows when we run service. But when i try to add base service in public static void main instead of app.config it works fine I'm not getting?? Can anyone please help me?
Following is the app.config file manually added:
<configuration>
<system.serviceModel>
<services>
<service name="SelfHostedWCFService.WCFService">
<endpoint
address="http://localhost:8067/WCFService"
binding="wsHttpBinding"
contract="SelfHostedWCFService.IWCFService">
</endpoint>
</service>
</services>
</system.serviceModel>
</configuration>
Following is the Program.cs:
static void Main(string[] args)
{
ServiceHost host = new ServiceHost(typeof(SelfHostedWCFService.WCFService));
host.Open();
Console.WriteLine("Server is Running...............");
Console.ReadLine();
}
Following is the Interface file Manually added:
namespace SelfHostedWCFService
{
[ServiceContract]
interface IWCFService
{
[OperationContract]
int Add(int a,int b);
[OperationContract]
int Sub(int a,int b);
[OperationContract]
int Mul(int a, int b);
}
}
Following is the Service cs file Manually added:
namespace SelfHostedWCFService
{
class WCFService : IWCFService
{
public int Add(int a, int b)
{
return (a + b);
}
public int Sub(int a, int b)
{
return (a-b);
}
public int Mul(int a, int b)
{
return (a*b);
}
}
}
Is something wrong with my app.config or some other concept??
A: You will need to add the meta endpoint to the self hosted service as well...
ServiceMetadataBehavior meta = new ServiceMetadataBehavior();
meta.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
_host.Description.Behaviors.Add(meta);
_host.AddServiceEndpoint(
ServiceMetadataBehavior.MexContractName,
MetadataExchangeBindings.CreateMexHttpBinding(),
"http://localhost:8067/WCFService/mex"
);
A: You should try to import System.ServiceModel.Web to your Interface project, and add [WebGet] attribute for your OperationContract(s)
The interface would look as below:
using System.ServiceModel.Web;
namespace SelfHostedWCFService
{
[ServiceContract]
interface IWCFService
{
[OperationContract]
[WebGet]
int Add(int a,int b);
[OperationContract]
[WebGet]
int Sub(int a,int b);
[OperationContract]
[WebGet]
int Mul(int a, int b);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7541685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.