text stringlengths 8 267k | meta dict |
|---|---|
Q: PrototypeJS - Changing Elements Within HTML Variable Is there a way to make calls within an HTML variable that is not in the DOM? For example, my code copies an existing row and then places it in the DOM. The problem is, I need to change some things within it. Code like:
newHTML = $$('.someRow')[0].innerHTML;
//Need to change form fieldName1 to fieldName2 in the newHTML variable, etc
$(this).up(1).insert({
before: newHTML
});
Right now I am changing things after, but it makes it difficult when there is a radio button that retains the same fieldname and changes the checked value of the original row.
Thanks.
A: You should be able to do this if you clone the node that you want to insert. e.g.
var newNode = $$('.someRow')[0].clone(true);
The cloned node is not inserted into the DOM until you insert it so you can manipulate it in whatever way you choose before doing so, its just a prototype Element.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Position images along a Bézier curve We currently have a dynamic image, which holds on it text which is created from user input. This text follows a Bézier curve to define its position and rotation.
For various reasons, the text needs to be changed to be a set of images as the font needs to be very specific. We will therefore have one PNG for every allowable character of the alphabet. So if the user enters the word "TEST", the system will pull out the letters T, E, S and T and position them next to each other. This part isn't an issue.
The problem is forcing each of the images to follow the same Bézier curve as the text did using graphics.DrawString. The images must be positioned correctly, and ideally should be rotated correctly as well.
Is this possible, and how could this be done?
A: The quick answer is that you "simply"
*
*parametrise the bezier curve evenly (PDF on math) (Explanation of what is wrong with standard parametrisation)
*calculate the normals to the curve
*arrange your images along the curve according to the even parametrisation using the glyph widths as the parameter distance
*rotate your images so that "up" for your image is the normal direction to the curve
But even this does not get a fairly good looking image. Usually you need to apply a nonlinear transform to each image so that parts away from curve have different width than those near the curve, depending on curvature and convexity.
This site explains many of the details by decomposing the outline of an image in paths
However, as the previous links I'm sure start to show, this is a calculation-intensive process. Instead, you may find it much easier to simply convert your images to fonts and use the method you were using previously. This solution would rely upon some third-party tool to do the conversion, and I hesitate to make suggestions. One direction, though, (of many) would be to use a raster-to-vector graphics tool like the open source Inkscape and create your fonts from the vector graphics output. This method scales best but may involve a separate step of converting the output to a preferred font format like True-Type.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is the code below converting a character into its ASCII value? Is the code below converting a character into its ASCII value?.
I faced a piece of code while studying evaluation of postfix operation,where it says "the expression converts a single digit character in C to its numerical value".?
int x=getch();
int c=x-'0'; /*does c have the ASCII value of x?*/
printf("%d",c);
A: No, it's converting the ASCII value to a number >= 0.
Let's say you type '1'. getch() will return 49 which is the ASCII value of '1'. 49 - '0' is the same as 49 - 48 (48 being the ASCII value for '0'). Which gives you 1.
Note that this code is broken if you enter a character that is not a number.
E.g. if you type 'r' it will print 'r' - '0' = 114 - 48 = 66
(Ref.)
A: No, it's giving the numeric value of a digit. So '5' (53 in ASCII) becomes 5.
A:
Is the code below converting a character into its ASCII value?
It isn't. It's doing the opposite (converting an ASCII value to the numerical value) and it only works for decimal digits.
A: To print the ascii value all you need to do is :
int x=getch();
printf("%d",x);
If you are sure that you only want to accept integers as input then you need to put some constraints to the input before proceeding to process them.
int x = getch();
if (x >='0' || x <= '9') {
int c = x - '0'; // c will have the value of the digit in the range 0-9
. . .
}
A: Any character(in your case numbers) enclosed within single quotes is compiled to its ASCII value. The following line in the snippet above translates to,
int c=x-'0'; ---> int c= x-48; //48 is the ASCII value of '0'
When the user inputs any character to your program, it gets translated to integer as follow,
If x = '1', ASCII of '1' = 49, so c= 49-48 = 1
If x = '9', ASCII of '9' = 57, so c= 57-48 = 9 and so on.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: attempting to convert String data into numerical data, the drop the data into an array of arrays (Json) I have this:
(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)
I'm attempting to get the output to look like this:
"coords": [[65.94647177615738, 87.890625],[47.040182144806664, 90],[45.089035564831036, 122.34375]]
Any Idea?
The first result comes back to me as a string, so when i try to assign the first object to an array, the console shows me this:
array is: "(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)"
A: var str = "(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)";
str = str.slice(1,-1); // remove outermost parentheses
var arrCoord = str.split(')(');
for (var i=0; i<arrCoord.length; i++) {
var tarr = arrCoord[i].split(", ");
for (var j=0; j<tarr.length; j++) {
tarr[j] = parseFloat(tarr[j]);
}
arrCoord[i] = tarr;
}
// arrCoord is now populated with arrays of numbers
A: Decided to sort of play code golf. Assuming:
var sample = '(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)';
Then:
var coords = sample
.split(/\(([^)]+)\)/)
.filter(function(v){return v!=""})
.map(function(v){return v.split(/[^0-9\.]+/)})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Save .dta files in python I'm wondering if anyone knows a Python package that allows you to save numpy arrays/recarrays in the .dta format of the statistical data analysis software Stata. This would really speed up a few steps in a system I have.
A: The scikits.statsmodels package includes a reader for Stata data files, which relies in part on PyDTA as pointed out by @Sven. In particular, genfromdta() will return an ndarray, e.g.
from Python 2.7/statsmodels 0.3.1:
>>> import scikits.statsmodels.api as sm
>>> arr = sm.iolib.genfromdta('/Applications/Stata12/auto.dta')
>>> type(arr)
<type 'numpy.ndarray'>
The savetxt() function can be used in turn to save an array as a text file, which can be imported in Stata. For example, we can export the above as
>>> sm.iolib.savetxt('auto.txt', arr, fmt='%2s', delimiter=",")
and read it in Stata without a dictionary file as follows:
. insheet using auto.txt, clear
I believe a *.dta reader should be added in the near future.
A: The only Python library for STATA interoperability I could find merely provides read-only access to .dta files. The R foreign library however provides a function write.dta, and RPy provides a Python interface to R. Maybe the combination of these tools can help you.
A: pandas DataFrame objects now have a "to_stata" method. So you can do for instance
import pandas as pd
df = pd.read_stata('my_data_in.dta')
df.to_stata('my_data_out.dta')
DISCLAIMER: the first step is quite slow (in my test, around 1 minute for reading a 51 MB dta - also see this question), and the second produces a file which can be way larger than the original one (in my test, the size goes from 51 MB to 111MB). This answer may look less elegant, but it is probably more efficient.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: forfiles with UNC path I am trying to use forfiles to delete files that are older than 7 days. The files are in a UNC path. Below is the script that I am using.
Forfiles -p \\devexpress\C$\FULL\ -s -m *.* -d -7 -c "cmd /c del /q @path"
But I get an error mentioning that UNC paths (\\machine\share) are not supported.
There appears to be workarounds available but cannot get a clear answer googling.
A: Enhanced solution to the PA's first answer is:
PushD "\\devexpress\C$\FULL\" &&(
forfiles -s -m *.* -d -7 -c "cmd /c del /q @path"
) & PopD
The PushD command maps the UNC path to free drive letter automatically, so this is portable approach.
Found in http://www.petri.co.il/forums/showthread.php?t=24241.
A: The error I get when trying to reproduce the problem says that the problem is not with FORFILES not suporting UNC Path, but with CMD not being able to start with an UNC path as default directory. In case that this is also your problem, there are three approaches to solve it.
*
*you might assign the UNC path to a disk letter, via NET USE
NET USE V: \\devexpress\C$
Forfiles -p V:\FULL\ -s -m *.* -d -7 -c "cmd /c del /q @path"
*You may bypass CMD and directly use some ERASEFILE executable utility directly in the -C option of the FORFILES
*You may bypass FORFILES and use FOR command with some date checking logic instead. See my answer to this Stack overflow question How can I check the time stamp creation of a file in a Windows batch script?
A: I got this to work:
PushD "\\DS\Tajana\Arhiva\Arhive po danima" &&("forfiles.exe" /s /m "*.*" /d -7 /c "cmd /c del @path") & PopD
although I get a message about the error in cmd window "not supporting UNC Path" but it still deletes files older than 7 days
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Finding the names of the running activities Edited to change 'running to 'running or paused and in background'
Is there a method which which I can log the names of the classes of the activities running or paused and in the background (i.e. not finished) in my application?
I find the shell command adb shell dumpsys meminfo com.mypackage.myapp to be most useful in managing the activity stack but it only gives me the number of activities running, not their names.
For example on startup it gives me this snippet:
** MEMINFO in pid 215 [com.mypackage.myapp] **
native dalvik other total
size: 4336 3203 N/A 7539
allocated: 4326 2527 N/A 6853
free: 9 676 N/A 685
(Pss): 1034 1974 1994 5002
(shared dirty): 2160 4732 1564 8456
(priv dirty): 864 684 912 2460
Objects
Views: 22 ViewRoots: 2
AppContexts: 3 Activities: 2
Assets: 2 AssetManagers: 2
Local Binders: 7 Proxy Binders: 11
Death Recipients: 0
OpenSSL Sockets: 0
Now I reckon I should only have one activity occupying memory, yet it tells me there are two. I'd quite like to know what the other one is.
A: As soon as an activity has lost focus and another activity runs the first one is paused or stopped. The conclusion is that there is always just one activity really running and that is the visible activity on the foreground.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: WPF TabItem Desire Binding to Only Occur When IsSelected True The contents of one TabItem is large CPU expensive to create. Would like to only get the content via binding for the TabItem when IsSelected = True. Or get alternate content based on IsSelected True or False. Giving up IsAsync = True in this case is not an option.
The XAML below works but it retrieves the content regardless if IsSeleted = False or IsSelected = True.
<TabItem IsSelected="False" Header="Expensive Content">
<FlowDocumentReader Name="FlowDocumentPageViewer1" HorizontalAlignment="Stretch" DataContext="{Binding Source={x:Static Application.Current}}">
<FlowDocumentReader.Document>
<Binding Path="MyGabeLib.Search.SelectedDoc.XAMLdocFlowDocument" IsAsync="True" Converter="{StaticResource flowDocumentToXamlConverter}"
FallbackValue="{StaticResource DefaultFlowDoc}" Mode="OneWay"/>
</FlowDocumentReader.Document>
</FlowDocumentReader>
</TabItem>
The converter is to convert a string (serialized using XamlWriter.Save(DocFlowDocument)) back to a FlowDocument as cannot use IsAsync = True (directly) with a FlowDocument.
Binding to a property in the code behind to redirect did not work as the UI with IsAcync = True is on another thread and does not have access to IsSelected.
Was hoping to use a template with a trigger but this is as far as I got. Not very far but it does not throw a syntax error.
<TabItem IsSelected="False" Name="TabItemFlowDoc">
<FlowDocumentReader ...>
<FlowDocumentReader.Template>
<ControlTemplate>
</ControlTemplate>
</FlowDocumentReader.Template>
</FlowDocumentReader>
Tried trigger directly on the TabControl and could not even get past syntax errors
<TabControl Grid.Row="0" Grid.Column="0" Name="TabControlView">
<TabControl.Resources>
<DataTemplate>
<FlowDocumentReader.Template>
</FlowDocumentReader.Template>
</DataTemplate>
</TabControl.Resources>
Thanks in advance.
A: So what I ended up doing was fetching the document text and other parameter for marking it up on a background thread. Then on the UI thread I check the TabIndex if that tab is selected and only produce the FlowDocument if that tab is selected. Another tab presents the first 4 thousand characters of the text so the user can quickly decide if they want to render the full highlighted documents.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ajax doesnt work when I publish to my MVC3 project I have a problem in my MVC3 project about using ajax. I have done couple of settings for using it like add some scripts in master page and change some stuff in web.config file etc.
Actually after all those things my project works fine in my local server. But when I publish it, ajax stuff doesnt work any more.
Do you have any idea for solving this problem? what do ı neen to do?
It would be great if someone could help me.
Thanks in advance.
These things are in my master page.
<script src="/Scripts/MicrosoftAjax.debug.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
And these are from web.config I have just changed UnobtrusiveJavaScriptEnabled value from "true" to "false"
<configuration>
<appSettings>
<add key="inspector" value="EmrTelInspector" />
<add key="browserExpireCookie" value="EmrTel" />
<add key="webpages:Version" value="1.0.0.0" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="false" />
</appSettings>
A: Replace:
<script src="/Scripts/MicrosoftAjax.debug.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
with:
<script src="@Url.Content("~/Scripts/MicrosoftAjax.debug.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
or if you are using the WebForms view engine:
<script src="<%= Url.Content("~/Scripts/MicrosoftAjax.debug.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js") %>" type="text/javascript"></script>
The reason why your code doesn't work when you publish is because there is a virtual directory in IIS so the correct url is no longer /Scripts/MicrosoftAjax.debug.js but /NameOfYourApplication/Scripts/MicrosoftAjax.debug.js.
For this reason you should never hardcode any urls in an ASp.NET MVC application. You should always use url helpers to ensure that this application will work no matter where it is deployed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CURL or file_get_contents to update a list of feeds? I am running a feed reader site, where there will be a lot of RSS around. I will have to synchronize those feeds as often as possible, so I found these two methods of doing it.
1 method : Using CURL
$weblog_name = 'MyBlog';
$weblog_url = 'http://feeds.feedburner.com/myblog';
$ping_url = 'http://ping.feedburner.com';
$request = <<<EOT
<?xml version="1.0" encoding="iso-8859-1"?>
<methodCall>
<methodName>weblogUpdates.ping</methodName>
<params>
<param>
<value>
<string>$weblog_name</string>
</value>
</param>
<param>
<value>
<string>$weblog_url</string>
</value>
</param>
</params>
</methodCall>
EOT;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $ping_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_POSTFIELDS, trim($request));
$result = curl_exec($ch);
curl_close($ch);
Second Method : file_get_contents
file_get_contents("http://feedburner.google.com/fb/a/pingSubmit?bloglink=http://feeds.feedburner.com/myblog");
My question is which is the better and faster solution to ping at least 50 feeds at once ?
A: Because you will be updating 50 feeds at once, I would strongly suggest using CURL for two reasons:
*
*you can use curl_multi() functions that will allow you to send
all 50 requests at once, while file_get_contents() will only go
one-by-one. The documentation for these functions is a bit sparse,
so I would suggest using a lightweight library - it's much easier to
work with. I personally use
https://github.com/petewarden/ParallelCurl, but you will find many
around.
*as you are pinging the services, you do not really need to know
the response, I guess (as long as it's HTTP 200). So you could
use
the CURL option CURLOPT_NOBODY to make it into a HEAD request,
thus
in response you would get the headers only, too. This should
speed
up the process even more.
Put it otherwise, file_get_contents might be faster for simple requests, but in this case your situation is not simple. Firing 50 requests without really needed to get the whole document back is not a standard request.
A: Actually i think curl is faster than file_get_contents.
Googling a bit I've found out some benchmarks here in SO: file_get_contents VS CURL, what has better performance?
A: I would recommend considering using curl ... while it might be some development overhead at first sight, it is much more powerful than file_get_contents. especially if you want to fetch multiple feeds, curl multi requests might be worth looking at:
http://php.net/manual/en/function.curl-multi-init.php
A: If you want flexibility for the future (e.g. Authentication, Cookies, Proxy etc.) then use cURL. The speed is about the same as file_get_contents() judging from benchmarks (some say it's faster)
If you want a quick and easy solution then by all means use file_get_contents(). However, it wasn't built for the purpose for requesting external URL's. Most people swear by cURL for doing any work with external URL's, even simple GET requests.
The only additional work with using cURL is a few extra lines of code, wrap it in a function and you're good to go.
A: Fetching google.com using file_get_contents took (in seconds):
2.31319094
2.30374217
2.21512604
3.30553889
2.30124092
CURL took:
0.68719101
0.64675593
0.64326
0.81983113
0.63956594
This was using the benchmark class from http://davidwalsh.name/php-timer-benchmark
A: get_file_contents is faster. It does a simple http without any extra instantiations
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Can you set a weak_ptr<> in a ctor? The following code fails to compile in Visual C++ 11 with this error:
1>c:\users\tony\documents\visual studio 11\projects\cpp11_ex1\cpp11_ex1\main.cpp(52): error C2440: '' : cannot convert from 'Foo *const ' to 'std::weak_ptr<_Ty>'
#include <stdio.h>
#include <memory>
using namespace std;
class Foo;
class Bar
{
public:
Bar( weak_ptr<Foo> foo ) : _foo(foo) { printf("Bar(%p)\n",this); }
~Bar() { printf("~Bar(%p)\n",this); }
private:
weak_ptr<Foo> _foo;
};
class Foo
{
public:
Foo() : _bar() { _bar = make_shared<Bar>( weak_ptr<Foo>(this) ); printf("Foo(%p)\n",this); }
~Foo() { printf("~Foo(%p)\n",this); }
private:
shared_ptr<Bar> _bar;
};
int main( int argc, char* argv[] )
{
shared_ptr<Foo> instance = make_shared<Foo>();
return 0;
}
It seems that I can't create a weak_ptr from a raw this pointer. This causes an interesting series of problems.
*
*Since I am attempting this in Foo's ctor, Foo's reference count is 0 (i.e. the make_shared<> in main hasn't returned yet).
*I've discovered that I can create weak_ptrs from shared_ptrs... But if I change Bar ctor to take a shared_ptr, I the act of calling Bar's constructor ends up destroying Foo! (Since Foo's reference count is still 0, creating (and then destroying) a shared_ptr to Foo via a call to Bar's ctor ).
All I really want to do is create Foo, have Foo create and own a Bar, but have Bar have a weak reference back to Foo. I really don't want to be forced into 2 part initialization here!
A: boost::weak_ptr<T> is for storing, not for using.
You want to pass boost::shared_ptr objects, and then store them in the boost::weak_ptr objects (usually private).
struct Foo {
Foo(const boost::shared_ptr<int> &data) : weak_data(data) {}
boost::shared_ptr<int> getData() {
boost::shared_ptr<int> data = weak_data.lock();
if (!data)
throw std::runtime_error("data is no longer valid");
return data;
}
private:
boost::weak_ptr<int> weak_data;
};
Whether you throw or pass back and empty shared_ptr<T> is up to you. If you cannot lock the object though, you shouldn't be passing it around anymore. It really isn't valid at that point.
That being said, you may want to refrain from creating a shared pointer in that manner. It isn't clear from your example if you need this design. If you can redesign it in a way like Mooing Duck suggested you will be better off, in all honesty.
From similar experiences when I needed circular dependencies like this, it probably is not a simple construction scenario. I would look at a two part constructor (static named constructor, or builder perhaps) to manage creating the two objects and ensuring that their references are valid.
Here is a quick example of a simple named constructor.
class Foo;
// Likely that this should be a child class of Foo
class Bar {
private:
friend class Foo;
Bar(const boost::shared_ptr<Foo> &foo) : weak_foo(foo) {}
weak_ptr<Foo> weak_foo;
};
class Foo {
public:
static boost::shared_ptr<Foo> CreateFoo() {
boost::shared_ptr<Foo> foo = boost::shared_ptr<Foo>(new Foo);
foo.bar = boost::make_shared<Bar>(foo);
return foo;
}
private:
Foo() {}
boost::shared_ptr<Bar> bar;
};
Here you control the invariant that your foo and bar variables are created correctly.
A: It is not possible to have a weak pointer in the absence of strong pointers to the same object, by definition. When the last strong pointer goes away, all the weak pointers turn null. That's all the weak pointers do.
Write your own function that returns a shared ptr to Foo (a Foo factory), and initialize the weak ptr in Bar from that pointer.
A: Since Foo will be pointed at by a shared_ptr, and Bar will always be owned by a shared_pointer of Bar, then if Bar exists, Foo exists. Ergo, you don't need a smart pointer in Bar. (If I understand the problem correctly)
#include <stdio.h>
#include <memory>
using namespace std;
class Foo;
class Bar
{
public:
Bar( Foo* foo ) : _foo(foo) { printf("Bar(%p)\n",this); }
~Bar() { printf("~Bar(%p)\n",this); }
private:
Foo* _foo;
};
class Foo
{
public:
Foo() : _bar(new Bar(this)) { printf("Foo(%p)\n",this); }
~Foo() { printf("~Foo(%p)\n",this); }
private:
shared_ptr<Bar> _bar;
};
int main( int argc, char* argv[] )
{
shared_ptr<Foo> instance = make_shared<Foo>();
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ContentManager in console mode? Is there a way to setup a ContentManager without using a GraphicsDevice? It's a console app..
The problem is I get a "Reach profile" not supported, is there a way to make it without needing DirectX?
A: ContentManager takes an IServiceProvider. It is best to create a class that implements IServiceProvider with your own behavior rather than just using Game or GraphicsDevice.
From msdn:
"Caution
When creating a new ContentManager, if no instance of Game is otherwise required by the application, it is often better to create a new class that implements the IServiceProvider interface rather than creating an instance of Game just to create a new instance of GraphicsDeviceManager."
http://msdn.microsoft.com/en-us/library/bb195757.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Prevent browser scrolling to hash on page load Using localscroll on ready but the browser snaps to hash on ready. How do I prevent that and have it scroll to the top no matter what?
if this is not possible. How do you offset the position of the window.location of hash?
A: Use $(window).scrollTop(0);
$(function(){
$(window).scrollTop(0);
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: CSS Menu Hover Image Stretch I have a simple horizontal menu which has <li> elements of different widths, when a user hovers over I would like to use the attached image to designate the hover, however I cannot work out the best way to do this.
the Image...
Can anyone post any code and suggest what I might need to do here.
Thanks
A: You would simply use the a:hover selector in your css, and add a background image. However, be aware, that stretching this image only works in modern browsers (IE9, Chrome, FF) that support CSS3.
A: This is how you make a menu;
http://jsfiddle.net/sg3s/49T6w/1/
When you style a menu it is important to make the anchors (a tags) display:block. That makes sure you have full power over their look and dimensions. Als if you use the anchors to make the menu it is backward compatible with older browsers that don't support :hover on block level elements (but do on anchors even if you make them a block since they're originally inline).
The background image is easy, just add it in the :hover class of the anchor. Gl
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to select PayPal checkout layout PayPal provides two different checkout layouts. I would use the oldest layout (so not the enhanced). How can I set this preference? Is there some special variable to do that? Or I should do that from profile settings page?
Thanks
A: You cannot. The new (enhanced) layout is gradually being rolled out. The old one will disappear over time.
A: By adding force_sa=true in your calling Url, you can still use the old layout
Check that
Paypal express "order summary" page
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Width of first row of floated elements? Say that I have a bunch of divs floated left, in a grid like fashion. These are in a container with a fixed width.
Now I'd like to know the width of the first row! so that I can compare that width with the fixed width and see if there's a lot of whitespace there, which I would like to minimize.. by setting the container width to the width of the first row of elements.
Now, the difficulty is of that when I float elements there is no concept of first or second row.. Well, I don't really need to know the first row width persé, I just need to know the nr of pixels of white, empty space that is next to the last element to the right side of the container..
See this example: http://i54.tinypic.com/256wdjn.png (don't mind the flashy colors, just for testing)
The right side has too much white space.. I can't just calculate this before hand as the margins, border widths, image widths etc are all dynamic..
Thanks!
A: Broadly, what you can do is loop through the nested elements and use .offset().top or .position().top. If elements n and n+1 are the first elements to have different top offsets, they must be in different rows.
Then add the width of elements 0 through n (together with their padding, borders, and margins) to get the total width of that row.
(Oh, and don't forget to exit your loop, since you only needed to compute the first row.)
A: Well, you haven't really shown us your HTML so it's hard to advise very specifically, but the only way I know of to do this is to measure how big one of the grid elements is after it's in the page and then set the container to the closest integral multiple of that so that there is no extra space in the container.
jQuery has very useful methods .width(), .innerWidth() and .outerWidth() for measuring depending upon what exactly you're trying to do.
If the container itself has margins or padding, then you will have to account for that in computing the desired width of the container that leaves the integral amount of space on its interior.
A: You're overcomplicating it. You really don't need to do any of that. Do you always have 4 images like that? If so you can just use width: 25%; text-align:center; on the elements container.
A: I'm not sure it works for floated child nodes but you can try to add "display:inline-block" to the container div without width and height specified. this way the container gets as narrow as possible...if that is what you're seeking for.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Template method for dojo When I look in the dojo documentation for template all I get is for dijit and examples only show you been able to use them in a widgit. I'm looking for the equivalent of the below methods in js prototype
var tmpl = new Template(url)
tmpl.evaluate(templateObj)
Does dojo have a template method that you can use in a dojo.declare( class ){} like you can do in js prototype. If not how could I go about similar functionality
Thanks
A: You may be interested in dojo.string.substitute (you'll need to dojo.require("dojo.string")).
http://dojotoolkit.org/api/dojo/string/substitute
[Edit] Also, if you're interested in acquiring a template for use in substitution from a URL on the same server, you may also want to look into dojo.cache (which is also what is often used to fetch widget templates):
http://dojotoolkit.org/reference-guide/dojo/cache.html
To clarify missingno's response, I don't think dojo.parser is what you're interested in right now; its job is to scan the DOM and transform DOM nodes into widgets and other Dojo components. dijit._Templated only uses dojo.parser when child widgets are involved (i.e. widgetsInTemplate is true); on the other hand, it uses dojo.string.substitute in all cases, to initially parse ${...} strings (e.g. ${id}) in the template.
A: I don't know Prototype, but this sounds like dojo.parser stuff. It is what is used by dijit._Templated behind the scenes (you can chack that in the source code if you want...)
Just note that you probably wouldn't need to cal this yourself - there is parseOnLoad=true for automatically parsing your initial HTML.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: problem with webview in android I have a webview in my app. I can see the title of the website on the title bar (I have custom title bar). However, i dont see anything in the view - the website is not viewable :(.. any suggestions ? Here's the code:
public class WebViewer extends Activity {
WebView webView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewer);
webView = (WebView) findViewById(R.id.webview);
String url = "http://www.google.com";
final TextView title=(TextView) findViewById(R.id.title_text_view_success3);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
title.setText("Loading...");
WebViewer.this.setProgress(progress * 100);
if(progress == 100)
title.setText(webView.getTitle());
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
// Handle the error
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webView.loadUrl(url);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
A: @Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
This isn't needed. shouldOverrideUrlLoading is called before the url is loaded to give you a chance to handle loading yourself. What you're doing is loading the url over and over.
http://developer.android.com/reference/android/webkit/WebViewClient.html#shouldOverrideUrlLoading%28android.webkit.WebView,%20java.lang.String%29
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Weird problem - Glassfish 3.1.1 Server and Eclipse Indigo I have installed Glassfish 3.1.1. Open Source Ed. Server for my development purpose and Eclipse Indigo as my IDE. The add-on(s) i have installed in eclipse are Glassfish Server Tools and Spring 3 Tools from elipse market place. Now the problem i am facing is like when i try to start the glassfish from elipse i got credential error. But if i test the server from browser like http://localhost:8080/ it works fine. But funny thing is that when i unplug my pc from internet and try to start the GF server from eclipse it works fine!!! i could not figure out what's happening.
My OS is Windows 7 Enterprise Ed and JDK is 1.7.0
Things i tried to solve the problem
*
*Shut down MS SQL Reporting Server(2008)
*Disable Firewall
*Turn off Anti-virus
*Netstat -noa | findstr 0.0.8080 to find process and kill it
*Stop IIS sever
A: Finally I have solved the problem. It was due to the proxy setting. I added "127.0.0.1 localhost"(without quote) in /etc/hosts file and connected my pc to internet, then tried to start the GF server from eclipse . BANG ... it worked !!! (although i did it from my home, i will update this post after testing from my office network).
BTW: @vineet, i tried that too but didn't work. i forgot to mention in the first place. thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: New Column in Doctrine / CodeIgniter app produces Column not found: 1054 Unknown column error Doctrine_Connection_Mysql_Exception [ 42 ]: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'allocation_rule_number' in 'field list'
I have the above error after adding a new column to my table manually via mysql command prompt. I have traced it down to synchronizeWithArray in my controller - for some reason in my code igniter controller
$this->_table->columns
is missing the new column I added so synchronizeWithArray is failing. I know that it's in the POST data so I'm not sure what part of Doctrine has the old table definition.
if ($is_update)
{
$this->license->synchronizeWithArray($this->tmp_record);
}
Any ideas why would this happen or how to diagnose?
A: I forgot to add the same column to the license_versions table. I figured it out by checking the MySQL query log, which was invaluable in pointing out that exactly how it was trying to modify the wrong table!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Do you know any dynamic instrumentation tool for Android with multi-device support (ideally in Python or Jython)? For my CI infrastrucure I need to automatically deploy and run complex tests between two (or more) android phones from a controler machine (linux).
So far android monkeyrunner in combination with android unit tests is not a satisfactory solution:
*
*monkeyrunner does not call single methods from a remote app and can't address UI components by their id
*writing java tests cases with ActivityInstrumentationTestCase2 is too expensive (loC) and does not provide enough flexibility for interacting between two devices
*robotium.org is a step in the right direction but is in java (not dynamic) and not multidevice yet
*all other solutions I found does not allow interactive testing thx to dynamic scripting
Any suggestion?
A: There is a tool called AndroidViewClient which extends the usability of monkeyrunner. You can address UI components by ID with it, check their properties and so on.
Here's the link:
https://github.com/dtmilano/AndroidViewClient
A: Have you looked at MonkeyTalk?
Here:
http://www.gorillalogic.com/testing-tools/monkeytalk
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How can I add a link tag to the atom.builder feed generator? In rails 3.0.9 (and maybe earlier) this code no longer works:
//feed.atom.builder
atom_feed :language => 'en-US' do |feed|
feed.title @title
feed.updated @updated
feed.link('href' => 'http://[REDACTED].superfeedr.com/', 'rel' => "hub")
...
end
The exact error is: ArgumentError: wrong number of arguments (1 for 2) with a stack trace of:
/Users/[REDACTED]/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/fileutils.rb:302:in `ln'
[GEM_ROOT]@global/gems/rake-0.8.7/lib/rake.rb:1094:in `link'
[GEM_ROOT]/gems/actionpack-3.0.9/lib/action_view/helpers/atom_feed_helper.rb:146:in `method_missing'
app/views/feeds/index.atom.builder:4:in `block in _app_views_feeds_index_atom_builder___2426096422608134746_70129604713820_3077995114801777171'
[GEM_ROOT]/gems/actionpack-3.0.9/lib/action_view/helpers/atom_feed_helper.rb:123:in `block in atom_feed'
…
This is important for me and to setup a superfeedr Pubsubhubbub as described here. I need to get a <link rel="hub" … > tag into the atom feed but feed.link no longer works like it used to due to the method being removed from atom_feed_helper.rb. How can I get this link tag to show up again?
A: I believe you used this gem which seems a bit old, and since Atom is just a flavor of XML, it may be easier to just write the feed yourself anyway, using the answer given there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adaptive time/position series filter in R...? I'm trying to filter a time/position data series to produce a smoothed plot. I am measuring depth vs time (mechanical system) where the velocity is changing. I calculate velocity from the measured depth/time values and can plot velocity vs. depth, but at low speeds, the noise is excessive (for various reasons). The trend at low speeds is correct, but I'd like to be able to apply a filter that will use an adaptive smoothing routine, i.e. for low speeds (where I have many data points) I need to use a larger smoothing window, and for high speeds (few data points) I need to use a smaller window.
I've looked a bit and have figured out a solution using rollapply() but was wondering if there are other approaches. In particular, I'm not clear on how to "vectorise" an operation. I'm a relatively new coder so I'm sorry if my code is a bit amateurish. My solution is below:
adapt<-function(x,wmin,wmax) {
# adapt takes a vector of calculated velocities (x), a minimum window size (wmin),
# and a maximum window size (wmax). It returns a vector of filtered velocities
#
x<-ifelse(is.na(x),0,x) # check for na values
x<-ifelse(is.infinite(1/x),1/wmax,x) # check for infinite values
x<-runmed(x,11) # smooth raw velocities using 11 point window
wins<-ceiling(ifelse(is.infinite(1/x),wmin,1+wmax/(1+x)^15)) # set window widths
wins<-ifelse(wins<=wmin,wmin,wins) # set min windows
wins<-ifelse(wins>wmax,wmax,wins) # set max windows
out<-rollapply(x,width=wins,median) # apply filter to each element
out[length(x)]<-0 # set last value to zero
return(out)
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why is this page's body center-aligned? I am putting together a new site from an existing site and copying over some of the html and css. I don't really understand why the body is center-aligned here: http://www.problemio.com/auth/forgot_password.php
Any idea what is doing that?
Thanks!
A: You've got body {text-align: center} in your stylesheet.
A: The stylesheet being served from Yahoo has body { text-align: center; } in it. You can just put body { text-align: left; } in yours to counter it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP real-time chat technology choices What technology to use for chat? I would like to create an open connection.
When I put a new message to the database. I want to automatically without using the timer and making loops came a new message to the browser.
I have Linux web hosting with a MySQL database.
I tried to make retrieving new messages and use the timer. Every three seconds I am using Ajax retrieve data. This solution seems to me inefficient, so looking for others.
A: PHP is a server-side scripting language, which means all the PHP is processed before the page even loads. In order to generate a chat-like environment, you would need to use Javascript to establish an open connection to the back-end (the PHP part). There are many methods to doing this, including polling (timers) and sockets (much more complicated).
The best way I know of to handle a chat-like service using Javascript would be to check out Node.js and its capabilities, specifically demonstrated as a chat room here: http://chat.nodejs.org/.
The problem with NodeJS and persistent connections in general is that most cheap hosting providers don't allow you to have persistent connections open. You would need to pony up for a higher-cost dedicated server. There are, I believe, hosts that specifically allow NodeJS-type services in their environments, but I don't know of any off the top of my head.
A: You might need to implement COMET technology. It allows to make long pooling requests. When one request is done you can start another one. In COMET connection is always open.
In PHP you can do that creating infinity loop, while(true) for example and break connection when you need.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a simple way to launch a background task from a Python CGI script without waiting around for it to terminate? In Windows, that is.
I think the answer to this question is that I need to create a Windows service. This seems ludicrously heavyweight for what I am trying to do.
I'm just trying to slap together a little prototype here for my manager, I'm not going to be responsible for productizing it... in fact, it may never even BE productized; it might just be something that a few researchers play around with.
I have a CGI script that receives a file for upload, stores it to a temporary location, then launches a background process to do some serious number-crunching on the file. Then some Javascript stuff sits around calling other CGI scripts to check on the status and update the page as needed.
All of this works, except the damn web server won't close the connection as long as the subrocess is running. I've done some searching, and it appears the answer on Unix is to make it a daemon, but I'm stuck on Windows right now and I guess the answer there is to make it a Windows service?!? This seems incredibly heavyweight to just, you know, launch a damn process and then close the server connection.
That's really the only way?
Edit: Okay, found a nifty little hack over here (the choice (3) that the guy gives):
How to completely background a process in Perl CGI under IIS
I was able to modify this to make it even simpler, and although this is a klugey solution, it is perfect for the quick-and-dirty little prototype I am trying to make.
So I initially had my main script doing this:
subprocess.Popen("python.exe","myscript.py","arg1","arg2")
Which doesn't work, as I've described. Instead, I now have my main script emit this little bit of Javascript which runs after the document is fully loaded:
$("#somecrap").load("launchBackgroundProcess.py", {arg1:"foo",arg2:"bar"});
And then launchBackgroundProcess.py does the subprocess.Popen.
This solution would never scale, since it still leaves the browser connection open during the entire time the background task is running. But since this little thinger I am whipping up might someday have two simultaneous users at most (even then I doubt it) resources are not a concern. This allows the user to see the main page and get the Javascript updates even though there is still an http connection hanging open for no good reason.
Thanks for the answers! If I'm ever asked to productize this, I'll take at the resources Profane recommends.
A: Simplest, but not most efficient way would be to just run another python executable
from subprocess import Popen
Popen("python somescript.py")
A: You can just use a system call using the "start" windows command. This way your python script will not wait for the completion of the started program.
A: If you haven't much experience with windows programming and don't wish to peruse the MSDN docs-- I don't blame you-- you may want to try to pick up a copy of Mark Hammond's cannonical guide to all things python and windows. It somehow never goes out-of-date on many of these sorts of recurring questions. Instead of launching the process with the every-platform solution, you'd probably be better off using the win32process module. Chapter 17 of the Hammond book covers this extensively, but you could probably get all you need by downloading the pywin ide (I think it comes bundled in the windows extensions which you can download from pypi), and looking through the help docs it has on python's windows' api. Here's an example of using the api, from a project I was working on recently. It may in fact do some of what you want with a little adaptation. You'd probably want to focus on CreationFlags. In particular, win32process.DETACHED_PROCESS is "often used to execute console programs in the background." Many other flags are available and conveniently wrapped however.
if subprocess.mswindows:
su=subprocess.STARTUPINFO()
su.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW
process = subprocess.Popen(['program', 'flag', 'flag2'], bufsize=-1,
stdout=subprocess.PIPE, startupinfo=su)
A: CGI scripts are run with standard output redirected, either directly to the TCP socket or to a pipe. Typically, the connection won't close until the handle, and all copies of it, are closed. By default, the subprocess will inherit a copy of the handle.
There are two ways to prevent the connection from waiting on the subprocess. One is to prevent the subprocess from inheriting the handle, the other is for the subprocess to close its copy of the handle when it starts.
If the subprocess is in Perl, I think you could close the handle very simply:
close(STDOUT);
If you want to prevent the subprocess from inheriting the handle, you could use the SetHandleInformation function (if you have access to the Win32 API) or set bInheritHandles to FALSE in the call to CreateProcess. Alternatively, close the handle before launching the subprocess.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Technique to identify a video in iOS camera roll I'm trying to solve a specific problem (but this could benefit others) which from googling around doesn't seem to have a definitive solution. I think there are probably several partial solutions out there, I'd like to find the best of those (or a combination) that does the trick most of the time.
My specific example is: users in my app can send videos to each other and I'm going to allow them to save videos they have received to their camera roll. I would like to prevent them from forwarding the video on to others. I don't need to identify a particular video, just that it was originally saved from my app.
I have achieved a pretty good solution for images by saving some EXIF metadata that I can use to identify that the image was saved from my app and reject any attempts to forward it on, but the same solution doesn't work for videos.
I'm open to any ideas. So far I've seen suggested:
*
*Using ALAssetRepresentation in some way to save a filename and then compare it when reading in, but I've read that upgrading iOS wipes these names out
*x-Saving metadata. Not possible.
*MD5. I suspect iOS would modify the video in some way on saving which would invalidate this.
*I've had a thought about appending a frame or two to the start of the video, perhaps an image which is a solid block of colour, magenta for example. Then when reading in, get the first frame, do some kind of processing to identify this. Is this practical or even possible?
What are your thoughts on these, and/or can you suggest anything better?
Thanks!
Steven
A: There are 2 approaches you could try. Both solutions only work under iOS5.
1) Save the url returned by [ALAssetRepresentation url]. Under iOS 5 this URL contains a CoreData objectID and should be persistent.
2) Use the customMetadata property of ALAsset to append custom info to any asset you saved yourself.
Cheers,
Hendrik
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MarkLogic: Loading (import) XQuery Modules from database I want to load a module which is stored in a database under the modules named as "/modules/mylib.xqy".
Currently, in the document requiring these module, I am writing
import module namespace rb2lib="http://example.com/modules/lib" at "/modules/mylib.xqy";
Unfortunately, this expression makes a lookup on the filesystem and not on my database.
Is there a way loading modules stored in database?
Thanks in advance!
A: Yes, change the application server configuration's modules setting from (file system) to the Modules database (or any database). The XQuery module must be stored in that database, and its URI must be the app server's module root plus the import location. For example, you could set your module root to / and store the module at /modules/mylib.xqy.
A: This is controlled by a setting on the administrative console. Look at your App Server configuration for the "modules" config item. It is currently set to file system, right? Change it to the database that has your modules.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python, how i can get gif frames I am looking some kind method to get gif frames number. I am looking on Google, StackOverflow and any other sites and I find only rubbish! Someone know how to do it? I need only simple number of gif frames.
A: I was faced with the same problem recently and found the documentation on GIFs particularly lacking. Here's my solution using imageio's get_reader to read the bytes of an image (useful if you just fetched the image via HTTP, for example) which conveniently stores frames in numpy matrices:
import imageio
gif = imageio.get_reader(image_bytes, '.gif')
# Here's the number you're looking for
number_of_frames = len(gif)
for frame in gif:
# each frame is a numpy matrix
If you just need to open a file, use:
gif = imageio.get_reader('cat.gif')
A: Which method are you using to load/manipulate the frame? Are you using PIL? If not, I suggest checking it out: Python Imaging Library and specifically the PIL gif page.
Now, assuming you are using PIL to read in the gif, it's a pretty simple matter to determine which frame you are looking at. seek will go to a specific frame and tell will return which frame you are looking at.
from PIL import Image
im = Image.open("animation.gif")
# To iterate through the entire gif
try:
while 1:
im.seek(im.tell()+1)
# do something to im
except EOFError:
pass # end of sequence
Otherwise, I believe you can only find the number of frames in the gif by seeking until an exception (EOFError) is raised.
A: If you are using PIL (Python Imaging Library) you can use the n_frames attribute of an image object.
See this answer.
A: Just parse the file, gifs are pretty simple:
class GIFError(Exception): pass
def get_gif_num_frames(filename):
frames = 0
with open(filename, 'rb') as f:
if f.read(6) not in ('GIF87a', 'GIF89a'):
raise GIFError('not a valid GIF file')
f.seek(4, 1)
def skip_color_table(flags):
if flags & 0x80: f.seek(3 << ((flags & 7) + 1), 1)
flags = ord(f.read(1))
f.seek(2, 1)
skip_color_table(flags)
while True:
block = f.read(1)
if block == ';': break
if block == '!': f.seek(1, 1)
elif block == ',':
frames += 1
f.seek(8, 1)
skip_color_table(ord(f.read(1)))
f.seek(1, 1)
else: raise GIFError('unknown block type')
while True:
l = ord(f.read(1))
if not l: break
f.seek(l, 1)
return frames
A: Ok, 9 years maybe are a little too much time, but here is my answer
import tkinter as tk
from PIL import Image
def number_of_frames(gif):
"Prints and returns the number of frames of the gif"
print(gif.n_frames)
return gif.n_frames
def update(ind):
global root, label
frame = frames[ind]
ind += 1
if ind == frameCnt:
ind = 0
label.configure(image=frame)
root.after(100, update, ind)
file = Image.open("001.gif")
frameCnt = number_of_frames(file)
root = tk.Tk()
frames = [tk.PhotoImage( file='001.gif', format = f'gif -index {i}')
for i in range(frameCnt)]
label = tk.Label(root)
label.pack()
root.after(0, update, 0)
root.mainloop()
A: I did some timings on the currently proposed answers, which might be of interest:
*
*Pillow seek: 13.2 ms ± 58.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
*Custom parsing: 115 µs ± 647 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
*Pillow n_frames: 13.2 ms ± 169 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
*ImageIO improps (via pillow): 13.1 ms ± 23.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
So despite being pure python, custom parsing is about 100x faster than using pillow ... interesting. Among the other solutions, I like the ImageIO one, because it is short; however, I'm one of the devs there so I am obviously biased.
Setup code:
# get a test GIF (as in-memory stream to avoid measuring file IO)
import imageio.v3 as iio
import io
gif_array = iio.imread("imageio:newtonscradle.gif", index=None)
test_file = io.BytesIO()
iio.imwrite(test_file, gif_array, format="GIF")
# ImageIO is more strict with file handling and would close test_file
# It does handle byte strings natively though, so we can pass that for timings
gif_bytes = iio.imwrite("<bytes>", gif_array, format="GIF")
Pillow seek:
%%timeit
from PIL import Image
test_file.seek(0) # reset file
n_frames = 1 # opening returns the first frame
with Image.open(test_file) as file:
# To iterate through the entire gif
try:
while 1:
file.seek(file.tell()+1)
n_frames += 1
# do something to im
except EOFError:
pass # end of sequence
assert n_frames == 36
Custom Parsing
%%timeit
class GIFError(Exception): pass
def get_gif_num_frames(filename):
frames = 0
with io.BytesIO(filename) as f: # I modified this line to side-step measuring IO
if f.read(6) not in (b'GIF87a', b'GIF89a'): # I added b to mark these as byte strings
raise GIFError('not a valid GIF file')
f.seek(4, 1)
def skip_color_table(flags):
if flags & 0x80: f.seek(3 << ((flags & 7) + 1), 1)
flags = ord(f.read(1))
f.seek(2, 1)
skip_color_table(flags)
while True:
block = f.read(1)
if block == b';': break # I also added a b'' here
if block == b'!': f.seek(1, 1) # I also added a b'' here
elif block == b',': # I also added a b'' here
frames += 1
f.seek(8, 1)
skip_color_table(ord(f.read(1)))
f.seek(1, 1)
else: raise GIFError('unknown block type')
while True:
l = ord(f.read(1))
if not l: break
f.seek(l, 1)
return frames
n_frames = get_gif_num_frames(gif_bytes)
assert n_frames == 36
Pillow n_frames:
%%timeit
from PIL import Image
test_file.seek(0) # reset file
with Image.open(test_file) as file:
# To iterate through the entire gif
n_frames = file.n_frames
assert n_frames == 36
ImageIO's improps (via pillow):
%%timeit
import imageio.v3 as iio
props = iio.improps(gif_bytes, index=None)
n_frames = props.shape[0]
assert n_frames == 36
There is also a new PyAV based plugin I'm writing which is faster than pillow, but still slower than the pure-python approach. Syntax-wise it's pretty similar to the ImageIO (via pillow) approach:
%%timeit
# IIO improps (via PyAV)
# 507 µs ± 17.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
# Note: at the time of this writing this approach is still a PR.
# it needs documentation and test coverage before being merged.
import imageio.v3 as iio
props = iio.improps(gif_bytes, index=None, plugin="pyav")
n_frames = props.shape[0]
assert n_frames == 36
A: Here's some code that will get you a list with the duration value for each frame in the GIF:
from PIL import Image
gif_image = Image.open("animation.gif")
metadata = []
for i in range(gif_image.n_frames):
gif_image.seek(i)
duration = gif_image.info.get("duration", 0)
metadata.append(duration)
You can modify the above code to also capture other data from each frame such as background color index, transparency, or version. The info dictionary on each frame looks like this:
{'version': b'GIF89a', 'background': 0, 'transparency': 100, 'duration': 70}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503567",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: From a python module, called from a pl/python function, how to get the return value? Is there any reason this function call would not return 'result'?
CREATE OR REPLACE FUNCTION myfunction (input int, OUT result int) AS $$
result = mymodule.object(input,plpy)
plpy.info(" ========= EXTRA-module result: ===",result)
$$ LANGUAGE plpythonu;
=== Content of mymodule ============
def object(input,plpy):
import StringIO
try:
plan = plpy.prepare("INSERT INTO file VALUES (nextval('primary_sequence'),$1) RETURNING primary_key", ["integer"] )
except:
plpy.error(traceback.format_exc())
try:
rv = plpy.execute(plan, [ input ])
result = rv[0]["primary_key"]
plpy.info(" ========= INTRA-module result: ===",result)
return result
except:
plpy.error(traceback.format_exc())
A: I'm not to familiar with plpython, but if it is throwing an error and that isn't getting printed out or passed further up the chain you would never know.
I don't know if you are testing with a command line or not but try putting a print statement in your except blocks to see if it is just erroring out instead of returning.
A: @ed. Didn't actually need the RETURNS syntax instead of OUT, but your suggestion put me onto the answer. And yes, I feel like a real dummy. This is the beauty of having others review one's work.
with the return result added, things work out nicely. Key assumption I'd made here was that the result = syntax did not actually finish the return within the scope of the calling function. Doh!
CREATE OR REPLACE FUNCTION myfunction (input int, OUT result int) AS $$
result = mymodule.object(input,plpy)
plpy.info(" ========= EXTRA-module result: ===",result)
# This was the key bit:
return result
$$ LANGUAGE plpythonu;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Coderush search for specific issues how i can in coderush see only the issues related to a specific problem. For example i want to iterate over the clases that is not calling dispose().
Thanks.
A: You can use the CodeRush Code Issues tool window that shows a summary of code issues found inside the source code within an entire solution. It is intended to help you overview, analyze and navigate between code issues. The window has a Filter that allows you to specify code issue filtering options for the entire list. You can choose any issues you would like to see there, so you will see only the list of specific issues.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: I have a large query, how do I debug this? So, I get this error message:
EDT ERROR: syntax error at or near "union" at character 436
The query in question is a large query that consists of 12 smaller queries all connected together with UNION ALL, and each small query has two inner join statements. So, something like:
SELECT table.someid as id
,table.lastname as name
,table2.groupname as groupname
, 'Leads ' as Type
from table
inner join table3 on table3.specificid = table.someid
INNER JOIN table2 on table3.specificid=table2.groupid
where table3.deleted=0
and table.someid > 0
and table2.groupid in ('2','3','4')
LIMIT 5
UNION all
query2....
Note that table2 and table3 are the same tables in each query, and the fields from table2 and table3 are also the same, I think.
Quick question (I am still kinda new to all this):
What does 'Leads ' as Type mean? Unlike the other statements preceding an AS, this one isn't written like table.something.
Quick edit question: What does table2.groupid in ('2','3','4') mean?
I checked each small query one by one, each one works and returns a result, though the results are always empty for some reason(this may or may not be dependent on the user logged in though, as some PHP code generated this query).
As for the results themselves, most of them look something like this (they are arranged horizontally though):
id(integer)
name (character varying(80))
groupname (character varying(100))
type (unknown)
The difference in the results are twofold:
1)Most of the results contain the same field names but quite a few of them have different field lengths. Like some will say character varying (80), while others will say character varying (100), please correct me if this is actually not field length.
2)2 of the queries contain different fields, but only the id field is different, and it's probably because they don't have the "as id" part.
I am not quite sure of what the requirements of UNION ALL are, but if I think, it is meant to only work if all the fields are the same, but if that funky number changes (the one in the brackets), then are the fields considered to be different even if they have the same name?
Also, what's strange is that some of the queries returned the exact same fields, with the same field length, so I tried to UNION ALL only those queries, but no luck, still got a syntax error at UNION.
Another important thing I should mention is that the DB used to be MySQL, but we changed to PostGreSQL, so this bug might be a result of the change (i.e. code that might work in MySQL but not in PostGres).
Thanks for your time.
A: You can have only one "LIMIT xxx" clause. At the end of the query, and not before the UNION.
A: The error you get is due to missing parentheses here:
...
LIMIT 5
UNION all
...
The manual:
(ORDER BY and LIMIT can be attached to a subexpression if it is
enclosed in parentheses. Without parentheses, these clauses will be
taken to apply to the result of the UNION, not to its right-hand input
expression.)
Later example:
*
*Sum results of a few queries and then find top 5 in SQL
A: The only real way I have found to debug big queries is to break it into understandable parts and debug each subexpression independently:
*
*Does each show the expected rows?
*Are the resulting fields and types as expected?
*For union, do the result fields and types exactly match corresponding other subexpressions?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why sendAction: doesn't work while performSelector: does? I have a custom class that supports the target-action mechanism but oddly in this specific case, when I try to call the action by executing:
[NSApp sendAction:action_ to:target_ from:self]
it doesn't work, but this way does:
[target_ performSelector:action_ withObject:self];
Obviously both target_ and action_ have valid values.
This is not a big deal as I got it working.
I just can't figure out why -[NSApplication sendAction:to:from:] would not work, as this looks like a pretty basic operation. I've been using sendAction:... in the past without a problem but there seems to be some significant difference between these two, apart from the fact that sendAction has a mechanism to look for an object that responds to the message if its target is nil.
A: Are you sure NSApp isn't nil at the time you do sendAction:to:from:?
If it, nothing will happen. To make sure NSApp is a valid object, perform [NSApplication sharedApplication] at least once, or combine them:
[[NSApplication sharedApplication] sendAction:action_ to:target_ from:self];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: how to use a sql database table for 2 difference cases? (C#) in C# ::I need to use a table for 2 school classes, i am using a table for one now, but i need to use a table same as this, for another school class. how can i do this?
how many DataAdapter, DataSet or SqlConnection do I need?
A: Not knowing the exact structure of your database surely don't help to answer precisely to your question but considering the info you provided, if you use the same database engine for both of your tables, you can use one SqlConnection and as many DataAdapter, DataSet as you wish.
But you should establish a correct design of your database first and submit it would help everybody to give you a better answer than this one:-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Selenium 2 and html tables Just wondering if there is a better way to get values from a table in selenium 2. I am currently using 2 for loops I loop over each TR and within each TR I loop over all TD. so for example if I have a table row with 10 columns I loop 10 times and pull out the text value. That seems clunky to me.
My table Rows looks like so
<tr id="cTestData" class="odd">
<td class="date_activated">08/31/2011</td>
<td class="date_redeemed"> Not redeemed * </td>
<td class="expiration_date">09/01/2011</td>
<td class="product"> State of Maine </td>
<td class="value">$1.00</td>
<td class="store"> – – – </td>
<td class="offer_details">
</tr>
I think I should be able to say for each table Row get me the TD element with class = date_activated and have it return the date. I tried a few things but nothing seemed to work based on TD class name = foo
If it helps my actual code is
for(WebElement trElement : tr_collection)
{
List<WebElement> td_collection=trElement.findElements(By.xpath("td"));
System.out.println("NUMBER OF COLUMNS="+td_collection.size());
col_num=1;
HashMap actInfo = new HashMap(); // new hashmap for each line inthe result set
if(!td_collection.isEmpty() && td_collection.size() != 1 ){
for(WebElement tdElement : td_collection)
{
System.out.println("Node Name=== " + tdElement.getAttribute("class"));
System.out.println("Node Value=== " + tdElement.getText());
actInfo.put(tdElement.getAttribute("class"), tdElement.getText());
col_num++;
}
masterMap.add(actInfo);
} // end if
row_num++;
}
A: Try this:
driver.findElements(By.xpath("//tr[@class='foo']/td[@class='date_activated']"))
That will return all the TD elements with the class date_activated with a parent row with class foo. You can then loop through the elements and use getText to get the dates. This works from the root of the page.
If you would like to do it from each TR element, try:
trElement.findElement(By.xpath("./td[@class='date_activated']")).getText()
A: I found it easier to work with tables as a table. You still have to use the XPath, but it's limited to the table.
IWebElement table = driver.FindElement(By.Id("TableId")); //Get Table
List<IWebElement> Rows = new List<IWebElement>(table.FindElements(By.XPath(".//tbody/tr")));
List<List<IWebElement>> table_element = new List<List<IWebElement>>();
for (int k = 0; k < Rows.Count; k++)
{
table_element.Add(new List<IWebElement>(Rows[k].FindElements(By.XPath("./td")))); //Get all Elements from Rows
}
for (int k = 0; k < table_element[0].Count; k++)
{
if (table_element[0][k].Text == "08/31/2011")
{
table_element[0][k].Click();
}
}
A: If you prefer to use a css selector, try:
List<WebElement> myTds = driver.findElements(By.cssSelector("#tableId .date_activated"));
Note the space in "#tableId .date_activated".
This will select all the elements with class date_activated within a table with an id tableId. You will still need to loop over this list to get the text of each of your cells.
A little simpler selector might be sufficient:
driver.findElements(By.cssSelector(".date_activated"))
This will find all the elements with class date_activated on your page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Symfony: paginate a filtered list Hi i have the following code:
public function executeFilter(sfWebRequest $request) {
$c = new Criteria();
$c->add(NomenclatoreCodicePeer::LIST_CODE, $request->getParameter('list_code'), Criteria::LIKE);
$pager = new sfPropelPager('NomenclatoreCodice', sfConfig::get('app_max_jobs_on_category'));
$pager->setCriteria($c);
$pager->setPage($this->getRequestParameter('page', 1));
$pager->init();
$this->pager = $pager;
}
It works fine, but when i press "next page" button it loose the filtered items and page as if filter had not been set.
how can i fix it?
A: You should debug the queries to see if they are correct on each page.
My first guess would be that the list_code parameter is not set on subsequent requests.
Is the list_code parameter also passed to the url for the second page? And is the filter action called on the second page? Or just your default list(?) action?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails thumbs_up error Validation failed: Voteable has already been taken So thumbs_up does exactly what I want it to, but when I try to double vote I get this error Validation failed: Voteable has already been taken instead of being redirected to the previous page and Im not sure how to do that
A: OK, I dont know if its supposed to redirect automatically like Vote_fu does but I fixed it by adding an if/else in the controller to see if the current user has voted on the item or not.
unless current_member.voted_for?(@tattoo)
current_member.vote_for(@tattoo)
redirect_to :back
else
redirect_to :back
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503586",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Write to GAE datastore asynchronously In my Java app, sometimes my users do some work that requires a datastore write, but I don't want to keep the user waiting while the datastore is writing. I want to immediately return a response to the user while the data is stored in the background.
It seems fairly clear that I could do this by using GAE task queues, enqueueing a task to store the data. But I also see that there's an Async datastore API, which seems like it would be much easier than dealing with task queues.
Can I just call AsyncDatastoreService.put() and then return from my servlet? Will that API store my data without keeping my users waiting?
A: I think you are right that the Async calls seem easier. However, the docs for AsyncDatastore mention one caveat that you should consider:
Note: Exceptions are not thrown until you call the get() method. Calling this method allows you to verify that the asynchronous operation succeeded.
The "get" in that note is being called on the Future object returned by the async call. If you just return from your servlet without ever calling get on the Future object, you might not know for sure whether your put() worked.
With a queued task, you can handle the error cases more explicitly, or just rely on the automatic retries. If all you want to queue is datastore puts, you should be able to create (or find) a utility class that does most of the work for you.
A: Unfortunately, there aren't any really good solutions here. You can enqueue a task, but there's several big problems with that:
*
*Task payloads are limited in size, and that size is smaller than the entity size limit.
*Writing a record to the datastore is actually pretty fast, in wall-clock time. A significant part of the cost, too, is serializing the data, which you have to do to add it to the task queue anyway.
*By using the task queue, you're creating more eventual consistency - the user may come back and not see their changes applied, because the task has not yet executed. You may also be introducing transaction issues - how do you handle concurrent updates?
*If something fails, it could take an arbitrarily long time to apply the user's updates. In such situations, it probably would have been better to simply return an error to the user.
My recommendation would be to use the async API where possible, but to always write to the datastore directly. Note that you need to wait on all your outstanding API calls, as Peter points out, or you won't know if they failed - and if you don't wait on them, the app server will, before returning a response to the user.
A: If all you need is for the user to have a responsive interface while stuff churns in the back on the db, all you have to do is make an asynchronous call at the client level, aka do some ajax that sends the db write request, changes imemdiatelly the users display, and then upon an ajax request callback update the view with whatever is it you wish.
You can easily add GWT support to you GAE project (either via eclipse plugin or maven gae plugin) and have the time of your life doing asynchronous stuff.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails database testing and clearing Let's imagine this:
class ModTest < ActiveSupport::TestCase
test "something" do
m1 = Mod.new
# test some things
assert m1.save
end
test "whatever" do
m2 = Mod.new
# test other things
assert m2.save
end
end
Before the 2nd test case gets executed, the one called whatever, will the database be cleared, or will it contain the object added by the first test case?
Can this behaviour be controlled/customised?
A: Not 100% sure on what the default behavior is, I've been using the database_cleaner gem for this purpose. Below is the relevant code in my spec_helper.rb:
require 'database_cleaner'
RSpec.configure do |config|
# Truncated for brevity
config.before :suite do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with :truncation
end
config.before :each do
DatabaseCleaner.start
end
config.after :each do
DatabaseCleaner.clean
end
end
One caveat, if you go this route make sure you take out the config.use_transactional_fixtures line in the default spec_helper.rb if you use the transaction cleaning strategy - leaving it set to true causes transaction within transaction errors (at least for sqlite databases).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Strange Process.GetProcesses problem This code behaves strangely. If I comment the line
Process[] processlist = Process.GetProcesses();
then it works as expected. I see a 'test' message every 2 seconds. If I leave this line, it will print 2-3 'test' messages then stop. What am I doing wrong?
static void processTimerCallback(object x)
{
try
{
Process[] processlist = Process.GetProcesses();
}
catch
{
}
Console.WriteLine("test");
}
static void Main(string[] args)
{
System.Threading.Timer processTimer = new System.Threading.Timer(new TimerCallback(processTimerCallback), null, 2000, 2000);
Application.Run(form = new MainForm());
}
A: I linked to another answer that explains the problem. In a nutshell, the problem is not with the Process class, it is with the timer. It is a local variable of your Main() method, not sufficient to keep the garbage collector convinced that the timer object is still in use. Nobody can repro the problem from your code snippet because the garbage collector won't run often enough.
The difference between the Debug and Release build is the way the jitter reports the life-time of local variables. When a debugger is attached, it reports it life for the entire method body. That makes debugging easy.
Two basic fixes for this problem. The insight one:
static void Main(string[] args)
{
System.Threading.Timer processTimer = new System.Threading.Timer(new TimerCallback(processTimerCallback), null, 2000, 2000);
Application.Run(form = new MainForm());
GC.KeepAlive(processTimer);
}
And the practical one:
static System.Threading.Timer processTimer;
static void Main(string[] args)
{
processTimer = new System.Threading.Timer(new TimerCallback(processTimerCallback), null, 2000, 2000);
Application.Run(form = new MainForm());
}
A: I tried the program once as a console app and once as a windows forms app. It didn't crash on my machine, but I'm logged in as an administrator. Maybe you access a process you are not allowed to?
The code is a bit strange because you access the Console within a windows application. And I miss the attribute STAThread before the Main method (however I tried without, it didn't crash).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can't subscribe to page's likes through Real-time updates API I am trying to get updates when the like count of a page my app is on is updated. I am trying to accomplish this by using the FB Real-time Updates API
When I do a POST, with the object = "page" and the fields = "likes", I get a 400 error with the message '"likes" is an invalid field name'.
object = "page" and the fields = "name" works fine.
The documentation states you are allowed to subscribe to any public attribute.
For those playing the home game, here are the steps to reproduce the problem:
*
*Get an OAuth token for your app:
https://graph.facebook.com/oauth/access_token?client_id=<app_id>&client_secret=<secret>&grant_type=client_credentials
*Post to subscription URL:
https://graph.facebook.com/<app_id>/subscriptions
POST Variables:
'access_token' => `<access token from step 1>`,
'object' => 'page',
'fields' => 'likes',
'callback_url' => `<a callback url>`,
'verify_token' => 'testingstring123'
A: This isn't supported - from the section 'Real-time Updates' on https://developers.facebook.com/docs/reference/api/page/ :
The Page object supports Real-time Updates for picture, tagged and
checkins connections.
Note: Real-time updates are not yet supported for the total number of
Page checkins.
A: Subscribing to likes is only for pages that a user likes. The 'likes' object is what pages a user or page likes, not the count of how many people like your page, which cannot be subscribed to.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Transform Array to Output in Certain Manner PHP
<?php
$result = $sth->fetchAll(PDO::FETCH_NUM);
print_r($result); //or var_dump($result); for more info
foreach($result as $row){
$half = array_splice($row,0,5);
echo implode(" ",$half)."<br /><br />Merchant Offered:<br />".implode(" ",$row);
}
?>
SQL
SELECT uFName, uLName, listTitle, listPropPrice, listCmt, listDt, mFName, mLName, moAmt, moDtOff
FROM User U, Listing L, Merchant M, MerchantOffer MO
WHERE U.uID = L.uID
and L.listID = MO.listID
and M.mID = MO.mId
Currently outputting:
http://i.stack.imgur.com/qAtcf.png
How do I get it to NOT output the first big array :
Array ( [0] => Array ( [0] => Joseph [1] => Dickinson [2] => Need Xbox 360 [3] => 150 [4] => I need one quick! [5] => 2011-09-15 [6] => John [7] => Doe [8] => 149.99 [9] => 2011-09-15 ) [1] => Array ( [0] => Joseph [1] => Dickinson [2] => Need Xbox 360 [3] => 150 [4] => I need one quick! [5] => 2011-09-15 [6] => Jane [7] => Doe [8] => 154.99 [9] => 2011-09-15 ) [2] => Array ( [0] => Joseph [1] => Dickinson [2] => Need Xbox 360 [3] => 150 [4] => I need one quick! [5] => 2011-09-15 [6] => Diana [7] => Matthews [8] => 160.00 [9] => 2011-09-15 ) [3] => Array ( [0] => Joseph [1] => Dickinson [2] => Need Xbox 360 [3] => 150 [4] => I need one quick! [5] => 2011-09-15 [6] => Amanda [7] => Koste [8] => 174.99 [9] => 2011-09-15 ) [4] => Array ( [0] => Warren [1] => Kennan [2] => Need New Sofa [3] => 1000 [4] => Need one quick [5] => 2011-09-15 [6] => Diana [7] => Matthews [8] => 495.99 [9] => 2011-09-15 ) [5] => Array ( [0] => Warren [1] => Kennan [2] => Need New Sofa [3] => 1000 [4] => Need one quick [5] => 2011-09-15 [6] => Amanda [7] => Koste [8] => 489.99 [9] => 2011-09-15 ) ) Joseph Dickinson Need Xbox 360 150 I need one quick!
and instead TO POST the output like:
Joseph Dickinson Need Xbox 360 150 I need one quick!
Merchant Offered:
2011-09-15 John Doe 149.99 2011-09-15
Thanks
A: Try something like that
The code
<?php
...
// Do a loop on each row of your result / repeat the display
foreach ($result as $row) {
for ($i=0;$i<=count($row); $i++) {
echo $row[$i].' ';
if ($i==6) {
echo '<br/><br/>Merchant Offered:<br/>';
}
}
echo '<br/><br/>';
}
Output would be
Joseph Dickinson Need Xbox 360 150 I need one quick!
Merchant Offered:
2011-09-15 John Doe 149.99 2011-09-15
Joseph Dickinson Need Xbox 360 150 I need one quick!
Merchant Offered:
2011-09-15 Jane Doe 149.99 2011-09-15
...
Two stuff:
*
*Not sure output would be exactly what you need, do you really want to repeat the user request on each line or do you want one time and after all merchantoffer? like below
Joseph Dickinson Need Xbox 360 150 I need one quick!
Merchant Offered:
2011-09-15 John Doe 149.99 2011-09-15
2011-09-15 Jane Doe 149.99 2011-09-15
...
In that case you need to add an identifier on people request to group the line for example...
*Maybe you can concatenate your informations into your sql statement to improve the readability of your code and avoid the line : if ($i==6) which doesn't really represents something understandable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Bitnami Djangostack + Eclipse IDE? I'm trying to setup the Eclipse (with pyDev) to work with Bitnami Djangostack in Mac OS X. I have installed the Djangostack and it works all right.
Problem is that I can't get the Eclipse to understand Djangostack. I've added the Djangostack python interpreter to the PyDev-setup. And also I added the apps/django folder to the Libraries. apps/django folder exist in the djangostack folder. Still, when I'm trying to create PyDev Django project, Eclipse cannot find Django (import django do not work). Any ideas what other things I'd have to setup before Eclipse can find the Djangostack installation?
A: It seems it cannot find the django package.
Make sure you're adding it to the PYTHONPATH.
i.e.:
if it's installed at:
/foo/bar/django
/foo/bar/django/__init__.py
make sure that /foo/bar/ is in your interpreter PYTHONPATH (and make sure that /foo/bar/django is NOT in the PYTHONPATH).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cannot find the asymmetric key -- because it does not exist or you do not have permission I am trying to be able to run a .Net dll through SQL using the CLR - I am doing so unsuccessfully.
I am following the instructions here
So I am doing the following:
CREATE ASYMMETRIC KEY AKEY_SqlClr FROM EXECUTABLE FILE = 'C:\dlls\mySqlClr.dll'
Which works fine and creates the Key, then I try to do the following:
CREATE LOGIN SQLCLR_AsymKeyLogin FROM ASYMMETRIC KEY AKEY_SqlClr
And I get the error:
Cannot find the asymmetric key 'AKEY_SqlClr', because it does not exist or you do not have permission.
How could I not have permissions to this? I have verified that I have CREATE LOGIN permissions. Any ideas?
A: Logins are server principals and as such they cannot be created from keys stored in user databases. You must create the key from assembly in master database:
use master;
CREATE ASYMMETRIC KEY AKEY_SqlClr FROM EXECUTABLE FILE = 'C:\dlls\mySqlClr.dll';
CREATE LOGIN SQLCLR_AsymKeyLogin FROM ASYMMETRIC KEY AKEY_SqlClr;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How can I override BorderBrush? I have a style to a textbox, and I want in the application layer override de BorderBrush of this style.
I tried: d:LayoutOverrides="BorderBrush". But this doesn't work.
I want the same style, but with a red BorderBrush.
How can I do this please?
Thank you.
A: as you mentioned Blend in your tags: you can right-click a textbox search templates and create new ones from the existing (Edit a Copy). This will extract the complete definition of the textbox and you can change everything you want there.
Here is everything explained step-by-step: Create or edit a control template
A: Base your style on your old one and change the Border brush
<Style TargetType="TextBox" BasedOn="{StaticResource oldBrushKey}">
<Setter Property="BorderBrush" Value="Red" />
</Style>
or if it's the default style you want to override use
BasedOn="{StaticResource {x:Type TextBox}}"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: IIS Single Sign on with Active Directory account I have a client. They will login their window by using the account in Active Directory and they want to create a web that authenticate user automatically using their current window account (i.e. Single sign on the web) by using Window Authenication in Asp.net.
As their company is quite big, therefore, their structure of Active directory is quite complex.
The following is the illustration (the below showed only a simplified version):
ABC.com
|-------- XX.ABC.com
|-------- YY.ABC.com
|-------- ZZ.ABC.com
They have a root domain called ABC.com and there are several subdomains under it.
The IIS server is placed under "XX.ABC.com". I believe that all users under this domain have no problem for single sign on.
However, could those user in YY.ABC.com and ZZ.ABC.com be logged in the site using the AD account?
if not, then
if the server is moved to the root domain (i.e. ABC.com), could users in all subdomains(i.e. XX.ABC.com, YY.ABC.com and ZZ.ABC.com) be logged in the site?
Howver, client said that "moving the server to root domain will cause timeout problem because it may need to go through all subdomains to search for a single user". Is it true?
Is there any method that can keep the server in XX.ABC.com but still can authenicate YY.ABC.com and ZZ.ABC.com?
A: You can leave the server in the XX domain. Clients in YY and ZZ may (probably) need to have *.xx.abc.com added to their Local Intranet zone in IE.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: backbone "mouseleave" is fired when the "click" event is fired When the cursor leaves a div, the mouseleave event is fired, but if I click on a button inside the div, both the mouseleave and click events fire, although my cursor is still inside the div.
here is the code:
events: {
'mouseleave': 'test_1',
'click button': 'test_2'
},
test_1: function() {
alert('mouseleave!');
},
test_2: function() {
alert('click!');
}
When I click the botton the mouseleave alert appears. Why??
A: Try changing your alert to console.log. I think it's the alert in test_2 that is causing you to leave the div.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Query transactions that occured only at a certain time I am trying to run a select query that will pull all meds scheduled at 2300 for a date range. Is there a way I can convert the scheduled date/time to just hour? This is what I have so far:
SELECT DISTINCT USERCODE,
TRANSACTIONID,
ACTION,
TRANSACTIONHOUR,
SOURCE,
RXNUMBER,
DESCRIPTION,
MASTERPATIENTID,
FACILITYCODE,
ADMINISTRATIONTIME
FROM ( ABC.TL TL
INNER JOIN
ABC.S_VIEW S_VIEW
ON (TL.RXNUMBER = S_VIEW.RXNUMBER))
INNER JOIN
ABC.PV PATIENTVISIT
ON (TL.MASTERPATIENTID = PV.MASTERPATIENTID)
WHERE (TL.USERCODE NOT IN ('ABC'))
AND (TL.ACTION IN ('A', 'DC'))
AND (TL.TRANSACTIONHOUR BETWEEN to_date('2011-07-01 00:00:00', 'yyyy/mm/dd hh24:mi:ss') AND to_date('2011-09-30 23:59:59', 'yyyy/mm/dd hh24:mi:ss')
I would like the query to include all dispense during the specified dates but only at 2300 time. Database is oracle 10g.
A: First, you have given the date string in a different format and the format in different format. Make it consistent.
Try this:
SELECT DISTINCT USERCODE,
TRANSACTIONID,
ACTION,
TRANSACTIONHOUR,
SOURCE,
RXNUMBER,
DESCRIPTION,
MASTERPATIENTID,
FACILITYCODE,
ADMINISTRATIONTIME
FROM ( ABC.TL TL
INNER JOIN
ABC.S_VIEW S_VIEW
ON (TL.RXNUMBER = S_VIEW.RXNUMBER))
INNER JOIN
ABC.PV PATIENTVISIT
ON (TL.MASTERPATIENTID = PV.MASTERPATIENTID)
WHERE (TL.USERCODE NOT IN ('ABC'))
AND (TL.ACTION IN ('A', 'DC'))
AND (TL.TRANSACTIONHOUR BETWEEN to_date('2011/07/01 00:00:00', 'yyyy/mm/dd hh24:mi:ss') AND to_date('2011/09/30 23:59:59', 'yyyy/mm/dd hh24:mi:ss')
AND TO_CHAR(TL.TRANSACTIONHOUR, 'HH24MI') = '2300' --THIS IS THE NEW CONDITION
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do i convert this to XML layout format? This is the code comming from the Activity file. I would like to have the layout looks the same but i want that code in XML format. Because it's so damn disturbing to have some code in dynamically and some in XML files. So please can someone make this from dynamically to xml layout?
protected void initLayout() {
// root view - GRN
LinearLayout rootView = new LinearLayout(this.getApplicationContext());
rootView.setOrientation(LinearLayout.VERTICAL);
this.mText = new TextView(this.getApplicationContext());
this.mText.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
rootView.addView(this.mText);
this.eventLayout = new LinearLayout(this.getApplicationContext());
this.eventLayout.setOrientation(LinearLayout.VERTICAL);
ScrollView sv_obj = new ScrollView(this.getApplicationContext());
sv_obj.addView(this.eventLayout);
rootView.addView(sv_obj);
this.setContentView(rootView);
}
A: <LinearLayout android:orientation="vertical>
<TextView android:width="wrap_content android:height="wrap_content/>
<ScrollView>
<LinerLayout android:orientation="vertical>
</LinearLayout>
</ScrollView>
</LinearLayout>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Recommended clang optimization level? What's the "standard" optimization level used for clang? I believe that "O2" is a good choice for gcc - does that hold for clang also, or is there a generally better alternative?
A: -O2 and -Os are both good choices for general use with clang.
A: -O3 will usually give you both the smallest and fastest code, but does tend to expose non obvious bugs in your code.
In general, you should make sure your code runs fine with all possible optimizations.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: EWS API - Create calendar and share with reviewer permissions I'm having some trouble on creating and share a calendar with review permissions using Exchange Webservice API .NET.
At the moment this is my code:
Folder addCalendar = new Folder(service);
addCalendar.DisplayName = name;
addCalendar.FolderClass = "IPF.Appointment";
var perm = new FolderPermission(new UserId("reviewer@test.com"),
FolderPermissionLevel.Reviewer);
addCalendar.Permissions.Add(perm);
addCalendar.Save(WellKnownFolderName.MsgFolderRoot);
The calendar is created, in my account I can see the calendar and the user 'reviewer@test.com' has the correct permissions.
The problem is: The calendar doesn't show at the reviewer's account.
A: You have to do two things:
Set the appropiate permissions:
var folder = Folder.Bind(service, WellKnownFolderName.Calendar);
folder.Permissions.Add(new FolderPermission("someone@yourcompany.com",
FolderPermissionLevel.Reviewer));
folder.Update();
Then, send an invitation message. Now, this is the hard part. The message format is specifified in [MS-OXSHARE]: Sharing Message Object Protocol Specification. The extended properties are defined in [MS-OXPROPS]: Exchange Server Protocols Master Property List. You need to create a message according to that specification and send it to the recipient.
EDITED:
To set the sharing properties on the element, use extended properties.
First, define the properties. For example, the PidLidSharingProviderGuidProperty is defined as follows:
private static readonly Guid PropertySetSharing = new Guid("{00062040-0000-0000-C000-000000000046}");
private static readonly ExtendedPropertyDefinition PidLidSharingProviderGuidProperty = new ExtendedPropertyDefinition(PropertySetSharing, 0x8A01, MapiPropertyType.CLSID);
private static readonly ExtendedPropertyDefinition ConversationIdProperty = new ExtendedPropertyDefinition(0x3013, MapiPropertyType.Binary);
You can then set the property on a new item using the SetExtendedProperty method:
item.SetExtendedProperty(PidLidSharingProviderGuidProperty, "somevalue");
A: I figured out how to programmatically send a sharing invitation within an organization through EWS. May not answer all your questions, but it's a good start to understanding how in-depth you gotta get to actually do it. Heres the link
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Should I convert my Grails domain relations to use Hibernate Bags? In Grails 1.3.7 I've spent quite some time to convert my domain class relations according to Burt's suggestions in http://www.infoq.com/presentations/GORM-Performance
Now, Grails 2 supports Hibernate's Bags and I am considering to revert my changes back to hasMany/belongsTo.
*
*With which option will I be more future-proof?
*Which problems might arise if I stick to the manual/explicit implementation?
*Which problems might arise if I switch to Bags?
*Is there any advantage in either variant compared to the other?
Note that the application will see long-term improvements over many years (so no 'deploy-and-forget' :).
UPDATE: One main concern is how much hassle it would incur in regards to manual changes in the database if I did the change after the app goes live. Currently it is unreleased, so it poses to be reasonable before Go-Live.
UPDATE: THE ANSWER
In the blogpost 'Hibernate Bags in Grails 2.0' dated November 2011, Burt Beckwith describes issues with Bags in Grails 2 and concludes:
So I guess I’m back to advocating the approach from my earlier talks;
don’t map a collection of Books in the Author class, but add an Author
field to the Book class instead
So the answer is to stick with the converted (i.e. non-set/-list/-bag) variant.
Please vote for re-opening this thread so it may be answered & accepted in correct fashion.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How pass username/password command line options to jndi grails.naming.entries in Config.grooy I have a jndi entry in Config.groovy like so:
grails.naming.entries = ['jdbc/test_me': [
type: "javax.sql.DataSource", //required
auth: "Container", // optional
description: "Data source for ...", //optional
//properties for particular type of resource
url: "jdbc:oracle:thin:@testserver:1521:SID",
username: "someuser",
password: "somepassword",
driverClassName: "oracle.jdbc.driver.OracleDriver",
maxActive: "8", //and so on
maxIdle: "4"
]
]
This works fine but I do not want to store the username/password in the Config.groovy source. Is there a way to pass the credential from command line options, -Duser=someuser -Dpass-somepassword, to grails.naming.entries in Config.groovy?
A: Your best bet is to use externally stored configuration settings.
This allows Grails to load in unique settings for the production (or test or dev) server, that are not stored within the grails application WAR. The other nice thing is that these can be updated without replacing any code, just restart the application on the server.
Example from this great article on the subject:
// Put this at the top of your Config.groovy
// Copied from http://blog.zmok.net/articles/2009/04/22/playing-with-grails-application-configuration
if(System.getenv("MY_GREAT_CONFIG")) {
println( "Including configuration file: " + System.getenv("MY_GREAT_CONFIG"));
grails.config.locations << "file:" + System.getenv("MY_GREAT_CONFIG")
} else {
println "No external configuration file defined."
}
Now set the environment variable MY_GREAT_CONFIG to the absolute path for the external groovy config. See the link for a more complete example.
A: It appears any options added via grails.config.locations are not available in Config.groovy. "${System.getProperty('password')}".toString() is the only way this worked.
Here are my test results:
Added at the beginning of Config.groovy:
if (new File("${userHome}/.grails/${appName}-config.groovy").exists()){
grails.config.locations = ["file:${userHome}/.grails/${appName}-config.groovy"]
}
Added at the end of Config.groovy:
println "(*) grails.config.locations = ${grails.config.locations}"
def f = new File("${userHome}/.grails/${appName}-config.groovy")
f.eachLine{ line -> println line }
println "test password: ${testPassword}" // same result ([:]) with grails.config.testPassword
println "${System.getProperty('password')}"
grails.naming.entries = ['jdbc/test_mnr': [
type: "javax.sql.DataSource", //required
auth: "Container", // optional
description: "Data source for ...",
url: "jdbc:oracle:thin:@server:1521:SID",
username: "username",
password: "${System.getProperty('password')}".toString(),
driverClassName: "oracle.jdbc.driver.OracleDriver",
maxActive: "8",
maxIdle: "4",
removeAbandoned: "true",
removeAbandonedTimeout: "60",
testOnBorrow: "true",
logAbandoned: "true",
factory: "org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory",
validationQuery: "select count(*) from dual",
maxWait: "-1"
]
]
Content of user.home/.grails/mnroad-config.groovy:
testPassword='some_password'
Here is the result when run with -Dpassword=somePassword :
(*) grails.config.locations = [file:C:\Documents and Settings\carr1den/.grails/mnroad-config.groovy]
testPassword=some_password
test password: [:]
somePassword
The grailsApplication.config.testPassword option is available after the app initializes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: TFS 2010 msbuild overwrites different versions of referenced library in output directory I'm building Web project using TFS 2010. The project contains Silverlight client and .NET/C# server side. Both of these (client and server) are referencing one 3rd party library for which we have Silverlight and .NET version, but both versions use the same name. The problem is that msbuild with outdir property specified puts all the libraries to one flat hierarchy in output directory so one library overwrites the other.
I know that one solution would be to modify build template and not specify outdir, but this brings problems with other parts of the build template (I had problem with unit tests and I read about people having problems with putting output to _PublishedWebsites).
Another workaround would be to rename that library/libraries so the names will not collide. But this will not be solution if there is a lot of such libraries.
I'd like to find some clean solution. Do you know about some elegant way how to solve this?
A: According to Microsoft there are (at least) three ways of referencing assemblies:
*
*install the assembly in the GAC
*specify the assembly in the application configuration
*or use the AssemblyResolve Event
The GAC is no option here, as you would have the same problem (same names).
Using the AssemblyResolve Event and then use Assembly.LoadFrom would possibly a way of doing it, but easier would be imho ...
... to do it the second mentioned way: specify the assembly in the application configuration. Here you basically edit the App.config like so:
<configuration>
<runtime>
<assemblyBinding xmlns=”urn:schemas-microsoft-com:asm.v1″>
<probing privatePath=”bin;Silverlight;ParentFolder\SubFolder;”/>
</assemblyBinding>
</runtime>
</configuration>
and the application will search for the assemblies in specified directories.
So, you could create specific folders (possibly "NET" and "Silverlight" or the like), copy the respective assembly into that folder and probe for the assembly in the proper folder as described above.
Considering that when no reference is specified in the application configuration the application will be looking into either the same folder as the referencing assembly or into a folder with the name of the referencing assembly, you could also simply create 2 folders with the same name as the respective application (say "Client" and "Server" if they are called "Client.exe" and "Server.exe") and copy the proper assembly into that folder. In that case there would not even be any need to change the application configuration file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How would I use Procs in Ruby on Rails? There are a few helpers I am using in my project, which I just thought that I could maybe treat as Procs, as they do very specific tasks and can be used by very different components.
I've used Procs in small Ruby projects, mainly when learning the language, and I thought that this would be a good occasion to put them to use.
My question is, where would I put the Procs in the Rails folder structure? Are there any guidelines or reccomdendations for this? Is it considered good practice?
A: I am a bit puzzled what the advantage would be of using Procs over using simple methods? So if you could give some examples, that would be nice.
Anyways: since Procs can be stored in a variable, I would declare a module inside the lib folder, and define the procs as variables, constants, or methods returning the proc. Something like this
module ProcContainer
def proc_1(factor)
Proc.new { |n| n*factor }
end
PROC_2 = Proc.new { |n| 2 * n }
end
which would be used as
gen_proc = ProcContainer.proc_1(6)
result = gen_proc(3)
other_proc = ProcContainer.PROC_2(4)
The advantage of the method is obvious i guess, since it will return a new Proc object every time it is called, while the constant is only evaluated once.
(of course you should change the naming to something more appropriate)
A: Ruby has amazing syntax for blocks, so we tend to favor them over explicitly making procs. The downside of blocks is that they need to be executed immediately when the called method yields to them (procs don't have that limitation). That is in place for performance reasons, but you can easily package up a block as a proc, and store it somewhere else for later, or pass it down to another method. So even though you are probably using procs every day, you don't really realize it, because your interface to them is through the block syntax.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Date arithmetic in SQL on DB2/ODBC I'm building a query against a DB2 database, connecting through the IBM Client Access ODBC driver. I want to pull fields that are less than 6 days old, based on the field 'a.ofbkddt'... the problem is that this field is not a date field, but rather a DECIMAL field, formatted as YYYYMMDD.
I was able to break down the decimal field by wrapping it in a call to char(), then using substr() to pull the year, month and day fields. I then formatted this as a date, and called the days() function, which gives a number that I can perform arithmetic on.
Here's an example of the query:
select
days( current date) -
days( substr(char(a.ofbkddt),1,4) concat '-' -- YYYY-
concat substr(char(a.ofbkddt),5,2) concat '-' -- MM-
concat substr(char(a.ofbkddt),7,2) ) as difference, -- DD
a.ofbkddt as mydate
from QS36F.ASDF a
This yields the following:
difference mydate
2402 20050402
2025 20060306
...
4 20110917
3 20110918
2 20110919
1 20110920
This is what I expect to see... however when I use the same logic in the where clause of my query:
select
days( current date) -
days( substr(char(a.ofbkddt),1,4) concat '-' -- YYYY-
concat substr(char(a.ofbkddt),5,2) concat '-' -- MM-
concat substr(char(a.ofbkddt),7,2) ) as difference, -- DD
a.ofbkddt as mydate
from QS36F.ASDF a
where
(
days( current date) -
days( substr(char(a.ofbkddt),1,4) concat '-' -- YYYY-
concat substr(char(a.ofbkddt),5,2) concat '-' -- MM
concat substr(char(a.ofbkddt),7,2) ) -- DD
) < 6
I don't get any results back from my query, even though it's clear that I am getting date differences of as little as 1 day (obviously less than the 6 days that I'm requesting in the where clause).
My first thought was that the return type of days() might not be an integer, causing the comparison to fail... according to the documentation for days() found at http://publib.boulder.ibm.com/iseries/v5r2/ic2924/index.htm?info/db2/rbafzmst02.htm, it returns a bigint. I cast the difference to integer, just to be safe, but this had no effect.
A: You're going about this backwards. Rather than using a function on every single value in the table (so you can compare it to the date), you should pre-compute the difference in the date. It's costing you resources to run the function on every row - you'd save a lot if you could just do it against CURRENT_DATE (it'd maybe save you even more if you could do it in your application code, but I realize this might not be possible). Your dates are in a sortable format, after all.
The query looks like so:
SELECT ofbkddt as myDate
FROM QS36F.ASDF
WHERE myDate > ((int(substr(char(current_date - 6 days, ISO), 1, 4)) * 10000) +
(int(substr(char(current_date - 6 days, ISO), 6, 2)) * 100) +
(int(substr(char(current_date - 6 days, ISO), 9, 2))))
Which, when run against your sample datatable, yields the following:
myDate
=============
20110917
20110918
20110919
20110920
You might also want to look into creating a calendar table, and add these dates as one of the columns.
A: What if you try a common table expression?
WITH A AS
(
select
days( current date) -
days( substr(char(a.ofbkddt),1,4) concat '-' -- YYYY-
concat substr(char(a.ofbkddt),5,2) concat '-' -- MM-
concat substr(char(a.ofbkddt),7,2) ) as difference, -- DD
a.ofbkddt as mydate
from QS36F.ASDF a
)
SELECT
*
FROM
a
WHERE
difference < 6
A: Does your data have some nulls in a.ofbkddt? Maybe this is causing some funny behaviour in how db2 is evaluating the less than operation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android: SharedPreference errors after force close I'm getting some weird effects after I force close my app. When the app is closed with finish(), everything is fine. I have some variables saved in a sharedPreferences so when the app is loaded again, it can restore those variables into the UI. However, if I force close the app and THEN try to continue where it had left off, some variables start "acting funny". By that I mean (in onCreate) I check to see if a string, loaded from the sharedPreferences, equals a value (crunched down version):
String namec;
private static final String TAG = "MyActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//namec was set as "forest" in a previous activity
//which is bypassed if the user selects continue
//from the main menu
SharedPreferences pathtaken = getSharedPreferences("pathtakenpref", MODE_WORLD_READABLE);
namec = pathtaken.getString("namec", "Unknown");
ImageView v1 = (ImageView) findViewById(R.id.pathpic1);
RelativeLayout v2 = (RelativeLayout) findViewById(R.id.pathmain);
Log.i(TAG, "namec= " + namec);
if(namec == "forest"){
v1.setImageResource(R.drawable.forest);
v2.setBackgroundResource(R.drawable.forestrepeat);
}
}
What happens here is namec, does in fact, equal "forest". I send the value to the log and it shows the variable exactly as it should be ("forest"). Yet it won't run the code inside of the if{}. It's giving me nightmares. I've been stuck on this for a week!
In the same code, I load a different set of sharedPreferences (labeled as TRHprefs) and each one of those (6 integers and 3 strings) load up and display just fine. I even add an if{} to test 1 string and 1 integer from TRHprefs... they both came back true.
Q.1: Is there anything that can cause my sharedPreferences xml to become, somehow, corrupted on a force close?
Q.2: Is there a way for me to view the xml file before and after I use force close to help debug the situation. Thanks so much!
A: Its a String. Try this:
if("forest".equals(namec)){
A: If you want to compare two String you need to use this:
if(namec.equals("forest")){
v1.setImageResource(R.drawable.forest);
v2.setBackgroundResource(R.drawable.forestrepeat);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Where do I put my credentials when using Ivy and a private company repository? I'm using Ant + Ivy, and my company has recently set up a Nexus server for our own private libraries. Ivy can get dependencies from the Nexus server by using a ibilio resolver and m2compatible=true, but I have to put my credentials in a ivysettings.xml file.
How are different developers supposed to store their credentials?
Is the ivysettings.xml file not supposed to be commited in vcs?
I really don't want to store my password in plain text.
A: The ivysettings.xml sample in Mark O'Connor's answer should actually be as follows:
<ivysettings>
<property name="repo.host" value="default.mycompany.com" override="false"/>
<property name="repo.realm" value="Sonatype Nexus Repository Manager" override="false"/>
<property name="repo.user" value="deployment" override="false"/>
<property name="repo.pass" value="deployment123" override="false"/>
<credentials host="${repo.host}" realm="${repo.realm}" username="${repo.user}" passwd="${repo.pass}"/>
..
</ivysettings>
Means, the property names should not be surrounded by ${...} (it took me quite a while to find out why this failed - but now I know how to debug ivy access - use commons-httpclient-3.0, set everything to verbose etc.)
A: Use a settings file with properties controlling the Nexus credentials:
<ivysettings>
<property name="repo.host" value="default.mycompany.com" override="false"/>
<property name="repo.realm" value="Sonatype Nexus Repository Manager" override="false"/>
<property name="repo.user" value="deployment" override="false"/>
<property name="repo.pass" value="deployment123" override="false"/>
<credentials host="${repo.host}" realm="${repo.realm}" username="${repo.user}" passwd="${repo.pass}"/>
..
..
</ivysettings>
When you run the build you can then specify the true username and password:
ant -Drepo.user=mark -Drepo.pass=s3Cret
Update/Enhancement
Storing passwords as properties on the file system requires encryption.
Jasypt has a command-line program that can generate encrypted strings:
$ encrypt.sh verbose=0 password=123 input=s3Cret
hXiMYkpsPY7j3aIh/2/vfQ==
This can be saved in the build's property file:
username=bill
password=ENC(hXiMYkpsPY7j3aIh/2/vfQ==)
The following ANT target will decrypt any encrypted ANT properties:
<target name="decrypt">
<taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy" classpathref="build.path"/>
<groovy>
import org.jasypt.properties.EncryptableProperties
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor()
encryptor.setPassword(properties["master.pass"])
Properties props = new EncryptableProperties((Properties)properties, encryptor);
props.propertyNames().each {
properties[it] = props.getProperty(it)
}
</groovy>
</target>
Of course to make this work, the password used for encrypting the properties needs to be specified as part of the build.
ant -Dmaster.pass=123
This means the solution is only good for hiding data at rest.
A: For my purposes the command-line credentials weren't an option because I'm running through Jenkins and they'd be clearly pasted on the build output, so here was my solution which strikes a balance by being reasonably secure.
*
*Create a properties file in your home directory that contains the sensitive information (we'll call it "maven.repo.properties")
repo.username=admin
repo.password=password
*Near the top of your build file, import the property file
<property file="${user.home}/maven.repo.properties"/>
*In your publish target under build.xml, set your ivy settings file location (which does get checked in to code control) but embed your credential properties
<target name="publish">
<ivy:settings file="ivysettings.xml">
<credentials host="repohostname" realm="Artifactory Realm" username="${repo.username}" passwd="${repo.password}"/>
</ivy:settings>
<!-- ivy:makepom and ivy:publish targets go here -->
</target>
*Create your ivysettings.xml just as you did before, but strip out the username and passwd attributes
You can then leverage your operating system's permissions to make sure that the maven.repo.properties file is properly hidden from everybody except you (or your automatic build implementation).
A: Additional to Mark O'Connor's answer you can hide the password from your daily work and from the prying eyes of your workmates by putting these properties either into the antrc startup file or into the environment variables used by ant. Please note that they are not very secure in either place.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Reference to a temporary variable - why doesn't compiler detect it? I hope this is not a duplicate, I've read a number of related questions but no one seemed to cover this case:
#include <iostream>
int* return_dangling_p()
{
int x = 1;
return &x; // warning: address of local variable 'x' returned
}
void some_func()
{
int x = 2;
}
int main(int argc, char** argv)
{
// UB 1
int* p = return_dangling_p();
std::cout << *p; // 1
some_func();
std::cout << *p; // 2, some_func() wrote over the memory
// UB 2
if (true) {
int x = 3;
p = &x; // why does compiler not warn about this?
}
std::cout << *p; // 3
if (true) {
int x = 4;
}
std::cout << *p; // 3, why not 4?
return 0;
}
I thought these are two cases of the same undefined behaviour. The output is 1233 while I (naively?) expected 1234.
So my question is: why doesn't compiler complain in the second case and why the stack isn't rewritten like in the case of 12? Am I missing something?
(MinGW 4.5.2, -Wall -Wextra -pedantic)
EDIT: I'm aware that it's pointless to discuss outputs of UB. My main concern was if there's any deeper reason to why one is detected by the compiler and the other isn't.
A:
why doesn't compiler complain in the second case
I am not sure. I suppose it could.
why the memory isn't rewritten like in the case of 12
It's undefined behaviour. Anything can happen.
Read on if you're really curious...
When I compile your code as-is, my compiler (g++ 4.4.3) places the two x variables in UB 2 at different locations on the stack (I've verified this by looking at the disassembly). Therefore they don't clash, and your code also prints out 1233 here.
However, the moment I take the address of the second x, the compiler suddenly decides to place it at the same address as the first x, so the output changes to 1234.
if (true) {
int x = 4; // 3, why not 4?
&x;
}
Now, this is what happens when I compile without any optimization options. I haven't experimented with optimizations (in your version of the code, there's no reason why int x = 4 can't be optimized away completely).
The wonders of undefined behaviour...
A: I'm not sure why the compiler doesn't complain. I suppose it's not a very common use-case, so the compiler authors didn't think to add a warning for it.
You can't infer anything useful about behaviour you observe when you are invoking undefined behaviour. The final output could have been 3, it could have been 4, or it could have been something else.
[If you want an explanation, I suggest look at the assembler that the compiler produced. If I had to guess, I'd say that the compiler optimised the final if (true) { ... } away entirely.]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Node.js port issue on Heroku cedar stack I'm running a basic Express app in Node.js and trying to deploy to Heroku. The app works fine locally and I believe my setup with Heroku has gone well up until starting the server where i get the following error:
2011-09-21T16:42:36+00:00 heroku[web.1]: State changed from created to starting
2011-09-21T16:42:39+00:00 app[web.1]: Express server listening on port 3000 in production mode
2011-09-21T16:42:40+00:00 heroku[web.1]: Error R11 (Bad bind) -> Process bound to port 3000, should be 12810 (see environment variable PORT)
2011-09-21T16:42:40+00:00 heroku[web.1]: Stopping process with SIGKILL
2011-09-21T16:42:40+00:00 heroku[web.1]: Process exited
this is currently all i have in my app.js
app.listen(3000);
I did also run this as mentioned on Heroku's getting started.
$ heroku config:add NODE_ENV=production
Adding config vars:
NODE_ENV => production
I believe I just need to set up the port for production? Thanks.
A: Can you show the entire section of code where you call listen? You should be checking for the process environment variable PORT, not just hardcoding it to 3000. From their docs:
var port = process.env.PORT || 3000;
app.listen(port, function() {
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: UIPopoverController in application window I am creating a UIPopoverController from the application delegate and I want to center it on the window, how ca I do that?
A: You can specify the rectangle that it is anchored to when you display it. Just specify an rectangle and direction that guarantees it will be displayed in the position you want.
It does sound like you may be doing something that would be best done by presenting a custom UIView as a new subview instead of using a popover. The popover will always have the little arrow coming off the side.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: python3: list() from generator: strange behaviour when yielding item-changed lists I have a generator defined like this:
def gen():
r = [0]
yield r
r[0] = 1
yield r
r[0] = 2
yield r
it will yield three lists of one element going from 0 to 2:
>>> a = gen()
>>> next(a)
[0]
>>> next(a)
[1]
>>> next(a)
[2]
>>> next(a)
Traceback (most recent call last):
File "<pyshell#313>", line 1, in <module>
next(a)
StopIteration
Now, when I go to make a list from the generator, I got this:
>>> list(gen())
[[2], [2], [2]]
That is, it seems to yield each time the very last computed value.
Is this a python bug or am I missing something?
A: It's not a bug, it does exactly what you told it to do. You're yielding the very same object several times, so you get several references to that object. The only reason you don't see three [2]s in your first snippet is that Python won't go back in time and change previous output to match when objects are mutated. Try storing the values you get when calling next explicitly in variables and check them at the end - you'll get the same result.
Such an iterator is only useful if no yielded value is used after the iterator is advanced another time. Therefore I'd generally avoid it, as it produces unexpected results when trying to pre-compute some or all results (this also means it breaks various useful tricks such as itertools.tee and iterable unpacking).
A: You want:
def gen():
for i in (0,1,2):
yield [i]
That will yield three lists, not one list three times.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Help with a really strange COM+ callstack We have a legacy COM+ dll that is called by an old ASP application. It is periodically crashing, and the call stack is very strange looking
It appears that a call to DllUnregisterServer and to CoInstall appear within the call stack (we don't dynamically install/uninstall anything within the code -- it's just querying a database).
I am wondering if it is possible that MSI "file protection" is kicking in and causing the crash. Do you think that's possible? any way I can dig up more information? (it's an old VFP applicaiton, so I don't think I can get proper debug symbols)
Here's the call stack:
Call Stack:
vfp9t! + 0x2272f
vfp9t!VFPDllGetClassObject + 0xb6
ctcvccomasyncproxy!DllGetClassObject + 0x3e
ole32!CoInitializeSecurity + 0x5ff5
ole32!CoInitializeSecurity + 0x5bdc
ole32!CoGetTreatAsClass + 0x2a2
ole32!CoInitializeSecurity + 0x3a2b
COMSVCS!DispManGetContext + 0xbc07
ole32!CoInitializeSecurity + 0x3a2b
ole32!CoInstall + 0x6ed
ole32!CoQueryAuthenticationServices + 0x21aa
ole32!CoQueryAuthenticationServices + 0x2c56
ole32!CoGetContextToken + 0xd48d
ole32!CreateStreamOnHGlobal + 0x1b7c
ole32!CoCreateObjectInContext + 0xd9f
ole32!CoInstall + 0x903
ole32!CoGetContextToken + 0x12f5b
RPCRT4!NdrServerInitialize + 0x1fc
RPCRT4!NdrStubCall2 + 0x217
RPCRT4!CStdStubBuffer_Invoke + 0x82
ole32!StgGetIFillLockBytesOnFile + 0x13b27
ole32!StgGetIFillLockBytesOnFile + 0x13ad4
ole32!DcomChannelSetHResult + 0xaab
ole32!DcomChannelSetHResult + 0x495
ole32!CoFreeUnusedLibrariesEx + 0xb06
ole32!StgGetIFillLockBytesOnFile + 0x139e1
ole32!StgGetIFillLockBytesOnFile + 0x13872
ole32!StgGetIFillLockBytesOnFile + 0x12d59
ole32!CoFreeUnusedLibrariesEx + 0x9f5
ole32!CoFreeUnusedLibrariesEx + 0x9c0
USER32!LoadCursorW + 0x4cf5
USER32!LoadCursorW + 0x4e86
USER32!TranslateMessageEx + 0x10d
USER32!DispatchMessageW + 0xf
COMSVCS!DllUnregisterServer + 0x270
COMSVCS!DllUnregisterServer + 0x180
COMSVCS!DllUnregisterServer + 0xc6c
COMSVCS!DllUnregisterServer + 0xf4d
msvcrt!_endthreadex + 0xa3
kernel32!GetModuleHandleA + 0xdf
A:
ole32!CoInstall + 0x6ed
The +0x6ed offset is an important 'quality' indicator. What it tells you is that the return address is 1773 bytes from the known address of CoInstall. That's rather a lot. The stack trace builder just didn't have any other known address that was closer so it could only offer CoInstall as a guess. Once the offset goes beyond 0x100, the odds that the code is actually part of the indicated known function start to dwindle rapidly.
There are a lot of entries in the trace that have huge offsets. Making the entire trace rather low quality. Editing the stack trace and leaving only good quality lines in place:
vfp9t!VFPDllGetClassObject + 0xb6
ctcvccomasyncproxy!DllGetClassObject + 0x3e
...
RPCRT4!CStdStubBuffer_Invoke + 0x82
...
USER32!DispatchMessageW + 0xf
Which is a pretty standard stack trace for a cross-apartment request to get a COM object class factory. Why it failed is not guessable, you don't have debug symbols for foxpro and didn't document the HRESULT.
A: *
*That stack dump does not appear to be plausible. It is almost certainly not useful.
*I suggest writing an unhandled exception handler and trying to get it to crash again. Your handler can try to do a better stack dump or even a proper crash dump.
See
*
*http://msdn.microsoft.com/en-us/library/windows/desktop/ms680634.aspx
*http://www.microsoft.com/msj/0197/Exception/Exception.aspx
*http://msdn.microsoft.com/en-us/library/windows/desktop/ms680360.aspx
The handler would be in your code that calls the dll code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Navigating to a different page based on a timer in MVC2 I was hoping that I could be able to send a user to a different page if they have not executed any functions in a certain time frame. Is there some kind of timer that I can execute to accopmlish this?
Thanks,
Derek
A: You could use the jQuery idle plugin.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to show an alert before download a file This is my question i have an aspx page that has to show a popup message and when the user clicks ok begin download
any help would be appreciated
A: Script
function download() {
if (confirm ('Download file?')) {
location.href = 'yourfile.pdf';
}
return false;
}
HTML
<a href='#' onclick='return download()'>Download</a>
A: You can use a click handler on your link or button:
<a href="url/to/file.txt" onclick="return confirm('are you sure you want to download this file?');">file text</a>
working example: http://jsfiddle.net/QRgvV/
A: In JavaScript you will have to create a modal which instructs the user to click on a link within the modal to continue the download. You can't use JS to force a download to begin, due to security concerns. So the best you can do is give them a message and a second link which will actually trigger the download (when the user manually clicks on it).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Problem with CSS property display: inline-block In quirks mode (IE) the following code will function correctly. In standards compliant mode, this code will only show the text of the nested span, but it will not be given 100% for width. Is there a way to force the nested inline-block span to set its width to the div size, and if so is there a way to do it without changing the html code? Thanks for any help.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html>
<head>
<style>
span {display:inline-block;}
</style>
<head>
<body>
<div>
<span>
<span style='width:100%; text-align:center;'>
Blah
</span>
</span>
</div>
</body>
A: The parent (span) don't have any width. Just set it and you resolve your problem
div span { width:100% }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP backend for Android / Iphone - Special character issue We are using PHP as backend for mobile application (in both Android and IPhone). From mobile we will hit the backend to get the record listings in xml format (same for both android and iphone) from php.
We have special characters in the database in some fields (swedish characters). From mobile we will pass the search text which user keys in and display the records accordingly. So first we tested from iphone, there was some characters not displayed properly and then we changed charset to UTF-8 in mysql_charset. After that it was working fine in IPhone. But there was problem in retreiving records from Android. When we input text which has special characters, then the expected result was not displayed. But when we search from the browser , results are displayed normally.
We have used the xmlencoding as utf-8 also added 'header('Content-Type: text/xml; charset=utf8'); '
If there is any other solution compatible for both Iphone and Android, please let me know.
Characters which we will be using are ä, å, é, ö.
Thanks in Advance,
Regards
Srini
A: on this website you find all HEX codes of every special character. http://www.ascii.cl/htmlcodes.htm
In Android (Java) you display special characters like this view.setText("hello\u0021"); for hello!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to display text in a textbox using jQuery and another textbox? I have a form, where there are three fields: Title, Slug, and URL.
I have a plugin that converts the text entered in the Title field as a slug. (For example, if I type "Joe Bloggs Goes On Holiday" would then display as "joe-bloggs-goes-on-holiday" in the slug field).
What I need to do now, is get the information in the slug field and add it to my URL field. In the URL field, there already is text (usually "/mainpage/" but this will depend on what type of page is being created). So in the URL field I would then have "/mainpage/joe-bloggs-goes-on-holiday".
How can I achieve this?
Cheers
A: You can use the .val method to get and set the value of fields:
var urlField = $("#urlField");
urlField.val(urlField.val() + $("#slugField").val());
A: You would use either jQuery append, or concatinate the value:
Former
$('textarea').append($('slug').val());
Latter
$('textfield').val($('textfield').val + $('slug').val());
A: Use jQuery's val() method.
HTML
Slug: <input id="slug" value="joe-bloggs-goes-on-holiday" /><br />
URL: <input id="url" value="/mainpage/" /><br />
Result: <input id="result" />
JavaScript
var $urlObj = $("#url");
$("#result").val($urlObj.val() + $("#slug").val());
Here's a working jsFiddle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Question about pthreads & pointers Here is an example of thread creation code that is often seen. pthread_create uses a lot of pointers/addresses and I was wondering why this is so.
pthread_t threads[NUM_THREADS];
long t;
for(t=0; t<NUM_THREADS; t++){
rc = pthread_create(&threads[t], NULL, &someMethod, (void *)t);
}
Is there a major advantage or difference for using the '&' to refer to the variable array 'threads' as well as 'someMethod' (as opposed to just 'threads' and just 'someMethod')? And also, why is 't' usually passed as a void pointer instead of just 't'?
A: int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine)(void*), void *arg);
You need to pass a pointer to a pthread_t variable to pthread_create. &threads[t] and threads+t achieve this. threads[t] does not. pthread_create requires a pointer so it can return a value through it.
someMethod is a suitable expression for the third argument, since it's the address of the function. I think &someMethod is redundantly equivalent, but I'm not sure.
You are casting t to void * in order to jam a long into a void *. I don't think a long is guaranteed to fit in a void *. It's definitely a suboptimal solution even if the guarantee exists. You should be passing a pointer to t (&t, no cast required) for clarity and to ensure compatibility with the expected void *. Don't forget to adjust someMethod accordingly.
pthread_t threads[NUM_THREADS];
long t;
for (t=0; t<NUM_THREADS; t++) {
rc = pthread_create(&threads[t], NULL, someMethod, &t);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to display Current Location ADDRESS in textbox? I've created this Textbox, and a Button beside it. I've also linked this Button to a class which display a map with the longitude, latitude, a push pin etc. But i have a question, how do i make this textbox such that it auto generate the current location address ?
A: hiii..
It's so simple if you already tracked the latitude and longitude of as in case of map view.
TextView myAddress = (TextView)findViewById(R.id.myaddress);
myLatitude.setText("Latitude: " + String.valueOf(LATITUDE));
myLongitude.setText("Longitude: " + String.valueOf(LONGITUDE));
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
myAddress.setText(strReturnedAddress.toString());
}
else{
myAddress.setText("No Address returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
myAddress.setText("Canont get Address!");
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Symfony2 - default values in Form Collection prototype I'm trying to get the collection prototype to have a set of default values instead of blank values. Ideally I'd like to be able to define those default somewhere either in the model class or the form definition class, but I cannot find a way to do this anywhere.
As an example:
I've created an AbstractType for my form which contains a nested collection of Person rows (relevant code shown below):
public function buildForm(FormBuilder $builder, array $options)
{
...
$builder->add('people', 'collection', array(
'type' => new PersonType(),
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
));
...
}
The PersonType class contains the following code:
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('name', 'text');
$builder->add('date_of_birth', 'date');
$builder->add('age', 'number');
// This would be great if I could do this but I can't:
//$builder->add('date_of_birth', 'date', array('empty_value' => new \DateTime(...))); // some default value defined here
}
The best I've been able to come up with so far is shown below in the view file (the code shown is used to render the collection prototype):
...
<tr>
<td> {{ form_widget(person.name) }} </td>
{# THIS DOES NOT WORK (I just get the default selected date) #}
<td> {{ form_widget(person.date_of_birth, {'value': person.date_of_birth.get('value')|default({'year':2010, 'month':10, 'day':15})} }} </td>
{# THIS WORKS (the field contains '0' instead of being empty) #}
<td> {{ form_widget(person.age, {'value': person.age.get('value')|default(0)} }} </td>
</tr>
...
*
*It only seems to work with simple types like text and number. It doesn't work with the date type.
*This anyway doesn't feel like the right approach. I should be able to define a default/empty value either in the underlying model (e.g. protected $age = 10; inside the model class), or else in the form definition (AbstractType) class (e.g. array('empty_value' => new DateTime()), but neither are currently possible.
So in summary, my question is:
How can I define default values for a model class that will be set automatically on the client when adding new items to a form 'collection' (instead of just getting blanks).
Does anyone know of a good way to do this?
A: In the constructor of the entity that the form is being used for, you simply set the date with a \DateTime object, like so:
class MyEntity {
private $myDate;
public function __construct() {
$this->myDate = new \DateTime('today');
}
}
You can also use \DateTime('now') or \DateTime('tomorrow'), as described in the discussion below
http://groups.google.com/group/symfony2/browse_thread/thread/18a5b20aca485dc4/e9947d0f06d6519d
Edit: Actually, this information is in the symfony2 documentation:
http://symfony.com/doc/2.0/book/forms.html#building-the-form
A: may be
$builder->setData(array('date_of_birth', new \DateTime(...)));
A: With Symfony >2.0 this is not possible.
Symfony 2.0 retrieved the values for the prototype from the underlying object so setting them in the constructor also changed the values in the prototype. However, this behavior was changed with Symfony 2.1 which removed this functionality, depraving us of the possibility of setting default values for the prototype:
I think setting a default value for the prototype is then indeed not possible right now. --webmozart, Symfony collaborator (https://github.com/symfony/symfony/issues/5087)
There is an open bug under active development which should add support for a data_prototype option. Using this option, it will be possible to supply data to prefill the prototype. However, this will probably be released no sooner than with Symfony 2.7.
A: As @Alexey Kosov mentioned in his comment and @Chris mentioned was going to be possible, you can now set the option 'prototype_data' => new YourEntity()
$builder
->add('your_field', CollectionType::class, [
'entry_type' => YourEntityType::class,
// ...
'prototype_data' => new YourEntity(),
])
;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Take text from Text area I have this html code -
<form method="post" style="width:100%; margin-bottom:40px;" >
<textarea id="wall_post" style="width:100%;; margin-left:-4px; margin-right:auto; resize:none;" rows="4"></textarea>
<input id="wallPost" type="submit" value="Post" method="post" style="float:right; font-size:65%;" />
<div id="vectors" style="display:inline; float:left; margin-right:20px;">
<input type="checkbox" id="sms" value = "SMS" method = "post"/><label for="sms" style="font-size:65%;">SMS</label>
<input type="checkbox" id="email" value = "Email" method = "post"/><label for="email" style="font-size:65%;">Email</label>
</div>
</form>
As you can see there are a few buttons. I'd like to have it so that when say the checkbox with value SMS is clicked, the stuff in the textarea is passed to a django view. I know I can pass stuff into django using a jquery ajax post with the relevant url conf, but how do I do so on the request of the user? (in pseudocode - if user clicks post, give django function text area text)
thanks!
A: Why do you have to change whether or not your textarea is being submitted to django?
It's not much data. Why not always submit it and check in your view if the SMS checkbox is checked?
If checked: do something with textarea data. If not: don't.
Note: you're missing the name attribute on each of your inputs.
def my_view(request):
if request.method == 'POST':
if request.POST.get('sms'):
# do something with text area data since SMS was checked
print request.POST.get('my_textarea')
# process form as usual.
If you want to change whether or not django reads your data, you could potentially dynamically add or remove the textarea's name attribute with javascript, but this is riskier and more work than the above solution.
update - the html to work with above code.
<form method="post">
{% csrf_token %}
<textarea name="my_textarea"></textarea>
<input type="checkbox" name="sms" />
</form>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Justify html to right margin I'm having trouble getting html text justified to the right margin (it's a right-to-left language). When I use the text-align:right attribute, it justifies the text only to the point defined by the width attribute (e.g., at 400pt from the left margin). How can I justify it to the right margin, without having the text extend all the way to the left margin?
Here's an example:
</head><body><div style="width:400pt;line-height:125%;text-align:right" lang="he" dir="rtl"><bdo dir="rtl">ילח שדגחי שדחי שךלח דק לחי שדלחילחי לחדגי חליל ש דגחי שדגחכילח שדגחי שדחי שךלח דקילח שדגחי שדחי שךלח דק לחי שדלחילחי לחדגי חליל ש דגחי שדגחכילח שדגחי שדחי שךלח דקילח שדגחי שדחי שךלח דק לחי שדלחילחי לחדגי חליל ש דגחי שדגחכילח שדגחי שדחי שךלח דקילח שדגחי שדחי שךלח דק לחי שדלחילחי לחדגי חליל ש דגחי שדגחכילח שדגחי שדחי שךלח דק</bdo></div></body></head>
Thanks.
A: If I understand what you are wanting correctly, then you shoud replace
text-align: right;
with
float: right;
You can see what this looks like here.
By the way, why do you have a final kaf ך in the middle of the word שךלח?
| {
"language": "he",
"url": "https://stackoverflow.com/questions/7503669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: tar exclude file pattern I am trying to create a tar with follwing command:
tar -cvf myFile.tar -X exclude-files.txt myContentDirectory
and my exclude-file has follwing patterns to exclude:
**/*.bak
**/*.db
**/*.html
But i dont see these file types being excluded out in my tar.
What am I doing wrong here?
I found that when i have just one pattern in my exclude-files.txt, lets say only
**/*.bak
it does work. But not with multiple file patterns (EACH ON NEW LINE)
A: I think this:
*.bak
*.db
*.html
is the correct format for the exclude file if you want to exclude a particular directory you could do:
some-dir/*.db
Also your command should look like this:
tar -cvf myFile.tar -X exclude-files.txt myContentDirectory
A: Sorry if this answer is a little late.
tar -cO --exclude=*.bak myContentDirectory | tar -O --delete '*.db' | tar -O --delete '*.html' > myFile.tar
See, what you're doing here is creating the tar, but sending it to stdout instead of to a file then piping that into tar to delete the stuff you don't want, one or more times and finally writing the output to a file.
You can even test it first like this:
tar -cO --exclude=*.bak myContentDirectory | tar -O --delete '*.db' | tar -O --delete '*.html' | tar -tv
Which will spit out a list of all the files remaining in the archive.
A: Most likely the order of the command is incorrect.
tar -cvf myFile.tar -X exclude-files.txt myContentDirectory
should be something like
tar cv -X exclude-files.txt -f myFile.tar myContentDirectory
PS. I haven't looked into the filters itself. Most likely order of the parameters is the issue.
If issues is in the filters/patterns - it's easier to test one by one with --exclude option.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: How do I add a new solution to my team project? We have a team project in TFS 2010. This team project is used as a container for a few smaller, related projects in order to share bugs, work items, etc. My question, how do I add a new VS solution to this team project?
I created the new solution in my local working folder. The team project is already created on the server. When I go into the Source Control Explorer and try to add the new solution to the project, I can’t add the new solution because I don’t have a destination folder mapped. I can’t map the destination folder because I can’t figure out how to add a new folder to the server project for the new solution. Caught in what appears to be some wicked circular logic… help!?!
A: To add a new solution from you local files to TFS you could:
In the solution explorer right click on the solution and select 'Add Solution to Source Control'
Then you can right click and select check in.
Then the entire solution will be added to your team project in TFS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Masking Currency for Regular Expression in C# just a little help on how to mask number to make proper currency value in Regular Expression with comma..
i made it this far..
₱\d*\.\d{2}
and it will mask
from 3342.34 to ₱3342.34
how to mask it with comma for every 3 digits? :)
thanks in advance..
A: Seeing as you have to use regex, here is your answer:
₱(?>\d{3},)*\d{1,3}(>?\.\d{1,2})?$
This will accept:
*
*₱10
*₱100
*₱100,1
*₱1.1
*₱100,512,423.15
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to sort MYSQL query to display alphabetically, with numbers last, and not including the word "The" in sort Basically I have a PHP MYSQL query which returns 16 items. 15 of them start with letters A-Z, and one starts with a number (the name of a product is "3d Star Gazer"). In a regular query, sorting alphabetically displays this one item that starts numerically first. I want the list to be sorted alphabetically, with the 3d Star Gazer displayed last.
Is this possible?
SELECT t1.id, t2.name, t2.manufacturer
FROM db.t1
LEFT JOIN db.t2 ON t1.id = t2.id
WHERE year = '2011'
ORDER BY t2.name ASC
I saw this link: Sort MySQL results alphabetically, but with numbers last but the solution wasn't working for me...
As a secondary question, is it possible to not include the word "The" in the sort? For example, a game is called "The Guessing Game," I want it to appear sorted as "G", not as "T".
A: Using the IF() operator and adding two columns to control the sort order:
SELECT t1.id, t2.name, t2.manufacturer,
IF(LEFT(t2.name, 1) BETWEEN '0' AND '9', 2, 1) as sortOrder1,
IF(t2.name LIKE 'The _%', SUBSTRING(t2.name FROM 5), t2.name) as trimmedName
FROM db.t1
LEFT JOIN db.t2 ON t1.id = t2.id
WHERE year = '2011'
ORDER BY sortOrder1, trimmedName;
The underscore in the pattern for the LIKE operator matches any single character, and is used to make sure that the returned substring will not be null.
If you don't want the extra columns in your final output, wrap the above select statement inside another:
SELECT id, name, manufacturer FROM ([select statement above]) a;
A: See the results in this answer
Sort MySQL results alphabetically, but with numbers last
with particular attention to the order by case
As for the extraction of "the", I'm sure you could do something in the lines of
trim( replace( name, 'The','') ) as name_order
and then order based on that in conjunction with the order by case mentioned in the linked answer.
A: you can make an union first you select the values that start with letters and in the second query you select the ones that start with numbers
(select .... order by <<letter>>) union (select ... order by <<number>>)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: @RequestParam variables return a set of comma separated values, when a method gets called several times I just noticed that a @RequestParam variable that I use to check POST params, such as usernames, or ids, behaves rather strangely when the controller method gets called consecutive times. Rather than returning the current parameter value (for example, "Jason", "Michael", "John"), it returns a concatenated string of all parameter values that the method has been called with before that. It results in the variable having the value of: "Jason,Michael,John", rather than just "John" which was the last one.
I noticed that this strange behavior is per session. When I reduced the session duration to 1 minute only, i noticed that after the session is gone, so are the multiple values.
This thing never happens if I call request.getParameter("username"). Of course, I would like to stick to Spring MVC conventions if possible.
Is this a bug, or something intentional? How can I avoid it?
A: This is a bug in your JSP page. You likely have a hidden and an input with the same name. This results in a comma separated list of values.
A: Try without spring annotations:
Add to your method an attribute named HttpServletRequest
String s = request.getParameter("parameterName")
A: Your attribute might be saved internally by spring in the http session and re-used from there. Do you by any chance, on you spring controller class, have a configuration that would make that parameter session scoped (Either @SessionAttributes("username") on the class, or requireSession=true in your xml declaration of the controller bean)?
Or do you'add it to the model when you rediplay your page from the controller?
A: Faced the same issue while implementing an ajax login and found out that it was caused by the redirect that is triggered after the failing attempts to login. Somehow was accumulating the j_usernamen and j_password parameters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Sorting a python dictionary by name? I have a python dictionary that I want to sort according to name:
location_map_india = {
101: {'name': 'Andaman & Nicobar Islands', 'lat': 11.96, 'long': 92.69, 'radius': 294200},
108: {'name': 'Andhra Pradesh', 'lat': 17.04, 'long': 80.09, 'radius': 294200},
...
}
It doesn't come out the way I expect it. I tried:
location_map_india = sorted(location_map_india.iteritems(), key=lambda x: x.name)
The above didn't work. What should I do?
Update
The following was allowed and behaved as expected. Thanks for all the help.
Code:
location_map_india = sorted(location_map_india.iteritems(), key=lambda x: x[1]["name"])
Template:
{% for key,value in location_map_india %}<option value="{{key}}" >{{value.name}}</option>{% endfor %}
A: You are close. Try:
location_map_india = sorted(location_map_india.iteritems(), key=lambda x: x[1]["name"])
but the result would be a list not a dict. dict is orderless.
A: If you're using python 2.7 or superior, take a look at OrderedDict. Using it may solve your problem.
>>> OrderedDict(sorted(d.items(), key=lambda x: x[1]['name']))
A: you should try
location_map_india = sorted(location_map_india.items(), key=lambda x: x[1]['name'])
A: If you are using a dictionary that must have order in any way, you are not using the correct data structure.
Try list or tuples instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: which c# collection to use instead of List>? I want to store data such as
{
{"apple",15 }
{"pear",12.5 }
{"", 10 }
{"", 0.45 }
}
Data will be plotted on a bar chart (string will be the legend and double will be the value)
Insert order is important.
Perfs don't matter.
Strings could be duplicated or empty. (values could be duplicated too)
I need to get min and max values (easily if possible) to set the scale.
I use
List<KeyValuePair<string, double>> data = new List<KeyValuePair<string, double>>();
data.Add(new KeyValuePair<string,double>("",i));
Quite boring and unreadable.
Is there a cleaner way to do it ?
StringDoubleCollection data = new StringDoubleCollection();
data.add("apple",15);
data.add("",10);
double max = data.values.Max();
double min = data.values.Min();
if not how to get the max value of List<KeyValuePair<string, double>> without too much hassle
NameValueCollection looks nice but its a <string,string> I need a <string,double>
A: You could create a class like the following:
class X
{
public string Name { get; set; }
public double Value { get; set; }
// name is an optional parameter (this means it can be used only in C# 4)
public X(double value, string name = "")
{
this.Name = name;
this.Value = value;
}
// whatever
}
And then get maximum and minimum values using LINQ with a selector:
var data = new List<X>();
data.Add(new X(35.0, "Apple"))
data.Add(new X(50.0));
double max = data.Max(a => a.Value);
double min = data.Min(a => a.Value);
EDIT: if the code above still seems unreadable to you try to improve it using an operator for cases in which you want to have just the value.
// Inside X class...
public static implicit operator X(double d)
{
return new X(d);
}
// Somewhere else...
data.Add(50.0);
A: Have you looked at LookUp?
The only problem is that it's immutable, so you need to be able to create your collection in one go.
As Anthony Pegram notes, it's a bit of a pain to create one. It depends on where your data is coming from. Have a look at the ToLookup method.
A: If it's worth it for usability (i.e. you're using awkward collections of List<KeyValuePair<string, double>> everywhere, it might just be worth it to implement StringDoubleCollection. It wouldn't be that difficult to wrap the underlying collection with the friendlier syntax you've described in your example.
And, as other comments / answers are suggesting, the Framework doesn't seem to provide a simpler solution that matches all of your requirements...
As for "max value", I assume you mean the Key-Value Pair with the greatest value. It can be retrieved like so:
var max = list.Select(kvp => kvp.Value).Max();
A: Just define your own model class to hold the data instead of depending on a KeyValuePair and everything becomes cleaner:
using System;
using System.Collections.Generic;
public class Fruit
{
public string Name {get; set;}
public double Price {get; set;}
}
public class Program
{
public static void Main()
{
List<Fruit> _myFruit = new List<Fruit>();
_myFruit.Add(new Fruit{Name="apple", Price=15 });
_myFruit.Add(new Fruit{Name="pear", Price=12.5 });
_myFruit.Add(new Fruit{Name="", Price=10 });
_myFruit.Add(new Fruit{Name="", Price=0.45 });
// etc...
}
}
A: To determine which data structure you really want, lets look at your usage patterns.
*
*Insert order matters.
*You don't access your items by key.
*You want min and max.
A heap offers min or max, but doesn't preserve order. A hash based dictionary also doesn't preserve order. A List is actually a good choice for your data structure. It is available and offers excellent support.
You can prettify your code by defining classes for both the data structure and your bar data. And you can add min/max functionality to the collection. Note: I didn't use the Linq Min/Max functions, because they return the minimum value, not the minimum element.
public class BarGraphData {
public string Legend { get; set; }
public double Value { get; set; }
}
public class BarGraphDataCollection : List<BarGraphData> {
// add necessary constructors, if any
public BarGraphData Min() {
BarGraphData min = null;
// finds the minmum item
// prefers the item with the lowest index
foreach (BarGraphData item in this) {
if ( min == null )
min = item;
else if ( item.Value < min.Value )
min = item;
}
if ( min == null )
throw new InvalidOperationException("The list is empty.");
return min;
}
public BarGraphData Max() {
// similar implementation as Min
}
}
A: What about implementing the StringDoubleCollection to work like you want...
public class StringDoubleCollection
{
private List<KeyValuePair<string, double>> myValues;
public List<double> values
{
get { return myValues.Select(keyValuePair => keyValuePair.Value).ToList(); }
}
public void add(string key, double value)
{
myValues.Add(new KeyValuePair<string,double>(key,value));
}
}
A: You can implementing Dictionary<key, value>
Dictionary<string, string> openWith = new Dictionary<string, string>();
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
https://learn.microsoft.com/pt-br/dotnet/api/system.collections.generic.dictionary-2?view=net-5.0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Two columns with separator border I would like to have two columns with separator border.
The task is quite simple when the columns have the same height.
But, if the heights of columns are different, and you don't know a priori which is the higher column, (and I don't want to use fixed value) how can I solve the problem?
The background color is the same.
A pure css solution is the best. If not possible, also a JavaScript code is acceptable.
Click here for the current example.
A: You can set the display of the container to table and the left and right columns to table-cell
#container {
display: table;
width: 100%;
}
#content-left {
border-right: 4px dotted #000;
width: 50%;
display: table-cell;
margin-right: -4px;
}
#content-right {
width: 50%;
display: table-cell;
}
Then you just need to wrap the left and right columns in the container and you have it.
<div id="wrapper">
<div id="container">
<div id="content-left">left</div>
<div id="content-right">right<br />right<br />right</div>
</div>
<div id="footer">
footer content
</div>
</div>
Look Here
A: One css method is to use a repeating background image for the dotted line - this repeat goes on a div surrounding the 2 columns, like so:
http://jsfiddle.net/P5Z9s/ (obviously you'd get a better image, I just pulled this from google)
Or using jQuery, you can do something like:
http://jsfiddle.net/ntWRY/ (you basically add the same class to the columns you want to equalize, and then call the function on that class)
A: I suggest you read about faux columns.
If you can't afford the time (not that much, but...), then using JS you could simply check which is higher and set the other's min-height to that.
I think this would work as you want it. But I suggest you learn about the faux columns instead.
A: Perhaps something like this is what you are looking for:
http://jsfiddle.net/euYTQ/40/
HTML:
<div class="container">
<div class="left">section left</div>
<div class="right">section right<br>other row</div>
<div class="footer">section footer</div>
</div>
CSS:
div.container {
position:absolute;
background:#eee;
margin: 0 auto;
width: 750px;
height:100%;
}
.left{
position:absolute;
left:0px;
top:0px;
bottom:50px;
width:48%;
border-right-style:dotted;
}
.right {
position:absolute;
right:0px;
top:0px;
bottom:50px;
width:48%;
border-right-style:dotted;
}
.footer {
position:absolute;
background: none repeat scroll 0 0;
bottom: 0px;
height:50px;
left:0px;
right:0px;
border-top-style:dotted;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to open a browser in full screen in ASP.NET application programmatically? I am making a web application in ASP.NET 4.0. For some reason I need to open a web site always in full screen. It is a tedious task to open a web site in browser and then toggle to fullscreen.
Is there any way to open the browser (preferably IE9 or Google Chrome) in full screen programmatically?
Can I put some code in the Page_Load() method of my default page that toggles the browser to full screen?
A: The only way to manipulate the window size for a web app is through javascript, and so that will need to be a requirement for your page/site. Even here, you have three challenges:
*
*Some browsers provide an option to disable this particular feature of javascript
*I can't recall a way off the top of my head to see from javascript how big the screen really is, and how much of that space will be taken up by the browser chrome. I suspect it's not possible to know.
*There is no way to hide all of the browser chrome.
Parts of those challenges are there for security reasons, to prevent malicious web sites from hijacking user's screens, and therefore they will be no workaround.
A: I'd suggest embeding a javascript function into your ASP.NET code. use window.open() and then pass the proper parameters. I used something comparable of embedding javascript into .net with Response.Write. This example method below does window.open. Just push the proper parameters and URL, etc.
The parameters btw are : 'http://URL', 'Title' , 'type=fullWindow, fullscreen, scrollbars=yes'
private void MessageBox(string URL, string parameters)
{
if (!string.IsNullOrEmpty(URL))
{
Response.Write
("<script type=\"text/javascript\" language=\"javascript\">");
Response.Write("window.open('" + URL + parameters + "');");
Response.Write("</script>");
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SolidColorBrush problem in silverlight I have problem with SolidColorBrush setting. I create polygon layer in bing map control in silverlight. When I set color as:
Dim kocka As New Microsoft.Maps.MapControl.MapPolygon()
kocka.Fill = New SolidColorBrush(Colors.Blue)
everything is OK and polygon is displayed. But, when I use this approach (dynamic setting):
Dim kocka As New Microsoft.Maps.MapControl.MapPolygon()
kocka.Fill = New SolidColorBrush(Color.FromArgb(0, 233, 14, 55))
'OR: Color.FromArgb(CByte(0), CByte(233), CByte(14), CByte(55)))
the polygon is not displayed. What is wrong? I tried everything and nothing works.
Thanks
A: The first parameter in Color.FromArgb is the Alpha channel (aka opacity). A value of 0 will make it fully transparent, so you should set it to something greater than 0 if you want to actually see the color. For instance:
kocka.Fill = New SolidColorBrush(Color.FromArgb(255, 233, 14, 55))
Check out this Wikipedia article for more information on ARGB colors.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Strange requests which ends with -moz-zoom-in Production server gets a lot (hundreds) of requests which ends with -moz-zoom-in.
It just adds -moz-zoom-in to current url, e.g. http://www.wikipaintings.org/en/paintings-by-genre/allegorical-painting/-moz-zoom-in
I made a search through project and did not find any mentions of this keyword. As I understand from documentation this is related to firefox cursor type.
I wasn't able to see such requests with firebug.
Any ideas what in CSS or HTML could cause such effect?
A: You should have a look at the user agent string of the requests. I suspect that it is some browser that doesn't support -moz-zoom-in (meaning: not Firefox, so it is not surprising that you cannot see that request in Firebug). You probably have cursor: -moz-zoom-in somewhere in your CSS styles, probably through some third-party library like jQuery UI, and that browser "fixes" it for you and turns it into cursor: url("-moz-zoom-in"). So it actually tries to load the cursor from that URL instead of ignoring the invalid cursor.
A: It is a CSS cursor which indicates that an element/object in a webpage is being resized. It is part of Mozilla extensions for CSS (they begin with -moz). For more information read this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to write Scrollable for Table in j2me by canvas? Now i try to draw a table by Canvas, but i have a problem, my table doesnt has scrollable.
How can i write some code to help my table can scrollable?
My Code here
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
/**
*
* @author Kency
*/
public class TableCanvas extends Canvas{
private int w,h;
private int pad;
private int cols = 3;
private int rows = 10;
public TableCanvas() {
w = getWidth();
h = getHeight();
}
protected void paint(Graphics g) {
g.setColor(148, 178, 255);
g.fillRect(0, 0, w, h);
for(int i =0 ; i <= cols ; i++){
g.setColor(0x00D0D0D0);
for(int j = 0 ; j <= rows ; j++){
g.drawLine(0, j * h/rows, cols * w, j* h/rows);
g.drawLine(i * w/cols, 0, i * w/cols, w * rows);
}
}
}
}
A: For code like in your excerpt, most straightforward way would probably be with Graphics#translate API.
One would also have to handle key pressed / pointer events to allow user to scroll. Eg when key press corresponds to game action right/left/up/down, you scroll respectively. When pointer is dragged, you find out the direction and, again, scroll respectively
Painting scrollbar(s) would also require "handmade" code.
Another option would be using 3rd party library like LWUIT or J2ME Polish
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to get scrobbling from information from last.fm API I am getting information about the track I am listening to from last.fm.. I cannot however get the information about what I am scrobbling from, like you see on you last.fm page: "scrobbling now from spotify"
Does anyone know if this is possible without scraping the user page?
I don't see anything in the API docs - could easily be missing something.
The call I am using to get the now playing track is user.getRecentTracks which you use a attribute on the first song returned (nowplaying="true") to tell if its being played now and there is nothing about what I am listening on there.
A: The answer is: no, Last.fm API doesn't support this feature.
The only way you can get this information is to scrap it from <div class="scrobblesource">.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Validate if form data is a present select input option I have a select input:
<label for="gender">Gender:</label>
<select id="gender" name="gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
How to validate whether submitted data belongs to select input?
I have tried:
<?php
if ($_POST['gender'] !== 'Male' || $_POST['gender'] !== 'Female') {
// perform redirect
}
A: A cleaner way to do it would be
$options = array( 'Male', 'Female' );
if( !in_array( $_POST['gender'], $options ) ) // if Male or Female are not in $_POST
// redirect
A: if ($_POST['gender'] != 'Male' && $_POST['gender'] != 'Female') {
// perform redirect
}
The above will redirect if neither option is checked. But personally, I prefer to do a '--Choose--' option, and simply check against it.
<label for="gender">Gender:</label><select id="gender" name="gender">
<option value="0" selected=selected>--Choose--</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
if ($_POST['gender'] != '0') {
// perform redirect
}
Also, your original will work with:
if ($_POST['gender'] == 'Male' || $_POST['gender'] == 'Female') {
// perform redirect
}
A: You can also use this method.
<?php
if ( isset($_POST['submit']) ) {
$_POST = array_map( 'stripslashes', $_POST );
extract( $_POST );
if ( !isset($Male) && !isset($Female) ) {
// redirect
}
}
?>
A: You should avoid passing literal values altogether when these are in a known range/domain.
The form can be generated using an indexed value, e.g.
<?php
$options = [];
$options['gender'] = [1 => 'Male', 2 => 'Female'];
?>
<label for="gender">Gender:</label>
<select id="gender" name="gender">
<?php foreach ($options['gender'] as $i => $name):?>
<option value="<?=$i?>"><?=$name?></option>
<?php endforeach;?>
</select>
Then your input validation logic would simply check for value presence in the $options array, e.g.
<?php
if (isset($options['gender'][$_POST['gender']])) {
//
}
Furthermore, consider using existing form generation tools (e.g. https://github.com/gajus/dora) and input validation libraries (https://github.com/gajus/vlad). I am the author of both libraries, and each library will refer you to the existing alternatives. The purpose of using an existing library for generating form and handling input validation is to avoid re-inventing the wheel and protecting yourself from silly security bugs that are often overlooked when handling forms, e.g. XSS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: When updating an index in sphinx.conf is restarting searchd in sphinx always required? If I update a resource in my sphinx.conf file I can reindex with --rotate and everything works fine. If I update an index in my sphinx.conf or add a new index --rotate has no effect and I have to restart searchd.
Am I doing this correctly, I feel like --rotate should correctly index the new or modified index configurations.
A: It depends on your sphinx version. In the latest versions just about anything (except maybe the searchd config section) will work with changing the config file.
Just changing the settings on an individual index, a --rotate indexing of the particular index is enough. If you change the settings of particular index, and dont actully reindex it, searchd probably wont pickup the changes. (because it reads stuff from the index header, not direct from conf file)
I just tested adding a index, and removing a index. both happened with a seemless rotate.
Sphinx 2.0.1-beta (r2792)
Prior to 0.9.9-rc1 - a restart would be required for most config file changes.
A: You have to restart searchd when modifying the sphinx.conf file.
Rotate will not effect new index additions to your sphinx.conf file - it reindexes an analogous index of the original. Kind of like having a file and file-copy(1) then swapping them over.
If you modify the .conf file its sort of like declaring a brand new index.
Thus --rotate does not work if the exact index does not previously exist.
See; http://sphinxsearch.com/docs/2.0.1/ref-indexer.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: PListBuddy Fails When Called From ant I have a build script that pulls the old version out of the plist for an iOs product, outputs it, then updates the plist. The two commands are
/usr/libexec/PlistBuddy -c Print CFBundleVersion ${LocationOfPList}
/usr/libexec/PlistBuddy -c Set :CFBundleVersion ${Version} ${LocationOfPList}
Run from the command line (with the version and the proper PList file location), everything is fine. Run from ant as
<exec executable="/usr/libexec/PlistBuddy"
outputproperty="CurrentVersion"
errorproperty="PListError">
<arg value="-c"/>
<arg value ="Print :CFBundleVersion"/>
<arg value="${LocationOfPList}"/>
</exec>
<echo message="Fetched the last version in the plist: ${CurrentVersion}" />
<!-- Set the plist to the current build number -->
<exec executable="/usr/libexec/PlistBuddy"
outputproperty="PListOutput"
errorproperty="PListError"
>
<arg value="-c"/>
<arg value ="Set :CFBundleVersion ${Version}" />
<arg value=" ${LocationOfPList}"/>
</exec>
<echo message="Output: ${PListOutput}"/>
<echo message="Errors: ${PListError}"/>
<echo message="Old version number: ${CurrentVersion} New Version Number: ${Version}" />
Results in some strange behavior. The first command works, the second fails. This ant script is running as the same user as the command line example. The output I see is:
[echo] Fetched the last version in the plist: 3.0.0
[exec] Result: 1
[echo] Output: File Doesn't Exist, Will Create: /Users/macbuild/iPhone/branches/anttest/iChime/Program-Info.plist
[echo] Errors:
[echo] Old version number: 3.0.0 New Version Number: anttest
The plist isn't updated, and the only hit is a return code of 1. I'm the release engineer - I don't know xcode. Does anyone see what I'm doing wrong here?
A: You've got a leading space just before the plist location in the set command:
<!-- v -->
<arg value=" ${LocationOfPList}"/>
It's one of those invisible errors - you might notice two spaces between "Will Create:" and "/Users" in the error message.
Remove the space and it should work.
Also, the PListError property is set to an empty string by the first exec, and Ant properties are immutable, hence no error text for the second exec.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: IIS HTTP Keep-Alives I am reading that Keep-Alives is meant for performance - so that no connections need to be recreated but just reuse the existing ones. What if there is a traffic spike, will new connections be created?
Additionally, if I don't turn on Keep-Alive and in a high traffic environment, will it eventually running out of connections/socket port on client side? because a new connection has to be created for each http/web request.
A: HTTP is a stateless protocol.
In HTTP 1.0 each request meant opening a new TCP connection.
That caused performance issues (e.g. have to re-do the 3-way handshake for each GET or POST) so the Keep-Alive Header was added to maintain the connection across requests and in HTTP1.1 the default is persistent connection.
This means that the connection is reused across requests.
I am not really familiar with IIS but if there is a configuration to close the connection after each HTTP response, it will have impact on the performance.
Concerning the running out of sockets/ports on the client side, that could occur if the client fires a huge amount of requests and a new TCP connection must be opened per HTTP request.
After a while the ports will be depleted
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: wrapping a data grid with a toolbox I got a wpf application.
I want all my data grids in application to have a set of buttons above them.
Tried to use decorator and adorner without success(the dataGrid stopped showing rows)
Any suggestions?
A: Given that you're wanting to have functionality behind the toolbox buttons (which I assume will require a reference to the grid) it probably makes sense to inherit from a HeaderedContentControl for this. This does mean that you can put any content in the control, but it would be possible to put override the metadata to add validation for this.
Anywhere, here's the xaml:
<!-- ToolBoxGridControl.xaml -->
<HeaderedContentControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfApplication3.ToolBoxGridControl">
<HeaderedContentControl.Header>
<StackPanel Orientation="Horizontal">
<Button/>
<Button/>
<Button/>
</StackPanel>
</HeaderedContentControl.Header>
<HeaderedContentControl.Template>
<ControlTemplate TargetType="HeaderedContentControl">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<ContentControl Grid.Row="0" Content="{TemplateBinding Header}"/>
<ContentControl Grid.Row="1" Content="{TemplateBinding Content}"/>
</Grid>
</ControlTemplate>
</HeaderedContentControl.Template>
</HeaderedContentControl>
And the simple code-behind (where you can put your toolbox implementation).
public partial class ToolBoxGridControl : HeaderedContentControl
{
private DataGrid DataGrid { get { return (DataGrid)Content; } }
public ToolBoxGridControl()
{
this.InitializeComponent();
}
}
To actually use, you can just add the following to your XAML with your data grid
<local:ToolBoxGridControl>
<DataGrid/>
</local:ToolBoxGridControl>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Avoiding round-trips when importing data from Excel I'm using EF 4.1 (Code First). I need to add/update products in a database based on data from an Excel file. Discussing here, one way to achieve this is to use dbContext.Products.ToList() to force loading all products from the database then use db.Products.Local.FirstOrDefault(...) to check if product from Excel exists in database and proceed accordingly with an insert or add. This is only one round-trip.
Now, my problem is there are two many products in the database so it's not possible to load all products in memory. What's the way to achieve this without multiplying round-trips to the database. My understanding is that if I just do a search with db.Products.FirstOrDefault(...) for each excel product to process, this will perform a round-trip each time even if I issue the statement for the exact same product several times ! What's the purpose of the EF caching objects and returning the cached value if it goes to the database anyway !
A: There is actually no way to make this better. EF is not a good solution for this kind of tasks. You must know if product already exists in database to use correct operation so you always need to do additional query - you can group multiple products to single query using .Contains (like SQL IN) but that will solve only check problem. The worse problem is that each INSERT or UPDATE is executed in separate roundtrip as well and there is no way to solve this because EF doesn't support command batching.
Create stored procedure and pass information about product to that stored procedure. The stored procedure will perform insert or update based on the existence of the record in the database.
You can even use some more advanced features like table valued parameters to pass multiple records from excel into procedure with single call or import Excel to temporary table (for example with SSIS) and process them all directly on SQL server. As last you can use bulk insert to get all records to special import table and again process them with single stored procedures call.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Having trouble making a local copy of an xml feed using php I'm trying to save a local copy of an xml file, and then open it with simple xml, but i'm getting some errors.. here's my code:
$feedURL = "https://gdata.youtube.com/feeds/api/users/manitobachildhealth/favorites";
//$xml = file_get_contents("$feedURL");
$xml = file_get_contents($feedURL);
file_put_contents("video.xml", $xml);
// read feed into SimpleXML object
//$sxml = simplexml_load_file($feedURL);
$sxml = simplexml_load_file('video.xml');
The error i'm getting is as follows:
Warning: file_get_contents(https://gdata.youtube.com/feeds/api/users/manitobachildhealth/favorites) [function.file-get-contents]: failed to open stream: Result too large in D:\wamp\www\videos2.php on line 48
I'm not sure why it would be too large of a result, it only returns 6kb of xml. what am i doing wrong?
Update:
This is running on a windows platform using WAMP server - not ideal, but i'm stuck with it.
Update 2:
I've tried using curl and fwrite to achieve a similar result, as suggested below, but it won't write the xml file to the local server. It doesn't give me any errors though.
update 3:
This is obviously a very specific problem with the hosting environment, but I'm not sure where to start looking for the problem. Using curl works great on a linux-based dev server, but is causing problems on this windows-based production server. An extra help in troubleshooting this issue would be most appreciated!
A: Correct answer for the question:
It is possible you are having the same problem as of this question: CURL and HTTPS, "Cannot resolve host" (DNS-Issue)
Other Details:
You can use SimpleXML to load and save the xml data
$xml = new SimpleXMLElement('https://gdata.youtube.com/feeds/api/users/manitobachildhealth/favorites', NULL, TRUE);
$xml->asXML('video.xml');
I have tested the code above in a WAMP server and it works fine.
Update:
If the above returns error message "[simplexmlelement.--construct]: I/O warning : failed to load external entity ...." It's possible that your server does not allow to include external data or the php file/script does not have the right permission.
Try the following:
1. echo the content of the xml file.
$xml = new SimpleXMLElement('https://gdata.youtube.com/feeds/api/users/manitobachildhealth/favorites', NULL, TRUE);
echo htmlentities($xml->asXML());
If you managed to retrieved the xml content and print it to the browser, then your server is allowing to include external content and most likely the problem with the file permission. Make sure file/script have the right to create xml file.
If the above still does not work try using cURL.
function getPageContent($options)
{
$default = array(
'agent' => $_SERVER['HTTP_USER_AGENT'],
'url' => '',
'referer' => 'http://'.$_SERVER['HTTP_HOST'],
'header' => 0,
'timeout' => 5,
'user' => '',
'proxy' => '',
);
$options = array_merge($default, $options);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $options['url']);
curl_setopt($ch, CURLOPT_HEADER, $options['header']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if ($options['proxy'] != '') {
curl_setopt($ch, CURLOPT_PROXY, $options['proxy']);
}
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $options['timeout']);
curl_setopt($ch, CURLOPT_REFERER, $options['referer']);
curl_setopt($ch, CURLOPT_USERAGENT, $options['agent']);
if ($options['user'] != '') {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $options['user']);
}
$result = array();
$result['content'] = curl_exec($ch);
$result['info'] = curl_getinfo($ch);
$result['error'] = curl_error($ch);
curl_close($ch);
return $result;
}
$result = getPageContent(array(
'proxy' => '[ip or address]:[port]', // if needed
'user' => '[username]:[password]', // if needed
'url' => 'http://gdata.youtube.com/feeds/api/users/manitobachildhealth/favorites'
));
if (empty($result['error'])) {
// ok
// content of xml file
echo htmlentities($result['content']);
// file
$filename = 'video.xml';
// Open File
if (!$fp = fopen($filename, 'wt')) {
die("Unable to open '$filename'\n\n");
}
// write content to file
fwrite($fp, $result['content']);
// close file
fclose($fp);
} else {
// failed
echo '<pre>';
echo 'Error details;';
print_r ($result['error']);
echo '<hr />Other info:';
print_r ($result['info']);
echo '</pre>';
}
A: Have you tried using curl and fwrite to get the contents and write them to a local file?
$ch = curl_init("https://gdata.youtube.com/feeds/api/users/manitobachildhealth/favorites");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
fwrite("video.xml",$output);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JMX - Monitor process existence I want to be able to monitor a process's existence continuously and restart it if it had crashed or killed for any reason using JMX. Stopping and starting a process is not a probelm as the agent executes a script for it. I can monitor process's existence by implementing heartbeats between the agent and the monitored process but I am looking for something using JMX itself, if something exists?
A: You can expose the component as a JMX managed resource.
Try to do the heartbeat.
If you get instanceNotFound from the managed bean server then it has crashed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CRM for Outlook Connector - failure to initialize after AD password reset Everything seems to work fine with my dynamics CRM 2011 until the day when there is an auto password request from our AD. I have the crm for outlook connector and this does not get initialized after I change the AD password - just a plain old outlook with mail and everything comes up, but no crm.
how do I resolve this? more importantly whats the long term solution? because our AD password reset occurs every 2months....ouch!
A: In Control Panel\User Accounts\Credential Manager in section Generic Credentials delete the correspondent entry for your crm.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Oracle - Way to rewrite this query to not use sub-selects? I'm trying to create a materialized view in Oracle 11.1, which apparently does not support nested selects in a materialized view (Why this is, I haven't been able to figure out).. Is there a way to write this query to work as a materialized view? Thanks!
CREATE MATERIALIZED VIEW MV_Area90DayReport
NOLOGGING
CACHE
BUILD IMMEDIATE
REFRESH FAST ON COMMIT
AS
select
T.TASKID,
V.PROJECTID,
V.VERSIONID,
T.GOLDDATE,
P.BUSINESSLAUNCHDATE,
V.NAME as ProjectName,
T.NAME as TaskName,
T.COURSECODE,
DT.NAME as DeliveryMethod,
T.DELIVERABLELENGTHHOUR,
T.DELIVERABLELENGTHMINUTE,
V.PRIORITY,
(SELECT MIN(STARTDATE) FROM TPM_TRAININGPLAN WHERE PROJECTID=V.PROJECTID AND TRAININGPLANTYPE='prescribed') as TrainingDeliveryDate,
(SELECT wm_concat(WORKGROUPID) FROM TPM_PROJECTWORKGROUPS WHERE PROJECTID=V.PROJECTID GROUP BY PROJECTID) as Workgroups,
from TPM_TASK T
inner join TPM_PROJECTVERSION V ON (V.PROJECTID = T.PROJECTID AND V.VERSIONID = T.VERSIONID)
inner join TPM_PROJECT P ON (P.PROJECTID = T.PROJECTID)
inner join TPM_DOCUMENTTYPE DT ON (DT.DOCUMENTTYPEID = T.DOCUMENTTYPEID);
The error I get is:
>[Error] Script lines: 1-25 -------------------------
ORA-22818: subquery expressions not allowed here
Script line 20, statement line 20, column 115
A: I believe this is a limitation (that was raised as a bug sometime back), documented here on the Oracle site - http://download.oracle.com/docs/cd/B12037_01/server.101/b10736/basicmv.htm#sthref431
To resolve, you should use JOINS rather than subqueries.
A: Try the following query:
select
T.TASKID,
V.PROJECTID,
V.VERSIONID,
T.GOLDDATE,
P.BUSINESSLAUNCHDATE,
V.NAME as ProjectName,
T.NAME as TaskName,
T.COURSECODE,
DT.NAME as DeliveryMethod,
T.DELIVERABLELENGTHHOUR,
T.DELIVERABLELENGTHMINUTE,
V.PRIORITY,
TP.TrainingDeliveryDate,
WG.Workgroups,
from TPM_TASK T
inner join TPM_PROJECTVERSION V ON (V.PROJECTID = T.PROJECTID AND V.VERSIONID = T.VERSIONID)
inner join TPM_PROJECT P ON (P.PROJECTID = T.PROJECTID)
inner join TPM_DOCUMENTTYPE DT ON (DT.DOCUMENTTYPEID = T.DOCUMENTTYPEID)
left join (
SELECT PROJECTID, MIN(STARTDATE) as TrainingDeliveryDate
FROM TPM_TRAININGPLAN
WHERE TRAININGPLANTYPE='prescribed'
GROUP BY PROJECTID
) TP on TP.PROJECTID=V.PROJECTID
left join (
SELECT PROJECTID, wm_concat(WORKGROUPID) as Workgroups
FROM TPM_PROJECTWORKGROUPS
GROUP BY PROJECTID
) WG on WG.PROJECTID=V.PROJECTID
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Submodule importing primary module First of all, my apologies if this question has already be asked elsewhere. I really searched for it, but didn't find anything.
The situation is the following:
In a folder mod, I have the files __init__.py and sub.py.
They contain the following data:
__init__.py:
print "mod"
sub.py:
import __init__
print "sub"
Now let's do the following:
>>> import mod
mod
>>> import mod.sub
mod
sub
But when doing import mod.sub, why is mod/__init__.py executed again? It had been imported already.
The same strange feature exists if we just call:
>>> import mod.sub
mod
mod
sub
Can I change the behaviour by changing the import __init__? This is the line that seems most likely wrong to me.
A: You can actually inspect what is going on by using the dictionary sys.modules. Python decides to reload a module depending on the keys in that dictionary.
When you run import mod, it creates one entry, mod in sys.modules.
When you run import mod.sub, after the call to import __init__, Python checks whether the key mod.__init__ is in sys.modules, but there is no such key, so it is imported again.
The bottom line is that Python decides to re-import a module by keys present in sys.modules, not because the actual module had already been imported.
A: you should replace
import __init__
by
import mod
A: For completeness, I found another solution playing around with relative imports:
Replace
import __init__
by
from . import __init__
But I don't understand why this works.
edit: This actually doesn't work. the resulting__init__ is not the module mod, but something else of the type method-wrapper. Now I'm totally confused.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Submitting a form programmatically
Possible Duplicate:
How do you programmatically fill in a form and 'POST' a web page?
I've been looking for a way to allow a user to submit a form using C# or even HTML,so I get the source code, save it in a file and get the name of the text fields in order to submit the form.
for example logging with ur email to Facebook, gmail,stackoverflow ... or any page containing a form.
Before I ask how,is it possible?
My project is mainly to help visually impaired people surf the web easier! like get any html source code and be able to re-arrange the tags, omit images and such tags that won't benefit them,and try to give them the ability to log in using speech to text ...so my code will take the speech convert it to text field by field and submit the form when he/she's done! of course the name of the fields will be spoken using text to speech!
Thanks in advance
A: Have you looked at the WebBrowser control?
http://msdn.microsoft.com/en-us/library/aa752041(v=vs.85).aspx
It will allow you to automate surfing. You'll also be able to interact with the pages and modify values in text boxes, click buttons, submit forms.
Here's some talk about how to handle clicking.
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/2eed72f7-4fde-4730-abf7-738e9b6e87c4/
I've used that approach successfully in the past, but I will say it's problematic if you don't/can't control the website. If I write a program that will automate logging into facebook with this method it would require me telling it what URL to visit, what textboxes to fill, and what form name or button name to click.
If Facebook redesigns their layout - my code may no longer work.
If you are just interested in the logging in part; you might want to take a look at browser addons (I don't know if this will help at all, but I thought I would mention it). I use a product called, 'LastPass' (https://lastpass.com/) and it manages all of my user names and passwords. If I visit a site it is familiar with, it can automatically fill in the forms for me, allowing me to log in or completely enter my address.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error: Unbound value PolkaGrid.manager_alloc_loose I am still trying to compile this file, by ocamlc -I /usr/local/lib/ocaml/3.11.2/apron -I /usr/local/lib/ocaml/3.11.2/gmp/ -c file.ml
open Apron;;
open Mpqf;;
open Format;;
let print_array = Abstract0.print_array;;
let lincons1_array_print fmt x =
Lincons1.array_print fmt x
;;
let generator1_array_print fmt x =
Generator1.array_print fmt x
;;
let manpk = Polka.manager_alloc_strict();;
let manbox = Box.manager_alloc ();;
let manoct = Oct.manager_alloc ();;
let manppl = Ppl.manager_alloc_strict();;
let mangrid = Ppl.manager_alloc_grid ();;
let maneq = Polka.manager_alloc_equalities ();;
let manpkgrid = PolkaGrid.manager_alloc_loose ();;
The errors in my previous threads have been resolved, now I am stuck with Error: Unbound value PolkaGrid.manager_alloc_loose. But I can find polkaGrid.cmi, polkaGrid.cmxa and some other files under /usr/:
...@ubuntu$ find -name "*polkaGrid*"
./lib/polkaGrid.cma
./lib/polkaGrid.cmi
./lib/polkaGrid.mli
./lib/polkaGrid.a
./lib/dllpolkaGrid_caml.so
./lib/libpolkaGrid_caml_debug.a
./lib/polkaGrid.cmxa
./lib/libpolkaGrid_caml.a
./local/lib/ocaml/3.11.2/stublibs/dllpolkaGrid_caml.so
./local/lib/ocaml/3.11.2/stublibs/dllpolkaGrid_caml.so.owner
./local/lib/ocaml/3.11.2/apron/polkaGrid.cma
./local/lib/ocaml/3.11.2/apron/polkaGrid.cmi
./local/lib/ocaml/3.11.2/apron/polkaGrid.mli
./local/lib/ocaml/3.11.2/apron/polkaGrid.a
./local/lib/ocaml/3.11.2/apron/libpolkaGrid_caml_debug.a
./local/lib/ocaml/3.11.2/apron/polkaGrid.cmxa
./local/lib/ocaml/3.11.2/apron/polkaGrid.cmx
./local/lib/ocaml/3.11.2/apron/libpolkaGrid_caml.a
Does anyone know the reason of the error message? Thank you very much!
PS: about PolkaGrid
A: You should replace
let manpkgrid = PolkaGrid.manager_alloc_loose ();;
by
let manpkgrid = PolkaGrid.manager_alloc manpk mangrid;;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: QT: Position tabs within QTabBar block There is a QTabBar element with a vertical size policy which is expanding. I want to make the tabs to be aligned to the bottom of the QTabBar element box, but they are always appearing from the top.
I have tried styling QTabBar and QTabBar::tab with different combinations of vertical-align: bottom, alignment: bottom;, bottom:0; but with zero luck. It seems that the only alignment that actually work is when I align horizontally.
Current results:
The tabs are separated from where the content will go. And before suggesting me to not use an expanding vertical policy. I have to do it like this, I have my reasons.
A: The widget alignment can be set in the containing layout, and you have to use a non-zero stretch value:
vbox->addWidget(tabBar, 1, Qt::AlignBottom);
vbox->addWidget(otherWidget, 1);
The tab will be correctly aligned, with empty space above it, but that space won't be a part of the QTabBar (the expanding policy will be ignored).
If you need to put something in the space above the QTabBar, you could insert it at the bottom of another intermediary QWidget and insert that widget into the layout instead of the QTabBar.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503757",
"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.