text stringlengths 8 267k | meta dict |
|---|---|
Q: Minimize/Maximize/Close buttons' tooltip and Devexpress lookAndFeel I'm trying to force Minimize/Maximize/Close buttons' tooltips (in ribbonform) to get a look from a lookAndFeel. So far I created a ribbonform, then I placed defaultLookAndFeel component on it ahd I chose an OfficeBlue skin. My ribbon form changed however the tooltips for control buttons(minimize,maximize,close) look the same. I also tried to use DefaultToolTipControler however changing properties on appearance section didn't get any results.
Is there any way to change appearance of tooltips mentioned before?
A: You're probably trying to get rid of the Aero integration.
Set AllowFormGlass to false.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python & P4V: Automating changelist description I have a variable, fulltext, which contains the full text of what I want the description of a new changelist in P4V to be. There are already files in the default changelist.
I want to use python to populate the description of a new changelist (based on default) with the contents of fulltext.
How can this be done. I've tried this:
os.sytem("p4 change -i")
print fulltext
But that doesn't create any new change list at all. I don't know how to tell p4 that I'm done editing the description.
A: If you're trying to write Python programs that work against Perforce, you might find P4Python helpful: http://www.perforce.com/perforce/doc.current/manuals/p4script/03_python.html
A: It is easiest if you have the changelist numbers that you know you are going to change.
#changeListIDNumber is the desired changelist to edit
import P4
p4 = P4.connect()
cl = p4.fetch_changelist(changeListIDNumber)
cl['Description'] = 'your description here'
p4.save_change(cl)
If you are using this for your default changelist, and you do not pre populate your description with anything, you will get an error as there will be no 'Description' key in your changelist dictionary.
A: on shell this works, you may use in any language
echo "Change:new\nClient:myclient\nUser:me\nStatus:new\nDescription:test" | p4 change -i
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: FMS based video chat - Best practices I am working on a video-chat application, with FMS 4.
While it's really easy to make one, thanks to Adobe, I found it hard to make it a good one.
I'm looking for any advice on the server configuration (machine configuration server.xml, applicatio.xml and so on) or on client implementation (bandwidth handling, cam and mic settings...).
Any insight is greatly appreciated
Thanks!
A: My questoion was dircectly answered here:
http://www.adobe.com/devnet/flashmediaserver/articles/real-time-collaboration.html
and here:
http://www.adobe.com/devnet/flashplayer/articles/rtmfp_cirrus_app.html
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Malloc allocates memory more than RAM I just executed a program that mallocs 13 MB in a 12 MB machine (QEMU Emulated!) . Not just that, i even browsed through the memory and filled junk in it...
void
large_mem(void)
{
#define LONGMEM 13631488
long long *ptr = (long long *)malloc(LONGMEM);
long long i;
if(!ptr) {
printf("%s(): array allocation of size %lld failed.\n",__func__,LONGMEM);
ASSERT(0);
}
for(i = 0 ; i < LONGMEM ; i++ ) {
*(ptr+i)=i;
}
free(ptr);
}
How is it possible ? I was expecting a segmentation fault.
A: This is called as Lazy Allocation.
Most OS like Linux have an Lazy Allocation memory model wherein the returned memory address is a virtual address and the actual allocation only happens at access-time. The OS assumes that it will be able to provide this allocation at access-Time.
The memory allocated by malloc is not backed by real memory until the program actually touches it.
While, since calloc initializes the memory to 0 you can be assured that the OS has already backed the allocation with actual RAM (or swap).
Try using callocand most probably it will return you out of memory unless your swap file/partition is big enough to satisfy the request.
A: Sounds like your operating system is swapping pages:
Paging is an important part of virtual memory implementation in most
contemporary general-purpose operating systems, allowing them to use
disk storage for data that does not fit into physical random-access
memory (RAM).
In other words, the operating system is using some of your hard disk space to satisfy your 13 MB allocation request (at great expense of speed, since the hard disk is much, much slower than RAM).
A: Unless the virtualized OS has swap available, what you're encountering is called overcommit, and it basically exists because the easy way to manage resources in a system with virtual memory and demand/copy-on-write pages is not to manage them. Overcommit is a lot like a bank loaning out more money than it actually has -- it seems to work for a while, then things come crashing down. The first thing you should do when setting up a Linux system is fix this with the command:
echo "2" > /proc/sys/vm/overcommit_memory
That just affects the currently running kernel; you can make it permanent by adding a line to /etc/sysctl.conf:
vm.overcommit_memory=2
A: It's called virtual memory which is allocated for your program. It's not real memory which you call RAM.
There is a max limit for virtual memory as well, but it's higher than RAM. It's implemented (and defined) by your operating system.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Adding dynamic height with jQuery I need to calculate available height of an element and add it to a style via jQuery. How to I add the var of the height? Here's where I am at the moment:
var scrolH = $("#box").height() - $(".alert").height() - 100;
$("#container").css({"overflow-y":"scroll", "height": scrolH + "px"});
A: i think You should do:
$("#container").height(scrolH);
$("#container").css({"overflow-y":"scroll"});
A: Even a little bit shorter
$("#container").height(scrolH).css({"overflow-y":"scroll"});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using both MyIsam & Innodb For past few days I was in a great confusion deciding whether to use MyIsam or Innodb, with both having their own pros and cons. My table will have large amount of data with heavy INSERT, UPDATE and SELECT operations.
I decided to create two tables of same structure; tbl_mytbl_innodb(innodb engine) and tbl_mytbl_myisam(myisam engine) I then created two triggers on tbl_mytbl_innodb for INSERT and UPDATE events that will insert/update tbl_mytbl_myisam. So it will always write to tbl_mytbl_innodb and read from tbl_mytbl_myisam.
Is this process correct, or do I need to do it a better way?
A: That's a silly way to go. The only time you should use both in parallel is if you require transactions+foreign keys AND fulltext indexes. You'd use triggers to sync up the fulltextable fields in a MyISAM table, and otherwise keep everything in InnoDB.
There's few usage cases where MyISAM is preferable over InnoDB, and the major one is the lack of fulltext support in InnoDB.
A: I'd say that's the opposite of a correct process. My personal recommendation is use InnoDB for almost all business activities, as it supports transactions... the only use I've found for MyISAM is full text searches (dunno why that's not available in InnoDB) but I freely admit that's a personal preference.
Using triggers to synchronize the same data across multiple tables can't be good. Define your business requirements and choose an engine. If you need to use the other engine for a specific requirement, define that and populate a subset of data as necessary.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Merging a git stash with the current head I did a git stash on production but then others pushed more changes to the repository. So is there a way merge them both together. I can see the changes in the stash but not in the current head.
Git fsck shows
git fsck
dangling tree b00308a00025bbe3eaa370b326d82dae5b9403cc
dangling tree e714ea6c807bbdd039abfe8a8fb779c02403c3b3
dangling tree cc1e0f3768af3e5cb22fdfde7603f663c1812d78
dangling tree f51f1aa3298e21affb0b2ee31343f2c47df438c3
dangling tree b530b1163c677de735d82d7c11081921b35807ae
dangling tree bfb862564922f45cc272daac3e1d131fd254a8ed
dangling tree cdd02c02d05dfbc928c4ce9123fc4c360299395c
dangling tree b851786925e57bb2d7e71badefc5171b9110ccd5
dangling tree ae5caf6ede4e4b5f9c344ac3e749aaed6bee5e96
dangling tree e56ad067c775f25d18cab3520f3f1add2731c67d
dangling tree 1871498602802cbe324ed746395ac300884622ce
dangling tree c0f61e31611cf5fbed159737e9f04b9b214ed663
dangling tree 7bf8bdd7e6cca37cd1929473d50d2914cc1f94c1
Thanks.
A: One of the points of stash is that you can reapply it anywhere. You stashed away your changes, so they are stored as relative to the commit that was checked out then, but now that you've checked out a different commit, you're free to use git stash apply or git stash pop to apply the stashed changes. (pop deletes the stash once they're successfully applied; apply leaves it.)
Of course, if things have changed significantly, the stashed changes may no longer apply cleanly. Git will treat this as a merge conflict, and you can resolve it as you would any other merge conflict.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Placing JSON values from a json response, to HTML elements Every 2 seconds, I send out a POST that returns:
[{"a":false,"i":"58","b":"sergio","p":"0,22","t":15},
{"a":false,"i":"59","b":"sergio","p":"0,23","t":15},
{"a":false,"i":"60","b":"sergio","p":"0,14","t":15},
{"a":false,"i":"61","b":"sergio","p":"0,07","t":15}]
I have a Javascript function that captures this information and I'd like it to also parse the JSON and place the values into their appropriate elements.
function updateauctions(response) {
//Parse JSON and place into HTML elements.
//For debug purposes.
alert(response);
}
I'm using jQuery and I'd like to know how to fetch JSON values, and place them into HTML elements.
An example of a div .auctionbox:
<div id="60" class="auctionbox gold">
//Other things here.
</div>
For example, I have n amount of divs with class .auctionbox and each one of those divs also has an ID of #i. So each JSON object corresponds to a single .auctionbox. How would I place the p value of the JSON into the appropriate #i, .auctionbox?
With this simple example, I can start working on other requirements, I just need a little nudge. :)
Thank you.
A: http://jsfiddle.net/mA4Ye/4/
Solution with using the template if you need to perform some specific html + css
html
<div id="data">
<div class="template auctionbox"></div>
</div>
js
var json = '[{"a":false,"i":"58","b":"sergio","p":"0,22","t":15},' +
'{"a":false,"i":"59","b":"sergio","p":"0,23","t":15},' +
'{"a":false,"i":"60","b":"sergio","p":"0,14","t":15},' +
'{"a":false,"i":"61","b":"sergio","p":"0,07","t":15}]';
var data = $.parseJSON(json);
var $template = $('.template');
$(data).each(function() {
var $element = $template.clone().removeClass('template').appendTo('#data');
$element.attr('id', this.i);
$element.html(this.p);
});
A: setInterval(function() {
$.getJSON('your-json-url', function(json) {
$(json).each(function() {
$('#'+this.i).html(this.p);
});
});
}, 2000);
hope this helps
A: var obj = $.parseJSON(data); // data is the returned JSON string
for( var i in obj){
$('.auctionbox'+i).html( obj[i].a );
}
That would add the contents of obj.a into a div with the class .auctionbox0, auctionbox1, etc.
Also, I'm not sure you an use numbers as IDs on HTML elements.
A: You could do:
var response = [{"a":false,"i":"58","b":"sergio","p":"0,22","t":15},
{"a":false,"i":"59","b":"sergio","p":"0,23","t":15},
{"a":false,"i":"60","b":"sergio","p":"0,14","t":15},
{"a":false,"i":"61","b":"sergio","p":"0,07","t":15}];
function updateauctions(response) {
for (i=0; i<response.length; i++){
//if the ids are unique just leave the class alone and select the div with the id
var id = 'div#'+response[i].i;
$(id).html(response[i].p);
//For debug purposes.
}
}
A: assuming the json response is already parsed to a js object (using dataType: "json" with $.ajax() or setting the optional 4th parameter to "json" with $.get() or $.post()), you can loop through the json array using $.each(), then navigate to each div to set it's value.
$.each(response,function(i,item) {
$("#id-" + item.i).html(item.p);
});
Note: id's cannot start with a number, they must start with an alpha character. because of this, i assumed you would add id- to the id's.
Edit: here's how i would suggest doing it every 2 seconds:
var timer;
(function ajaxInterval(){
$.getJSON(url,data,function(){
timer = setTimeout(function(){
ajaxInterval();
},2000);
});
})();
A: I think you want something like this inside your function:
$.each(response, function(key, item) {
$('#' + item.i).text(item.p);
});
A: I second Samich's answer and say use a templating engine that specializes in converting json to html like json2html
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://json2html.com/js/jquery.json2html-2.3-min.js"></script>
<div id='list'></div>
<script>
var json =
[{"a":false,"i":"58","b":"sergio","p":"0,22","t":15},
{"a":false,"i":"59","b":"sergio","p":"0,23","t":15},
{"a":false,"i":"60","b":"sergio","p":"0,14","t":15},
{"a":false,"i":"61","b":"sergio","p":"0,07","t":15}];
//Transform used to create the div
var transform =
{tag:'div',id:'.i',class:'actionbox gold',children:[
{tag:'span',html:'.b'},
{tag:'span',html:' + other stuff'}
]};
//Render the json into a list of divs
$('#list').json2html(json, transform);
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Zipping files and HTML5 File API Is it possible to bundle files into a zip file using the File API, or another part of the HTML5 suite? If so, are there any example implementations available? If not, is this something likely to be supported by modern browsers in the next year or two?
A: I think this is what you might have been looking for. It's probably too late to help you, but I'll just leave this here for anyone else who might be interested.
http://stuartk.com/jszip/
A: While I don't know of anything built into HTML5 currently, I've seen some projects that are starting to touch on this in JavaScript. You may want to take a look at this project, which allows you to read the contents of a zip file, and if it's compressed using the Deflate algorithm, can unzip them.
A: Another option which works really well with plain javascript is a zip API called sendzip. It allows you to create zip file on the fly and streaming it to users.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Converting a string into a function that is not in a namespace in clojure Here is the sample code I want to get to work:
(letfn [(CONC [f] f)
(CONT [f] (str "\newline" f))]
((voodoo "CONC") "hamster"))
Is there some voodo that will make it call the CONC function with hamster as the parameter? That is, is there some way to convert the string "CONC" into a function that is not bound to a namespace but rather to a local binding?
EDIT:
To be clearer, the way this will be called is:
(map #((voodoo (:tag %)) (:value %))
[
{:tag "CONC" :value "hamster"}
{:tag "CONT" :value "gerbil"}
]
)
A: I'd probably solve this by creating a map of functions indexed by strings:
(def voodoo
{"CONC" (fn [f] f)
"CONT" (fn [f] (str "\newline" f))})
Then your desired code should work directly (exploiting the fact that a map is a function that looks up it's argument)
(map #((voodoo (:tag %)) (:value %))
[
{:tag "CONC" :value "hamster"}
{:tag "CONT" :value "gerbil"}
]
)
Note that the functions here are fully anonymous - you don't need them to be referenced anywhere in the namespace for this to work. In my view this is a good thing, because unless you also need the functions somewhere else then it's best to avoid polluting your top-level namespace too much.
A: No. Eval does not have access to the local/lexical environment, ever.
Edit: This is not a very good answer, and not really accurate either. You could write voodoo as a macro, and then it doesn't need runtime access to the lexical environment, just compile-time. However, this means it would only work if you know at compile time that the function you want to call is x, and so it wouldn't be very useful - why not just type x instead of (voodoo "x")?
(defmacro voodoo [fname]
(symbol fname))
(letfn [(x [y] (inc y))]
((voodoo "x") 2))
;; 3
(letfn [(x [y] (inc y))]
(let [f "x"]
((voodoo f) 2)))
;; error
A: Well, it's sort of possible:
(defmacro voodoo [s]
(let [env (zipmap (map (partial list 'quote) (keys &env))
(keys &env))]
`(if-let [v# (~env (symbol ~s))]
v#
(throw (RuntimeException. "no such local")))))
...and now we can do weird stuff like this:
user> (defn example [s]
(letfn [(foo [x] {:foo x})
(bar [x] {:bar x})]
((voodoo s) :quux)))
#'user/example
user> (example "foo")
{:foo :quux}
user> (example "bar")
{:bar :quux}
user> (example "quux")
; Evaluation aborted.
user> *e
#<RuntimeException java.lang.RuntimeException: no such local>
That "Evaluation aborted" means an exception was thrown.
You could also replace the throw branch of the if in voodoo with (resolve (symbol ~s)) to defer to the globals if no local is found:
(defmacro voodoo [s]
(let [env (zipmap (map (partial list 'quote) (keys &env))
(keys &env))]
`(if-let [v# (~env (symbol ~s))]
v#
(resolve (symbol ~s)))))
...and now this works with definition of example as above (though note that if you are experimenting at the REPL, you will need to recompile example after redefining voodoo):
user> (defn quux [x] {:quux x})
#'user/quux
user> (example "quux")
{:quux :quux}
Now, this is an abuse of Clojure's facilities which one would do well to try to do without. If one cannot, one should probably turn to evalive by Michael Fogus; it's a library which provides an "eval-with-locals" facility in the form of an evil function and a couple of utilities. The functionality seems to be well factored too, e.g. something like the ~(zipmap ...) thing above is encapsulated as a macro and evil there appears to be almost a drop-in replacement for eval (add the env parameter and you're good to go). I haven't read the source properly, but I probably will now, looks like fun. :-)
A: Im not really clear what you are asking for so i'll try a couple answers:
if you have a string that is the name of the function you wish to call:
(def name "+")
((find-var (symbol (str *ns* "/" name))) 1 2 3)
this would give voodoo a deffinition like this:
(defn voodoo [name args] (apply (find-var (symbol (str *ns* "/" name))) args))
#'clojure.core/voodoo
clojure.core=> (voodoo "+" [1 2 3])
6
clojure.core=>
this assumes your function is in the current namepace ns.
if you want to turn a string into a function you could use this pattern
(let [f (eval (read-string "(fn [] 4)"))] (f))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: how to access user id from cookie using javascript: Rails, Devise, Page Caching I have various image galleries for different users. For the most part the complete page may be cached. However I also want the following features:
*
*If a user is logged in and visiting his own gallery, then the user
can see an "x" delete link overlaying each image.
*If a user is logged in and on someone else's gallery, then they can
see overlays "thumb up", "thumb down" voting for each image.
*If a user is NOT logged in, they can see the overlays for
voting,
however clicking on them will pop-up a login dialog.
The approach I have come up with is this:
*
*In the server side erb template I will always generate the voting
links and delete links regardless of login status, but I will have
them hidden with css by default.
*I will then reveal them using js
depending on the user's login status.
The question is... what is the best way of determining the user's login status on a cached page? Can I use cookies over cached pages?
Would it work if I had a piece of javascript on the cached page that checked for a cookie value similar to this:
if ($.cookie("user_id") == 23) { //if user is owner of this gallery...
//reveal delete links, hide voting links
}
I hate to build something special to set that cookie... there should already exist some type of DEVISE cookie right? How do I access it?
A: Use $.cookie("user_id") to set the cookie, use $.cookie("user_id", "23") to set a cookie. You should beware of unauthenticated abuse, though: Every credential-less request that requires authentication should be rejected, or the purpose of logging in will be defeated.
If you want to check for the available cookies on your website, use this bookmarklet:
javascript:alert(document.cookie)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: will limiting dynamic urls with robots.txt improve my SEO ranking? My website has about 200 useful articles. Because the website has an internal search function with lots of parameters, the search engines end up spidering urls with all possible permutations of additional parameters such as tags, search phrases, versions, dates etc. Most of these pages are simply a list of search results with some snippets of the original articles.
According to Google's Webmaster-tools Google spidered only about 150 of the 200 entries in the xml sitemap. It looks as if Google has not yet seen all of the content years after it went online.
I plan to add a few "Disallow:" lines to robots.txt so that the search engines no longer spiders those dynamic urls. In addition I plan to disable some url parameters in the Webmaster-tools "website configuration" --> "url parameter" section.
Will that improve or hurt my current SEO ranking? It will look as if my website is losing thousands of content pages.
A: This is exactly what canonical URLs are for. If one page (e.g. article) can be reached by more then one URL then you need to specify the primary URL using a canonical URL. This prevents duplicate content issues and tells Google which URL to display in their search results.
So do not block any of your articles and you don't need to enter any parameters, either. Just use canonical URLs and you'll be fine.
A: As nn4l pointed out, canonical is not a good solution for search pages.
The first thing you should do is have search results pages include a robots meta tag saying noindex. This will help get them removed from your index and let Google focus on your real content. Google should slowly remove them as they get re-crawled.
Other measures:
In GWMT tell Google to ignore all those search parameters. Just a band aid but may help speed up the recovery.
Don't block the search page in the robots.txt file as this will block the robots from crawling and cleanly removing those pages already indexed. Wait till your index is clear before doing a full block like that.
Your search system must be based on links (a tags) or GET based forms and not POST based forms. This is why they got indexed. Switching them to POST based forms should stop robots from trying to index those pages in the first place. JavaScript or AJAX is another way to do it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Conditional invoking of a trigger I have triggers on a table but I want to invoke them only when the table is altered by an application directly (.NET application) and not if it is altered because of some other stored proc which may be in same database or an another database. Is there anything like ClientID or something which could help me distinguish and invoke trigger conditionally.
Thanks.
A: The trigger will always be invoked but obviously you can just put conditional logic in to RETURN if you don't want additional code to run.
A couple of functions which might help are APP_NAME() or CONTEXT_INFO()
Failing that you could try
SELECT *
FROM sys.dm_exec_sessions
WHERE session_id = @@SPID
to see if anything suitable is there.
Don't rely on these for security however as they are easily manipulable by the client.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is used on Lion version for SMB sharing? I know that Apple has changed implementation for SAMBA sharing on Lion Version. I am trying to share folder programmatically. IT works on Snow Leopard.
But it doesn't on Lion, can you give me a clue, what Apple used for SMB sharing on Lion version? And where does it store information about shared folders using SMB.
A: Here is a report from AppleInsider.
Apple has replaced SAMBA with their own proprietary internally-developed code, called SMBX, apparently largely due to not being able to comply with the SAMBA project's open-source licensing requirements.
I am not aware of any documentation released by Apple, but I don't have a developer account.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: using SquishIt in ASP.NET MVC 3 I'm trying to use SquishIt for minifying CSS and Javascripts in ASP.NET MVC 3 project.
When I use Render method:
.Render("~/content/themes/base/combined_#.css");
css is generated with random number instead of #, but link to css file is not generated and I need to insert it manually to cshtml file:
<link href="~/content/themes/base/combined_#.css" rel="stylesheet" type="text/css" />
but I don't know this random number, added to file name.
Without # it works fine.
But I have impression that Render should automatically generate css link according to this article:
http://www.codethinked.com/squishit-the-friendly-aspnet-javascript-and-css-squisher
Am I correct?
A: The following works great for me:
@Html.Raw(Bundle.JavaScript()
.Add("~/scripts/jquery-1.5.1.js")
.Add("~/scripts/jquery.unobtrusive-ajax.js")
.ForceRelease()
.Render("~/scripts/combined_#.js")
)
@Html.Raw(
Bundle.Css()
.Add("~/content/site.css")
.Add("~/content/site2.css")
.ForceRelease()
.Render("~/content/combined_#.css")
)
it emits:
<script type="text/javascript" src="/scripts/combined_B8A33BDE4B3C108D921DFA67034C4611.js"></script>
<link rel="stylesheet" type="text/css" href="/content/combined_97A4455A9F39EE7491ECD741AB4887B5.css" />
and when I navigate to the corresponding url the correct squished and combined resource is obtained.
There is also a Contrib project which provides a base Razor page to integrate SquishIt in an ASP.NET MVC application.
A: Or add a reference to the SquishIt.Mvc assembly and use the .MvcRender method
eg.
@using SquishIt.Framework
@using SquishIt.Mvc
@(Bundle.JavaScript()
.Add("~/scripts/jquery-1.5.1.js")
.Add("~/scripts/jquery.unobtrusive-ajax.js")
.ForceRelease()
.MvcRender("~/scripts/combined_#.js")
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Obtain website's description (meta) from ODP DMOZ.org using PHP I am working on a php website. What I want to do is to retireve description or meta information of websites. What I hope to do is to obtain the information from dmoz.org, is there a way of doing such a thing ?
If not, then what are other alternatives ? cURL ?
Many thanks,
EDIT:
Apparently my question wasn't clear. dmoz.org is open directory that gives you information about websites. The information given is different than the meta tags from the website itself. So what i want to do is getting such information..
A: PHP has a built-in function for extracting the meta information:
$tags = get_meta_tags('http://dmoz.org');
print_r($tags);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating a self updating form I'm creating a form on a web page, but I want that form to change as a user inputs values.
Example: If we have a drop down menu: ObjectType
And someone chooses Cars when that selected I'd want new options below to show up. Say, Make, Model, Year, & Notes.
Whereas, if that person chooses Vegetables then maybe all I want is a checkbox for Root Vegetables.
My question is what is the best way to do this. My form is pretty intricate and is going to have perhaps 20 different possible set ups, but I want those set ups to be sorted. I used appendChild() with AJAX requests, but I just ended up with out of order fields. And on top of that, the occasional slow connection keeps an individual waiting for a field to show up.
Rather than loading HTML pages with these form objects (technically part of a table), should I be keeping all of this stuff in an array? Is it possible to just load one HTML page or XML object and use selectElementById() on that result after it has been saved?
The objects I'm loading are rows, here's an example of one and what it would need to be able to do:
<td>
<strong>Abilities:</strong>
</td>
<td>
<textarea
id ='abilities'
name="abilities"
style="width:100%" rows="4"
onchange='userCreation.updateAbilities()'
onkeyup='userCreation.updateAbilities()'>
</textarea>
</td>
I have a table in my page, I was creating a new tr element with JavaScript, setting this as the innerHTML and then appending the child. Is there a better way to do this?
A: I would just put all of the form elements in a page, and hide the ones you're not using with CSS. That way you maintain order, and don't have to wait for fields to show up. It will slightly slow down page load time, but make your life a lot simpler.
Otherwise, I'd store the name (or whatever) of each field in an array or object, and when it comes time to AJAX load it, look up its position first and put it there.
A: Just have the entire for in the page and just change the visibility of different sections, based on user interaction instead of dynamically loading elements via AJAX.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does SciPy return negative p-values for extremely small p-values with the Fisher-exact test? I've noticed that the Fisher-exact test in SciPy returns a negative p-value if the p-value is extrememly small:
>>> import scipy as sp
>>> import scipy.stats
>>> x = [[48,60],[3088,17134]]
>>> sp.stats.fisher_exact(x)
(4.4388601036269426, -1.5673906617053035e-11)
In R, using the same 2x2 contingency table:
> a = matrix(c(48,60,3088,17134), nrow=2)
> fisher.test(a)
p-value = 6.409e-13
My question is 1) why does SciPy return a negative p-value? 2) how can I use SciPy to generate the correct p-value?
Thanks for the help.
A: Fisher's exact test uses the hypergeometric distribution.
The version of scipy you are using uses an implementation of the hypergeometric distribution that is not very precise. This is a known problem and has been fixed in the scipy repository.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Getting name of object as a string in JavaScript
Possible Duplicate:
How do I enumerate the properties of a javascript object?
Javascript: Getting a Single Property Name
Given a JavaScript object or JSON object such as:
{
property: "value"
}
How can one get the word property as a string?
A: var obj = {
property: "value"
};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
alert("key = " + key + ", value = " + obj[key]);
}
}
A: for(var i in obj) alert(i);//the key name
A: One brutal way would be to use .toString on the object and then extract the name. But i'm sure there would be better ways :)
A: Use Object.keys()[docs].
var key = Object.keys( my_obj )[ 0 ]; // "property"
It returns an Array of the enumerable keys in that specific object (not its prototype chain).
To support older browsers, include the compatibility shim provided in the MDN docs.
if (!Object.keys) {
Object.keys = function (o) {
if (o !== Object(o)) throw new TypeError('Object.keys called on non-object');
var ret = [],
p;
for (p in o) if (Object.prototype.hasOwnProperty.call(o, p)) ret.push(p);
return ret;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Devise: redirect back after unsuccessful login attempt Using Rails 3.1 and Devise 1.4.2
I'm new to using Devise and the site I'm working on has login forms embedded in many pages across the site. When a user attempts to login and they are rejected, the default behavior is to redirect back to users/sign_in.
I would like to redirect back (to request.referrer), but I can't seem to figure out how/where to make this happen.
I tried overriding the Devise::SessionsController with my own Create action:
# POST /resource/sign_in
def create
resource = warden.authenticate!(:scope => resource_name)
set_flash_message(:notice, :signed_in) if is_navigational_format?
sign_in_and_redirect(resource, request.referrer)
end
but this also seems to redirect to users/sign_in.
I have confirmed that my custom SessionsController is receiving the request
Thank you
A: Please look at this devise wiki page:
https://github.com/plataformatec/devise/wiki/How-To%3A-Redirect-to-a-specific-page-when-the-user-can-not-be-authenticated
I think that you can find all necessary information there :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python OptParser I am trying to input a path using optparser in python. Unfortunately this piece of code keeps showing an error.
import optparse,os
parser = optparse.OptionParser()
parser.add_option("-p","--path", help = "Prints path",dest = "Input_Path", metavar = "PATH")
(opts,args) =parser.parse_args()
print os.path.isdir(opts.Input_Path)
Error :-
Traceback (most recent call last):
File "/Users/armed/Documents/Python_Test.py", line 8, in
print os.path.isdir(opts.Input_Path)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.py", line 41, in isdir
st = os.stat(s)
TypeError: coercing to Unicode: need string or buffer, NoneType found
Any help is much appreciated !
A: That error is because opts.Input_Path is None, instead of being your path string/unicode.
Are you sure you are calling the script correctly? You should probably put in some error checking code in any case to make sure that if a user doesnt put -p, the program won't just crash.
Or, change it to a positional argument to make it 'required' by optparse:
http://docs.python.org/library/optparse.html#what-are-positional-arguments-for
Edit: Also optparse is deprecated, for a new project you probably want to use argparse.
A: I copied your script and ran it. Looks like you call your script in a wrong way:
$ python test.py /tmp
Traceback (most recent call last):
File "test.py", line 8, in <module>
print os.path.isdir(opts.Input_Path)
File "/usr/lib/python2.6/genericpath.py", line 41, in isdir
st = os.stat(s)
TypeError: coercing to Unicode: need string or buffer, NoneType found
but
$ python test.py --path /tmp
True
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to add button in the last cell of table? I am using tableView .
Now I want to make a button in my last cell??
can anyone tell me how to do this??
other data I am getting by an array . I want to add the button after the last element of the table
A: Add your button as a tableFooterView of the table, this is much simpler than trying to use a custom cell for the last row.
A: i am not having my mac right now trying to guide you:
1.Implement CellForRowAtIndexPath method.
2.u can use something like
`if (indexpath.row==[array count])
{
//make button here with cgrectmake and add to the view
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect/custom/...];
[button addTarget:self
action:@selector(aMethod:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[cell addSubview:button ];
}`
hope it help you
A: Is there any specific reason to display the button when user scroll till end of the last row of the table,
if yes:
then you can add your button in tableFooterView
else :
you can reduce the height of your table view in such a way so you can
add a custom view contains your button and place your custom view
after your tableView
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I change the initial loading image How can I change the initial image when app is loading. Currently it is set to default.jpg but I don't know where in the project I can change it.
Thanks
A: You change it in the Info.plist. It is also my understanding that this image must be a .png file, not a .jpg.
A: You are looking for file called 'Default.png'. In xCode it will likely be in your Resources folder.
If you are supporting anything other than a regular iPhone (so retina or iPad) you will need extra Launch images
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: pdf to chm handling libraries for python3 I've tried to find a software for pdf to chm conversion to convert my pdf e-books to chm, but I ended up disappointed.
So, as a pythonian, I decided to create my own program to convert pdf files to chm, however, all pdf/chm libraries I found are python2 libraries.
Are there python 3 libraries to handle pdf/chm files?
A: If you want to write CHM, then afaik only Free Pascal (and therefore Delphi with minimal effort) has a free CHM generator library.
All other tools use the Microsoft commandline tool behind the scenes.
For reading there is chmlib, I assume there is some python wrapper for it somewhere.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Malloc performance in a multithreaded environment I've been running some experiments with the openmp framework and found some odd results I'm not sure I know how to explain.
My goal is to create this huge matrix and then fill it with values. I made some parts of my code like parallel loops in order to gain performance from my multithreaded enviroment. I'm running this in a machine with 2 quad-core xeon processors, so I can safely put up to 8 concurrent threads in there.
Everything works as expected, but for some reason the for loop actually allocating the rows of my matrix have an odd peak performance when running with only 3 threads. From there on, adding some more threads just makes my loop take longer. With 8 threads taking actually more time that it would need with only one.
This is my parallel loop:
int width = 11;
int height = 39916800;
vector<vector<int> > matrix;
matrix.resize(height);
#pragma omp parallel shared(matrix,width,height) private(i) num_threads(3)
{
#pragma omp for schedule(dynamic,chunk)
for(i = 0; i < height; i++){
matrix[i].resize(width);
}
} /* End of parallel block */
This made me wonder: is there a known performance problem when calling malloc (which I suppose is what the resize method of the vector template class is actually calling) in a multithreaded enviroment? I found some articles saying something about performance loss in freeing heap space in a mutithreaded enviroment, but nothing specific about allocating new space as in this case.
Just to give you an example, I'm placing below a graph of the time it takes for the loop to finish as a function of the number of threads for both the allocation loop, and a normal loop that just reads data from this huge matrix later on.
Both times where measured using the gettimeofday function and seem to return very similar and accurate results across different execution instances. So, anyone has a good explanation?
A: You are right about vector::resize() internally calling malloc. Implementation-wise malloc is fairly complicated. I can see multiple places where malloc can lead to contention in a multi-threaded environment.
*
*malloc probably keeps a global data structure in userspace to manage the user's heap address space. This global data structure would need to be protected against concurrent access and modification. Some allocators have optimizations to alleviate the number of times this global data structure is accessed... I don't know how far has Ubuntu come along.
*malloc allocates address space. So when you actually begin to touch the allocated memory you would go through a "soft page fault" which is a page fault which allows the OS kernel to allocate the backing RAM for the allocated address space. This can be expensive because of the trip to the kernel and would require the kernel to take some global locks to access its own global RAM resource data structures.
*the user space allocator probably keeps some allocated space to give out new allocations from. However, once those allocations run out the allocator would need to go back to the kernel and allocate some more address space from the kernel. This is also expensive and would require a trip to the kernel and the kernel taking some global locks to access its global address space management related data structures.
Bottomline, these interactions could be fairly complicated. If you are running into these bottlenecks I would suggest that you simply "pre-allocate" your memory. This would involve allocating it and then touching all of it (all from a single thread) so that you can use that memory later from all your threads without running into lock contention at user or kernel level.
A: Memory allocators are definitely a possible contention point for multiple threads.
Fundamentally, the heap is a shared data structure, since it is possible to allocate memory on one thread, and de-allocate it on another. In fact, your example does exactly that - the "resize" will free memory on each of the worker threads, which was initially allocated elsewhere.
Typical implementations of malloc included with gcc and other compilers use a shared global lock and work reasonably well across threads if memory allocation pressure is relatively low. Above a certain allocation level, however, threads will begin to serialize on the lock, you'll get excessive context switching and cache trashing, and performance will degrade. Your program is an example of something which is allocation heavy, with an alloc + dealloc in the inner loop.
I'm surprised that an OpenMP compatible compiler doesn't have a better threaded malloc implementation? They certainly exist - take a look at this question for a list.
A: Technically, the STL vector uses the std::allocator which eventually calls new. new in its turn calls the libc's malloc (for your Linux system).
This malloc implementation is quite efficient as a general purpose allocator, is thread-safe, however it is not scalable (the GNU libc's malloc derives from Doug Lea's dlmalloc). There are numerous allocators and papers that improve upon dlmalloc to provide scalable allocation.
I would suggest that you take a look at Hoard from Dr. Emery Berger, tcmalloc from Google and Intel Threading Building Blocks scalable allocator.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: MySQL INSERT IGNORE result (was the record added or not)? I'm using VB.NET with MySQL and would like to know if there's a way to know if an INSERT IGNORE sql has added a new record to DB or not.
Given a Table (tblA) with one column (col1) and 1 record ('foo')
-------
| col1 |
-------
| foo |
-------
The sql "INSERT IGNORE INTO tblA VALUES ('foo');" would silent fail, i.e no record added
but sql "INSERT IGNORE INTO tblA VALUES ('bar');" would succed, inserting a new record.
So i need to be aware of the result...
suggestions?
Thx
Paulo Bueno.
A: I'm not a VB.NET person, but you want the equivalent of mysql_affected_rows. This will be 1 if the record was inserted, and zero otherwise. Additional queries aren't necessary.
A: You can query for the number of rows in the table before and after the INSERT operation, and check if the results differ. If they do, the operation did insert a row.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: OAuth 2.0 (Oct 1st) and Encrypted Access Token I am trying to get clarity on whether our app will be able to connect after Oct 1st.
If I enable the Encrypted Access Token migration (via the advanced settings menu in the Facebook Developers app) and my site can still connect, does that mean that it will still work on October 2nd?
The description of that migration is:
"Enabling confirms that your app is migrated to OAuth 2.0 and accepts an encrypted access token."
A: Going off of this https://developers.facebook.com/blog/post/561/ developer blog post, you should be fine. The only setting (as far as I can tell) that they are going to force is "Upgrade to Requests 2.0".
You will also need to add a "Secure Canvas URL" and a "Secure Page Tab URL", if you haven't already.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to estimate relative performance of CUDA gpus? How can I estimate the cuda performance of cards that I don't own, ie. new cards?
For instance I found an incomplete Cuda example and the author wrote, that it takes him 0,7 s on his GF 8600 GT. But on my Quadro it takes 1,7s.
My question is: Is the code which I used to fill the gaps faulty or is the GF 8600 really twice as fast?
The kernel is memory bound, but my card has an higher memory bandwidth. I don't know what conclusions to draw from this.
Name Quadro FX 580 GeForce 8600 GT
CUDA Cores 32 32
Core clock (MHz) 450 540
Memory clock (MHz) 400 700
Memory BW (GB/s) 25.6 22.4
Shader Clock (MHz) ???? 1180
A: Just want to provide you with some pointers that may be possible sources of error. Firstly, use cudaEvents to time your code, not cuda profiler as cudaEvents is more accurate. Secondly, please check what the author is measuring; is he only talking about the computation time, or is he also considering the time to transfer data to and from the GPU. Are you measuring the same time?
Secondly, the cuda architecture is changing quite fast. For example, for cards with cc 1.x, it is suggested that we should use shared memory to get better performance; however, for cards with cc 2.x, there is a L1 cache with each multiprocessor that makes global memory accesses quite fast. So, you may aslo want to compare the architecture of the two cards and their compute capabilities.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Magento use models to store/transfer data Lets say I create a table object in magento -
$model = Magento::getModel('table1')
$model->getCollection()->getFirstItem->setname('newname');
But I dont save it . I dont want to store it in db now.
Now I do
$model2 = Mage::getSingleton('table1')
# It should return same table object.
$name = $model->getCollection()->getFirstItem->getname();
I dont get $name as newname, above line fires a sql and gets the name from DB, logically if I am getting same object from singleton then I should be able to retrieve the $name value as newname.
A: The first request for your model uses getModel. This retrieves an instance model.
The second request for your model users getSingleton. This instantiates an instance model and registers it as a singleton. From this point on, future requests to getSingleton or getModel will return the same object. However, models instantiated with getModel prior to registers the model as a singleton will maintain their instance state.
"Works as Designed"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JSON ARRAY Retrieve I have an Array thats pulling back about 20 sets of items from a JSON FILE:
$.getJSON('jsonfile.json', function(data){
var variable = data.twenty_items;
But I only wanted lets say 5 to be retrieved
-Or maybe i wanted only 10 to be called back
can someone help me with this..How do i approach this?
A: You can ignore the extra items in your code.
For example:
arr = arr.slice(0, 5);
If you want to save the bandwidth, you'll need to write a server-side script that parses the JSON and returns a subset of it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I use other directory to store session data I'm new to PHP, so I don't know how to change default (/temp/) directory to store session data. eg I want to store all session() data in a seperate directory called (/root/sceret_data/). Do I need to change it in .htaccess ? I've no root access as I.m on shared host.
Any help with example please ?
A: You can set the path with this PHP function:
session_save_path();
http://at.php.net/manual/en/function.session-save-path.php
The path /root is not the best idea. PHP have no write access there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rewrite Javascript path String In Javascript, I have a string for a path that looks like:
/xxx:Level1/yyy:Level2/xxx:Level3/ccc:Level4
The prefix may or may not be there for each level. I need to create a new string which eliminates the prefix on each folder level, something like:
/Level1/Level2/Level3/Level4
OK. I've done something like the following, but I think perhaps with regex it could be made more compact. How could I do that?
var aa = "/xxx:Level1/yyy:Level2/xxx:Level3/ccc:Level4"
var bb = aa.split("/").filter(String);
var reconstructed = "";
for( var index in bb )
{
var dirNames = bb[index].split(":");
if(dirNames.length==1) reconstructed += "/" + dirNames[0];
else if(dirNames.length==2) reconstructed += "/" + dirNames[1];
}
A: You can use regex like this:
var str = "/xxx:Level1/yyy:Level2/xxx:Level3/ccc:Level4";
var out = str.replace(/\/[^:\/]+:/g, "/");
alert(out);
This matches:
/
followed by one or more characters that is not a : or a /
followed by a :
and replaces all that with a / effectively eliminating the xxx:
Demo here: http://jsfiddle.net/jfriend00/hbUkz/
A: Like this:
var bb = aa.replace(/\/[a-z]+:/g, '/');
Change the [a-z] to include any characters that might appear in the prefix, or just use [^\/:].
A: var a = "/xxx:Level1/yyy:Level2/xxx:Level3/ccc:Level4";
var b = a.replace(/\/[^\/]*:/g, "/");
A: aa = aa.replace(/\/[^:\/]\:/g, "/");
This function will replace every occurence of "/xxx:" by "/" using a RE, where xxx: is a prefix.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: memory deallocation problem of an object I hava a class
class vlarray {
public:
double *p;
int size;
vlarray(int n) {
p = new double[n];
size = n;
for(int i = 0; i < n; i++)
p[i] = 0.01*i;
}
~vlarray() {
cout << "destruction" << endl;
delete [] p;
size = 0;
}
};
when I use in main
int main() {
vlarray a(3);
{
vlarray b(3);
b.p[0] = 10;
for(int i = 0; i < 3; i++) {
cout << *(b.p+i) << endl;
}
a = b;
} // the magic happens here deallocation of b
for(int i = 0; i < 3; i++) {
cout << *(a.p+i) << endl;
return 0;
}
when b deallocated smth happens to a .. what is the problem, why that problem occurs and how to avoid such type of problems?
A: There seems to be some confusion amongst the existing answers on this question, so I am going to jump in.
Immediate issue
Your primary issue is that you have not defined your own copy assignment operator. Instead, the compiler generates a naive one for you, so that when you run a = b, the pointer inside b is copied into a. Then, when b dies and its destructor runs, the pointer now inside a is no longer valid. In addition, a's original pointer has been leaked.
Your own copy assignment operator will need to delete the existing array, allocate a new one and copy over the contents from the object you're copying..
More generally
Going further, you will also need to define a few other things. This requirement is neatly summed-up as the Rule of Three (C++03) or Rule of Five (C++11), and there are plenty of explanations online and in your favourite, peer-recommended C++ book that will teach you how to go about satisfying it.
Or, instead...
Better still, you could start using an std::vector instead of manually allocating everything, and avoid this entire mess:
struct vlarray {
std::vector<double> p;
vlarray(int n) {
p.resize(n);
for(int i = 0; i < n; i++)
p[i] = 0.01*i;
}
};
A: You need to follow the Rule of Three in C++03 and Rule of Five in C++11.
Background and Basis of these Rules:
Whenever your class has an pointer member with an dynamic memory allocation, and whenever another object is created from this existing object by using any of the Copying Functions(Copy constructor & Copy Assignment Operator in c++03) unless you overload these two make a Deep Copy of the member pointer, the newly created object will keep pointing to the memory allocation of the parent object(Shallow Copy). The problem occurs when the parent object gets destroyed( for ex: by going out of scope) it's destructor gets called, which usually would free the memory allocated to the pointer member, When this happens the objects with a shallow copy of this pointer now point to invalid memory region and become Dangling Pointers. These dangling pointers when accessed result in Undefined Behavior and most likely crashes.
To avoid this you need to follow the Rule of Three in C++03 and Rule of Five in C++11.
The difference of Rules in C++03 and C++11 because the functions that control the copying behavior for a class have changed in C++11.
Rule of Three Basically states:
Implement the copy constructor, copy assignment operator and Destructor for your class.
EDIT:
If you are using C++11, then the Rule of Three actually becomes Rule of Five.
A: What you didn't implement is called:
*
*Rule of three (C++ programming)
which in short says,
The rule of three (also known as the Law of The Big Three or The Big Three) is a rule of thumb in C++ that claims that if a class defines one of the following it should probably explicitly define all three:
*
*destructor
*copy constructor
*copy assignment operator
Since you tagged your question C++11 as well, then you have to implement this:
*
*Rule of Five (in C++11)
A: I think the problem is that you don't have a copy constructor. The compiler tried to do its best but it doesn't always succeed. Write a copy constructor and try again.
A: The destruction of b caused the member pointer p to be deleted. Since this pointer was copied to a, the member pointer of a is now pointing to deleted memory. You have undefined behavior.
To avoid this you need to do a deep copy at any point where you copy one object to another, typically the copy constructor and assignment operators. Allocate a new array and copy all the elements from one array to the other. You now adhere to the Rule Of Three because you've already defined a destructor.
The best way around this problem is to avoid raw pointers altogether and replace them with std::vector.
A: Direct asignment shares P between instances. Create a copy constructor.
A: When you assign b to a (a=b) the the compiler gerneated copy constructor does a shallow copy on your data members. I does not deference the pointers. So they both share the same resource, and when either of them are destroyed then they take their shared resource with them
Either define your own copy constructor to do a deep copy, or use an array abstraction like vector.
class vlarray {
public:
std::vector<double> p;
int size;
vlarray(int n) {
p.resize(n);
size = n;
for(int i = 0; i < n; i++) p[i] = 0.01*i;
}
~vlarray() {
cout << "destruction" << endl;
}
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: RedirectToAction Causes "No route in the route table matches the supplied values" in ASP.NET MVC 3 I have a project that I recently upgraded to ASP.NET MVC 3. On my local machine, everything works fine. When I deploy to the server, I get an error anytime I use a RedirectToAction call. It throws a System.InvalidOperationException with the error message No route in the route table matches the supplied values. My assumption is that there is some configuration problem on the server, but I can't seem to be able to figure it out.
A: I had a similar problem once with RedirectToAction and found out that you need a valid route registered that leads to that action.
A: Check out glimpse and see if you can get some route debugging information:
http://getglimpse.com/
A: I ran into this with areas within MVC3 when redirecting across areas. As others have said, Glimpse is very useful here.
The solution for me was to pass in the Area within the route values parameter changing:
return RedirectToAction("ActionName", "ControllerName");
to:
return RedirectToAction("ActionName", "ControllerName", new { area = "AreaName" });
A: You could add a route table to your RouteConfig.cs file like below:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapMvcAttributeRoutes();
var namespaces = new[] { typeof(HomeController).Namespace };
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("name", "url", new { controller = "controllerName", action = "actionName" }, namespaces);
}
NB: the "url" is what you'd type into the address bar say: localhost:/home
After setting up the route, use RedirectToRoute("url").
Or if you'd prefer the RedirectToAction() then you don't need to set up the above route, use the defaults.
RedirectToAction(string action name, string controller name);
I hope this helps.
A: There's a difference with trailing slashes in routes not working with MVC 3.0. MVC 2.0 doesn't have a problem with them. I.e., if you change the following:
"{controller}.mvc/{action}/{id}/"
to:
"{controller}.mvc/{action}/{id}"
it should fix this (from this thread, worked for me). Even when you use the upgrade wizard to move to MVC 3.0, this still throws InvalidOperationException. I'm not aware whether this is what Schmalls was talking about though.
A: In my case, default route was missing:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Ajax: Simultaneous loading of multiple images I have a grid of pictures (3x3, side by side, laid out in a ). I need to update this grid every so often. Since every picture independent from the rest (they get grabbed from different locations), I elected to load every picture by its own ajax callback, like so:
for (var i=0; i < numPictures; i++) {
Dajaxice.loadPicture(callback_loadPicture, {'picture_id':i})
}
The function callback_loadPicture() puts the picture into its proper place in the .
The problem is: Often, even though some picture will finish loading sooner than others, the browser will not display anything until the last ajax call is finished. Since some calls can time out, this means that I don't see anything until that single picture times out.
This behaves slightly differently in every browser: sometimes the picture will show as the callbacks finish (but usually not), sometimes the browser will show some images, but postpone showing all until the last one is finished loading.
I am using:
*
*django 1.3 (python 2.7)
*windows x64 as (test) server
*dajaxice for ajax implementation
I am open to changing the structure of my code.
Any comments or suggestions will be appreciated.
A: Since the ajax calls are blocking as said by chrisdpratt, if you really need to display the images at the same time I would advise some kind of preloading of the 3x3 grid of images and when required by the code you can display them.
With this in mind you can run the code you already have on $(document).ready() but make the images hidden (ie display:none). When later required you would just change the display attribute on the images you need to display.
A: If the issue you were seeing was indeed caused by the single-threaded implementation of the Django development server, you might try django-devserver (https://github.com/dcramer/django-devserver). Amongst other improvements, it boasts:
"An improved runserver allowing you to process requests simultaneously."
The other improvements make it worth it, too!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to stop fan gate / like gate from redirecting to wall when clicking "Like" I've created a Facebook fan page that works as a fan gate / like gate. When the user clicks the "Like" button the page redirects to the wall. I want to override this behavior and have the page redirect back to the Liked version of the fan gate. The app is an iFrame page tab app using the PHP signed request to determine liked/notliked status.
An example of this is http://www.facebook.com/1800flowers
When you like the page, it redirects you to http://www.facebook.com/1800flowers?sk=app_116748578401618
So my search-fu found a piece of JavaScript that was supposed to fix this:
<script type="text/javascript">
if (top != self) top.window.location = 'linkgoeshere';
</script>
I've tried placing this block of JavaScript in both the have liked and have not liked sections of the page. Either way it creates a redirect loop where the page just continually refreshes.
If this code is the answer, where should it be located, and what should "linkgoeshere" be replaced with? There is a possibility I've been using the wrong link.
If this isn't the answer, is there an alternative?
A: This is a bug on facebook right now, described here - https://developers.facebook.com/bugs/110015112440103
It'd be great to have an interim fix but since the code for the Like button is outside of what's accessible to the page tab, I'm having trouble imaging what a solution might look like, short of removing the address from your page to make it not a "place", which seem to be the only pages affected.
A: You shouldn't need any JavaScript.
Makes sure you set the "Default Landing Tab" to be your fan gate in the "Manage Permissions" section of the page Admin.
A: I've been having this problem for the past few days, but today I found the solution. You were right with your suspicions that this is caused by the new recommend dialog box on pages. This box only appears on pages for PLACES. If you have a address assigned to your page then remove it and your fangate will reload in the window when liked and not redirect to the wallpage.
A: Here is the solution I use. Also, be sure as marked above to set the default landing tab. You will need to download the latest facebook sdk for php, and replace the lines for your app ID, app secret, and the path to your fanpage int he $loginNextPage below.
Notice that there are two places where you can add your own HTML or an include of the page content that should be served for the appropriate audiences.
Also, returning users who liked you pages always get the wall by default, no matter what you set as the default tab. So if they leave and come back, they will get the wall.
<?php
require 'facebook.php';
$app_id = "YOUR APP ID";
$app_secret = "YOUR APP SECRET";
$loginNextPage = 'YOUR FAN PAGE URL'.'?sk=app_'.$app_id;
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
$signed_request = $facebook->getSignedRequest();
$page_id = $signed_request["page"]["id"];
$like_status = $signed_request["page"]["liked"];
if ($like_status) {
// FOR FANS
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'next' => $loginNextPage,
'req_perms' => 'publish_stream,photo_upload,user_photos,user_photo_video_tags'
)
);
$fbme = null;
if (!$session) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
else {
try {
$access_token = $facebook->getAccessToken();
$fbme = $facebook->api('/me');
$user = $facebook->getUser();
$url = "https://graph.facebook.com/".$user;
$info = file_get_contents($url);
$info = json_decode($info);
$vars = "id=$user&first_name=$info->first_name&last_name=$info->last_name&access_token=$access_token&pathToServer=$pathToServer&appName=$appName";
} catch (FacebookApiException $e) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
// Begin Like Gated Content.
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
</head>
<body>
<h1>You Have Liked The Page</h1>
</body>
</html>
<?
}
}
else {
// FOR NON FANS
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
</head>
<body>
<h1>Click Like To View Content</h1>
</body>
</html>
<?
}
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: error: expected declaration or statement at end of input Hi i'm getting an error of:
depthTemperature.c: In function 'main':
depthTemperature.c:29: error: expected declaration or statement at end of input
depthTemperature.c:29: error: expected declaration or statement at end of input
when i try to compile and i'm not sure why, everything seems to be kosher to me, of course there must be something im doing wrong. thank you in advance for your help.
#include <stdio.h>
void celsius_at_depth(double depth);
void fahrenheit(double celsius);
int
main(void)
{
double depth;
printf("Please input your depth to the nearest whole foot (eg. 100)> ");
scanf("%lf", &depth);
celsius_at_depth(depth);
return 0;
{
void celsius_at_depth(double depth)
{
double celsius;
celsius=10*depth+20;
printf("The temperature in celsius is: %f", celsius);
fahrenheit(celsius);
}
void farenheit(double celsius)
{
double farenheit;
farenheit=1.8*celsius+32;
printf("The temperature in farenheit is: %f", farenheit);
}
A: This is not OK:
int
main(void)
{
return 0;
{
^ ???
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Stored Proc slower from application than Management Studio We have a stored proc which runs pathetically when called from application (Spring - DBCP - jtds) infact timesout after 10 minutes, but runs in 30 seconds when executed from SQL Server Managament Stuido. Can someone provide leads into this issue?
A: This normally indicates a parameter sniffing issue.
See Slow in the Application, Fast in SSMS? Understanding Performance Mysteries for details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQLiteException because of ' char, how to escape it? When my EditText contain " ' " char I have SQLiteException because of it. Do I need to escape the char, if so, how to do that quickly?
public Cursor getAll() {
return(getReadableDatabase()
.rawQuery("SELECT _id, " +
COLUMN_NAME_ONE + ", " +
COLUMN_NAME_TWO + ", " +
COLUMN_NAME_THREE + ", " +
COLUMN_NAME_FOUR + " FROM " + TABLE_NAME, null));
A: Use android.database.DatabaseUtils.sqlEscapeString(sql_string);
A: Escape it by adding \ in front of it (so \" instead of ") inside the string.
You can use
replaceAll(char oldChar, char newChar) to replace ' by \' and escape it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to have different schema files to different cores in SOLR? I have one instance of SOLR with three different cores.
I created a solr.xml config file which specifies the schema file for each core, but, it is not recognized. The system still tries to load the default schema.xml (I removed it, so it fails).
For debugging purposes I left only one code in the solr.xml, here are the entries I have:
<solr persistent="false">
<cores adminPath="/admin/cores" defaultCoreName="content" shareSchema="false">
<core name="content" instanceDir=".">
<property name="schema" value="conf/contentSchema.xml" />
</core>
</cores>
</solr>
The file `contentSchema.xml exists under [SOLR_HOME]/conf. Itried both just the file name and conf/filename
Don't even reach that phase, the error is:
SEVERE: java.lang.RuntimeException: Can't find resource 'schema.xml' in classpath or
/usr/local/solr/./conf/', cwd=/usr/local/solr
A: If you have source downloaded , check the multicore folder which demos the multicore configuration which you can refer and test.
or refer @ http://svn.apache.org/repos/asf/lucene/dev/trunk/solr/example/multicore/
More @ http://wiki.apache.org/solr/CoreAdmin#Configuration - would be a good starting point.
The multicore need not be under the solr home folder and can be specified with
-Dsolr.solr.home=multicore
The solr.xml is in the same folder as the core folders.
The instance directory points to the core folders
schemaName -- The name of the core's schema file (schema.xml by default)
e.g.
<core name="content" instanceDir="content">
<property name="schemaName" value="contentSchema.xml" />
</core>
A: Read the document carefully, 'schema' is an ATTRIBUTE of core element, not a PROPERTY. so suppose you put 'myschema.xml' under core's conf folder:
<core ....>
<property name="schema" value="myschema.xml" />
</core>
will cause can't find schema.xml in classpath or ...../conf error
Whereas,
<core .... schema='myschema.xml' />
will succeed.
Note: Lucid Imagination's doc may be out-of-date or maybe it's talking about a feature of a future version of Solr, I guess.
A: This is what I finaly used and is working
<cores adminPath="/admin/cores" defaultCoreName="content">
<core name="content" instanceDir="./content" />
<core name="users" instanceDir="./users" />
<core name="users_organizations" instanceDir="./users_organizations" />
</cores>
Under each of those directories I have a conf directory with it's own conf files, which they in turn also point to the right data folder (in the solrconfig.xml file)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: int to char casting int i = 259; /* 03010000 in Little Endian ; 00000103 in Big Endian */
char c = (char)i; /* returns 03 in both Little and Big Endian?? */
In my computer it assigns 03 to char c and I have Little Endian, but I don't know if the char casting reads the least significant byte or reads the byte pointed by the i variable.
A: Since you're casting from a larger integer type to a smaller one, it takes the least significant part regardless of endianness. If you were casting pointers instead, though, it would take the byte at the address, which would depend on endianness.
So c = (char)i assigns the least-significant byte to c, but c = *((char *)(&i)) would assign the first byte at the address of i to c, which would be the same thing on little-endian systems only.
A: If you want to test for little/big endian, you can use a union:
int isBigEndian (void)
{
union foo {
size_t i;
char cp[sizeof(size_t)];
} u;
u.i = 1;
return *u.cp != 1;
}
It works because in little endian, it would look like 01 00 ... 00, but in big endian, it would be 00 ... 00 01 (the ... is made up of zeros). So if the first byte is 0, the test returns true. Otherwise it returns false. Beware, however, that there also exist mixed endian machines that store data differently (some can switch endianness; others just store the data differently). The PDP-11 stored a 32-bit int as two 16-bit words, except the order of the words was reversed (e.g. 0x01234567 was 4567 0123).
A: Endianness doesn't actually change anything here. It doesn't try to store one of the bytes (MSB, LSB etc).
*
*If char is unsigned it will wrap around. Assuming 8-bit char 259 % 256 = 3
*If char is signed the result is implementation defined. Thank you pmg: 6.3.1.3/3 in the C99 Standard
A: When casting from int(4 bytes) to char(1 byte), it will preserve the last 1 byte.
Eg:
int x = 0x3F1; // 0x3F1 = 0000 0011 1111 0001
char y = (char)x; // 1111 0001 --> -15 in decimal (with Two's complement)
char z = (unsigned char)x; // 1111 0001 --> 241 in decimal
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: c# merge objects Class Person
{
string Name
int yesno
int Change
List<Cars> Personcars;
houses Personhouses
}
Person user1 = new Person()
Person user2 = new Person()
user1.Name = "userName"
user2.Name ="";
user2.cars[0] = new car("Mazda");
user1.cars[0] = new car("BMW");
i want to merge the objects so that user2 will take the name and the car from user1
user2 will have this values
user2.Name will be userName
user2.cars will hold the Mazda and the Bmw
thanks !
A: user2.Name = user1.Name;
user2.Personcars.AddRange(user1.Personcars);
You could add this as a method on the class itself:
public class Person
{
List<Cars> _personcars;
public string Name { get; set; }
// what the hell is a yesno int? If it's 1 or 0 then just use a bool
public int yesno { get; set; }
public int Change { get; set; }
public List<Cars> Personcars
{
get
{
return _personcars ?? (_personCars = new List<Cars>());
}
set { _personcars = value; }
}
public Houses Personhouses { get; set; }
public void Merge(Person person)
{
Name = person.Name;
Personcars.AddRange(person.Personcars);
}
}
Which will allow you to write something like this:
user2.Merge(user1);
A: Try this extension methods
public void Merge(this Person _person, Person source)
{
_person.Name = source.Name;
if(_person.Cars !=null)
{
_person.Cars.AddRang(source.Cars);
}
else
{
_person.Cars = source.Cars;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: intercepting url rewrite module, prevent rewrite Is there anything that would cause the url rewrite module in IIS to not fire off? Maybe a site that is in integrated mode or an http handler?
I have tried a few different things to get the rewrite rules to work but nothing. My latest is as such
<rewrite>
<rewriteMaps>
</rewriteMaps>
<rules>
<rule name="rewriterule" enabled="true" patternSyntax="Wildcard" stopProcessing="true">
<match url="*" />
<action type="Redirect" url="http://www.google.com" />
</rule>
</rules>
</rewrite>
and it doesn't work at all. I've tried various regex, etc. Its like it doesnt get used.
A: Seems like you have your answer but here are some other possible things that might cause Rewrite Module not to work :
*
*When you deploy your web site and see this feature not working on
your server, it is highly possible that you misconfigured something
on your server. One of the misconfiguration you might have done could
be setting the overrideModeDefault attribute to Deny for rules under
<sectionGroup name="rewrite"> inside your applicationHost.config
file.
*If you are on a shared hosting environment and you see this feature
not working, then ask your provider if they have given you the
permission of configuring this part.
*In your development environment, if you run your web site under
Visual Studio Development Sever, you won’t be able to see this
feature working. You need to configure your application to run under
at least IIS Express to see this feature working.
A: The answer in my case is that you have to be running the site in the same target platform as the url rewrite module. for example, I have x64 version of url rewrite module installed but the site was running under 32bit. Once I setup the site to run under 64bit, the rewrite started working.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to display and edit data of 2 tables in phpmydatagrid I'm using the phpmydatagrid.class.php. Everything is working fine except I can't edit data when I use data from 2 database tables. I got to know from the doc that if I set the column type to "related" instead of integer or text then I can refer data of other table. But the document did not gave further details. The doc's url is http://www.gurusistemas.com/documentation.php
A: phpMyDataGrid is a PHP class to display and edit records of a MySQL database table.(And not tables.) Editing can be done via AJAX. It can display the contents of the records in an HTML table. The class can be configured to determine which fields of the database table are displayed.
The class is capable to save data from only one table currently. (In future class may provide functionality for multiple tables.) So it is not possible currently to display and edit data of 2 tables in phpmydatagrid.
See this discussion.
A: You can edit several tables with phpMyDataGrid at once if you create an editable view on a join of those tables.
then you just implement the view as you would a table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to retrieve Tab names from excel sheet using OpenXML I have a spreadsheet document that has 182 columns in it. I need to place the spreadsheet data into a data table, tab by tab, but i need to find out as I'm adding data from each tab, what is the tab name, and add the tab name to a column in the data table.
This is how I set up the data table.
I then loop in the workbook and drill down to the sheetData object and walk through each row and column, getting cell data.
DataTable dt = new DataTable();
for (int i = 0; i <= col.GetUpperBound(0); i++)
{
try
{
dt.Columns.Add(new DataColumn(col[i].ToString(), typeof(string)));
}
catch (Exception e)
{
MessageBox.Show("Uploader Error" + e.ToString());
return null;
}
}
dt.Columns.Add(new DataColumn("SheetName", typeof(string)));
However at the end of the string array that I use for the Data Table, I need to add the tab name. How can I find out the tab name as I'm looping in the sheet in Open XML?
Here is my code so far:
using (SpreadsheetDocument spreadSheetDocument =
SpreadsheetDocument.Open(Destination, false))
{
WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
Workbook workbook = spreadSheetDocument.WorkbookPart.Workbook;
Sheets sheets =
spreadSheetDocument
.WorkbookPart
.Workbook
.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
OpenXmlElementList list = sheets.ChildElements;
foreach (WorksheetPart worksheetpart in workbook.WorkbookPart.WorksheetParts)
{
Worksheet worksheet = worksheetpart.Worksheet;
foreach (SheetData sheetData in worksheet.Elements<SheetData>())
{
foreach (Row row in sheetData.Elements())
{
string[] thisarr = new string[183];
int index = 0;
foreach (Cell cell in row.Elements())
{
thisarr[(index)] = GetCellValue(spreadSheetDocument, cell);
index++;
}
thisarr[182] = ""; //need to add tabname here
if (thisarr[0].ToString() != "")
{
dt.Rows.Add(thisarr);
}
}
}
}
}
return dt;
Just a note: I did previously get the tab names from the InnerXML property of "list" in
OpenXmlElementList list = sheets.ChildElements;
however I noticed as I'm looping in the spreadsheet it does not get the tab names in the right order.
A: Using spreadsheetDocument As SpreadsheetDocument = spreadsheetDocument.Open("D:\Libro1.xlsx", True)
Dim workbookPart As WorkbookPart = spreadsheetDocument.WorkbookPart
workbookPart.Workbook.Descendants(Of Sheet)()
Dim worksheetPart As WorksheetPart = workbookPart.WorksheetParts.Last
Dim text As String
For Each Sheet As Sheet In spreadsheetDocument.WorkbookPart.Workbook.Sheets
Dim sName As String = Sheet.Name
Dim sID As String = Sheet.Id
Dim part As WorksheetPart = workbookPart.GetPartById(sID)
Dim actualSheet As Worksheet = part.Worksheet
Dim sheetData As SheetData = part.Worksheet.Elements(Of SheetData)().First
For Each r As Row In sheetData.Elements(Of Row)()
For Each c As Cell In r.Elements(Of Cell)()
text = c.CellValue.Text
Console.Write(text & " ")
Next
Next
Next
End Using
Console.Read()
A: Here is a handy helper method to get the Sheet corresponding to a WorksheetPart:
public static Sheet GetSheetFromWorkSheet
(WorkbookPart workbookPart, WorksheetPart worksheetPart)
{
string relationshipId = workbookPart.GetIdOfPart(worksheetPart);
IEnumerable<Sheet> sheets = workbookPart.Workbook.Sheets.Elements<Sheet>();
return sheets.FirstOrDefault(s => s.Id.HasValue && s.Id.Value == relationshipId);
}
Then you can get the name from the sheets Name-property:
Sheet sheet = GetSheetFromWorkSheet(myWorkbookPart, myWorksheetPart);
string sheetName = sheet.Name;
...this will be the "tab name" OP referred to.
For the record the opposite method would look like:
public static Worksheet GetWorkSheetFromSheet(WorkbookPart workbookPart, Sheet sheet)
{
var worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id);
return worksheetPart.Worksheet;
}
...and with that we can also add the following method:
public static IEnumerable<KeyValuePair<string, Worksheet>> GetNamedWorksheets
(WorkbookPart workbookPart)
{
return workbookPart.Workbook.Sheets.Elements<Sheet>()
.Select(sheet => new KeyValuePair<string, Worksheet>
(sheet.Name, GetWorkSheetFromSheet(workbookPart, sheet)));
}
Now you can easily enumerate through all Worksheets including their name.
Throw it all into a dictionary for name-based lookup if you prefer that:
IDictionary<string, WorkSheet> wsDict = GetNamedWorksheets(myWorkbookPart)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
...or if you just want one specific sheet by name:
public static Sheet GetSheetFromName(WorkbookPart workbookPart, string sheetName)
{
return workbookPart.Workbook.Sheets.Elements<Sheet>()
.FirstOrDefault(s => s.Name.HasValue && s.Name.Value == sheetName);
}
(Then call GetWorkSheetFromSheet to get the corresponding Worksheet.)
A: The sheet names are stored in the WorkbookPart in a Sheets element which has children of element Sheet which corresponds to each worksheet in the Excel file. All you have to do is grab the correct index out of that Sheets element and that will be the Sheet you are on in your loop. I added a snippet of code below to do what you want.
int sheetIndex = 0;
foreach (WorksheetPart worksheetpart in workbook.WorkbookPart.WorksheetParts)
{
Worksheet worksheet = worksheetpart.Worksheet;
// Grab the sheet name each time through your loop
string sheetName = workbookPart.Workbook.Descendants<Sheet>().ElementAt(sheetIndex).Name;
foreach (SheetData sheetData in worksheet.Elements<SheetData>())
{
...
}
sheetIndex++;
}
A: worksheet.GetAttribute("name","").Value
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: virtual function that is const in the base class and not const in the derived Can anyone explain the output of the following code?
#include <iostream>
#include <string>
class Animal
{
public:
Animal(const std::string & name) : _name(name) { }
~Animal() { }
virtual void printMessage() const
{
std::cout << "Hello, I'm " << _name << std::endl;
}
private:
std::string _name;
// other operators and stuff
};
class Cow : public Animal
{
public:
Cow(const std::string & name) : Animal(name) { }
~Cow() { }
virtual void printMessage()
{
Animal::printMessage();
std::cout << "and moo " << std::endl;
}
};
int main() {
Cow cow("bill");
Animal * animal = &cow;
cow.printMessage();
animal->printMessage();
}
The output is
Hello, I'm bill
and moo
Hello, I'm bill
I don't understand why. The pointer animal points at an object of type Cow. printMessage is a virtual function. Why isn't the implementation of the Cow class the one that is called?
A: You have two different versions of printMessage, one which is const and one which isn't. The two are unrelated, even though they have the same name. The new function in Cow hides the one in Animal, so when you call it directly the compiler only considers the Cow version.
A: Cow isn't overriding the virtual function from Animal because it has a different signature. What's actually happening is that Cow is hiding the function in Animal.
The result of this is that calling printMessage on an Animal will just use the version in Animal, regardless of the one in Cow (it isn't overriding it), but calling it from Cow will use the one in Cow (because it hides the one from Animal).
To fix this, remove the const in Animal, or add the const in Cow.
In C++ 2011, you will be able to use the override keyword to avoid subtle traps like this:
class Cow : public Animal
{
public:
Cow(const std::string & name) : Animal(name) { }
~Cow() { }
virtual void printMessage() override
{
Animal::printMessage();
std::cout << "and moo " << std::endl;
}
};
Notice the added override after printMessage(). This will cause the compiler to emit an error if printMessage doesn't actually override a base class version. In this case, you would get the error.
A: It took me a while to understand Peter Alexander's hiding answer, but another way to understand it is as follows:
Say that you mispelled the method name in the Cow class, but spelled it correctly in Animal class:
Animal::printMessage()
Cow::mispelledPrintMessage()
then when you have an
Animal *animal;
you can ONLY call
animal->printMessage();
but you CANNOT call
animal->mispelledPrintMessage();
because mispelledPrintMessage() doesn't exist in the Animal class. Its a brand new method in the Cow class, so it cannot be polymorphically called thru a base pointer.
So having the Animal method have const in the signature, but not in Cow method is kinda analogous to a slightly mispelled method name in the derived class.
PS: Another 4th solution (1 making both methods const, 2 making both methods non-const, or 3 using new 2011 override keyword), is to use a cast, to force the Animal pointer into a Cow pointer:
((Cow*)animal)->printMessage();
But this is a very ugly HACK, and I would not recommend it.
PS: I always try to write my toString() methods with const in the signature in the Base class and all derived classes for this very reason. Plus, having const in the toString() signature allows you call toString() either with a const or non-const object. Had you instead left out the const, and tried to pass call toString() with a const object, GCC compiler would complain with the discards qualifiers error message:
const Bad' as `this' argument of `std::string Bad::toString()' discards qualifiers
for this code:
#include <iostream>
#include <string>
class Bad
{
public:
std::string toString()
{
return "";
}
};
int main()
{
const Bad bad;
std::cout << bad.toString() << "\n";
return 0;
}
So, in conclusion, since Cow doesn't change any data members, the best solution probably is to add const to printMessage() in derived Cow class, so that both BASE Animal and DERIVED Cow classes have const in their signatures.
-dennis bednar
-ahd 310
A: Correction to Dennis's post.
Note you state as a solution you can cast the animal (which is a Animal*) to a Cow*. However, once a Cow* your printMessage from the Animal class will not be available.
Therefore ((Cow*)animal)->printMessage() needs to be ((Cow*)animal)->mispelledPrintMessage()
A: Just tried it. Add the const to the Cow class and it will work.
i.e. virtual void printMessage () const for both classes.
A: virtual in subclass-->no need. You just add const to function in subclass to make it same signature
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Z3: A better way to model? I've two SMT problem instances. The first is here:
http://gist.github.com/1232766
Z3 returns a model for this problem in about 2 minutes on my not-so-great machine, which is great.. I also have this one:
http://gist.github.com/1232769
I've ran z3 overnight on this problem, without Z3 completing. If you check the contents of these files, you'll see that the second one is identical to the first, except it has an extra assertion to "reject" the model returned by the first instance. (You can do a "diff" between them to see what I mean.) I happen to know that this problem has multiple satisfying models, and I'm trying to use z3 to find all satisfying models.
I understand that this might be completely expected, but I was curious to know why the second one is a much tougher problem for Z3 compared to the first. Is there a better way to formulate the second problem so Z3 will have an easier time?
Thanks..
A: It is hard to give you a precise answer without knowing more about your application.
As you suggested, modeling plays a big role in the logic you are using: AUFBV.
The strategy used by Z3 also has a big impact on the overall performance.
Z3 comes equipped with several builtin strategies. It has many parameters that can be used to influence the search.
Z3 also has a strategy specification language. This is a new feature. I’m not advertising it because it is working in progress, and the language will most likely change in the next versions.
You can access more information about the strategy language by executing the commands:
(help check-sat-using)
(help-strategy)
That being said, there is a builtin strategy in Z3 that seems to be effective on your problem.
It is the strategy used for the logic UFBV. Your problem uses arrays, but they can be avoided by transforming table0 into a function with two arguments:
(declare-fun table0 ((_ BitVec 64) (_ BitVec 64)) (_ BitVec 8))
And replacing every term of the form (select (table0 s65) t) with (table0 s65 t) where t is an arbitrary term.
Finally, you must also add the command (set-logic UFBV) in the beginning of the file. With this setting, I managed to generate 4 different models for your query.
I didn’t try to generate more than that. Each call consumed approx 75 secs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Using jQuery keynav plugin with live() I have a website with two columns, in the first is a form and the second an ajax generated series of divs. I need keyboard friendly navigation and so far jQuery plugin keynav is doing a good job.
But if I want the key navigation to extend over the divs that are added to DOM I would need to use live() and I'm having trouble figuring out. I assumed it would be something like this:
$(document).live('keyup', function(){
$('input, button, .restu').keynav('keynav','keynav');
});
Where "restu" is the class of the generated divs. But that's not working. Any ideas?
A: Try window instead of document
$(window).live('keyup', function(){
$('input, button, .restu').keynav('keynav','keynav');
});
A: You could use delegate:
$(document).delegate('div', 'keyup', function(){
$('input, button, .restu').keynav('keynav','keynav');
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ER Diagram/Data Modelling question I wanted to know how to represent a relationship between two entities which means "atleast".
Eg- A song must be part of atleast one album.
If "A song can be part of one or more than one album" means a one to many relationship between song and album, then what would the ER diagram for the Eg given above be?
A: It's represented on an ERD by a double line (called a participation constraint).
If one song can be on many albums, you need a junction table, Like so:
album -+------< album_song >------+- song
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Iterate through a MATLAB structure numerically Is it possible to iterate through a MATLAB structure numerically like a vector instead of using the field names?
Simply, I am trying to do the following inside an EML block for Simulink:
S.a.type = 1;
S.a.val = 100;
S.a.somevar = 123;
S.b.type = 2;
S.b.val = 200;
S.b.somevar2 = 234;
S.c.type = 3;
S.c.val = 300;
S.c.somevar3 = 345;
for i = 1:length(s)
itemType = S(i).type;
switch itemType
case 1
val = S(i).val * S(i).somevar1;
case 2
val = S(i).val * S(i).somevar2;
case 3
val = S(i).val * S(i).somevar3;
otherwise
val = 0
end
end
disp(var);
A: You should be able to generate the fieldnames dynamically using sprintf using something like the following:
for i = 1:length(s)
theFieldName = sprintf('somevar%d', S(i).type);
val = S(i).val * getfield(S(i), theFieldName);
end
A: You need to use the field names, but you can do so dynamically. If you have a structure defined as:
s.field1 = 'foo';
s.field2 = 'bar';
Then you can access the field field1 with either
s.field1
s.('field1')
The only thing you need is the function fieldnames to dynamically get the field names such that your code example will look somewhat like
elements = fieldnames(S);
for iElement = 1:numel(elements)
element = S.(elements{iElement});
itemType = element.type;
switch itemType
case 1
val = element.val * element.somevar1;
case 2
val = element.val * element.somevar2;
case 3
val = element.val * element.somevar3;
end
end
If those are the exact field names, you should do some other things. First of all you would need to rethink your names and secondly you could use part of Matt's solution to simplify your code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get EventClicked from UserControl in aspx Hei,
I would like get the name of the button who was clicked at usercontrol
I was tried this but I just get null:
UserControl uc = (UserControl)Page.FindControl("ImportTXP");
A: If it's in your event handler, the sender will be the button that raised the event:
string name = ((Button)sender).Name;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Validation was not occurring Asp.net MVC2 Validation was not occurring Asp.net MVC2, I am using ckeditor Control that why mentioned "[ValidateInput(false)]"
Controller
[AcceptVerbs(HttpVerbs.Post)]
[ValidateInput(false)]
public ActionResult Create(EventInfo EventInfo)
{
//
}
Model
[Required(ErrorMessage = "Title is required")]
[StringLength(250, ErrorMessage = "Maximum 250 Characters")]
public string TITLE { get; set; }
How can i solve this issue.
A: You're probably asking for
if (!ModelState.IsValid)
return View(EventInfo);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I remap control-shift-leftmouse in gvim? I'd like to remap a modified click in gvim (and also MacVim), but certain combinations of modifiers work while others do not. In gvim on a Linux box, I would like to insert "hello" anywhere I type:
:noremap <C-S-LeftMouse> <LeftMouse>ihello<ESC>
However, that command does not work: control-shift-click retains its original behavior. Yet I can remap control-click in gvim:
:noremap <C-LeftMouse> <LeftMouse>ihello<ESC>
In MacVim, command-shift-click <D-S-LeftMouse> is likewise unresponsive, as are most other modified clicks.
How can I actually remap the modified mouse clicks?
A: To remap the <C-LeftMouse> in MacVim, you should first disable the contextual menu:
defaults write org.vim.MacVim MMTranslateCtrlClick 0
A: Double modifier keys don't work in MacVim. It's a known limitation/bug.
:nnoremap <M-LeftMouse> <LeftMouse>ihello<Esc>
seems to work, though, but neither <C-LeftMouse> nor <D-LeftMouse> do.
<C-LeftMouse> brings the normal contextual menu everyone expects, I wouldn't count on it being easily changed.
<D-LeftMouse> does nothing at all. I wonder if it's even registered.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Menu inflater not running on emulator I am trying to use the menu inflator to give the user the option to email me for support, but everytime I hit the menu button on the emulator it will do nothing.
Would I need to edit this in my manifest? My xml has menu as the title and items for the well items.
Here is my xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/email" android:title="@string/email_menu"
android:icon="@drawable/ic_envelope" android:onClick="emailme" />
<item android:id="@+id/test1" android:title="@string/test1"
android:icon="@drawable/ic_dashboard" android:onClick="test1" />
</menu>
Activity:
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MenuButton extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.menu.menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.email:
emailme();
return true;
case R.id.test1:
test1();
return false;
default:
return super.onOptionsItemSelected(item);
}
}
private void test1() {
// TODO Auto-generated method stub
}
private void emailme() {
// TODO Auto-generated method stub
String domsEmail = "MYEMAIL@EXAMPLE.com";
String message = "Hello, I just want to let you know that your app";
String myemail[] = { domsEmail };
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, myemail);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "your app");
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
startActivity(emailIntent);
}
}
A: Here are various issues with your code:
*
*Please have onCreateOptionsMenu() use return(super.onCreateOptionsMenu(...)) with the same parameters that you receive -- in other words, chain to the superclass when you are done
*Your android:onClick attributes will only work on API Level 11 and higher, and your methods that you have tied to them need to be public and have a MenuItem parameter (which yours do not)
*Your MIME type in emailme() needs to be text/plain, not plain/text
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Calculate and Display Disk Usage Using CF8, I want to produce a graph that displays the disk usage, in megabytes, per client. The clients are the directories within D:\inetpub\sites.
I've looked through the docs and found examples only using DB queries. I am using <cfdirectory> to get a list of directories.
<cfdirectory action="list"
directory="#expandPath("../../")#"
name="webDirectories">
<cfquery name="getInfo" dbtype="query">
select sum(size) as total, name
from webDirectories
group by name
</cfquery>
<h1>Web Server Disk Usage Analysis</h1>
<!--- Bar graph, from Query of Queries --->
<cfchart format="flash"
xaxistitle="Client"
yaxistitle="Disk Usage">
<cfchartseries type="bar"
query="getInfo"
itemcolumn="name"
valuecolumn="size">
<cfoutput query="getInfo">
<cfchartdata item="#name#" value=#Round(total/1000)*1000#>
</cfoutput>
</cfchartseries>
</cfchart>
I would like to have the clients listed in the x-axis and usage on the y-axis. How can I achieve this?
A: Your chart code is wrong. I changed it to this, and it worked for me:
<h1>Web Server Disk Usage Analysis</h1>
<!--- Bar graph, from Query of Queries --->
<cfchart format="flash"
xaxistitle="Client"
yaxistitle="Disk Usage">
<cfchartseries type="bar"
query="getInfo"
itemcolumn="name"
valuecolumn="total" />
</cfchart>
If you want to do your round(total/100)*1000, you can just massage the query further before feeding it into the chart.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: -bash: rspec: command not found I found rspec in /Library/Ruby/Gems/1.8/gems/rspec-2.6.0/lib
I even put a path to it in my .bash_profile:
PATH="/usr/local/bin:/Library/Ruby/Gems/1.8/gems/rspec-2.6.0/lib:
But when I enter rspec in terminal I get command not found. Even when I'm in the same directory as the file rspec?
Besides being a noob, what am I doing wrong?
*Update:*I was able to execute rspec using "bundle exec rspec" but I'd like to figure out why I can't just use rspec.
A: Check that your PATH environment variable is what you expect. echo $PATH
Check that your target binary has executable permission. ls -l /Library/Ruby/Gems/1.8/gems/rspec-2.6.0/lib
Check again. which rspec
A: for a file to be executable as a binary you generally need to:
(a) make the file executable by running chmod 755 /path/to/scripts/awesometask.gem
(b) add a "shebang" to the top of the file (first line) that contains the path of the interpreter for the script: #!/usr/bin/ruby
(c) execute file with full path: /path/to/scripts/awesometask.gem
or
(c1) add the folder where the file is to PATH: PATH=$PATH:/path/to/scripts
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to easily grab an array of children from a batch node by tag I know that I can get an array of all the children of a CCSpriteBatchNode by using its children property, but can I get an array easily of just the subset of children that share a common tag?
What I do now is:
Get the array of the children of the batch node
Make a new array for the children with the tag of interest
Iterate through the children, and if the individual child has that tag, add it to the new array
Seems kind of cumbersome so I thought there might be a way to to it easily. If you just want a single child, you can use getChildByTag I think...
A: That's the way to do it.
However you can (and should) initialize an array with the children that use the same tag in your class, and every time you add a child with that tag you'll also add it to the "childsWithTagX" array. Same for removing. That way you have an always up-to-date separate children array containing only nodes with a given tag.
I think I'll have to add this as a feature to the Kobold2D Roadmap. I needed that a few times already.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: iPhone voice recognition "Vocalkit by KingOFBrian" compile error i'm using last version of VocalKit for iPhone https://github.com/KingOfBrian/VocalKit
I followed all instructions to add in new project as specified on github,
but on compile time i getting these errors:
Ld build/Debug-iphonesimulator/Voice.app/Voice normal i386
cd /Users/asd/Desktop/Voice
setenv MACOSX_DEPLOYMENT_TARGET 10.6
setenv PATH "/Developer-old/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer-old/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer-old/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 -arch i386 -isysroot /Developer-old/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk -L/Users/asd/Desktop/Voice/build/Debug-iphonesimulator -F/Users/asd/Desktop/Voice/build/Debug-iphonesimulator -filelist /Users/asd/Desktop/Voice/build/Voice.build/Debug-iphonesimulator/Voice.build/Objects-normal/i386/Voice.LinkFileList -mmacosx-version-min=10.6 -all_load -ObjC -Xlinker -objc_abi_version -Xlinker 2 -framework Foundation -framework UIKit -framework CoreGraphics "/Users/asd/Downloads/KingOfBrian-VocalKit-a25e5f3 2/build/Debug-iphonesimulator/libVocalKit.a" -framework AudioToolbox -liconv -o /Users/asd/Desktop/Voice/build/Debug-iphonesimulator/Voice.app/Voice
Undefined symbols:
"_ssymm_", referenced from:
_matrixmultiply in libVocalKit.a(matrix.o)
"_spotrf_", referenced from:
_determinant in libVocalKit.a(matrix.o)
"_sposv_", referenced from:
_invert in libVocalKit.a(matrix.o)
_solve in libVocalKit.a(matrix.o)
ld: symbol(s) not found
collect2: ld returned 1 exit status
what can i do?
What's the cause of these problems?
I tried to import in xcode3 and xcode4, but it's the same.
My sdk version is 4.3.
thanks.
A: from the readme file on the github page...
I no longer advise using VocalKit, as a much better project, Open Ears has come out. http://www.politepix.com/openears/
Maybe check out openears?
A: Thanks all,
but I solved using google chrome speech.
Speech recognition framework for iOS that supports Spanish
Using chromium src: src.chromium.org/viewvc/chrome/trunk/src/content/browser/speech/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I bind a listbox selecteditem content to a textbox? I have a listbox thats getting binded by this query when TextName content changes:
var players =
from p in context.Player
where p.GivenName.StartsWith(TextName.Text.Trim())
select p;
listNames.ItemsSource = players.ToList();
It shows the players names that starts with the text on the textbox. Now when I click any Item (name) from the listbox I need that the TextName shows the player name that's selected on the listbox. I tried to bind it this way:
<TextBox ... Text="{Binding Source=listNames, Path=SelectedItem.Content}" ... />
But when I click a ListboxItem, the textbox just get cleared and does not show anything.. may I have to set up the textbox like I do with the listbox when setting the DisplayMemeberPath???? I need a only one way binding!!
What can I do??
A: You have 2 problems with your binding:
*
*You are using the Source property instead of the ElementName to specify the list box name
*You are trying to bind to a Content property which (I am assuming) does not exist on your Player object. This happens because the SelectedItem property of the ListBox is an instance of Player when you specify an ItemsSource as you have
To solve this you should change your binding to the following:
<TextBox ... Text="{Binding ElementName=listNames, Path=SelectedItem.GivenName}" ... />
A: <TextBox ... Text="{Binding ElementName=listNames, Path=SelectedItem.Name}" ... />
This binds the TextBox.Text to the ListBoxes - called listNames - SelectedItem, which contains Player objects, and you need its Name property.
A: <Page
x:Class="Studentt1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Studentt1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="Wheat">
<ListBox x:Name="listBox1" ItemsSource="{Binding StudentsList}"
SelectedItem="Binding SelectedStud,Mode=TwoWay}"
DisplayMemberPath="StudName"
HorizontalAlignment="Left" Height="332" Margin="59,173,0,0" VerticalAlignment="Top"
<Button Content="Load" Command="{Binding LoadCommand}" HorizontalAlignment="Left"
Margin="144,567,0,0" VerticalAlignment="Top"/>
<Grid Background="Brown" HorizontalAlignment="Left" Height="352"
VerticalAlignment="Top" Width="633">
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="347"/>
<ColumnDefinition Width="401"/>
<ColumnDefinition Width="367*"/>
<ColumnDefinition Width="251*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" FontSize="30" Grid.Column="0" Text="Registration
Number" HorizontalAlignment="Center" Margin="46,0,25,0" Width="276"/>
<TextBox Grid.Row="0" Grid.Column="1" Text="{Binding
ElementName=listBox1,Path=SelectedItem.RegNo,Mode=TwoWay}"/>
<TextBlock Grid.Row="1" Grid.Column="0" FontSize="30" Text="Name"
HorizontalAlignment="Center" Margin="144,0,124,0" Width="79"/>
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding
ElementName=listBox1,Path=SelectedItem.StudName,Mode=TwoWay}"/>
<TextBlock Grid.Row="2" Grid.Column="0" FontSize="30" Text="Age"
HorizontalAlignment="Center" Margin="157,0,137,0" Width="53"/>
<TextBox Grid.Row="2" Grid.Column="1" Text="{Binding
ElementName=listBox1,Path=SelectedItem.Age,Mode=TwoWay}"/>
</Grid>
</Grid>
</Page>
here i bind the selected item of list box to text box..
you can find zip file for full source code
A: You should use RelativeSource to access the ListBox, e.g.:
<TextBox ... Text="{Binding RelativeSource={RelativeSource
AncestorType={x:Type ListBox}}, Path=SelectedItem.Content}" .... />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Accessing Action class in JSP using Struts2 Does anyone know how to easily access the Action class in a JSP when using Struts2? While I know it is often possible to use Struts tags and OGNL, I actually find them both to be confusing (clearly due to ignorance) and quite frankly find it easier to maintain Java in the JSP (not to mention it's easier to explain to new programmers as everyone knows Java).
I have searched for a solutions for years, and the best solution I have found is to call a static method from a class, that looks like:
public static BaseAction getCurrentAction(HttpServletRequest request) {
OgnlValueStack ognlStack = (OgnlValueStack)request.getAttribute(org.apache.struts2.ServletActionContext.STRUTS_VALUESTACK_KEY);
return (BaseAction)ognlStack.getRoot().get(0);
}
...which would be in a BaseAction class extended by you own Action class, so that in your JSP you can say:
<%
MyAction action = (MyAction)BaseAction.getCurrentAction(request);
String myValue = action.getMyValue();
%>
However this all seems overly complicated and it assumes a precise order in the OgnlValueStack - there must be a better way, non?
Many thanks for any advice!
A: If you don't want to use struts2 tags an equally valid approach is to use JSTL tags. These tags are supported by struts2 and I'm guessing most major java web frameworks.
It is strongly recommended that you avoid servlets/scriplets in typical business programming using any Java Web Framework.
You probably already know this but to get a property from the action just say:
<s:property value="myProperty"/>
Or equally valid using the JSTL (some here would even say more valid as the view no longer depends on struts2)
<c:out value="${myProperty}" />
There are few programmers (and I would stand to say no seasoned struts2 programmers) who would find this harder to understand than
<%
MyAction action = (MyAction)BaseAction.getCurrentAction(request);
String myValue = action.getMyValue();
%>
There are only a handful of tags required to generate a page, you need to get properties, iterate to produce tables/lists and that's about it. The time learning those few tags will save a great deal of time.
A: To follow up on Quaternion's answer, you can access any public method in your action class from OGNL tags or JSTL as he suggested.
You can also pass parameters to the action class through the tags:
public String getHello(String value){
return "Hello " + value + "!";
}
Which is called on the JSP:
<s:property value="getHello('Russell')"/>
Which outputs:
Hello Russell!
A: Besides Quaternion's answer , I want to add another way to call action object in here.The action object is on the top of the valueStack.In your jsp, you can access struts action like this,
<% MyAction myAction = (MyAction) ActionContext.getContext().getValueStack().peek(); %>
References:
https://struts.apache.org/tag-developers/access-to-valuestack-from-jsps.html
If you want to know more how to access via ognl expression, the following discussion may be helpful for you
What are different ways to access variables with OGNL in Struts 2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to make ipad like dropdownlist in desktop browsers using select tag of HTML and css only, is it possible? I am working on a project where i have to give some style to a select box(dropdown list) ....this page will work almost on every devices (responsive web design) i have to give style to a select box like this
In ipad its working but for desktop version ,how i can achieve same style for a select box using css only ? i m using HTML select tag <select> ......</select> for this.
I want to use this markup
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
A: I did have some sort of recollection of maybe seeing menu like that before but at least i couldnt find it.
These however could quite easily be changed to what you want:
http://www.filamentgroup.com/lab/jquery_ipod_style_and_flyout_menus/ - Especially this one.
http://www.filamentgroup.com/lab/jquery_ui_selectmenu_an_aria_accessible_plugin_for_styling_a_html_select/
A: I don't think it's possible to change the default styling of a select box just with CSS alone for most Grade A browsers on the desktop, but I could be wrong. You're going to have to use JavaScript and CSS to get what you are wanting. I'm sure there are some jQuery plugins that could help you out. Here are a few that I found, I've never tested these out but hopefully they provide some guidance.
http://www.bulgaria-web-developers.com/projects/javascript/selectbox/ (archived)
http://abeautifulsite.net/blog/2011/01/jquery-selectbox-plugin/ (archived)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: fgetcsv doesn't validate whether or not this is a csv file This question has been asked several times, but as it turns out all of the answers I have come across have been wrong.
I'm having a problem validating whether a file is a CSV or not. Users upload a file, and the application checks to see if fgetcsv works in order to make sure it's a CSV and not an Excel file or something else. That has been the traditional answer I'm finding via Google.
e.g.:
if ($form->file->receive()) {
$fileName = $form->file->getFileName();
$handle = fopen($fileName, 'r'); // or 'w', 'a'
if (fgetcsv($handle)) {
die('sos yer face');
}
if ($PHPExcelReader->canRead($fileName)) {
die('that\'s what she said');
}
}
What happens with the above is 'sos yer face' because fgetcsv validates as true no matter what you give it if your handle comes from fopen($fileName, 'r') as long as there is a file to read; and fgetcsv always false when using fopen($fileName, 'w') or 'a' because the pointer will be initiated at the EOF. This is according to the php.net documentation.
Maybe what I'm saying is ridiculous and I just don't realize it. Can anyone please fix my brain.
A: The problem with validating whether or not a file is a CSV file is that CSV is not a well-defined format. In fact, by most definitions of CSV, just about any file would be a valid CSV, treating each line as a row with a single column.
You'll need to come up with your own validation routine specific to the domain you are using it in.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ActiveRecord saves object when adding to association collection From the Rails docs:
Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object (the owner of the collection) is not yet stored in the database.
I would like to prevent this save from occurring (for better or worse). I've come up with three strategies and would be curious to hear which one is recommended.
*
*Block access to the DB during "<<". I posed the question of how best to accomplish this in another question: How can I prevent ActiveRecord from writing to the DB?. The proposed solution seems quite feasible.
*Leveraging the caveat of "except if the parent object is not yet stored in the db". Looking at the rails code, this condition is determined with the new_record? method. I wrote a little method that makes an object think it's new for the duration of a block.
# model.rb
def appear_as_new_record
instance_eval { alias :old_new_record? :new_record? }
instance_eval { alias :new_record? :present? }
yield
instance_eval { alias :new_record? :old_new_record? }
end
# used like this:
model.appear_as_new_record do
model.gadgets << gadget
end
*Using the 'build' method, to attach the object to the collection. This would like something like this (I know this doesn't cover all the edge cases)
new_gadget = model.gadgets.build(gadget.attributes)
new_gadget.id = gadget.id
there are quites a few scary things about this approach... but namely, it won't do a copy by reference. So if gadget also had a collection of objects already loaded, they wouldn't be accessible via the model without having to hit the db.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a jqueryUi.mouse.js version for jQuery mobile? I use a jqueryui.sortable widget for my site, and it doesn't work in mobile platforms. I looked through source code, and looks like it's mouse.js that binds handlers to events.
Is there a version of mouse.js for jQ mobile, or is there a simple way to translate jq mobile events (vmousedown, vmousemove, vmouseup) into usual mouse events, so that jQuery UI widgets receive them?
A: You could probably extend the library yourself without too much work.
The check for if the device support touch or not is easy:
var supportTouch = ("ontouchend" in document);
Then you can use the appropriate event based on if touch is enabled or not, the following is used in jQuery mobiles library:
var touchStartEvent = supportTouch ? "touchstart" : "mousedown",
touchStopEvent = supportTouch ? "touchend" : "mouseup",
touchMoveEvent = supportTouch ? "touchmove" : "mousemove";
Then you change the library to use those variables instead of the current hardcoded mouse events, probably looks something like this:
$(".sortable").bind("mousedown", doSomething());
But should look like this:
$(".sortable").bind(touchStartEvent, doSomething());
Do some testing before you do too much work, I have not tested the above code and not looked at the sortable library.
Another note is that some mobile devices don't support dragging of objects in the browser, one I know about is Windows Phone 7 (both with and without Mango). If you want to support those you should build some "non drag and drop" solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I insert a space before and after the content of a DOM element? If i have
<p>someword here</p>
<span>another thing here</span>
<div id="text">other thing here</div>
<!-- any other html tags -->
How do I insert a space in first and last position of the content?
I want the result to be
<p> someword here </p>
<span> another thing here </span>
<div id="text"> other thing here </div>
<!-- after tags like <p> and before </p> there have one space -->
A: Naive (and incorrect!) example would be:
var victims = document.querySelectorAll('body *');
for( var i = 0; i < victims.length; i++ ) {
victims[i].innerHTML = " " + victims[i].innerHTML + " ";
}
But once you run it, you will find out that all your elements got destroyed! Because, when you are changing innerHTML, you are changing element children as well. But we can avoid that, by not replacing content, but adding it:
var padLeft = document.createTextNode( " " );
var padRight = document.createTextNode( " " );
victims[i].appendChild( padRight );
victims[i].insertBefore( padLeft, victims[i].firstChild );
Looks cool! But, o no - we ruin our script tags, images and so on. Lets fix that too:
var victims = document.querySelectorAll('body *');
for( var i = 0; i < victims.length; i++ ) {
if( victims[i].hasChildNodes ) {
var padLeft = document.createTextNode( " " );
var padRight = document.createTextNode( " " );
victims[i].appendChild( padRight );
victims[i].insertBefore( padLeft, victims[i].firstChild );
}
}
Here you got the script :) Its not cross-browser all the way down to Netscape4, but is enough to understand basic idea.
A: If you insist using JS + RegExp to pad every element's innerHTML then you could do:
var
r = /(<[^>]+>)(.*)(<\/[^>]+>)/g,
func = function(str) {
return str.replace(r, function(original, a, b, c) {
return a + ' ' + (r.test(b) ? func(b) : b) + ' ' + c;
});
};
func("<p name='somename'>someword here</p>");
// "<p name='somename'> someword here </p>"
func("<div>I have things here<span>And more here<p>And even more here</p></span></div>");
// "<div> I have things here<span> And more here<p> And even more here </p> </span> </div>"
This is just to show how you could do this, but I highly recommend against it. The examples I provide is extremely simple. Anything like a normal page (say, the one you are looking at now) has all sorts of tags. This would be extremely exhaustive. And not very wise.
A: For a single element (as you seem to be asking):
element.html(' ' + element.html() + ' ')
For every element on the page (as your example seems to indicate), apply that to each element.
A: With jQuery*:
$('#id').html(' ' + $('#id').html() + ' ');
If you know that the elements do not have nested elements, it would be better to use the simpler:
$('#id').text(' ' + $('#id').text() + ' ');
(*) The reason for using jQuery and not plain javascript is that browsers (I'm looking at you, IE), have different inbuilt properties for getting and setting these values. jQuery saves you from having to worry about that.
A: in your case:
$("*").html(function(index, html){ return " " + html + " "; });
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Binding control name problem I have in the mainwindow this code:
<TabControl x:Name="tc" Margin="0" SelectedIndex="0">
<TabItem Header="Tab 1" Width="150"
IsSelected="false">
<!--<TextBox Width="200" Height="200"/>-->
</TabItem>
</TabControl>
i have a mainwindowviewmodel and i want it to bind to the controltab name which is tc:
private void AddTab_Execute(object parm)
{
s = s + 1;
TabItem Item = new TabItem();
Item.Width = 150;
Item.Header = "Tab " + s;
tc.Items.Add(Item);
}
he doesn't recognize tc
what do i have to do ?
A: This has nothing to do with binding, but it would be easier if you had one. You should not need to reference controls like the TabControl in the view-model.
Bind the ItemsSource of the the TabControl to an ObservableCollection, then you just need to add items to that collection. Use the ItemTemplate (header) and ContentTemplate (tab item content) to create the tabs from the items in the collecton dynamically.
A: First of all, be careful with how you are using the word "bind". That has a particular meaning which is not what you are doing in your example. To see what binding actually means, check out this article.
You cannot access controls in your UI from your viewmodel. What you should be doing is binding the ItemsSource of the TabControl to a collection in the viewmodel. You can create DataTemplateSelectors and use them for the TabControl's ContentTemplateSelector and ItemTemplateSelector if you want to select different templates depending on the item which is bound to each TabItem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating a dynamic page with master page content I've created functionality for my client to create dynamic pages. They create a page in the admin tool by specifying the Name and HTML for the page. Then, if someone on the front-end navigates to http://www.site.com/content/{Name}, the dynamic content is loaded.
Here's what I have. Global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Content", // Route name
"Content/{name}", // URL with parameters
new { controller = "ContentPages", action = "Page" }
);
}
and ContentPagesController:
public ContentResult Page(string name)
{
var contentPage = _contentPagesRepository.GetContentPage(name);
return new ContentResult
{
Content = contentPage.Content,
ContentType = "text/html"
};
}
This works great. Everything loads correctly.
I also have other pages that aren't dynamic, like the Contact Us page. All these other pages use a Layout page. The problem is that the dynamic pages don't have the HTML from the Layout page.
Is there any way to load up the dynamic content, and somehow utilize the RenderBody() function of the Layout page and wrap the content in the Layout HTML?
I'm using MVC 3 and Razor.
A: If you use MVC then your problem is solved. Load the page in the controller. Pass the page to a view. The view uses the layout.
Why are you not doing this?
That is how we do it and our pages can be different. You can store a view for each page type or create a view that works with your dynamic content. We have done both and both approaches work well. We actually use both approaches in the same project depending on the needs as both have strengths.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Need some help understanding transient properties in Core Data I read the documentation on transient properties but I can't really understand their purpose. Can someone tell me the difference between having and not having a transient property if I have a custom subclass of NSManagedObject like this?
@interface Board : NSManagedObject
{
NSMutableArray *_grid;
}
// Core Data to-many relationship
@property (nonatomic, retain) NSSet *pieces;
@property (nonatomic, readonly) NSArray *grid;
-(void)awake;
-(void)movePiece:(PieceState *)piece to_x:(int)x y:(int)y;
@end
@implementation Board
@dynamic pieces;
-(void)awakeFromInsert {
[super awakeFromInsert];
[self awake];
}
-(void)awakeFromFetch {
[super awakeFromFetch];
[self awake];
}
-(void)awake {
_grid = nil; // probably not necessary
}
-(NSArray *)grid {
if (!_grid) {
_grid = [[NSMutableArray alloc] initWithCapacity:10];
for (int i = 0; i < 10; i++) {
NSMutableArray *column = [[NSMutableArray alloc] initWithCapacity:10];
[_grid addObject:column];
for (int j = 0; j < 10; j++)
[column addObject:[NSNull null]];
[column release];
}
for (PieceState *piece in self.pieces)
if (piece.x >= 0 && piece.y >= 0)
[[_grid objectAtIndex:piece.x] replaceObjectAtIndex:piece.y withObject:piece];
}
return _grid;
}
-(void)movePiece:(PieceState *)piece to_x:(int)x y:(int)y {
if (x >= 0 && y >= 0) {
NSObject *capturedPieceObject = [[self.grid objectAtIndex:x] objectAtIndex:y];
if ([capturedPieceObject isKindOfClass:[PieceState class]]) {
PieceState *capturedPiece = (PieceState *)capturedPieceObject;
[self removePiecesObject:capturedPiece];
[[self managedObjectContext] deleteObject:capturedPiece];
capturedPiece = nil;
}
}
if (_grid) {
if (piece.x >= 0 && piece.y >= 0)
[[_grid objectAtIndex:piece.x] replaceObjectAtIndex:piece.y withObject:[NSNull null]];
if (x >= 0 && y >= 0)
[[_grid objectAtIndex:x] replaceObjectAtIndex:y withObject:piece];
}
[piece setX:x];
[piece setY:y];
}
- (void)didTurnIntoFault {
[_grid release];
_grid = nil;
[super didTurnIntoFault];
}
@end
So pieces and grid present two ways to access the same data. pieces is the actual Core Data relationship property, and is a dense list of all the pieces. grid is a way to find the contents of a particular space on the board addressed by (x, y) coordinates. grid is built lazily and updated (as long as it exists) when a piece changes location.
I'm not declaring grid as a transient property and everything is working fine. I'm just wondering if there is some unusual condition that could arise that would cause a bug if I don't declare a transient property.
I think I read transient properties are needed to get proper undo behavior if you're doing a derived property like this. I'm not using undo, and in any case I don't see how it could work in this case. If a piece move is undone, the undo manager can assign the old value of _grid back to it (maybe assuming I didn't make it readonly), but the old value is the same as the new value. It is a pointer to the same NSMutableArray instance, only the contents have changed. Anyway I don't use undo.
So do I get any benefit if I declare grid to be a transient property?
Additional question. What if I have code like this:
Board *board = someOtherManagedObject.board;
NSObject *boardContents = [[board.grid objectAtIndex:5] objectAtIndex:5];
Is it possible board is a fault after accessing someOtherManagedObject.board? I'm having trouble understanding faulting too. I think in that case my code would crash. I noticed awake sets _grid to nil. I think the sequence would be like this:
*
*grid getter called
*_grid allocated
*self.pieces accessed
*fault fires
*awake called
*_grid = nil
*return to grid getter
*[[_grid objectAtIndex:... access nil value, crash or at least no-op
*grid getter returns nil
*crash or incorrect behavior when boardContents is expected to contain a value
On the other hand, maybe if I declare grid to be a transient property, then the fault fires before my grid getter is called?
From TechZen:
Faults are placeholder objects that define an object graph with relationships but don't load attribute values. They will log as instances of either an NSManagedObject or of a private _NSFault... class.
Because unmodeled properties are only attributes of the custom NSManagedObject subclass and not the entity, the fault objects know nothing about them. Fault objects are initialized from the data model so that all the keys they respond to must be in the data model. This means faults will not reliably respond to request for unmodeled properties.
Wait what? I'm starting to realize my objects can be faults at any time but are you telling me they might not even be instances of my class!? Or if you use a custom subclass are they guaranteed to be the sort of faults that are instances of NSManagedObject (specifically my subclass)?
If they aren't instances of the custom class then what happens with something like this:
@interface Foo : NSManagedObject {
int data;
}
@property (nonatomic, retain) NSString *modeledProperty;
-(void)doSomething;
@end
@implementation Foo
@dynamic modeledProperty;
-(void)doSomething {
data++;
}
@end
What happens if I call doSomething on a fault?
*
*Doesn't respond to selector, crash
*Runs my code, but my instance variables don't exist, who knows what happens when it does data++
*data exists, just modeledProperty doesn't exist because it's a fault
Transient properties fix this problem. The transient property provides a key that the context can observe without saving. If you have a fault, sending it a key-value message for a transient property will trigger the context to "fire" the fault and load the complete managed object.
Okay, but what if I have an instance method that's not a property accessor, like doSomething above? How do I make sure I have a real object before I call it? Or can I call it, and first thing in the method body make sure I have a real object (for example by accessing a modeled property)?
In your case, you want to use a transient property for grid if the value of grid depends on the values of any modeled properties of the Board class. That is the only way to guarantee that grid will always be populated when you access it.
I thought if it depended on the values of modeled properties, then it would fire the fault when it depended on them, i.e. the line for (PieceState *piece in self.pieces) fires the fault because it accesses self.pieces, which is a modeled property. But you are telling me which?
*
*I can't even call the grid getter method on a fault
*I can call it but I can't use _grid the way I want to
It seems if I understand what you're saying and it's true, the custom subclasses of NSManagedObject are very limited.
*
*They can't have any instance methods that aren't modeled property getters or setters, because the object can't be guaranteed to exist in a useable state when they are called. (Exception: instance methods that are just helper methods for property accessors would be fine.)
*They can't have any instance variables for any useful purpose other than temporary caches of computed values, because those instance variables could be erased at any moment. I know they won't be persisted on disk, but I thought they would at least be persisted as long as I retained the object in memory.
If that's the case then are you not intended to put application logic in your custom NSManagedObject subclasses? Should application logic reside in other classes that have references to the managed objects, and the managed objects are only dumb objects that you read from and write to (just a little bit smart, with some capabilities to maintain data consistency)? Is the only point of subclassing NSManagedObject to do some "tricks" with non-standard data types?
A: The advantage of transient properties comes from the difference between modeled/observed properties and unmodeled/unobserved properties.
The managed object context uses key-value observing (KVO) to monitor modeled properties. Based on the information provided in the data model, it knows what properties must have values, what default, minimum and max values are, when the property is changed and, most importantly, whether the managed object has a key name for a property. All this provides the "managed" part of managed objects.
Modeled properties do not require a custom NSManagedObject subclass but can use a generic NSManagedObject instance initialized to an entity. Accessing a modeled property of a fault (see below) causes the fault to load fully.
The managed object context doesn't observe unmodeled properties and unmodeled properties require a custom NSManagedObject subclass. The unmodeled properties are attributes of the class only and do not show up in the entity and they are never persisted in Core Data. Changes to unmodeled properties go unnoticed by the context.
Faults are placeholder objects that define an object graph with relationships but don't load attribute values. You can think of them as "ghost" objects. They will log as instances of either an NSManagedObject or of a private _NSFault... class. If it is a NSManagedObject the attributes are all empty. When a fault "fires" or is "faulted in" the placeholder object is replaced with a fully populated NSManagedObject instance whose attributes can be read.
Because unmodeled properties are only attributes of the custom NSManagedObject subclass and not the entity, the fault objects know nothing about them. Fault objects are initialized from the data model so that all the keys they respond to must be in the data model. This means faults will not reliably respond to request for unmodeled properties.
Transient properties fix this problem. The transient property provides a key that the context can observe without saving. If you have a fault, sending it a key-value message for a transient property will trigger the context to "fire" the fault and load the complete managed object.
It is important to note that although the data model has a key name for a transient property, the property only has a value when the managed object is fully instantiated and loaded. This means that when you do any fetches, which operate solely in the persistent store, the transient properties will have no values.
In your case, you want to use a transient property for grid if the value of grid depends on the values of any modeled properties of the Board class. That is the only way to guarantee force Core Data to guarantee that grid will always be populated when you access it.
[Edit:
That last is highly theoretical. Using a transient property ensures that Core Data tracks the property such that the accessing the property will cause a fault to fire and provide the data. However, in practice accessing any modeled property will reliably fire the fault and unmodeled methods are always available (see below.)
You can also use:
+[NSManagedObject contextShouldIgnoreUnmodeledPropertyChanges:]
… to force a context to watch unmodeled properties. However, that can cause unanticipated and unmanaged behavior if the unmodeled properties have side effects.
I think that it is good practice to use transient properties whenever possible to make sure everything is covered.]
Update:
Okay, but what if I have an instance method that's not a property
accessor, like doSomething above? How do I make sure I have a real
object before I call it?
I think you're over thinking this and my cumbersome explanation didn't help any.
Core Data manages all these issues for you. I've been using Core Data as long as there has been a Core Data and I have never run into any problems. Core Data wouldn't be much use if you had to constantly stop and check if the objects were faults or not.
For example, I set up a simple model with classes like so:
Alpha:
@class Beta;
@interface Alpha : NSManagedObject {
@private
}
@property (nonatomic, retain) NSNumber * num;
@property (nonatomic, retain) NSString * aString;
@property (nonatomic, retain) NSSet *betas;
-(NSString *) unmodeledMethod;
@end
@interface Alpha (CoreDataGeneratedAccessors)
- (void)addBetasObject:(Beta *)value;
- (void)removeBetasObject:(Beta *)value;
- (void)addBetas:(NSSet *)values;
- (void)removeBetas:(NSSet *)values;
@end
@implementation Alpha
@dynamic num;
@dynamic aString;
@dynamic betas;
-(NSString *) unmodeledMethod{
return @"Alpha class unmodeledMethod return value";
}
@end
Beta:
@class Alpha;
@interface Beta : NSManagedObject {
@private
}
@property (nonatomic, retain) NSNumber * num;
@property (nonatomic, retain) NSSet *alphas;
-(NSString *) unmodeledMethod;
-(NSString *) accessModeledProperty;
@end
@interface Beta (CoreDataGeneratedAccessors)
- (void)addAlphasObject:(Alpha *)value;
- (void)removeAlphasObject:(Alpha *)value;
- (void)addAlphas:(NSSet *)values;
- (void)removeAlphas:(NSSet *)values;
@end
@implementation Beta
@dynamic num;
@dynamic alphas;
-(NSString *) unmodeledMethod{
return [NSString stringWithFormat:@"%@ isFault=%@", self, [self isFault] ? @"YES":@"NO"];
}
-(NSString *) accessModeledProperty{
return [NSString stringWithFormat:@"\n isFault =%@ \n access numValue=%@ \n isFault=%@", [self isFault] ? @"YES":@"NO", self.num,[self isFault] ? @"YES":@"NO"];
}
@end
Then I created an object graph of Alpha object with a related Beta object. Then I restarted the app and ran a fetch of all Alpha objects. Then I logged the following:
id aa=[fetchedObjects objectAtIndex:0];
id bb=[[aa valueForKey:@"betas"] anyObject];
NSLog(@"aa isFault= %@",[aa isFault] ? @"YES":@"NO");
//=> aa isFault= NO
NSLog(@"\naa = %@",aa);
//=> aa = <Alpha: 0x63431b0> (entity: Alpha; id: 0x6342780 <x-coredata://752A19D9-2177-45A9-9722-61A40973B1BC/Alpha/p1> ; data: {
//=> aString = "name 2";
//=> betas = (
//=> "0x63454c0 <x-coredata://752A19D9-2177-45A9-9722-61A40973B1BC/Beta/p7>"
//=> );
//=> // ignore fetchedProperty = "<relationship fault: 0x6153300 'fetchedProperty'>";
//=> num = 0;
//=> })
NSLog(@"\nbb isFault= %@",[bb isFault] ? @"YES":@"NO");
//=> bb isFault= YES
NSLog(@"\nany beta = %@",[[bb class] description]);
//=> any beta = Beta
NSLog(@"\n-[Beta unmodeledMethod] =\n \n %@",[bb unmodeledMethod]);
//=> -[Beta unmodeledMethod] =
//=> <Beta: 0x639de70> (entity: Beta; id: 0x639dbf0 <x-coredata://752A19D9-2177-45A9-9722-61A40973B1BC/Beta/p7> ; ...
//=>...data: <fault>) isFault=YES
NSLog(@"\n-[Beta accessModeledProperty] = \n %@",[bb accessModeledProperty]);
-[Beta accessModeledProperty] =
//=> isFault =NO
//=> access numValue=2
//=> isFault=YES
NSLog(@"\nbb = %@",bb);
//=>bb = <Beta: 0x6029a80> (entity: Beta; id: 0x6029460 <x-coredata://752A19D9-2177-45A9-9722-61A40973B1BC/Beta/p7> ; data: {
//=> alphas = "<relationship fault: 0x60290f0 'alphas'>";
//=> num = 2;
//=>})
Note that:
*
*Both aa and bb are set to the expected class even though I did a generic object assignment. The context ensures that the fetch returns the proper class.
*Even bb's class is Beta it reports as a fault meaning that the object represents an instance of the Beta class but that none of it's modeled properties are populated.
*The bb object responds to the unmodeledMethod selector even though within the method it still reports as a fault.
*Accessing the modeled property of Beta.num converts bb from a fault even before the call is made (the compiler sets it to trigger) but as soon as the access is done it reverts back to a fault.
*The objects in the relationships are not only faults but not the same objects returned by accessing the relationship. In Alpha.betas the Beta object has the address of 0x63454c0 whereas bb has the address of 0x639de70> while it is a fault. After it converts from a fault and then back again, it's a address is 0x6029a80. However, the managedObjectID of all three objects is the same.
The morals here are:
*
*"faults" are more about the state of a managed object and less about the actual class. Depending on how you access the object, you might get the actual subclass or you might get an instance of the hidden _NSFault… classes. From the coders perspective, all these different objects are interchangeable.
*Even if a managed object reports as a fault, it will still respond to unmodeled selectors.
*Accessing any modeled property causes the fault to fire and the object becomes fully active.
*Core Data does a great deal of object swapping behind the scenes that you can't control and shouldn't worry about.
In short don't worry about unmodeled properties and methods. They should work transparently. It's best practice to use transient properties especially if those properties have side effects with modeled properties. You can force a context to track unmodeled properties but that can cause unnecessary complexity.
If you have doubts, just perform test yourself on faults to ensure that your class works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: C++ vector containing pointers of user-defined types I have a problem with this code:
struct document_type_content
{
long long m_ID;
QString m_type_name;
};
std::vector<QString> document_type::get_fields_by_name(e_doc_type) const
{
std::vector<QString> tmp;
std::vector<document_type_content*>::iterator it = m_table_data.begin(),
it_end = m_table_data.end();
for ( ; it != it_end; ++it) {
document_type_content* cnt = *it;
tmp.push_back(cnt->m_type_name);
}
}
I'm using QtCreator for the project and it's gave me the following error(for lines, where the iterator is being initialized):
error: conversion from '__gnu_cxx::__normal_iterator<document_type_content* const*, std::vector<document_type_content*, std::allocator<document_type_content*> > >' to non-scalar type '__gnu_cxx::__normal_iterator<document_type_content**, std::vector<document_type_content*, std::allocator<document_type_content*> > >' requested
This may be simple problem, anyway, not to me:).
Great thanks in advance.
A: Because your function is constant, you only have constant access to the this pointer of your class. The results in a constant access to your vector. You need to get a const_iterator from the vector.
This should do the trick:
std::vector<QString> document_type::get_fields_by_name(e_doc_type) const
{
std::vector<QString> tmp;
std::vector<document_type_content*>::const_iterator it = m_table_data.begin(),
it_end = m_table_data.end();
for ( ; it != it_end; ++it) {
document_type_content* cnt = *it;
tmp.push_back(cnt->m_type_name);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: jquery validate, put messages before input box I'm using this jQuery plugin: http://docs.jquery.com/Plugins/Validation/validate and it seems to always put the messages after the input element. is there a way to get them to append to before the element instead of after?
A: Check errorPlacement: options for plugin:
$("#myform").validate({
errorPlacement: function(error, element) {
error.insertBefore(element);
}
})
A: Check errorPlacement: options for plugin
$("#myform").validate({
errorPlacement: function(error, element) {
element.before(error);
}
});
A: Use errorPlacement to control will allow you to put error message on specific place.
$("#myform").validate({
errorPlacement: function(error, element) {
error.appendTo(element.parent("td").next("td") );
}
});
Here are a few samples of errorPlacement with error options as well
*
*error.appendTo(element.parent("div").next("div"));
*error.appendTo($('#id'));
*error.insertAfter(element);
*error.insertBefore(element);
For custom error message and control creation
errorPlacement: function(error, element) {
var elementForm = "", containerError = "";
offset = element.offset();
elementForm = element.attr("name");
containerError = "#" + elementForm + "error";
error.prependTo(containerError);
error.addClass('message');
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: iPad: UISplitViewController top gets cut off inside UITabViewController I have a UITabViewController which contains a UISplitViewController as the first view. When the app loads and shows the split controller, the top of the two views are cut off and shifted down a maybe 15 pixels. Clicking another tab fixes the problems and jumps both views back up:
When app loads:
After clicking another tab problem is corrected:
Code being used (unimportant stuff left out):
NewsSplit *newsTemp = [[NewsSplit alloc] init];
...
// The view controllers to the tabBar
[tabController setViewControllers:[NSArray arrayWithObjects:newsSplit, eventSplit, classesSplit, dirSplit, settings, nil]];
...
self.window.rootViewController = self.tabController;
[self.window makeKeyAndVisible];
Why would the top be cut off and shifted down?
A: The short of it is that UISplitViewController isn't supposed to be embedded within another view controller. It's meant to be the root view controller of your window. I've run into this exact same issue in the past. Support for things such as rotation was glitchy. I eventually got it working like I wanted, but it was a hassle.
Unless they've improved things, I think you're going to have to subclass some things and shift frames around to get it to look right.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Select query issue I have the following data in a table:
Date ID Start END Duration_S Duration_A
9/12/2011 22216 9/12/2011 12:30:00 PM 9/12/2011 2:15:00 PM 6300 NULL
9/12/2011 22216 9/12/2011 2:30:00 PM 9/12/2011 2:39:00 PM 540 NULL
9/12/2011 22216 9/12/2011 5:20:00 PM 9/12/2011 5:50:00 PM 1800 NULL
My goal is to update the Duration_A column, currently Null.
The information I use to get that info is a table structured like so:
ID Start_Time State End_Time State_Duration
22216 6/3/10 2:07:58 1 6/3/10 2:20:58 800
22216 6/3/10 2:21:58 2 6/3/10 2:25:55 52
22216 6/3/10 5:21:58 2 6/3/10 5:31:05 600
To update my Duration_A, I have to sum the duration containing certain states(this is no problem), but the issue is that the Start_Time and End_Time have to match the Start and End of my first table. Here is what I am doing:
SELECT tblB.ID, SUM(tblB.StateDuration) AS Total, tblA.Start_Time,
tblA.End_Time
FROM
tblA INNER JOIN tblB ON tblB.Id = tblA.ID
tblB.Start_Time >= tblA.Start AND
tblB.End_Time <= tblA.End
WHERE STATE IN (1, 2, 3, 4, 5, 6, 7, 10, 11)
GROUP BY tblB.StateDuration, tblB.Id, tblA.Start_Time,
tblA.End_Time,tblB.End_Time,
tblB.Start_Time
This gives me the first duration when the start and end time of tblB match tblA, where I want the sum of all durations between those time frames. If I am not clear, let me know.
A: As far as I can understand you don't need to group by all there fields. Just add more conditions into the WHERE clause:
SELECT tblB.ID, SUM(tblB.StateDuration) AS Total, tblA.Start_Time,
tblA.End_Time
FROM
tblA INNER JOIN tblB ON tblB.Id = tblA.ID
tblB.Start_Time >= tblA.Start AND
tblB.End_Time <= tblA.End
WHERE STATE IN (1, 2, 3, 4, 5, 6, 7, 10, 11) AND
tblA.Start_Time <= tblB.Start_Time AND
tblB.End_Time <= tblA.End_Time
GROUP BY tblB.id
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Git command with wildcard expansion
Possible Duplicate:
Can you delete multiple branches in one command with Git?
I'm trying to clear out my old feature branches in my git repo, and I find myself typing
git branch -d SOME_BRANCH_NAME
for each branch name. Does git support any type of wildcard expansion, so I could specify something like:
git branch -d temp_branch_*
thanks
A: Well, in the worst case, you could:
git branch | grep temp_branch | xargs git branch -d
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Listview item background image problem in my android application I have in my application a listview with an adapter that uses different layouts for the items.
I want the result to be like in the attached exp_result.png.
http://imageshack.us/photo/my-images/717/expresult.png/
But unfortunatly - I get like in result.png.
http://imageshack.us/photo/my-images/839/resultf.png/
The problem is that image stretches on the screen not the way I wanted.
Any ideas?
Maybe other solution to this layout - maybe built in?
Drawables are in the links, since I cannot upload images. The original picture is like in the first listview item in the exp_result.png. I want to use 1 picture for each - top, buttom and middle and to be used no matter the listview item size. XML is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/list_up" >
<TextView
android:id="@+id/name_entry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="28dip" />
<TextView
android:id="@+id/number_entry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="28dip" />
</LinearLayout>
I can really really use some help here.
Yoav
A: This may be a good application of the 9-patch image type:
9-Patch
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Subversion - What tool will help me to package project? I have set up subversion on my computer
Is there a tool that can build a package for my project when i commit ?
Thanks
A: What kind of project is it?
There are various continuous integration servers that can poll subversion for changes, and perform a build and run tests each time a new commit is found.
One such server that is quite popular is Jenkins
Jenkins is primarely for building Java based projects, but I think there are plugins for building different kind of projects as well.
No matter what kind of technology your project is, I'm sure there's a continuous integration server available that fits your needs.
A: You want some sort of post-commit hook: a script that executes every time you commit.
There may also be some sort of continuous integration software for your particular project type, as @rlovtang mentions.
A: It's is a javascript project and just package all file after time i commit
and i run it in my local computer, no connect to another server
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trouble finding source of a designer exception in VS2010 When loading the mainform of a WinForms app I'm working on, I encountered a familiar exception: a "To prevent possible data loss before loading the designer, the following errors must be resolved" error. The stacktrace is as follows:
Object reference not set to an instance of an object.
Instances of this error (4)
1. Hide Call Stack
at System.ComponentModel.ReflectPropertyDescriptor.SetValue(Object component, Object value)
at Microsoft.VisualStudio.Shell.Design.VsTargetFrameworkPropertyDescriptor.SetValue(Object component, Object value)
at System.Windows.Forms.Design.ControlDesigner.CanResetSizePropertyDescriptor.SetValue(Object component, Object value)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializePropertyAssignStatement(IDesignerSerializationManager manager, CodeAssignStatement statement, CodePropertyReferenceExpression propertyReferenceEx, Boolean reportError)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeAssignStatement(IDesignerSerializationManager manager, CodeAssignStatement statement)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeStatement(IDesignerSerializationManager manager, CodeStatement statement)
I know what's causing this error -- there are four lines buried somewhere in the MainForm that make reference to an image object that doesn't exist at design time. I even have an idea of how to fix the error, thanks to this post at MSDN. The trouble is, I can't find the lines from which the exception is thrown. Normally I would navigate to the exception using the Error List window, but it says that there are zero errors. Any ideas as to how I can locate the offending lines?
A: I usually find that this relates to a user control hosted on the form that relies on a DI container or similar, but as you say it is sometimes difficult to determine the source from the call stack the designer provides. If you're hosting a lot of controls, to figure out which controls are causing the issue without diving into each one you could:
*
*Make a list of the user controls that are directly hosted on the form, then
*Create a new temporary form, then
*Drop each user control in your list onto the form to see which one kills the designer
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Display validation error in DataGridCell tooltip I have a WPF DataGrid which displays types that implement IDataErrorInfo. As expected when the validation fails the row gets the red exclamation mark and the invalid cell gets the red highlight.
This is all well and good; however, I want the validation error message to display in the tooltip of the invalid cell so the user has some indication of what is wrong. I presently have:
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors[0].ErrorContent}"/>
</Style>
</DataGrid.CellStyle>
This approach works for TextBox but not for DataGridCell. What is the difference?
A: Take a look at this MSDN log post:
https://blogs.msdn.microsoft.com/bethmassi/2008/06/27/displaying-data-validation-messages-in-wpf/
Follow its instructions to create a textbox cell editing template that will look something like this:
<Style TargetType="TextBox" x:Key="errTemplate">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
Then, you can use it in your datagrid by setting the EditingElementStyle like so:
<DataGridTextColumn Header="Variable"
Binding="{Binding Variable, ValidatesOnDataErrors=True}"
EditingElementStyle="{StaticResource errTemplate}"/>
It is important to use the data trigger so that you can support a standard tool tip as well as a tool tip when there is an error as explained in this post:
Tooltip Not Showing Up When No Validation Error WPF
A: I have something similiar in a project I'm working on right now, and it goes something like this:
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="DataGridCell.ToolTip"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Style>
</DataGridTextColumn.ElementStyle>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to extract a specific frequency range from a .wav file? I'm really new on sound processing, so maybe my question will be trivial.
What I want to do is to extract a specific frequency range (let's say 150-400 Hz) from a wav file, using R. In other words, I want to create another wave file (wave2) that contains only the frequency component that I specify (150 to 400 Hz, or what else).
I read something on the net, and I discovered out that this can be done with a FFT analysis, and here's come the problems.
Suppose I've this code:
library(sound)
s1 <- Sine(440, 1)
s2 <- Sine(880, 1)
s3 <- s1 + s2
s3.s <- as.vector(s3$sound)
# s3.s is now a vector, with length 44100;
# bitrate is 44100 (by default)
# so total time of s3 is 1sec.
# now I calculate frequencies
N <- length(s3.s) # 44100
k <- c(0:(N-1))
Fs <- 44100 # sampling rate
T <- N / Fs
freq <- k / T
x <- fft(s3.s) / N
plot(freq[1:22050], x[1:22050], type="l") # we need just the first half of FFT computation
The plot we obtain is:
Well, there are two peaks. If we want to know to what frequency they correspond, just find:
order(Mod(x)[1:22050], decreasing=T)[1:10]
[1] 441 881 882 880 883 442 440 879 884 878
First two values are really near to the frequency I've used to create my sound:
real computed
Freq1: 440 | 441
Freq2: 880 | 881
So, now comes the problem: how to proceed, if I want to delete from my sound the frequencies in the range, say, (1, 500) ? And how to select (and save) only the range (1, 500) ?
What I attend, is that my new sound (with deleted frequencies) will be something near to simple Sine(freq=880, duration=1) (I know, it cannot be exactly like so!).
Is that possible?
I'm pretty sure that fft(DATA, inverse = TRUE) is what I need. But I'm not sure, and however I don't know how to proceed.
A: If you don't want to programm it, you can use Praat.
Praat is a free scientific software program for the analysis of speech in phonetics.
But you can also use it to edit the spectrum of any sound (remove frequencies, ...) and then export the result as a new sound file.
A: Maybe I missed the point, but don't you already have your answer? From your post:
order(Mod(x)[1:22050], decreasing=T)[1:10]
[1] 441 881 882 880 883 442 440 879 884 878
Simply collect all values above 500:
junk <- order(Mod(x)[1:22050], decreasing=T)[1:10]
(junk1 <- junk[junk > 500])
[1] 881 882 880 883 879 884 878
To generate the new signal simply repeat what you did to build the original signal:
junk2 <- Sine(0, 1)
for (i in 1:length(junk1)) {
junk2 <- junk2 + Sine(junk1[i], 1)
}
junk2.s <- as.vector(junk2$sound)
To keep the values below 500:
(junk3 <- junk[junk <= 500])
[1] 441 442 440
A: look at the 'signal' package on cran, one of the filter functions there should do
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Change Control's Text Color Depending on Control's Background Color I have a TextBox that displays a color as its background color and the background color code in its text. I have set the text color as Black.
The problem is that if the user sets the color as Black then the color code will be unreadable. How do I set the text color programmatically so that it becomes readable when the user selects any color?
A: You can use negative color for the text:
Color InvertColor(Color sourceColor) {
return Color.FromArgb(255 - sourceColor.R,
255 - sourceColor.G,
255 - sourceColor.B);
}
Any color is guaranteed to be more or less readable on its negative color, so there you go. This is a quick and dirty way to invert a color, you may also want to check the answers for this question: How do I invert a color?
Another option is to add a white halo to the black text. That's what people do in GIS applications to ensure that map labels are readable on top of any surface. The idea of halo effect is to have a thin white border around black text. This way the text is readable whether it's on white background (the border becomes invisible) or on black background (the border outlines the text).
There are multiple tutorials on the topic, like this article or this SO question (with VB.NET sample).
When you have a Color picked out, just assign it to the ForeColor property of your textbox like this:
txtColor.ForeColor = mycolor;
A: Not working on Gray color.
This code is more usable:
lblCarColor.BackColor = color;
if ((color.B + color.R + color.G) / 3 <= 128)
{
lblCarColor.ForeColor = Color.White;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: History.js howto questions and behaviour in IE9 and FF3 I would like to use History.js but it doesn't work as expected and I'm not sure if I do it the right way...
Here is what I did:
<!-- jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<!-- jQuery UI -->
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>
<!-- jQuery ScrollTo Plugin -->
<script defer src="mySite/js/jquery.scrollto.min.js"></script>
<!-- JSON2 Plugin -->
<script type="text/javascript">if ( typeof window.JSON === 'undefined' ) { document.write('<script src="mySite/js/json2.js"><\/script>'); }</script>
<!-- jQuery ScrollTo Plugin -->
<script src="mySite/js/amplify.store.min.js"></script>
<!-- History.js -->
<script defer src="mySite/js/history.adapter.jquery.js"></script>
<script defer src="mySite/js/history.js"></script>
<script defer src="mySite/js/history.html4.js"></script>
<!-- ajaxify-mySite.js -->
<script defer src="mySite/js/ajaxify-mySite.js"></script>
The ajaxify-mySite.js script is mostly the same as it is shown here
Thats whats going wrong:
In IE9 I get urls like "http://www.mySite.com/index.php/tools.html#index.php/contact.html?&_suid=478" (it should be "http://www.mySite.com/index.php#contact.html?&_suid=478" I think) and the content won't load the most time..
My FF3.6.21 loads all pages without using this script - is this normal behaviour?
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Conditional from SUM() of another table? i have data 2 table like this
Table Transaction
ID | Amount
1 | 200
2 | 300
Table Payment
ID | Transaction | Amount
1 | 1 | 200
2 | 2 | 150
3 | 2 | 100
then i using query
SELECT `transaction`.id AS `id`,
`transaction`.amount AS amount,
SUM(payment.amount) AS payment,
`transaction`.amount - SUM(payment.amount) AS balance
FROM `transaction`
LEFT JOIN payment
ON payment.`transaction` = `transaction`.id
GROUP BY payment.`transaction`;
and then i get data like this
id | amount | payment | balance
1 | 200 | 200 | 0
2 | 300 | 250 | 50
Now how do i make conditional to only show data which balance is more than 0?
Which is should only show row id 2
i tried do this query, but it give me error.
SELECT `transaction`.id AS `id`,
`transaction`.amount AS amount,
SUM(payment.amount) AS payment,
`transaction`.amount - SUM(payment.amount) AS balance
FROM `transaction`
LEFT JOIN payment
ON payment.`transaction` = `transaction`.id
WHERE `transaction`.amount - SUM(payment.amount) > 0
GROUP BY payment.`transaction`;
Thank you,
Gusde
A: The "HAVING" SQL clause does what you are looking for. It like "WHERE", except it runs after the JOINS and GROUP BY's, and allows you filter based on the almost final output. It's also useful for finding missing relationships between tables you've joined together.
SELECT `transaction`.id AS `id`,
`transaction`.amount AS amount,
SUM(payment.amount) AS payment,
`transaction`.amount - SUM(payment.amount) AS balance
FROM `transaction`
LEFT JOIN payment
ON payment.`transaction` = `transaction`.id
GROUP BY payment.`transaction`
HAVING balance > 0;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Getting row of UITableView cell on button press I have a tableview controller that displays a row of cells. Each cell has 3 buttons. I have numbered the tags for each cell to be 1,2,3. The problem is I don't know how to find on which cell a button is being pressed. I'm currently only getting the sender's tag when one of the buttons has been pressed. Is there a way to get the cell row number as well when a button is pressed?
A: Edit: This answer is outdated. Please use this method instead
Try this:
-(void)button1Tapped:(id)sender
{
UIButton *senderButton = (UIButton *)sender;
UITableViewCell *buttonCell = (UITableViewCell *)[senderButton superview];
UITableView* table = (UITableView *)[buttonCell superview];
NSIndexPath* pathOfTheCell = [table indexPathForCell:buttonCell];
NSInteger rowOfTheCell = [pathOfTheCell row];
NSLog(@"rowofthecell %d", rowOfTheCell);
}
Edit: If you are using contentView, use this for buttonCell instead:
UITableViewCell *buttonCell = (UITableViewCell *)senderButton.superview.superview;
A: There are two ways:
*
*@H2CO3 is right. You can do what @user523234 suggested, but with a small change, to respect the UITableViewCellContentView that should come in between the UIButton and the UITableViewCell. So to modify his code:
- (IBAction)button1Tapped:(id)sender
{
UIButton *senderButton = (UIButton *)sender;
UITableViewCellContentView *cellContentView = (UITableViewCellContentView *)senderButton.superview;
UITableViewCell *tableViewCell = (UITableViewCell *)cellContentView.superview;
UITableView* tableView = (UITableView *)tableViewCell.superview;
NSIndexPath* pathOfTheCell = [tableView indexPathForCell:tableViewCell];
NSInteger rowOfTheCell = pathOfTheCell.row;
NSLog(@"rowofthecell %d", rowOfTheCell);
}
*If you create a custom UITableViewCell (your own subclass), then you can simply call self in the IBAction. You can link the IBAction function to your button by using storyboard or programmatically when you set up the cell.
- (IBAction)button1Tapped:(id)sender
{
UITableView* tableView = (UITableView *)self.superview;
NSIndexPath* pathOfTheCell = [tableView indexPathForCell:self];
NSInteger rowOfTheCell = pathOfTheCell.row;
NSLog(@"rowofthecell %d", rowOfTheCell);
}
A: You should really be using this method instead:
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
Swift version:
let buttonPosition = sender.convert(CGPoint(), to:tableView)
let indexPath = tableView.indexPathForRow(at:buttonPosition)
That will give you the indexPath based on the position of the button that was pressed. Then you'd just call cellForRowAtIndexPath if you need the cell or indexPath.row if you need the row number.
If you're paranoid, you can check for if (indexPath) ... before using it just in case the indexPath isn't found for that point on the table view.
All of the other answers are likely to break if Apple decides to change the view structure.
A: I assume you add buttons to cell in cellForRowAtIndexPath, then what I would do is to create a custom class subclass UIButton, add a tag called rowNumber, and append that data while you adding button to cell.
A: Another simple way:
*
*Get the point of touch in tableView
*Then get index path of cell at point
*The index path contains row index
The code is:
- (void)buttonTapped:(id)sender {
UITapGestureRecognizer *tap = (UITapGestureRecognizer *)sender;
CGPoint point = [tap locationInView:theTableView];
NSIndexPath *theIndexPath = [theTableView indexPathForRowAtPoint:point];
NSInteger theRowIndex = theIndexPath.row;
// do your stuff here
// ...
}
A: I would recommend this way to fetch indexPath of cell which has any custom subview - (compatible with iOS 7 as well as all previous versions)
-(void)button1Tapped:(id)sender {
//- (void)cellSubviewTapped:(UIGestureRecognizer *)gestureRecognizer {
// UIView *parentCell = gestureRecognizer.view.superview;
UIView *parentCell = sender.superview;
while (![parentCell isKindOfClass:[UITableViewCell class]]) { // iOS 7 onwards the table cell hierachy has changed.
parentCell = parentCell.superview;
}
UIView *parentView = parentCell.superview;
while (![parentView isKindOfClass:[UITableView class]]) { // iOS 7 onwards the table cell hierachy has changed.
parentView = parentView.superview;
}
UITableView *tableView = (UITableView *)parentView;
NSIndexPath *indexPath = [tableView indexPathForCell:(UITableViewCell *)parentCell];
NSLog(@"indexPath = %@", indexPath);
}
This doesn't require self.tablview either.
Also, notice the commented code which is useful if you want the same through a @selector of UIGestureRecognizer added to your custom subview.
A: Swift 3
Note: This should really go in the accepted answer above, except that meta frowns upon such edits.
@IBAction func doSomething(_ sender: UIButton) {
let buttonPosition = sender.convert(CGPoint(), to: tableView)
let index = tableView.indexPathForRow(at: buttonPosition)
}
Two minor comments:
*
*The default function has sender type as Any, which doesn't have convert.
*CGPointZero can be replaced by CGPoint()
A: One solution could be to check the tag of the button's superview or even higher in the view hierarchy (if the button is in the cell's content view).
A: I would like to share code in swift -
extension UITableView
{
func indexPathForCellContainingView(view1:UIView?)->NSIndexPath?
{
var view = view1;
while view != nil {
if (view?.isKindOfClass(UITableViewCell) == true)
{
return self.indexPathForCell(view as! UITableViewCell)!
}
else
{
view = view?.superview;
}
}
return nil
}
}
A: In swift:
@IBAction func buttonAction(_ sender: UIButton) {
guard let indexPath = tableView.indexPathForRow(at: sender.convert(CGPoint(), to: tableView)) else {
return
}
// do something
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "84"
} |
Q: I have an app where I am asking for input a username and password.Right now. It has been changed. Once the user clicks on login in the login menu I have an app where I am asking for input a username and password.
Right now. It has been changed. Once the user clicks on login in the login menu.
The username should be refilled with a known username and we only ask the user to input password to improve user experience.
Could we use the exist username edit text in my layout file or i have to change to label instead of edit text? I know i can use setText() to populate the username edit text field.
The question is not about saving username (using sharedpreference). what is the best way to
change my code to use ( either edit box or label ).
Please let me know what is the best case to avoid too much change.
A: Use SharedPreferences to store the usreanme and then everytime you load the layout in your code, check your sharedPreferences and fill the username edittext using setText
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Fine tuning Routes in MVC3 I have the following routes defined:
routes.MapRoute(
"EventInfo", // Route name
"Events/{year}/{month}/{day}", // URL with parameters
new { controller = "Events", action = "Index", year = UrlParameter.Optional, month = UrlParameter.Optional, day = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"EventType", // Route name
"Events/Type/{id}/{year}/{month}/{day}", // URL with parameters
new { controller = "Events", action = "Type", id = UrlParameter.Optional, year = UrlParameter.Optional, month = UrlParameter.Optional, day = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
I am seeing some "weird" behavior when navigating. For instance I have an Html.ActionLink on my main menu which is defined like:
<li class="@item.Class">@Html.ActionLink(item.Title, item.Action, item.Controller, null, new { @class="standard" } )</li>
I also have a sidebar secondary menu defined the same way in my View - I just change what Model feeds the 2 different (Partial) Views. For instance, my Main Menu's Model looks like:
public MenuItems()
{
List = new List<Menu> {
new Menu { Controller="Home", Action="Index", Title="Home", Class="grid-2 menubutton" },
new Menu { Controller="Info", Action="Index", Title="Information", Class="grid-2 menubutton" },
new Menu { Controller="Events", Action="Index", Title="Events", Class="grid-2 menubutton" },
new Menu { Controller="Guilds", Action="Index", Title="Guilds", Class="grid-2 menubutton" },
new Menu { Controller="Populace", Action="Index", Title="Caer Galenites", Class="grid-3 menubutton" },
new Menu { Controller="Loop", Action="Index", Title="Get in the Loop", Class="grid-3 menubutton" }
};
}
Now, I am at the point of testing my Events page (see the Routes above) so I am altering the URL once I am on the main Events page. i.e.: I click on Events in the main menu and get to http://site.com/Events and I see my event listings. I then append a year like http://site.com/Events/2011 and the filter works. Append a Month like http://site.com/Events/2011/9 and now I see the current months' events. So far, so good.
I then hover over one of the sidebar menu items expecting to see http://site.com/Events/Type/Kingdom but instead I am seeing http://site.com/Events/Type/Kingdom/2011/9. I hover over my main menu link and instead of http://site.com/Events I see http://site.com/Events/2011/9. If I hover over the other Main Menu items they are showing the correct URLs.
Why? How do I "fix it"?
TIA
A: Following the advice in the comments above I got it all working. Instead of having the date parts as part of the URL (yyy/mm/dd) I opted for a single date string (yyyy-mm-dd or yyyy-mm or yyyy) and have a parser to pull that apart then bring back the correct listings.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PDO pgsql fetch with absolute position cursor fails I am trying to implement a paging feature using PDO's ability to create cursors.
Currently, my code looks a bit like this (very complicated, I know that):
$pdo = new PDO();
$pdo->setAttribute(PDO::ATTR_CURSOR, PDO::CURSOR_SCROLL);
// prepared select-query omitted
$pdoStatement = $pdo->execute();
$start_index = MAX_THINGS_PER_PAGE * $current_page - MAX_THINGS_PER_PAGE;
$stop_index = MAX_THINGS_PER_PAGE * $current_page;
$row_count = $this->statement->rowCount(); // works for the PgSQL driver
$index = $start_index;
while (($row_count > 0) && ($index < $stop_index))
{
// try-catch block omitted
$values[] = $this->statement->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, $index);
--$row_count;
++$index;
}
However, seemingly, no matter what $start_index is, the query only fetches the first 10 (which is the value of MAX_THINGS_PER_PAGE) rows of the resultset. Always.
Probably I am doing something wrong, but the art of using cursors for pagination seems to be somewhat arcane and underdocumented...
A: I just ran into this problem today. PDOStatement::rowCount() does not work for SELECT on some databases. From PDOStatement::rowCount:
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
It took me quite a bit to realize this, as I thought that it was a problem with using cursors.
This is the approach I took: Replace the use of PDOStatement::rowCount() with the following:
<?php
$row_count = count($stmt->fetchAll());
?>
It is not efficient memory-wise, but this is what many databases do to calculate the total number of rows anyway.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: HTML/CSS Two auto-width columns I'm having an incredibly difficult time achieving the following effect:
==========================================================
= Variable Width = <input style="width: 100%" /> =
==========================================================
I am using the following HTML:
<dl>
<dt>
<label>Variable Width</label>
</dt>
<dd>
<input style="width: 100%" />
</dd>
</dl>
Please note that I've trimmed down the HTML for readability.
Can anyone suggest what CSS I should use to achieve this effect? I would prefer to not have to use display: table because I am looking for cross-browser compatibility that reaches IE7.
A: This is "incredibly difficult" to do without <table> or display: table.. until you know how!
See: http://jsfiddle.net/thirtydot/aLgwt/
This works in IE7 and greater + all modern browsers.
dt {
float: left
}
dd {
overflow: hidden;
padding: 0 4px 0 9px
}
dd input {
width: 100%
}
An explanation of why it works is here.
A: BTW, if you want to have the right column fixed but the left one with auto-with you can change this pattern to:
CSS:
dt {
float: right;
}
dd {
overflow: hidden;
padding: 0 4px 0 9px;
}
dd input {
width: 100%
}
Notice, that label should follow before input anyway.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Using a view bounds with scalaz I'm taking my first foray into scalaz by converting an existing class to use the Monoid trait. What I am trying to achieve is to set a view bound on my class type parameter to ensure that it can only be used with types that can be implicitly converted to a Monoid. My (simplified) class definition is thus:
import scalaz._
import Scalaz._
case class Foo[T <% Monoid[T]](v: T)
new Foo(42)
Compiling this simple example gives the compiler error:
error: No implicit view available from Int => scalaz.Monoid[Int].
Previously this view bound was defined against my own custom trait with an implicit conversion from T to the trait and this worked fine.
What am I missing now that I have converted this to scalaz?
Thanks,
Chris
A: You are supposed to be using a context bound, and not a view bound there.
import scalaz._
import Scalaz._
case class Foo[T : Monoid](v: T)
new Foo(42)
The T : Monoid notation means that there is an implicit of type Monoid[T] in scope. In fact, it desugars to the following:
case class Foo[T](v: T)(implicit ev: Monoid[T])
This is known as type class pattern and you can read more about it here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Python/Excel: How to freeze the top line of a generated sheet (or sheets) This isn't actually a question -- it's more of an FYI. It took me a while to figure this out, since my searching with Google turned up bits and pieces (including some related questions here on StackOverflow), but no article or blurb gave me the whole answer all in one place. I was finally able to figure it out by recording a macro in Excel and looking at its source code and combining what I found there with what I found on the web.
Anyway, the following code snippets show two helper functions, plus a sample main() type of function (which I always use, even in Perl and Python apps, since I have a C/C++/Java background).
The first helper method will auto-fit every used column on the given sheet. Since the auto-fit logic depends on the data in the cells, as well as the font(s) in use, you shouldn't call this method until the entire sheet has been completely populated with your data. Also, I'm pretty new to VBA, so I'm not so sure that this line:
sheet.Cells(1, i).EntireColumn.AutoFit()
is correct, but it does seem to work just fine. If it's not entirely correct, maybe you can post a correction.
def autoFitSheet(sheet):
"""Auto-fits all the used columns on the given sheet. Obviously, this
method should only be called _after_ the sheet has been populated."""
firstCol = sheet.UsedRange.Column
numCols = sheet.UsedRange.Columns.Count
for i in range(firstCol, (firstCol + numCols)):
sheet.Cells(1, i).EntireColumn.AutoFit()
The second helper is a "freeze the top line" method. All it does is freeze the top line of the sheet that you pass it. A side effect of this method is that the sheet becomes the active sheet in the spreadsheet, so you might need/want to activate some other sheet once all your sheets' top lines have been frozen.
def freezeTopLine(window, sheet):
"""Freezes the top line of the given sheet."""
sheet.Activate()
window.SplitColumn = 0
window.SplitRow = 1
window.FreezePanes = True
The last snippet is a sample main() function, which just shows how to call the two helper methods. I'm actually using code very similar to this to populate a spreadsheet with mutliple tabs/sheets, and it works perfectly (on Windows 7 -- can't guarantee how well it will work on your system).
def main(...):
#
# (whatever...)
#
excel = win32.gencache.EnsureDispatch('Excel.Application')
workbook = excel.Workbooks.Add()
sheets = workbook.Sheets
window = workbook.Windows(1)
sheet1 = workbook.Worksheets('Sheet1')
straddles.Name = 'My First Sheet'
straddles.Tab.ColorIndex = 6 # yellow
sheet2 = workbook.Worksheets('Sheet2')
cashSummary.Name = 'Some Other Sheet'
cashSummary.Tab.ColorIndex = 4 # bright green
#
# Populate sheets...
#
for sheet in sheets:
autoFitSheet(sheet)
freezeTopLine(sheet)
#
# (whatever...)
#
Like I said, it took me a while to figure this out, and I was hoping that maybe I could save someone some of the headache that I went through. Good luck.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Closure versus classic class I'm using Node.js.
Could you tell where is the advantage of using this (closure):
function sayHello() {
var num = 0;
var sayAlert = function (val) {
num++;
console.log(num);
}
return sayAlert;
}
over this old classic one:
function sayHello2() {
var num = 0;
this.sayAlert = function (val) {
num++;
console.log(num);
}
}
var ee1 = sayHello();
ee1(5);
ee1(6);
var ee2 = new sayHello2();
ee2.sayAlert(5);
ee2.sayAlert(6);
(shorter code perhaps for closure and more "JavaScipt way"?)
A: It seems like what you're really after is a function with a static counter. For that you can just use an immediately executing function.
var say = (function() {
var num = 0;
return function (val) {
// Not sure why you're passing val here, it's not used
num++;
console.log(num);
}
})();
Unless what you want is multiple counters, then you should use better names so it's clear to all who read it.
function createCounter() {
var num = 0;
return function () {
console.log(++num);
}
}
In the second example, you've implemented the same thing by using a counter on the closure of the constructor let's call it Speaker.
function Speaker() {
var num = 0;
this.sayAlert = function() {
console.log(++num);
}
}
They all do kind of the same thing
say(); say(); //outputs 1,2
var speaker = new Speaker();
speaker.sayAlert(); speaker.sayAlert(); //outputs 1,2
var speaker2 = new Speaker();
speaker2.sayAlert(); speaker2.sayAlert(); //outputs 1,2
var ctr1 = createCounter(); ctr1(); ctr1(); //outputs 1,2
var ctr2 = createCounter(); ctr2(); ctr2(); //outputs 1,2
Which one to use depends on whether you want a function or an object. And mostly whether you prefer to write functional or OO code.
A: Neither is better. It depends on your needs.
They're nearly identical, except that one returns a function and the other returns an object that holds a function.
A: The second example allows to have more than one method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: button not working with .show() and .hide() functions I ve faced a problem which I have no idea the why ... so Im here..
http://www.agenciadefreela.com.br/testJquery.php
thats the page!
First, I have to choose the "tipo" ...
if is foto, I have to fill the "nome" ... and then, the "ok" button will show up. Once clicked, it will submit the form. Working fine.
But, When I change the "tipo" to video, I have to choose between "arquivo" (portuguese word to file) or "vimeo/youtube" link ...
If is file (and we have a albuns's name) the ok button will show up ... BUT ...ITS NOT WORKING.... when the button is clicked, nothing happens ...
Its the same when link has been choosen, and in this case, theres a link validator ...
any idea ?????
ps: do not click in the "data" field... I didnt upload the files, so, if u do it, you will get a javascript error !
thns !
A: It's not working because the console logs:
hiddenMsg is not defined
hiddenMsg();
If you post your code on jsfiddle we might help
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What version of IE does Outlook 2003 use? I am running into some formatting issues while testing. My email looks fine in IE9, so I am wondering what version Outlook 2003 uses.
A: When Outlook 2003 is installed for the first time, it uses the version of IE that is installed on that particular OS as it's rendering engine. From there, if IE6 is upgraded to IE7, Outlook will still use the original version of IE (in this case IE6).
If you don't have a version of IE6, I suggest using a tool like Email on Acid for testing.
A: Actually for reasons best known to Microsoft it uses the Word rendering engine. I believe they cited something about security or some such at the time.
This is a very annoying decision as it means support for all sorts of CSS and HTML goodies is extremely lacking.
EDIT: Apologies that seems to be from 2007 onwards, but I will leave the answer here as it is probably still relevant as those with newer Outlooks will still have problems unless it is some internal email and you are sure everyone will have 2003.
It seems 2003 uses the IE6 render engine which is probably almost as annoying.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why does casting give CS0030, while "as" works? Suppose I have a generic method:
T Foo(T x) {
return x;
}
So far so good. But I want to do something special if it's a Hashtable. (I know this is a completely contrived example. Foo() isn't a very exciting method, either. Play along.)
if (typeof(T) == typeof(Hashtable)) {
var h = ((Hashtable)x); // CS0030: Cannot convert type 'T' to 'System.Collections.Hashtable'
}
Darn. To be fair, though, I can't actually tell if this should be legal C# or not. Well, what if I try doing it a different way?
if (typeof(T) == typeof(Hashtable)) {
var h = x as Hashtable; // works (and no, h isn't null)
}
That's a little weird. According to MSDN, expression as Type is (except for evaluating expression twice) the same as expression is type ? (type)expression : (type)null.
What happens if I try to use the equivalent expression from the docs?
if (typeof(T) == typeof(Hashtable)) {
var h = (x is Hashtable ? (Hashtable)x : (Hashtable)null); // CS0030: Cannot convert type 'T' to 'System.Collections.Hashtable'
}
The only documented difference between casting and as that I see is "the as operator only performs reference conversions and boxing conversions". Maybe I need to tell it I'm using a reference type?
T Foo(T x) where T : class {
var h = ((Hashtable)x); // CS0030: Cannot convert type 'T' to 'System.Collections.Hashtable'
return x;
}
What's going on? Why does as work fine, while casting won't even compile? Should the cast work, or should the as not work, or is there some other language difference between casting and as that isn't in these MSDN docs I found?
A: The cast operator in C# can:
*
*box/unbox
*upcast/downcast
*call a user-defined conversion operator
as Hashtable always means the second.
By eliminating value types with the constraint, you've knocked out option 1, but it's still ambiguous.
Here are the two "best" approaches that both work:
Hashtable h = x as Hashtable;
if (h != null) {
...
}
or
if (x is Hashtable) {
Hashtable h = (Hashtable)(object)x;
...
}
The first needs only one type test, so it's very efficient. And the JIT optimizer recognizes the second one, and treats it like the first (at least when dealing with non-generic types, I'm not sure about this particular case.)
A: "The C# compiler only lets you implicitly cast generic type parameters to Object, or to constraint-specified types, as shown in Code block 5. Such implicit casting is type safe because any incompatibility is discovered at compile-time."
See the section on Generics and Casting:
http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx#csharp_generics_topic5
A: Ben's answer basically hits the nail on the head, but to expand on that a bit:
The problem here is that people have a natural expectation that a generic method will do the same thing that the equivalent non-generic method would do if given the types at compile time. In your particular case, people would expect that if T is short, then (int)t should do the right thing -- turn the short into an int. And (double)t should turn the short into a double. And if T is byte, then (int)t should turn the byte into an int, and (double)t should turn the byte into a double... and now perhaps you begin to see the problem. The generic code we'd have to generate would basically have to start the compiler again at runtime and do a full type analysis, and then dynamically generate the code to do the conversion as expected.
That is potentially expensive; we added that feature in C# 4 and if that's what you really want, you can mark the objects as being of type "dynamic" and a little stripped-down version of the compiler will start up again at runtime and do the conversion logic for you.
But that expensive thing is typically not what people want.
The "as" logic is far less complicated than the cast logic because it does not have to deal with any conversions other than boxing, unboxing and reference conversions. It does not have to deal with user-defined conversions, it does not have to deal with fancy representation-changing conversions like "byte to double" that turn one-byte data structures into eight-byte data structures, and so on.
That's why "as" is allowed in generic code but casts are not.
All that said: you are almost certainly doing it wrong. If you have to do a type test in generic code your code is not generic. This is a really bad code smell.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: Is there any convention for a helper class in Android? For every Activity I add to my app I'm noticing a lot of similar code being used in the initialization of the Activity. A helper class with a static method to wrap this similar code seems the way to go.
I first thought of a singleton class. I could add static methods/variables and use them across the application. I haven't really tried to see how would this work in an Android application. Searching a little bit more I saw something about creating a class extending Application. For this I did a simple test:
public class MyApp extends Application {
public static String DEMOTEXT = "WORKING!";
public static void ShowToast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
}
}
MyApp.ShowToast(this, MyApp.DEMOTEXT); // Placed on onCreate of some Activity
This works exactly as I expected. Is this the way to go on Android or is there a better convention? Anything else I should consider when doing this?
By the way, should I use the final keyword on the string? What about the method?
EDIT: I just read this:
There is normally no need to subclass Application. In most situation,
static singletons can provide the same functionality in a more modular
way. If your singleton needs a global context (for example to register
broadcast receivers), the function to retrieve it can be given a
Context which internally uses Context.getApplicationContext() when
first constructing the singleton.
http://developer.android.com/reference/android/app/Application.html
Should I use a singleton then?
A: Application is primarily used for a global application initialization. You would create your own class, override Application.onCreate() and initialize your static application data there.
Dont forget to declare it in the AndroidMainfest.xml:
<application
android:icon="@drawable/icon"
android:label="@string/app_name"
android:name="your.package.path.to.MyApp">
A static helper class is made the way you did.
The convention is to use lower case letter at first position, so MyApp.showToast(...).
You would use final for the String if you would want to avoid madifications on other places (since it should be a contant).
// this would allow ...
public static String DEMOTEXT = "WORKING!";
// ... to do this somewhere else
MyApp.DEMOTEXT = "NOT WORKING!"
A: I haven't tried this but I think you should be able to do something like this as well.
public class MyActivity extends Activity {
private static final String DEMOTEXT = "WORKING!";
@Override
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
Toast.makeText(this, DEMOTEXT, Toast.LENGTH_SHORT).show();
}
}
Now for all activities that need to use that initialization could just extend your base activity class.
public class SomeActivity extends MyActivity {
...
// Should display the toast on create
...
}
A: Yes just use a singleton. Well in this case if your methods are static, you don't even need a singleton. Just a class with static methods.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: iPhone/iPad: When to change background on rotate of device At what point in the rotation of a device should I replace the image that forms the background. There are 2 images, one for Landscape, one for Portrait.
Currently I use the WillRotate event, but it's 'choppy' in performance and I get warnings about not to do this in a two stage rotation.
A: I use either -
1.
-(void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
Sent to the view controller before performing a one-step user interface rotation.
or
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
Sent to the view controller after the user interface rotates.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iOS: 4.2 or lower must include ARM6 object code?
Possible Duplicate:
How to build for armv6 and armv7 architectures with iOS 5
I need to build a library and executable that will be installable on both iPhone 3 and iPhone 3gs & later. I guess the iPhone 3 has an arm6 processor and later devices have arm7. However when I try to build for later devices with Build for Active Architectures Only to set No, which would produce an arm6+arm7 binary, the build doesn't complete, because it rejects the library.
Is there a way to get Xcode to build for both arm6 and arm7 without complaints?
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to enable/disable cookies programmatically for IE I'd like to turn on cookies programmatically using a script or C# code. This needs to work at least for IE8 and IE9. Is there a way to do that. Is it a registry setting? Is there an API to do it?
I believe it is a per user setting, so ideally it would change the setting for the user the script/process is executing under.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Pylons and zombie processes I'm trying to write an application that will allow the user to start long-running calculation processes (a few hours, for example). To do so, I use Python Popen() function. As long as the main Pylons process works fine, everything is good, but when I restart the Pylons process, it doesn't respond to any requests if there are any zombie processes left from the previous paster launch.
What could be the origin or a workaround for this problem?
Thanks in advance, Ivan.
A: To avoid zombie processes, the child must do a double fork to detach itself from the controlling process. See http://en.wikipedia.org/wiki/Zombie_process
So all you need to do is make your child process fork again - while being careful to keep the relevant file handles open so that you can still communicate.
A: You need some kind of message passing. This maybe done by installing a signal handler. Python has the signal module for this and Popen has a send_signal method.
Maybe http://www.doughellmann.com/PyMOTW/subprocess/#signaling-between-processes helps you too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I get the min/max possible numeric? Is there a function that returns the highest and lowest possible numeric values?
A: help(numeric) sends you to help(double) which has
Double-precision values:
All R platforms are required to work with values conforming tothe
IEC 60559 (also known as IEEE 754) standard. This basically works
with a precision of 53 bits, and represents to that precision a
range of absolute values from about 2e-308 to 2e+308. It also has
special values ‘NaN’ (many of them), plus and minus infinity and
plus and minus zero (although R acts as if these are the same).
There are also _denormal(ized)_ (or _subnormal_) numbers with
absolute values above or below the range given above but
represented to less precision.
See ‘.Machine’ for precise information on these limits. Note that
ultimately how double precision numbers are handled is down to the
CPU/FPU and compiler.
So you want to look at .Machine which on my 64-bit box has
$double.xmin
[1] 2.22507e-308
$double.xmax
[1] 1.79769e+308
A: help("numeric")
will ask you to do
help("double)
which will give the answer: range of absolute values from about 2e-308 to 2e+308.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: SQL query: HAVING, GROUP BY I have two tables. One with a list of shops and their ID's (shop_id)
and one with a list of employees with the ID (shop_id) of the shop they work at.
I have to print out each employee with a certain position form a certain shop.
My query is normally correct but I seem to get an error like tblEmployees.
Normally my query would look something like.
SELECT tblEmployees.Name, tblEmployees.Surname, tblShops.shop_id
FROM tblEmployees, tblShops
GROUP BY tblEmployees.shop_id
HAVING tblEmployees.shop_id = tblShops.shop_id;
Normally I get an error saying something like:
tblEmployees.Name is not part of an aggregate function.
What I want to know is if it would solve my problem if I put every column that gives me this error under the GROUP BY statement. Or is there another way of fixing this error without it affecting the result I need to get from this query.
A: Drop the GROUP BY and HAVING clauses. You aren't aggregating here. You want to be joining your tables.
SELECT tblEmployees.Name, Surname, tblShops.shop_id
FROM tblEmployees JOIN tblShops
ON tblEmployees.shop_id=tblShops.shop_id
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Running batch job using TeamCity fails, but Manual command prompt works I am getting this error message running a batch job with TeamCity. The batchjob is copying files from TeamCity Server to another server(server2). Have checked multiple times, the folders have all the rights permissions needed and this works fine (copies files between servers) when the batch job is run manually from command prompt. I have this error for each file that needs to be copied.
error MSB3021: Unable to copy file "..\bin\Release\Boo.Lang.Compiler.dll" to "\Server2\DestinationFolder\". Could not find a part of the path '\Server2\DestinationFolder'.[10:54:32]: Creating directory "\Server2\DestinationFolder".
I tried few things, but issue remains unresolved. Thanks for your input.
A: TeamCity build Agent is running as System user account that has no access to the network resources, you should change the service user to an account that has network permissions, like your Administrator account.
See also the related question.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7504470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.