text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Best way to build a multiple filter in rails I want to build dynamics filters with rails for one of my model but i don't know the best way to do that.
My model is en Event witch has a Continent, a Country and a Month.
So i want to be able to find an event with several filters. For example, "Found all events in Europe for the Month of Febrary"
What is the best way to do that. I have to make a function findByfilter in my Event model?
Thank you for answer, example are welcome!
(I use rails 3)
A: I'm guessing what you're looking for is a little beyond just using scope to create filters:
i.e.
class Event < ActiveRecord::Base
scope :by_continent, lambda {|continent| where(:continent => continent)}
scope :by_country, lambda {|country| where(:country => country)}
...
end
and then doing Event.by_continent('NA').by_country('Canada')
If you're looking to build a more formal search model with a mechanism to to_s and describe your search, I'd probably start with something like Railscast 111. He builds an advanced search model, which basically lets you set fields then filter down based on what's set.
From that, you could implement your own to_s method (or another name if you prefer) that would take a look at which search attributes have been set, and build a nice string to describe it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Why are there no Makefiles for automation in Python projects? As a long time Python programmer, I wonder, if a central aspect of Python culture eluded me a long time: What do we do instead of Makefiles?
Most ruby-projects I've seen (not just rails) use Rake, shortly after node.js became popular, there was cake. In many other (compiled and non-compiled) languages there are classic Make files.
But in Python, no one seems to need such infrastructure. I randomly picked Python projects on GitHub, and they had no automation, besides the installation, provided by setup.py.
What's the reason behind this?
Is there nothing to automate? Do most programmers prefer to run style checks, tests, etc. manually?
Some examples:
*
*dependencies sets up a virtualenv and installs the dependencies
*check calls the pep8 and pylint commandlinetools.
*the test task depends on dependencies enables the virtualenv, starts selenium-server for the integration tests, and calls nosetest
*the coffeescript task compiles all coffeescripts to minified javascript
*the runserver task depends on dependencies and coffeescript
*the deploy task depends on check and test and deploys the project.
*the docs task calls sphinx with the appropiate arguments
Some of them are just one or two-liners, but IMHO, they add up. Due to the Makefile, I don't have to remember them.
To clarify: I'm not looking for a Python equivalent for Rake. I'm glad with paver. I'm looking for the reasons.
A: There is a number of options for automation in Python. I don't think there is a culture against automation, there is just not one dominant way of doing it. The common denominator is distutils.
The one which is closed to your description is buildout. This is mostly used in the Zope/Plone world.
I myself use a combination of the following: Distribute, pip and Fabric. I am mostly developing using Django that has manage.py for automation commands.
It is also being actively worked on in Python 3.3
A: Any decent test tool has a way of running the entire suite in a single command, and nothing is stopping you from using rake, make, or anything else, really.
There is little reason to invent a new way of doing things when existing methods work perfectly well - why re-invent something just because YOU didn't invent it? (NIH).
A: The make utility is an optimization tool which reduces the time spent building a software image. The reduction in time is obtained when all of the intermediate materials from a previous build are still available, and only a small change has been made to the inputs (such as source code). In this situation, make is able to perform an "incremental build": rebuild only a subset of the intermediate pieces that are impacted by the change to the inputs.
When a complete build takes place, all that make effectively does is to execute a set of scripting steps. These same steps could just be deposited into a flat script. The -n option of make will in fact print these steps, which makes this possible.
A Makefile isn't "automation"; it's "automation with a view toward optimized incremental rebuilds." Anything scripted with any scripting tool is automation.
So, why would Python project eschew tools like make? Probably because Python projects don't struggle with long build times that they are eager to optimize. And, also, the compilation of a .py to a .pyc file does not have the same web of dependencies like a .c to a .o.
A C source file can #include hundreds of dependent files; a one-character change in any one of these files can mean that the source file must be recompiled. A properly written Makefile will detect when that is or is not the case.
A big C or C++ project without an incremental build system would mean that a developer has to wait hours for an executable image to pop out for testing. Fast, incremental builds are essential.
In the case of Python, probably all you have to worry about is when a .py file is newer than its corresponding .pyc, which can be handled by simple scripting: loop over all the files, and recompile anything newer than its byte code. Moreover, compilation is optional in the first place!
So the reason Python projects tend not to use make is that their need to perform incremental rebuild optimization is low, and they use other tools for automation; tools that are more familiar to Python programmers, like Python itself.
A: Actually, automation is useful to Python developers too!
Invoke is probably the closest tool to what you have in mind, for automation of common repetitive Python tasks: https://github.com/pyinvoke/invoke
With invoke, you can create a tasks.py like this one (borrowed from the invoke docs)
from invoke import run, task
@task
def clean(docs=False, bytecode=False, extra=''):
patterns = ['build']
if docs:
patterns.append('docs/_build')
if bytecode:
patterns.append('**/*.pyc')
if extra:
patterns.append(extra)
for pattern in patterns:
run("rm -rf %s" % pattern)
@task
def build(docs=False):
run("python setup.py build")
if docs:
run("sphinx-build docs docs/_build")
You can then run the tasks at the command line, for example:
$ invoke clean
$ invoke build --docs
Another option is to simply use a Makefile. For example, a Python project's Makefile could look like this:
docs:
$(MAKE) -C docs clean
$(MAKE) -C docs html
open docs/_build/html/index.html
release: clean
python setup.py sdist upload
sdist: clean
python setup.py sdist
ls -l dist
A: Setuptools can automate a lot of things, and for things that aren't built-in, it's easily extensible.
*
*To run unittests, you can use the setup.py test command after having added a test_suite argument to the setup() call. (documentation)
*Dependencies (even if not available on PyPI) can be handled by adding a install_requires/extras_require/dependency_links argument to the setup() call. (documentation)
*To create a .deb package, you can use the stdeb module.
*For everything else, you can add custom setup.py commands.
But I agree with S.Lott, most of the tasks you'd wish to automate (except dependencies handling maybe, it's the only one I find really useful) are tasks you don't run everyday, so there wouldn't be any real productivity improvement by automating them.
A: The original PEP where this was raised can be found here. Distutils has become the standard method for distributing and installing Python modules.
Why? It just happens that python is a wonderful language to perform the installation of Python modules with.
A: Here are few examples of makefile usage with python:
https://blog.horejsek.com/makefile-with-python/
https://krzysztofzuraw.com/blog/2016/makefiles-in-python-projects.html
I think that a most of people is not aware "makefile for python" case. It could be useful, but "sexiness ratio" is too small to propagate rapidly (just my PPOV).
A:
Is there nothing to automate?
Not really. All but two of the examples are one-line commands.
tl;dr Very little of this is really interesting or complex. Very little of this seems to benefit from "automation".
Due to documentation, I don't have to remember the commands to do this.
Do most programmers prefer to run stylechecks, tests, etc. manually?
Yes.
generation documentation,
the docs task calls sphinx with the appropiate arguments
It's one line of code. Automation doesn't help much.
sphinx-build -b html source build/html. That's a script. Written in Python.
We do this rarely. A few times a week. After "significant" changes.
running stylechecks (Pylint, Pyflakes and the pep8-cmdtool).
check calls the pep8 and pylint commandlinetools
We don't do this. We use unit testing instead of pylint.
You could automate that three-step process.
But I can see how SCons or make might help someone here.
tests
There might be space for "automation" here. It's two lines: the non-Django unit tests (python test/main.py) and the Django tests. (manage.py test). Automation could be applied to run both lines.
We do this dozens of times each day. We never knew we needed "automation".
dependecies sets up a virtualenv and installs the dependencies
Done so rarely that a simple list of steps is all that we've ever needed. We track our dependencies very, very carefully, so there are never any surprises.
We don't do this.
the test task depends on dependencies enables the virtualenv, starts selenium-server for the integration tests, and calls nosetest
The start server & run nosetest as a two-step "automation" makes some sense. It saves you from entering the two shell commands to run both steps.
the coffeescript task compiles all coffeescripts to minified javascript
This is something that's very rare for us. I suppose it's a good example of something to be automated. Automating the one-line script could be helpful.
I can see how SCons or make might help someone here.
the runserver task depends on dependencies and coffeescript
Except. The dependencies change so rarely, that this seems like overkill. I supposed it can be a good idea of you're not tracking dependencies well in the first place.
the deploy task depends on check and test and deploys the project.
It's an svn co and python setup.py install on the server, followed by a bunch of customer-specific copies from the subversion area to the customer /www area. That's a script. Written in Python.
It's not a general make or SCons kind of thing. It has only one actor (a sysadmin) and one use case. We wouldn't ever mingle deployment with other development, QA or test tasks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
}
|
Q: Connection from MySQL to remote DB - possible? is it possible to create a connection from a MySQL DB to a remote database (probably Oracle) using something like an ODBC/JDBC connector? I need to create a trigger on the MySQL side that performs an insert/update on a table in the remote DB.
Can MySQL act as a client in this way?
Thanks
Craig
A: I am certain that you can connect to MySql from Oracle, not that I have done it myself, but I am not sure if it can be done the other way round.
If a connection from Oracle to MySql can solve your problem then have a search for 'Oracle Database Heterogeneous Connectivity'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Safety concerns about short circuit evaluation
Possible Duplicate:
Is short-circuiting boolean operators mandated in C/C++? And evaluation order?
AFAIK Short circuit evaluation means that a boolean expression is evaluated only up to the point that we can guarantee its outcome.
This is a common idiom in perl where we can write things like:
(is_ok() returns non-zero value on "OK")
is_ok() || die "It's not OK!!\n";
instead of
if ( ! is_ok() ) {
die "It's not OK!!\n";
}
This only works because the order of evaluation is always left-to right and that guarantees that the rightmost statement is only executed if the first statement if not "false".
In C I can do something simillar like:
struct foo {
int some_flag;
} *ptr = 0;
/* do some work that may change value of ptr */
if ( 0!=ptr && ptr->some_flag ) {
/* do something */
}
Is it safe to use this kind of idiom?
Or is there any chance that the compiler may generate code that evaluates ptr->some_flag before making sure that ptr is not a zero pointer? (I am assuming that if it is non-null it points to some valid memory region).
This syntax is convenient to use because it saves typing without losing readability (in my opinion anyway). However I'm not sure if it is entirely safe which is why I'd like to learn more on this.
NB: If the compiler has an effect on this, I'm using gcc 4.x
A: The evaluation order of short-circuit operators (|| and &&) is guaranteed by the standard to be left to right (otherwise they would lose part of their usefulness).
§6.5.13 ¶4
Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation;
there is a sequence point after the evaluation of the first operand. If the first operand
compares equal to 0, the second operand is not evaluated.
§6.5.14 ¶4
Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; there is
a sequence point after the evaluation of the first operand. If the first operand compares
unequal to 0, the second operand is not evaluated.
A:
Or is there any chance that the compiler may generate code that
evaluates ptr->some_flag before making sure that ptr is not a zero
pointer?
No, zero-chance. It is guaranteed by the standard that ptr->some_flag will not be evaluated if the first operand is false.
6.5.13-4
Unlike the bitwise binary & operator,the && operator guarantees
left-to-right evaluation; there is a sequence point after the
evaluation of the first operand. If the first operand compares equal to
0, the second operand is not evaluated.
A:
/* do some work that may change value of ptr */
if ( 0!=ptr && ptr->some_flag ) {
/* do something */
}
Is it safe to use this kind of idiom?
Yes.
A: It is safe in the above example, however anyone maintaining such code may not realise that there is a dependency on the order of evaluation and cause an interesting bug.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Set selected item in ComboBox by Code I want to selected the first item of a comboBox by code if the value list have only one item. I've tried this:
Comboitem item = new Comboitem();
for(Empresa e : empresasList){
item.setValue(e.getEmpId());
item.setLabel(e.getEmpNombre());
item.setParent(cb_empresa);
}
if(empresasList.size()==1){
idEmpresa = empresasList.get(0).getEmpId();
//cb_empresa.setSelectedIndex(0);
cb_empresa.setSelectedItem(item);
}
But it does not work. I also tried the commented line:
//cb_empresa.setSelectedIndex(0);
Any help?
Thanks!
A: I don't know whether the item.setParent(cb_empresa); has an immediately effect to the view.
You can try setting the index later, or after refresh the cb_empresa.
A: First of all, your code is buggy. you have to create as many Comboitems as empresasList.size(). I guess something like
for(Empresa e : empresasList){
Comboitem item = new Comboitem();
item.setValue(e.getEmpId());
item.setLabel(e.getEmpNombre());
cb_empresa.appendItem(item);
}
if(cb_empresa.getItemCount()==1){
cb_empresa.setSelectedIndex(0);
}
Should work. However, there was a bug in ZK that the setSelectedIndex() had to be postponed, as Aloong mentioned. As far as I remember, this bug has been fixed. If not, you can use Event.echoEvent() as a workaround.
A: for(Empresa e : empresasList){
Comboitem item = new Comboitem();
item.setValue(e.getEmpId());
item.setLabel(e.getEmpNombre());
cb_empresa.appendChild(item);
}
if(cb_empresa.getItemCount()==1){
cb_empresa.setSelectedIndex(0);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Logging in Http Module We have created an http module to mobile detection and redirection. What the http module will do is according to the coming request it will find the device and redirect accordingly.
So here we want to log the methods in the http module. But i don't know whether it is a good practice to log all the requests? We planned to use text file logging. We have concerns about the performance since it will log all requests.
Please give your suggestions.
A: Depending on what information you want to log, all request are logged in iis. You can these log at %SystemDrive%\inetpub\logs\LogFiles. If the information is not there you can add extra information or add extra logging in the global asax. Good loggers will have minimal impact on you application. You should watch you diskspace at all time, and make a business case on what you want to do with the information.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I use ALAssetsLibrary in unit test? I wonder how I can use ALAssetsLibrary in my unit test in Xcode 4?
Right now I get "Data unavailable" when calling ALAssetsLibrary.
A: Plug in a phone and run the test target on the phone. Doing so is the same as running your app on the phone, but instead of the normal app target, run your test target.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Set frame position on application launched in shared workspace Mac OSX I am opening the system preferences application from within my application. I also would like to set the the applications frame so it is aligned at the left side of my application. The problem is that I do not know how to access the applications frame property, or launch it at a specific point.
I am using NSWorkspace to launch it, then get an instance of NSRunningApplication which I hope can be used to manipulate the window.
-(void)openPreferencesAndSetFrame;
{
@try {
BOOL success = [[NSWorkspace sharedWorkspace] openFile:@"/System/Library/PreferencePanes/Localization.prefPane"];
if (success == YES)
{
NSArray *appArray = [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.systempreferences"];
if ([appArray count] > 0)
{
NSRunningApplication *sysPrefApp = [appArray objectAtIndex:0];
//set frame here
}
}
} @catch (NSException *exception) {
NSLog(@"%@", [exception description]);
}
}
A: After some research, try and error I found the solution. As mentioned AppleScript is able to do the job.
-(void)openPreferencesAndSetFrame;
{
@try {
NSAppleEventDescriptor *theResult;
NSDictionary *errorInfo;
float posX = 100;
float posY = 200;
NSString *sourceStr = [NSString stringWithFormat:@"ignoring application responses\r\n tell application \"System Preferences\"\r\n activate\r\n end tell\r\n tell application \"System Events\"\r\n tell process \"System Preferences\"\r\n set position of window 1 to {%f, %f}\r\n end tell\r\n end tell\r\n end ignoring\r\n", posX, posY];
NSAppleScript *theScript = [[NSAppleScript alloc] initWithSource:sourceStr];
theResult = [theScript executeAndReturnError:&errorInfo];
if (nil == theResult ) {
NSString *err = [NSString stringWithFormat:
@"Error %@ occured call: %@",
[errorInfo objectForKey:NSAppleScriptErrorNumber],
[errorInfo objectForKey:NSAppleScriptErrorBriefMessage]];
NSRunAlertPanel(@"AttachAScript Error", err, @"ok", nil, nil);
}
} @catch (NSException *exception) {
NSLog(@"%@", [exception description]);
}
}
A: Applications don’t have a frame property. If you want to set the frame of the main window you should be able to do that using AppleScript, either via NSAppleScript or the scripting bridge.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Socket buffer size dynamic I develop a speed test software with a graph. Each seconds, i draw the throughput on the graph. I use socket with a loop on socket.read(...)
The problem is the buffer size. If i set the buffer to 32ko, when the speed is low, my graph is wrong (block on read function until the buffer isn't full). If i set the buffer to 512 octets, the speed is "flanged".
How to set dynamically the buffer size ?
A:
block on read function until the buffer isn't full
I don't know what that means. Socket reads don't attempt to fill the buffer, they wait until some data arrives and then move that into the buffer, whatever its length, up to the size of the buffer. The size of the buffer should have no effect when speeds are low. It will take effect when speeds are high.
A: You can resize recv (and send) buffers like so:
int oldsize = sock.getReceiveBufferSize();
sock.setReceiveBufferSize(oldsize * 2);
..although its not a great idea. Resizing the buffer 'on the fly' like this causes at least one massive array to array data copy to happen internal to the socket, which is a massive performance loss. Additionally, sockets have an OS restriction on their max buffer size.
If you are blocking on a read() call, then I guess you are using regular IO, not NIO. I recommend using a preallocated, fixed size intermediate buffer and loop for moving data off the socket:
/* Init socket here... */
Socket sock = new Socket(...);
/* Set time out to next to nothing. */
sock.setSoTimeout(1);
/* Setup Streams */
InputStream is = sock.getInputStream();
/* Pick a buffer size, any reasonable size will do: 1k,2k,4k... */
byte[] buf = new byte[1024 * 2];
int lastRead = 0;
do {
try {
lastRead = 0;
lastRead = is.read(buf);
} catch (SocketTimeoutException ste) {
/* Do something, or not. Your call! */
}
/*do something with 'buf' here */
} while (lastRead > 0);
By setting a low read timeout, e.g. 1ms, your read() call will not block (for very long) and you will still be able to detect whether there is data available or not. Since this potentially uses an Exception process a 'normal' condition, this really borders on abuse of java.io.
A: One possibility is to pick a smallish buffer size, and Kalman filter the observations before plotting them.
The filter is very easy to implement, but requires calibration. For this application, I'd tune the parameters by hand until the level of smoothness of the resulting graph is pleasing to the eye.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: CQRS and service bus CQRS is about separating commands and queries. We can add it easily using several patterns & technologies like Event Sourcing, DDD, NoSQL, etc... but is ServiceBus mandatory?
A: No serviceBus is not mandatory, it's simply one of the technologies that be used to implement CQRS, for example Event Pub/Sub. If anything, Event Sourcing & DDD have a closer relationship to CQRS than ServiceBus.
A: I'd say messaging and a service bus is optional.
CQRS simply means decomposing your application so that the Read and Write parts of your application can be optimized for the respective concern. Commands can be handled directy, even Events, if you decide to use them, can be dispatched synchronously.
A good reference for using an internal dispatcher is Greg Young's simple examle.
Update: Rob Ashton has just posted a very good article on what CQRS is and how not to make it more complicated than it actually is.
A: No. You can use CQRS without service bus. In your case you only need the command dispatcher and the query dispatcher
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: loop in javascript function DC() {
var elements = $(".panel");
elements.first().fadeOut(1000, function() {
$(this).insertAfter(elements.last());
$(this).fadeIn(1000);
});
}
$(document).ready(function() {
var i =0;
for (var i=0; i < 10; i++) {
DC();
};
});
I want DC() to loop 10 times, but it only looped once.
What did I do wrong?
A: DC starts a fadeOut 10 times in a row. If you want your elements to fade out and back in 10 times then you should call DC as fadeIn's callback.
elements.first().fadeOut(1000, function() {
$(this).insertAfter(elements.last());
$(this).fadeIn(1000, DC);
});
A: mpartel is correct in that you may want to call DC as a callback - but in order to ensure it doesn't run forever, you'll need to check against a count:
var count = 0;
function DC() {
elements.first().fadeOut(1000, function() {
if(count >= 10) return;
count++;
$(this).insertAfter(elements.last());
$(this).fadeIn(1000, DC);
});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: cursor position issue in activity I have created one activity i.e loginpage. it contains some edit textboxes, when I run the application the cursor is defaultly going to last edit text field. My requirement is cursor should be defaultly in first edit text field.
A: EditText yourEdittext1=(EditText)findview...();
EditText yourEdittext2=(EditText)findview...();
yourEdittext1.requestFocus();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ruby OCI8 DBI, how to check query generated after parameter binding? need to check for "in" queries While using Ruby-DBI I am facing issues with parameter binding for where "in" queries.
Two questions:
*
*How do I get sql generated after parameter binding?
*Does in parameter for sql work properly if using DBI and OCI8?
My code looks like this:
dbh = DBI.connect(setting[:tns], setting[:username], setting[:password])
#date and in_params are parameters to sql query.
#In the query they are seen as ? "Question marks"
sth = dbh.execute(File.read('import_values.sql'), date, in_params)
The query looks like this:
SELECT date, col1, col2
FROM TABLEX
WHERE date = ?
AND col1 not in ( ? )
Please help.
A: I re-factored code to not use "in".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Get the wallpaper file name for the currently displayed wallpaper in a theme in Windows 7? I am using JNA to call system libraries on Windows 7 and need a way to get the current wallpaper file name that is being displayed from a theme where it randomly changes the wallpaper at a set interval.
I have used the SPI_GETDESKWALLPAPER system call in user32 using SystemParametersInfo but it returns the following path for each and every wallpaper no matter which is selected:
C:\Users\<user name>\AppData\Roaming\Microsoft\Windows\Themes\TranscodedWallpaper.jpg
but the original wallpaper are in say C:\wallpapers
Is there any way to get the original wallpaper file name? This transcoded wallpaper file name is useless for me.
Thanks
A: There's a short script available here which does what you want it to do.
The file name of the source for the current wallpaper is stored in a registry variable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Jquery show hide single link menu-unable to hide on mouse out <html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".link").click(function(){
$(".myList").show();
$(".link1").click(function(){
$(".myList").hide();
});
});
});
</script>
</head>
<body>
<div class="myDiv"> <a href="#." class="link">Text</a>
<div class="mylist" style="display:none;"> <a href="#." class="link1">Text</a> <a href="#." class="link1">Text</a> <a href="#."class="link1">Text</a> </div>
</div>
</body>
</html>
I want to hide list panel on mouse out, currently I am able to hide it on clicking on any link but want it on mouse out too...
A: Just change the click event to mouseout ;-).
$(".link1").mouseout(function(){
$(".myList").hide()
}
A: $(".link").click(function(ev){
$(".myList").show();
ev.preventDefault();
});
$(".link1").mouseout(function(){
$(".myList").hide();
});
you had a typo too: mylist & myList
try this.
$(".link").click(function(ev){
$(".myList").show();
ev.preventDefault();
});
$(".myList").mouseleave(function(){
$(".myList").hide();
});
A: try using this instead http://jsfiddle.net/G28aH/3/
A: Try
$('.myList').mouseout(function() { $(this).hide(); });
A: If you don't use animation I think that it's better to use CSS :hover pseudo-class for this task. But if you want to use jQuery then use mouseout event. But in order to prevent dropdown from disappearing when moving over it you should bind event on .myDiv.
$('.myDiv').mouseout(function(){
$(".myList").hide()
})
Also you can try hoverIntent plugin which was perfect for my needs. It delays showing and hiding in order to prevent accidental dissapearing.
http://cherne.net/brian/resources/jquery.hoverIntent.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: FedEx 556 - No valid services available. when there should be Hi I'm trying to use the wsdl api to get shipping cost calculated for my website.
I'm using opencart and this module (http://www.opencart.com/index.php?route=extension/extension/info&extension_id=2055&filter_search=fedex&sort=e.date_modified&order=DESC).
On checkout I'm getting this error:
WARNING::556::There are no valid services available.
But I tried the same from and to address on the calculator on the fedex website and it gives me two services: International Priority and International Economy
This is the debug data I have:
Array
(
[WebAuthenticationDetail] => Array
(
[UserCredential] => Array
(
[Key] => REDACTED
[Password] => REDACTED
)
)
[ClientDetail] => Array
(
[AccountNumber] => REDACTED
[MeterNumber] => REDACTED
)
[TransactionDetail] => Array
(
[CustomerTransactionId] => *** Rate Request v9 using PHP ***
)
[Version] => Array
(
[ServiceId] => crs
[Major] => 9
[Intermediate] => 0
[Minor] => 0
)
[ReturnTransitAndCommit] => 1
[RequestedShipment] => Array
(
[DropoffType] => REQUEST_COURIER
[ShipTimestamp] => 2011-09-28T09:02:01+00:00
[PackagingType] => YOUR_PACKAGING
[TotalInsuredValue] => Array
(
[Amount] => 2000
[Currency] => EUR
)
[Shipper] => Array
(
[Address] => Array
(
[StreetLines] => Array
(
[0] =>
[1] =>
)
[City] => Ronchis
[StateOrProvinceCode] =>
[PostalCode] => 33050
[CountryCode] => IT
[Residential] => 1
)
)
[Recipient] => Array
(
[Address] => Array
(
[StreetLines] => Array
(
[0] =>
[1] =>
)
[City] => villach
[StateOrProvinceCode] =>
[PostalCode] => 9500
[CountryCode] => AT
[Residential] => 1
)
)
[ShippingChargesPayment] => Array
(
[PaymentType] => SENDER
[Payor] => Array
(
[AccountNumber] => 263150082
[CountryCode] => IT
)
)
[RateRequestTypes] => LIST
[PackageCount] => 1
[PackageDetailSpecified] => 1
[PackageDetail] => INDIVIDUAL_PACKAGES
[RequestedPackageLineItems] => Array
(
[0] => Array
(
[Weight] => Array
(
[Value] => 34
[Units] => KG
)
[Dimensions] => Array
(
[Length] => 48
[Width] => 53
[Height] => 122
[Units] => CM
)
)
)
)
)
----------
-- NUSOAP -- Array
(
[HighestSeverity] => WARNING
[Notifications] => Array
(
[Severity] => WARNING
[Source] => crs
[Code] => 556
[Message] => There are no valid services available.
[LocalizedMessage] => There are no valid services available.
)
[TransactionDetail] => Array
(
[CustomerTransactionId] => *** Rate Request v9 using PHP ***
)
[Version] => Array
(
[ServiceId] => crs
[Major] => 9
[Intermediate] => 0
[Minor] => 0
)
)
What should I do?
A: I was also having this issue .. but with Joomla, Virtuemart. Because the FedEx server is the same so may be my solution could help somebody else too..
Here are the main things what I fixed to fix this issue.
*
*Product's Weight should be less than the limit if you've set any as Maximum Weight.
*If you are using any packaging has more weight than FedEx's provided box i.e. 25KG BOX or 10KG box, then always use "Your Own packaging"
*it's true, do keep an eye on ZIP===States (i was testing and put wrong state with different zip) And this ZIP should be added in "Shop's Address" because this is considered as FROM and the destination address as well.
*Do note if products have added weights. LWH (Length, Width, Height).
Mine issue resolved after weeks of trouble! I wish somebody else could also resolve this issue if facing.
I was facing following error
"10 kg packaging box is **only** Available at FedEx World Service Center® locations!"
which was a big help to resolve the limitation i've set.
A: This issue happen when one of the bellow cases.
*
*Country given is not associated with FedEx account.
*Origin address is not real, Especially the post code.
*The given packagingType is available in your country.
A: I just ran into this error, and it turned out that the issue was an invalid postal code. Double check that you are specifying the "Shipper" information correctly.
Also, if that doesn't work give the FedEx customer support phone number a try. We would not have figured this issue out without their help.
A: You need to provide a ServiceType. One of these:
EUROPE_FIRST_INTERNATIONAL_PRIORITY
FEDEX_1_DAY_FREIGHT
FEDEX_2_DAY
FEDEX_2_DAY_AM
FEDEX_2_DAY_FREIGHT
FEDEX_3_DAY_FREIGHT
FEDEX_EXPRESS_SAVER
FEDEX_FIRST_FREIGHT
FEDEX_FREIGHT_ECONOMY
FEDEX_FREIGHT_PRIORITY
FEDEX_GROUND
FIRST_OVERNIGHT
GROUND_HOME_DELIVERY
INTERNATIONAL_ECONOMY
INTERNATIONAL_ECONOMY_FREIGHT
INTERNATIONAL_FIRST
INTERNATIONAL_PRIORITY
INTERNATIONAL_PRIORITY_FREIGHT
PRIORITY_OVERNIGHT
SMART_POST
STANDARD_OVERNIGHT
Use it in the same level as the DropoffType
A: Make sure that you have the Zip Code set to required.
You can do that in System -> Localization -> Countries.
It is not required by default in opencart, and the fedex shipping system will not work without it.
A: This issue can also be caused by requesting insurance in a country that doesn't support it, such as Canada.
A: I also ran into this problem and the solution was trimming extra spaces from the end of the address, city & postal code. After that, all was well again.
I don't know why FedEx's API all of a sudden stopped accepting the extra spaces, but who knows...
A: In my case, this was caused by trying to ship internationally from the US to Italy, and having specified a SignatureOptionDetail of NO_SIGNATURE_REQUIRED. Changing this to SERVICE_DEFAULT fixed it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to release the NSUrlConnection class object,NSMutableData class object? iam making one applciation.In that iam using the NSUrlconnection class.Below one is my code.
- (void)viewDidLoad {
[super viewDidLoad];
responsedata = [[NSMutableData data] retain];
NSString *url = [NSString stringWithFormat:@"https://www.google.com"];
NSURL *URL = [NSURL URLWithString:url];
NSURLRequest *request=[[NSURLRequest alloc]initWithURL:URL];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
[request release];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[responsedata setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responsedata appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
}
In this code when iam executing,it shows the memory leak at
responsedata = [[NSMutableData data] retain];
[[NSURLConnection alloc] initWithRequest:request delegate:self]; in viewDidLoad()
.SO please tell me where it released.
A: *
*You should save reference to your NSURLConnection :
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
*You should start it:
[connection start];
*And you should release it in didFailWithError or connectionDidFinishLoading.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Find and replace with incremental number at the end I have an xml file with multiple nodes:
<member>
<screen_name>User</screen_name>
<username>username</username>
</member>
What I want tis to find an replace User with User1,User2,User(n) and username with username1,username2, username(n)
Is that possible?
A: Apply this XSL template to your XML files (there are several command line tools that can do this)
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*" />
</xsl:copy>
</xsl:template>
<xsl:template match="screen_name/text() | username/text()">
<xsl:value-of select="concat(., count(preceding::member) + 1)" />
</xsl:template>
</xsl:stylesheet>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Get QueryString from inside a WebControl I have a page which contains a dynamic number of custom WebControls. What I want to do is get the containing page's query string via "Request.QueryString".
If I understand the problem correctly I need the containing page's HttpRequest object?
Is there a way to do this?
I probably should point out that I don't want to pass the QueryString from the containing page to the WebControl. I want to access the QueryString directly from the WebControl.
A: Consider the following link:
HttpContext.Current.Request.QueryString
A: You should be able to access the query string from a custom web user control (ascx) in the same way as you do from the page, i.e:
Request.QueryString...
From a custom control, you can either access it via:
Page.Request.QueryString
//or
HttpContext.Current.Request.QueryString
BTW: the last option (System.Web.HttpContext.Current...) also works from any non-web-control classes (e.g. business logic).
A: you can access the httpContext from anywhere using
HttpContext.Current
From there you can find the Request and the querystring
A: No need to to anything in particular, Request object is directly available also to webcontrols:
this.Request.QueryString
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: PhoneGap Facebook Plugin compilation error in Xcode 4 on my attempt to build a PhoneGap-based iOS app, I stumbled upon this problem. The app is using facebook connect plugin provided by phonegap team. I followed the instructions on the README, and encountered this compilation error on Xcode:
/../facebook-ios-sdk/src/FBRequest.m:183: error: 'SBJSON' undeclared (first use in this function)
/../facebook-ios-sdk/src/FBRequest.m:183: error: (Each undeclared identifier is reported only once
/../facebook-ios-sdk/src/FBRequest.m:183: error: for each function it appears in.)
/../facebook-ios-sdk/src/FBRequest.m:183: error: 'jsonParser' undeclared (first use in this function)
I am new to phonegap and Xcode/iOS development, so would appreciate any help on resolving this error. Thanks.
A: Found out the problem, turned out I was using updated (but not released) forked phonegap library, which the SBJSON class has been renamed to PG_SBJSON. Manually changed the SBJSON class to PG_SBJSON resolved the problem.
A: If you upgraded to PhoneGap 1.1.0 .. you need to degrade to PhoneGap
1.0.0 since the new version does not work correctly with the Facebook
Plugin.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Adding custom OnTextChange event handler on custom TextBox I currently have a custom text box, it implements majority of the base implementations a normal text box has, by doing something like:
public string Text
{
get { return customTextBox.Text; }
set { customTextBox.Text = value; }
}
I now want to implement a custom event handler to get a postback on text changed. I currently am doing the following is this correct if not then how should I go about this:
private static readonly object EventCustomTextChanged = new Object();
public event EventHandler TextChanged
{
add
{
Events.AddHandler(EventCustomTextChanged, value);
}
remove
{
Events.RemoveHandler(EventCustomTextChanged, value);
}
}
This implementation comes from: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.ontextchanged.aspx
Before someone says why don't you use the one thats already there, I will tell you it's not implented because this is a custom user control. I am trying to implement it.
Thanks in Advanced!
A: This is the way to do it:
public event EventHandler TextChanged
{
add { customTextBox.TextChanged += value; }
remove { customTextBox.TextChanged -= value; }
}
Assuming that customTextBox is the System.Web.UI.WebControls.TextBox control.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Get cookies in Webdriver how? There is a method in Webdriver Ruby bindings for getting the cookies:
(Array<Hash>) all_cookies
with the following description:
Returns:
* (Array<Hash>) — list of cookies
Could you please, provide an example of its usage.
Thanks!
A: Try this:
driver.manage.all_cookies
A: Here is nice blog on webdirver and cookies:
http://element34.ca/blog/webdriver-and-cookies
In case you are looking for solution to read cookies from multiple domains:
http://automationoverflow.blogspot.in/2013/07/getting-cookies-from-all-domains.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to make more than one listview respond for different onItemClickListener? I'm using 4list views with class extending Activity. I have to perform different list item click function. Can i use the following method code for it? So how to set a single onItemClickListener for multiple ListViews?
public void onItemClick(AdapterView<?> adapter, View view, int index, long id)
{
switch(view.getId())
{
case <listview1 Id> : //call method 1; break;
case <listview2 Id> : //call method 2; break;
case <listview3 Id> : //call method 3; break;
}
}
A: Set different adapters for different list views.
I take two list view for example. So take two adapter for these two. And setOnItemClick(context) will be like as below..
public void onItemClick(AdapterView<?> adv, View v, int arg2, long arg3) {
// TODO Auto-generated method stub
switch(adv.getId()) {
case R.id.ListView1:
Toast.makeText(this, "list1", Toast.LENGTH_LONG).show();
break;
case R.id.ListView2:
Toast.makeText(this, "list2", Toast.LENGTH_LONG).show();
break;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to differentiate onclick fun on multiple anchor tags with id in JQuery Could you please suggest me how to handle multiple anchor tags for click functionality?
My code is like :
<a id="test1" href="#" >test1</a>
<a id="test2" href="#" >test2</a>
My jQuery functionality is :
$('a').click(function(event) {
alert('click');
});
The jQuery click functionality works for all anchor tags, but I want to differentiate the jQuery functionality based on id attribute ..
A: Look at the id on this and make an if statement or a switch (switch is recommended):
$('a').click(function(event) {
switch(this.id) {
case 'test1':
alert('link with an id of test1!');
event.preventDefault();
break;
case 'test2':
alert('link with an id of test2!');
event.preventDefault();
break;
default:
//Default behavior
}
});
A: You want to do something different depending on the ID?
You could do something like
$('a').click(function(e){
var id = $(this).attr('id');
// switch depending on id
});
OR
$('#test1').click(function(e){ alert("you clicked test1"); });
$('#test2').click(function(e){ alert("you clicked test2"); });
But this wouldn't be very nice if you are then going to add multiple's to do the same thing.
A: You can get the id attribute.
$('a').click(function(event) {
alert($(this).attr('id')+' clicked!');
});
A: you can read the id of the element and depending on the id make your functions
$('a').click(function(event) {
if ($(this).attr("id") == 'test1')
{
alert('Test 1 was clicked');
}
else if ($(this).attr("id") == 'test2')
{
alert('Test 2 was clicked');
}
});
A: If you want to bind to an element based on id:
$('#test1').click(function(event) {
alert('test1 clicked');
});
A: This is my approach
$('a').click(
function()
{
switch($(this).attr('id'))
{
case 'test1':
// Do some work
break;
case 'test2':
// Do some work
break;
}
}
);
A: You can look at the id as suggested in the other answers but you can also attach data attributes on each tag with a custom data attribute (html5) or use the href, that can later be accessed from the onclick event (html5).
sample:
<a id="test1" data-my-custom-data="Insert" data-row-id="24" href="#" >test1</a>
<a id="test2" href="Insert" >test2</a>
$("a").click(function(event)
{
alert($(this).attr("data-my-custom-data"));
alert($(this).attr("data-row-id"));
alert($(this).attr("href"));
event.preventDefault(); // To avoid browsing to href...
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Issue with radio buttons while firing Validations Hi all i have my form with some controls as follows
2 Radio buttons 1 Text Box, 1 Required field validator and a button
I wrote my sample code in such a way that if one radio button is selected i will enable or disable the text box that i will have.
I am having a required field validator which was set for text box available. Now what i need is when the control was disabled i don't want to perform the validation for this is it possible to do
Sample code
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
TextBox1.Enabled = true;
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
TextBox1.Enabled = false;
}
My design
<form id="form1" runat="server">
<div>
<asp:RadioButton ID="RadioButton1" runat="server" AutoPostBack="True" GroupName="g"
OnCheckedChanged="RadioButton1_CheckedChanged" ValidationGroup="g1" />
<asp:RadioButton ID="RadioButton2" runat="server" AutoPostBack="True" GroupName="g"
OnCheckedChanged="RadioButton2_CheckedChanged" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
ErrorMessage="RequiredFieldValidator" ValidationGroup="g1"></asp:RequiredFieldValidator>
<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="g1" /></div>
</form>
Validation should apply only when the control was enabled
A: Validators have an Enabled property that you can use:
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
TextBox1.Enabled = RequiredFieldValidator1.Enabled = true;
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
TextBox1.Enabled = RequiredFieldValidator1.Enabled = false;
}
A: I got this and works well for me
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
TextBox1.Enabled = true;
Button1.CausesValidation = true;
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
Button1.CausesValidation = false;
TextBox1.Enabled = false;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: No child processes error ... again I have a process running (call it main proc if you will) doing something. At some point it forks a process say proc1 that does something else. At some other point proc1 decides it needs a child process to do some chores, let's call it proc2.
proc2 does it's business or runs in an infinite loop at which point proc1 sends a sigterm signal to its' child proc2. Anyway, either way, proc2 finishes cleanly. While proc2 is doing the necessary stuff proc1 is waiting for proc2 to finish. When waitpid() reports proc2 as finished proc1 sends itself sigterm and exits. At that moment the main process was doing a check with waitpid(pid, WNOHANG) in a loop. When proc1 finishes my waitpid from main process throws an error: *Error in atexit._run_exitfuncs: OSError: [Errno 10] No child processes* and Error in sys.exitfunc:OSError: [Errno 10] No child processes.
From what I learned reading around similar questions there is a problem in handling the SIGCHLD signal. If this is the problem than i am unclear as how to solve it.
At the moment I solved this by putting the waitpid() in the main process in a try except block. Are there other ways? any better ways?
If it helps I can add an example that I've been fiddling with replicating the errors.
Thank you in advance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Can I to run several projects in one solution for debugging in VS 2010 Ultimate? I have a solution consisting of several executable projects (formally speaking server and its clients). But start-up project is only one (server) but I need to debug and clients too. Now I start their (clients) from folder from shell explorer. Is there any solution for this?
A: Yes you have to set up your solution to start multiple solutions.
Right-Click on your solution and choose "Set StartUp Projects...".
Then in the Dialog check "Multiple startup projects" and choose the action of those you want to start to "Start" (with debuging) or "Start without debuging".
Click Ok - done.
Now just hit F5 and all your selected projects should fire up and run.
A: I'm not sure about running all the projects at the same time, but there are two things that spring to mind:
*
*Open Visual Studio twice. Run the server from one, and the client from the other, or
*Continue to run the client from the shell, but attach the debugger to the client. Just go to the Debug menu, and select 'Attach to Process'.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Changing how the attributes are presented in Wicket Datatable I'm developing a new application in Wicket and have run into a small problem.
I'm using a Wicket DataTable, but I want some of the attributes in the dable to be presented different from their "actual" values. For example, I have a Date that is presented as "2011-09-01 00:00", but I want it to be presented as "2011-09-01". How do I do that?
I don't really want to change to POJO or the Date object (maybe override something, somewhere?).
Thanks in advance!
Olle
A: You could create a custom IColumn implementation, that formats the value:
class FormatedPropertyColumn<T> extends PropertyColumn<T> {
private final Format format;
public FormatedPropertyColumn(IModel<String> displayModel, String sortProperty, String propertyExpression, Format format) {
super(displayModel, sortProperty, propertyExpression);
this.format = format;
}
public FormatedPropertyColumn(IModel<String> displayModel, String propertyExpression, Format format) {
super(displayModel, propertyExpression);
this.format = format;
}
@Override
protected IModel<?> createLabelModel(IModel<T> rowModel) {
final IModel<?> originalModel = super.createLabelModel(rowModel);
return new AbstractReadOnlyModel<String>() {
@Override
public String getObject() {
Object value = originalModel.getObject();
return (value != null) ? format.format(value) : null;
}
};
}
}
Then you pass the desired format when you instantiate it.
List<IColumn> columns = Arrays.asList(
new FormatedPropertyColumn<POJO>(Model.of("Date"), "date", new SimpleDateFormat("yyyy-MM-dd"))
);
A: By using a Converter configured in your application you will be able to format date the way you want for example.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Can you make animations multithreaded? How to improve animation performance I'm using the FluidKit Cube Animation in my WPF application.
The animation is smooth when the application window is not in full-screen, but when the application is running in full screen (maximised - borderless window with no controls), the animation is not smooth.
I noticed the WPF application is hammering a single thread and only utilising one of the four cores of the CPU, memory utilisatio is low.
I'm wondering if there is any way of making the window multithreaded or just the animations multithreaded so the application can utilise more of the available hardware?
Are there any other ways to improve animations?
Ben
A: I will be really excited if someone tells me a UI thread in WPF can leverage multi core CPUs....
Jokes apart, GPU and CPU are different concepts sadly. Will it be controversial if I say "The hardware acceleration mode for WPF apps utilizes GPU's own hyper threading model instead of multi core CPUs."?
Although there are ways to improve animations such as animating Adorners using PresentationSource, Transforming Drawings and Geometries than Shapes, CompositionTarget.Rendering event, BeginStoryBoard.HandoffBehavior="Compose" etc. You will find all of these discussed in details over the internet.
Interestingly there is an old (very useful post) about multi core systems and their impact on parallel .Net frameworks such as PLINQ and WPF 3.0 etc. http://social.msdn.microsoft.com/forums/en-US/wpf/thread/07562a10-17bd-44d3-975b-99ed02bd05de/
I hope this kicks off some very interesting brain storming from our very able StackOverflow experts....
Expectantly Waiting ... :-)
A: Try to avoid any effects and see how it works and totally avoid bitmap effects, because they force WPF to use software rendering which is not really good.
Suggest you to check out Performance Profiling Tools from Windows SDK. Good luck ;)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to overcome keyboard configuration in VMWare Player ? Sorry for asking a stupid question but I have a problem that makes me crazy. I am trying to install a program on my VMware Player, but while writing the password since it includes " # " character inside of the password I always get incorrect login error.
I am using an english keyboard and when I try to write " # " , i always get a different character from it.
Do you know how I can overcome this keyboard fault ?
Thanks a lot
A: Change keyboard settings on operating system running on virtual machine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I fetch first n rows from a TopLink query? For optimization purpose, I want to fetch first N results in a subquery (I'm getting first N ID values) and in the main query fetch full rows for the ID values in the subquery and order them. What I have now is
// This just adds params to the subquery
Expression managedEmp = generateExpression(p_upravljackaFilter);
ReportQuery subQuery = new ReportQuery(CustomDocument.class,
managedEmp);
subQuery.addAttribute("m_id");
Expression exp = new ExpressionBuilder().get("m_id").in(subQuery);
ReadAllQuery testQuery = new ReadAllQuery(CustomDocument.class,
exp);
testQuery.addAscendingOrdering("m_creationDate");
List documentList = (List)getTopLinkTemplate().executeQuery(testQuery, true);
What I'm trying so far is using a user defined function, like this:
ExpressionOperator fetchFirst = new ExpressionOperator();
fetchFirst.setSelector(1);
Vector s = new Vector();
s.addElement("FETCH FIRST 5 ROWS ONLY");
fetchFirst.printsAs(s);
fetchFirst.bePostfix();
fetchFirst.setNodeClass(FunctionExpression.class);
ExpressionOperator.initializeOperators();
ExpressionOperator.addOperator(fetchFirst);
expression = expression.and(builder.get("m_datumKreiranja").getFunction(fetchFirst);
This is literally where I stopped so this won't work but it can show you which way I'm heading. Is something like this even possible? I'm using Java 1.4 and toplink 10g.
A: Really simple, just insert into second line:
managedEmp = managedEmp.postfixSQL("FETCH FIRST 5 ROWS ONLY");
My mistake was in the fact that I tried it like this:
managedEmp.postfixSQL("FETCH FIRST 5 ROWS ONLY");
because I didn't read what postfixSQL does.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: java - vector has always the same results I read an .ini File and put every property into an temporary array which i put at the end into a vector - until here it works fine.
But if I want to access every array in that vector, I get ALWAYS the same results, which is impossible. I tried it with different ways, different loops and everything different, but always the same results, here is my actuall code:
tmp2 = new String[2];
for(Enumeration e=allPropertys.elements(); e.hasMoreElements();) {
tmp2 = (String[])e.nextElement();
for(int i = 0; i < tmp2.length; i++)
{
System.out.println(tmp2[i]);
}
}
And here is the code where I put everything into the vector:
try {
tmp = new String[2];
prop = new Properties();
prop.load(new FileReader("konfig.ini"));
Enumeration e = prop.propertyNames();
while (e.hasMoreElements()) {
String key = (String)e.nextElement();
String value = prop.getProperty( key );
tmp[0] = key + " " + value;
tmp[1] = value;
System.out.println("Property: " + tmp[0] + " und Value: " + tmp[1]);
allPropertys.add(tmp);
}
}
A: My guess is that when you populate your vector, you reuse the same string array for every property. This makes you vector contain 10 times (10 being the number of entries) the same array:
String[] property = new String[2];
for (every line in the file) {
property[0] = ...;
property[1] = ...;
vector.add(property);
}
This should be replaced by
for (every line in the file) {
String[] property = new String[2];
property[0] = ...;
property[1] = ...;
vector.add(property);
}
Also, note in your code snippet, you create a new String array to initialize your tmp2 variable, and then replace its value by the one in the vector. The initialization is unnecessary.
A: You are replacing the values inside the array and putting the very-same array into the collection once and again.
You must understand how objects and arrays work. You think that adding it to a collection copies it or something (that's why you initialize the array before the loop in the reading part, I think). It only adds the reference. You always work with references.
You must create a new array for each time you want to add it. Think of an array variable (or any object variable) as a reference to an object. As an arrow to the real thing. When you add it to the vector you are adding arrows to the same structure in memory (the same two buckets).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: EXC_BAD_ACCESS when calling cvThreshold Im getting EXC_BAD_ACCESS error when calling cvThreshold. Without that line (if I comment it), the image is displayed perfectly.
void CVWindow::processImage()
{
sourceImg = cvCreateImage(cvSize(640,480),8,1);
cvSetData(sourceImg, &m_img, sourceImg->widthStep);
cvThreshold(sourceImg, sourceImg, 100, 255, CV_THRESH_BINARY);
m_img = *sourceImg->imageData;
}
Any possible reasons? I have been searching for two days for a solution but cant find it.
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SSIS - VB Script Component to Convert Input to XML Im completely new to (VB) scripting, and am trying to find a way in an SSIS script component to convert 3 input columns into one XML structured output column.
Input:
ID NAME DATE
1 AAA 2011-01-01
2 BBB 2011-02-01
3 CCC 2011-03-01
Expected Output:
<output>
<row>
<id>1</id>
<name>AAA</name>
<date>2011-01-01</date>
</row>
<row>
<id>2</id>
<name>BBB</name>
<date>2011-02-01</date>
</row>
<row>
<id>3</id>
<name>CCC</name>
<date>2011-03-01</date>
</row>
</output>
The solution im looking for needs to be scalable, in that there can be x number of columns and the script just needs to iterate through each column and generate the name tag and value.
I have kind of got there by outputting each value into a generic "param" node, but am unsure how to get the column names.
Public Overrides Sub ProcessInput(ByVal InputID As Integer, ByVal Buffer As Microsoft.SqlServer.Dts.Pipeline.PipelineBuffer)
inputBuffer = Buffer
MyBase.ProcessInput(InputID, Buffer)
End Sub
Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)
Dim xml_string As String = ""
Dim counter As Integer
xml_string = "<output>"
For counter = 0 To inputBuffer.ColumnCount - 1
xml_string = xml_string + "<param>" + inputBuffer.Item(counter).ToString() + "</param>"
Next
xml_string = xml_string + "<output>"
Row.xmloutput = xml_string
End Sub
A: SQL code:
SELECT [ID]
,rtrim([Name]) [Name]
,[Date]
FROM [tempdb].[dbo].[Table1]
FOR XML PATH('row'), ROOT ('output')
I got this OutPut
<output>
<row>
<ID>1</ID>
<Name>AAA</Name>
<Date>2011-01-01</Date>
</row>
<row>
<ID>2</ID>
<Name>BBB</Name>
<Date>2011-02-01</Date>
</row>
<row>
<ID>3</ID>
<Name>CCC</Name>
<Date>2011-03-01</Date>
</row>
</output>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: replace images in data from webservice android Hi all,
How can i replace the text or symbol from web service with local images in drawable folder.
I get a symbol and text from web service. I need to replace that symbol with my image that is saved in local drawable folder in the application.
Please suggest few ideas of how can i do that.
Thanks in advance.
A: You cannot change or add any drawables inside your drawable folder. These resources are compiled into an .apk file, and there is no way to change them at runtime. Only solution I see is to store downloaded images on SD card and fetch them when you need it. Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ribbon menu in Android app I want to use ribbon menu(as on Microsoft Word 2007 or 10) in my android application. Anyone have any suggestions? If it impossible to implement, may be anyone have other ideas how to implement similar functionality? In Android development i am newbie, so i can not imagine how to modulate Ribbon menu with Activities(windows) and Android tools.
May be using of Ribbon menu in mobile Apps is not good idea, if so, what alternative i can use?
Ribbon menu need because application is very large, and it's have many tools and options.
Thanks!:)
A: There is no such thing as a built in ribbon menu in Android.
You could model it with a TabLayout (Android dev info on Tabs) that has a tab for each of the ribbon menu entries such as Home, Insert, ...
You can then show the different menus in the view displayed.
A: You can use TabLayout mixed + linear/relativelayout + using layout_weight properly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Dynamic Linq for dates I want to build dynamic Linq. Following is my code which works fine for one date. But user can select many dates from calendar. And I need to make Linq for all those selected dates.
saleDate = calendarSales.SelectedDate;
List<SaleDetails> saleDetials = new List<SaleDetails>();
saleDetials = GetSaleDetails();
saleDetials.Where(sale => (Convert.ToDateTime(sale.DATE_TIME).Day == saleDate.Day &&
Convert.ToDateTime(sale.DATE_TIME).Month == saleDate.Month &&
Convert.ToDateTime(sale.DATE_TIME).Year == saleDate.Year)
).ToList();
How to update this query?
A: You have to build the predicate for your where clause dynamically.
Take a look at the predicatebuilder.
EDIT
Of cause PredicateBuilder supports AND and OR operators.
When using OR you have to start with the initial value of False:
// building the predicate
var pred = PredicateBuilder.False<SaleDetails>();
foreach (var date in MyDateList)
{
pred = pred.Or(sale => sale.DATE_TIME.Date == saleDate.Date);
}
// finally get the data and filter it by our dynamic predicate
List<SaleDetails> saleDetails = GetSaleDetails().Where(pred).ToList();
A: I'm not sure you need dynamic LINQ here. You should be able to check Where the sale matches Any of the selected dates, like so:
var saleDates = GetSelectedDate();
List<SaleDetails> saleDetials = new List<SaleDetails>();
saleDetials = GetSaleDetails();
saleDetials.Where(sale => saleDates.Any(date =>
(Convert.ToDateTime(sale.DATE_TIME).Day == date.Day &&
Convert.ToDateTime(sale.DATE_TIME).Month == date.Month &&
Convert.ToDateTime(sale.DATE_TIME).Year == date.Year)
)).ToList();
or checking on the Date property:
var saleDates = GetSelectedDate();
List<SaleDetails> saleDetials = new List<SaleDetails>();
saleDetials = GetSaleDetails();
saleDetials.Where(sale => saleDates.Any(date =>
Convert.ToDateTime(sale.DATE_TIME).Date == date.Date)).ToList();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: IIS Restart (cannot start any process and call iisreset) from the website itself public static void RestartIIS()
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.System) + @"\iisreset.exe";
System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(path);
info.UseShellExecute = true;
System.Diagnostics.Process.Start(info);
}
A: You'll need to have administrative permissions to do this; running IIS as administrator is absolutely not recommended!
Rather, I'd suggest that instead of trying to administer the site from itself you work with one of the remote access / remote management tools. Something like the remote administration for IIS is basic but useable: http://learn.iis.net/page.aspx/158/remote-administration-for-iis-manager/.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ActiveX in HTML My requirement is to instantiate an object using new ActiveX() in html.
I have created a COM component SimpleActiveX using ATL. I have created the dll SimpleActiveX.dll for the same. In order to instantiate this component in html file I need to register the dll. So I registered the dll using the command regsvr32 %Path of dll%.
After doing so I am trying to create and instance of the component in html file as follows,
var req;
req = new ActiveX("SimpleActiveX.Hello"); //Assume Hello as a class.
req.Hi(); //Assume that Hi() is a member function of Hello.
By doing so I am unable to create the ActiveX object.
Html doesnt give any error too. I dont know whether I am doing anything wrong or am I missing anything.
Could anyone please tell me the proper steps to perform above operations.
How do I need to create the dll (Here in this case I have just build the ATL project in Visual Studio to generate the dll)?
What else do I need to do with the dll in case if I need to create an ActiveX object in html?
I had come across something called as <object> </object> tag in html where we mention the classid and attributes. I dont know whether I need to mention this in my html file or not.
Thanks for your help in advance.
A: To instantiate an ActiveX object in JavaScript, assuming the dll is correctly registered, you just have to use:
var req = new ActiveXObject("SimpleActiveX.Hello");
Unfortunately I don't know how to register a dll using Visual Studio.
Regarding the tag, it is used when you want to embed the object directly in your HTML code, so that it will be instantiated when the document loads, instead of using JavaScript.
For example:
<object id="myObject" classid="CLSID:2D360200-FFF5-11D1-8D03-00A0C959BC0A"></object>
Then you can access the COM object with
var myObject = document.getElementById("myObject").object
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Hibernate querying results format I have a web service that provides queries functionality using hibernate.
A query can return multiple results - each results contains multiple parameters.
The question is: how should I return the result:
*
*Can serialize everything into 1 string nd client will parse it.
*I know there is a possibility to return Array of strings or Array of complex types.
Which is better for performance - there might be lots of user doing request etc.
If better using the complex types - can give an example of using it - or a link to some info.
Thanks
Yoav
A: Web services generally return results in a platform-independent, but structured way. XML and JSON are two frequent choices.
There are plenty of apis in Java to generate XML and JSON. Google for them. I like using JAXB for XML. Some APIs take JAXB-annotated objects and serialize them into JSON instead of XML.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I save a MovieClip as an image in Actionscript 3? I have created a customized dress up avatar using flash. Now I have to do that a registered user can make his avatar. After user creates his/her avatar how can I save the customized avatar in a database?
A: Save image from Flash, send it to PHP and return a URL string to Flash:
Save image from Flash, send it to PHP and return a URL string to Flash
Send bitmap data from Flex to Php:
Send bitmap data from Flex to Php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get all network printers in asp.net 4.0 Please any one help me to get all network printers.
I get all printers installed in the local machine using "System.Drawing.Printing.PrinterSettings.InstalledPrinters".
But I can't get the printers which are in the Network.
I try with "ManagementObjectSearcher" but I can't access this class.
I think it does not support in framework 4.0.
I'm using ASP.NET 4.0, C#. Any help will be greatly appreciated.
Thanks
Singaravelu.R.
A: if you cannot find/reference the ManagementObjectSearcher Class probably is because you did not add the proper reference to: System.Management.dll to your C# project. Surely it is supported also by .NET 4.
as you can see in this question: ManagementObjectSearcher select network printers? you can find all network printers in this way:
var searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Printer");
var results = searcher.Get();
IList<ManagementBaseObject> printers = new List<ManagementBaseObject>();
foreach (var printer in results) {
if ((bool)printer["Network"]) {
printers.Add(printer);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Scala: Constraining a generic type parameter to a type within another parameter I'm still trying to grasp the Scala language, so please bear with me and all my questions.
Can I reference an abstract type from one type parameter in the bound for another? For instance, is there a way in which the following code can be made to work? The essence of what I'm trying to achieve here is that the KEY for the MAP parameter of C should be the SomeType of the parameter T.
trait T1 {
type SomeType;
}
trait MyMap[KEY, VALUE] { ... }
class C {
def m[T <: T1, MAP <: MyMap[T.SomeType, Int]] { ... }
}
A: You need type projection:
def m[T <: T1, MAP <: MyMap[T#SomeType, Int]]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Facebook Android SDK - There was a problem generating the Feed story from the provided data FB publishing for all my Android applications stopped working today saying - ""There was a problem generating the Feed story from the provided data"". They had been working fine for the last 6 months
All the applications did was publish quotes on users' walls. I use the following code to do this -
Bundle parameters = new Bundle();
parameters.putString("attachment", myAttachent);
facebookClient.dialog(this, "stream.publish", parameters, this);
The publishing worked fine till now. Any idea what could be wrong?
A: This is my working code........currently checked............
try {
JSONObject me = new JSONObject(mFacebook.request("me"));
fbname = me.getString("name");
first_name = me.getString("first_name");
System.out.println("Name :: " + fbname);
System.out.println("FName :: " + first_name);
JSONObject attachment = new JSONObject();
attachment.put("message", "Oil and Gas Navigator");
attachment.put("href", link);
attachment.put("description", "<B>" + title + "" + desc);
Bundle params = new Bundle();
params.putString("attachment", attachment.toString());
JSONObject actionLink = new JSONObject();
actionLink.put("text", "Link");
actionLink.put("href", link);
JSONArray jasonarray = new JSONArray().put(actionLink);
params.putString("action_links", jasonarray.toString());
mFacebook.dialog(mActivity, "stream.publish", params,
new SampleDialogListener());
} catch (Exception ex) {
ex.printStackTrace();
}
A: @ihurupin I can confirm this issue is affecting ios devices also. Code was working until ~ 24 hours ago (i was debugging specifically adding custom news feed). Now getting a nice "There was a problem generating the Feed story from the provided data"
bug filed with fb dev here fb dev bug tracking
A: This issue is now fixed. It appears to have been a problem with their API service. I have tested and asked my customers to confirm.
They have updated the bug status to "Fixed"
http://developers.facebook.com/bugs/295765603772094
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is the equivalent of Oracle’s REF CURSOR in MS-SQL when using JDBC? In Oracle I can declare a reference cursor.
but MS-SQL I don't know.
private Connection conn;
private CallableStatement stmt;
private OracleResultSet rset;
stmt = conn.prepareCall("{ ? = call " + call + "}");
stmt.registerOutParameter(1, <b>OracleTypes.CURSOR</b>);
stmt.execute();
rset = (OracleResultSet)stmt.getObject(1);
A: I'm not an expert on JDBC, but MSSQL doesn't have any direct equivalent of a REF CURSOR: result sets are returned directly from a procedure or query to the client. You don't mention which JDBC driver you're using, but if it's the Microsoft one then working with result sets is well documented.
If that doesn't help, please clarify which JDBC driver you're using and what code you've tried so far.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to block keyboard input selectively in Windows? How? My app (in C#) need to interface with a USB bar-code scanner, which is basically working like a keyboard. It inputs the bar-code with an enter key at the end.
The app need to be work even when it's at background, so I am using low level keyboard hook to get and filter the bar-code out in the global key events. This part is already working.
Here is my problem: I don't want other apps to get the keyboard(scanner) inputs if it is a bar-code. And the normal key events should not be interfered. In one word, block the key events selectively. Is this possible?
My app is in C#, but I have no problem with C++ or more native solutions as long as it's easy to integrate in C#.
Thanks.
Additional Information:
*
*The whole idea is working at background, even when it's not active. It watches the global key events stream and spot the bar-code sequence (already implemented with Hook). And most importantly, it do NOT interfere with normal keyboard events nor other applications' operation. That's why I cannot block all the key events or make it top-most.
*I already can get the bar-code. I need to prevent other applications from getting the bar-code.
A: At the end of your keyboard hook you would call CallNextHookEx to execute next hook in the chain.
I would suggest that put some unique signature as a preamble for your barcode so that your keyboard hook procedure can detect it as a valid barcode input from your scanner. Now, when you get this data, just skip the call to 'CallNextHookEx' so that the chain will be discontinued and other programs won't get your barcode. Otherwise - call 'CallNextHookEx' so the chain can continue.
Note: This is my theory, I have never tried the exact same thing myself. I have however, written hooks in C++ and C#.
A: Check this project out
http://globalmousekeyhook.codeplex.com/
It is in C# as well so will make your coding easier. Sounds like all you need is to hook up the global key press event and suppress it by setting the Handled value or something similar.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: as2 video resume How can I do resume video.
general.video_button.onRelease = function(){
if (general.stop_button._visible == false){
general.video.resume();
}
general.video.play(0);
general.video_button._visible = false;
general.stop_button._visible = true;
}
Thanks for answers.
A: If Video.pause() was previously called, playback begins from the current position. If Video.stop() was previously called, playback begins from the first frame.
general.video_button.onRelease = function(){
if (general.stop_button._visible == false){
general.video.resume();
general.video_button._visible = true;
general.stop_button._visible = false;
return;
}
general.video.pause();
general.video_button._visible = false;
general.stop_button._visible = true;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: mod_rewrite, can't rewrite existing file I'm trying to pass all images in a directory to watermark.php using mod_rewrite in .htaccess.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule \.jpg$ /watermark.php?path=%{REQUEST_FILENAME} [L]
It works fine on local machine, but on my online production server (shared hosting) all image files are served without rewriting.
mod_rewrite is enabled online, but it ignores the rule if file exists.
What could be wrong?
UPDATE
Here's my full setup: there's a domain with a subdomain in a subfolder of main domain's document_root.
public_html (example.com DOCUMENT_ROOT)/
img (img.example.com DOCUMENT_ROOT)/
.htaccess in public_html folder:
<FilesMatch "\.(inc\.php|log)$">
Deny from all
</FilesMatch>
Options -Indexes +FollowSymLinks
php_value short_open_tag 0
php_value auto_prepend_file /home/username/public_html/bootstrap.inc.php
RewriteEngine On
RewriteCond %{HTTP_HOST} ^img\. [NC]
RewriteRule .* - [L]
RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^example\. [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ shop/$1 [L]
.htaccess in img folder:
<FilesMatch "\.(inc|log)$">
Deny from all
</FilesMatch>
Options -Indexes +FollowSymLinks
php_value short_open_tag 0
php_value auto_prepend_file none
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule \.jpg$ /watermark.php?path=%{REQUEST_FILENAME} [L]
The problem is that existing images in img folder are not rewrited. Apache just serve them as is. But if, for example, I request non-existing file the rule works and echo $_GET['path'] prints the full filepath to non-existing file.
A: Here's what you can use:
RewriteEngine On
RewriteRule ^(media|image|images)(/?)(.*)$ - [F]
RewriteRule ^([a-z0-9\-_\.]+)\.(jpg|jpeg|png|gif)$ /watermark.php?path=%{REQUEST_URI} [L]
The first RewriteRule is set to make sure people don't go to that folder - it gives a 403 permission denied (this is optional)
The second one will redirect any images that match letters, numbers, dash, underscore and dot with the extension: jpg, jpeg, png and gif to your watermark.php file. eg:
http://www.domain.com/logo.jpg => path = /logo.jpg
UPDATE:
Since the rule is in a different folder and the root directory of IMG is /home/username/public_html/img/ the watermark.php file does not exists. Either copy the file you need (watermark.php and its libraries) to the IMG folder or create symblink.
cd /home/username/public_html/img/
ln -s ../watermark.php (and other library files as well)
A: htaccess change :
Options -Indexes +FollowSymLinks
by
Options -Indexes +FollowSymLinks -MultiViews
This behaviour steel exists on Apache 2.4..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Problem in Naming the Audio file in Facebook Post in Android Friends, I posted the Audio link to Facebook Friends wall without Dialog.
I'm able to play the Posted Audio link within Facebook, but i am unable to give title , name for it. Refer the Picture - I want to Post like ..
Following is my code :
try{
String userID="1000021233268431111";
Bundle params = new Bundle();
params.putString("name", "name of link");
params.putString("title", "title of link");
params.putString("descrption", "descrption of link");
params.putString("caption", "Get utellit to send messages like this!");
params.putString("link", "http://www.looptvandfilm.com/blog/Radiohead%20-%20In%20Rainbows/01%20-%20Radiohead%20-%2015%20Step.MP3");
params.putString("type", "mp3");
params.putString("source", "http://www.looptvandfilm.com/blog/Radiohead%20-%20In%20Rainbows/01%20-%20Radiohead%20-%2015%20Step.MP3");
String response = facebook.request(((userID == null) ? "me" : userID) + "/feed", params, "POST");
Log.v("response", response);
} catch(Exception e){
}
If i try to use the JSON Array to add attachment,nothing is added in the Parameter and i am getting Empty post like this:
Using JSON ARRAY mu code is :
Bundle parameters = new Bundle();
JSONObject attachment = new JSONObject();
try {
JSONObject media = new JSONObject();
media.put("type", "mp3");
media.put("src", "http://www.looptvandfilm.com/blog/Radiohead%20-%20In%20Rainbows/01%20-%20Radiohead%20-%2015%20Step.MP3");
media.put("title", "Listen to your message");
media.put("artist", "By: utellit for Android");
media.put("album", "Utellit");
attachment.put("media", new JSONArray().put(media));
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
attachment.put("message", "Messages");
attachment.put("name", "Get utellit to send messages like this!");
attachment.put("href", "http://www.looptvandfilm.com/blog/Radiohead%20-%20In%20Rainbows/01%20-%20Radiohead%20-%2015%20Step.MP3");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
parameters.putString("attachment", attachment.toString());
String response =facebook.request(((userID == null) ? "me" : userID) + "/feed",parameters, "POST");
Log.v("response", response);
A: Finally i got it.. Here is my solution :
try{
String link="LINK that should goes if yoy click Get utellit to send messages like this";
String amazon_link=".mp3 link that should play inside Facebook";
Bundle parameters = new Bundle();
JSONObject attachment = new JSONObject();
try {
JSONObject media = new JSONObject();
media.put("type", "mp3");
media.put("src", amazon_link);
media.put("title", "Listen to your message");
media.put("artist", "By: utellit for Android");
media.put("album", "Utellit");
attachment.put("media", new JSONArray().put(media));
} catch (JSONException e1) {}
try {
attachment.put("message", "Messages");
attachment.put("name", "Get utellit to send messages like this!");
attachment.put("href", link);
} catch (JSONException e) {}
parameters.putString("attachment", attachment.toString());
parameters.putString("message", "Text is lame. Listen up:");
parameters.putString("target_id", "xxxx"); // target Id to post
parameters.putString("method", "stream.publish");
String response = facebook.request(parameters);
}
catch(Exception e){}
In facebook.request method we should send only parameters and the Method of post should added in Attachments
Finally my Post in Facebook looks likes this :
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: To fetch Random/different records each time I have 3 thumbnails which i want to rotate each time a user refresh the page. Therefore want to show different thumbnail each time. I have image name stored in the database. I am using this SQL query to fetch "select thumbnail from tablename order by rand() limit 1". It is fetching one thumbnail perfectly.
The problem is that sometime same images comes up. For example first time i refresh the page thumbnail 1.jpg shows but second time again 1.jpg comes up.
So what i am looking for is to have different thumbnail each time i refresh the page.
Can anyone provide me some suggestions to achieve this ?
A: this is not possible with random selection, as the same image can come again.
For the effect you want you need to use a cookie to store the last displayed image name and NOT display that image for the next request.
As you have confirmed in your comment you do not want to display the last displayed thumbnail. IN that case you can do this like this using sessions:
// get last shown from session if any
$last_shown = '';
if(isset($_SESSION['last_shown_thumb']))
$last_shown = $_SESSION['last_shown_thumb'];
// select a thumbnail randomly which is not the one last shown
$query = "SELECT thumbnail FROM tablename WHERE thumbnail <> '" . $last_shown . "' order by rand() limit 1";
$res = mysql_query($query);
$row = mysql_fetch_row($res);
$curr_thumb = $row[0];
// set the current to last shown in session
$_SESSION['last_shown_thumb'] = $curr_thumb;
A: Assuming you are using PHP, you store the previous thumbnail in $current_thumbnail.
Then, you can do it like this
SELECT thumbnail FROM tablename WHERE thumbnail <> '$current_thumbnail' ORDER BY rand() LIMIT 1
Your query just needs to know what thumbnail you are currently displaying so you can filter it out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Decomposing big member function Decomposing a member function
In a class there is a member function that is rather long. Let's say we have
class Customer {
public:
void process();
...
};
The method process is by nature long and consists of a couple of different
steps. You'd like these steps to be functions of their own, to avoid having
multiple levels of abstraction in the process method. I have thought of these
different options (including the noop-alternative):
Create stand-alone functions for the steps outside of the class.
double step_a(vector<Order> orders, double foo);
void step_b(double bar);
void Customer::proccess()
{
double foo;
...
double bar = step_a(this->orders, foo);
...
step_b(bar);
};
Concerns: The class is less self-contained. The stand alone functions are so
specific to the process function that they would never be of interest to any
other code, making it feel unnatural to keep them outside of the class.
Create private methods.
class Customer {
public:
void process();
private:
double step_a(double foo);
void step_b(double bar);
};
Concerns: The private methods for the steps (at least some of them) wouldn't
operate on any class members at all. They have no side effects, they only
compute a value from arguments and return it, so they have no need at all to
be member functions of the class.
Leave Customer::process as is
Concerns: The function becomes long, and could be hard to read, because of all
the details in the steps making it hard to see the big picture of what steps
the process contains.
Question:
What would be the cleanest way to handle this?
(Perhaps none of the above, but someting I hadn't thought of.)
A: The question isn't really language agnostic. Not all languages have stand alone functions.
In C++ or C# I would probably use private member functions (static if possible).
In C++ you could use stand-alone functions (possibly in an anonymous namespace) so they are not visible to the outside.
A: I'd point you at the refactoring books - especially Martin Fowler's Refactoring, and Joshua Kerievsky's Refactoring to Patterns. This problem is explored at some depth in those books.
The "stand-alone" option you describe is often called "helper methods"; there's nothing inherently wrong with this, except that they often explode into becoming the core of the method, and this leads to dependency explosion.
Private (static) methods are best if the code is directly related to the duties of the class in question.
Leaving it as is can be okay - but there's a fairly well-understood correlation between the complexity of a method and the likelihood it contains bugs. If this is a living code base, I'd refactor it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to parse CIMPLICITY's ctx file I have to parse CIMPLICITY's ctx file. Ctx file sample:
(Version 42)
(DocumentSummary)
(GmmiToplevelDocument
(GmmiDocumentObject
(GmmiContainerObject
(GmmiObject "" 0
(Help "" "" "")
(GmmiPointMap
(GmmiPoint "MODBUS.HOIST.HST1.HST" 8 0 1)
(GmmiPoint "MODBUS.HOIST.HST2.MAXVAL" 9 0 1))
(GmmiOptionTable
(GmmiVariables))
(GmmiTabOrder -1)) (Color 3 8) (Color 3 5)
(Font "Arial" 0 280 1 0)
(GmmiObjectPtrList
(GmmiOleObject
(GmmiObject "" 0
(Help "" "" "")
(Empty)
(GmmiTabOrder 0)) 0
(Extents
(Rect 180 6840 6255 3825)
(Rect 180 6840 6255 3825))
(Border (Color 1 &hff000000) 0 11 0)
(Interior (Color 0) (Color 1 &hff000000) 1)
(Interior (Color 1 &hff000000) (Color 1 &hff000000) 1) 0 0 1000 1000 1000 1000
(Rect 180 6840 6255 3825) "TREND.TrendCtrl.1"
(OleMagic 0)
(GROleControl
(OlePropBag {B4E7803D-9435-11CE-9CF4-0020AF743F4D}
"BInLegend1" 1
"BaseProject" "MOD_TEST"
"Color1" 255
"CompressionSampleUnits1" 0
"Name1" "MODBUS.HOIST.HST1.HST"
"Name2" "Chart X Axis"
"Name3" "Chart Y Axis"
"NumberLines" 1
"Order1" 0
"PointID1" "MODBUS.HOIST.HST1.HST"
"Type1" 7
"Type3" 1
"_ExtentX" 10716
"_ExtentY" 5318
"_StockProps" 13
"_Version" 393220)))
(GmmiTextObject
(GmmiObject "" 0
(Help "" "" "")
(Empty)
(GmmiTabOrder -1)) 23
(Extents
(Rect 180 3600 3144 2752)
(Rect 180 3600 1776 2752))
(Font "" 0 720 1 0)
(Interior (Color 1 &hff000000) (Color 1 &hffffffff) 1)
(Border (Color 1 &hff000000) 0 11 0) 18
(Point 180 3600) "HOIST 1")
(GmmiTextObject
(GmmiObject "" 0
(Help "" "" "")
(GmmiOptionTable
(GmmiOptionTable
(GmmiValueAnim
(GmmiExprAnim 3
(GmmiExpr "MODBUS.HOIST.HST1.HST")) 0
(ExecCond "" "") "%s" 4)))
(GmmiTabOrder -1)) 23
(Extents
(Rect 3240 3600 4436 2964)
(Rect 3240 3420 4436 2784))
(Font "" 0 540 1 0)
(Interior (Color 1 &hff000000) (Color 1 &hffffffff) 1)
(Border (Color 1 &hff000000) 0 11 0) 18
(Point 3240 3600) "Text")
(GmmiTextObject
(GmmiObject "" 0
(Help "" "" "")
(Empty)
(GmmiTabOrder -1)) 23
(Extents
(Rect 360 1800 1662 1471)
(Rect 360 1800 1662 1471))
(Font "Arial" 0 -280 1 0)
(Interior (Color 1 &hff000000) (Color 1 &hffffffff) 1)
(Border (Color 1 &hff000000) 0 11 0) 18
(Point 360 1800) "Test data:")
(GmmiTextObject
(GmmiObject "" 0
(Help "" "" "")
(GmmiOptionTable
(GmmiOptionTable
(GmmiValueAnim
(GmmiExprAnim 3
(GmmiExpr "MODBUS.HOIST.HST2.MAXVAL")) 0
(ExecCond "" "") "%s" 4)))
(GmmiTabOrder -1)) 23
(Extents
(Rect 1980 1800 2599 1471)
(Rect 1980 1800 2599 1471))
(Font "Arial" 0 -280 1 0)
(Interior (Color 1 &hff000000) (Color 1 &hffffffff) 1)
(Border (Color 1 &hff000000) 0 11 0) 18
(Point 1980 1800) "Text")) 0
(GmmiBackdrop
(Border (Color 1 &hff000000) 0 11 0)
(Interior (Color 1 &hffc0c0c0) (Color 1 &hff000000) 1))))
(Point 100 100)
(Size 9600 7200) 100 "")
(OleItems)
The file above represents CIMPLICITY's screen. The issue is to build WPF screen based on that file. First of all, by my opinion, I should parse that file, remove unneeded parts and then build interface.
I've googled on the Internet .Net based parser - FParsec. The problem is I've never coded with F# and it's difficult to understand how to use this library. So I don't want to do an extra work.
The main question: is it possible to parse that file to custom object representing screen's structure with FParsec. For example, this object may has so definition:
public class Document
{
public string Version { get; set; }
public object Summary { get; set; }
public GmmiTopLevelDocument GmmiTopLevelDocument { get; set: }
}
public class GmmiTopLevelDocument
{
public GmmiDocumentObject GmmiDocumentObject { get; set; }
public Point Point { get; set; }
public Size Size { get; set; }
}
public class GmmiDocumentObject
{
...
}
May be it's wrong way? What is right?
UPDATE:
Also I have BNF for scree language. Sample:
<GmmiTextButtonObject> ::= "(" GmmiTextButtonObject<GmmiButtonObject><GRTextButton>")"
<GmmiTextObject> ::= "(" GmmiTextObject<GmmiGraphicObject> <GRText> ")"
<ToplevelDocument> ::= "(" GmmiToplevelDocument<GmmiDocument><initialPosition.Point><Size>zoom.number> ")"
<ToplevelDocumentPO> ::= <GmmiPointMap><ambientForeground.GRColorAttr><ambientBackground.GRColorAttr>
<ambientFont.GRFontAttr>
<GmmiProcedureMap>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Rails linked tables belongs_to or has_many not working I have three tables User, User_types and Purchases.
*
*user: id etc
*user_purchase_types: id, typename, user_id
*purchases: id, user_id, user_purchase_type_id, note
Users can have any number of purchases and user_types. A purchase can have one user_purchase_type.
Users can log in, create types, do purchases etc - this all works fine
However I want, when listing purchases, to see the user_purchase_types.typename, rather than the id number. Simple I think, use belongs_to, they already have the right id fields, should just work. But it doesn't
I have tried a million variations of belongs_to, has_many , has_many through etc etc but cannot get the right relationship and so show the typename rather than the id.
There are the right foreign_key id fields in the tables so this should work.
When listing the purchases in the purchase controller I use @purchase = current_user.purchases.
When looping this to display in the view I think I should be able to use purchase.user_purchase_type.typename but this gives me a 'NoMethodError'.
What am I doing wrong or should I just denormalise the DB and have done with it?
EDIT Models as req
class UserPurchaseType < ActiveRecord::Base
belongs_to :user
belongs_to :purchase
attr_accessible :typename, :id
end
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :purchases, :dependent => :destroy
has_many :user_purchase_types, :dependent => :destroy
end
class Purchase < ActiveRecord::Base
belongs_to :user
has_many :user_purchase_types
attr_accessible :date, :user_purchase_type_id, :note
end
index.erb file
<% @purchases.each do |purchase| %> #this works
<tr>
<td><%= purchase.user_purchase_type.typename %></td> #this fails
<td><%= purchase.date %></td>
<td><%= purchase.note %></td>
</tr><p>
<% end %>
purchase controller
def index
@user_purchase_types = current_user.user_purchase_types # this works
@purchases = current_user.purchases #this works
A: there is a one to one relationship between them rgt?
yes you should be able to be able to access typename, but by using @purchase.user_type.typename. and not purchase.user_type.typename.
and would be better if you could show user models too.
and is current_user defined?
also you can try by finding out the usertype first and then access it:
@user_type = UserType.find(@purchase.user_type_id)
@user_type.typename
You should always try the relationships first on console and see if your getting it rgt
Your relationships are all messed up.
You have a one to many relationships between purchases and user purchase type.
and therefore you can not use @purchase.user_purchase_type.typename
You have to use
@purchase.user_purchase_types.each do |i|
i.typename
end
A: class Purchase < ActiveRecord::Base
belongs_to :user
has_many :user_purchase_types
attr_accessible :date, :user_purchase_type_id, :note
end
The Purchase -> UserPurchaseType association is a has_many relationship but you seem to be trying to use it with user_purchase_type_id which would indicate a belongs_to :user_purchase_type relationship, but your association is has_many :user_purchase_types
It sounds like you may want something like:
<% @purchases.each do |purchase| %> #this works
<tr>
<td><%= purchase.user_purchase_types.collect(&:typename).join(',') %></td>
<td><%= purchase.date %></td>
<td><%= purchase.note %></td>
</tr><p>
<% end %>
to list all your UserPurchaseType typename's, comma separated.
If you do this, make sure when you load your @purchases in the controller to also include a .includes(:user_purchase_types). This will eager load the association and avoid rails loading each UserPurchaseType as you iterate through.
A: You just need to add foreign key in your existing association.
class Purchase < ActiveRecord::Base
belongs_to :user
has_many :user_purchase_types, :foreign_key => 'user_purchase_type_id'
attr_accessible :date, :user_purchase_type_id, :note
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: want to know the list of users who liked my brand page
Possible Duplicate:
Querying Users who 'like' my Facebook Page
I am new to Facebook development and I created one Brand page. I would like to know the list of users who liked my brand page.
I can see the list of people who liked my page on left side of menu under "Like this". Is there any way where we can retrieve those list and store somewhere?
Please help.
A: I'm afraid due to policies there is no real way to extract this information. It' supposed to protect the users, or something.
You can check if a specific Facebook user likes your page, though.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HttpWebRequest work differently in debug/release Ive a problem with a code because it work differently if I test it in Visual Studio either I test it on my site.
i am trying to do an autologin on an external web site. If I test it from VS, I am correctly redirected on the external site. From my site i obtain i am redirected to "http://www.MySite.com/cgi-bin/wbc_login/...."!!!!!
The code is the following:
private void MioMetodo(String username, String password)
{
CookieContainer Cookies = new CookieContainer();
Cookie langCookie = new Cookie("pk_lang", "\"italiano\"", "/");
langCookie.Domain = "xxx.yy";
Cookie loginCookie = new Cookie("wc_loginoslimit", "\"" + username + "\"", "/");
loginCookie.Domain = "xxx.yy";
Cookie passwordCookie = new Cookie("wc_passwordoslimit", "\"" + password + "\"", "/");
passwordCookie.Domain = "xxx.yy";
Cookies.Add(langCookie);
Cookies.Add(loginCookie);
Cookies.Add(passwordCookie);
UTF8Encoding encoding = new UTF8Encoding();
String postData = "wc_login=" + username + "&wc_password=" + password + "&limit=0&Avanti=Avanti";
Byte[] data = encoding.GetBytes(postData);
HttpWebRequest myHttpWebRequest = WebRequest.Create("http://xxx.yy/cgi-bin/wbc_login") as HttpWebRequest;
myHttpWebRequest.Method = "POST";
myHttpWebRequest.Referer = "http://xxx.yy/cgi-bin/wbc_login";
myHttpWebRequest.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
myHttpWebRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
myHttpWebRequest.Headers.Add(HttpRequestHeader.AcceptLanguage, "it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4");
myHttpWebRequest.Headers.Add(HttpRequestHeader.CacheControl, "max-age=0");
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
myHttpWebRequest.CookieContainer = Cookies;
myHttpWebRequest.ContentLength = data.Length;
Stream newStream = myHttpWebRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse myHttpWebResponse = myHttpWebRequest.GetResponse() as HttpWebResponse;
StreamReader streamRead =new StreamReader(myHttpWebResponse.GetResponseStream());
Response.Write(streamRead.ReadToEnd());
streamRead.Close();
myHttpWebResponse.Close();
}
Thanx in advance
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Write Selenium Test to test text wrapping? I am trying to write the selenium test using selenium 2.0 for the attached scenario.
HTML code is as follows
<div width="100px" style = "background-color:blue">
This%is%Normal%Text%on%page%without%dynamic%view%and%not%width%set.
</div>
I need to verify whether text is wrapping or not. Text should wrap in the 2nd scenario
Any help would be appreciated.
Thanks,
Sahil
A: I'm afraid it goes too deep to browser's internals so it is not possible with Selenium. Maybe you can check the height ow wrapping element (div) if it exceeds height of line, but it looks fragile to me.
A: May be should try the url encode/uncode to see if that particular text is encoded or not?
A: You can check if the text is overflowed.
public boolean isElementOverflowed(CoreLocator element) {
return (boolean) coreDriver.executeScript("return arguments[0].scrollWidth > arguments[0].clientWidth",
element.getWebElement());
}
and call it in your code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to increase line height in NetBeans 7? I found a hack how to increase it in 6.9, but it does not work in NetBeans 7. Is there any way to increase the space between the lines in ver. 7? Please help, googled it too - no info about it :/
A: Here you go,
*
*Find org-netbeans-modules-editor-settings-CustomPreferences.xml in ~/.netbeans/x.x/config/Editors/Preferences where x.x is your netbeans version.
*Add this xml markup just above </editor-preferences> or anywhere if you know what you doing.
<entry javaType="java.lang.Float" name="line-height-correction" xml:space="preserve">
<value><![CDATA[1.4]]></value>
</entry>
A: In Apache Netbeans 14,
I was installed it via .sh file
I figure out how to change/add editor custom preferences as well
open
/home/username/.netbeans/14/config/Editors/Preferences/
and open
org-netbeans-modules-editor-settings-CustomPreferences.xml
then add a new entry
<entry javaType="java.lang.Float" name="line-height-correction" xml:space="preserve">
<value><![CDATA[1.5]]></value>
</entry>
Have a nice edit.
A: @pengemizt answer is greate but it is long time now
for netbeans 11.2
on Ubuntu 18.04 LTS you will look for
org-netbeans-modules-editor-settings-CustomPreferences.xml
inside
snap/netbeans/common/data/11.2/config/Editors/Preferences
You can change this
<![CDATA[1.4]]>
as you like for me I make it 1.5
<![CDATA[1.5]]>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: android - fitting image in imageview I'm implementing a widget where i'm trying to display a large image inside an image view (8mpx) like this :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" android:id="@+id/widget"
android:background="#000000"
android:padding="15dp"
android:layout_margin="5dp"
android:layout_gravity="top|center_vertical|center_horizontal"
>
<LinearLayout android:background="#ffffff" android:padding="1dp" android:layout_width="wrap_content" android:layout_weight="1"
android:layout_height="wrap_content" >
<ImageView
android:adjustViewBounds="true"
android:id="@+id/image"
android:src="@drawable/sample"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="top|center_horizontal"
android:scaleType="fitXY"
android:maxWidth="200dip"
android:maxHeight="300dip"
/>
</LinearLayout>
In the emulator everything seems ok, but when i deploy to device, i get the "problem loading widget" message.
the emulator is HVGA and my device has a 480x800 resolution.
Any ideea what am i doing wrong ?
Thank you!
==================================================
As advised by you guys i've made a screenshot of the logcat.
Here it is :
A: imageview.setScaleType(ScaleType.CENTER_INSIDE);
A: Try below code
<ImageView
android:adjustViewBounds="true"
android:id="@+id/image"
android:src="@drawable/sample"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|center_horizontal"
android:scaleType="centerInside"
/>
A: use this
imageview.setImageResource(your_image);
imageview.setScaleType(ScaleType.MATRIX);
A: Old post, but you never know...
The logcat shows the problem:
"allocation too large for this process"
The image you are trying to render is too large to fit into memory. You need to scale the image down, but don't try to create a scaled version of the bitmap or you'll hit the same problem. The solution is the load the Bitmap into memory but ONLY for it's dimensions, then create a new Bitmap with a sample size that reduces the overall size of the image.
Actually you don't even need to load in the image to get it's original size to do this but it often makes sense so you can choose an appropriate sample size.
e.g.
Assuming your Bitmap is obtained from an InputStream:
InputStream in = ... // Your Bitmap Stream
// Decode JUST the dimensions
Options dimensionOptions = new Options();
dimensionOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, dimensionOptions);
// Get the dimensions of the raw
int rawWidth = dimensionOptions.outWidth;
// Choose a target width for the image (screen width would make sense)
int targetWidth = 480;
// Select the sample size which best matches our target size.
// This must be an int
float sampleSize = (float)rawWidth / (float)targetWidth;
// Assume lower, which will result in a larger image
int sample = (int) FloatMath.floor(sampleSize);
// Use this to decode the original image data
Options scaleOptions = new Options();
scaleOptions.inPreferredConfig = Bitmap.Config.ARGB_8888; // 4 bytes per pixel
scaleOptions.inSampleSize = sample;
// Now create a bitmap using the sample size
Bitmap scaled = BitmapFactory.decodeStream(in, null, scaleOptions);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Can't load new url using if / else javascript statement - help? I've appropriated some code to create a countdown timer for the launch of a new site. The timer itself, which uses a custom typeface, works very well.
However, when the if / else statement for timesup is true and goes to 'else', I can't get any other function to work apart from the way you see it below:
function formatresults(){
if (this.timesup==false){//if target date/time not yet met
var displaystring="<div class='row'><div class='col'> "+arguments[0]+" </div> <div class='thincol'>•</div> <div class='col'> "+arguments[1]+" </div> <div class='thincol'>•</div><div class='col'> "+arguments[2]+" </div> <div class='thincol'>•</div> <div class='col'> "+arguments[3]+" </div> </div>"
}
else {
var displaystring = "BAR"
}
return displaystring
}
if I change var displaystring to window.location (to load the full site at the end of the countdown), the timer ceases to work completely.
I know this is due to a fundamental misunderstanding of javascript in a way, but in all honesty I've developed sites using javascript and libraries like jquery and mootools and haven't hit a brick wall like this in a long time.
If you have any advice, please do share it with me!
Many thanks in advance
A: Seems like you have a serious issue of no formatting madness going on. You should properly indent and format your JavaScript and terminate each statement with a semicolon:
function formatresults() {
var displaystring = "";
if (this.timesup == false) { // if target date/time not yet met
displaystring = "<div class='row'><div class='col'> "
+ arguments[0]
+ " </div> <div class='thincol'>•</div> <div class='col'> "
+ arguments[1]
+ " </div> <div class='thincol'>•</div><div class='col'> "
+ arguments[2]
+ " </div> <div class='thincol'>•</div> <div class='col'> "
+ arguments[3]
+ " </div> </div>";
} else {
displaystring = "CRAP";
window.location.href = "http://example.com/";
}
return displaystring
}
The above code should work just fine. Now I don't know why you would want to redirect the user after having set displaystring, since that will abort the current page execution, but nonetheless; the above code should work.
As Ben Lee writes; you shouldn't be doing window.location.href changes in this function, but instead in the function invoking formatresults() so formatresults() only does what it says, which is to format the results. This is how I'd solve it:
function formatresults() {
var result = { success : false, value : null };
if (this.timesup) { // if target date/time not yet met
result.success = false;
result.value = "Time's up!";
} else {
result.success = true;
result.value = "<div class='row'><div class='col'> "
+ arguments[0]
+ " </div> <div class='thincol'>•</div> <div class='col'> "
+ arguments[1]
+ " </div> <div class='thincol'>•</div><div class='col'> "
+ arguments[2]
+ " </div> <div class='thincol'>•</div> <div class='col'> "
+ arguments[3]
+ " </div> </div>";
}
return result;
}
// ...
var result = formatresults();
if (!result.success) {
window.location.href = "http://example.com/";
} else {
// Do something with result.value
}
A: Why not just immediately redirect in the else clause?
function formatresults() {
if (this.timesup == false) {
return "<div class='row'><div class='col'> "+arguments[0]+" </div> <div class='thincol'>•</div> <div class='col'> "+arguments[1]+" </div> <div class='thincol'>•</div><div class='col'> "+arguments[2]+" </div> <div class='thincol'>•</div> <div class='col'> "+arguments[3]+" </div> </div>";
} else {
window.location.href = "http://url.to.full.site";
}
}
Really the check doesn't belong in formatresults, you should try to move it out into whatever function called formatresults. I just did it this way for demo purposes, since I don't have a sample of your calling code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Magento CLI install: in table "core_resource" column "data_version" remains null, why? i try to install Magento 1.5.1 via cli.
As far as i can see all database tables are created with relevant content, but in table core_resource i can see the data_version comming from sql dir (mysql4-data-upgrade... files) is missing. At all rows in core_resource the column data_version is null. Why?
CLI is called according to the instructions here:
http://www.magentocommerce.com/wiki/groups/227/command_line_installation_wizard
A Mage::app()->cleanCache(); after installation do not help.
I can fix this by do a login to the backend SYSTEM / CACHE MANAGEMENT and refreshing of CacheType=CONFIGURATION. But how to do that via cli?
A: The installer never calles the applyAllDataUpdates() to make the installation complete. Install.php trusts that the magento downloader was used before, which does a call to applyAllDataUpdates().
But in my case i did not use the magento downloader, because i installed a magento instance from a local git repository (for buildserver, dev machine, etc.) via my own ant script. I gussed that the cli install is independend from the downloader (by design) - but here a "hidden" dependency is discovered. Running cli installer alone, setup the extensions without upgrading "data_version".
Normally you can trust in the first http call to the magento frontend / backend, which calls the applyAllDUpdates() and applyAllDataUpdates() if there is a error with the config (in cache), but in this case the cache was created successfull (extension config) by the installer - so no applyAllDataUpdates() is triggered.
I am running unit tests, integration tests and function tests (in that chain) after a build of magento (without using the downloader). I get strange behaviours if "data_version" is not poluted. My solution is to add:
Mage_Core_Model_Resource_Setup::applyAllUpdates();
Mage_Core_Model_Resource_Setup::applyAllDataUpdates();
to the bootstrap of my unit tests.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Apple HTTP LIVE streaming Is it possible to use the Live streaming method to create a Voice call or Video call app ?
thanks
A: HLS is not the ideal technology for your purpose due to
*
*Latency HLS video stream is broken down into mpegts chunks of 10secs each which has to be transferred fully before it can be played. Hence there is always a significant delay associated with HLS.
*Buffering In case of poor data transmission, HLS player buffers and doesn't skip ahead which is not what you want for a video chat.
*No Hole punching HLS works on HTTP, not UDP - so you won't be able to leverage UDP hole-punching if your clients are behind NAT / firewalls
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to apply concatenated classes within another class using Less? Let's say I have the following Less setup:
.box {
border: 1px solid #333;
&.error {
background-color: Red;
}
}
If I wanted to declare another class which applied the full style of .box.error, as .error-box for example, what's the correct syntax?
If I use:
.error-box {
.box.error;
}
All I get is the red background, with no border. I've tried many different combinations, but I always get a syntax error.
A: I plugged in your less as so:
.box {
border: 1px solid #333;
&.error {
background-color:red;
}
}
.error-box {
.box;
}
and the CSS output was this:
.box {
border: 1px solid #333;
}
.box.error {
background-color: red;
}
.error-box {
border: 1px solid #333;
}
.error-box.error {
background-color: red;
}
were you wanting the .error-box class to alone receive both styles? The only way I can think of doing that would be:
.error-bg {
background:red;
}
.box {
border:1px solid #333;
&.error {
.error-bg;
}
}
.error-box {
.box;
.error-bg;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Selected item in asp menu control to look like a button with rounded corners using CSS2.1? I am trying to make my selected menu item look like a rounded corner button using images and CSS2.1.
.StaticSelectedStyle a
{
display: block;
padding-left:5px;
height:35px;
width: 100%;
background: transparent url('../images/button_right.png') no-repeat scroll right top;
float:left;
/*FONT*/
color: White;
text-align:center;
vertical-align:middle;
line-height: 32px;
}
.StaticSelectedStyle
{
display: block;
height:35px;
background: transparent url('../images/button_left.png') no-repeat;
text-align:center;
vertical-align:middle;
}
The image (button_right.png) is not displayed, and at the same time ,the text color is displayed as white as indicated in the same CSS class. Any ideas why this might be happening?
Here is the HTML. My menu has 6 items: Reem, Omneya Ismail Siam, Michel, Nevine, Karim and Engy. The selected item is Nevine:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
<link href="CSS/menu_style.css" rel="stylesheet" type="text/css" />
<style type="text/css">
.Menu1_0 { background-color:white;visibility: hidden; display: none; position: absolute; left: 0px; top: 0px; }
.Menu1_1 { text-decoration: none; }
.Menu1_2 { }
.Menu1_3 { border-style: none; }
.Menu1_4 { }
.Menu1_5 { }
.Menu1_6 { border-style: none; }
.Menu1_7 { }
.Menu1_8 { border-style: none; }
.Menu1_9 { }
</style>
</head>
<body bgcolor="black">
<form name="form1" method="post" action="default.aspx" id="form1">
<table id="Menu1" class="menunav StaticMenuStyle Menu1_5 Menu1_2" cellpadding="0" cellspacing="0" border="0">
<tr>
<td onmouseover="Menu_HoverStatic(this)" onmouseout="Menu_Unhover(this)" onkeyup="Menu_Key(this)" >
<table class="StaticMenuItemStyle Menu1_4" cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td style="white-space: nowrap;"><a class="Menu1_1 StaticMenuItemStyle Menu1_3" href="#" style="border-style: none; font-size: 1em;">Reem</a></td>
</tr>
</table>
</td>
<td style="width: 10px;"></td>
<td style="width: 10px;"></td>
<td onmouseover="Menu_HoverStatic(this)" onmouseout="Menu_Unhover(this)" onkeyup="Menu_Key(this)" id="Menu1n1">
<table class="StaticMenuItemStyle Menu1_4" cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td style="white-space: nowrap;"><a class="Menu1_1 StaticMenuItemStyle Menu1_3" href="#" style="border-style: none; font-size: 1em;">Omneya Ismail Siam</a></td>
</tr>
</table>
</td>
<td style="width: 10px;"></td>
<td style="width: 10px;"></td>
<td onmouseover="Menu_HoverStatic(this)" onmouseout="Menu_Unhover(this)" onkeyup="Menu_Key(this)" id="Menu1n2">
<table class="StaticMenuItemStyle Menu1_4" cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td style="white-space: nowrap;"><a class="Menu1_1 StaticMenuItemStyle Menu1_3" href="javascript:__doPostBack('Menu1','Michel')" style="border-style: none; font-size: 1em;">Michel</a></td>
</tr>
</table>
</td>
<td style="width: 10px;"></td>
<td style="width: 10px;"></td>
<td onmouseover="Menu_HoverStatic(this)" onmouseout="Menu_Unhover(this)" onkeyup="Menu_Key(this)" id="Menu1n3">
<table class="StaticMenuItemStyle Menu1_4 StaticSelectedStyle Menu1_7" cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td style="white-space: nowrap;"><a class="Menu1_1 StaticMenuItemStyle Menu1_3 StaticSelectedStyle Menu1_6" href="#" style="border-style: none; font-size: 1em;">Nevine</a></td>
</tr>
</table>
</td>
<td style="width: 10px;"></td>
<td style="width: 10px;"></td>
<td onmouseover="Menu_HoverStatic(this)" onmouseout="Menu_Unhover(this)" onkeyup="Menu_Key(this)" id="Menu1n4">
<table class="StaticMenuItemStyle Menu1_4" cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td style="white-space: nowrap;"><a class="Menu1_1 StaticMenuItemStyle Menu1_3" href="#" style="border-style: none; font-size: 1em;">Karim</a></td>
</tr>
</table>
</td>
<td style="width: 10px;"></td>
<td style="width: 10px;"></td>
<td onmouseover="Menu_HoverStatic(this)" onmouseout="Menu_Unhover(this)" onkeyup="Menu_Key(this)" id="Menu1n5">
<table class="StaticMenuItemStyle Menu1_4" cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td style="white-space: nowrap;"><a class="Menu1_1 StaticMenuItemStyle Menu1_3" href="#" style="border-style: none; font-size: 1em;">Engy</a></td>
</tr>
</table>
</td>
<td style="width: 10px;"></td>
</tr>
</table>
<a id="Menu1_SkipLink"></a></div>
<script type="text/javascript">
//<![CDATA[
var Menu1_Data = new Object();
Menu1_Data.disappearAfter = 500;
Menu1_Data.horizontalOffset = 0;
Menu1_Data.verticalOffset = 0;
Menu1_Data.staticHoverClass = 'Menu1_9 StaticHoverStyle';
Menu1_Data.staticHoverHyperLinkClass = 'Menu1_8 StaticHoverStyle';
//]]>
</script>
</form>
</body>
</html>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to enable the default highlight menus in android webview? How to enable the default text highlights menu like: Copy/Paste/Search/Share in android webview ?
A: Working on Android 1.5 - 2.3 you can use emulateShiftHeld() made public since 2.2 but now is deprecated. this method put your WebView into text selection mode.
https://developer.android.com/reference/android/webkit/WebView.html#emulateShiftHeld%28%29
Unfortunately there's no copy/paste/search/share function integrated in Android, since Android 2.0 the text selection
can be driven by touch but other than that, there's no other thing you can do.
A: I found a workaround for this
Check out method selectText() on WebView (it's not in API, but can be invoked using reflection)
here is my full method source code:
public void startTextSelection() {
try {
WebView.class.getMethod("selectText").invoke(this);
} catch (Exception e) {
try {
WebView.class.getMethod("emulateShiftHeld").invoke(this);
} catch (Exception e1) {
KeyEvent shiftPressEvent = new KeyEvent(0, 0,
KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0);
shiftPressEvent.dispatch(this);
Toast.makeText(getContext(), R.string.select_text, Toast.LENGTH_LONG).show();
}
}
}
Works on ICS too.
A: Try this:
mWebView.setHapticFeedbackEnabled(true);
mWebView.setLongClickable(true);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: How can I read a JSON in the script-tag from JavaScript? I have a dynamically generated page where I want to use a static JavaScript and pass it a JSON string as a parameter. I have seen this approach used by Google (see Google's +1 Button: How do they do it?).
But how should I read the JSON string from the JavaScript?
<html>
<head>
<script src="jquery-1.6.2.min.js"></script>
<script src="myscript.js">{"org": 10, "items":["one","two"]}</script>
</head>
<body>
Hello
</body>
</html>
In this JavaScript I would like to use the JSON argument {"org": 10, "items":["one","two"]} from the HTML document. I don't know if it's best to do it with jQuery or without.
$(function() {
// read JSON
alert("the json is:")
})
A: To read JSON in <script id="myJSON"> use
var manifest= document.getElementById('myJSON').innerHTML; //sets manifest to the text in #myJSON
manifest= JSON.parse(manifest) //Converts text into JSON
You can also use methods to point to the script like document.scripts[0]
//var manifest= JSON.parse(document.getElementById('myJSON').innerHTML); /*Shortend of 2&3*/
var manifest= document.getElementById('myJSON').innerHTML; //Gets text in #myJSON
manifest= JSON.parse(manifest) //Converts it into JSON
document.getElementById('test').innerHTML= manifest.name+ '<br/>'+ manifest.otherOptions; //Displays it
console.log('manifest')
console.log(manifest);
<head>
<script type="application/json" id="myJSON">
{"name":"Web Starter Kit", "otherOptions":"directly here"}
</script>
</head>
<body>
<p id="test"></p>
</body>
A: JSON.parse($('script[src="mysript.js"]').html());
or invent some other method to identify the script.
Maybe instead of .html() you might need .text(). Not sure. Try them both.
A: I would change the script declaration to this:
<script id="data" type="application/json">{"org": 10, "items":["one","two"]}</script>
Note type and id fields. After that
var data = JSON.parse(document.getElementById('data').textContent);
will work just fine in all browsers.
The type="application/json" is needed to prevent browser from parsing it while loading.
And the reason why we use textContent instead of innerHTML or innerText to read the raw Json text is because innerHTML tries to parse the contents as HTML which will lead to slower performance and possible parsing bugs and XSS attacks, and innerText won't grab the raw text and will instead look for human-visible text, whereas textContent grabs the pure text as-is (which is what you want). See https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent for more details about why innerHTML and innerText are bad.
A: I ended up with this JavaScript code to be independent of jQuery.
var jsonElement = document.getElementById('json-script-tag');
var myObject = JSON.parse(jsonElement.textContent);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "104"
}
|
Q: Styling a Google Map - Javascript I have followed two different tutorials for my google map, one to run the map from a MySQL database, and another to style the map.
I'm having trouble combining the two of them, I haven't got much experience with javascript...
the code i have for the map working with the database is:
you can see this map here
<!DOC
TYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Intern Map</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=myapikey" type="text/javascript"></script>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map { height: 100% }
</style>
<script type="text/javascript">
//<![CDATA[
var iconStudent = new GIcon();
iconStudent.image = 'images/man.png';
iconStudent.shadow = 'images/man_shadow.png';
iconStudent.iconSize = new GSize(35, 60);
iconStudent.shadowSize = new GSize(60, 55);
iconStudent.iconAnchor = new GPoint(6, 30);
iconStudent.infoWindowAnchor = new GPoint(5, 1);
var iconAgency = new GIcon();
iconAgency.image = 'images/pin.png';
iconAgency.shadow = 'images/pin_shadow.png';
iconAgency.iconSize = new GSize(40, 40);
iconAgency.shadowSize = new GSize(60, 40);
iconAgency.iconAnchor = new GPoint(6, 20);
iconAgency.infoWindowAnchor = new GPoint(5, 1);
var customIcons = [];
customIcons["restaurant"] = iconStudent;
customIcons["bar"] = iconAgency;
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(40, 0), 3);
// map.setCenter(new GLatLng(47.614495, 0), 3);
GDownloadUrl("marker.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, name, address, type);
map.addOverlay(marker);
}
});
}
}
function createMarker(point, name, address, type) {
var marker = new GMarker(point, customIcons[type]);
var html = "<b>" + name + "</b> <br/>" + address;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
//]]>
</script>
</head>
<body onload="load()" onunload="GUnload()">
<div id="map"></div>
</body>
and then i have code working for the style i want:
you can see this one here
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(40,0);
var myOptions = {
zoom: 3,
center: latlng,
panControl: false,
panControlOptions: {
position: google.maps.ControlPosition.RIGHT_TOP
},
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_TOP
},
scaleControl: false,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
can anybody help me combine the two, or point me in the right direction.
thanks in advance
alsweeet
A: The first script is using the javascript api v2 and the second the javascript api v3.
So it is not possible to combine the two.You should begin with basics and post here any further questions
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to redisplay the value in html page I have a signup.jsp page, there are some input boxes of html on this page, there is a input box for email-id also, when i submit form after fill up there is server side checking of email address, if email address already exist in database then signup.jsp page will redered again, then i want all the value should be dispalyed in all the input boxes that the user filled before submitting the form.
Appropriate help will be appreciable...
A: <input type="text" name="email" value="<c:out value='${param.email}'/>"/>
This displays the value of the email request parameter in the email text box. Initially, this parameter won't exist, so the text box will be blank.
Note the use of the <c:out> JSTL tag, which allows HTML-escaping the value of the parameter.
A: Your form parameters should be wrapped in a element. When submitted they will be sent to server using request parameters.
Then in your jsp file you need to render those request parameters in the places they should appear. Initially they will be empty, so user will see them rendered as initial blank values to fill.
A: The better approach is that you have to create a bean with session scope using <jsp:useBean/>, on server code update the bean's attributes and in view (jsp) page embed bean's property value to the <input/> attributes.
<form method='post' action='your_action'>
<input type='text' value="<c:out value='${bean.name}'/>" name='name'/>
</form>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make my app stay on top of fullscreen apps I have an app which must always stay on top of other applications.
I'm currently using the setLevel property for the main window to keep it on top of other desktop applications.
I'm trying to fix my app so it can also stay on top of full-screen apps in Lion.
Any ideas on how this can be done?
The Application delegate looks like this:
#import "alwaysOnTopAppDelegate.h"
@implementation alwaysOnTopAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[window setLevel:NSFloatingWindowLevel];
}
@end
A: Found the answer: The app delegate should look like this:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[window setLevel:kCGMainMenuWindowLevel-1];
[window setCollectionBehavior:NSWindowCollectionBehaviorStationary|NSWindowCollectionBehaviorCanJoinAllSpaces|NSWindowCollectionBehaviorFullScreenAuxiliary];
}
A: The way that Yoink works is simple:
Just set "Application is Agent (UIElement)" to YES in the Info.plist for your application. It will mean it doesn't show in the dock etc. but that's probably fine for an auxiliary window (well, it was for me!). It probably makes sense to provide a menu bar item in this case so the user can stop the application easily.
A: follow is my test code, it work ok, hope can help.
NSPanel *test_panel = [[NSPanel alloc] initWithContentRect:NSMakeRect(300, 300, 500, 500) styleMask:NSTitledWindowMask|NSClosableWindowMask backing:NSBackingStoreBuffered defer:YES];
[test_panel setReleasedWhenClosed:YES];
[test_panel setHidesOnDeactivate:NO];
[test_panel setFloatingPanel:YES];
[test_panel setStyleMask:NSBorderlessWindowMask | NSNonactivatingPanelMask];
[test_panel setLevel:kCGMainMenuWindowLevel-1];
[test_panel setCollectionBehavior:NSWindowCollectionBehaviorCanJoinAllSpaces|NSWindowCollectionBehaviorFullScreenAuxiliary];
[test_panel setCanBeVisibleOnAllSpaces:YES];
[test_panel center];
[test_panel orderFront:nil];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: datatemplate issue in silverlight(when assigning value to property) Consider this code:
public class customlistbox : ListBox
{
public customlistbox()
{
this.itemtemplate = this.gettemplate();
}
private string gettemplate()
{
return ".......<locall:CustomGrid Background='" + Background.Color + "' ParentReference='" + this + "' > "....."
}
}
'ParentReference' is a property which is of type customlistbox. but i give ParentReference='" + this + "', it shows error. how can i give value for 'ParentReference' in such case??
A: This is failing because you're passing a string to a property which is a DataTemplate.
You could try using a XamlReader to load the string as xaml, but for the sake of just specifying a color within the template I'd define the template in XAML and then bind the value you want for the color.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to use lapack under windows I want to use lapack and make C++ matrix wrapper for it, but lapack is written in Fortran, there are some clapack but I want to use it from source. compile firstly *.f and *.cpp files to object files then link it into a application..
the following apps and sources that I have.
*
*visual studio proff edition,dev c++,ultimate++,mingw whatever
*g95 and gfortran (under mingw) compiler
*lapack (latest source)
*blas (included in lapack)
How can I make an application please help...
My Operating System is Windows 7 and CPU Core2Duo and I dont have Intel math kernel
A: You can use the official C bindings for LAPACK, and then build your C++ wrapper around that. That avoids the issue of having to worry about the Fortran calling conventions, and the C bindings are a bit friendlier for C/C++ programmers than calling the Fortran routines directly.
Additionally, you could use one of the C++ matrix libraries that are already available, instead of rolling your own. I recommend Eigen.
PS.: Eigen matrices/vectors have a data() member that allows calling LAPACK without having to make temporary copies.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581152",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is there any way in Vim to test that I have no file opened at start? At the end of my .vimrc I want to conditionally launch a command opening my TODO list.
The problem is that I only want that behaviour when I am using vim or gvim.
And currently, I also load that buffer if I launch vim foo.bar, which is pretty inconvenient because I have to switch back to foo.bar
So basically I want to be able to write something like :
if (some condition telling me that I am on the defaut buffer)
silent LaunchTaskList
endif
A: Well, you always have a buffer when you're running Vim. It sounds like the check you really want to do is based on whether file arguments were given to Vim, and thus the args list is empty. For that, you can use the argc function.
if argc() == 0
...
endif
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Preventing certain things from being committed in XCode Situation: I have a few things in my code repository that I only want to be in my own working copy, but I still want to be able to modify the rest of the codebase and do commits without putting in those certain things I mentioned. Is it possible to lock those down in some way so they do not go in with the rest of my commit? Right now XCode commits everything that was modified. I realize I could commit files individually but it would be nice to continue to use the global commit.
A: Why not try the svn:ignore property (about half-way down the page)?
A: Maybe you could change the status of files to locked, then commit them without locked files.
For SVN help, pls reference to http://svnbook.red-bean.com/en/1.5/index.html.
A: You should comment in "global-ignores" line in the configuration file located in ~/.subversion/config.
By this way you could ignore file types that you have given. I use the following set:
global-ignores = *.o *.lo .la ## .*.rej .rej .~ ~ .# .DS_Store *.mode1v3 *.pbxuser
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to call for a Maven goal within an Ant script? Is it possible to call or execute a Maven goal within an Ant script?
Say I have an ant target called 'distribute' and inside which I need to call a maven 'compile' goal from another pom.xml.
A: You may use a java task (this example is similar to @mateusz.fiolka answer but also works on Linux)
<target name="mvn-install">
<property environment="env" />
<path id="classpath">
<fileset dir="${env.M2_HOME}/boot">
<include name="plexus-classworlds-*.jar" />
</fileset>
</path>
<property name="mvn.mainclass" value="org.codehaus.plexus.classworlds.launcher.Launcher" />
<java classname="${mvn.mainclass}" classpathref="classpath" fork="true" failonerror="true">
<jvmarg value="-Dclassworlds.conf=${env.M2_HOME}/bin/m2.conf" />
<jvmarg value="-Dmaven.home=${env.M2_HOME}" />
<arg value="install" />
</java>
</target>
tested with maven 3.0.5
A: Here there is a complete solution:
<target name="mvn_windows_setup" if="isWindows">
<property name="mvn.executable" value="cmd" />
<property name="mvn.args" value="/c" />
</target>
<target name="mvn_unix_setup" if="isUnix">
<property name="mvn.executable" value="sh" />
<property name="mvn.args" value="-c" />
</target>
<target name="run-mvn-goals" depends="mvn_windows_setup, mvn_unix_setup">
<exec dir="${basedir}" executable="${mvn.executable}">
<arg line="${mvn.args} 'mvn ${p_goals}'" />
</exec>
</target>
<!-- EXAMPLES OF HOW TO USE -->
<!-- let's say you want to run mvn clean install -->
<target name="mvn-clean-install">
<antcall target="run-mvn-goals">
<param name="p_goals" value="clean install"/>
</antcall>
</target>
<!-- or maybe you want to clean, package but skipping tests -->
<target name="mvn-clean-package-notests">
<antcall target="run-mvn-goals">
<param name="p_goals" value="clean package -DskipTests"/>
</antcall>
</target>
The output is something like this...
Buildfile: /home/.../build.xml
deploy-complete:
deploy-complete:
mvn_windows_setup:
mvn_unix_setup:
run-mvn-goals:
[exec] [INFO] Scanning for projects...
[exec] [INFO]
[exec] [INFO] ------------------------------------------------------------------------
[exec] [INFO] Building wpm 0.0.1-SNAPSHOT
[exec] [INFO] ------------------------------------------------------------------------
[exec] [INFO]
[exec] [INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ wpm ---
...
...
...
[exec] [INFO] BUILD SUCCESS
[exec] [INFO] ------------------------------------------------------------------------
[exec] [INFO] Total time: 28.817 s
[exec] [INFO] Finished at: 2016-11-14T14:01:34-05:00
[exec] [INFO] Final Memory: 84M/872M
[exec] [INFO] ------------------------------------------------------------------------
BUILD SUCCESSFUL
Total time: 31 seconds
A: Since none of the solutions worked for me, this is what I came up with:
Assuming you are running on Windows:
<target name="mvn">
<exec dir="." executable="cmd">
<arg line="/c mvn clean install" />
</exec>
</target>
or on UNIX:
<target name="mvn">
<exec dir="." executable="sh">
<arg line="-c 'mvn clean install'" />
</exec>
</target>
or if you want it to work on both UNIX and Windows:
<condition property="isWindows">
<os family="windows" />
</condition>
<condition property="isUnix">
<os family="unix" />
</condition>
<target name="all" depends="mvn_windows, mvn_unix"/>
<target name="mvn_windows" if="isWindows">
<exec dir="." executable="cmd">
<arg line="/c mvn clean install" />
</exec>
</target>
<target name="mvn_unix" if="isUnix">
<exec dir="." executable="sh">
<arg line="-c 'mvn clean install'" />
</exec>
</target>
A: An example of use of exec task utilizing Maven run from the Windows CLI would be:
<target name="buildProject" description="Builds the individual project">
<exec dir="${source.dir}\${projectName}" executable="cmd">
<arg value="/C"/>
<arg value="${env.MAVEN_HOME}\bin\mvn.bat"/>
<arg line="clean install" />
</exec>
</target>
A: I used this answer from @Adam Siemion above, but I didn't want separate targets for running on Windows or Linux. Instead I just set the property near the top of my ant script:
<condition property="isAntRunningOnWindows">
<os family="windows" />
</condition>
Then in the middle of my script I use an if-then-else statement:
<if>
<equals arg1="${isAntRunningOnWindows}" arg2="true" />
<then>
<echo message="OS is Windows" />
<exec dir="." executable="cmd">
<arg line="/c mvn clean package" />
</exec>
</then>
<else>
<echo message="OS is Linux/Unix" />
<exec dir="." executable="sh">
<arg line="-c 'mvn clean package'" />
</exec>
</else>
</if>
A: I am using the following target to run maven clean, install and clean install goals. Works fine.
<project name="Maven run goals" basedir="."
xmlns:artifact="antlib:org.apache.maven.artifact.ant"
xmlns:rsel="antlib:org.apache.tools.ant.types.resources.selectors">
<target name="maven clean">
<artifact:mvn mavenHome="${maven.home}" fork="true">
<arg value="clean" />
</artifact:mvn>
</target>
<target name="maven install">
<artifact:mvn mavenHome="${maven.home}" fork="true">
<arg value="install" />
</artifact:mvn>
</target>
<target name="maven clean-install">
<artifact:mvn mavenHome="${maven.home}" fork="true">
<arg value="clean" />
<arg value="install" />
</artifact:mvn>
</target>
</project>
Your maven.home property should point to the maven home directory. For example,
<property name="maven.home" value="D:\\Downloads\\apache-maven-3.0.5"/>
A: You can also look at maven ant tasks which is now retired though as commented below. This allows you to run specific maven goals from within your ant build script. You can look at this SO question as well.
A: You can use the exec task and call mvn compile as a terminal command. This is not ideal since you won't have any control over the execution, but otherwise I don't think there is a way to execute a Maven goal.
A: Maven Ant Tasks github easy to run maven with goals form Ant.
Installation
Create a lib directory in the root of your project and place the maven-ant-tasks.jarbinaries, sonatype file inside it.
<?xml version="1.0" encoding="UTF-8"?>
<project name="maven" default="build" xmlns:artifact="antlib:org.apache.maven.artifact.ant">
<property environment="env" />
<!-- <get src="http://search.maven.org/remotecontent?filepath=org/apache/maven/maven-ant-tasks/2.1.3/maven-ant-tasks-2.1.3.jar" dest="lib/maven-ant-tasks-2.1.3.jar"/> -->
<path id="maven-ant-tasks.classpath" path="lib/maven-ant-tasks-2.1.3.jar" />
<typedef resource="org/apache/maven/artifact/ant/antlib.xml" uri="antlib:org.apache.maven.artifact.ant" classpathref="maven-ant-tasks.classpath" />
<record name="build.log" loglevel="verbose" action="start"/>
<target name="build" description="project build ant script">
<fail unless="env.MAVEN_HOME" message="Environment variable MAVEN_HOME was not found on your system!" />
<artifact:mvn mavenHome="${env.MAVEN_HOME}" fork="true">
<arg value="clean" />
<arg value="install" />
<arg value="-Pqa" />
</artifact:mvn>
</target>
</project>
Small information between these elements ant typedef vs taskdef.
*
*Typedef: Using a typedef declaration allows you to store the Ant Tasks' library anywhere you like (such as source control) and put it's location in the build file.
<typedef name="urlset" classname="com.mydomain.URLSet"/>
*Taskdef Adds a task definition to the current project, such that this new task can be used in the current project.
Using PropertyFiles.java task by adding it to taskdef externally.
<taskdef name = "propertyfiles"
classname = "org.apache.tools.ant.taskdefs.optional.PropertyFiles" />
All the taskdef are configured in apache-ant-1.9.4\lib\ant.jar\org\apache\tools\ant\taskdefs\defaults.properties properties files. But i have created an external class and placed inside jar file. But instead of adding entry in defaults.properties file externally informing the task by taskdef.
Second way, You can create a jar file, list all the tasksef in one properties file and refer the resource
antcontrib You can place the JAR in your Ant lib directory, and set classpath.
<taskdef resource="net/sf/antcontrib/antcontrib.properties">
<classpath>
<pathelement location="${env.ANT_HOME}/lib/ant-contrib-0.6.jar"/>
</classpath>
</taskdef>
A: From Thiagoh answer, I have to add this to make it work.
<condition property="isWindows">
<os family="windows" />
</condition>
<condition property="isLinux">
<os family="unix" />
</condition>
<target name="mvn_windows_setup" if="isWindows">
<property name="mvn.executable" value="cmd" />
<property name="mvn.args" value="/c" />
</target>
<target name="mvn_unix_setup" if="isLinux">
<property name="mvn.executable" value="sh" />
<property name="mvn.args" value="-c" />
</target>
<target name="run-mvn-goals" depends="mvn_windows_setup, mvn_unix_setup">
<exec dir="${basedir}" executable="${mvn.executable}">
<arg line="${mvn.args} 'mvn ${p_goals}'" />
</exec>
</target>
A: plexus seems to be an older solution for embedding Maven.
Take a look at the Apache's Maven Embedder project.
This article paragraph outlines embedding Maven into Java code, without a locally installed Maven executable.
A: This is an old post, but still relevant (for me, anyhow). I think things have changed since the original post. Turns out the solution is quite simple, and you don't need all the ant-maven integration fluff. It makes me wonder why this wasn't the answer 8 years ago, as I'm pretty sure it would have worked then as it does now. I should mention this is for Windows. You could probably tweak it to support Unix or both.
*
*Install maven for Windows
*Create an environment variable MAVEN_HOME that points to the base mvn install directory (e.g., C:\dev\apache-maven-3.6.3)
*Add this task to your build.xml:
<target name="mvnPackage" description="Creates war file">
<fail unless="env.MAVEN_HOME" message="Environment variable MAVEN_HOME was not found on your system!" />
<exec executable="${env.MAVEN_HOME}\bin\mvn.cmd">
<arg value="clean" />
<arg value="package" />
</exec>
</target>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
}
|
Q: WPF Toolkit: display a label above each line in LineSeries Chart I'm trying to display a label on a lineseries in a WPFToolkit chart. The result I'm looking for would be something like this:
LineSeries with labels
Is there a way to easily do this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Problem with $.each() in jQuery I want append some from array by jQuery.each and data hotel_id, number each hotel_id is 4, and this loop $.each(data[0].hotel_id,... }); run 4 times contents inside self, in case that there are or inserted in database rows residence_u and residence_p 3 times (each of they there are 3, not 4(like hotel_id)), when run the following code, this code not have error jus not work. if i remove codes $.each(info_ru.units,... }); and $.each(info_rp.start_date,... }); it worked: How can fix it?
See full my js code: [http://pastebin.com/jBWEDZrN][1]
This is summary from my js code in ajax call(url: 'get_gr',):
$.each(data[0].hotel_id, function (index, value) {
var $li = $('<li><input name="hotel_id[]" value="' + value.hotel_id + '" style="display:none;"></li>');
var $tooltip = $('<div class="tooltip"></div>').appendTo($li);
$li.appendTo('#residence_name');
var info_ru = data[0].residence_u[index];
$.each(info_ru.units, function (index, value) {
$tooltip.append(value + ' & ' + info_ru.extra[index] + ' & ' + info_ru.price[index] + '<br>');
});
var info_rp = data[0].residence_p[index];
$.each(info_rp.start_date, function (index, value) {
$tooltip.append(value + ' & ' + info_rp.end_date[index] + ' & ' + info_rp.price_change[index] + '<br>');
});
tool_tip()
});
This is output php code(url: 'get_gr',):
[{
"guide": null,
"hotel_id": [{
"hotel_id": ["1"]
}, {
"hotel_id": ["2"]
}, {
"hotel_id": ["3"]
}, {
"hotel_id": ["4"]
}],
"residence_u": [{
"units": ["hello", "how", "what"],
"extra": ["11", "22", "33"],
"price": ["1,111,111", "2,222,222", "3,333,333"]
}, {
"units": ["fine"],
"extra": ["44"],
"price": ["4,444,444"]
}, {
"units": ["thanks", "good"],
"extra": ["55", "66"],
"price": ["5,555,555", "6,666,666"]
}],
"residence_p": [{
"start_date": ["1111", "2222"],
"end_date": ["1111", "2222"],
"price_change": ["1111", "2222"]
}, {
"start_date": ["3333", "4444"],
"end_date": ["3333", "4444"],
"price_change": ["3333", "4444"]
}, {
"start_date": ["5555", "6666"],
"end_date": ["5555", "6666"],
"price_change": ["5555", "6666"]
}]
}]
Update:
I insert several(array) value with json_encode in one row from database table, now want echo they as order with jquery.
Output js code is this:
1 hello & 11 & 1,111,111 how & 22 & 2,222,222 what & 33
& 3,333,333, 1111 & 1111 & 1111 2222 & 2222 & 2222
2 fine & 44 & 4,444,444 3333 & 3333 & 3333 4444 & 4444 & 4444
3 thanks & 55 & 5,555,555 good & 66 & 6,666,666 5555 & 5555 & 5555 6666 & 6666 & 6666
4
A: You only have 3 elements in your residence_u and 2 in residence_p arrays, but 4 in the original hotels array. Could it be as simple as to check for a valid info_ru
var info_ru = data[0].residence_u[index];
if ( infor_ru != null ) {
$.each(info_ru.units, function (index, value) {
$tooltip.append(value + ' & ' + info_ru.extra[index] + ' & ' + info_ru.price[index] + '<br>');
});
}
before continuing with the each?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WCF Authentication for a Javascript (Sencha) web app I work on a mobile web app in Javascript(Sencha)/HTML5 with WCF Rest services that needs to use authentication to authenticate users from a custom (MySQL) database in order to customize services responses during the user session.
I search about WCF authentication and founded so many ways that i'am really lost to find the best way to answer my constraints...
Can i really authenticate my user from the WCF web service (with his username and password) and then keep a token or a cookie or whatever that can be used in the following request in order to identify my user and make my response according to that user ?
Thanks in advance for your help !
A: Authentication as you many know can be done in many ways. Username/password, Certificate etc. It really depends upon your requirement.
For e.g.
If you have a mobile application which is dealing with financial information for a user (such as Bank account) then I would use both user credentials as well as X509Certificates.
If you have an application which is public facing then you can get away with using just certificates (Just client certi).
If you have a B2B application (which I would doubt in this case) then you can use Asymantic certificates (Client and server) in which you will create Both Client and Server certifcates (X509) and give to the client and let the client manually install it on their client devices.
For the simplest senario you can start by try using username and password. So your client app will user username/password to authenticate with a WCF Service at server.
Follwing my give you a good starting point
http://msdn.microsoft.com/en-us/library/ms733131.aspx
http://www.codeproject.com/KB/WCF/CustomUserNamePassAuth2.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript convert huge float to string
Possible Duplicate:
How to avoid scientific notation for large numbers in javascript?
Javascript: how to avoid scientific notation when displaying large unumber
I have this code:
var f = 1000000000000000000000; // 1e+21
var fstr = f.toString(); // return "1e+21"
But I don't need scientific number representation. I want to get "1000000000000000000000" in 'fstr' variable. How I can get it?
A: You can find an util script here:
http://snippets.dzone.com/posts/show/2206
There is also a short example at the bottom of the page.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: not able to load a view when I disable javascript rails 3 Here is my controller code:-
def image_test
respond_to do |format|
format.js {render :layout => false}
format.html {redirect_to image_test_path}
end
end
I have got a partial by the name of _image_test.html.erb and and a simple view image_test.html.erb
In my routes I have done this:-
match "/image_test", :to => "/index#image_test"
It works fine when the javascript is enabled in the borwser however when I disable the javascript I want it to redirect me to my image_test.html.erb file. Instead I get a no route match error.
Please help me with this.
Thanks,
A: I created a workaround for this solution which is giving the desired result of redirecting to another page if javascript is disabled in a browser but I do not know if this is the rails way.
I created empty action corresponding view for those actions and redirected to those views in case javascript is disabled.
Here is an example of what I did :-
def javascript_enabled_view
respond_to do |format|
format.js {render :layout => false}
format.html {redirect_to :action => "javscript_disabled_view"}
end
end
I have got a corresponding js.erb file and the partial for the above action which will work if javascript is enabled in the browser.
def javascript_disabled_view
end
I have got the corresponding html.erb file which will work in case javascript is disabled in the browser.
Thanks,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: RewriteRule for the same file which is currently targeted I have a file like
www.domain.com/test.php
I want to write a rule that when ever this is called i am sending an argument to this file but I don't want them to show in the URL I.E. when the above path is in the browser the actual rule should be:
www.domain.com/test.php?state=yes
What should be the .htaccess rule for this?
Currently i have in my .htaccess
RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC]
RewriteRule ^test\.php$ /test.php?view=index [NC,L]
But this is throwing a 500 server error???
A: I don't get a 500 error, what else do you have in your .htaccess?
Here's what you can use:
RewriteEngine on
RewriteBase /
RewriteRule ^test\.php test.php?view=index [NC,L,QSA]
The QSA flag was missing:
When the replacement URI contains a query string, the default behavior of RewriteRule is to discard the existing query string, and replace it with the newly generated one. Using the [QSA] flag causes the query strings to be combined.
Consider the following rule:
RewriteRule /pages/(.+) /page.php?page=$1 [QSA]
With the [QSA] flag, a request for /pages/123?one=two will be mapped to /page.php?page=123&one=two. Without the [QSA] flag, that same request will be mapped to /page.php?page=123 - that is, the existing query string will be discarded.
source: http://httpd.apache.org/docs/current/rewrite/flags.html#flag_qsa
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Keep a view alive while switching activity I created a game, where I rotate through multiple activitys. Each activity stays just for a few seconds. Now I should add ads to the game. Since it doesn't make sense if the ad refreshes after just a few seconds I have to create a view which stays alive the whole time even if I start a new activity.
Since a view is bind to an activity (?) it might not be possible. So I wonder wether there is another solution to keep the adView alive while the content views are rotating.
Thanks in advance.
Edit:
Here is a simple Activity which is part of the activity cycle:
public class Punish extends ActivityWithSound implements OnClickListener {
@SuppressWarnings("unused")
private final String TAG = "Punish";
private RelativeLayout buttonContainer;
private ImageView bgImg;
private TextView nameTxt;
private TextView questTxt;
private Button mainMenuBtn;
private Button okBtn;
private Bundle bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
bundle = getIntent().getExtras();
if(bundle == null)
bundle = StbApp.getTempBundle();
setContentView(R.layout.quest);
setupView();
super.onCreate(savedInstanceState);
}
@Override
protected void onResume() {
soundtrack.startFX(R.raw.fx_execution);
super.onResume();
}
@Override
protected void onPause() {
StbApp.getTempBundle().putInt(Victim.VICTIM, bundle.getInt(Victim.VICTIM));
soundtrack.stopAllFX();
super.onPause();
}
@Override
public void onClick(View view) {
if (view == mainMenuBtn){
//TODO Continue Function
Intent intent = new Intent(this, TitleScreen.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
StbApp.setContinueBtn(true);
StbApp.getLastActivity().setClass(this, Punish.class);
startActivity(intent);
}
if (view == okBtn){
if (StbApp.getPenalty() == PenaltyType.LEAVE){
StbApp.getPlayer().remove(bundle.getInt(Victim.VICTIM));
StbApp.setNumberOfPlayer(StbApp.getNumberOfPlayer()-1);
}
if (StbApp.getNumberOfPlayer() == 2 && StbApp.getPenalty() == PenaltyType.LEAVE)
startActivity(new Intent(this, GameOver.class));
else {
startActivity(new Intent(this, Round.class));
}
}
}
@Override
public void onBackPressed() {
return;
}
private void setupView() {
float textSize = (float) getResources().getDimension(R.dimen.standard_text_size)/getResources().getDisplayMetrics().scaledDensity;
buttonContainer = (RelativeLayout) findViewById(R.id.container_button);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) findViewById(R.id.container_button).getLayoutParams();
params.setMargins(0, 0, 0, (int) (StbApp.AdHeight*1.3));
buttonContainer.setLayoutParams(params);
bgImg = (ImageView) findViewById(R.id.imgv_girl);
Log.d(TAG, "PlayerSize " + StbApp.getPlayer().size());
nameTxt = (TextView) findViewById(R.id.text_victim_name);
Log.d(TAG, "PlayerSize " + StbApp.getPlayer().size());
Log.d(TAG, "PlayerIndex bundle.getInt(Victim.VICTIM) " + bundle.getInt(Victim.VICTIM));
nameTxt.setText(StbApp.getPlayer().get(bundle.getInt(Victim.VICTIM)).getName());
nameTxt.setTextSize(textSize);
questTxt = (TextView) findViewById(R.id.text_quest);
switch (StbApp.getPenalty()) {
case LEAVE:
questTxt.setText(getResources().getString(R.string.punish_leave));
break;
case DRNK:
questTxt.setText(getResources().getString(R.string.punish_drink));
break;
case UNDRESS:
questTxt.setText(getResources().getString(R.string.punish_undress));
break;
}
questTxt.setTextSize(textSize);
mainMenuBtn = (Button) findViewById(R.id.button_mainmenu);
mainMenuBtn.setOnClickListener(this);
okBtn = (Button) findViewById(R.id.button_ok);
okBtn.setOnClickListener(this);
}
@Override
protected void onDestroy() {
if (bgImg.getDrawable() != null){
bgImg.getDrawable().setCallback(null);
bgImg.setImageDrawable(null);
}
super.onDestroy();
}
What I need would be an alternative for onDestroy, onPause and onResume.
A: A solution could be using a ViewFlipper/ViewSwitcher instead of jumping activities and then placing the adsView over or under the ViewFlipper/ViewSwitcher - It will however probably require quite a large re-write of your app.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Regular Expression for email for a specific domain name This is my code:
<asp:RegularExpressionValidator ID="regexEmail"
runat="server" ValidationExpression="(\w+@[test]+?\.[com]{3})"
ErrorMessage="Please Enter Valid Email Id"
ControlToValidate="txtEmailAddress" />
which is not working. But my problem does not end there. I would also like to know how to validate only characters in the username, and not numbers and special characters.
Please if anybody could help with this code. Thanks in Advance.
A: ^[a-zA-Z]+@yourdomain\.com$
should do the trick
A: At first I think there is a miss understanding of the square brackets. With [com]{3} you are createing a character class and match 3 characters out of this class, that means this will match com (I think as you wanted), but also ccc, cmc and so on.
Similar for [test]+?, this matches at least 1 character from t, e and s
When you say:
validate only characters in the username, and not numbers and special
characters
I think you mean only letters? Or only ASCII letters?
What you meant is probably
(\w+@test\.com)
\w is a character class that contains A-Za-z0-9 and _ (and maybe anything thats a letter in unicode, I am not sure). If you want only ASCII characters then create your own character class with [A-Za-z], if you want to allow any letter use the Unicode property \p{L}
Something like this
@"^(\p{L}+@test\.com)$"
A: [test] is probably not what you want. It's equivalent to [tes] and means 't' or 'e' or 's'.
Did you try something like:
^[a-zA-Z]+@.*\.com$
This will validate to emails of the form xxx@xxx.com
As C# literal this is "^[a-zA-Z]+@.*\\.com$".
A: MSDN has an article about email validation.
http://msdn.microsoft.com/en-us/library/01escwtf.aspx
cheers
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Feed dialog generating errors with iOS SDK UPDATE: This problem was resolved when facebook fixed their service.
I'm trying to get the feed dialog to work for sharing with facebook. I had it all working before with the old, deprecated API and SDK, but have just moved to using the current iPhone SDK and am trying an example directly from the documenation here;
I keep getting the error, "Error with publishing" "There was a problem generating the Feed story from the provided data" and I cannot see what I'm doing wrong. Note that I have taken out the message parameter as it was deprecated in July, but I get the same problem whether or not that parameter is present.
Facebook *facebook = [[Facebook alloc] initWithAppId:kFacebookAppId andDelegate:self];
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
kFacebookAppId, @"app_id",
@"https://developers.facebook.com/docs/reference/dialogs/", @"link",
@"http://fbrell.com/f8.jpg", @"picture",
@"Facebook Dialogs", @"name",
@"Reference Documentation", @"caption",
@"Using Dialogs to interact with users.", @"description",
nil];
[facebook dialog:@"feed" andParams:params andDelegate:self];
Can anyone see what I might be doing wrong?
Thanks!
A: The page http://developers.facebook.com/live_status reports the issue today at 16:49 (GMT+1)
To follow the issue : https://developers.facebook.com/bugs/295765603772094
A: I don't think you are doing something wrong.
Just experienced the same problem with with my working app.
Most likely an issue on the side of facebook
A: You can use direct REST API or Graph API calls that are working now.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: Deploying *.war application with Java Web Start (JNLP) I want to rollout a web application (*.war) with Java Web Start (JNLP). My starting condition is that I have a running configured Tomcat 6.0 server available at the client.
Normal deployment at tomcat is pretty clear to me. Just put the *.war file to the webapps folder and restart tomcat - finished.
If I want to the same with JNLP it looks somehow complicated. I was thinking about the following JNLP:
<?xml version="1.0" encoding="utf-8"?>
<!-- JNLP File for JimageConnect.com JTwacker Application -->
<jnlp codebase="file:///local_installer">
<information>
<title>War deployment</title>
<vendor>Vendor</vendor>
<description>long </description>
<description kind="short">short</description>
<offline-allowed/>
</information>
<security>
<all-permissions/>
</security>
<resources>
<jar href="deployment.jar"/>
<j2se version="1.6+" href="http://java.sun.com/products/autodl/j2se"/>
</resources>
<application-desc main-class="com.vendor.deployment.Deploy" />
Where deployment.jar holds:
-) the *.war file which should be deployed
-) everything which is needed to use command line redeployment of web application descibed at http://tomcat.apache.org/tomcat-6.0-doc/manager-howto.html#Executing_Manager_Commands_With_Ant
-) the class Deploy which reads the *.war as Stream from the classloader and executes an undeployment/deployment for tomcat.
That sollution should work but it looks hand made and somehow ugly. Is there a better solution available?
A: I solved the problem by creating a customer installer which installed my Tomcat server and even handled UAC correctly.
A second tooling deployed my application if needed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Autorenewable Subscriptions won't be autorenewed Sorry for that millionth question on autorenewable subscriptions, but i don't get it.
I've done everything as describet in Apples In-App Purchase Guidelines but it didn't solve the problem.
My problem is that i have created autorenewable subscriptions but they won't be autorenewed.
I've create a Payment Transaction Observer class, which implements the SKPaymentTransactionObserver interface. This class will be installed as a paymentObserver at Application startup in the viewDidLoad: method.
PaymentTransactionObserver *observer = [[PaymentTransactionObserver alloc] init];
[[SKPaymentQueue defaultQueue] addTransactionObserver:observer];
In the paymenttransactionobserver i have the paymentQueue:updateTransactions method: (same as describet in Apple's documentation)
*
*(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
for (SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchased:
[self completeTransaction:transaction];
break;
case SKPaymentTransactionStateFailed:
[self failedTransaction:transaction];
break;
case SKPaymentTransactionStateRestored:
[self restoreTransaction:transaction];
break;
default:
break;
}
}
When i buy a autorenewable product, the product will successfully be purchase.
But it will never be autorenewed. I thought of, that the transaction observer, somehow will get deallocated, but it won't (Otherwhise, i would be notified by the debugger). I also though, i did remove the observer but it will never be removed.
I used the debugger to ensure, that the updateTranscations: method will get called, but nothing. When i buy a test product (in sandbox-mode) with autorenewal time of one week, the method should get called after 3 minutes, but it wont.
What am i doing wrong?
Can anybody help?
Br Nic
A: If a subscription is autorenewed, the transaction won't pass the paymentQueue:updateTransactions method. The renew just happens on the Store. If you want to test for it you have to either:
*
*Revalidate the receipt on your application server, if you store the receipt there.
*Revalidate the receipt on ur iOS client
(http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/StoreKitGuide/VerifyingStoreReceipts/VerifyingStoreReceipts.html#//apple_ref/doc/uid/TP40008267-CH104-SW1)
In order to avoid testing for an autorenew each launch/activation you should store the endDate of the subscription period to test for a renew afterwards.
Also see:
http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/StoreKitGuide/RenewableSubscriptions/RenewableSubscriptions.html#//apple_ref/doc/uid/TP40008267-CH4-SW4
However, there seems to be a bug in the sandbox. Subscriptions sometimes get renewed, sometimes not. Hard to test....
A: Auto-renewals only get posted to your app's purchase queue on app launch or when it cycles back from being backgrounded. Try clicking the home button and then returning to your app.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How did malloc and calloc end up with different signatures?
Possible Duplicate:
Why calloc takes two arguments while malloc only one?
There are lots of resources describing the difference in functionality between malloc and calloc, but I can't easily find one that describes the history behind the differing function signatures:
void *calloc(size_t nmemb, size_t size);
void *malloc(size_t size);
Of course, the size in the former is the size for each member. Maybe the idea was that multiple-of-the-page-size member size callocs could be done lazily via the operating system?
(I can make up reasons as well as the next guy -- no accepted answers without cited sources. :-) )
A: This is somewhat open to interpretation of the language used in the C specification.
The language here seems very carefully chosen - malloc is defined in section 7.20.3.3 as:
The malloc function allocates space for an object whose size is
specified by size and whose value is indeterminate.
Earlier an object was defined in section 3.14 as:
region of data storage in the execution environment, the
contents of which can represent values
calloc on the other hand is defined in 7.20.3.1 as:
The calloc function allocates space for an array of nmemb objects,
each of whose size is size. The space is initialized to all bits
zero.
This should make it obvious. The difference between calloc and malloc is that calloc allocates memory for an array of n conceptual objects, although in practice this is no different from a call to malloc which allocates space for 1 conceptual object of size (n * size).
So the next question is... what is the need for the distinction between space for an array of objects and space for one large object?
From a programmers perspective the two function calls are just asking for different things. One is asking for a big hunk of memory to be assigned - and I'll deal with it. The other is saying - I want an array of n things which are of this size, give me some memory which I could use for this array, and zero it - because in most implementations I can make good assumptions about what zeroed memory means.
The fact that you are trying to use it as malloc + zeroing is, by my reading of the specification, a misunderstanding about the purpose of the function.
They ended up with different signatures because they do different things.
Some cute side thoughts... A trivial malloc implementation can look like:
#define malloc(x) (calloc(1, x))
It is also fun to note that if my NULL pointer representation is not zeroed, then calloc won't return me an array of NULL pointers. Better yet, if I design an integer representation in which zeroed memory is not ((int)0), calloc won't return me an array of 0s.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
}
|
Q: How do I remove duplicate entries in this T-SQL query containing LEFT OUTER JOIN I am having issues taking out duplicate entries from this query containing multiple LEFT OUTER JOINs
SELECT s.Category,
SUM(spons.SPONS) AS SPONSOREDAMT,
SUM(priv.PRIV) AS PRIVATEAMT FROM (SELECT ID AS ID,
Name AS Category FROM dbo.ServicesTable) s
LEFT OUTER JOIN (SELECT DISTINCT ( ServiceId ) AS ServiceId,
DateCreated,
SUM(SPONSORAMT) AS SPONS
FROM dbo.SponsorMonthlyBill
GROUP BY ServiceId,
DateCreated) spons
ON ( s.ID = spons.ServiceId )
LEFT OUTER JOIN (SELECT DISTINCT ( ServiceId ) AS ServiceId,
DateCreated,
SUM(PRIVATEAMT) AS PRIV
FROM dbo.PrivateMonthlyBill
GROUP BY ServiceId,
DateCreated) priv
ON ( s.ID = priv.ServiceId )
AND ( MONTH(priv.DateCreated) = MONTH('2011-08-04') )
GROUP BY s.Category,
spons.SPONS,
priv.PRIV
If I make last line look like this:
GROUP BY s.Category
instead of what its now, I'll have the duplicate entries adding up. If there are more than double entries, all 3 or 4 or more get added up. So how go about this.
Scorpi0 gave an answer which worked but needs some extra modification. This was the modification I made to it:
SELECT s.Name AS Category,
SUM(spons.SPONS) AS SPONSOREDAMT,
SUM(priv.PRIV) AS PRIVATEAMT, SUM(spons.SPONS) + SUM(priv.PRIV) as
TOTAL,spons.DateCreated
FROM dbo.ServicesTable s
LEFT OUTER JOIN (SELECT ServiceId,DateCreated,
SUM(SPONSORAMT) AS SPONS
FROM dbo.SponsorMonthlyBill
GROUP BY ServiceId,DateCreated) spons
ON ( s.ID = spons.ServiceId )
LEFT OUTER JOIN (SELECT distinct ServiceId,
SUM(PRIVATEAMT) AS PRIV
FROM dbo.PrivateMonthlyBill
GROUP BY ServiceId
) priv
ON ( s.ID = priv.ServiceId )
GROUP BY s.Name,spons.DateCreated
I know it introduced the duplicates again but how can keep the DateCreated out of GROUP BY and still access it in the main SELECT clause? Please keep in mind that this is a View and there are some rules that it insists must be followed.
A: Your duplicates are coming from your useless group by DateCreated.
Try with this query, it should give you the right results:
SELECT s.Name AS Category,
SUM(spons.SPONS) AS SPONSOREDAMT,
SUM(priv.PRIV) AS PRIVATEAMT
FROM dbo.ServicesTable s
LEFT OUTER JOIN (SELECT ServiceId,
SUM(SPONSORAMT) AS SPONS
FROM dbo.SponsorMonthlyBill
GROUP BY ServiceId) spons
ON ( s.ID = spons.ServiceId )
LEFT OUTER JOIN (SELECT ServiceId
SUM(PRIVATEAMT) AS PRIV
FROM dbo.PrivateMonthlyBill
WHERE MONTH(DateCreated) = MONTH('2011-08-04')
GROUP BY ServiceId
) priv
ON ( s.ID = priv.ServiceId )
GROUP BY s.Name
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Double status bar when showing modal view controller I have a modal view, which I show after application launch. The problem now is that the Modal view leaves 20 pixels for the status bar (See picture)
double status bar http://k.minus.com/j1vKSpCmFJXie.png
This is what my MyViewController looks like in Interface builder:
IB-Layout http://k.minus.com/jbyZPICtsq0sMy.png
In the viewDidLoadcallback I set the view to my WelcomeVC's view like this:
- (void)viewDidLoad{
[super viewDidLoad];
self.view = self.navController.view; // navController is the outlet to my NavigationController in IB
}
I open the modal like this:
MyViewController *welcomeVC = [[MyViewController alloc]init];
[self presentModalViewController:welcomeVC animated:YES];
[welcomeVC release];
How do I get rid of this space between the view and the status bar?
A: I'm not sure if I understood your question correctly.
Are you calling your modal view from within your navController?
If so, the problem could be that a child viewController is calling the modal, while the parent should, meaning the rootViewController, who is hosting your navController -- not the navController itself.
If you navController is calling the modal view -- just an opinion - why do you need to call a modalView? push it as a view into the stack, that is more compatible with UINavigationController environment.
A: I figured out that it does not make a lot of sense to add the NavigationController directly to the viewcontroller, since the NavigationController should rather be defined outside the ViewController, since my ViewController does not neccesarily know whether it will be displayed inside a NavigationController or a modal popup or maybe even a Popover on an iPad.
So what I've done is I created two separate ViewControllers for both the Welcome view and the Plans view. This means that they are more universally usable also for cases when only either of the views is displayed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to remove the 5s delay of the Silverlight Unit Testing Framework I use the Silverlight Unit Testing Framework and it works pretty well.
However every time I launch my tests, I have to wait 5 seconds or click the "No, run all tests" button.
Is there a way to skip this step that I don't need?
A: In the App.xaml.cs:
Replace
RootVisual = UnitTestSystem.CreateTestPage();
With
UnitTestSettings settings = UnitTestSystem.CreateDefaultSettings();
settings.StartRunImmediately = true;
settings.ShowTagExpressionEditor = false;
RootVisual = UnitTestSystem.CreateTestPage(settings);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Binary Typing Problem I am trying to work with the Haskell Bson and I want to save and load them. The saving seems to be no problem, but I get a typing error with the Binary.get functions.
Here's my code:
{-# LANGUAGE GeneralizedNewtypeDeriving, TypeSynonymInstances, FlexibleInstances #-}
module Database.Axiom where
import Data.Bson (Document, Field)
import Data.Bson.Binary (putDocument, getDocument)
import Data.Binary as B (Binary(..), decodeFile, encodeFile)
import Control.Monad (liftM2)
instance Binary Document where
put = putDocument
get = getDocument
data Collection = Collection {
collectionName :: ByteString,
collectionDocs :: [Document]
}
instance Binary Collection where
put (Collection name docs) = B.put name >> B.put docs
get = liftM2 Collection B.get B.get -- < Here is the type error
Which leads to this error:
Database/Axiom.hs:24:39:
Overlapping instances for Binary [Field]
arising from a use of `B.get'
Matching instances:
instance Binary a => Binary [a] -- Defined in Data.Binary
instance Binary Document -- Defined at Database/Axiom.hs:13:10-24
In the third argument of `liftM2', namely `B.get'
In the expression: liftM2 Collection B.get B.get
In an equation for `get': get = liftM2 Collection B.get B.get
The problem is that Document is merely a synonym of [Field]. But I need an instance for Binary Document, as there are no functions to serialize a single Field. And moreover, BSON does not export any instances for Binary Field, so I am completely confused why this error happens in the first place.
I tried it with strict type declaration and then to use a self made get method, but a get :: [Document] only works nicely when there's a get :: Document method.
So, anyone can help me, perhaps?
A: Altough a little subjective, I think the cleanest and most robust way to fix is is to add a newtype for Document. Something like:
import Control.Applicative ((<$>))
import Data.ByteString (ByteString)
import Data.Bson (Document, Field)
import Data.Bson.Binary (putDocument, getDocument)
import Data.Binary as B (Binary(..), decodeFile, encodeFile)
import Control.Monad (liftM2)
newtype CollectionDoc = CollectionDoc {unCollectionDoc :: Document}
instance Binary CollectionDoc where
put = putDocument . unCollectionDoc
get = CollectionDoc <$> getDocument
data Collection = Collection {
collectionName :: ByteString,
collectionDocs :: [CollectionDoc]
}
instance Binary Collection where
put (Collection name docs) = B.put name >> B.put docs
get = liftM2 Collection B.get B.get
should work. In addition, newtype wrappers are completely optimized away, so there is no overhead at runtime.
A: Don't define the instance for Document; just call getDocument instead of B.get (which I see no need for qualifying with the B.) in your get definition for Collection.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: in a xcode webview: how to get the name or id of input tag selected? Inside an xcode application, I have an webview with a variable number of text input.
There is a method to get to xcode the attribute "name" or "id" when I selected the field?
My problem is that I don't know how to pass the name or id of selected field to xcode.
A: Check this out :
NSString *string =
[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('your_id_here');"];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to use Apple Header doc for auto-generated documentation for iOS development? I have used Doxygen tool for document generation. But later on I have come to know that Apple itself provides "Documentation Set Guide".
Here is the reference link:
http://developer.apple.com/library/mac/#documentation/DeveloperTools/Conceptual/Documentation_Sets/000-Introduction/introduction.html#//apple_ref/doc/uid/TP40005266-CH1-SW1
Is there anyone aware about this - how to use this and all? Whether it would be useful for autogenerated document creation?
Thanks in advance,
Mrunal
A: 'docsets' are merely a way to package documentation and show it in XCode.
Doxygen has support for docsets, see
http://developer.apple.com/library/mac/#featuredarticles/DoxygenXcode/_index.html
and
http://www.duckrowing.com/2010/03/18/documenting-objective-c-with-doxygen-part-i/ and
http://www.duckrowing.com/2010/03/18/documenting-objective-c-with-doxygen-part-ii/
If you want a tool that mimics Apples output (and care less about the features provided by doxygen) you could have a look at appledoc http://www.gentlebytes.com/home/appledocapp
A: Apple has it's own documentation generation tool. It's called HeaderDoc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Regex matching of simple expression I'm new to regex and can't figure out how to match the following in C# using Regex.Matches
left -> right
I tried "(\w) -> (\w)" but I think I'm way off.
A: Not way off, you need:
(\w+) -> (\w+)
I would recommend this guide for learning regex.
A: Match m = Regex.Match("left -> right", @"(\w+) -> (\w+)");
Console.WriteLine(m.Groups[1]); //left
Console.WriteLine(m.Groups[2]); //right
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Very slow java application start up I have a very strange problem. My java application is starting up very slow. Here is a snippet of code:
public static void main(String[] args) {
System.out.println("Is this going to be printed really fast?");
if (args.length == 0) {
//other code below
The thing is even the println statement isn't print it instantly. I tried remote profilling - to no avail the JVM apparently doesn't bootstrap fast enough. I tried setting a breakpoint on the println and then remotely connecting with a debugger - the breakpoint is not hit for some minutes. My JVM version:
java -Xmx120m -version
java version "1.6.0_14"
Java(TM) SE Runtime Environment (build 1.6.0_14-b08)
Java HotSpot(TM) 64-Bit Server VM (build 14.0-b16, mixed mode)
My os is: Linux 2.6.27.45-lustre-1.8.3.ddn3.3 #1 SMP Tue Oct 19 15:02:53 BST 2010 x86_64 GNU/Linux and I have no static classes.
The way I invoke my application - java -Xmx120m -jar /path/to/app. If I had a bug in the code - I would understand - expensive operation, flaky logic - whatever. But the first statement after the main class and having such slow start I don't think it is normal.
A: Are there big static classes initialized in your code? They are executed before the first line of main. For example, the following code will output "Bark" first and "Are we done barking now?" second.
public class Example
{
static Woof w = new Woof();
public static void main( String[] args )
{
System.out.println("Are we done barking now?");
}
}
class Woof
{
Woof()
{
System.out.println("Bark");
}
}
Note that this only happens when the constructor is explicitly called.
A: The "main" method isn't necessarily the first code executed.
Static initialization code is executed first when classes are loaded, so it's possible that some of this static initialisation code is taking a long time to run.
A: If you think it is slow, your very first action is to quantify it.
For example, if the command will execute and finished almost immediately, you can use the "time" command to the total time for the command from loading start to finish.
Example:
$ time java -cp . MyClassInTrouble
Assuming that, the problem in question is simple enough, but you still experience slow startup. You can see strace to see the a break down at system call level and get a easy feeling on how much time is spent on the JVM startup (instead of your program).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to print time in micro seconds using ctime() function? HI how to print time in macro second also with the use of following function in c++, I am using,
time_t rawtime;
time(&rawtime);
std::cout<<"Cuuent TIme is :: "<< ctime(&rawtime)<< std::endl;
Above code will give me only hours, minutes and second. I also need the micro seconds.
Any suggestion how to get time with micro seconds also?
A: I used following code to get time in H,M,S,mS:
char timeBuf [256];
struct timeval tv;
struct timezone tz;
struct tm *tm;
gettimeofday(&tv, &tz);
tm=localtime(&tv.tv_sec);
sprintf (timeBuf, "%02d:%02d:%02d:%03ld",tm->tm_hour, tm->tm_min, tm->tm_sec, (tv.tv_usec/1000) );
A: BSalunke, look at this piece of code. Includes the uSeconds and the time_t structure you were using.
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main( int argc, char **argv )
{
struct timeval timeValue;
long uSeconds;
if ( gettimeofday( &timeValue, NULL ) == 0 )
{
// This is what you have:
time_t time = timeValue.tv_sec;
// This is what you are looking for:
printf( "Current milliseconds: %ld\n", timeValue.tv_usec );
return EXIT_SUCCESS;
}
else
return EXIT_FAILURE;
}
A: Two options:
*
*gettimeofday()
*clock(...)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: returning a reference fom a local (within function) variable from a function back to the caller my Q is quite similar to these, but not exactly the same to:
Returning const reference to local variable from a function
Returning function-local variable as reference
I have a bit of code that is used to parse an xml file.
what's basically happening is that a local variable is passed by reference OUT of the function using the return statement. To be more precise:
ezxml_t ezxml_parse_fd(int fd){
ezxml_root_t root;
//DO STUFF
return &root->xml;
}
the caller is the following
ezxml_t xml = ezxml_parse_fd(fd);
Well, the thing compiles and works (gcc)... but I have always known that a local variables are destroyed once their scope no longer exists... i'm confused
A: The local variable is not "passed out by reference", because that would mean return &root;, which is not what your code says.
Rather, a pointer to some other, unrelated variable, which you didn't care to show us, is returned, and we should assume that the code was correctly written so that that pointer points to some dynamically allocated memory which will remain valid.
A: Once the function returns, function stack is unwound & references to function-local variables are invalid. You may get away with it for now, but don't rely on it!
Why not pass an output parameter to the function to store the value? Maybe, on these lines:
void ezxml_parse_fd(int fd, ezxml_t *parse_value)
{
ezxml_root_t root;
//DO STUFF
*parse_value = &root->xml;
return;
}
...
ezxml_t xml;
ezxml_parse_fd(fd, &xml);
If you are using gcc there is a good chance that you might have seen a warning message "warning: function returns address of local variable" Please do pay attention to compiler warning! It is only trying to help you (most of the times) :)
Hope this helps!
A: yes, the local variables are destroyed already, but your reference points to the place in memory that hold last assigned value. The place where your variable was placed. And it will work in most cases in the single threaded environment for simple types.
But when you allocate on the stack some object with destructor, the destructor will be called just when the execution of block (in your case -- function) will be finished. So outside the function you have a reference to destroyed object.
Shortly: don't do this :-)
A: In C - that is probably very wrong.
Please tell us what ezxml_t is and what root->xml is.
My guess is that ezxml_t is automatically casted to by the pointer to root->xml that you return.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to detect a level=2 memory warning in iOS? Apple defines lev=1 and lev=2 memory warnings as very different (one is "hmm. not much memory around. Be careful", the other is "I am about to kill a process, you have 5 ... 4 ... 3 ...")
...but how do you find out programmatically which one you've received?
I have an iPad app which processes images with specialist tools, and lev=1 memory warnings are inevitable - even processing an image in small pieces, it still uses up a lot of memory just to display all the GUI etc.
I get lev=1 ALL THE TIME and there's literally nothing I can do about it.
lev=2 memory warnings are a very different matter. If I get a lev=2 that usually means that there's some background app taking up a lot of memory, or that something the user has done has bloated memory - and I need to take emergency action to prevent me getting killed. There are things that I can do - but ALL of them are bad for the user (e.g. remove all GUI, wait a couple of seconds, then reload it).
So ... I need two different code paths inside "didRecieveMemoryWarning": one for lev=1 warnings, and one for lev=2 warnings.
EDIT: some info on warning levels: iPhone OS Memory Warnings. What Do The Different Levels Mean?
NB: Apple frequently "doesn't document" things. If we as developers only stuck to the documented information, and the bug-free parts of the API, then many (most?) of the boundary-pushing apps wouldn't exist until several iOS releases later. Instead, we work around the bugs, and we work out what's actually happening where Apple fails to document it.
EDIT2: ...looking into the linked header file, looks like that's got the underlying private function Apple uses to find out which level is current: "OSMemoryNotificationLevel OSMemoryNotificationCurrentLevel(void)" - but I guess there's no way we could get this past Apple Submission :( ?
A: I don't think the warning level is made available to applications but -- and I know this isn't what you want to hear -- that doesn't really matter. Just because the OS has two different levels of memory warning does not mean that you should do different things at each level and hope that other applications do the Right Thing.
The documentation says:
It is strongly recommended that you implement this method. If your
application does not release enough memory during low-memory
conditions, the system may terminate it outright.
There is no talk of "be careful" or "about to kill." That may be what currently happens, but is it the same in iOS5? Or in later versions? It's pretty dangerous to make those kinds of assumptions.
I think you need to consider optimising your memory usage. There's almost always a way to optimise images, release cached/intermediate data, more efficiently use autorelease pools, smaller/more efficent data structures. You don't say what techniques you're using currently so it's difficult to be specific.
A: An alternative approach that I have NOT TRIED but might work: Capture the output of Apple's system logger (ASL), look for the lev2 warning string.
Assuming Apple is actually using the ASL (which they might not be!) you could try following the instructions here: http://www.cocoanetics.com/2011/03/accessing-the-ios-system-log/ - which show how to access the ASL using Apple public API's.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Left join resulting in null rows for column with no null rows This has me confused, I'm getting NULL columns for this query even though the table movie_image doesn't have any NULL values in the column mi.filename.
SELECT m.*, mi.filename, COUNT(p.movieid) AS publicationsCount
FROM movies m
LEFT JOIN (movie_publications p, movie_image mi)
ON (m.movieid = p.movieid
AND
p.movieid = mi.movieid)
GROUP BY m.movieid
A: A left Join will take all rows from the first table (movies) and try to match with the second table (movie_publications). When it's not possible NULL columns will be inserted instead of the columns of the second table.
If you don't want this to happen you should use an INNER JOIN.
UPDATE: you said in the comments that movies can have or not publication, but will always have an image, so you could rewrite the query as follows. In case you're not totally sure that all movies have an image you could use LEFT JOIN also for movie_image.
SELECT m.*, mi.filename, COUNT(p.movieid) AS publicationsCount
FROM movies m
LEFT JOIN movie_publications p
ON (m.movieid = p.movieid)
INNER JOIN movie_image mi
ON (m.movieid = mi.movieid)
GROUP BY m.movieid
A: The LEFT JOIN returns all rows from the left table, even if there are no matches in the right table, and NULL is for the no matches.
A: If I get you right, it is exactly what LEFT JOIN is for: to get a result even for "non-matching joins".
Your query walks through movies and emits at least one result row for every row, even if there is no "matching partner" in the other tables.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I persist some data with a Magento Quote Item for reference on checkout? I need to persist some data associated to a product and then process it on checkout. This is internal data that isn't visible to the user, however it is calculated when a user is adding an item to the cart.
I've tried extending the Cart Model's addProduct() call and using:
$product->setData('some_var', $my_data);
However, on the checkout, when I do:
$items = $this->getOnepage()->getQuote()->getAllItems();
foreach($items as $item)
{
echo $item->getData('some_var');
}
That item doesn't persist.
I assume it's not actually storing the item but saving all of the product id's and regenerating the collection.
Any advice on this would be greatly appreciated.
A: It's easier to add new attribute for product and then add quote item definition to the config.xml
<global>
<sales>
<quote>
<item>
<product_attributes>
<your_attirubute_code />
</product_attributes>
</item>
</quote>
</sales>
</global>
Also this attribute must used in product listing. ("Used in Product Listing" = Yes)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Soft-delete user table? Or is there another alternative? My head's spinning from reading all the pro's & con's articles about soft-delete. But that's the only way I know to achieve this:
maintain the foreign keys & user info (history data)
Even if the user is deleted/inactive, there are foreign keys in comments, attachments and stories tables. So that it can still be identified that it was him who wrote this comment etc.
Other info:
deactivated users cannot login, won't be included in lists.
But if I use soft delete, it's not really good adding an extra column in the WHERE in sql statement every time I query for that table.
What to do? Hope you guys can give some inputs.
Note: I use mysql and ROR
A: If you "soft delete" users, you don't add an extra column in the WHERE clause of every SQL statement. Instead, build one view that returns only active users, and the queries that need to know about active users use that query. They don't use the base table.
It might look something like this.
create view users_active as
select * from users
where deleted = false;
Depending on how much development you've done so far, you might want to rename the users table, and name the new view "users" instead. Something along these lines . . .
alter table users rename to users_all;
create view users as
select user_id, user_name from users_all -- All columns except "deleted"
where deleted = false;
Now any query that used to hit the table "users" will instead hit the view "users". Logical data independence--this is why views and tables share the same namespace in the relational model.
A: There are so many ways to achieve things in this world, don't think what someone said is always true :)
First off, when it comes to comments - yes, if you are joining users table to obtain username for the person who sent the comment, using soft delete - yes, it's much, much easier to obtain who wrote the comment.
It's also easy to check whether they're deleted so you can render it in HTML too.
On the other hand, you can also store username in the comments table so you can avoid joining the users table. However, it's difficult to know whether the user was deleted or not since you're not receiving that information from users table.
Adding additional clause in WHERE won't kill anyone. SQL was made so you get the data you want, computers conform to users' needs, not the other way around. So, if you think soft-delete is what you need, use it. The only "real" con is that you keep the record in the db, so someone might say that soft deletes inflate databases.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: HTML: Can I mark/highlight a drop-down list menu item? Say I've got a list. I want to let the user know that one of the indices was the one that was previously set. I would like it so that when the user opens the drop down menu he can see that one of the options is marked so it looks different from the rest.
Is there a facility for this? I won't bother with it if I have to hack up something ugly or re-implement the entire menu functionality to get this to work.
A: If this is a element that has tags inside,
you could try adding a specific class for option you want to highlight.
<option class="myoption"...
Then apply background color to this option through css.
.myoption {background-color: red;}
I think this will not work in IE 6 and 7, because you cannot apply styles for selects in these versions of browsers.
If you have < ul > and < li > elements for list, apply the same method decribed above.
A: Generally, this would be unnecessary as you would simply have the previously selected option pre-selected the next time the page loads when in state.
However, if you want to show select-list options in a specific colour, then you can essentially give each option individual css styles, shown in an example here.
A: Are you talking about a simple <select>-Dropdown?
If so, it's pretty straightforward with CSS:
<select>
<option style="background:yellow">yellow</option>
<option style="background:red">red</option>
<option style="background:blue">blue</option>
</select>
Of course CSS-Classes will work, too.
A: Using the selected attribute on the option tag would be another solution. See
http://www.w3schools.com/tags/att_option_selected.asp
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581242",
"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.