text stringlengths 8 267k | meta dict |
|---|---|
Q: Issue installing PHP with IMAP/Kerberos support on Ubuntu 11 I'm trying to install PHP on Ubuntu 11.04. I'm compiling from source.
Here is me installing dependencies:
apt-get -y install php5-dev php-pear
apt-get -y install libxml2-dev libevent-dev zlib1g-dev libbz2-dev libgmp3-dev libssl-dev libcurl4-openssl-dev libjpeg-dev libpng-dev libgd2-xpm-dev libmcrypt-dev memcached libmemcached-dev libc-client-dev libkrb5-dev
And here is my configure script:
./configure --enable-fpm --enable-cli --with-fpm-user=php-fpm --with-fpm-group=php-fpm --prefix=/usr/local/php --exec-prefix=/usr/local/php --with-config-file-path=/usr/local/php/etc --with-config-file-scan-dir=/usr/local/php/etc --enable-bcmath --enable-ctype --with-curl --with-curlwrappers --enable-dba --with-cdb --with-flatfile --with-inifile --enable-exif --enable-ftp --disable-fileinfo --with-gd --with-jpeg-dir --with-png-dir --with-zlib-dir --with-xpm-dir --with-ttf --with-freetype-dir --enable-gd-native-ttf --with-gettext --with-gmp --with-imap --with-imap-ssl --with-ldap --with-ldap-sasl --enable-mbstring=all --with-mcrypt --with-mhash --with-mysql --with-mysqli --with-pdo-mysql --with-openssl --with-kerberos --with-pspell --enable-shmop --enable-simplexml --with-snmp --enable-soap --enable-sockets --with-tidy --enable-wddx --enable-xmlreader --with-xmlrpc --with-xsl --with-zip --with-zlib --enable-sysvsem --enable-sysvshm
However, I get an error:
configure: error: Kerberos libraries not found.
Check the path given to --with-kerberos (if no path is given, searches in /usr/kerberos, /usr/local and /usr )
I didn't provide a path, but there's no directory like /usr/kerberos on my system. About five lines above the error there is a log entry that says checking for IMAP Kerberos support... yes.
Do I need to specify a directory for --with-kerberos and what would this directory be exactly? I've been on this all day, and can't seem to figure it out.
Thanks in advance.
EDIT:
I was able to sort this issue out with a symbolic link.
Below is the what you do before you run the configure command.
mkdir /usr/kerberos
ln -s /usr/lib/x86_64-linux-gnu /usr/kerberos/lib
Cheers.
A: I was dealing with this issue installing PHP 5.3.8 from source on Ubuntu 11.04. I was using:
./configure '--with-libdir=lib64' '--with-mysql=/usr' '--with-curl' '--with-imap' '--with-imap-ssl' '--with-kerberos' '--with-mhash=shared' '--with-gd' '--with-jpeg-dir' '--with-png-dir' '--with-zlib-dir' '--with-freetype-dir' '--with-mcrypt' '--with-mysqli' '--enable-gd-native-ttf' '--enable-calendar' '--enable-ftp' '--with-openssl' '--enable-pcntl' '--enable-soap' '--enable-sockets' '--enable-spl' '--enable-tokenizer' '--enable-wddx' '--with-apxs2=/usr/local/apache/bin/apxs' '--with-config-file-path=/usr/local/apache/conf'
and was getting the same error:
configure: error: Kerberos libraries not found.
Check the path given to --with-kerberos (if no path is given, searches in /usr/kerberos, /usr/local and /usr )
I realized that my kerberos installation files were in the very different /usr/lib/x86_64-linux-gnu. I tried the suggested "--with-kerberos=/usr/lib/x86_64-linux-gnu" but as one of the linked pages suggests, the search automatically adds "lib" to the end of the provided path.
As mentioned, one of the other pages linked to here discusses that the script automatically adds "lib" onto the paths (so without specifying a path, it looks in /usr/kerberos/lib, /usr/local/lib, and /usr/lib) but what I failed to realize is that if you're using "--with-libdir=lib64" this results in the script actually looking for /usr/kerberos/lib64, /usr/local/lib64, /usr/lib64).
Upon realizing this, I just created the following symlinks and tried again without specifying a kerberos path.
mkdir -p /lib/kerberos
ln -s /usr/lib/x86_64-linux-gnu/ /usr/kerberos/lib
ln -s /usr/lib64/x86_64-linux-gnu/ /usr/kerberos/lib64
This worked for me. Hopefully it helps someone else.
A: Did you try Googling your error message? This page seems to have a viable solution to your problem.
" I checked my system, and found that the Kerberos libraries were installed in /usr/lib64. So I passed –with-kerberos=/usr/lib64 to the configure script, but the script still reported that the Kerberos libraries could not be found. "
" From the pages of output that filled my terminal, I found that the configure script was appending “lib” to the –with-kerberos path that I provided, so it was looking inside a non-existent “/usr/lib64/lib” directory. However, I found that I could change “lib” to “lib64″ by passing –with-libdir=lib64 to the configure script. "
A: As i had this error with 10.04 as well, I decided to paste my solution as well. Maybe it can help someone someday. Running the compilation on lucid I changed from --with-kerberosto with-kerberos=shared,/usr/lib. Looks like this was all the magic here as the compiler ran through lib64 missing out on that one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: html5 canvas - rotate and move an image at the same time i allready found out how to rotate an image with canvas, but im having problems creating an animation, which rotates and moves an image at the same time. This is what i already have:
var img;
var context;
var processID;
var i = 0;
var rectWidth = 64;
var rectHeight = 64;
window.onload = function(){
var canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
context.translate(canvas.width / 2, canvas.height / 2);
processID = setInterval(draw,1000/100);
}
function draw() {
if(i <= 360) {
context.clearRect(-canvas.width / 2, -canvas.width / 2, canvas.width, canvas.height);
context.strokeRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight);
context.rotate(1 * Math.PI / 180);
i++;
} else {
clearInterval(processID);
}
}
So now i want my square to move to the top while rotating. I'm really lost here and would appreciate some help.
A: You could use the translate method, or more generically the transform method. See the docs for a reference of what you can do, and the wiki page for Transformation Matrices
A: So luckily i found the answer myself:
var img;
var context;
var processID;
var i = 0;
var rectWidth = 64;
var rectHeight = 64;
window.onload = function(){
var canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
processID = setInterval(draw,1000/100);
}
function draw() {
if(i <= 360) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.save();
context.translate(canvas.width / 2, i+(canvas.height / 2));
context.rotate(i * Math.PI / 180);
context.strokeRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight);
context.restore();
i++;
} else {
clearInterval(processID);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I change the RollingFileAppender to another than the one set in config file? I'm using log4j in my app, and a config file that sets up output to console and a rollingfileappender. Pasting config file below. Is there a way to change
the fileappender output file after opening the config file in code? It opens fine for me, but there are times when I will want to use a different output file than the default one in the config file. Thanks for any direction.
log4j.rootLogger=info, stdout, RFA
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=[%p] [%d{MM/dd/yyyy HH:mm:ss}] - %m %n
log4j.appender.RFA=org.apache.log4j.RollingFileAppender
log4j.appender.RFA.File=${user.home}/output.log
log4j.appender.RFA.MaxFileSize=100KB
# Keep backup files
log4j.appender.RFA.MaxBackupIndex=5
log4j.appender.RFA.layout=org.apache.log4j.PatternLayout
log4j.appender.RFA.layout.ConversionPattern=[%p] [%d{MM/dd/yyyy HH:mm:ss}] - %m %n
A: If you mean to edit the properties file from your code and have log4j detect it you'll have to make log4j monitor the properties file first by calling PropertyConfigurator.configureAndWatch("log4j.properties")
However, I'd prefer to access the appenders programatically using the Logger api like kunal mentioned.
update; code for doing it programatically
Enumeration allAppenders = Logger.getRootLogger().getAllAppenders();
while (allAppenders.hasMoreElements()) {
Object object = (Object) allAppenders.nextElement();
if (object instanceof RollingFileAppender) {
RollingFileAppender appender = (RollingFileAppender) object;
appender.setFile("/path/to/new/file.log");
appender.activateOptions();
break;
}
}
A: define another appender (with a different File value).
A: I think you want to set (change) the File programmatically. Have a look at the RollingFileAppender API.
public void setFile(String fileName,
boolean append,
boolean bufferedIO,
int bufferSize)
throws IOException
Sets and opens the file where the log output will go. The specified file must be writable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Recover deleted MySQL rows? The situation is that I deleted rows from the database and now they are wanted back.
There are no binary logs, and no backup.
But as I know records are not deleted instantly, they're just marked as 'deleted', but they're actually deleted only after next optimisation.
And I have just copied all the database files into safe places: frms, MIYs and MYDs. I know the structure of table I'm interested in; I can even find all deleted row ids.
Is there any tool to recover recently deleted rows?
A: If you happen to know the offset of the data (or know some unique string) for the rows you deleted, then go ahead an pop open a hex editor and copy the (binary) data by hand. If you do recover it all you'll be extremely fortunate, and I hope you write up an article on it, because frankly I don't believe this is possible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Use Facebook Connect using Lua? I am a beginner in Lua and was trying to implement Facebook connect api using Lua. I searched online and found out that Corona SDK provides this but I am not allowed to purchase any SDK and use Lua.
Can anyone suggest any open source SDK or any other way that I can implement facebook connect api using Lua?
A: Firstly I will start and say that I have no knowledge of Lua what-so-ever. That said, any language with the capability of making http requests can use the facebook api.
Facebook's documentation of the Graph API details what and where exactly to query.
As I imagined there are lots of resources on Lua and networking. The actual calls to facebook look something like this :
https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&
client_secret=YOUR_APP_SECRET
With that code you retrieve your access token, and then you can make requests like this :
https://graph.facebook.com/SOME_USER_ID/feed?access_token=YOUR_ACCESS_TOKEN
That will give you a JSON response with the users wall and its data.
A GREAT place to start playing with those urls and their meanings is this great tool from facebook. Its the Graph API Explorer. Click on get access token and mark the permissions you need and then poke away at all your facebook data!
A: There may not already be a wrapping of the FB API in Lua. That said, it should not be difficult to do.
The LuaSocket module supplies support for HTTP requests. You would use it to request the individual URLs that make up the API calls. Those requests will return data in JSON format that you will need to parse in order to use.
To parse JSON easily in Lua, you will want to find a suitable wrapper for a JSON parser. A quick search shows that there are a fair number of choices out there. A popular one appears to be JSON4Lua.
Here is an article that includes a worked example for accessing a particular JSON-based API from Yahoo! based on both LuaSocket and JSON4Lua. The sample code looks like:
-- Client for the Yahoo Traffic API (http://developer.yahoo.com/traffic/rest/V1/index.html)
-- using JSON and Lua
-- Matt Croydon (matt@ooiio.com) http://postneo.com
http = require("socket.http") -- http://www.cs.princeton.edu/~diego/professional/luasocket/
json = require("json") -- http://json.luaforge.net/
-- Retrieve traffic information for Kansas City, MO
r, c, h = http.request("http://local.yahooapis.com/MapsService/V1/trafficData?appid=LuaDemo&city=Kansas+City&state=MO&output=json")
if c == 200 then
-- Process the response
results = json.decode(r)["ResultSet"]["Result"]
-- Iterate over the results
for i=1,table.getn(results) do
print("Result "..i..":")
table.foreach(results[i], print)
print()
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I fix this error when installing ADT on Ubuntu? I do not know much about Eclipse, but according to this tutorial everything should work fine (I am using the .zip archive). The error seems to occur only when Android Development Tools are checked.
Here is the full error code:
Cannot complete the install because one or more required items could not be found.
Software being installed: Android Development Tools 12.0.0.v201106281929-138431 (com.android.ide.eclipse.adt.feature.group 12.0.0.v201106281929-138431)
Missing requirement: Android Development Tools 12.0.0.v201106281929-138431 (com.android.ide.eclipse.adt.feature.group 12.0.0.v201106281929-138431) requires 'org.eclipse.gef 0.0.0' but it could not be found.
A: I got the answer from the Eclipse forums here
At the available software window, click on the link "Available software sites".
You need two items checked, the Android Plugin that you added and the download.eclipse.org/releases/helios or galilio if that is your version of eclipse. Click ok to go back to the available software window.
Now select Work with: Android plugin.
Now click next continuing with install.
Steps:
*
*Help > Install New Software
*type or paste: http://download.eclipse.org/releases/galileo (change to match your version of eclipse then click Add)
*Click Cancel, go back to Install New Software and choose the Android related repository. ie. http://dl-ssl.google.com/android/eclipse/)
Note that sometimes you need to use the http, not https link for the ADT repository (the https did not work for me).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: High performance simple Java regular expressions Part of the code I'm working on uses a bunch of regular expressions to search for some simple string patterns (e.g., patterns like "foo[0-9]{3,4} bar"). Currently, we use statically-compiled Java Patterns and then call Pattern#matcher to check whether a string has contains a match to the pattern (I don't need the match, just a boolean indicating whether there is a match). This is causing a noticeable amount of memory allocation that is affecting performance.
Is there a better option for Java regex matching that is faster or at least doesn't allocate memory every time it searches a string for a pattern?
A: If you expect less than 50% of lines matching your regex, you can first try to test for some subsequence via String.indexOf() which is about 3 to 20 times faster for simple sequence compared to regex matcher:
if (line.indexOf("foo")>-1) && pattern.matcher(line).matches()) {
...
If you add to your code such heuristics, remember to always well document them, and verify using profiler that code is indeed faster compared to simple code.
A: If you want to avoid creating a new Matcher for each Pattern, use the usePattern() method, like so:
Pattern[] pats = {
Pattern.compile("123"),
Pattern.compile("abc"),
Pattern.compile("foo")
};
String s = "123 abc";
Matcher m = Pattern.compile("dummy").matcher(s);
for (Pattern p : pats)
{
System.out.printf("%s : %b%n", p.pattern(), m.reset().usePattern(p).find());
}
see the demo on Ideone
You have to use matcher's reset() method too, or find() will only search from the point where the previous match ended (assuming the match was successful).
A: Try matcher.reset("newinputtext") method to avoid creating new matchers each time you are calling Pattern.matcher.
A: You could try using the Pattern.matches() static method which would just return the boolean. That wouldn't return a Matcher object so it could help with the memory allocation issues.
That being said the regex pattern would not be precompiled so it would be a performance vs resources thing at the point.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: How do you non-interactively turn on features in a Linux kernel .config file? I have a situation where our software needs to work with several different Linux kernel distributions / kernel trees. (including Android forks)
In trying to automate our build process, I am finding that some of the defconfig files for particular builds we need to support do not include the kernel modules we depend on.
For example, let's imagine I need an option called XXX in my .config. For some dependencies, I can do something like this:
sed -i 's/# CONFIG_XXX is not set/CONFIG_XXX=m/' .config
For others, it's not so easy since the dependency may span multiple lines of .config statements.
Is there a more supported way to do this non-interactively, or am I stuck writing a more complex search-and-replace script?
A: merge_config.sh config fragments
$ cd linux
$ git checkout v4.9
$ make x86_64_defconfig
$ grep -E 'CONFIG_(DEBUG_INFO|GDB_SCRIPTS)[= ]' .config
# CONFIG_DEBUG_INFO is not set
$ # GDB_SCRIPTS depends on CONFIG_DEBUG_INFO in lib/Kconfig.debug.
$ cat <<EOF >.config-fragment
> CONFIG_DEBUG_INFO=y
> CONFIG_GDB_SCRIPTS=y
> EOF
$ # Order is important here. Must be first base config, then fragment.
$ ./scripts/kconfig/merge_config.sh .config .config-fragment
$ grep -E 'CONFIG_(DEBUG_INFO|GDB_SCRIPTS)[= ]' .config
CONFIG_DEBUG_INFO=y
CONFIG_GDB_SCRIPTS=y
Process substitution does not work unfortunately:
./scripts/kconfig/merge_config.sh arch/x86/configs/x86_64_defconfig \
<( printf 'CONFIG_DEBUG_INFO=y\nCONFIG_GDB_SCRIPTS=y\n' )
because of: https://unix.stackexchange.com/a/164109/32558
merge_config.sh is a simple front-end for the make alldefconfig target.
When cross compiling, ARCH must be exported when you run merge_config.sh, e.g.:
export ARCH=arm64
export CROSS_COMPILE=aarch64-linux-gnu-
make defconfig
./scripts/kconfig/merge_config.sh .config .config-fragment
The merged output file can be specified explicitly with the KCONFIG_CONFIG environment variable; otherwise it just overwrites .config:
KCONFIG_CONFIG=some/path/.config ./scripts/kconfig/merge_config.sh .config .config-fragment
Buildroot automates it with BR2_LINUX_KERNEL_CONFIG_FRAGMENT_FILES: How do I configure the Linux kernel within Buildroot?
Related: https://unix.stackexchange.com/questions/19905/how-to-non-interactively-configure-the-linux-kernel-build Migrated 20 days earlier :-)
A: Yes, some config options change names between releases, sometimes as an indication of subtle semantic changes.
I have written python classes to merge together a set of configuration fragments into base kernel configuration files. That's overkill for you, though; you can do the same thing as a sed script; you aren't limited to one-liners.
sed -ir 's/^(CONFIG_XXX=.*|# CONFIG_XXX is not set)/CONFIG_XXX=m/;
s/^(CONFIG_FOO=.*|# CONFIG_FOO is not set)/CONFIG_FOO=m/;
s/^(CONFIG_BAR=.*|# CONFIG_BAR is not set)/CONFIG_BAR=m/' .config
Or even create a separate script. Say, config.sed that contains the lines:
s/^(CONFIG_XXX=.*|# CONFIG_XXX is not set)/CONFIG_XXX=m/;
s/^(CONFIG_FOO=.*|# CONFIG_FOO is not set)/CONFIG_FOO=m/;
s/^(CONFIG_BAR=.*|# CONFIG_BAR is not set)/CONFIG_BAR=m/;
Then you can run
sed -ire config.sed .config
Hope that helps!
A: To do a series of simple flipping of a single config while updating any and all config dependencies:
Single Option approach
./scripts/config --set-val CONFIG_OPTION y
./scripts/config --enable CONFIG_BRIDGE
./scripts/config --enable CONFIG_MODULES
./scripts/config --disable CONFIG_X25
./scripts/config --module CONFIG_NFT
make oldconfig
(updates dependencies; may prompt with new dependencies, but old deps silently goes away)
Multiple-File Merge approach
If you have several small snippets of .config-* files that you want to selectively merge into the main .config file, execute:
# Merge IP fragment CONFIG_ settings into the main .config file
./scripts/kconfig/merge_config.sh .config .config-fragment
# Merge Notebook HW-specific CONFIG_ settings into main .config file
./scripts/kconfig/merge_config.sh .config .config-notebook-toshiba
# Auto-add/auto-remove CONFIG_ dependencies
make oldconfig
References
*
*https://www.kernel.org/doc/html/latest/kbuild/kconfig.html#nconfig-mode
*https://stackoverflow.com/questions/27090431/linux-kconfig-command-line-interface/70728869#70728869
A: The kernel has a tool (./scripts/config) to change specific options on .config. Here is an example:
./scripts/config --set-val CONFIG_OPTION y
Although, it doesn't check the validity of the .config file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: MVC Custom Action Attribute During testing (at least) we're logging some low-level information for each controller/action. All controllers are derived from our custom BaseController which overrides OnActionExecuting to do the logging.
We have a property in the BaseController that determines whether or not this logging will occur, so that a controller can override OnActionExecuting itself, reset the flag, and then call "base.OnActionExecuting". The flag is normally true, but we'd want to turn it off for some Json requests, for example.
What we'd prefer to do is create a custom controller/action filter to handle that, something like this:
[LogPageAccess(false)]
[HttpGet]
Public ActionResult Foobar()
I'm sure there's a way to do it, but I haven't been able to figure out how to create the custom attribute and have it reset the flag in the BaseController.
Thanks...
A: in my project I use the following to verify access controllers:
[Capability(UserCapability.FileManagement)]
public ActionResult FileList(FileListRequestModel request, bool ajax = false)
{
//code
}
Here is my Capability Class
/// <summary>
/// Decorator to MVC class and method to evaluate if a certain capability is enabled
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CapabilityAttribute : AuthorizeAttribute
{
#region Class Attributes
private object _capability = null;
#endregion
#region Public Methods
/// <summary>
/// Create a new capability attribute
/// </summary>
/// <param name="capability">Context Value passed to the validator</param>
public CapabilityAttribute(object capability)
{
this._capability = capability;
}
/// <summary>
/// Check if attribute is enabled
/// </summary>
/// <param name="filterContext"></param>
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!Capability.Enabled(this._capability))
{
throw new UnauthorizedAccessException();
}
else
{
base.OnAuthorization(filterContext);
}
}
#endregion
}
You just need to adapt this code for your case, I hope it become useful
A: I tried to build out a simple example of your situation for a while, but then realized that I couldn't pass instance data to an Attribute-- so say if I set a Log flag to false, I couldn't use that to directly manipulate the base controller's property.
Check out this SO post.
Here was the code I was playing around with (does not compile -- can't pass this):
public class BaseController : Controller
{
public bool LogPageRequests { get; set; }
}
public class LogPageAccess : ActionFilterAttribute
{
public LogPageAccess(BaseController baseController, bool log = true)
{
baseController.LogPageRequests = log;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//Do Whatever
base.OnActionExecuting(filterContext);
}
}
public class SomeController : BaseController
{
[LogPageAccess(this, false)]
public ActionResult Index()
{
return View();
}
}
Maybe you can do something with reflection, but it might be the case that you'll have to do it the way you've been doing it since it just doesn't seem possible to get instance data to the attribute.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Google Analytics IOS SDK session timeout Average time spent per visit as reported by Google Analytics does not match my server logs. What is the default idle session timeout for the IOS SDK?
A: The SDK version of Google Analytics doesn't work quite the same way as the web version. It looks like you need something along the lines of:
-(void) applicationDidEnterBackground:(UIApplication*)application
{
[[GANTracker sharedTracker] stopTracker];
}
You need to end a given session because an app running in the background will continue to hold that session. Monitor the application state and call the appropriate methods accordingly. More here:
Why are my iOS app's session lengths 30 min + in Google Analytics?
So, to answer your question you need to know how you're calculating time in app with your logs and how to emulate that with Google Analytics, taking the background state into consideration.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android market icon application In the web android market, when I search my application I see my personal icon, but when I search my application from my phone my application has the default icon. I would like that icon to be my launch icon. What could I do?
A: Make sure you have your app icon in each drawable resource folder in your app this way each screen will have its on icon for its screen density.. And make sure in your AndroidManifest you change the Icon from the default icon to your icon you want.
A: Do you have your icon in app resources folder and in AndroidManifest.xml?
A: The launch icon and label is defined in the manifest in this line:
<application android:icon="@drawable/icon" android:label="@string/app_name">
You must put the launch icon in the res/drawable directory (preferably different resolutions under the different resolution directories). So in the above example you must have an icon.png file in res/drawable, or an icon.png in each of res/drawable-hdpi, res/drawable-mdpi, res/drawable-ldpi. See http://developer.android.com/guide/practices/ui_guidelines/icon_design.html for the icon design guidelines.
A: Hey You can use this program to change the images for Android =>
Android Icon Maker
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iPhone Core Data Missing Entities I've had an app that I've been working on for a while that I originally included Core Data support in, but didn't actually start trying to use it until recently. Now that I'm actually trying to use Core Data ... it doesn't seem like I can. When I edit my xcdatamodel to include new (or really, any) entities, I can't seem to actually access those entities in the application itself. Somewhere along the way, I renamed the project from ProjectTest to CoreDataTest, which I suspect is causing or is related to this problem. I haven't changed any of the default methods which were generated in the app delegate initially by Xcode (initially 3, but now using 4).
So, I've created a new entity called simply enough TestEntity with a single attribute (String) TestAttribute.
In my app delegate, I've tried a couple of different ways to access the Entity and save a string to it, but all fail. So I thought I'd walk through all entities thinking I was somehow messing up creating the creation of the NSEntityDescription. I put the following code in to show a listing of all Entities ... and got nothing:
NSManagedObjectModel *model = [[self.managedObjectContext persistentStoreCoordinator]
managedObjectModel];
NSLog(@"List of Entities:");
for (NSEntityDescription *entity in model)
{
NSLog(@"Entity: %@", entity);
}
NSLog(@"Done with list");
For an output I just get:
2011-09-21 14:58:01.955 CoreDataTest[1813:b603] List of Entities:
2011-09-21 14:58:01.955 CoreDataTest[1813:b603] Done with list
So ... I've tried cleaning the build. I've searched through a lot of questions here on SO and more on google, but I can't seem to find anything that solves my problem. I don't get any actual error messages or uncaught exceptions during a run of the app. Any ideas what could be causing it? I'm sure it's probably something stupidly simple that I'm overlooking ...
Thanks for any help,
Will
A: Try adding .entities, i.e.:
for (NSEntityDescription *entity in model.entities) { //...
See The docs for NSManagedObjectModel.
Also check your model is not null. Try printing it: NSLog(@"%@",model);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Find outliers in a list of coordinates data I have a list of coordinates for a boundary line, it looks like this:
-74.71224,31.11124
-74.70204,31.71901
-74.71414,31.77729
-74.70109,31.74797
-74.49712,31.74914
-74.70144,31.71014
-74.49714,31.49251
-74.70915,31.49724
-74.71194,31.70104
-74.77215,31.71404
-74.77312,31.71092
-74.71137,31.72254
-74.14272,31.71177
-74.14943,31.72044
-74.14515,31.72794
-74.19794,31.72114
-74.91112,31.71751
-74.94971,31.70549
-74.94172,31.70943
-74.97931,31.49104
The entire list should gives you a closed-loop boundary line.
And for my data, there's some points that shouldn't be there, i.e. a point that's not part of the boundary line.
And my question is, how can I find these points?
EDIT:
My idea is that, right now I have a circle with some points away from that circle, how can I check every points if it's too far away from that circle to be consider part of it?
Please see picture for what I mean. I think if a points's distance from its closest one's is bigger than x, then it's an outliers.
points in the file are not in order, meaning, not one next to next other in terms of location on the map
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I wipe the JS environment in Rhino within the interperter? I have a problem wherein I am loading a number of JS files and then
executing a function in JavaScript, then I want to wipe the global
namespace of the loaded objects, and load a different set of JS files
before executing the next JavaScript Function.
Does anyone here know of a good way of doing this without exiting the
Rhino JavaScript interpreter.
A: How exactly you're executing scripts? Some code sample would help.
Some time ago I used it this way:
Object obj = ScriptableObject.getProperty (scope, methodName);
Callable fun = (Callable) obj;
Scriptable thisObj = scope;
scope = ScriptableObject.getTopLevelScope (scope);
Object result = fun.call(cx, scope, thisObj, args);
where scope contains all loaded objects created before and cx is an instance of Context.
So you don't exactly need to wipe anything - just use new scope.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Having a list of sounds in a UIPickerView I have a UIPickerView, and I have 10 sounds. I want to implement the 10 sounds into a UIPickerView. So once the user scrolls through the picker view, each sound plays.
I'm pretty new to obj c, so bear with me please.
Here is the current code.
#import <UIKit/UIKit.h>
@interface TesttimeViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource> {
IBOutlet UIPickerView *pickerView;
NSMutableArray *list;
IBOutlet UILabel *pickLabel;
}
@end
#import "TesttimeViewController.h"
@implementation TesttimeViewController
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
return [list count];
}
-(NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [list objectAtIndex:row];
}
-(void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
NSString *string = [NSString stringWithFormat:@"Now Playing: %@", [list objectAtIndex:row]];
pickLabel.text = string;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
list = [[NSMutableArray alloc]init];
[list addObject:@"100"];
[list addObject:@"2100"];
[list addObject:@"1300"];
[list addObject:@"1400"];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
All this does is select the text then shows in a uilabel which text has been selected in the uipickerview.
Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Histogram of Oriented Gradients In Haskell I have never written a single line of Haskell code (except for random stuff in my xmonad configuration file), but I thought the perfect way to learn functional programming is by doing. I want to write a program that reads in an image file of arbitrary file type and size, and also reads in a list of pixel locations. Then it should compute histogram of oriented gradients in a window centered on each of the input list of pixels, and it needs to write these histograms out. I'll start small, so let's assume I am using just text files as the output.
What are some resources online for learning how to do this. In particular, how to read images, work with arrays of pixels, etc. I don't mind needing to build infrastructure myself; but my hope is this is the sort of project where, once I complete it, I'll be reasonably able to make my own Haskell subroutines for scientific computing tasks. Any other thoughts / suggestions are very welcome and encouraged, even if you think this idea is dumb or you're one of those weird OCaml people. My background is all Python. It's easy to do this in Python with NumPy, but I want to learn Haskell for science!
A: If you've never written any Haskell code before, I wouldn't recommend starting by playing with binary data manipulation, as you would mostly be fighting with the libraries instead of learning the language in itself. Maybe you should instead start by taking a look at Learn You a Haskell, Real World Haskell or Yet Another Haskell Tutorial.
If you really wish to go forward with that project, I recommend you use PGM as it's very simple image format. I recently implemented a parser for PGM in Haskell, and
my biggest difficulty was to understand how to deal with binary data in Haskell. Here are some resources that helped me:
*
*Chapter 10. Code case study: parsing a binary data format
*Handling Binary Data with Haskell
A: My (masterful) student implemented this just last week. Perhaps you can check for hints in his implementation of HOG. There is also a realtime CPU implementation buried in there.
It is still work in progress though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Excel macro to copy and paste data from one worksheet to another worksheet I am trying to Search for a value in a column and copy row from Sheet1 and creating new sheet as MySheet and pasting that particular row .But I am getting run time error while pasting data in MySheet.Any suggestions please.
Data Input I am trying :
ID name price units desc
1 ikura 10 4 Mail Box
2 test 11 14 xxxx
3 test 11 14 yyyy
4 test 11 14 Mail Box
Sub SearchForString()
Dim LSearchRow As Integer
Dim LCopyToRow As Integer
On Error GoTo Err_Execute
'Start search in row 4
LSearchRow = 4
'Start copying data to row 2 in Sheet2 (row counter variable)
LCopyToRow = 2
Worksheets.Add (After:=Worksheets(Worksheets.Count)).Name = "MySheet"
While Len(Range("A" & CStr(LSearchRow)).Value) > 0
'If value in column E = "Mail Box", copy entire row to Sheet2
If Range("E" & CStr(LSearchRow)).Value = "Mail Box" Then
'Select row in Sheet1 to copy
Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Select
Selection.Copy
'Paste row into Sheet2 in next row
Sheets("MySheet").Select
Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Select
ActiveSheet.Paste
'Move counter to next row
LCopyToRow = LCopyToRow + 1
'Go back to Sheet1 to continue searching
Sheets("Sheet1").Select
End If
LSearchRow = LSearchRow + 1
Wend
'Position on cell A3
Application.CutCopyMode = False
Range("A3").Select
MsgBox "All matching data has been copied."
Exit Sub
Err_Execute:
MsgBox "An error occurred."
End Sub
Regards,
Raju
A: First things first:
*
*Stop using .Select and .Activate when they're not needed, they're the
devil's methods. Deal with range/worksheet objects directly.
*Change your row counters from intergers to longs just in case.
*Explicitly declaring which worksheet you're working with can save yourself from odd bugs/errors. If you don't like the typing use a worksheet object.
*Your error handler should always output err.Number and
err.Description. If you'd done that from the beginning you
probably wouldn't have had to post this question.
*Range.Copy has a destination argument. Use it instead of Range.Paste
to save some potential headaches.
Here's some simplified code, see if it works:
Sub SearchForString()
Dim LSearchRow As Long
Dim LCopyToRow As Long
Dim wksInput As Worksheet
Dim wksOutput As Worksheet
On Error GoTo Err_Execute
'Create a new sheet output to and store a reference to it
'in the wksOutput variable
Set wksOutput = Worksheets.Add(AFter:=Worksheets(Worksheets.Count))
wksOutput.Name = "MySheet"
'The wksInput variable will hold a reference to the worksheet
'that needs to be searched
Set wksInput = ThisWorkbook.Worksheets("Sheet2")
'Start copying data to row 2 in Sheet2 (row counter variable)
LCopyToRow = 2
'Loop through all the rows that contain data in the worksheet
'Start search in row 4
For LSearchRow = 4 To wksInput.UsedRange.Rows.Count
'If value in column E = "Mail Box", copy entire row to wksOutput
If wksInput.Cells(LSearchRow, 5) = "Mail Box" Then
'One line copy/paste
wksInput.Rows(LSearchRow).Copy wksOutput.Cells(LCopyToRow, 1)
'Increment the output row
LCopyToRow = LCopyToRow + 1
End If
Next LSearchRow
With wksInput
.Activate
.Range("A3").Select
End With
MsgBox "All matching data has been copied."
Exit Sub
Err_Execute:
MsgBox "An error occurred. Number: " & Err.Number & " Description: " & Err.Description
End Sub
A: Try this simplified version:
Sub CopyData()
'// Turn off screen updating for cosmetics
Application.ScreenUpdating = False
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = "MySheet"
'// Change this to your sheet you are copying from
With Sheet1
'// Filter all rows with Mail Box
.Range("E:E").AutoFilter Field:=1, Criteria1:="Mail Box", Operator:=xlAnd
'// Copy all rows except header
.UsedRange.Offset(1).SpecialCells(xlCellTypeVisible).EntireRow.Copy Worksheets("MySheet").Cells(2, 1)
'// Remove the autofilter
If .AutoFilterMode Then .AutoFilterMode = False
End With
Application.ScreenUpdating = True
MsgBox "All matching data has been copied."
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: GWT JSNI call applet method I want to add a Java applet to a GWT page and call some of the applet's methods. This is possible in javascript by doing:
document.applet_id.someAppletMethod("value");
However when I try to implement the same idea using JSNI native function in GWT it fails. Basically it cannot find the applet object. Here's the JSNI code:
public native void callStringMethod(String methodName, String arg) /*-{
var temp = "document." + this.@com.my_project.AppletWrapper::appletName + "." + methodName + "(\"" + arg + "\");";
eval(temp); //<----- FAIL
//SOME TEST CODE
$doc.applet_id.someAppletMethod("test value") //<----- FAIL as well
alert(typeof $doc.applet_id); //Undefined
alert(typeof document.applet_id); //Undefined
alert(typeof $wnd.applet_id); //Undefined
}-*/;
Note1: I know "document" is not a valid name to be used from JSNI, you use $doc instead (explanation). I don't quite know how to encode this in eval() statement so the compiler replaces $doc with proper reference, and also the javascript generated contains the user specified method name and argument. As you may be aware it's not possible to just mix input Java variables and Javascript (explanation)
Note2: The following JavaScript runs from the web browser address bar
javascript:document.applet_id.someAppletMethod("asdf")
So the applet is there on the page, under document object and I can access it from Javascript. It's just not quite working from JSNI.
Note3: I'm adding the actual applet tag to a panel by subclassing GWT's HTML class. Along the lines of:
public AppletWrapper(String appletName, String jarName, String className) {
StringBuilder applet = new StringBuilder();
applet.append("<applet archive=\"").append(jarName).append("\" ");
applet.append("code=\"").append(className).append("\" ");
applet.append("name=\"").append(appletName).append("\" ");
applet.append("id=\"").append(appletName).append("\" ");
applet.append("width=\"100%\" height=\"450\">");
applet.append("Browser doesn't support Java");
applet.append("</applet>");
this.setHTML(applet.toString());
}
Thanks for any help on getting this working.
A: *
*Try adding mayscript="mayscript" to the <applet> tag.
*Maybe naive - is the callStringMethod() called after the applet is added to the page?
*There are 2 other at least 2 other questions like this: GWT JSNI: invoking applet methods? and GWT problem with calling Java methods from JSNI
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Unknown method error using FB.ui I'm running into an issue using the FB.ui. It is a pretty simple implementation but every time I try it I get "API Error Code: 3", "API Error Description: Unknown method".
Here is an exact copy and paste with dummy data of what I am using to get this error.
function fbSend(){
FB.ui({
method: 'send',
name: 'Me testing name',
link: 'http://google.ca',
picture: 'http://www.gravitationalfx.com/wp-content/uploads/2011/07/google+logo-75x75.png',
description: 'Me is testing description'
});
};
I'm not using any Oauth/ requesting user permissions.
Any thoughts?
Thanks in advance
Smccullough
A: There is a filed bug about it here: http://bugs.developers.facebook.net/show_bug.cgi?id=18942
Use the option display: "popup" to make it work
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Basic resizing with paperclip/imagemagick not working I'm building a Rails 3.1 app and I'm using S3 and paperclip in a for photo storage, but I keep getting the following error:
RuntimeError (Style thumb has no processors defined.):
Here are the pertinent lines from my Photo model:
has_attached_file :photo,
:default_style => :original,
:styles => {:thumb => "150x150>"},
:url => "uploads/photos/:id/photo.:extension",
:path => "uploads/photos/:id/photo.:extension",
:storage => :s3
Here is the code around line 49 in the photos controller:
@photo = current_user.photos.new
@photo.caption = params['Filename']
# first save so that we can render a row
@photo.save
@photo.photo = params['Filedata']
Thread.new do
# second save to upload the photo
@photo.save
end
Any ideas as to what I'm doing wrong?
A: After reading the paperclip documentation on processors, it seems to me that the default processor (Paperclip::Thumbnail) does not get attached. You could try and add it manually with:
:processors => [:thumbnail]
A: I figured out the problem. I was overriding the default settings class method for Paperclip in an initializer.
A: For Mac OSX users:
installing homebrew and running
brew install imagemagick
did the trick for me.
PS. If the installation of imagemagick results in something like this:
Error: The linking step did not complete successfully
The formula built, but is not symlinked into /usr/local
run:
sudo brew link imagemagick
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: grab domain name and expiry date from string I want to grab domain name and expiry date from following string...
'2011-09-25,$69,climatelawpolicy.net'
can you help me to write regex to grab doman and date from above using php. thanks.
A: Simply you can explode(',' , '2011-09-25,$69,climatelawpolicy.net')
Full code:
$arr=explode(',' , '2011-09-25,$69,climatelawpolicy.net')
echo $arr['0']; //date
echo '<br/>';
echo $arr['2']; //domain
A: I have used explode for this instead of preg_match
$str = '2011-09-25,$69,climatelawpolicy.net';
$expiring = explode(',', $str);
echo 'Date: '.$expiring[0];
echo 'Domain: '.$expiring[2];
simple using explode()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: JSF template: rendered page missing DOCTYPE TL;DR: I can't get the DOCTYPE header to appear on my JSF pages.
I just inherited a JSF 1.2 project that's having some display issues under IE. I'm brand new to JSF, but I think the issues stem from the fact that the rendered pages (from "view source") do not contain a proper DOCTYPE.
The pages are composed of multiple parts, brought together using several layers of <ui:composition>. A typical page will look like:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
template="../layout/template.xhtml">
<ui:define name="body">
<!-- html content goes here... -->
</ui:define>
</ui:composition>
Then the ../layout/template.xhtml has:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
template="./headertemplate.xhtml">
<ui:define name="menuSelection">
<ui:insert name="menuSelection"/>
</ui:define>
<ui:define name="body">
<ui:insert name="body"/>
</ui:define>
<ui:define name="footer">
<div class="footer">
<ui:include src="footer.xhtml"/>
</div>
</ui:define>
</ui:composition>
And finally, the headertemplate.xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
contentType="text/html">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<body>
<ui:insert name="body" />
</body>
</html>
</ui:composition>
I have left out many xmlns lines for brevity; I hope you get the idea.
How can I get the DOCTYPE to show up in the rendered pages?
A: Remove <ui:composition> from your master template, which is the headertemplate.xhtml. It doesn't belong there. The <ui:composition> will strip all other content outside the tag.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<ui:insert name="body" />
</body>
</html>
Note that the doctype (and xml) declaration is unnecessary in template definition files (the ones using <ui:composition>). Just remove them.
See also:
*
*How to include another XHTML in XHTML using JSF 2.0 Facelets?
*Facelets 1.x docbook
A: You must remember one thing, that everything outside ui:compostion tags is simply cut out, so the DOCTYPE declaration in your case is simply ignored.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to recover from I2C bus collision BCLIF? I posted this a couple of days ago on the Microchip Forum (here) but the only response has been crickets.
The I2C code below works most of the time but occasionally on power-up there is a bus collision (BCLIF) and the I2C module is unable to recover after the BCLIF.
The I2C lines are pulled up by 3.3K ohms.
Using REALICE and breakpoints I can see that i2c_write() resets BCLIF and returns FALSE when BCLIF is set.
I have used a scope to verify that the I2C bus has flat-lined.
Re-initializing the PIC18F25K20 I2C module (see init_i2c() below) when i2c_write() returns FALSE does not help.
The PIC18F25K20 I2C is connected to a single slave device (MCP4018 I2C Digital POT).
I have used this same code on previous PIC18 projects without issue so I replaced the MCP4018 suspecting a bad part but see no difference.
Is there a way to reset the PIC18F25K20 I2C module when it is locked up?
void init_i2c(I2C_BAUD_RATE baud_rate, float freq_mhz)
{
UINT32 freq_cycle;
/* Reset i2c */
SSPCON1 = 0;
SSPCON2 = 0;
PIR2bits.BCLIF = 0;
/* Set baud rate */
/* SSPADD = ((Fosc/4) / Fscl) - 1 */
freq_cycle = (UINT32) ((freq_mhz * 1e6) / 4.0);
if (baud_rate == I2C_1_MHZ)
{
SSPADD = (UINT8) ((freq_cycle / 1000000L) - 1);
SSPSTATbits.SMP = 1; /* disable slew rate for 1MHz operation */
}
else if (baud_rate == I2C_400_KHZ)
{
SSPADD = (UINT8) ((freq_cycle / 400000L) - 1);
SSPSTATbits.SMP = 0; /* enable slew rate for 400kHz operation */
}
else /* default to 100 kHz case */
{
SSPADD = (UINT8) ((freq_cycle / 100000L) - 1);
SSPSTATbits.SMP = 1; /* disable slew rate for 1MHz operation */
}
/* Set to Master Mode */
SSPCON1bits.SSPM3 = 1;
SSPCON1bits.SSPM2 = 0;
SSPCON1bits.SSPM1 = 0;
SSPCON1bits.SSPM0 = 0;
/* Enable i2c */
SSPCON1bits.SSPEN = 1;
}
BOOL i2c_write(UINT8 addr, const void *reg, UINT16 reg_size, const void *data, UINT16 data_size)
{
UINT16 i;
const UINT8 *data_ptr, *reg_ptr;
/* convert void ptr to UINT8 ptr */
reg_ptr = (const UINT8 *) reg;
data_ptr = (const UINT8 *) data;
/* check to make sure i2c bus is idle */
while ( ( SSPCON2 & 0x1F ) | ( SSPSTATbits.R_W ) )
;
/* initiate Start condition and wait until it's done */
SSPCON2bits.SEN = 1;
while (SSPCON2bits.SEN)
;
/* check for bus collision */
if (PIR2bits.BCLIF)
{
PIR2bits.BCLIF = 0;
return(FALSE);
}
/* format address with write bit (clear last bit to indicate write) */
addr <<= 1;
addr &= 0xFE;
/* send out address */
if (!write_byte(addr))
return(FALSE);
/* send out register/cmd bytes */
for (i = 0; i < reg_size; i++)
{
if (!write_byte(reg_ptr))
return(FALSE);
}
/* send out data bytes */
for (i = 0; i < data_size; i++)
{
if (!write_byte(data_ptr))
return(FALSE);
}
/* initiate Stop condition and wait until it's done */
SSPCON2bits.PEN = 1;
while(SSPCON2bits.PEN)
;
/* check for bus collision */
if (PIR2bits.BCLIF)
{
PIR2bits.BCLIF = 0;
return(FALSE);
}
return(TRUE);
}
BOOL write_byte(UINT8 byte)
{
/* send out byte */
SSPBUF = byte;
if (SSPCON1bits.WCOL) /* check for collision */
{
return(FALSE);
}
else
{
while(SSPSTATbits.BF) /* wait for byte to be shifted out */
;
}
/* check to make sure i2c bus is idle before continuing */
while ( ( SSPCON2 & 0x1F ) | ( SSPSTATbits.R_W ) )
;
/* check to make sure received ACK */
if (SSPCON2bits.ACKSTAT)
return(FALSE);
return(TRUE);
}
A: This same bug seems to ocur on PIC18F26K20/SS (Revision B3) too, also needs to be added to it's errata.
A: I don't know your specifics but I ran into a problem once where the microcontroller was coming out of reset way early (much before Vdd stabilized on the I2C bus). So the uController started to read / write data before the target could function properly causing all sort of I2C operational issues.
A: This Errata needs to be added to PIC18F25K20 Errata.
PIC18F2455/2550/4455/4550 Rev. A3 Silicon Errata
17 Module: MSSP
It has been observed that following a Power-on Reset, I2C mode may not
initialize properly by just configuring the SCL and SDA pins as either
inputs or outputs. This has only been seen in a few unique system
environments.
A test of a statistically significant sample of
preproduction systems, across the voltage and current range of the
application's power supply, should indicate if a system is susceptible
to this issue.
Work around
Before configuring the module for I2C
operation:
*
*Configure the SCL and SDA pins as outputs by clearing their
corresponding TRIS bits.
*Force SCL and SDA low by clearing the corresponding LAT bits.
*While keeping the LAT bits clear, configure SCL and SDA as inputs
by setting their TRIS bits.
Once this is done, use the SSPCON1 and
SSPCON2 registers to configure the proper I2C mode as before.
A: This errata also helped me with I2C stuck on PIC18F27J53 (but in my case there was also needed unlock of I2C bus blocked by SGP30 device, code example here: https://github.com/esp8266/Arduino/issues/1025#issuecomment-158667929)
I finally decided to implement routine performing restart-unstuck-restart called when start condition fails (code fragment of my I2C stack):
eI2Cerr i2c_do_RUR(void) {
//performs restart-unstuck-restart
eI2Cerr eRetVal;
eRetVal = i2c_do_restart();
if (eRetVal == I2C_ERR_TIMEOUT_RSEN_COLLISION) {
i2c_unstuck(true); //true=performs also I2C bus unlock
eRetVal = i2c_do_restart();
}
return(eRetVal);
}
I2C seems to be stable and working well now.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Non-POD datatypes allowed in firstprivate of OpenMP parallel section? Can we specify a std::vector object in the firstprivate clause of a openmp task pragma?
Is is possible to make a vector object firstprivate?
It compiles and runs correctly... It is always threadsafe?
A: Yes you can
*
*The firstprivate variable is initialized once per thread
*the firstprivate object is constructed by calling its copy constructor with the master thread's copy of the variable as its argument
So basically as long as
*
*the copy constructor and assignment operator for the class are accessible
*they provide deep copy (value) semantics
Note that the STL containers satisfy these criteria but you may alter the semantics by doing a container of (non-shared) pointer elements, etc.
You're good to go
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Break out parts of a LINQ2SQL Expression I have this piece of LINQ code
private static void Original()
{
using (var context = new AdventureWorksContext())
{
var result =
from product in context.Products
from workorder in product.WorkOrders
select new
{
productName = product.Name,
order = workorder,
};
var result2 =
from item in result
where item.order.WorkOrderRoutings.Count() == 1
select item.productName;
foreach (var item in result2.Take(10))
{
Console.WriteLine(item);
}
}
}
I want to break out the item.order.WorkOrderRoutings.Count() part and replace with something else, like item.order.OrderQty based on some input parameter.
My first attempt:
private static Func<WorkOrder, int> GetRoutingCountFunc()
{
return workOrder => workOrder.WorkOrderRoutings.Count();
}
private static void RefactoredFunc()
{
using (var context = new AdventureWorksContext())
{
var result =
from product in context.Products
from workorder in product.WorkOrders
select new
{
productName = product.Name,
order = workorder,
};
var result2 =
from item in result
where GetRoutingCountFunc()(item.order) == 1
select item.productName;
foreach (var item in result2.Take(10))
{
Console.WriteLine(item);
}
}
}
of course fails a runtime with an exception
Method 'System.Object DynamicInvoke(System.Object[])' has no supported translation to SQL.
So I figured out I need to put in some kind of Expression. The most reasonable I can figure out is
private static Expression<Func<WorkOrder, int>> GetRoutingCountExpression()
{
return workOrder => workOrder.WorkOrderRoutings.Count();
}
private static void RefactoredExpression()
{
using (var context = new AdventureWorksContext())
{
var result =
from product in context.Products
from workorder in product.WorkOrders
select new
{
productName = product.Name,
order = workorder,
};
var result2 =
from item in result
where GetRoutingCountExpression()(item.order) == 0
select item.productName;
foreach (var item in result2.Take(10))
{
Console.WriteLine(item);
}
}
}
But that gives a compile time error: "Method name expected" on the line where GetRoutingCountExpression()(item.order) == 0.
If it wasn't for the anonymous type I could have created a method returning Expression<Func<"anonType", bool>> and use that as the where argument.
How do I break out parts of the LINQ-expression?
A: The easiest thing to do is to create methods that transform IQueryable<T> instances. For instance a method like this:
private static IQueryable<WorkOrder> FilterByRoutingCount(
IQueryable<WorkOrder> orders, int count)
{
return
from workOrder in orders,
where workOrder.WorkOrderRoutings.Count() == count)
select workOrder;
}
You can use this method like this:
var workorders =
from product in context.Products
from workorder in product.WorkOrders
select workorder;
var result2 =
from workorder in FilterByRoutingCount(workorders, 1)
select workorder.Product.productName;
A: You could simply do like:
private static int GetRoutingCount(WorkOrder w)
{
return w.WorkOrderRoutings.Count();
}
If we assume that item.order is of type WorkOrder, then you could use it like:
var result2 =
from item in result
where GetRoutingCount(item.order) == 0
select item.productName;
Edit
This should do the job:
Expression<Func<Tuple<string, Order>, bool>> routingCountZero = x =>
x.Item2.Roundings.Count == 0;
You'll have to use lambda expressions:
var result2 = result.Where(routingCountZero).Select(x => x.Item1);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Variable height DIV with minimum distance from top & bottom of the viewport Okay, I have a div that's supposed to be a widget for controlling stuff in other divs.
It is to be positioned above (as in z-index) everything else and must be a specific distance from the top of the viewport (say, 10em). Since the page may not exceed the viewport it could either be position: fixed or position: absolute. Now, I want it to be of viariable height (depending on content) but also have a min-height and never be closer than, say, 5 em to the bottom of the viewport.
What I would like to write is:
.myDiv {
position: absolute;
top: 10em;
min-height: 8em;
max-height: 100% - 15em; //which doesn't work
overflow: auto;
}
Is something like that at all possible using css only?
A: It's apparently not possible using css alone. I'm using javascript now. Here's the code:
//within a prototype.js environment
var innerHeight = (typeof window.innerHeight === 'undefined') ? document.documentElement.clientHeight : window.innerHeight;
var emSize = parseFloat($(document.body).getStyle('font-size'));
someElement.style['maxHeight'] = (innerHeight - (14 * emSize)).toString() + 'px';
A: Although it is late, but to help other people searching for this, you can use calc() function of css3. It can be used like below -
.myDiv {
position: absolute;
top: 10em;
min-height: 8em;
max-height: calc(100% - 15em);
overflow: auto;
}
This function is not supported on older browsers and we can have any of the following mathematical operators inside it - + - * /
A: Why don't you simply use max-height:98%; ?
This way you'll always have some space at the bottom (but not a fixed space).
I think the only way to have it a fixed space would be to use javascript to get the viewport height and set your widget max-height accordingly.
A: I think you are over complicating this. Why not try this. It just adds a little padding at the top, or if you want you can use margin-top depending on what your other divs are doing.
.myDiv {
postion: absolut;
padding-top: 10em;
min-height: 100px;
max-height: 98%;
overflow: auto;
A: Timm,
Firstly, I'm not sure why you are using em, but whatever works for you i guess.
You are pretty much there, here's the code i used to do what you want, the only thing is that instead of a fixed distence from the btm of the viewport, I used a %. I think it behaves the way you are seeking.
`.myDiv {
position:absolute;
color:#fff;
background:#000;
top:20px;
width:150px;
min-height: 100px;
max-height: 90%;
overflow:auto;
}`
`<div class="myDiv">
content<br>content<br>content<br>content<br>
content<br>content<br>content<br>content<br>
content<br>content<br>content<br>content<br>
content<br>content<br>content<br>content<br>
content<br>content<br>content<br>content<br>
content<br>content<br>content<br>content<br>
content<br>content<br>content<br>content<br>
content<br>content<br>content<br>content<br>
</div>`
i hope this is what you're looking for!
check it out here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Protovis Treemap - Show labels on hover over I have a treemap that I've created. Now I'm trying to get the hover over to work properly. I would like the text for each treemap.leaf to only appear when the user hovers over that particular leaf.
I've tried to follow this example to no avail
http://mbostock.github.com/protovis/docs/interaction.html
The code I have so far is as follows:
var json = {
"sectors":{
"electronics": { "Sony": 85, "AMD": 70, "Techtronics": 20, "Apple": 220, "Microsoft": 340},
"automotive": {"Chevy": 43, "Audi":120, "BMW": 200}},
"ids":{"Sony":72833,"AMD":582926,"Techtronics":839261, "Apple":822463, "Microsoft":242512, "Chevy":627363, "Audi":524362,"BMW":25143}
};
var tree = json.sectors;
var ids = json.ids;
var nodes = pv.dom(tree).root("tree").nodes();
color = pv.Colors.category10().by(function(d){return d.parentNode.nodeName});
var vis = new pv.Panel()
.width(400)
.height(400)
.canvas("test");
var treemap = vis.add(pv.Layout.Treemap)
.nodes(nodes)
.round(true);
treemap.leaf.add(pv.Panel)
.def("active", false)
.fillStyle(function(d) d.active ? "lightcoral" : color(d))
.strokeStyle("#fff")
.lineWidth(1)
.antialias(false)
.cursor("pointer")
.event("mouseover", function(d) { return this.active(true)});
treemap.label.add(pv.Label)
.visible(function() {return this.parent.children[0].active()})
.textStyle(function(d) {return pv.rgb(0, 0, 0, 1)});
vis.render();
A: There are a couple of issues here:
*
*When you use the .event() method, and the function you pass in returns an instance of pv.Mark, Protovis will re-render the mark and its children. (The documentation is pretty opaque about the requirement that you return the mark you want to re-render.)
*Within the Treemap layout, labels are not the children of the nodes - they're a separate group of children of the layout. So when you update a node, you won't get the corresponding label to re-render.
*You have a typo in the line:
.fillStyle(function(d) d.active ? "lightcoral" : color(d))
d is the data, not the instance. It should be:
.fillStyle(function() this.active() ? "lightcoral" : color(d))
But as noted above, this still won't update the label (and while I didn't play with this too much, just correcting this line seems to highlight all of the nodes, not just the one you're over).
So to fix all this, you want to set the active def on treemap, not on the node. Instead of just using true/false, you can set the index of the active node, and then use the same index to refer to the label:
var treemap = vis.add(pv.Layout.Treemap)
.nodes(nodes)
.round(true)
// define the active node on the layout
.def("active", -1);
treemap.leaf.add(pv.Panel)
.fillStyle(function(d) {
return treemap.active() == this.index ? "lightcoral" : color(d)
})
// ...
.event("mouseover", function() {
return treemap.active(this.index);
})
.event("mouseout", function() {
return treemap.active(-1);
});
treemap.label.add(pv.Label)
.visible(function() {
return treemap.active() == this.index;
});
Working jsFiddle here.
The downside here is that you're re-rendering the entire treemap each time. I think there's probably a way to only re-render the specific node and label, but it would be more complex, so if the performance doesn't seem to be an issue, I wouldn't bother.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MySQL - Group By, Max, Inner Join - issue Having trouble with a SQL in MySQL. Not sure the correct was to bring back all of the Awards my Users have won... but only the highest AwardLevel of the Award they have won. The relation ship is as follows:
A User can win many AwardLevel(s). Each AwardLevel is tied to a category called an Award. AwardLevels have a difficulty rating (1, 2, or 3)
This is similar to Stackoverflow's Badges and passing through a Bronze, Silver and Gold type of the Award.
I'm trying to bring back all the Awards for a User but filtered to the Max(difficulty) rating. For example, for a user to get to Level 3 (difficulty = 3) they must first earn the difficulty = 1 and then difficulty = 2. I don't want to show all three levels with my query just the highest (MAX). The problem with my current query is the GROUP BY seems to grab the first record it finds for the Award. Which sometimes is not the one with the difficulty = 3. Not sure if I should be putting the MAX expression somewhere else in the query.
UPDATED QUERY:
SELECT a.*, MAX(awlev.difficulty)
FROM Award AS a
INNER JOIN AwardLevel AS awlev ON awlev.id = a.level_id
WHERE a.user_id = 3 -- just a sample user_id
GROUP BY awlev.category_id
TABLE SETUP:
-- Note: I had forgotten the table relating Users
-- to won AwardLevels in this table setup I call it UserAwardLevels
CREATE TABLE Users (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
fullname VARCHAR(100)
);
CREATE TABLE AwardLevels (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
levelname VARCHAR(100),
difficulty INT
);
CREATE TABLE Awards (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
awardname VARCHAR(100)
);
CREATE TABLE UserAwardLevels (
user_id INT,
awardlevel_id INT
);
CREATE TABLE AwardLevels (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
levelname VARCHAR(100),
difficulty INT
);
A: If I understand what you want, in Mysql it is a little clumsy because windowing functions are not available. However, you can try
SELECT a.* /* put desired columns in */
FROM AwardLevel as awlev JOIN Award AS a
ON awlev2.id = a2.level_id
JOIN
SELECT (a2.user_id, MAX(awlev2.difficulty) AS maxdifficulty
FROM Award AS a2 INNER JOIN AwardLevel2 AS awlev2 ON awlev2.id = a2.level_id
GROUP BY a2.user_id, awlev2.category_id) AS subquery
ON a.user_id = subquery.user_id AND awlev.difficulty = maxdifficulty
WHERE a.user_id = 999; /* whatever id */
The optimizer will probably improve this, and I am not sure if the join of awlev and a is necessary without seeing the schema.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Event handling in classes I'm completely confused about the event handling. I read some articles about it but after it I just get confused to write and use them in my classes.
This is my class i. e.:
Public Class Test
Public Event playedEvent()
Public Sub playTimer()
RaiseEvent playedEvent()
End Sub
End Class
Usage:
Friend WithEvents t as Test
Private Sub AnEvent() Handles t.playedEvent()
'Do some stuff
End Sub
I dont have any argument passing. But I want to know how should I do it too. And I wanted to know if each instance of the Test class, run this event separately I mean each instance by themselves, This event AnEvent() will occur? Cuz I have lots of instances from my class.
Thanks.
A: Here's an example:
Public Event OnDisplayViewModeChange(ByVal sender As Object, ByVal displayMode As DisplayViewMode)
Public Sub UpdateDisplayMode(ByVal displayMode As DisplayViewMode)
DataViewMultiView.ActiveViewIndex = Convert.ToInt32(displayMode)
RaiseEvent OnDisplayViewModeChange(Me, displayMode)
End Sub
A: Every instance of class Test will have it's own event and you can handle them separately. If you e.g. want to add the instance of Test as parameter to the event, you have to change the event declaration in the following way:
Public Event playedEvent(t as Test)
Then you can raise it:
RaiseEvent playedEvent(Me)
and handle it:
Private Sub AnEvent(t as Test) Handles t.playedEvent()
't is the actual instance of Test
End Sub
Here are more informations: http://msdn.microsoft.com/en-us/library/wkzf914z.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problem with tapestry5 syntax checking in Eclipse 3.7 on OSX 10.5.8 I've been working with Tapestry5 in Eclipse 3.7 for a week or so, and can't get syntax checking to work correctly on OSX. I am using Eclipse Java EE IDE for Web Developers.
I found this link that explains what to do:
http://wiki.apache.org/tapestry/Tapestry5JSPEditorEclipse
This works perfectly in Eclipse 3.7 on Windows Vista Ultimate (my home workstation). However on OSX (my laptop), the hilighting itself works, yet Eclipse tells me there are errors in the code.
Here's an image of what it looks like:
screenshot
Eclipse tells me the following:
*
*The function message:greeting is undefined
*javax.servlet.jsp.JspException cannot be resolved to a type
*javax.servlet.jsp.PageContext cannot be resolved to a type
Since I am using Eclipse EE for Web Development, I would have thought I have the complete javax library. Naturally, I ran mvn eclipse:eclipse on the project to download all required libraries.
I'm at a loss for what I'm doing wrong...the Windows setup was effortless!
A: I resolved this last night, it turns out it was just a hiccup with the Eclipse project. After deleting the project (and contents on disk) and checking it out again, running mvn eclipse:eclipse, everything was good.
I love Eclipse, but some times you have to deal with issues like this...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Populate SQLite from csv I am trying to write a program. On of the funktions of the program is to be able to import data form a csv file to a sqlite database.
I have made this code so fare but it is not working properly. My problem is that it will only save the last line of my csv file in the database. What am i missing?
Here are the code
package com.android.FAC;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class Importcsv extends Activity
{
DbAdapter DbHelper;
String notification = "Concats imported!";
TextView tView;
String first;
String last;
String phone;
String mphone;
String room;
String initial;
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.importcsv);
DbHelper = new DbAdapter(this);
DbHelper.open();
tView = (TextView) findViewById(R.id.textView1);
Button b2 = (Button) findViewById(R.id.btnClick2);
Button b3 = (Button) findViewById(R.id.btnClick3);
Button b4 = (Button) findViewById(R.id.btnClick4);
b2.setOnClickListener(new TextView.OnClickListener() {
public void onClick(View v) {
try {
readfromcsv();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
b3.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(Importcsv.this, MainActivity.class);
Importcsv.this.startActivity(i);
}
});
b4.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
int n = 0;
while(n<30)
{
DbHelper.deleteContact(n);
n++;
}
}
});
}
public void readfromcsv() throws IOException
{
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"csvtest.csv");
BufferedReader in = new BufferedReader(new FileReader(file));
String reader = "";
while ((reader = in.readLine()) != null)
{
String[] RowData = reader.split(",");
first = RowData[0];
last = RowData[1];
phone = RowData[2];
mphone = RowData[3];
room = RowData[4];
initial = RowData[5];
}
DbHelper.createContact(first, last, phone, mphone, room, initial);
in.close();
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, notification, duration);
toast.show();
}
}
Thanks Peter
A: Presumably this line:
DbHelper.createContact(first, last, phone, mphone, room, initial);
belongs inside the while loop.
A: Change your while loop as follows:
while ((reader = in.readLine()) != null)
{
String[] RowData = reader.split(",");
first = RowData[0];
last = RowData[1];
phone = RowData[2];
mphone = RowData[3];
room = RowData[4];
initial = RowData[5];
DbHelper.createContact(first, last, phone, mphone, room, initial);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Help with css targeting IT should be something easy, but still I cant target it. What I have:
#navigation li a:hover .menu-description {
color: #000000;
}
What I want to do whenever user goes on #navigation li a class .menu-description should change color to black. How to target this? Maybe, any links on how to target such types of css?
Thanks for your help.
A: Impossible to say without seeing your HTML. Based on what you have, the HTML to match would have to be something like this:
<[tag] id="navigation">
<ul/ol>
<li>
<a>
<[tag] class="menu-description">
</[tag]>
</a>
</li>
</ul>
</[tag]>
A: #navigation li a.menu-description:hover {
color: #000000;
}
hover is wrong.
A: #navigation li a.menu-description:hover {
color: #000000;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Different ways of compiling a ocaml code with external libraries I have installed some libraries, and am trying to compile a code.
1) ocamlc -I /usr/lib -I /usr/local/lib/ocaml/3.11.2/apron -I /usr/local/lib/ocaml/3.11.2/gmp -c mlexample2.ml generates well mlexample2.cmi and mlexample2.cmo
2) ocamlopt -I /usr/lib -I /usr/local/lib/ocaml/3.11.2/apron -I /usr/local/lib/ocaml/3.11.2/gmp -o mlexample2.opt generates well mlexample2.cmx
3) However, If I follow the native-code compilation of this page:
ocamlopt -I /usr/lib -I /usr/local/lib/ocaml/3.11.2/apron -I /usr/local/lib/ocaml/3.11.2/gmp -o mlexample2.opt \ bigarray.cmxa gmp.cmxa apron.cmxa boxMPFR.cmxa polkaMPQ.cmxa mlexample2.ml returns File "mlexample2.ml", line 1, characters 0-1: Error: Cannot find file bigarray.cmxa, where usr/lib represents $APRON/lib in the doc. But big.array.cmxa is effectively in /usr/lib/ocaml/bigarray.cmxa. By the way, this command does generate .cmi, .cmx and .o.
So my questions are:
How could I progress from .cmi and .cmo of 1)?
How could I progress from .cmx of 2)
What can I do with the error in 3)
Could anyone help? Thank you very much!
Edit1: 2) should be: ocamlopt -I /usr/lib -I /usr/local/lib/ocaml/3.11.2/apron -I /usr/local/lib/ocaml/3.11.2/gmp -c mlexample2.ml generates .cmi, .cmx and .o.
A: From your other questions, it seems like you got some sample lines to compile and just blindly walking though without understanding the compile options.
1) You're compile line has the -c option. This option does not link, thus it allows someone to compile an individual module and link them later. This is helpful to allow the project to be built in pieces and updated in pieces for quicker final compilation. So, the -c option passed to ocamlc produces your cmi and cmo, byte-code complied module.
2) You are missing something here in your sample compile line --it doesn't mention anything regarding to produce an additional file. I'm going to assume that you also use the -c option. This is because a .cmx is also a compiled module, but natively compiled via ocamlopt.
3) This should be a pretty obvious compilation error to fix. Where in your included directories does bigarry.cmxa reside? None of them. You've said it yourself that it is in /usr/lib/ocaml/, a directory you did not include! The directories do not search recursively, and you've experienced that before in other questions.
I strongly suggest you read the manual on compilation. This documentation you're wading through is correct in how to compile, but you've set your environment up in a different way and discerning the differences is going to be frustrating until you get a handle on what those commands are actually doing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iPhone browser re-sizes form element placeholder font-size The problem I am having IS NOT with text on my webpage, nevermind "is it inside a <p> tag, or make sure it's in a <div> and -webkit-text-size-adjust: none; or 100%; does not fix this problem.
What I'm talking about is the placeholder values that display inside a text field are being re-sized by the iPhone browser and this is in turn re-sizing the height of each text field and in turn throwing off the alignment of the form fields to their backgrounds.
Link to Problem (Visit with iphone to see the problem, obviously)
A: The problem was not the font size, but rather the input boxes themselves.
The iPhone browser was adding a padding to them, so this was the fix:
`input{padding:1px 0;}`
Thanks!
A: Looking at your source, it looks like you may be trying to use
<input type="blah" placeholder="text">
but you do not affect the placeholder style in these kinds of tags. Instead, you should use something like
input::-webkit-input-placeholder { ...whatever here... }
to affect styling.
Check out this link on styling placeholders in various browsers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: WCF wsHttpBinding with certificate message security I am trying to create client and service applications with Message security with Certificate. But I have some errors all the time and can't make it work. Could somebody suggest what is wrong with my configuration files?
This is the service configuration:
<system.serviceModel>
<services>
<service name="SecuredCommunication.Service1" behaviorConfiguration="securedBehavior">
<endpoint address="test" binding="wsHttpBinding" bindingName="test" name="fasds" bindingConfiguration="securedWsBinding" contract="SecuredCommunication.IService1" >
</endpoint>
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="securedWsBinding">
<security mode="Message">
<message clientCredentialType="Certificate"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="securedBehavior">
<serviceMetadata httpGetBinding="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
<serviceCredentials>
<serviceCertificate findValue="wcftest.pvt" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName"/>
<clientCertificate>
<authentication certificateValidationMode="PeerTrust"/>
</clientCertificate>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
and this is the test client configuration
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior>
<clientCredentials>
<clientCertificate findValue="wcftest.pvt" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName"/>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<wsHttpBinding>
<binding>
<security mode="Message">
<message clientCredentialType="Certificate"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://wcftest.pvt/SecuredCommunication/Service1.svc" binding="wsHttpBinding" contract="SecuredCommunication.IService1">
</endpoint>
</client>
the current exception I have is:
System.ServiceModel.ServiceActivationException: The requested service, 'http://wcftest.pvt/SecuredCommunication/Service1.svc' could not be activated. See the server's diagnostic trace logs for more information.
For me configuration looks ok, I created it using some manuals from MSDN, so I can't understand what is wrong.
I installed certificate using makecert.exe tool like this
makecert.exe MakeCert -pe -ss My -sr LocalMachine -a sha1 -sky exchange -n CN=wcftest.pvt
Thanks,
Alexander.
A: In the service configuration, replace
<serviceMetadata httpGetBinding="true"/>
by
<serviceMetadata httpsGetBinding="true"/>
This matches the secure channel configuration applied in the bindings.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Redis / RabbitMQ - Pub / Sub - Performances I wrote a little test for a simple scenario:
One publisher and one subscriber
Publisher send 1000000 messages
Subscriber receive the 1000000 messages
First test with RabbitMQ, fanout Exchange, RabbitMq node type Ram : 320 seconds
Second test with Redis, basic pub/Sub : 24 seconds
Am i missing something? Why a such difference ? Is this a configuration problem or something?
First scenario: one node.js process for the subscriber, one for the publisher, each one, one connection to rabbitmq with amqp node module.
Second scénario: one node.js process for the subscriber, one for the publisher, each one got one connection to redis.
Any help is welcom to understand... I can share the code if needed.
i'm pretty new to all of this.
What i need, is a high performances pub / sub messaging system. I'd like to have clustering capabilities.
To run my test, i just launch the rabbitMq server (default configuration) and i use the following
Publisher.js
var sys = require('sys');
var amqp = require('amqp');
var nb_messages = process.argv[2];
var connection = amqp.createConnection({url: 'amqp://guest:guest@localhost:5672'});
connection.addListener('ready', function () {
exchangeName = 'myexchange';
var start = end = null;
var exchange = connection.exchange(exchangeName, {type: 'fanout'}, function(exchange){
start = (new Date()).getTime();
for(i=1; i <= nb_messages; i++){
if (i%1000 == 0){
console.log("x");
}
exchange.publish("", "hello");
}
end = (new Date()).getTime();
console.log("Publishing duration: "+((end-start)/1000)+" sec");
process.exit(0);
});
});
Subscriber.js
var sys = require('sys');
var amqp = require('amqp');
var nb_messages = process.argv[2];
var connection = amqp.createConnection({url: 'amqp://guest:guest@localhost:5672'});
connection.addListener('ready', function () {
exchangeName = 'myexchange';
queueName = 'myqueue'+Math.random();
var queue = connection.queue(queueName, function (queue) {
queue.bind(exchangeName, "");
queue.start = false;
queue.nb_messages = 0;
queue.subscribe(function (message) {
if (!queue.start){
queue.start = (new Date()).getTime();
}
queue.nb_messages++;
if (queue.nb_messages % 1000 == 0){
console.log('+');
}
if (queue.nb_messages >= nb_messages){
queue.end = (new Date()).getTime();
console.log("Ending at "+queue.end);
console.log("Receive duration: "+((queue.end - queue.start)/1000));
process.exit(0);
}
});
});
});
A: Check to ensure that:
*
*Your RabbitMQ queue is not configured as persistent (since that would require disk writes for each message)
*Your prefetch count on the subscriber side is 0
*You are not using transactions or publisher confirms
There are other things which could be tuned, but without knowing the details of your test it's hard to guess. I would just make sure that you are comparing "apples to apples".
Most messaging products can be made to go as fast as humanly possible at the expense of various guarantees (like delivery assurance, etc) so make sure you understand your application's requirements first. If your only requirement is for data to get shoveled from point A to point B and you can tolerate the loss of some messages, pretty much every messaging system out there can do that, and do it well. The harder part is figuring out what you need beyond raw speed, and tuning to meet those requirements as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Is it defined to provide an empty range to C++ standard algorithms? Following on from my previous question, can we prove that the standard allows us to pass an empty range to a standard algorithm?
Paragraph 24.1/7 defines an "empty range" as the range [i,i) (where i is valid), and i would appear to be "reachable" from itself, but I'm not sure that this qualifies as a proof.
In particular, we run into trouble when looking at the sorting functions. For example, std::sort:
Complexity: O(N log(N)) (where N == last - first) comparisons
Since log(0) is generally considered to be undefined, and I don't know what 0*undefined is, could there be a problem here?
(Yes, ok, I'm being a bit pedantic. Of course no self-respecting stdlib implementation would cause a practical problem with an empty range passed to std::sort. But I'm wondering whether there's a potential hole in the standard wording here.)
A: I don't seem much room for question. In §24.1/6 we're told:
An iterator j is called reachable from an iterator i if and only if there is a finite sequence of applications of the expression ++i that makes i == j.
and in $24.1/7:
Range [i, j) is valid if and only if j is reachable from i.
Since 0 is finite, [i, i) is a valid range. §24.1/7 goes on to say:
The result of the application of functions in the library to invalid ranges is
undefined.
That doesn't go quite so far as to say that a valid range guarantees defined results (reasonable, since there are other requirements, such as on the comparison function) but certainly seems to imply that a range being empty, in itself, should not lead to UB or anything like that. In particular, however, the standard makes an empty range just another valid range; there's no real differentiation between empty and non-empty valid ranges, so what applies to a non-empty valid range applies equally well to an empty valid range.
A: Apart from the relevant answer given by @bdonlan, note also that f(n) = n * log(n) does have a well-defined limit as n goes to zero, namely 0. This is because the logarithm diverges more slowly than any polynomial, in particular, slower than n. So all is well :-)
A: Big-O notation is defined in terms of the limit of the function. An algorithm with actual running time g(N) is O(f(N)) if and only if lim N→∞ g(N)/f(N) is a non-negative real number g(N)/f(N) is less than some positive real number C for all values N greater than some constant k (the exact values of C and k are immaterial; you just have to be able to find any C and k that makes this true). (thanks for the correction, Jesse!)
You'll note that the actual number of elements is not relevant in big-O analysis. Big-O analysis says nothing about the behavior of the algorithm for small numbers of elements; therefore, it does not matter if f(N) is defined at N=0. More importantly, the actual runtime behavior is controlled by a different function g(N), which may well be defined at N=0 even if f(0) is undefined.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Trigger not letting me DELETE in PostgreSQL I am trying to capture data changes on a table and am executing the following trigger function AFTER INSERT OR UPDATE as well as BEFORE UPDATE OR DELETE:
CREATE OR REPLACE FUNCTION cdc_test_function()
RETURNS trigger AS
$BODY$
DECLARE op cdc_operation_enum;
BEGIN
op = TG_OP;
IF (TG_WHEN = 'BEFORE') THEN
IF (TG_OP = 'UPDATE') THEN
op = 'UPDATE_BEFORE';
END IF;
INSERT INTO cdc_test VALUES (DEFAULT, DEFAULT, op, DEFAULT, DEFAULT, OLD.*);
ELSE
IF (TG_OP = 'UPDATE') THEN
op = 'UPDATE_AFTER';
END IF;
INSERT INTO cdc_test VALUES (DEFAULT, DEFAULT, op, DEFAULT, DEFAULT, NEW.*);
END IF;
RETURN NEW;
END;
My change table (CDC_TEST) is capturing everything properly and I can both INSERT and UPDATE records just fine in my TEST table. However, when I try to DELETE, it records the DELETE entry perfectly in CDC_TEST, but the record remains in my TEST table. If I disable the trigger, then I can DELETE from TEST just fine. Here is the code I used to create my tables as well as the code for my enum:
CREATE TABLE test
(
test_id serial NOT NULL,
value text NOT NULL,
CONSTRAINT test_pkey PRIMARY KEY (test_id )
)
CREATE TABLE cdc_test
(
cdc_test_id bigserial NOT NULL,
cdc_timestamp timestamp with time zone DEFAULT now(),
cdc_opeation cdc_operation_enum,
cdc_user name DEFAULT "current_user"(),
cdc_transaction_id bigint DEFAULT txid_current(),
test_id integer,
value text,
CONSTRAINT cdc_test_pkey PRIMARY KEY (cdc_test_id )
)
CREATE TYPE cdc_operation_enum AS ENUM( 'DELETE', 'INSERT', 'UPDATE_BEFORE', 'UPDATE_AFTER', 'UPDATE' );
A: Return OLD when the trigger runs for a deletion, NEW for an update.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: FIPS validated algorithm to store passwords in a database? I am looking for a FIPS validated hash algorithm to store passwords in the database.
I did use the following code but I still get the error
This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms.
SHA1CryptoServiceProvider Testsha1 = new SHA1CryptoServiceProvider();
byte[] hashedBytes;
UTF8Encoding encoder = new UTF8Encoding();
hashed = Testsha1.ComputeHash(encoder.GetBytes(strPassword));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashed.Length; i++)
{
sbuilder.Append(hashed[i].ToString("x2"));
}
string Password = sb.ToString();
A: Plain SHA-1 should not be used to store passwords. PBKDF2 is a good choice. In .net you can use it with the Rfc2898DeriveBytes class. See https://security.stackexchange.com/questions/2131/reference-implementation-of-c-password-hashing-and-verification/2136#2136
You might need to change the underlying hash function to SHA-256. From what I remember SHA-1 isn't NIST approved.
A: Adding the following line in web.config under system.web section
<machineKey validationKey="AutoGenerate,IsolateApps" ecryptionKey="AutoGenerate,IsolateApps" validation="3DES" decryption="3DES"/>
solved my problem
A:
I am looking for a FIPS validated hash algorithm to store passwords in the database.
Use one of the hashes from the SHA-2 family. For example, SHA256.
Do not use a managed class - they are not FIPS validated. Instead, use SHA256CryptoServiceProvider and friends.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MySQL timestamp record being updated but affected rows remains 0 There are a few similar questions but I'll throw this in the mix.
Basically, I have a timestamp column (which is an int) and one of my updates is ONLY updating this timestamp column and sometimes it's a barely noticeable distance. For instance, it might change from 1316631442 to 1316631877. Not really much of a difference between the two.
So the record is being updated, I can check in phpMyAdmin before the query is run and then afterward and see the difference. However, I'm doing a var_dump() on the affected row count and it remains 0.
If I update another column at the same time to a different value then the affected rows are 1.
So what does it take to trigger the row as being affected? Even though it's being affected since the update is successful.
Also, I'm using the Laravel PHP framework and its query builder. Currently doing a bit of debugging in there to see if something may be off but so far all seems to be well.
EDIT: Sorry I had mistyped something above. When I completely change another column's value the affected rows is 1, not 0.
A: For those curious I resorted to using an INSERT INTO... ON DUPLICATE KEY UPDATE to achieve the desired result. I still couldn't figure out why MySQL wasn't reporting the record as being affected.
I also tried using PHPs mysql_query() and related functions to check the affected row but it didn't work like that also. Perhaps MySQL doesn't deem the change to be worthy of marking the record as affected.
A: I can replicate the issue with MySql 5.1 but not with Mysql 5.7.
In the earlier version
UPDATE `test`
SET
`time` = TIMESTAMPADD(MINUTE, 10, NOW())
WHERE
`id = 1
does update the timestamp but the message is that zero rows have been affected.
With the later version of MySql the same query gives me one row affected.
It seems to be a MySql bug that has been fixed.
Time to get the Server admin to update some stuff?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to attach aspnetdb.mdf to local instance of sql server 2008 R2 from asp.net? I added a Security Token Service project to my solution using the federation utility. I then added an aspnetdb.mdb file to my project for sqlmembershipprovider store.
When I view and test my connection in the Server Explorer my connection succeeds. However when I run the solution I get an error: 26, A network-related or instance-specific error occurred while establishing a connection to SQL Server.
What am I doing wrong? How can I solve this?
<add name="connectionstring"
connectionString="Data Source=.;AttachDbFilename='C:\ClaimsEnableWebsite\ClaimsEnableWebSite_STS\App_Data\ASPNETDB.MDF';Integrated Security=True;User Instance=False;Context Connection=False"
providerName="System.Data.SqlClient" />
Edit >> Answer:
Connections to SQL Server database files (.mdf) require SQL Server Express to be installed and running on the local computer.
A: As you've found out, on any "real" version of SQL Server, you cannot use the AttachDbFileName= approach - this is really only intended for development work using a SQL Server Express edition.
You can however use the ASP.NET SQL Server Registration Tool (aspnet_regsql) that's installed with your .NET framework into a folder something like C:\Windows\Microsoft.NET\Framework\v4.0.30319 (substitute your current .NET framework version, if needed) to create those tables in any SQL Server database of your choice.
See MSDN docs on the ASP.NET SQL Server registration tool for details.
A: • You must run aspnet_regsql.exe to generate the security database (default aspnetdb) if you are using ‘real’ SQL Server and not an Express version. You cannot generate it automatically from ASP.ET Website Administrator. Since the directory where the utility is located is n levels deep, I use a batch file:
"c:\windows\Microsoft.Net\Framework\v4.0.30319"\aspnet_regsql
• The full SQL Server does not allow you to put a database anywhere on the system by default. Instead, when you run aspnet_regsql, the aspnetdb.mdf database (or whatever name you give it), is generated in the default directory of Sql Server (under C\Program Files\Micrsofot SQL Server...\Data). That’s okay.
Note: If you want to use a local database in the App_Data directory of your web site, follow these steps.
1. Ensure that that database is not being used by any other application but a single instance of SQL Server Management Studio.
2. Expand the Databases node.
3. Right click on aspnetdb (or whatever you’ve called it) and select Tasks->Detatch. Note that the Message column should blank, indicating no open connections, or Detach will fail.
*
*Click OK to detach the database.
*In Windows Explorer, navigate to C”\Program Files\Micrsofot SQL Server...\Data and locate the aspnetdb.mdb and aspnetdb_log.ldf files.
*Cut (or copy) these files from the directory.
*In Windows Explorer, navigate to the directory where you want the new database located (the App_Data folder for the website, for example).
*Paste the database and the log file into this directory.
*In SQL Server, right-click on the Databases Node and select Attach.
*Click the Add button.
*Navigate to the directory where you copied the new database and select the mdf (database) file (aspnetdb.mdf, for example).
*If you want to use one database for security for all of your websites, you can leave the name the same. If you want different security databases for different web sites, change the name to a unique name.
*Click OK.
*Click OK.
*If you right-click on the Databases node and select Refresh, you should see the new security database in Sql Server Management Studio.
• Manually add the required code to the section of the Visual Studio project’s Web.config file. I have tried hundreds of different variations of this theme, but this seems to be the only one that works every time.
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime/>
<sessionState allowCustomSqlDatabase="true"
sqlConnectionString="Data Source=JAYSDELL\MSSQLSERVER2008R;
Initial Catalog=aspnetdb;
Integrated Security=True"/>
<pages controlRenderingCompatibilityVersion="4.0"/>
</system.web>
<connectionStrings>
<remove name="LocalSqlServer"/>
<add name="LocalSqlServer"
connectionString="Data Source=JAYSDELL\MSSQLSERVER2008R;
Initial Catalog=aspnetdb;
Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Obviously values for sqlConnectionString and Initial Catalog need to be tailored to the app.
Now when you go into WEBSET->ASP.NET Configuration->Security you should see the following.
SUCCESS!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Test if a javax.swing.JButton is pressed down I would like to check whether a certain javax.swing.JButton (regular push-button) is pressed down (before it was released). Is there any option at all to check whether a button is down?
The most trivial solution is to add a MouseListener that will respond to the mouse click and release events. But, this does not cover the case where the button was activated by the Enter key, or any other way. I don't want to disable activating the mouse by keyboards or other ways - I just want to know when is it pressed down without restricting it's behaviour.
I tried listening to all the different events, and the only two that do respond to button press are the ActionPreformed (ActionEvent) and the StateChanged (ChangedEvent) events. ActionPreformed is executed once per click, meaning only after the button was pressed and released, so it's not good. StateChanged is indeed invoked several times when I click a button, and several times when I release it. But, the event object only includes information about the source widget (the button) and no information about the state change itself. This prevents from distiguishing which of the events we want to catch.
Thanks in advance!
A: ButtonModel can do that, more here or here or maybe off-topic JMenuItem & ChangeListener by @kleopatra
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Question on bindable variables in AS3 I'm probably misusing bindable variables here, so please bear with me here while I try and explain what I'm trying to to.
I have a simple spark list where I allow people to select a background by clicking on one of the items. When a background is selected, I then save it to the SharedObject in order to use it when the user loads the application again later.
This list is populated by an ArrayCollection (binded variable) created as follows:
[Bindable] private var arrBG:ArrayCollection = new ArrayCollection();
This then gets populated the following way:
var objImage:Object;
var strSharedObjImage:String = sharedObj.sharedBackground.data.backgroundIndex;
// Background
objImage = new Object();
objImage.icon = ICONS_PATH + objImage.label;
objImage.label = "Titanium";
objImage.selected = (strSharedObjImage == objImage.fileName) ? true : false;
arrBG.addItem(objImage);
objImage = new Object();
objImage.icon = ICONS_PATH + objImage.fileName;
objImage.label = "Iron";
objImage.selected = (strSharedObjImage == objImage.label) ? true : false;
arrBG.addItem(objImage);
I then use it as the dataProvider on my spark list.
If you notice above, on my object I have a property called selected, which will get set to true, if the value of my shared object is the same as the value on the "label" property.
On the item renderer for my spark list, I have the following:
<s:ItemRenderer name="HorizontalListSkin"
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
autoDrawBackground="false"
creationComplete="initMenuSkin(event)"
>
<fx:Script>
<![CDATA[
protected function initMenuSkin(event:Event):void
{
iconImage.source = data.icon;
iconText.text = data.label;
// Check to see if the item we're displying is selected. If it is make it stand out
if(data.selected){
iconText.setStyle("color", "Green")
}
}
]]>
</fx:Script>
<s:VGroup x="10" y="10" width="50" height="50" buttonMode="true" horizontalAlign="center">
<s:Image id="iconImage" horizontalCenter="0"/>
<s:Label id="iconText" fontFamily="Verdana" fontSize="11" fontWeight="bold" horizontalCenter="0" showTruncationTip="false"/>
</s:VGroup>
</s:ItemRenderer>
So as you can see, I'm simply changing the colour of the font on my selected item.
When I load it up, I can see that the item I have previously selected is marked in green, and if I select a new item, I would like it to now be marked as green instead.
Obviously there's a big gap in here, since nowhere in my explanation above I mention updating my bindable variable so in theory it wold propagate to my spark list (being it a bindable variable I would of thought it would simultaneously update the item on my list(?)).
Well, I have tried doing it in a few different ways, and the debugger does "say" my array has been updated, however, my list isn't being updated at all, and will only bring another item marked in green if I close the screen and open again (when it all gets reloaded)
The whole logic described above to create a new background is contained within a function, so whenever I select an item from my list of backgrounds I was triggering my "loadBackgrounds" method again, which would apply all the logic to know which is the selected background, and because the variable is binded with my spark list I'd have hoped would update the list. Thing is, it doesn't.
What am I doing wrong here? Am I going totally bonkers and there's a much easier way of doing this but only I can't see it?
Any help here would be appreciated.
Thanks in advance
A: After you set the data ion the collection you need to refresh it.
arrBG.refresh();
[EDIT]
Ok I re-read your question.
I think I misunderstood what you were asking.
You want to know how to update the list so the item renderer will re-render the new list after you made changes to the data provider?
function newSelection( val:String ):void{
for each( var item:Object in arrBG ){
if( item.label == val ){
item.selected = true;
}else{
item.selected = false;
}
}
arrBG.refresh();
}
// use the commit properties on your renderer not the init
// commit properties will trigger whenever there is a dataprovider update/change
<s:ItemRenderer name="HorizontalListSkin"
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
autoDrawBackground="false"
>
<fx:Script>
<![CDATA[
override protected function commitProperties():void{
super.commitProperties();
iconImage.source = data.icon;
iconText.text = data.label;
// Check to see if the item we're displying is selected. If it is make it stand out
if(data.selected){
iconText.setStyle("color", "Green")
}
}
]]>
</fx:Script>
<s:VGroup x="10" y="10" width="50" height="50" buttonMode="true" horizontalAlign="center">
<s:Image id="iconImage" horizontalCenter="0"/>
<s:Label id="iconText" fontFamily="Verdana" fontSize="11" fontWeight="bold" horizontalCenter="0" showTruncationTip="false"/>
</s:VGroup>
</s:ItemRenderer>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Stop it from uploading .sass files? Is there a way to get Aptana Studio 3 to not upload specific file extensions, such as .sass for example?
Thanks!
A: If you already have the project set up with a remote server, you could right-click on a .sass file in the project and select Deploy > Cloak this file type.
You could also go to Preferences > Aptana Studio > Remote and add .sass to the list of file extensions to be ignored.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Two boolean variables in Java I would like to program in java two Boolean variables which are corelated in a way that one is allways false and one allways true. So if you set one to true the other one would automaticly change to false.
A: Use setters and getters to manage the logic for you.
class Foo{
private boolean _bool1;
private boolean _bool2;
public void setBool1(boolean value)
{
_bool1 = value;
_bool2 = !value;
}
public void setBool2(boolean value)
{
_bool2 = value;
_bool1 = !value;
}
public boolean getBool1() { return _bool1 ;}
public boolean getBool2() { return _bool2 ;}
}
A: use smart setters
class Blah {
private bool1 = true;
private bool2 = false;
setBool1(val) {
this.bool1 = val;
this.bool2 = !val;
}
setBool2(val) {
this.bool2 = val;
this.bool1 = !val;
}
// more setters/getters
}
note I'm not sure if you really need this. If the 2 booleans are always opposites, why not just have 1 bool and make decisions based on it, instead of making decisions based on 2 bools?
A: Don't use variables - use methods.
Before using variables
class Before {
boolean first;
boolean second;
boolean setFirst(boolean newValue) {
first = newValue;
second = !first;
}
boolean setSecond(boolean newValue) {
second = newValue;
first = !second;
}
}
make this better like so: use a single piece of data (which is what you really have) and use methods for the logic.
class After {
private boolean value;
boolean first() {
return value;
}
boolean second() {
return !value;
}
}
A: I suspect you want boolean rather than Boolean
I also suspect you only need one field, flag1 with a method
public boolean getFlag2() {
return !flag1;
}
A: public class Opposites {
protected boolean x = true;
protected boolean y = false;
public boolean getX() { return x; }
public boolean getY() { return y; }
public boolean toggle() { x=!x; y=!y; }
}
Opposites o = new Opposites();
o.getX(); // => true
o.getY(); // => false
o.toggle();
o.getX(); // => false
o.getY(); // => true
A: you can use only one boolean variable:
boolean flag = true;
/*
flag is true
!flag is false
*/
...
flag = false;
/*
flag is false
!flag is true
*/
A: Just get the opposite with !myVar instead of having two variables. This can be in a function if you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Compose and andThen methods I'm following the tutorial Pattern matching & functional composition on Scala compose and andThen methods. There's such an example:
scala> def addUmm(x: String) = x + " umm"
scala> def addAhem(x: String) = x + " ahem"
val ummThenAhem = addAhem(_).compose(addUmm(_))
When I try to use it I get an error:
<console>:7: error: missing parameter type for expanded function ((x$1) => addAhem(x$1).compose(((x$2) => addUmm(x$2))))
val ummThenAhem = addAhem(_).compose(addUmm(_))
^
<console>:7: error: missing parameter type for expanded function ((x$2) => addUmm(x$2))
val ummThenAhem = addAhem(_).compose(addUmm(_))
^
<console>:7: error: type mismatch;
found : java.lang.String
required: Int
val ummThenAhem = addAhem(_).compose(addUmm(_))
However, this works:
val ummThenAhem = addAhem _ compose addUmm _
or even
val ummThenAhem = addAhem _ compose addUmm
What's wrong with the code in the tutorial? Isn't the latter expression the same as the first one without parenthesis?
A: Well, this:
addUhum _
is an eta expansion. It converts methods into functions. On the other hand, this:
addUhum(_)
is an anonymous function. In fact, it is a partial function application, in that this parameter is not applied, and the whole thing converted into a function. It expands to:
x => addUhum(x)
The exact rules for expansion are a bit difficult to explain, but, basically, the function will "start" at the innermost expression delimiter. The exception is partial function applications, where the "x" is moved outside the function -- if _ is used in place of a parameter.
Anyway, this is how it expands:
val ummThenAhem = x => addAhem(x).compose(y => addUmm(y))
Alas, the type inferencer doesn't know the type of x or y. If you wish, you can see exactly what it tried using the parameter -Ytyper-debug.
A: From compose documentation:
Composes two instances of Function1 in a new Function1, with this
function applied last.
so you should write
scala> val ummThenAhem = (addAhem _).compose(addUmm _)
ummThenAhem: String => java.lang.String = <function1>
to treat addAhem and addUmm as partially applied functions (i.e function1)
scala> addAhem _
res0: String => java.lang.String = <function1>
A: addAhem is a method. compose method is defined on functions. addAhem _ converts addAhem from method to function, so compose can be called on it. compose expects a function as it's argument. You are giving it a method addUmm by converting addUmm into a function with addUmm _ (The underscore can be left out because the compiler can automatically convert a method into a function when it knows that a function is expected anyway). So your code:
addAhem _ compose addUmm
is the same as
(addAhem _).compose(addUmm)
but not
addAhem(_).compose(addUmm(_))
PS
I didn't look at the link you provided.
A: I believe the tutorial was written for an earlier version of Scala (probably 2.7.7 or earlier). There have been some changes in the compiler since then, namely, extensions to the type system, which now cause the type inferencing to fail on the:
addUhum(_).compose(addAhem(_))
The lifting to a function still works with that syntax if you just write:
addUhum(_)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "48"
} |
Q: Activerecord can't find model by attribute, even though the query is correct I have a Model called Invitation which has an attribute called code. The application's goal is to find the correct invitation with a code that is entered somewhere.
My problem is, however, that even though the input is correct, ActiveRecord can't seem to find any results while querying in the database. I've created this small test to illustrate the problem:
ruby-1.9.2-p290 :003 > code = Invitation.first.code
Invitation Load (0.4ms) SELECT "invitations".* FROM "invitations" LIMIT 1
=> "86f50776bf"
So at this point I've loaded this invitation's code in a variable
ruby-1.9.2-p290 :004 > i = Invitation.where(:code => code)
Invitation Load (0.2ms) SELECT "invitations".* FROM "invitations" WHERE "invitations"."code" = '86f50776bf'
=> []
And the response of the query is an empty array, even though the code comes straight from the database. When using code == Invitation.first.code to see if the values are equal, it returns true. I already checked both the Ruby and database's data types, they're all Strings.
What can cause this? and how can I fix this?
A: Based on your comment, it could be the case that the column is not VARCHAR but CHAR, or it contains trailing spaces that are being trimmed off by the ActiveRecord ORM layer or the database driver. 'foo' and 'foo ' are not equivalent, but they are LIKE enough to match.
You may want to switch that column to variable length, or to adjust your query to test: RTRIM(code)=?
A: I found the solution when I stumbled upon this answer:
In Ruby 1.9, all strings are now encoded. By default, all strings should be UTF-8, however, SecureRandom.hex(30) returns an encoding of ASCII-8BIT.
Adding .force_encoding('UTF-8') to the key when it's being executed solves the problem :)
A: @Marco,
How you declare the code variable? As String?
Example:
code = "86f50776bf"
or
code = '86f50776bf'
?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Where can i find information about whats going behind the scene when creating thread? Where can i find information about whats going on behind the scene when Im creating a new
thread ?
when i write
Thread t = new Thread ()
....
t.start()....
i want to know what actually is going on...
can you please redirect me ?
A: Although managed threads don't necessarily behave the same way as native threads, have a look at this article which covers the basic premise:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms681917(v=vs.85).aspx
Specifically, when you create a thread the code will be running in the context below:
A thread is the entity within a process that can be scheduled for execution. All threads of a process share its virtual address space and system resources. In addition, each thread maintains exception handlers, a scheduling priority, thread local storage, a unique thread identifier, and a set of structures the system will use to save the thread context until it is scheduled. The thread context includes the thread's set of machine registers, the kernel stack, a thread environment block, and a user stack in the address space of the thread's process. Threads can also have their own security context, which can be used for impersonating clients.
A: Just so it's here as an answer, Jeffrey Richter's CLR via C# will probably† teach you stuff you don't know about CLR internals.
And here's Joe Duffy's Concurrent Programming on Windows
† in a statistical sense
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: php explode delimiter with numbers? So I'm trying to explode a string that has a list of answers.
ex: ANSWERS: 1. Comb. 2. Thumb. 3. Tomb (catacomb). 4. Womb. 5. Crumb. 6. Bomb. 7. Numb. 8. Aplomb. 9. Succumb.
Is there a way to explode this to come out like the following:
$answer = explode("something here", $answerString);
$answer[1] = 1. Comb.
$answer[2] = 2. Thumb.
$answer[3] = 3. 3. Tomb (catacomb).
The tricky thing is that I want to explode this string so that each answer can be separated after a number.
So, if the answer is 1 character, or 10 words, it will still split after each number.
Thanks.
A: No, this is not possible with explode(), but you can use preg_split()
http://sandbox.phpcode.eu/g/4b041/1
<?php
$str = '1. Comb. 2. Thumb. 3. Tomb (catacomb). 4. Womb. 5. Crumb. 6. Bomb. 7. Numb. 8. Aplomb. 9. Succumb';
$exploded = preg_split('/[0-9]+\./', $str);
foreach($exploded as $index => $answer){
if (!empty($answer)){
echo $index.": ".$answer."<br />";
}
}
?>
A: You probably want to use preg_split() instead. Something like:
$answer = preg_split('/\d\./', $answerString);
A: <?php
$org_string = "1. Comb. 2. Thumb. 3. Tomb (catacomb). 4. Womb. 5. Crumb. 6. Bomb. 7. Numb. 8. Aplomb. 9. Succumb";
$new_string = str_replace("b. ", "b. ,", $org_string);
$final_string = str_replace("b). ", "b). ,", $new_string);
$exploded = explode(" ,",$final_string);
foreach($exploded as $answer){
echo $answer."<br />";
}
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Resource usage of session_start() I use $_SESSION for authentication of users, but I was thinking about storing other variable in session too. However, I have no idea how much session may use resources on the server. I mean is it harmful to have session_start() on every page, as session will be started even when is not needed?
Is it good or bad or neutral to start session on every visit?
A: Generally speaking, do not worry about optimization until you see your website begin to crawl.
Using session_start() on every page is not harmful at all, in fact its pretty standard for websites that use authentication.
A: Yes, session_start() consumes resources. However, unless your site has huge amounts of traffic, not so as you'd notice. And the alternative ways of storing session data are nearly all a lot harder to implement, and tend to have interesting failure modes.
The only thing I'd recommend is to be careful about what you do put into the session - huge amounts of data will have a noticable impact even with lower levels of traffic. The classic mistake is to accidentally load the entire object tree for your business logic layer into your session state.
For instance, assume you're building a shopping cart; when the customer clicks "add to basket", you want to remember the item they added. So, you could add the item's unique ID into the session, but then you have to look up price and description every time you show the basket, which is a pain. So, you decide to load an object representing the item into your session. This object contains price and description, but also the item's category - and all the other items in that category, because your application isn't using lazy loading. So now, each item in your shopping basket also contains hundreds or thousands of other objects; and before you know where you are, you've loaded pretty much your entire database into the session.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: “404” and “There was no Home CMS page configured or found” after database backup/ import After importing a copy of the database, I got a 404 page on any page- the index, admin, etc. After some research, I read that core_store and core_website tables can sometimes get altered if the export / import settings are not not correct. After I updated the tables (as suggested here), The site not semi-loads, but shows a \"There was no Home CMS page configured or found.\” message on the index, and 404 on the admin.
The site: http://dev.steamsaunadepot.com/
Any help is greatly appreciated. Really stuck here.
Thanks.
A: Figured out the problem. The backup restore works, however, must be on a cleared database, and not overwrite.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to get the name of an object and change the text of a textbox with its' name? Hi there (developers of wp7 apps).
The following problem already caused countless sleepless nights, so i hope anyone could provide me with a solution.
Elements grouped as a grid should call (on tap) a function that changes a textbox' text with one i declare.
I already have the function that reads the "name" of the object:
private void FunctionABC(object sender, System.Windows.Input.GestureEventArgs e)
{
//Objects name
string ObjectSender = (sender as Grid).Name.ToString();
//But how to continue, if I want kind of "this" result?:
this.ObjectSender.Text = "abc";
}
I appreciate any answer my problem. Thanks.
A: If your question is how to change the textbox.text property which is placed inside a grid if you tap the grid then you should iterate through the grids Children and find the textbox you are looking for and then change it's text property.
First of all you need to change the this line :
string ObjectSender = (sender as Grid).Name.ToString();
because this line gives you the name of the Grid and not the Grid itself.
Grid ObjectSender = (Grid) sender;
And then you can search through it's children.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: "Invalid argument" when sending UDP packet, but which? My C++ application is sending binary data as UDP packets. The sendto() call returns EINVAL (Invalid argument), but I don't see anything wrong with the parameters I'm passing.
I did an strace of the application and here are the revelant system calls:
socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 33
setsockopt(33, SOL_IP, IP_RECVERR, [1], 4) = 0
fcntl(33, F_SETFD, FD_CLOEXEC) = 0
bind(33, {sa_family=AF_INET, sin_port=htons(1510), sin_addr=inet_addr("127.0.0.1")}, 16) = 0
sendto(33, "\2055\5\0\0\0\1\0\0\0\1\20 \0t\0c\300Ny\274B\10*\206H\206\367\r\2\5\0\200\200\331'\344\272\322\362sD\277\312\300\23\240\224\212\16\20\1\0\0\22", 55, 0, {sa_family=AF_INET, sin_port=htons(1510), sin_addr=inet_addr("219.132.100.190")}, 16) = -1 EINVAL (Invalid argument)
Does anybody see which parameter is invalid?
The application has recently been ported to support IPv6, but I don't know if that has anything to do with it.
A: You bound your socket to the local address 127.1, but you are sending to a non-localhost address. I need to check, but perhaps the EINVAL means "you can't send 127.1 packets off-host."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to display busy image when actual image is loading in client machine i am going to call my server side method by jquery and my server side method will just give a html like <img src='pop.gif' />
after getting the image url from server side function i will just push the html into my div but i want the when image will be loading at client side then i want to show a busy image. so i plan to write the code like below
first code call server side method
$.ajax({
url: 'image-map.aspx',
data: {}, // the image url links up in our fake database
dataType: 'html',
success: function (html) {
// because we're inside of the success function, we must refer
// to the image as 'img' (defined originally), rather than 'this'
var img = $(html);
$(img).load(function() {
//alert('Image Loaded');
});
$('#myidv').append(img);
}
});
so i just need to know my code is ok. does it work and how to show spinner image till the image download at client side?
A: First of all, you should put the img appending inside the onload function like this:
$(img).load(function() {
$('#mydiv').append(img);
});
This way the image will only be inserted after it's done loading.
For the loading part, there are many approaches, but one way is to put a loading image in the destination element (#mydiv), and remove that image at the same time when appending the new image. Something like this:
$.ajax({
beforeSend: function() {
$('#mydiv').append($(<img src="loading.gif" class="loading" />);
},
success: function(html) {
var img = $(html);
$(img).load(function() {
$('#mydiv .loading').remove();
$('#mydiv').append(img);
});
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: modify TasksByKanbanState.html rally script for a specific end user Can someone provide some guidance on how to modify the TasksByKanbanState.html rally script for a specific end user? An input for the username would be useful.
A: ability to select a user from a drop list will work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Parsing only specific values from an array? I'm parsing some information using Xpath and it returns me a simple array.
$values = array();
Array
(
[0] => http://www.aaa.com/19364328526/
[1] => http://www.bbb.com/207341152011/
[2] => http://www.ccc.co.jp/1246623/
)
Is there any way I can parse through the array and only take certain URLs based on URL weighting? For example. If aaa.com exists, take only aaa.com. If not, check for ccc.co.jp, if that exists, take that only, etc.
I only know how to select from arrays when I know what is there $values[0]/[1]/etc, unfortunately the order of links in this array change and/or aren't present sometimes.
Any help would be much appreciated!
Thanks!
Tre
A: You can use in_array() to check if a value exists. I don't know exactly what you are trying to do, but here is an example. Do you know all the possible values that you might get back?
//List domains in priority order
$weighted = array('aaa.com','bbb.com','ccc.com');
$selected_url = '';
foreach($weighted as $check) { //start with highest priority
foreach($values as $url) { //loop through all URL's
if(strpos($url,$check) !== false) {
//If a url matches priority, return it. We are finished to exit both loops
$selected_url = $url;
break 2;
}
}
}
$selected_url should have the highest priority URL, or it will be empty if none of the urls were found.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: RK4 in 2D gravity simulation probs In actionscript 3.0, I have two objects (a central red star and a orbiting blue planet). I want to use RK4 to plot the orbit. I'm running the simulation once per frame, and drawing once per frame. I have to relate the position of the blue planet in x,y to the central planet so I may be getting lost in the conversion somewhere. This is just for the 1,1 quadrant. I will be adjusting the gravity vector as the blue planet crosses from quadrant to quadrant.
PROBLEM: If I alter the time step, the orbit changes drastically. At small time steps, the orbit becomes a straight line. At large time steps, the orbit becomes tighter. The cooefficients for computing the acceleration for each "K" are not being scaled by dt (except for it being passed through the previous velocity vector).
Here is the RK4 code snip:
http://pastebin.com/Ee6HzBQ2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: 2 events handlers on the same form acting differently I have 2 event handlers attached to buttons on the same form. I want to disable the form and show a waitCursor while the method is running, then enable the form and put the cursor back to default.
Here's the strange part: with almost the same code, one of these events work, and the other doesn't! What could be wrong here?
This one works.
private void btnExceptionReport_Click(object sender, EventArgs e)
{
lblStatus.Text = "Printing exception report.";
ActiveForm.Cursor = Cursors.WaitCursor;
//Form.ActiveForm.Enabled = false;
if (DatabaseOps.printItemReport("Exceptions", cboEmployee.Text))
{
lblStatus.Text = "Exception report printed.";
}
else
{
MessageBox.Show("Error printing exception report.");
lblStatus.Text = "Error printing Exception report.";
}
//Form.ActiveForm.Enabled = true;
ActiveForm.Cursor = Cursors.Default;
}
While this one throws an error when I try to change the cursor back to default, stating that ActiveForm is null.
private void btnWIPReport_Click(object sender, EventArgs e)
{
lblStatus.Text = "Printing WIP Materials report.";
ActiveForm.Cursor = Cursors.WaitCursor;
//Form1.ActiveForm.Enabled = false;
if (DatabaseOps.printItemReport("WIP", cboEmployee.Text))
{
lblStatus.Text = "WIP Materials report printed.";
}
else
{
MessageBox.Show("Error printing WIP Materials report.");
lblStatus.Text = "Error printing WIP Materials report.";
}
//Form1.ActiveForm.Enabled = true;
ActiveForm.Cursor = Cursors.Default; //This line gives error saying ActiveForm is null
}
A: You don't need to call ActiveForm. Simply using this should work:
Cursor = Cursors.Default;
A: If you are using only standard Cursor and WaitCursor it is enough to set bool property UseWaitCursor defined at Control.
It seems that inside your code you have your form accessible as 'this'.
Or optionally is the Form accessible if you cast 'sender' to Button(?) and call FindForm() method on the typed result.
And you should add some try/finally block to restore the cursor even in case of exception in your 'processing' code
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: File upload control for asp.net mvc I'm writing an asp.net mvc application. I'm looking for free control to make file(s) upload. (Multiple files upload is not required). I found uploadify, ajax uploader, c5 filemanager.
I'm looking rather example which I could include in Razor form and add additional fields such as i.e. file description.
Do you have any specific control which you could suggest?
A: Uploadify in my opinion is the best.
Check out:
How do I get jQuery's Uploadify plugin to work with ASP.NET MVC?
its the same in mvc3.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: textbox size not changing with stylesheet here is my css:
<style type="text/css">
.list-problems {
height:600px !important;
width:400px !important;
display:inline-block;
}
.sizetextboxes {
height:600px !important;
width:400px !important;
display:inline-block;
}
the .list-problems is for a listbox and it works well! however i cannot get the .sizetextboxes to work! the textbox size is not being affected at all.
what am i doing wrong?
here's the complete code:
<%@ Page EnableEventValidation="true" Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="EnterData.DataEntry.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js" type="text/javascript"></script>
<link href="../niceforms/niceforms-default.css" rel="stylesheet" type="text/css" />
<script src="../niceforms/niceforms.js" type="text/javascript"></script>
<!--The below is to make the calendar look nice!-->
<link href="../jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" />
<style type="text/css">
.list-problems {
height:600px !important;
width:400px !important;
display:inline-block;
}
.sizetextboxes {
height:600px !important;
width:400px !important;
display:inline-block;
}
</style>
<script>
jQuery(function($) {
//$("#occurrence_dateTextBox").mask("99/99/9999");
//$("#<%= report_dateTextBox.ClientID %>").mask("99/99/9999");
$("#<%= occurrence_dateTextBox.ClientID %>").datepicker();
$("#<%= report_dateTextBox.ClientID %>").datepicker();
//$(".datepicker").datepicker();
});
function getselectedproblems() {
ob = document.getElementById('lstProblems');
var problemlist = '';
for (var i = 0; i < ob.options.length; i++) {
if (ob.options[i].selected) {
//alert(ob.options[i].value);
problemlist = problemlist + ';' + ob.options[i].value; //Do something useful here
}
}
document.getElementById("HiddenProblemList").value=problemlist;
}
</script>
</head>
<body><div id="container">
<form id="form1" runat="server" class="niceform">
<fieldset>
<legend>Section A</legend>
<dl>
<dt><label for="occurrence_dateTextBox" >Occurrence Date:</label></dt>
<dd><asp:TextBox ID="occurrence_dateTextBox" runat="server" size="50"/></dd>
</dl>
<dl>
<dt><label for="report_dateTextBox">Report Date:</label></dt>
<dd><asp:TextBox ID="report_dateTextBox" runat="server" size="50"/></dd>
</dl>
<dl>
<dt><label for="spec_idTextBox">Specimen ID:</label></dt>
<dd><asp:TextBox ID="spec_idTextBox" runat="server" size="50"/></dd>
</dl>
<dl>
<dt><label for="batch_idTextBox">Batch ID:</label></dt>
<dd><asp:TextBox ID="batch_idTextBox" runat="server" size="50"/></dd>
</dl>
<dl>
<dt><label for="report_byTextBox">Report By:</label></dt>
<dd><asp:TextBox ID="report_byTextBox" runat="server" size="50"/></dd>
</dl>
<dl>
<dt><label for="identified_byTextBox">Identified ID:</label></dt>
<dd><asp:TextBox ID="identified_byTextBox" runat="server" size="50"/></dd>
</dl>
</fieldset>
<fieldset>
<legend>Section B</legend>
<dl>
<dt><label for="lstProblems">Problems List:</label></dt>
<dd>
<asp:ListBox ID="lstProblems" runat="server" SelectionMode="Multiple"
CssClass="list-problems" DataSourceID="SqlDataSource2" DataTextField="Column1"
DataValueField="Column1"></asp:ListBox>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:LOM %>"
SelectCommand="select '[' + category + ']' + ' ' + description from tblProblemList">
</asp:SqlDataSource>
</dd>
</dl>
</fieldset>
<fieldset>
<legend>Section C</legend>
<dl>
<dt><label for="section_c_issue_error_identified_byTextBox">Issue/Error Identified By:</label></dt>
<dd><asp:TextBox ID="section_c_issue_error_identified_byTextBox" runat="server" size="50"/></dd>
</dl>
<dl>
<dt><label for="section_c_commentsTextBox" >Comments:</label></dt>
<dd><asp:TextBox ID="section_c_commentsTextBox" CssClass="sizetextboxes" runat="server" size="50"/></dd>
</dl>
</fieldset>
<fieldset>
<legend>Section D</legend>
<dl>
<dt><label for="section_d_investigationTextBox">Investigation:</label></dt>
<dd><asp:TextBox ID="section_d_investigationTextBox" runat="server" size="50"/></dd>
</dl>
</fieldset>
<fieldset>
<legend>Section E</legend>
<dl>
<dt><label for="section_e_corrective_actionTextBox">Corrective Action:</label></dt>
<dd><asp:TextBox ID="section_e_corrective_actionTextBox" runat="server" height="200" TextMode="MultiLine" size="50"/></dd>
</dl>
</fieldset>
<fieldset>
<legend>Section F</legend>
<dl>
<dt><label for="section_f_commentsTextBox">Comments:</label></dt>
<dd><asp:TextBox ID="section_f_commentsTextBox" runat="server" size="50"/></dd>
</dl>
</fieldset>
<fieldset>
<legend>Pre-Analytical</legend>
<dl>
<dt><label for="CheckBox1">PreAnalytical?</label></dt>
<dd> <asp:CheckBox ID="CheckBox1" runat="server" CausesValidation="false"
Visible="true" AutoPostBack="true" OnCheckChanged="CheckBox1_CheckedChanged"/></dd>
</dl>
<dl>
<dt><label for="prePracticeCodeTextBox">Practice Code:</label></dt>
<dd><asp:TextBox ID="prePracticeCodeTextBox" runat="server" Visible="false"/></dd>
</dl>
<dl>
<dt><label for="preContactTextBox1">Contact:</label></dt>
<dd><asp:TextBox ID="preContactTextBox" runat="server" Visible="false"/></dd>
</dl>
</fieldset>
<input id="HiddenProblemList" type="hidden" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="SubmitData" OnClientClick="getselectedproblems()"/>
</form>
</div></body>
</html>
here is the browser parsed code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head><title>
</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js" type="text/javascript"></script>
<link href="../niceforms/niceforms-default.css" rel="stylesheet" type="text/css" />
<script src="../niceforms/niceforms.js" type="text/javascript"></script>
<!--The below is to make the calendar look nice!-->
<link href="../jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" />
<style type="text/css">
.list-problems {
height:600px !important;
width:400px !important;
display:inline-block;
}
.sizetextboxes {
height:600px !important;
width:400px !important;
display:inline-block;
}
</style>
<script>
jQuery(function($) {
//$("#occurrence_dateTextBox").mask("99/99/9999");
//$("#report_dateTextBox").mask("99/99/9999");
$("#occurrence_dateTextBox").datepicker();
$("#report_dateTextBox").datepicker();
//$(".datepicker").datepicker();
});
function getselectedproblems() {
ob = document.getElementById('lstProblems');
var problemlist = '';
for (var i = 0; i < ob.options.length; i++) {
if (ob.options[i].selected) {
//alert(ob.options[i].value);
problemlist = problemlist + ';' + ob.options[i].value; //Do something useful here
}
}
document.getElementById("HiddenProblemList").value=problemlist;
}
</script>
</head>
<body><div id="container">
<form name="form1" method="post" action="WebForm1.aspx" id="form1" class="niceform">
<div>
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__LASTFOCUS" id="__LASTFOCUS" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTI4NTczNDc1Ng9kFgICAw9kFggCDQ8QDxYCHgtfIURhdGFCb3VuZGdkEBU8RFtMQUJFTFNdIFNwZWNpbWVuIGNvbGxlY3Rpb24gZGV2aWNlIG1pc2xhYmVsZWQvdW5sYWJlbGVkIGJ5IHByYWN0aWNlOFtMQUJFTFNdIFNwZWNpbWVuIG1pc2xhYmVsZWQ6IGluLWhvdXNlIGVycm9yIChMYWIgb3IgREUpN1tURVNUIFJFUVVJU0lUSU9OU10gTWlzc2luZzogbm8gZm9ybSBzZW50IHdpdGggc3BlY2ltZW5FW1RFU1QgUkVRVUlTSVRJT05TXSBXcm9uZyAoaS5lLiBPVCBpbnN0ZWFkIG9mIE9SQUwgLSBzaXN0ZXIgcHJhY3RpY2UpIVtURVNUIFJFUVVJU0lUSU9OU10gT3RoZXI6IE5vbi1NTDlbVEVTVCBSRVFVSVNJVElPTlNdIENvcGllcyBSZWNlaXZlZDogTmV3IElEL1JlcS4gYXNzaWduZWQ1W1RFU1QgUkVRVUlTSVRJT05TXSBJbmNvbXBsZXRlL0JsYW5rIFJlcXVpc2l0aW9uIEZvcm0mW1RFU1QgUkVRVUlTSVRJT05TXSAyIFNwZWNpbWVuczogMSBSZXEmW1RFU1QgUkVRVUlTSVRJT05TXSAyIFJlcXM6IDEgU3BlY2ltZW4qW1ZBTElESVRZIE9OTFldIE5lZWQgUE9DIFJlc3VsdHMgQ29uZmlybWVkLltWQUxJRElUWSBPTkxZXSBQT0MgUmVzdWx0cyBNYXJrZWQgSW5jb3JyZWN0bHkgW1ZBTElESVRZIE9OTFldIE5vIFRlc3RzIE9yZGVyZWQdW1ZBTElESVRZIE9OTFldIFNFQyBBIFVuY2xlYXIrW1NBTEVTXSBQcmFjdGljZSBpcyBub3QgZW50ZXJlZCBpbiBkYXRhYmFzZR9bU0FMRVNdIENQIGhhcyBub3QgYmVlbiB1cGRhdGVkDVtPVEhFUl0gT3RoZXIcW1JFQUdFTlQgUFJPQkxFTV0gUUMgRmFpbHVyZSJbUkVBR0VOVCBQUk9CTEVNXSBRQyBDb250YW1pbmF0aW9uIltSRUFHRU5UIFBST0JMRU1dIEFic2VuY2Ugb2YgSU5TVEQmW0lOU1RSVU1FTlQgUFJPQkxFTV0gTGlxdWlkIEhhbmRsZXIgIzofW0lOU1RSVU1FTlQgUFJPQkxFTV0gT2x5bXB1cyAjOiBbSU5TVFJVTUVOVCBQUk9CTEVNXSBMQy1NUy9NUyAjOjFbUFJPQ0VTU0lORyBQUk9CTEVNXSBBbGlxdW90aW5nL1NhbXBsZSBQcm9jZXNzaW5nNltQUk9DRVNTSU5HIFBST0JMRU1dIFNwZWNpbWVuIENvbnRhbWluYXRpb24vIENhcnJ5b3ZlcihbUFJPQ0VTU0lORyBQUk9CTEVNXSBQbGF0ZSBDb250YW1pbmF0aW9uKFtQUk9DRVNTSU5HIFBST0JMRU1dIEJsYW5rIENvbnRhbWluYXRpb24nW0RFTEFZIElOIFBST0RVQ1RJT05dIExpcXVpZCBIYW5kbGVyICM6IFtERUxBWSBJTiBQUk9EVUNUSU9OXSBPbHltcHVzICM6IVtERUxBWSBJTiBQUk9EVUNUSU9OXSBMQy1NUy9NUyAjOh9bT1BFUkFUT1IgRVJST1JdIE9wZXJhdG9yIEVycm9yGVtEQVRBIEVOVFJZXSBNZWRpY2F0aW9ucyASW0RBVEEgRU5UUlldIFRlc3RzHFtEQVRBIEVOVFJZXSBDb2xsZWN0aW9uIERhdGUZW0RBVEEgRU5UUlldIFBhdGllbnQgTmFtZRBbREFUQSBFTlRSWV0gRE9CEFtEQVRBIEVOVFJZXSBTU04hW0RBVEEgRU5UUlldIFJlcXVlc3RpbmcgUGh5c2ljaWFuIFtEQVRBIEVOVFJZXSBXcm9uZyBQcmFjdGljZSBDb2RlP1tEQVRBIEVOVFJZXSBDb3JyZWN0ZWQgUmVwb3J0IMO7IHBhdGllbnQgbmFtZSAmIGFsbCBkZW1vcyB3cm9uZx1bUFJBQ1RJQ0UgRVJST1JdIE1lZGljYXRpb25zIBZbUFJBQ1RJQ0UgRVJST1JdIFRlc3RzHVtQUkFDVElDRSBFUlJPUl0gRGVtb2dyYXBoaWNzOVtTQUxFUyBTVVBQT1JUL0NMSUVOVCBSRUdJU1RSQVRJT05dIFdyb25nIFJlcG9ydCBUZW1wbGF0ZUNbU0FMRVMgU1VQUE9SVC9DTElFTlQgUkVHSVNUUkFUSU9OXSBUeXBvIFByYWN0aWNlIE5hbWUgb3IgUGh5c2ljaWFuMltTQUxFUyBTVVBQT1JUL0NMSUVOVCBSRUdJU1RSQVRJT05dIEUtbWFpbCBBZGRyZXNzLltTQUxFUyBTVVBQT1JUL0NMSUVOVCBSRUdJU1RSQVRJT05dIEZheCBOdW1iZXJGW1NBTEVTIFNVUFBPUlQvQ0xJRU5UIFJFR0lTVFJBVElPTl0gQ3VzdG9tIFByb2ZpbGUgZW50ZXJlZCBpbmNvcnJlY3RseSlbU0FMRVMgU1VQUE9SVC9DTElFTlQgUkVHSVNUUkFUSU9OXSBPdGhlchhbU0FMRVNdIENQIFVwZGF0ZSBOZWVkZWQfW1NBTEVTXSBDbGllbnQgRWR1Y2F0aW9uIE5lZWRlZA1bU0FMRVNdIE90aGVyOFtPUEVSQVRPUiBFUlJPUl0gUmVwb3J0IFNlbnQgdG8gV3JvbmcgTG9jYXRpb24vUGh5c2ljaWFuKVtMQUJdIENvcnJlY3RlZCBSZXBvcnQgw7sgcmVwb3J0aW5nIGVycm9yIFtMQUJdIFBoeXNpY2lhbiBSZXF1ZXN0ZWQgUmVwZWF0C1tMQUJdIE90aGVyK1tRVUlLTEFCL01MSVMgUFJPQkxFTV0gUXVpa2xhYi9NTElTIFByb2JsZW0nW1BSQUNUSUNFIENPTVBMQUlOVF0gUHJhY3RpY2UgQ29tcGxhaW50E1tTSElQUElOR10gU2hpcHBpbmcRW0JJTExJTkddIEJpbGxpbmcNW09USEVSXSBPdGhlchU8RFtMQUJFTFNdIFNwZWNpbWVuIGNvbGxlY3Rpb24gZGV2aWNlIG1pc2xhYmVsZWQvdW5sYWJlbGVkIGJ5IHByYWN0aWNlOFtMQUJFTFNdIFNwZWNpbWVuIG1pc2xhYmVsZWQ6IGluLWhvdXNlIGVycm9yIChMYWIgb3IgREUpN1tURVNUIFJFUVVJU0lUSU9OU10gTWlzc2luZzogbm8gZm9ybSBzZW50IHdpdGggc3BlY2ltZW5FW1RFU1QgUkVRVUlTSVRJT05TXSBXcm9uZyAoaS5lLiBPVCBpbnN0ZWFkIG9mIE9SQUwgLSBzaXN0ZXIgcHJhY3RpY2UpIVtURVNUIFJFUVVJU0lUSU9OU10gT3RoZXI6IE5vbi1NTDlbVEVTVCBSRVFVSVNJVElPTlNdIENvcGllcyBSZWNlaXZlZDogTmV3IElEL1JlcS4gYXNzaWduZWQ1W1RFU1QgUkVRVUlTSVRJT05TXSBJbmNvbXBsZXRlL0JsYW5rIFJlcXVpc2l0aW9uIEZvcm0mW1RFU1QgUkVRVUlTSVRJT05TXSAyIFNwZWNpbWVuczogMSBSZXEmW1RFU1QgUkVRVUlTSVRJT05TXSAyIFJlcXM6IDEgU3BlY2ltZW4qW1ZBTElESVRZIE9OTFldIE5lZWQgUE9DIFJlc3VsdHMgQ29uZmlybWVkLltWQUxJRElUWSBPTkxZXSBQT0MgUmVzdWx0cyBNYXJrZWQgSW5jb3JyZWN0bHkgW1ZBTElESVRZIE9OTFldIE5vIFRlc3RzIE9yZGVyZWQdW1ZBTElESVRZIE9OTFldIFNFQyBBIFVuY2xlYXIrW1NBTEVTXSBQcmFjdGljZSBpcyBub3QgZW50ZXJlZCBpbiBkYXRhYmFzZR9bU0FMRVNdIENQIGhhcyBub3QgYmVlbiB1cGRhdGVkDVtPVEhFUl0gT3RoZXIcW1JFQUdFTlQgUFJPQkxFTV0gUUMgRmFpbHVyZSJbUkVBR0VOVCBQUk9CTEVNXSBRQyBDb250YW1pbmF0aW9uIltSRUFHRU5UIFBST0JMRU1dIEFic2VuY2Ugb2YgSU5TVEQmW0lOU1RSVU1FTlQgUFJPQkxFTV0gTGlxdWlkIEhhbmRsZXIgIzofW0lOU1RSVU1FTlQgUFJPQkxFTV0gT2x5bXB1cyAjOiBbSU5TVFJVTUVOVCBQUk9CTEVNXSBMQy1NUy9NUyAjOjXJlZCBpbmNvcnJlY3RseSlbU0FMRVMgU1VQUE9SVC9DTElFTlQgUkVHSVNUUkFUSU9OXSBPdGhlchhbU0FMRVNdIENQIFVwZGF0ZSBOZWVkZWQfW1NBTEVTXSBDbGllbnQgRWR1Y2F0aW9uIE5lZWRlZA1bU0FMRVNdIE90aGVyOFtPUEVSQVRPUiBFUlJPUl0gUmVwb3J0IFNlbnQgdG8gV3JvbmcgTG9jYXRpb24vUGh5c2ljaWFuKVtMQUJdIENvcnJlY3RlZCBSZXBvcnQgw7sgcmVwb3J0aW5nIGVycm9yIFtMQUJdIFBoeXNpY2lhbiBSZXF1ZXN0ZWQgUmVwZWF0C1tMQUJdIE90aGVyK1tRVUlLTEFCL01MSVMgUFJPQkxFTV0gUXVpa2xhYi9NTElTIFByb2JsZW0nW1BSQUNUSUNFIENPTVBMQUlOVF0gUHJhY3RpY2UgQ29tcGxhaW50E1tTSElQUElOR10gU2hpcHBpbmcRW0JJTExJTkddIEJpbGxpbmcNW09USEVSXSBPdGhlchQrAzxnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dkZAIbDxAPFgIeB0NoZWNrZWRnZGRkZAIdDw8WAh4HVmlzaWJsZWdkZAIfDw8WAh8CZ2RkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYCBQtsc3RQcm9ibGVtcwUJQ2hlY2tCb3gxsnH6pEBHE3hvTDOco3+vweb7Eyo=" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<div>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWTQLiuo+UCwKD5baLBQKZnLKIBQLq34WTAgKNleXoCgKzupqdCgLp2rvfCALz0+ysBQKizOL3BAKSoZuoDQK37abCBQKO24OKBgLnw6GqCgK02smsDQK70OnXCgKb//rOCwKHlszcCQKJxunbDALMlLBvAoHWvZkKAraY2oQPArz3m+4EAtXDhs4CAt6Zqq8IApD3guYEAvSX7IMCApCX7qgCApi8/oQNAqiwn9QPApXroJsMAvScpaUPAo2n9Y0PAvKhHgLj6u0wAovx+tgPAvHE15oGAti4lewHAtDMlLMPAsG79PsNAvOgmbcGApD96ugHAtGu5I0CAqWC1/UIApXdyPgDArrmzcMNAoi/takIAsO125MIAq+W7ewKAtussIIFApbHsYMHAvCw640HApPPoagBAvP7mu4NAqiz4hEC5/SD2wkCjYL7jgQCw6CutQUCypT7hAIClpCW8gcC0ajyygcC99KCqQoCwqvXlAMCtuGQ3wUCtaD6lgwC4savpgIC1JSSigIC1cOGzgIC8JeMzQ4C65vCygICzMeO4wgC88vz2wUCvPzqxAICguTXuwkC0tShiQgC2LOt5AUC7aqM6wsCjOeKxgYQxoUfHLhYSvs+Aadfw3/nRU3vtQ==" />
</div>
<fieldset>
<legend>Section A</legend>
<dl>
<dt><label for="occurrence_dateTextBox" >Occurrence Date:</label></dt>
<dd><input name="occurrence_dateTextBox" type="text" id="occurrence_dateTextBox" size="50" /></dd>
</dl>
<dl>
<dt><label for="report_dateTextBox">Report Date:</label></dt>
<dd><input name="report_dateTextBox" type="text" id="report_dateTextBox" size="50" /></dd>
</dl>
<dl>
<dt><label for="spec_idTextBox">Specimen ID:</label></dt>
<dd><input name="spec_idTextBox" type="text" id="spec_idTextBox" size="50" /></dd>
</dl>
<dl>
<dt><label for="batch_idTextBox">Batch ID:</label></dt>
<dd><input name="batch_idTextBox" type="text" id="batch_idTextBox" size="50" /></dd>
</dl>
<dl>
<dt><label for="report_byTextBox">Report By:</label></dt>
<dd><input name="report_byTextBox" type="text" id="report_byTextBox" size="50" /></dd>
</dl>
<dl>
<dt><label for="identified_byTextBox">Identified ID:</label></dt>
<dd><input name="identified_byTextBox" type="text" id="identified_byTextBox" size="50" /></dd>
</dl>
</fieldset>
<fieldset>
<legend>Section B</legend>
<dl>
<dt><label for="lstProblems">Problems List:</label></dt>
<dd>
<select size="4" name="lstProblems" multiple="multiple" id="lstProblems" class="list-problems">
<option value="[LABELS] Specimen collection device mislabeled/unlabeled by practice">[LABELS] Specimen collection device mislabeled/unlabeled by practice</option>
<option value="[LABELS] Specimen mislabeled: in-house error (Lab or DE)">[LABELS] Specimen mislabeled: in-house error (Lab or DE)</option>
<option value="[TEST REQUISITIONS] Missing: no form sent with specimen">[TEST REQUISITIONS] Missing: no form sent with specimen</option>
<option value="[TEST REQUISITIONS] Wrong (i.e. OT instead of ORAL - sister practice)">[TEST REQUISITIONS] Wrong (i.e. OT instead of ORAL - sister practice)</option>
<option value="[TEST REQUISITIONS] Other: Non-ML">[TEST REQUISITIONS] Other: Non-ML</option>
<option value="[TEST REQUISITIONS] Copies Received: New ID/Req. assigned">[TEST REQUISITIONS] Copies Received: New ID/Req. assigned</option>
<option value="[TEST REQUISITIONS] Incomplete/Blank Requisition Form">[TEST REQUISITIONS] Incomplete/Blank Requisition Form</option>
<option value="[TEST REQUISITIONS] 2 Specimens: 1 Req">[TEST REQUISITIONS] 2 Specimens: 1 Req</option>
<option value="[TEST REQUISITIONS] 2 Reqs: 1 Specimen">[TEST REQUISITIONS] 2 Reqs: 1 Specimen</option>
<option value="[VALIDITY ONLY] Need POC Results Confirmed">[VALIDITY ONLY] Need POC Results Confirmed</option>
<option value="[VALIDITY ONLY] POC Results Marked Incorrectly">[VALIDITY ONLY] POC Results Marked Incorrectly</option>
<option value="[VALIDITY ONLY] No Tests Ordered">[VALIDITY ONLY] No Tests Ordered</option>
<option value="[VALIDITY ONLY] SEC A Unclear">[VALIDITY ONLY] SEC A Unclear</option>
<option value="[SALES] Practice is not entered in database">[SALES] Practice is not entered in database</option>
<option value="[SALES] CP has not been updated">[SALES] CP has not been updated</option>
<option value="[OTHER] Other">[OTHER] Other</option>
<option value="[REAGENT PROBLEM] QC Failure">[REAGENT PROBLEM] QC Failure</option>
<option value="[REAGENT PROBLEM] QC Contamination">[REAGENT PROBLEM] QC Contamination</option>
<option value="[REAGENT PROBLEM] Absence of INSTD">[REAGENT PROBLEM] Absence of INSTD</option>
<option value="[INSTRUMENT PROBLEM] Liquid Handler #:">[INSTRUMENT PROBLEM] Liquid Handler #:</option>
<option value="[INSTRUMENT PROBLEM] Olympus #:">[INSTRUMENT PROBLEM] Olympus #:</option>
<option value="[INSTRUMENT PROBLEM] LC-MS/MS #:">[INSTRUMENT PROBLEM] LC-MS/MS #:</option>
<option value="[PROCESSING PROBLEM] Aliquoting/Sample Processing">[PROCESSING PROBLEM] Aliquoting/Sample Processing</option>
<option value="[PROCESSING PROBLEM] Specimen Contamination/ Carryover">[PROCESSING PROBLEM] Specimen Contamination/ Carryover</option>
<option value="[PROCESSING PROBLEM] Plate Contamination">[PROCESSING PROBLEM] Plate Contamination</option>
<option value="[PROCESSING PROBLEM] Blank Contamination">[PROCESSING PROBLEM] Blank Contamination</option>
<option value="[DELAY IN PRODUCTION] Liquid Handler #:">[DELAY IN PRODUCTION] Liquid Handler #:</option>
<option value="[DELAY IN PRODUCTION] Olympus #:">[DELAY IN PRODUCTION] Olympus #:</option>
<option value="[DELAY IN PRODUCTION] LC-MS/MS #:">[DELAY IN PRODUCTION] LC-MS/MS #:</option>
<option value="[OPERATOR ERROR] Operator Error">[OPERATOR ERROR] Operator Error</option>
<option value="[DATA ENTRY] Medications ">[DATA ENTRY] Medications </option>
<option value="[DATA ENTRY] Tests">[DATA ENTRY] Tests</option>
<option value="[DATA ENTRY] Collection Date">[DATA ENTRY] Collection Date</option>
<option value="[DATA ENTRY] Patient Name">[DATA ENTRY] Patient Name</option>
<option value="[DATA ENTRY] DOB">[DATA ENTRY] DOB</option>
<option value="[DATA ENTRY] SSN">[DATA ENTRY] SSN</option>
<option value="[DATA ENTRY] Requesting Physician">[DATA ENTRY] Requesting Physician</option>
<option value="[DATA ENTRY] Wrong Practice Code">[DATA ENTRY] Wrong Practice Code</option>
<option value="[DATA ENTRY] Corrected Report û patient name & all demos wrong">[DATA ENTRY] Corrected Report û patient name & all demos wrong</option>
<option value="[PRACTICE ERROR] Medications ">[PRACTICE ERROR] Medications </option>
<option value="[PRACTICE ERROR] Tests">[PRACTICE ERROR] Tests</option>
<option value="[PRACTICE ERROR] Demographics">[PRACTICE ERROR] Demographics</option>
<option value="[SALES SUPPORT/CLIENT REGISTRATION] Wrong Report Template">[SALES SUPPORT/CLIENT REGISTRATION] Wrong Report Template</option>
<option value="[SALES SUPPORT/CLIENT REGISTRATION] Typo Practice Name or Physician">[SALES SUPPORT/CLIENT REGISTRATION] Typo Practice Name or Physician</option>
<option value="[SALES SUPPORT/CLIENT REGISTRATION] E-mail Address">[SALES SUPPORT/CLIENT REGISTRATION] E-mail Address</option>
<option value="[SALES SUPPORT/CLIENT REGISTRATION] Fax Number">[SALES SUPPORT/CLIENT REGISTRATION] Fax Number</option>
<option value="[SALES SUPPORT/CLIENT REGISTRATION] Custom Profile entered incorrectly">[SALES SUPPORT/CLIENT REGISTRATION] Custom Profile entered incorrectly</option>
<option value="[SALES SUPPORT/CLIENT REGISTRATION] Other">[SALES SUPPORT/CLIENT REGISTRATION] Other</option>
<option value="[SALES] CP Update Needed">[SALES] CP Update Needed</option>
<option value="[SALES] Client Education Needed">[SALES] Client Education Needed</option>
<option value="[SALES] Other">[SALES] Other</option>
<option value="[OPERATOR ERROR] Report Sent to Wrong Location/Physician">[OPERATOR ERROR] Report Sent to Wrong Location/Physician</option>
<option value="[LAB] Corrected Report û reporting error">[LAB] Corrected Report û reporting error</option>
<option value="[LAB] Physician Requested Repeat">[LAB] Physician Requested Repeat</option>
<option value="[LAB] Other">[LAB] Other</option>
<option value="[QUIKLAB/MLIS PROBLEM] Quiklab/MLIS Problem">[QUIKLAB/MLIS PROBLEM] Quiklab/MLIS Problem</option>
<option value="[PRACTICE COMPLAINT] Practice Complaint">[PRACTICE COMPLAINT] Practice Complaint</option>
<option value="[SHIPPING] Shipping">[SHIPPING] Shipping</option>
<option value="[BILLING] Billing">[BILLING] Billing</option>
<option value="[OTHER] Other">[OTHER] Other</option>
</select>
</dd>
</dl>
</fieldset>
<fieldset>
<legend>Section C</legend>
<dl>
<dt><label for="section_c_issue_error_identified_byTextBox">Issue/Error Identified By:</label></dt>
<dd><input name="section_c_issue_error_identified_byTextBox" type="text" id="section_c_issue_error_identified_byTextBox" size="50" /></dd>
</dl>
<dl>
<dt><label for="section_c_commentsTextBox" >Comments:</label></dt>
<dd><input name="section_c_commentsTextBox" type="text" id="section_c_commentsTextBox" class="sizetextboxes" size="50" style="height:50px;" /></dd>
</dl>
</fieldset>
<fieldset>
<legend>Section D</legend>
<dl>
<dt><label for="section_d_investigationTextBox">Investigation:</label></dt>
<dd><input name="section_d_investigationTextBox" type="text" id="section_d_investigationTextBox" size="50" /></dd>
</dl>
</fieldset>
<fieldset>
<legend>Section E</legend>
<dl>
<dt><label for="section_e_corrective_actionTextBox">Corrective Action:</label></dt>
<dd><textarea name="section_e_corrective_actionTextBox" rows="2" cols="20" id="section_e_corrective_actionTextBox" size="50" style="height:200px;"></textarea></dd>
</dl>
</fieldset>
<fieldset>
<legend>Section F</legend>
<dl>
<dt><label for="section_f_commentsTextBox">Comments:</label></dt>
<dd><input name="section_f_commentsTextBox" type="text" id="section_f_commentsTextBox" size="50" /></dd>
</dl>
</fieldset>
<fieldset>
<legend>Pre-Analytical</legend>
<dl>
<dt><label for="CheckBox1">PreAnalytical?</label></dt>
<dd> <span OnCheckChanged="CheckBox1_CheckedChanged"><input id="CheckBox1" type="checkbox" name="CheckBox1" checked="checked" onclick="javascript:setTimeout('__doPostBack(\'CheckBox1\',\'\')', 0)" /></span></dd>
</dl>
<dl>
<dt><label for="prePracticeCodeTextBox">Practice Code:</label></dt>
<dd><input name="prePracticeCodeTextBox" type="text" id="prePracticeCodeTextBox" /></dd>
</dl>
<dl>
<dt><label for="preContactTextBox1">Contact:</label></dt>
<dd><input name="preContactTextBox" type="text" id="preContactTextBox" /></dd>
</dl>
</fieldset>
<input name="HiddenProblemList" type="hidden" id="HiddenProblemList" />
<input type="submit" name="Button1" value="Button" onclick="getselectedproblems();" id="Button1" />
</form>
</div></body>
</html>
A: The text box in question has inline styling of size="50" and style="height:50px;". It seems like you actually want a TextArea here, not an input textbox. I'm not familiar with ASP.NET, but adding this to the element might work Wrap="true" TextMode="MultiLine".
<asp:TextBox ID="section_c_commentsTextBox" CssClass="sizetextboxes" runat="server" Wrap="true" TextMode="MultiLine"/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why is it a bad thing to have multiple HTML elements with the same id attribute? Why is it bad practice to have more than one HTML element with the same id attribute on the same page? I am looking for a way to explain this to someone who is not very familiar with HTML.
I know that the HTML spec requires ids to be unique but that doesn't sound like a convincing reason. Why should I care what someone wrote in some document?
The main reason I can think of is that multiple elements with the same id can cause strange and undefined behavior with Javascript functions such as document.getElementById. I also know that it can cause unexpected behavior with fragment identifiers in URLs. Can anyone think of any other reasons that would make sense to HTML newbies?
A:
Why should I care what someone wrote in some document?
You should care because if you are writing HTML, it will be rendered in a browser which was written by someone who did care. W3C created the spec and Google, Mozilla, Microsoft etc... are following it so it is in your interest to follow it as well.
A: Besides the obvious reason (they are supposed to be unique), you should care because having multiple elements with the same id can break your application.
Let's say you have this markup:
<p id="my_id">One</p>
<p id="my_id">Two</p>
CSS is forgiving, this will color both elements red:
#my_id { color:red; }
..but with JavaScript, this will only style the first one:
document.getElementById('my_id').style.color = 'red';
This is just a simple example. When you're doing anything with JavaScript that relies on ids being unique, your whole application can fall apart. There are questions posted here every day where this is actually happening - something crucial is broken because the developer used duplicate id attributes.
A: Because if you have multiple HTML elements with the same ID, it is no longer an IDentifier, is it?
Why can't two people have the same social security number?
A: You basicaly responded to the question. I think that as long as an elemenet can no longer be uniquely identified by the id, than any function that resides on this functionality will break. You can still choose to search elements in an xpath style using the id like you would use a class, but it's cumbersome, error prone and will give you headaches later.
A: Based on your question you already know what w3c has to say about this:
The id attribute specifies a unique id for an HTML element (the id
attribute value must be unique within the HTML document).
The id attribute can be used to point to a style in a style sheet.
The id attribute can also be used by a JavaScript (via the HTML DOM)
to make changes to the HTML element with the specific id.
The point with an id is that it must be unique. It is used to identify an element (or an anything: if two students had the same student id schools would come apart at the seems). It's not like a human name, which needn't be unique. If two elements in an array had the same index, or if two different real numbers were equal... the universe would just fall apart. It's part of the definition of identity.
You should probably use class for what you are trying to do, I think (ps: what are you trying to do?).
Hope this helps!
A:
The main reason I can think of is that multiple elements with the same id can cause strange and undefined behavior with Javascript functions such as document.getElementById.
... and XPath expressions, crawlers, scrapers, etc. that rely on ids, but yes, that's exactly it. If they're not convinced, then too bad for them; it will bite them in the end, whether they know it or not (when their website gets visited poorly).
A: Why should a social security number be unique, or a license plate number? For the same reason any other identifier should be unique. So that it identifies exactly one thing, and you can find that one thing if you have the id.
A:
The main reason I can think of is that multiple elements with the same
id can cause strange and undefined behavior with Javascript functions
such as document.getElementById.
This is exactly the problem. "Undefined behavior" means that one user's browser will behave one way (perhaps get only the first element), another will behave another way (perhaps get only the last element), and another will behave yet another way (perhaps get an array of all elements). The whole idea of programming is to give the computer (that is, the user's browser) exact instructions concerning what you want it to do. When you use ambiguous instructions like non-unique ID attributes, then you get unpredictable results, which is not what a programmer wants.
Why should I care what someone wrote in some document?
W3C specs are not merely "some document"; they are the rules that, if you follow in your coding, you can reasonably expect any browser to obey. Of course, W3C standards are rarely followed exactly by all browsers, but they are the best set of commonly accepted ground rules that exist.
A: The short answer is that in HTML/JavaScript DOM API you have the getElementById function which returns one element, not a collection. So if you have more than one element with the same id, it would not know which one to pick.
But the question isn't that dumb actually, because there are reasons to want one id that might refer to more than one element in the HTML. For example, a user might make a selection of text and wants to annotate it. You want to show this with a
<span class="Annotation" id="A01">Bla bla bla</span>
If the user selected text that spans multiple paragraphs, then the needs to be broken up into fragments, but all fragments of that selection should be addressable by the same "id".
Note that in the past you could put
<a name="..."/>
elements in your HTML and you could find them with getElementsByName. So this is similar. But unfortunately the HTML specifications have started to deprecate this, which is a bad idea because it leaves an important use case without a simple solution.
Of course with XPath you can do anything use any attribute or even text node as an id. Apparently the XPointer spec allows you to make reference to elements by any XPath expression and use that in URL fragment references as in
http://my.host.com/document.html#xpointer(id('A01'))
or its short version
http://my.host.com/document.html#A01
or, other equivalent XPath expressions:
http://my.host.com/document.html#xpointer(/*/descendant-or-self::*[@id = 'A01'])
and so, one could refer to name attributes
http://my.host.com/document.html#xpointer(/*/descendant-or-self::*[@name = 'A01'])
or whatever you name your attributes
http://my.host.com/document.html#xpointer(/*/descendant-or-self::*[@annotation-id = 'A01'])
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: 404 error when posting form data in cakephp I have a RESTful api in a cakephp app that returns json data. I am testing it with firefox REST Client. The GET requests work fine, but I am getting 404 errors I dont understand when posting form data. The failing requests look like this:
.
If I change the content-type to "text/html" I don't get a 404 anymore, although I do not get the expected response, presumably because the form data is not being posted.
Any ideas what's going on?
A: I figured out the problem. The cakephp security component needed the csrf token. Setting "validatePost" to false on that compoment fixed the issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Custom Actions within c++/cli Setup project I have done over 20 installer classes for MSI's in c#, i'm now attempting one in c++/cli. I add my project output file (which contains my installer class) to the custom actions "Install"... i over ride OnAfterInstall within the Installer Class, with no code at the moment and i get the following error (just testing):
Error 1001. Exception occurred while initializing the installation:
System.10.FileLoadException: Attempt to load an unverifiable executable with fixups (IAT
with more than 2 sections or a TLS section.) (Exception from HRESULT: 0x30131019).
i would appreciate any guidance on this issue... I've never experienced it before. when this error happens it initiates a rollback... below is a link to the MSI LOG:
http://www.evas.com/MSILOG/MSI67b70.LOG
i would greatly appreciate some guidance,
Thank you
A: I've only written this type of custom actions in C++ so I don't know for sure what is the problem.
I found on MSDN the following samples, maybe it will help you:
http://msdn.microsoft.com/en-us/library/system.configuration.install.installer(v=vs.71).aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Extending cookie expiration dates in PHP When I look at the cookies for my site in Google Chrome, I see PHPSESSID,__utma, __utmb, __utmc, and __utmz. I don't understand what these cookies mean, except for maybe PHPSESSID, which I assume is the user's login session. Some expire "When I close my browser" and other expire at some future date. Is there a way I could make them all expire in 2 years for example?
I'm trying to make it so the user stays logged in after closing the browser.
A: __utma, __utmb, __utmc, __utmz are cookies set by Google Analytics, not your site's code.
To extend the PHPSESSID cookie, your PHP session cookie, modify the setting in php.ini:
; some long value in seconds (1 year)
session.gc_maxlifetime = 31536000
session.cookie_lifetime = 31536000
For cookies you yourself have set in code via setcookie() (none of which are listed among your list), pass the third parameter as a value in seconds:
// Two year cookie (86400 secs per day for 2 years)
setcookie('name', 'cookievalue', time() + 86400 * 365 * 2);
A: These are cookies from Google analytics to track you. You can read more about it here
Only times user gets logout from your website is when session or cookies expries. If they expire time is 0, they expires when browser closes
A: you need to find the code that sets the coockies and add the appropriate expire time
setcookie ("TestCookie", "", time() + 3600); //expires after 1 hour
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I programmatically add a cert to installed browsers? I have a cert generated through a custom protocol and I would like to add it to a browsers store (and and all browsers: ie, firefox, chrome, safari) so that it can use it to authenticate. How can I accomplish this?
A: Firefox stores certificates in the three .db files in the user profile. So you would need to go through all existing profiles and change them. That can be done using NSS, particularly the certutil command line tool and for PKCS #12 files also pk12util. Depending on your goals you could of course also integrate NSS into your application and call its functions without using any command line tools. Note that IMHO adding a client certificate requires entering the master password for the database if one is set.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP, PCI compliance problem: How to? I've have a problem with the PCI compliance. Basically they want me to add https:// on every page where the password field is present. this is kind of wierd.
My form in index.php looks like:
<form method=post action="login.php" id="login">
<input type="text" size="16" maxlength="30" name="login" id="login_user" />
<input type="password" size=16 maxlength="20" name="pass" class="ifield" id="login_pass"/>
<input name="msubmit" type="submit" value="Login" />
</form>
I've tried to post to https: <form method=post action="https://test.com/login.php" id="login"> but the test it still fails.
How should I fix this problem?
A: First, you will need to configure your webserver to support SSL. You will need to purchase an SSL certificate and configure your webserver to answer requests on both port 80 and port 443.
After you have completed these changes, you will be able to tell your form to post to the SSL version of your site via the URL you posted above.
If the compliance rules require it, you may also need to make the form itself load under the SSL version of the site. In this case, you can update all of your links to the form to point to the 'https://' version, or modify your webserver rules to forward all requests for the form to the 'https://' version.
A: From an objective security (not PCI) standpoint, there is nothing wrong with filling in the form as you have it, then posting it via SSL to an https address. Whether the page on which the blank form was originally displayed was a secure page is irrelevant, though many people think otherwise (wrongly). Presenting your form on a secure page is marketing -- people feel more comfortable when you do so. Submitting it via https is the actual secure part.
Many PCI-compliance requirements are hypothetical or about marketing and the perceptions of security, as opposed to actual security. If your scanner is flagging you simply because the form is being presented on a non-SSL page, then you could legitimately dispute that finding, as there is no security impact. If the form in question, even when properly accessed, doesn't allow access to server management or private information, then you could also legitimately dispute the finding. However, if the process of logging in allows access to personal information or server management, then there are multiple reasons to make sure that it is submitted via a secure port.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: setting the "DT_RowId" property when using simple_datatables I am using the simple datatables gem to integrate JQuery Datatables into my Rails App.
Is it possible to send the DT_RowId property in the json document as described in the doc when using simple_datatables?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: no-render with OpenGL --> contexts i have a program that does some GPU computing with Optional OpenGL rendering.
The use dynamic is as follow:
*
*init function (init GLEW being the most relevant).
*load mesh from file to GPU (use glGenBuffers are related functions to make VBO).
*process this mesh in parallel (GPU Computing API).
*save mesh into file.
my problem is that when mesh is loading i use opengl calls and wihout context created i just
get segmentation fault.
Edit: Evolution of the problem:
*
*I was missing GL/glx.h I thought that GL/glxew.h included it, thanks to the answers that got fixed.
*I was missing glXMakeCurrent; and therefore it was having zero contexts.
*After this fixes, it works :).
also thanks for the tools suggestions, i would gladly use them it is just that i needed the low level code for this particular case.
A:
i tried making a context with this code ( i am using glew, so i change the header to GL/glxew.h but the rest of this code remains the same)
Don'd do it. glxew is used for loading glx functions. You probably don't need it.
If you want to use GLEW, replace GL/gl.h with GL/glew.h leave GL/glx.h as it is.
X11 and GLX are quite complex, consider using sdl of glfw instead.
A: Just wildly guessing here, but could it be that GLEW redefined glXChooseFBConfig with something custom? Something in the call of glXChooseFBConfig dereferences an invalid pointer. So either glXChooseFBConfig itself is invalid, or fbcount to so small, or visual_attribs not properly terminated.
A: GLEW has nothing to do with context creation. It is an OpenGL loading library; it loads OpenGL functions. It needs you to have an OpenGL context in order for it to function.
Since you're not really using this context for drawing stuff, I would suggest using an off-the-shelf tool for context creation. GLFW or FreeGLUT would be the most light-weight alternatives. Just use them to create a context, do what you need to do, then destroy the windows they create.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sending and Receiving Serialized Objects in Java - Socket Programming (I know this can be done in RMI, but I need to do this using sockets since I found there could be some setup process if RMI methods used)
Please have a look at the simple Client-Server code at http://www.coderanch.com/t/205325/sockets/java/send-any-java-Object-through
In this program, the order two objects sent by SimpleServer are known by SimpleClient.
i.e: Server
oos.writeObject(new testobject(1,"object from client"));
oos.writeObject(new String("another object from the client"));
Client does the casting according to the order the object is received.But I want to avoid this nature and make client send any object at any time so the server should also be able to handle each object sent accordingly and return a result.
testobject to = (testobject)ois.readObject();
System.out.println(to.id);}
System.out.println((String)ois.readObject());
Is there a way to "label" the objects being sent so that the action can be determined by a simple "if" statement in Server?
OR
is there a better way to use a ResultSet returned by the Server instead of my object serializing approach?
thanks in advance.
Thanks
A: readObject will return an object in its proper class. if you need to have some branching logic based on that you can use instanceof:
Object newObj = stream.readObject();
if (newObj instanceof testobject) {
doSomething((testobject) newObj);
} else if (newObj instanceof String) {
doSomethingWithString((String) newObj);
} // etc.
As a rule, this is not recommended for all objects read from a stream. If you're going to use ObjectStreams to establish a protocol, you should document it and stick to it. That way, if one side sends incorrect data, you'll catch it more quickly on the other side.
However, in a scenario where at a given point in the protocol flow, it's expected that the client might be sending one of several different types of objects, then it might make sense.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: foreach statement cannot operate on variables of type '' because '' does not contain a public definition for 'GetEnumerator' I Got an Error Like This
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1579: foreach statement cannot operate on variables of type 'EventListing.Models.EventInfo' because 'EventListing.Models.EventInfo' does not contain a public definition for 'GetEnumerator'
Source Error:
Line 106: </th>
Line 107: </tr>
Line 108: <% foreach (var model in Model)
Line 109: { %>
Line 110: <tr>
Model
public static List<EventInfo> EventList()
{
var list = new List<EventInfo>();
Dbhelper DbHelper = new Dbhelper();
DbCommand cmd = DbHelper.GetSqlStringCommond("SELECT * FROM WS_EVENTINFO");
DbDataReader Datareader = DbHelper.ExecuteReader(cmd);
while (Datareader.Read())
{
EventInfo eventinfo = new EventInfo()
{
EVENT_ID = Convert.ToInt32(Datareader[
View Page
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<EventListing.Models.EventInfo>" %>
<% foreach (var model in Model)
{ %>
<tr>
<td>
<%= Html.ActionLink(Model.TITLE,"Detail", new {id = Model.EVENT_ID})%>
How can solve this Issue, i'm Using MVC2 Framework.
A: You need to bind a collection as a model. Check this post for details: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
View
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IList<EventListing.Models.EventInfo>>" %>
Controller
public ActionResult List()
{
return this.View(EventList());
}
Or use some another type for model and define property List<EventInfo> Events in it. Then iterate in following way:
<% foreach (var model in Model.Events)
{ %>
Also, Visual Studio can do it for you:
A: Presumably what you are trying to do is:
foreach(var model in Model.EventList()) {..}
Although it is difficult to be sure.
If you require the syntax you used then Model will have to be an object of a class with a GetEnumerator() method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Inline ntohs() / ntohl() in C++ / Boost ASIO Hi I'm using C++ / Boost ASIO and I have to inline ntohl() for performance reasons. Each data packet contains 256 int32s, hence a lot of calls to ntohl(). Has anyone done this?
Here is the compiled assembly output out of VC10++ with all optimizations turned on:
; int32_t d = boost::asio::detail::socket_ops::network_to_host_long(*pdw++);
mov esi, DWORD PTR _pdw$[esp+64]
mov eax, DWORD PTR [esi]
push eax
call DWORD PTR __imp__ntohl@4
I've also tried the regular ntohl() provided by winsock. Any help would be greatly appreciated.
Also, I've been thinking the C way of having a #define macro that does simple int32 barrel shifts (if the network order doesn't match the machines order at compile time). And if anyone knows and can provide the most efficient assembly for ntohl() on a x86 / x64 architecture, that would be awesome. Eventually my code needs to be portable to ARM as well.
A: The x86-32 and x86-64 platforms have a 32-bit 'bswap' assembly instruction. I don't think you'll do better than one operation.
uint32_t asm_ntohl(uint32_t a)
{
__asm
{
mov eax, a;
bswap eax;
}
}
A: Looking at the assembler, __imp__ntohl@4 is an import symbol from a DLL, so it is an external function and cannot be inlined.
Of course you can write your own, even macro, knowing that you are most likely using Windows in a little-endian machine, you just need to swap bytes.
You can find several highly optimized versions more or less portable version in the gtypes.h header from glib, macro GUINT32_SWAP_LE_BE:
glib.h
A: Please see optimizing byte swapping for fun and profit. It explains how to make it fast.
But I strongly recommend you stop worrying about it. Think about it - ASIO is allocating a memory to store handler's state every time you call async_read, just for example. That is by far more expensive than calling innocent ntohl, which is inlined in Linux by default, by the way. It seems like you have a premature optimization problem - you should stop that immediately, or you will waste your time and resources. After all - profile your application first, then optimize it (vTune or TotalView is recommended).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: A jQuery clock where I can set the initial time and then let it run client side I'd like to set the time at the top of my site and have it constantly update itself, only client side.
So on the initial page load, I'd give it the server time:
[HttpPost]
public ActionResult GetTime()
{
return Content(@DateTime.Now.AddHours(3).ToString("HH:mm"));
//Returns something like: "20:05"
}
Then I'd like the client to just start running a clock starting from the time I've given it.
So when a user loads the page, he recieves 20:05 and without regarding his own local time, I'd like that clock to move forward in a regular fashion. 20:06, 20:07, etc.
Is there something like this available for jQuery?
A: Here's an example of incrementing a number on a page by 1 every second: http://jsfiddle.net/ct3VW/
Is that enough for you to work with?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Parent Model that can only have one child in Rails? Sorry the title is pretty unclear - I'm just not quiet sure how to phrase the question without explaining it.
I would like to record workouts with my app. I would like a Workout Table (what I'm calling the parent) that has basic information like date and sub_workout_type_id
A workout record can have either a Cardiovascular workout (One Model) or a Strength Workout (Another Model).
My thought on have 3 tables instead of just the 2 Cario Workout model and strength workout model is that I would be able to pull a feed of any type of workout, by pulling the Workout Records and then dig deeper as needed.
Perhaps there is a more ruby-ish way to do this? Because right now I don't know of a way to say has_one_model_or_the_other. Thanks!
A: I see two options, either you use STI (single table inheritance) : in that case you would have a single table that would be able to contain both a cardiovascular model or a strength workout, and a type. This would only work if the two models share some common characteristics.
Another solution is to write something like
has_one :cardiovascular
has_one :strength
and then use validations to enforce that only one of them is set.
Hope this helps.
A: As mentioned by @nathanvda, STI could be a good choice.
If you're looking to store class specific data with your models, maybe check out Modeling inheritance with Ruby/Rails ORMs to see if that answer gives you any ideas on how to model this relationship.
Note, the example there uses has_many's but a lot of the ideas are similar.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Themeless Page - Or a content-only content type I need to create content that only outputs what I entered, no layout, no comments, blocks, etc.
If I could implement a custom content type that used blank templates that might work, but I've been unable to make it work so far as overriding the themes seems to replace everything site-wide. So, skipping that, is there a simple way I'm not aware of, to just output what I type in the content's body, with no layout/blocks/comments,etc.
Is it possible via a custom module to add a custom field at the bottom, and then during the process_page() hook, ignore the theming and layout and just output the content?
Please don't suggest "Views" as it's not stable.
Some example use cases:
A page that's a PHP type, and it's simply a script that I don't want layout as an example.
Or if I have some json data to return.
Or if I want to toss up a all-in-one page with it's own theme.
Any suggestions?
A: I am working on a module that will do this and also integrate with views so you can set a view to be "theme-less" as well. I have it so that it will create a checkbox on a node form that you can specify the node to be theme-less node. Once that is checked, the node will be displayed with no theme (the content only, no title).
It's a little hackish, but it works preliminarily. I will be fleshing this out as I have need for it and I will likely also integrate it with views over time.
timeless.install
<?php
/**
* themeless.install
* defines our schema for flagging nodes as being themeless or not.
*/
function themeless_schema() {
$schema['themeless_node'] = array(
'description' => 'Keeps track of which nodes are themeless.',
'fields' => array(
'nid' => array(
'description' => 'The node id of a themeless node',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
),
),
'primary_key' => array('nid'),
);
return $schema;
}
function themeless_enable() {
if (db_table_exists('themeless_node') == FALSE) {
drupal_install_schema('themeless');
}
}
function themeless_uninstall() {
drupal_uninstall_schema('themeless');
}
timeless.module
function themeless_process(&$variables, $hook) {
if ($hook == 'page') {
if (isset($variables['page']['content']['system_main']['nodes']) && is_array($variables['page']['content']['system_main']['nodes'])) {
$node = $variables['page']['content']['system_main']['nodes'];
$nodes = array_keys($node);
$result = db_query("SELECT t.nid AS themeless, n.promote
FROM {themeless_node} t, {node} n
WHERE t.nid=:nid
AND n.nid=t.nid",
array('nid' => $nodes[0]));
$tdata = $result->fetchObject();
if (isset($tdata->themeless) && $tdata->themeless > 0 && $tdata->promote != 1) {
if ($node[$nodes[0]]['body']['#object']->body['und'][0]['format'] == 'php_code') {
print $node[$nodes[0]]['body'][0]['#markup'];
} else {
print $node[$nodes[0]]['body']['#object']->body['und'][0]['value'];
}
exit();
}
}
}
}
function themeless_form_alter(&$form, &$form_state, $form_id) {
$parts = explode('_',$form_id);
$form_type = $parts[count($parts)-1].'_'.$parts[count($parts)-2];
$themeless = '';
if ($form_type == 'form_node') {
if (isset($form_state['node']->nid) && $form_state['node']->nid) {
$themeless = db_query("SELECT COUNT(*) AS themeless
FROM {themeless_node}
WHERE nid=:nid",
array('nid' => $form_state['node']->nid))->fetchField();
}
$checked = ($themeless == 1) ? 'checked' : '';
$form['themeless'] = array(
'#type' => 'fieldset',
'#title' => t('Themeless Node'),
'#weight' => 5,
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['themeless']['themeless_node'] = array(
'#type' => 'checkbox',
'#title' => 'Themeless Node',
'#description' => 'This theme will be displayed without any wrapper themes.',
'#weight' => 100,
'#default_value' => $themeless,
);
}
}
function themeless_node_insert($node) {
$result = db_query("INSERT INTO {themeless_node} (nid)
VALUES( :nid )",array('nid' => $node->nid));
}
function themeless_node_update($node) {
if ($node->themeless_node == 1) {
if (db_query("SELECT COUNT(*) AS themeless
FROM {themeless_node}
WHERE nid=:nid",
array('nid' => $node->nid))->fetchField() != 1) {
$result = db_query("INSERT INTO {themeless_node} (nid)
VALUES( :nid )",array('nid' => $node->nid));
}
} else {
$result = db_query("DELETE FROM {themeless_node}
WHERE nid=:nid",array('nid' => $node->nid));
}
}
timeless.info
name = Themeless
description = Gives the option to a node to have a themeless display or displayed without the various theme templates native to Drupal.
core = 7.x
version = 7.x-1.0dev
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How is Lua code execution handled when using LuaJava? I intend to use LuaJava to run scripts in my Java/Android applications.
*
*When I run Lua script, is it executed in some another thread?
*How do I manage execution of Lua code, how do I know that script finished execution?
If I want my Java program to wait for Lua code to finish, what do I do then?
My first guess was to use some semaphores and invoke Java callbacks from Lua. How do I do it in a right way?
UPD WITH CODE
Java:
LoadScript(final String filename) {
this.luaState = LuaStateFactory.newLuaState();
this.luaState.openLibs();
this.luaState.LdoFile(filename);//launch Lua script to print lines
printLines();// print Java lines
}
void printLines(){
for(int i=0;i<100;i++)
System.out.println("From java: "+i);
}
Lua:
for i=0,100
do
print("From lua: ",i)
end
In console I see that Java printed its strings first, and then Lua did.
A:
When I run Lua script, is it executed in some another thread?
No.
You will know that the script has "finished" execution when the next Java statement after the one that calls into the script is executed.
That happens because they're using different streams to write to std-out. They have different flushing behavior, so one will happen before the other. But the actual execution of the code is not threaded.
If you want to test this, just have the Lua script return something and then have your Java code get the top thing from the stack. It will always be what the Lua script generated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: div that sticks to the top when you scroll past it in jquery For example...the new facebook activity stream on the right. Or on okay cupid (the message/rating dialogue).
How does this work exactly. Can someone point me to a tutorial or explanation?
Thanks!
A: There are many ways to do this but here is one using CSS only
<div style="position:fixed; left:0; top:0; height:100px; width:100%">Stuck to Top</div>
Here is a fiddle
http://jsfiddle.net/2kmQe/
A: Add some Javascript to set position: fixed; top: 0px; when $(window).scrollTop() reaches the $("#element_id").offset().top.
Google does a similar thing with their new gmail look
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to decode bitmap images using python's email class Hello I have python script that takes apart an email from a string. I am using the get_payload(decode=True) function from the email class and it works great for pdf's and jpg's but it does not decode bmp files. The file is still encoded base64 when I write it to disk.
Has anyone come across this issue themselves?
A: OK so I finally found the problem and it was not related to the python mail class at all. I was reading from a named pipe using the .read() function and it was not reading the entire email from the pipe. I had to pass the read function a size argument and then it was able to read the entire email. So ultimately the reason why my bmp file was not decoded is because I had invalid base64 data causing the get_payload() function to not be able to decode the attatchment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails 3.1. What's the easiest way to make chaining dropdown selects? I was trying to make work this:
http://chainselects.hypermediasoft.com/
But got error:
Routing Error
uninitialized constant ChainSelectsHelper
So i have to make some break and ask community - is there any easy way to make chaining select boxes for my application forms?
UPDATE:
Maybe i should make editions in some config files? I can see thist ChainSelectsHelper in vendor/plugins/ChainSelects/lib/app/helpers/chain_selects_helper.rb. But why my application can't see this? Any assets pipeline configs needed?
And got this error in model:
undefined method `acts_as_chainable' for #<Class:0x007fe387542780>
A: From the looks of it, it seems that you did not add this in the controller:
include ChainSelectsHelper
Keep in mind that modifications have to be made to both model and controller, as stated here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I determine which version of virtualenvwrapper is installed? I know that which virtualenvwrapper.sh will locate the virtualenvwrapper bash script.
But, how can I determine which version of virtualenvwrapper is installed?
A: Updated Answer 02-Jun-17
Using pip:
$ pip list | grep virtualenvwrapper
virtualenvwrapper (4.7.2)
Original Answer
Not an elegant solution, but here's how I determined that I have version 2.10.1 of virtualenvwrapper installed:
$ which virtualenvwrapper.sh
/Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh
$ cd /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/
$ ls virtualenvwrapper*
virtualenvwrapper-2.10.1-py2.7-nspkg.pth
virtualenvwrapper-2.10-1-py2.7.egg-info
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: MySQL insert with value determined at insertion I need to set a field value, actually a flag, in a record to either 0 or 1 depending on whether the id field (int(10) auto_increment, primary key) is even or odd. I know I can determine the value after insertion with a bitwise selector and then run an update but I'm wondering if there is a way to do this within the insert statement.
A: I think the best way is to set a trigger on the insert action that will automaticaly set the parity of that field.
A: Why use another field to store data your ID is already carrying?
Even:
SELECT * FROM my_table WHERE (MOD(id,2) = 0)
Odd:
SELECT * FROM my_table WHERE (MOD(id,2) > 0)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What data structure could I use for counting occurrences of a country code? I need some kind of data structure don't know yet which would be most suitable.
Here is what I'm working with: I have a bunch rows of data processing and each row has its own country code.
I want to obtain as result how many times each country code repeats throughout the process.
A: You might try a HashMap. With a HashMap, you can use the country code as the key, and the count of how many times each appears as the value stored in that key. If you encounter a particular country code for the first time, insert it into the map with an initial value of 1; otherwise, increment the existing value.
HashMap<String, Integer> myMap = new HashMap<String, Integer>();
for (... record : records) {
String countryCode = record.getCountryCode();
int curVal;
if (myMap.containsKey(countryCode)) {
curVal = myMap.get(countryCode);
myMap.put(countryCode, curVal + 1);
} else {
myMap.put(countryCode, 1);
}
}
// myMap now contains the count of each country code, which
// can be used for whatever purpose needed.
A: I would use a HashMap with the country code as the key and the count as the value. Build the map from your collection and increment the count if it is already in the map.
A: Create a Map using country code String as the key and the current count as the value.
You realize, of course, that you can get such a thing directly out of a SQL query:
select country_code, count(country_code)
from your_table
group by country_code
order by country_code
You'll get a ResultSet with country code and count pairs. That's easy to load into a Map.
A: To complete the answer with something other than HashMap.
*
*If your country code list is or can easily be turned into a not very sparse numeric sequence, try a int[] or long[].
*If your country code range is sparse, but don't have many elements, create a CountryCode enum And use a EnumMap to store the amounts:
Example:
Map<CountryCode, Long> countryCodeAppearances =
new EnumMap<CountryCode,Long>(CountryCode.class);
Lightweight data structures will perform better and impose less memory / garbage collection overhead. So, array should be the fastest. EnumMap is kind off a hidden gem that, under the right circumstances may also give you a performance boost.
A: Guava offers the AtomicLongMap
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: jquery + Scrolling + Check what element is visible I would like to know if its possible with jQuery to do the following:
http://jsfiddle.net/AzFJR/2/
-check which ".main" is visible at the moment and dynamically add ".active" to the corresponding link in the "nav" ?
Regards!
Edit:
I have worked it out using this Viewport Plugin and following code:
//find what element is in view
var inview = '#' + $('.sectionSelector:in-viewport:first').attr('id'),
//find the corresponding link
$link = $('.mainNav li a').filter('[hash=' + inview + ']');
//check i its already active or not and if not
if ($link.length && !$link.is('.active')) {
//remove all previous active links and make the current one active
$('.mainNav li a').removeClass('active');
$link.addClass('active');
}
//Start same proccess on every scroll event again
$(window).scroll(function () {
var inview = '#' + $('.sectionSelector:in-viewport:first').attr('id'),
$link = $('.mainNav li a').filter('[hash=' + inview + ']');
if ($link.length && !$link.is('.active')) {
$('.mainNav li a').removeClass('active');
$link.addClass('active');
}
});
Thanks every1 for the help!
A: Use the jQuery ELEMENT ‘INVIEW’ EVENT plugin.
$('div').bind('inview', function(event, isInView, visiblePartX, visiblePartY) {
if (isInView) {
// find link and addClass '.active'
} else {
// remove the class
}
});
A: The scrollTo plugin should do the trick http://flesler.blogspot.com/2007/10/jqueryscrollto.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript Array with Links I am using an javascript array to swap images and act like a slide show. I am looking to apply an image map to each image and link to a specific page when clicked.
I need to code an image map hot spot covering a rectangle from (24,247) to (174,284) becomes a link. But I need each image to link to a different page (the hotspot location remains the same on every image.) How do I program this so when each image changes in the slide show it links to a different page?
Here is the coding involved:
in Head Section (js file listed far below):
<style> #Slideshow1 img {height:356px; width:912px}</style>
<script type="text/javascript" src="js/slideshowmerge.js"></script>
In the HTML Section to place array:
<div class="box_broadstyle">
<script>
var imgArray = new Array();
imgArray[0] = "images2/slide_pics/full/ashley.png";
imgArray[1] = "images2/slide_pics/full/auburn.png";
imgArray[2] = "images2/slide_pics/full/brooklyn.png";
imgArray[3] = "images2/slide_pics/full/cobane.png";
imgArray[4] = "images2/slide_pics/full/giddeon.png";
imgArray[5] = "images2/slide_pics/full/hartford.png";
imgArray[6] = "images2/slide_pics/full/saratoga.png";
imgArray[7] = "images2/slide_pics/full/seabrook.png";
imgArray[8] = "images2/slide_pics/full/spring.png";
slideshowMerge('Slideshow1','',imgArray,20,5000);
</script><
</div>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
Slideshowmerge.js listed here:
//=======================
//
// Merging Image Slideshow
//
//
//=======================
var slideshowMergeAnimate = new Array();
var slideshowMergeTimer = new Array();
var slideshowMergeCount = new Array();
var slideshowMergeImages = new Array();
//======================
function slideshowMerge(id,cl,imageArray,fadeInterval,holdTime)
{
for(i=0;i<imageArray.length;i++)
{
var imgLoad = new Image();
imgLoad.src = imageArray[i];
}
if(cl)
cl = ' class="'+cl+'"';
document.write('<div id="'+id+'"'+cl+' style="position:relative">');
document.write('<img id="'+id+'img1" style="position:absolute; top:0px; left:0px;" onload="slideshowMergeRun(\''+id+'\')"/>');
document.write('<img id="'+id+'img2" style="position:absolute; top:0px; left:0px;display:none;"/></div>');
slideshowMergeCount[id] = 0;
slideshowMergeImages[id] = imageArray;
slideshowMergeAnimate[id] = 'run';
slideshowMergeTimer[id] = setInterval('slideshowMergeAnimation(\''+id+'\',\''+holdTime+'\');',fadeInterval);
}
//======================
function slideshowMergeAnimation(id,holdTime)
{
if(slideshowMergeAnimate[id]=='run')
{
var obj1 = document.getElementById(id+'img1');
var obj2 = document.getElementById(id+'img2');
var opa = slideshowMergeCount[id]%100;
if(opa==0)
{
if(obj1.src)
{
slideshowMergeAnimate[id] = 'hold';
setTimeout('slideshowMergeRun(\''+id+'\')',holdTime);
obj2.src = obj1.src;
obj2.style.display = 'block';
}
}
else if(opa==1)
{
slideshowMergeAnimate[id] = 'load';
obj1.src = slideshowMergeImages[id][Math.floor(slideshowMergeCount[id]/100)%slideshowMergeImages[id].length];
}
obj1.style.opacity = (opa/100).toString();
obj1.style.filter = "alpha(opacity="+opa.toString()+")";
obj2.style.opacity = ((100-opa)/100).toString();
obj2.style.filter = "alpha(opacity="+(100-opa).toString()+")";
slideshowMergeCount[id]++;
if(slideshowMergeCount[id]==(slideshowMergeImages[id].length*100))
slideshowMergeCount[id]=0;
}
}
//======================
function slideshowMergeRun(id)
{
slideshowMergeAnimate[id] = 'run';
}
//======================
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: The concept of snapshot There is a concept of snapshot in Git basic terminology.
This concept is used in Git workflow:
*
*You modify files in your working directory.
*You stage the files, adding snapshots of them to your staging
area.
*You do a commit, which takes the files as they are in the
staging area and stores that snapshot permanently to your Git
directory.
Could you explain exactly what is snapshot and show some small example of files and it's snapshots and why Git uses them instead of making differences as in other VCSs?
A: A snapshot just means what a file's contents were at a given point in time. All version control systems operate conceptually on snapshots. You want to be able to see what your source code looked like at any given point in the past. They also all store diffs in order to save storage space. Where git is unique is in two ways: the way diffs are computed and stored internally isn't directly related to the file's history, and the diffs aren't recomputed every single time they could be.
Let's say you have a 1000-byte file that gets updated on practically every build. If you change one byte of it, git will temporarily store a completely new copy of the file, with the one byte changed. This is where people flip out and say, "OMG, git is so stupid, it should store the diffs right away. I'm sticking with subversion."
However, think about how you actually use your source control. Almost everything you want to do comparisons with are things that have changed since the last time you pushed. Because it hasn't computed the diffs yet, git just happens to have a full, easily accessible cache of all those recently-changed files, where other version control systems have to start with version 1 and apply hundreds of diffs to reconstruct the same content.
Then when you do a push to share your changes, git gc is run automatically in order to store those files more efficiently for transport over the network, and diffs are computed and stored then. However, it's not necessarily a diff from version n-1 to version n of the file. If content is repeated across many files, git can take that into account. If the same change is made in several branches, git can take that into account. If a file is moved, git can take that into account. If some heuristic is discovered in the future that can make things more efficient, git can take that into account without breaking existing clients. It's not wedded to the idea that the diff must always be from one consecutive version to the next.
It's fundamental design decisions like these that make git so fast compared to other version control software.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C++ prime number generator is not working #include <iostream>
using namespace std;
int checkIfPrime(int num) {
for (int i = 1; i < num; i++) {
int result = num / i;
if (num == result * i) {
return 0;
}
}
}
int main() {
int i = 3;
while(1) {
int c = checkIfPrime(i);
if (c != 0) {
cout << c << "\n";
}
i = i + 2;
}
}
Sorry about posting the wrong code!
When I run this, nothing happens.. Can someone tell me what I am doing wrong?
A: After the question has completely changed its meaning:
Your CheckIfPrime is just wrong. You're checking divisibility in a very strange way. The general way to check whether a is divisible by b is if(a % b == 0)
That said, your error is that your loop starts with 1. Of course every number is divisible by 1, therefore by your logic, no number is prime. Start with for(int i = 2; .... (Depending on whether you want to consider 1 as prime or not, you might want to test specially for num == 1 initially.)
Also, the end condition is very inefficient. It is enough to check before the square root of num, that is i <= sqrt(num), but since sqrt is a rather slow and imprecise operation, MUCH better is to loop this way:
for(int i = 2; i * i < = num; ++i)
Another note - to generate all prime numbers from 1 to some MAX_VAL, your approach is very inefficient. Use the Sieve of Erastothenes.
Some stylistic note: your function should ideally return bool rather than int, and don't forget to return true or 1 after the loop has finished without returning.
Original Answer:
First of all, you need
fprintf(OUTPUT_FILE, "%d", Num); //d instead of s, no & before Num
instead of
fprintf(OUTPUT_FILE, "%s", &Num);
Second, you use the file I/O extremely inefficiently. Why do you open and close the file for every number? You should open it once, write all numbers, and then close it.
And thirdly, your algorithm doesn't seem to have anything to do with prime numbers... :)
By the way, since the first issue results in Undefined Behavior, you can't complain about any behavior of the program, since it's... well, undefined.
A: You aren't error checking any of your FileIO - wonder if something's going wrong there. A few ifs could help sort that out. Beyond that, all I see is an app that will fill your HDD real fast if it's working correctly.
A: The main reason why your prime generator isn't working, that i can see:
for (int i = 1; i < num; i++) {
int result = num / i;
if (num == result * i) {
return 0;
}
}
You start checking at 1. Since every number / 1 == itself, and every number * 1 == itself, the condition will always be true on the first run; that is, your prime test will always return false. Start at 2 instead.
Once you fix that, you should also make it so that the test returns true if it manages to get all the way through the loop. (Inserting a return 1; after the loop should be enough.)
(BTW, if you care the least bit about efficiency, if ((num & 1) == 0) return 0; for (int i = 3; i * i <= num; i += 2) would be better. But better still would be a sieve of some sort, as mentioned elsewhere.)
A: int checkIfPrime(int num) {
for (int i = 1; i < num; i++) {
int result = num / i;
if (num == result * i) {
return 0;
}
}
}
*
*Missing return 1 at the end of the loop
*The initial value of i must not be 1. Walk through the first iteration with a pencil and paper and see what happens.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How do I emulate a HoneyComb-compatible app on older emulators? I began the process of making one of my apps Honeycomb-friendly.
I started by changing the project's target build to version 11, and edited to AndroidManifest.xml to use:
<uses-sdk android:minSdkVersion="5" android:targetSdkVersion="11" />
These are the only changes I made so far. I am able to test it perfectly on my Honeycomb tablet device.
However, I cannot get Eclipse to launch this app in an older emulator (e.g. version 9). Technically speaking, the app should run in older android versions, so what can I do to test this app for older devices?
Or am I doing something else wrong?
A: I'm by no means an expert on this front but setting the minSdkVersion different from the targetSdkVersion doesn't make the app automatically use a different API level based on the device. See this:
Android Min SDK Version vs. Target SDK Version
and this:
http://android-developers.blogspot.com/2010/07/how-to-have-your-cupcake-and-eat-it-too.html
I suspect that because your application is using level 11 apis it won't run on a device that is of a previous API level.
A: This seems to be some sort of bug. When my 3.1 device is plugged into my PC, Eclipse/Android won't let me launch a new emulator that's < 3.0.
I worked around this by launching the emulator before I plug in my device, and then it has no problems deploying the app to both of the running devices.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: providing assignment operator but no copy constructor I read here that if I don't write a copy constructor the compiler does it for me using
the assignment operator, which results in shallow copy of Objects. What if I do have the
assignment operator overloaded in all of my member object? wouldn't it result in a deep copy?
A:
if I don't write a copy constructor the compiler does it for me using the assignment operator
No, it doesn't use the assignment operator; it does it via a implicitly generated copy constructor which does a shallow copy.
What if I do have the assignment operator overloaded in all of my member object? wouldn't it result in a deep copy?
Given that the assignment operator is not used in absence of explicitly defined copy constructor, even though you have the assignment operator overloaded you still need to overload the copy constructor as well.
Read the Rule of Three in C++03 & Rule of Five in C++11.
A: The important part in the linked article is "each member of the class individually using the assignment operator." So it doesn't matter if you define the assignment operator for you class, it will use the assignment operator for each member of your class.
A: You're misinformed. The implicitly generated constructors and assignment operators simply perform construction or assignment recursively on all members and subobjects:
*
*copy constructor copies element by element
*move constructor moves element by element
*copy assignment assigns element by element
*move assign move-assigns element by element
This logic is the reason why the best design is one in which you don't write any copy constructor (or any of the other three, or the destructor) yourself, and instead compose your class of well-chosen, single-responsibility classes whose own semantics take care of everything.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Styling breaks after partial post back in update panel. How can i fix this? I am currently developing a website using ASP.NET and JQuery Mobile. The problem I am running into is that I need to do a popup with information retrieved from a service. Currently I am populating a list view with link buttons (used to retrieve additional info) inside of an update panel. The first time the page loads, all items are styled, but after a partial post back the styling is lost. NOTE: Jquery Mobile automatically styles the controls accordingly.
A: Try forcing recreation of the styles within the pageLoad function, which is called whenever the page loads (asynchronously or synchronously).
<script type="text/javascript">
function pageLoad(sender, args) {
$('#<%= updatePanel1.ClientID %>').trigger('create');
}
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Embed from imgur I'm currently using this code for embedding from youtube:
if($e['domain'] == "youtube.com") {
preg_match('/[\\?\\&]v=([^\\?\\&]+)/',$e['url'],$matches);
if(count($matches) > 1) {
$embed = true;
$embed_code = "<object width='480' height='344'><param name='movie' value='http://www.youtube.com/v/" . $matches[1] . "?fs=1&hl=en_US&color1=FFFFFF&color2=FFFFFF'></param><param name='allowFullScreen' value='true'></param><param name='allowscriptaccess' value='always'></param><embed src='http://www.youtube.com/v/" . $matches[1] . "?fs=1&hl=en_US&color1=FFFFFF&color2=FFFFFF' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='480' height='344'></embed></object>";
}
}
And I want to use kind of the same for imgur.com which uses the prefix "i" for embedding. So the images are prefix+$e. How do I make it work?
Right now I've tried:
if($e['domain'] == "i.imgur.com") {
preg_match('/[\\?\\&]([^\\?\\&]+)/',$e['url'],$matches);
if(count($matches) > 1) {
$embed = true;
$embed_code = "<img src='http://i.imgur.com/' alt='' title='Hosted by imgur.com' />";
}
}
But I get this error message:
Notice: Undefined variable: embed in /hsphere/local/home/xx/xx/xx/xx/view.php on line 107
EDIT: Here are the lines from 105-116:
else $embed = false;
if(isset($e['description']) || $embed == true) { ?>
<tr class="listing_spacer_tr"><td colspan="6"></td></tr>
<tr><td colspan="5"></td><td>
<?php if($embed) echo $embed_code . "<br /><br />"; ?>
<?php // DESCRIPTION
if(isset($e['description'])) { ?>
<div class="view_description"><?php echo make_clickable(nl2br($e['description'])); ?></div>
<?php }
} ?>
A: There isn't problem in code you have posted. You've probably got some problems somewhere else. Problem is reading, not assigning value to your $embed variable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to pass instances to WPF Window class? Suppose I have 3 classes to handle all database related requests:
public class DB_A{}
public class DB_B{}
public class DB_C{}
and I got 2 windows to interact with user:
window1.xaml;window1.xaml.cs;
window2.xaml;window2.xaml.cs
as window1 & window2 need to interact with database, they need to use functions from previous 3 classes, I created a class DataHandler:
public class DataHandler
{
public DB_A a;
public DB_B b;
public DB_C c;
public DataHandler()
{
a = new DB_A();
b = new DB_B();
c = new DB_C();
}
//some functions... ...
}
now the class DataHandler can handle all database related request, and now i need to pass a instant of DataHandler to both window1 and window2.
I tried to re-write the constructor for both window1 and window2 with parameter, but it does not allow me to do that. After google i know that WPF window form does not allow constructor with parameter.
Is there any way to pass my DataHandler to the two window form classes?
A: Make DataHandler a singleton, and let the window classes access it.
public class DataHandler
{
//singleton instance
static DataHandler _instance = new DataHandler ();
public DataHandler Instance
{
get { return _instance; }
}
};
Then,
public partial class Window1 : Window
{
DataHandler _dataHandler;
public Window1()
{
InitializeComponent();
_dataHandler = DataHandler.Instance;
}
}
Similarly, write other Window class.
Or even better is, apply some variant of MVP pattern, most likely, MVVM. Read these articles:
*
*Composite Guidance for WPF : MVVM vs MVP
*WPF patterns : MVC, MVP or MVVM or…?
*Model-View-Presenter Pattern
*Model View Presenter
A: Yes, you can, there are multiple ways to do that,
*
*you make your DataHandler a singleton. ( I do not like this one)
*add a public static property to app.xaml.cs that has an instance of your DataHandler class and in your Windows’ constructor take that from app. (it’s a better approach)
*add a ViewModel and let that view model present data to both Windows. (I prefer this one!)
If you need an example let me know which one works for you and I will provide one.
A: Can't you make the DataHandler class to singleton and use it's methods on wherever you want, without re-instantiating the class?
A: You can have parameters on your Window constructor. Alternatively you could pass it in through a property, set your DataHandler object to a public static property somewhere, or even just make your DataHandler a static class.
A: There are any number of ways to accomplish this.
You can make DataHandler a singleton.
Since DataHandler has a parameterless constructor, you can create it in the application's resource dictionary, and let objects use FindResource to get it.
One pattern that you'll see pretty commonly, in implementations using the MVVM pattern, is that the view models contain a reference to shared objects, and windows get access to them through binding, though I doubt very much that you're using MVVM.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Threading + raw_input in Python I've got a Python script that does a bunch of things in a single subthread, and I'd like the main thread to spit out raw_input("> ") (to be handled by the main thread), and keep that input on the bottom of the console, while the subthread prints things above. I originally thought I could use something like print "\b\b" + message + "\n> " in the subbthread, but that doesn't account for things like characters the user has typed in. So, the console would look something like this:
[22:04] Started
[22:06] Some output
[22:06] Some more output
>
Is this possible?
A: In addition to the curses suggestions, you might want to take a look at urwid, a higher-level, more python friendly library for dealing with console output.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Can anyone tell me why this javascript function call isn't working? Here's a jsFiddle
Fiddle
JavaScript:
function createTable(tbody, rows, cols) {
if (tbody == null || tbody.length < 1) return;
for (var r = 1; r <= rows; r++) {
var trow = $("<tr>");
for (var c = 1; c <= cols; c++) {
$("<td>")
.text("Table")
//.createElement("div")
.appendTo(trow);
}
trow.appendTo(tbody);
}
}
$(document).ready(function() {
createTable($("#table"), 4, 4);
});
HTML:
<table id="table" border="1">
<tbody>
</tbody>
</table>
----------------------------
<table id="table1" border="1">
<tbody>
</tbody>
</table>
<br><br>
Select table size?
<form>
<input type="button" value="4X4" onclick="createTable('table1', 4, 4)">
</form>
The JavaScript function called by JavaScript works fine(table), but the JavaScript function called by the OnClick isn't working(table1). Can you tell me why?
Also does anyone know why the createElement("div") isn't working either?
A: Fixed http://jsfiddle.net/7WD8v/6/
You needed to load you script in the head to have it available for that input
A: You have to use no wrap in the fiddle and jQuery doesn't have createElement method (as you are calling it as a jQuery method). You may use .append()
Fiddle
A: http://jsfiddle.net/7WD8v/12/
A: you need to pass the object on the onclick
createTable($('#table1'), 4, 4)
A: Because on OnClick you pass a String as first argument value and in js call a collection of elements is passed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How do I give KO an array inside my JSON data How do I access the internal array in my JSON data? I'm only showing the first element in the Scores, there are many in the real data. Do I really need to iterate the initialData by hand to get at this internal array?
var initialData = {
"DateId": 32,
"Scores": [{
"Alias": "Joyce",
"MemberId": 11,
"Game1": 220
}...]
};
var theScores = initialData.Scores;
var viewModel = {
scores: ko.observableArray(theScores)
};
A: scores is now an observableArray. To access the underlying array you would need to retrieve the value of the observable like viewModel.scores().
observableArrays do have the majority of the array methods added to them, so you can do things like push or splice directly on the observableArray. This will perform the action and then notify any subscribers that there was a change.
So, basically if you are trying to spit out your array in firebug, then do viewModel.scores(). A handy trick to unwrap all of the observables in a structure is to do ko.toJS(viewModel). This will give you back a plain JavaScript object.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can i move my layout via accelerometer sensor? I've two AbsoluteLayout are called Background_layout and Foreground_layout in one base XML.
I wanna move first layout (Background_layout) through the accelerometer sensor for direction Y X Z , How can i do that?
Here you can see my XML :
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/background_layout"
android:background="@drawable/background"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<AbsoluteLayout
android:id="@+id/foreground_layout"
android:layout_height="wrap_content"
android:background="@drawable/foreground"
android:layout_width="wrap_content"
android:layout_x="0dip"
android:layout_y="0dip">
</AbsoluteLayout>
</AbsoluteLayout>
I have all the values about direction , But I don't know How can I use them in layout view.
public void onSensorChanged(int sensor, float[] values) {
synchronized (this) {
if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
float ValuX = (float) values[0];
float ValuY = (float) values[1];
float ValuZ = (float) values[2];
int ResValuX = new Integer(Float.toString(ValuX));
int ResValuY = new Integer(Float.toString(ValuY));
int ResValuZ = new Integer(Float.toString(ValuZ));
Background.addView(Background,ResValuX);
Background.addView(Background,ResValuY);
Background.addView(Background,ResValuZ);
}
}
}
Any suggestion would be appreciated.
A: If you get values from the accelerometer, then you can update the postition of views by setting their layout parameters. To move the views to left, you could set the value as the left margin.
LinearLayout.LayoutParams lp = LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT
,LayoutParams.WRAP_CONTENT);
lp.leftMargin = 10;
view.setLayoutParameters(lp);
This should work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: OpenCV cvblob - Render Blob I'm trying to detect a object using cvblob. So I use cvRenderBlob() method. Program compiled successfully but when at the run time it is returning an unhandled exception. When I break it, the arrow is pointed out to CvLabel *labels = (CvLabel *)imgLabel->imageData + imgLabel_offset + (blob->miny * stepLbl); statement in the cvRenderBlob() method definition of the cvblob.cpp file. But if I use cvRenderBlobs() method it's working fine. I need to detect only one blob that is the largest one. Some one please help me to handle this exception.
Here is my VC++ code,
CvCapture* capture = 0;
IplImage* frame = 0;
int key = 0;
CvBlobs blobs;
CvBlob *blob;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("Could not initialize capturing....\n");
return 1;
}
int screenx = GetSystemMetrics(SM_CXSCREEN);
int screeny = GetSystemMetrics(SM_CYSCREEN);
while (key!='q') {
frame = cvQueryFrame(capture);
if (!frame) break;
IplImage* imgHSV = cvCreateImage(cvGetSize(frame), 8, 3);
cvCvtColor(frame, imgHSV, CV_BGR2HSV);
IplImage* imgThreshed = cvCreateImage(cvGetSize(frame), 8, 1);
cvInRangeS(imgHSV, cvScalar(61, 156, 205),cvScalar(161, 256, 305), imgThreshed); // for light blue color
IplImage* imgThresh = imgThreshed;
cvSmooth(imgThresh, imgThresh, CV_GAUSSIAN, 9, 9);
cvNamedWindow("Thresh");
cvShowImage("Thresh", imgThresh);
IplImage* labelImg = cvCreateImage(cvGetSize(imgHSV), IPL_DEPTH_LABEL, 1);
unsigned int result = cvLabel(imgThresh, labelImg, blobs);
blob = blobs[cvGreaterBlob(blobs)];
cvRenderBlob(labelImg, blob, frame, frame);
/*cvRenderBlobs(labelImg, blobs, frame, frame);*/
/*cvFilterByArea(blobs, 60, 500);*/
cvFilterByLabel(blobs, cvGreaterBlob(blobs));
cvNamedWindow("Video");
cvShowImage("Video", frame);
key = cvWaitKey(1);
}
cvDestroyWindow("Thresh");
cvDestroyWindow("Video");
cvReleaseCapture(&capture);
A: First off, I'd like to point out that you are actually using the regular c syntax. C++ uses the class Mat. I've been working on some blob extraction based on green objects in the picture. Once thresholded properly, which means we have a "binary" image, background/foreground. I use
findContours() //this function expects quite a bit, read documentation
Descriped more clearly in the documentation on structural analysis. It will give you the contour of all the blobs in the image. In a vector which is handling another vector, which is handling points in the image; like so
vector<vector<Point>> contours;
I too need to find the biggest blob, and though my approach can be faulty to some extend, I won't need it to be different. I use
minAreaRect() // expects a set of points (contained by the vector or mat classes
Descriped also under structural analysis
Then access the size of the rect
int sizeOfObject = 0;
int idxBiggestObject = 0; //will track the biggest object
if(contours.size() != 0) //only runs code if there is any blobs / contours in the image
{
for (int i = 0; i < contours.size(); i++) // runs i times where i is the amount of "blobs" in the image.
{
myVector = minAreaRect(contours[i])
if(myVector.size.area > sizeOfObject)
{
sizeOfObject = myVector.size.area; //saves area to compare with further blobs
idxBiggestObject = i; //saves index, so you know which is biggest, alternatively, .push_back into another vector
}
}
}
So okay, we really only measure a rotated bounding box, but in most cases it will do. I hope that you will either switch to c++ syntax, or get some inspiration from the basic algorithm.
Enjoy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: UIView or UIImage in a UITableView, what's better for performance I have a UITableView where we want to just put a colored square. Depending on the data in the UITableViewCell, the UIView changes its background color. That's the way it currently is. To me, it seems better to just have a UIImageView and have a .png image for the different color squares, and load the correct one per cell depending on the data in the UITableViewCell. I'm not sure which method is better, or if there is an even better method I do not know of. Any thoughts? Thanks.
A: Having worked with images contained in table cells, I have to believe that simply using a UIView and setting it's background color to whatever you need is going to be far faster.
Even with local images (those in your app bundle), think of all the extra work you'd be incurring to create a UIImage and then set the UIImageView's image property?
In my case, on two different projects, I had to load images off the 'net into table cells. Quite slow, so we did it in the background, which had it's own challenges and special conditions to deal with. This would be overkill for what you describe though.
I'd go with UIView's and background colors. Of course, you could try it yourself both ways and see how it works for you. :-) Remember to test on a real device, because it's easy to be lulled into a sense of "everything is GREAT!" when you watch your app scream on the simulator! :-)
A: I think it it better to fill background with some color rather then load images from file. It will be much more quickly, as you don't need to access file system.
A: Definitely just use the view’s background color. An opaque view filled with a solid color is one of the fastest things you can draw; a PNG will be notably slower, will consume more memory, and will needlessly bloat the size of your app bundle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Use of function calls in stored procedure sql server 2005? Use of function calls in where clause of stored procedure slows down performance in sql server 2005?
SELECT * FROM Member M
WHERE LOWER(dbo.GetLookupDetailTitle(M.RoleId,'MemberRole')) != 'administrator'
AND LOWER(dbo.GetLookupDetailTitle(M.RoleId,'MemberRole')) != 'moderator'
In this query GetLookupDetailTitle is a user defined function and LOWER() is built in function i am asking about both.
A: Yes.
Both of these are practices to be avoided where possible.
Applying almost any function to a column makes the expression unsargable which means an index cannot be used and even if the column is not indexed it makes cardinality estimates incorrect for the rest of the plan.
Additionally your dbo.GetLookupDetailTitle scalar function looks like it does data access and this should be inlined into the query.
The query optimiser does not inline logic from scalar UDFs and your query will be performing this lookup for each row in your source data, which will effectively enforce a nested loops join irrespective of its suitability.
Additionally this will actually happen twice per row because of the 2 function invocations. You should probably rewrite as something like
SELECT M.* /*But don't use * either, list columns explicitly... */
FROM Member M
WHERE NOT EXISTS(SELECT *
FROM MemberRoles R
WHERE R.MemberId = M.MemberId
AND R.RoleId IN (1,2)
)
Don't be tempted to replace the literal values 1,2 with variables with more descriptive names as this too can mess up cardinality estimates.
A: Using a function in a WHERE clause forces a table scan.
There's no way to use an index since the engine can't know what the result will be until it runs the function on every row in the table.
A: You can avoid both the user-defined function and the built-in by
*
*defining "magic" values for administrator and moderator roles and compare Member.RoleId against these scalars
*defining IsAdministrator and IsModerator flags on a MemberRole table and join with Member to filter on those flags
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Techniques for localizing in ASP.NET?
Possible Duplicate:
What do I need to know to globalize an asp.net application?
The default Visual Studio sample web-site contains:
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master"
AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>Welcome to ASP.NET!</h2>
<p>To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET
Website">www.asp.net</a>.
</p>
<p>
You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&clcid=0x409"
title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
</p>
</asp:Content>
This is a good trial on needed techniques for localizing a web-site. How would you localize these:
*
*<h2>Welcome to ASP.NET!</h2>
*<p>To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET
Website">www.asp.net</a>.</p>
*<p>You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&clcid=0x409"
title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.</p>
Note the use cases
*
*html element:
<H2>Welcome to ASP!</H2>
<H2>Bienvenue sur ASP.NET!</H2>
<H2>ASP.NET xoş gəlmisiniz!</H2>
*text with embedded html (notice how the link moves)
<P>To learn more about ASP.NET visit www.asp.net.</P>
<P>Pour en savoir plus sur www.asp.net visitez ASP.NET.</P>
<P>ASP.NET səfər www.asp.net haqqında daha ətraflı məlumat üçün.</P>
*text with embedded html, with embedded localizable text
<P>You can also find <A title="Documentation on ASP.net">documentation</A></P>
<P>Vous pouvez également trouver de la <A title="Documentation sur ASP.net">documentation</A></P>
<P>Siz həmçinin <A title="ASP.net sənədləşdirilməsi">sənədlərin</A> tapa bilərsiniz</P>
See also
*
*ASP.NET Localization (Quick Reference)
*Globalizing and Localizing ASP.NET Web Pages (Visual Studio)
One could use an asp:Localize element to translate the text in the first example:
<H2><asp:Localize>Welcome to ASP!</asp:Localize></H2>
<H2><asp:Localize>Bienvenue sur ASP.NET!</asp:Localize></H2>
<H2><asp:Localize>ASP.NET xoş gəlmisiniz!</asp:Localize></H2>
problem is this solution falls apart in the next case:
<P><asp:Localize>To learn more about ASP.NET visit www.asp.net.</asp:Localize></P>
<P><asp:Localize>Pour en savoir plus sur www.asp.net visitez ASP.NET.</asp:Localize></P>
<P><asp:Localize>ASP.NET səfər www.asp.net haqqında daha ətraflı məlumat üçün.</asp:Localize></P>
because the localized string cannot contain other HTML elements.
Now it starts to require something like:
<P><asp:Localize>To learn more about ASP.NET visit %s.</asp:Localize></P>
<P><asp:Localize>Pour en savoir plus sur %s visitez ASP.NET.</asp:Localize></P>
<P><asp:Localize>ASP.NET səfər %s haqqında daha ətraflı məlumat üçün.</asp:Localize></P>
And then the html containing the link can be embedded where %s is. But then the localizer must localize fragmented phrases:
*
*To learn more about ASP.NET visit www.asp.net.
becomes
*
*To learn more about ASP.NET visit %s.
and in other languages it pseudo translates to:
*
*To learn more about %s visit ASP.net
*ASP.net visit %s about to learn more
Edit: What is the approved technique to localize items in ASP.net.
A: *
*HTML elements, I usually place just the text within the HTML elements in resx files, rather than the entire HTML structure. I find it makes the localized content more re-usable
*Text with embedded HTML - In your examples, I would put everything other than the <p> tags in my resx files - so the hyperlinks I would keep in the resx files
*Text with embedded HTML - this scenario seems the same as the second, I would use the same approach
Another scenario to consider is when you need to dynamically inject content into a resource string, i.e. "Good afternoon Mr. Smith, how are you doing?" I recommend capturing these with a single resource key such as "Good afternoon {0}, how are you doing?" in order to avoid breaking sentences down into multiple resource keys such as "Good afternoon", and "how are you doing", since other languages don't follow the same grammar rules that English follows.
Sometimes it doesn't make sense to localize individual page fragments as separate resource strings. All of the HTML in the sample page that you've referenced could reside in a separate English text file for instance. Then you could create other language text files as need be. These might be XML files on your file system, or they might be stored as database resources, where you then dynamically load the appropriate language part at runtime. This can help to simplify the translation process and provide a lot more flexibility per language.
I usually localize titles, headings, individual terms, form fields, captions, error messages, etc., as separate resource keys, and often leave entire static pages/content snippets as their own resource fragments, rather than breaking them down into small units.
On the subject of where to persist your resources, you can use .resx, or roll your own (many people use filesystem-based approaches), or database driven. Rick Strahl has shared a great database resource provider if you're interested in persisting all of your resources to database, http://www.west-wind.com/weblog/posts/2009/Apr/02/A-Localization-Handler-to-serve-ASPNET-Resources-to-JavaScript.
A: Regarding the 3rd item (with the link), I once wrote a tiny little class to solve.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Refresh Datagrid automatically when its ItemsSource changed I'm using a datagrid in a UserControl. How can I refresh Datagrid automatically when its ItemsSource changed without using DataGrid.Items.Refresh();
A: What you need to do is use an observable collection.
here is an old but valid example:
http://www.codeproject.com/KB/WPF/WPFDataGridExamples.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Safari browser will not load a ".php" page I am working on a Mac and my website is on a dedicated server - when I try to load a ".php" page, the browser thinks it should download it instead of display it - why is this happening?
A: Make sure php is running on your server.
And also make sure IIS or Apache (or whatever your webserver is) is running as well.
A: Your webserver probably doesn't send the corect MIME-type with PHP-files. Different browsers might handle it differently. If you are sure that the server send the correct headers, check your safari options.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7505492",
"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.