text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: How much stack space does this routine use? Assuming the tree is balanced, how much stack space will the routine use for a tree of 1,000,000 elements?
void printTree(const Node *node) {
char buffer[1000];
if(node) {
printTree(node->left);
getNodeAsString(node, buffer);
puts(buffer);
printTree(node->right);
}
}
This was one of the algo questions in "The Pragmatic Programmer" where the answer was 21 buffers needed (lg(1m) ~= 20 and with the additional 1 at very top)
But I am thinking that it requires more than 1 buffer at levels lower than top level, due to the 2 calls to itself for left and right node. Is there something I missed?
*Sorry, but this is really not a homework. Don't see this on the booksite's errata.
A: First the left node call is made, then that call returns (and so its stack is available for re-use), then there's a bit of work, then the right node call is made.
So it's true that there are two buffers at the next level down, but those two buffers are required consecutively, not concurrently. So you only need to count one buffer in the high-water-mark stack usage. What matters is how deep the function recurses, not how many times in total the function is called.
This assuming of course that the code is written in a language similar to C, and that the C implementation uses a stack for automatic variables (I've yet to see one that doesn't), blah blah.
A: The first call will recurse all the way to the leaf node, then return. Then the second call will start -- but by the time the second call takes place, all activation records from the first call will have been cleared off the stack. IOW, there will only be data from one of those on the stack at any given time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Automating TestFlightApp with Xcode and Provisioning Portal I currently have a fairly manual process when releasing a new build in TestFlight:
*
*Download the additional devices text files from TestFlightApp
*Log into the Provisioning Profile
*Upload devices
*Update the Provisioning Profile to include the newly added devices
*Download the generated .mobileprovision file
*Click on the file to add to Xcode
*Product -> Archive, Share, Create IPA
*New Build in TestFlightApp
*Type up the release notes
*Upload (wait)
*Select testers to notify
Are there scripts or utilities that handle these steps for me? I don't mind a solution for part of these steps, as long as it reduces this process.
On the other hand, maybe I'm repeating steps I shouldn't be, or not doing things in an efficient manner.
A: There's a blog entry on developmentseed.org where it describes how to automate an archive build to be uploaded to TestFlight.
It doesn't include automatically updating devices in the provisioning profile, but MoProPro appears to be a command line utility to add new devices.
A: Jenkins is a build server with plugins for xcode and TestFlight. It is a huge time saver if you have multiple projects to upload. Once the job is set up, it can be a one-click process to deliver the apps to TestFlight. With my set up, I even get a email when the build has completed the upload to TestFlight.
Note, it does not do the first 6 points of your question, but it does do the rest.
A: Have you seen the nomad CLI tools for iOS development? They let you do things like:
Manage Devices
$ ios devices:add "iPad 1"=abc123
$ ios devices:add "iPad 2"=def456 "iPad 3"=ghi789 ...
Manage Provisioning Profiles
$ ios profiles:list
+----------------------------------+--------------+---------+
| Profile | App ID | Status |
+----------------------------------+--------------+---------+
| iOS Team Provisioning Profile: * | ABCDEFG123.* | Valid |
+----------------------------------+--------------+---------+
Build & Distribute through TestFlight
$ cd /path/to/iOS Project/
$ ipa build
$ ipa distribute
And more!
All examples taken from the nomad documentation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: How can I pass two models to a class based generic view I have an app called "blog" that has a model called "Entry". I use a class based generic to view this Entry and I am happy with this.
Now, along comes another app called "Eventapp" that has a model called "Event". Now I want to query this model for a few events, and then send it to the class based generic mentioned above. How do I do this?
Here is what I have in my urls.py so far to view the Entry model:
urlpatterns = patterns('',
url(r'^$', ArchiveIndexView.as_view(
model=Entry, paginate_by=5, date_field='pub_date',template_name='homepage.html'),
),
url(r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>\w+)/$',
DetailView.as_view(model=Entry, queryset=Entry.objects.all(), slug_field='slug')),)
Is there a way to pass the Event model to ArchiveIndexView.as_view() and DetailView.as_view() somehow?
A: As it looks to me you would like to have your events on more than one page, a context processor may be the right tool for you. It should allow you to access a queryset of events within the context of every template:
from eventapp.models import Event
def event_provessor(request):
return {'events': Event.objects.all()}
Because of the queryset's laziness you don't have to be afraid to hit the database if you don't need the list, the query is only run if you would iterate over events.
Of course you could also eg. subclass the views and add the events there to the context, but if more than one view is affected a context processor might make more sense!
A: Since you're using Django's class based views, just extend the class(es) you're using.
For the DetailView, in your app's views.py file, add your new view class:
from django.views.generic import DetailView
from blog.models import Entry
from eventapp.models import Event
class BlogEntryView(DetailView):
"""Extends the detail view to add Events to the context"""
model = Entry
def get_context_data(self, **kwargs):
context = super(BlogEntryView, self).get_context_data(**kwargs)
context['events'] = Event.objects.all()
return context
We're leaving out the queryset and the slug field name because given the model name the DetailView class defaults to the Entry.objects.all() queryset, and 'slug' is the default slug field name. If you want to explicitly declare those, then add them right under the model assignment.
Then update your urls.py file like so:
from blog.views import BlogEntryView
urls = patterns('',
url(r'^$', ArchiveIndexView.as_view(
model=Entry, paginate_by=5,
date_field='pub_date',template_name='homepage.html'),
),
url(r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>\w+)/$',
BlogEntryView.as_view()),
)
This is detailed in the class based generic view documentation, to boot.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Invalid index N for this SqlParameterCollection with Count=N only when associated table has null record I have a rather complex entity which will not save when a particular database table is missing a record. When the record exists the entity saves correctly. When the record does not I receive the exception:
Invalid index N for this SqlParameterCollection with Count=N
After reading a bunch of solutions found via Google and the most closely related questions on Stack Overflow:
*
*What's causing “Invalid index nn for this SqlParameterCollection
with Count=nn” when a column is Null in the database?
*Invalid Index n for this SqlParameterCollection with Count=n” OR “foreign key
cannot be null
I believe my issue has to do with the way I have my mapping files setup. The Customer entity has reference to the Person entity. Person maps to a table which we have read, but not write access to. It is when a record for the Person entity does not exist that I generate the exception. If the record exists no issue. I've set the reference to Person from customer to Nullable(). I have also double checked to ensure I do not have a property mapped twice from either entity.
Here is what I feel is the pertinent mapping information, but can provide more as needed:
Customer
//more mapping code...
References(x => x.Person, "snl_id").Nullable();
//more mapping code...
Person
//more mapping code...
ReadOnly();
Id(x => x.SnlId).Column("SNL_ID");
//more mapping code...
To further complicate matters we have some painful code to make NHibernate perform better when Person does not exist. I am not sure it applies here, but thought it pertinent enough to include in my question. We are using the below code because without it the NHibernate JIRA will create tons of queries. This solution is outlined in this Stack Overflow answer.
Customer's person property
public virtual Person Person
{
get
{
try
{
var snlId = per.Name;
return per;
}
catch
{
return null;
}
}
set
{
per = value;
}
}
private EPerson per;
What am I missing in my mappings that would cause this exception? Is there another piece of this problem that I am not seeing?
A: While Scott's solution of removing the snl_id property from the Customer class fixes the issue it causes problems that I cannot get around-- the snl_id can exist in the Customer table even there is not a corresponding Person table record. Since that is the case there are times when I will need access to the snl_id when I cannot get to it via the associated Person property.
I considered several alternative solutions but settled on creating a view of the Customer table including the Customer table primary key and the snl_id from the customer table. Then mapping that property via a join to the view.
Join("v_cust_id_snl_id", j => j.KeyColumn("cust_id").Map(x => x.SnlId, "snl_id")
This change allowed me to have my cake and eat it to. I was able to keep the SnlId property on customer, but no longer throw the exception when saving.
A: Do you have the snl_id referenced as a property in Customer as well as being the primary key for the child object? If so, this is causing the error you are receiving. Remove the property from Customer and use Person to get the value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Core Plot show 'Loading' spinner I am using core plot (0.4) to render a graph and it is working fine. However (especially when on the iPad) the graph can take a while to render. I have added a UIActivityIndicatorView to the graph which shows up when the graphs starts to be drawn, but I can't find any event to hook that I can use to stop the spinner.
I have tried using the numberForPlot method and detecting when the last datapoint has been requested, but this is called multiple times for each line on the scatterGraph, so I can't easily use this. Is there any sort of graph rendered event that I can hook for this?
A: If you're doing [graph reloadData] to update the graph, can you just bracket that call with your indicator start/stop calls? I think that core-plot does everything in the main thread.
A: Core Plot uses Core Animation for all rendering. A single graph contains many CA layers that are rendered independently. -reloadData just tells the graph to update its data cache next time it draws and tells Core Animation that it needs to be redrawn. Similarly, just bracketing the data source calls only captures the data caching that happens before the render. You would miss the actual drawing time and would never know if Core Animation re-rendered the graph at another time, such as after a resize.
If you only care about the time to render the plot and not the other parts of the graph, one way to do this would be to subclass CPTScatterPlot and override the -renderAsVectorInContext: method. Bracket the calls to super with your activity indicator code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: git: list all files with owner/identity at first commit (or rather, the first user to commit the file) How do I, using git, list all files in a particular directory together with the owner/identity of those files at first commit?
Is getting slices of information like this across many files usually difficult?
Edit: Okay, git doesn't provide a direct way to do this, but it does store who commits various files, right? I need this list in a particular directory so I can get a sense of which files I'm 'responsible' for.
A: I happened to run into a similar situation. The accepted answer is working, but why don't you guys use find with working copy?
find . -type f -exec git log --reverse --format="{} %cn" -1 {} \;
A: A very straightforward approach would be
git rev-list --objects --all |
cut -d' ' -f2- |
sort -u |
while read name; do
git --work-tree=. log --reverse --format="%cn%x09$name" -- "$name" | head -n1
done
Caveats:
*
*This shows the first author name (%an) of each path that exists in the object database (not just in (any) current revision). You may also want the committer name (%cn), though be aware that if person B rebased a commit from person A that created the file, B will be the committer and A will be the author.
*The --all flag signifies that you want all objects on all branches. To limit scope, replace it by the name of the branch/tag or just by HEAD
*n2 performance (doesn't scale well for very large repo's)
*improper output if the pathname contains formatting sequences (e.g. %H etc.)
It will start out with the empty name, which is the root tree object.
A: Give this a try:
$ cd thatdirectory
$ git ls-files |
while read fname; do
echo "`git log --reverse --format="%cn" "$fname" | head -1` first added $fname"
done
The "first added" can be misleading in case of renames.
Refs:
*
*https://git-scm.com/docs/git-ls-files
*https://git-scm.com/docs/git-log#_pretty_formats (see placeholders under format:<string>)
A: To do this efficiently,
git log --raw --date-order --reverse --diff-filter=A --format=%H%x09%an \
| awk -F$'\t' '
/^[^:]/ {thisauthor=$2}
$1~/A$/ {print thisauthor "\t" $2}
'
with maybe a |sort -t$'\t' -k1,1 or something to make it a bit prettier
A: Using git itself, this is not possible. Git does not keep track of the owner of the file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Importing a Site Collection as a Subsite in powershell I have a site collection that has subsites underneath it, and I want to move the entire collection so it's a subsite of another site. Thing is, the URL site collection I want to move is the same URL that I want the new subsite to be. I researched how to basically do this with powershell scripts, but I'm lost as to how to get my current site collection, which isn't a subsite of my site, to be imported as a subsite of my site with the same URL.
Any help would be greatly appreciated.
Thanks,
Michael
A: To be honest, I've not done anything like this in IIS 7+. In IIS 6, this is non-trivial. It may be as simple as you make it sound in IIS 7.
There are a dozen ways to do this if you're only doing it once or twice. Probably the easiest is to export the virtual directories off as XML and import the XML back into your new site. If you're planning to reuse whatever process you create, then maybe it's worth the time to learn PowerShell and generate a script, but consider approaching the problem in some simpler way.
A: Found an interesting article in this blog:
http://www.tcsc.com/move-a-site-collection-to-a-subsite-in-sharepoint-2010/
I think that is what you are looking for.
Summary of the article is:
*
*Export the site collection
Export-SPWeb -Identity https://portal.contoso.com/sites/MoveMe -Path “C:MoveMe.bak” -IncludeUserSecurity -Compression 1024 -IncludeVersions 4
*Create a new subsite
New-SPWeb -URL https://portal.contoso.com/sites/NewHome/MoveMe
*Import the Exported Site Collection
https://portal.contoso.com/sites/NewHome/MoveMe -Path “C:MoveMe.bak”
*Delete the Old Site Collection
Remove-SPSite -Identity https://portal.contoso.com/sites/MoveMe
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What changed my WordPress .htaccess? My WordPress site went down with an error 500. After looking around, I restored the .htaccess and that fixed it. My question is what in WordPress could have changed the .htaccess by itself? Do plugins sometimes do this? What about adding sub-domains within CPanel? Any way to prevent this?
The .htaccess was originally this:
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# uploaded files
RewriteRule ^([_0-9a-zA-Z-]+/)?files/(.+) wp-includes/ms-files.php?file=$2 [L]
# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^[_0-9a-zA-Z-]+/(wp-(content|admin|includes).*) $1 [L]
RewriteRule ^[_0-9a-zA-Z-]+/(.*\.php)$ $1 [L]
RewriteRule . index.php [L]
It keeps getting changed to this:
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# uploaded files
RewriteRule ^files/(.+) wp-includes/ms-files.php?file=$1 [L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule . index.php [L]
A: Permalinks as well as any Cache plugins can do that. However, you should have saved the "messed-up" .htaccess so that we could see the contents of that, vs. what it was originally...
A: Here is the messed up one
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
Here is the good one
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
A: My .htaccess file kept getting reset like that because my site was hacked. Here's a potential solution: https://wordpress.stackexchange.com/a/191570/20963
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Xcode 4 organization, Views and Controllers Thank you for reading this.
These are my first steps in the iPhone Ipad app programming.
In order to learn from scratch (and because I know my app would need dynamic views), I decided not to use Interface Builder.
My question is(regarding the fact that I don't use IB): how would one use Views and Controllers?
I think I understand the MVC concept as it is repeated over and over again in the tutorials I follow, but after the "MVC explanation" part, nothing is made to make it clear "on the field" and closer to the real world (Earth being Xcode here).
Worse, sometimes it seems that some tutorials mix these two concepts up and use one word to say the other.
I read around here a lot of questions (and answers of course) based on the matter but I still don't get it. Sometimes it's too generic, sometimes it's too specific (for me at least).
For what I think I understood, the UIView is the static View when the View Controller is the logic which links the View to the data and those 3 concepts must be separated.
This separation, while a bit clearer with the use of Interface Builder seems to get quite blurry when you code everything as it becomes a virtual soup.
Technically, should I create a specific ".h" and ".m" file for each View AND ALSO for each associated Controller?
If I understand the MVC pattern, it's seems that I should but when I follow tutorials (without IB) it is never the case, view and controllers are created and manipulated within the same implementation files.
Any high level (I'm a noob, don't forget) but still applicable explanation of the use and best practices?
Let's say I want to create a simple app with a green view I can swipe to get to a red view.
I know for sure that I would need at least an:
*
*xxxappDelegate.h
*xxxappDelegate.m
*xxxView.h
*xxxView.m
What else?
1)Where should I put the the second view (along with the first one in "xxxView" or should I create another class h and m file?)?
2) What would the controller(s) do, for that kind of application? In which files would they be created and in which files would they be invoked and how would they "control" the related view?
3) Mainly, regarding to MVC pattern and the fact that there would be no IB, how would you organize that app?
I know it's a lot if you go into the details and code but that's not the point here.
Thank you. This - as simple as it seems - would be of a great help and is not as easily found in tutorials as you might think.
I understand the tutorials I read but they are so particular. As soon as I try to create something on my own which is not a "Hello World" screen, I realize that something is missing, logic wise.
Thank you very much for your help.
A: Sorry, but I can't get past your first paragraph. If you don't use Interface Builder, you are not going to be a successful iOS programmer. It's that simple. The best advice I've ever read about this is in this Aaron Hillegass interview:
Experienced Cocoa programmers put a lot of the smarts of their application in the NIB file. As a result, their project has a lot less code. Programmers who have spent a few years working in Visual Studio get freaked out. They ask me stuff like, "Can I write Cocoa apps without using Interface Builder? I like to see the code. Maybe I can just explicitly create my windows and the views that go on it?"
It is difficult to explain how the NIB file (and a few other scary ideas) create leverage. It is that leverage that enables one guy in his basement to compete with a team of engineers at Microsoft or Adobe. It is like I showed a chain saw to a early American colonist, and he said, "Can I cut down the tree without starting the engine? I don't like the noise. Maybe I can just bang it against the tree?"
Yes, it's hard to generalize after reading specific tutorials, but you will learn. I thought the learning curve was insurmountable when I first started, but if I can become a programmer that gets paid to write Cocoa software, you can too. Just keep reading and practicing. Don't fight the tools--use them.
A: If you really insist on going without IB (and I agree 100% with SSteve) then in addition to the files you list you will also want to use a UIViewController. Now, it is important to know that you only need to create header and implementation files when you are adding or changing default behavior.
In you case, the view can probably just be a generic UIView, so you wouldn't need the files. What you would do is subclass UIViewController, and put the swipe logic there. In the swipe logic code you would probably just change the background color of the view.
You would instantiate the view controller in the delegate (in this case anyway) and create the view in the view controller's loadView method. That is required since you won't be using IB.
Personally though, I think that IB does a great job of encouraging proper MVC patterns, and if you are just starting then you should go with IB.
A: Early:
In order to learn from scratch (and because I know my app would need
dynamic views), I decided not to use Interface Builder.
Later:
As soon as I try to create something on my own which is not a "Hello
World" screen, I realize that something is missing, logic wise.
I think what is missing logic wise is that you have accepted your assumption that Interface Builder was a crutch and that to learn "from scratch" you had to avoid using it. You are trying to learn the MVC design pattern but you are not willing to use the tools that have been designed to support it.
In Apple's own documentation they discuss the fact that sometimes there is value in having combined roles—Model Controllers and View Controllers—and that is worth reading, as it may explain some of the code examples you're reviewing. But my primary advice would be: before assuming you know better than the people who built the tools, trying using them the way they recommend. It might be an eye-opener.
Additions later:
OK, so to try and actually answer your questions...
1)Where should I put the the second view (along with the first one in
"xxxView" or should I create another class h and m file?)?
If I am understanding correctly and the two views you are thinking of here are the red and the blue displays to the user, you wouldn't have a second view—what you would do, whether in IB or in code—is to have an element in your view on which you changed a colour property... This would be done programmatically whether you were setting up the parent view in IB or in code.
2) What would the controller(s) do, for that kind of application? In
which files would they be created and in which files would they be
invoked and how would they "control" the related view?
There would be a view controller that would implement the gesture support, and would provide a method for changing the colour of the item in the view between blue and red when that swipe gesture was successfully received. I would have a ViewController.h and and ViewController.m. I think if you were implementing the View entirely in code, it would be implemented in the ViewController.m rather than having a separate View.m. (If you were using IB, you would have a ViewController.h, ViewController.m and ViewController.xib, with the latter providing the basic setup of the view elements and layers.)
You would create a ViewController instance in your AppDelegate.
3) Mainly, regarding to MVC pattern and the fact that there would be
no IB, how would you organize that app?
As above.
A: In practice you mostly do not make classes for views, unless they need to do custom drawing or display.
For lightweight configuration of views, that is often done in the viewController's viewDidLoad (or I guess in your case loadView) method.
Yes it's a good idea to keep model and view separated, but that's also balanced with the equally good idea to reduce the amount of code that exists. The less code that is written, the fewer bugs you will have.
Since you are just starting out at this point I would absolutely start by using ARC, and using IB - even though I'm sure you're tired of hearing that from everyone, I'll give you an alternate take. Less code means fewer bugs. And the fact that so many experienced developers are telling you to use it should be a giant clue about what a productive path forward is. I mean, are you doing this to build applications or learn every corner of the UIView class?
To speak to your code example, you do not need the UIView custom class. Just create use a UIViewController's main view as a container view, place a UIView inside with the background set to red. On swipe (using a gesture recognizer attached to the container view) call the UIVew method to swap in a new green-background UIView for the existing red view, you can even define the transition style.
Or create a scroll view in the container view, set up the red and green view inside the scroll view, set the content size and enable paging on the scrollview.
Or create a custom UIView class as you had, listen for touch events and slowly adjust two subview positions to follow the drag action.
Or use an OpenGL backed view, and based on the gesture recognizer pan the scene you are observing with two triangles for a green rectangle and two triangles for a red rectangle.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Where does Firefox store the sessionStorage content I am trying to find out where Firefox stores the sessionStorage content but have been unable to find so. I am expecting it to be in a SqLite database like the localStorage content is stored but I have not been able to find it.
So far, I have searched all the typical ".sqlite" files in the profile folder such as cookies.sqlite and content-prefs.sqlite etc but they do not seem to have the sessionStorage data.
I also tried to open the special in-memory database that Firefox supposedly creates - https://developer.mozilla.org/en/XPCOM_Interface_Reference/mozIStorageService#openSpecialDatabase%28%29 but I could not find a way to enumerate the tables present in the database. I could get a connection to the in memory database but i have no clue as to how to figure out the tables etc. that are present in that in-memory database...
Any help is appreciated
Thanks,
A: localStorage data is saved in the file webappsstore.sqlite in the Firefox profile. There is a funny tweak that host names are reverted (gro.allizom instead of mozilla.org) but other than that it is pretty much what you would expect. There is only one table:
CREATE TABLE webappsstore2 (
scope TEXT,
key TEXT,
value TEXT,
secure INTEGER,
owner TEXT
)
Note that this structure might change in a future Firefox version.
As to sessionStorage, it only needs to persist for one browser session. Restarting the browser normally clears it, so it doesn't need to be stored in a database. Firefox still writes it to disk to allow restoring the current browsing session, namely to the sessionstore.js file (JSON format). There is a key storage, its value is a map from URLs to their corresponding sessionStorage data. I am not sure whether this data is complete however given that its main purpose is to recover from crashes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Assigning a domain name to localhost for development environment I am building a website and would not like to reconfigure the website from pointing to http://127.0.0.1 to http://www.example.com. Furthermore, the certificate that I am using is of course made with the proper domain name of www.example.com but my test environment makes calls to 127.0.0.1 which makes the security not work properly.
What I currently want to do is configure my development environment to assign the domain name www.example.com to 127.0.0.1 so that all http://www.example.com/xyz is routed to http://127.0.0.1:8000/xyz and https://www.example.com/xyz is routed to https://127.0.0.1:8080/xyz.
I am not using Apache. I am currently using node.js as my web server and my development environment is in Mac OS X Lion.
A: If you edit your etc/hosts file you can assign an arbitrary host name to be set to 127.0.0.1.
Open up /etc/hosts in your favorite text editor and add this line:
127.0.0.1 www.example.com
Unsure of how to avoid specifying the port in the HTTP requests you make to example.com, but if you must avoid specifying that at the request level, you could run nodejs as root to make it listen on port 80.
Edit: After editing /etc/hosts, you may already have the DNS request for that domain cached. You can clear the cached entry by running this on the command line.
dscacheutil -flushcache
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "70"
}
|
Q: I can't seem to get the value I want from UIStepper I am using iOS 5.0 and I'm trying to get a value from my UIStepper.
I set the minimum to 0.0
The maximum is 25.0
The step value is 1.0
The starting value is 15.0
If I tap the + button ten times, the + will grey out so I know I'm at the max.
I've wired the "value changed" event in the uistepper to an IBAction called stepulate
That method only has an NSLog
Looks like
NSLog(@"%d", [myStepper value]);
I keep getting zero printed. No matter how many times I tap the + or - button.
A: The UIStepper uses a float for its value. Try this:
NSlog(@"Stepper Value: %.f", [stepper value]);
A: double stepperValue = rating_pound_stepper.value;
self.lbl_pound_rating.text = [NSString stringWithFormat:@"%.f", stepperValue];
A: try
NSLog(@"%d", [myStepper intValue]);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how test if char array is null? I've been doing (in C)
char array[100];
if (array == NULL)
something;
which is very wrong (which I have finally learned since my program doesn't work). What is the equivalent where I could test a new array to see if nothing has been put in it yet?
Also, how do you make an array empty/clean it out?
I know there are other posts out on this topic out there, but I couldn't find a straightforward answer.
A: An array declared with
char array[100]
always has 100 characters in it.
By "cleaning out" you may mean assigning a particular character to each slot, such as the character '\0'. You can do this with a loop, or one of several library calls to clear memory or move memory blocks.
Look at memset -- it can "clear" or "reset" your array nicely.
If you are working with strings, with are special char arrays terminated with a zero, then in order to test for an empty array, see this SO question. Otherwise if you have a regular character array not intended to represent text, write a loop to make sure all entries in the array are your special blank character, whatever you choose it to be.
You can also declare your character array like so:
char* array = malloc(100);
or even
char* array = NULL;
but that is a little different. In this case the array being NULL means "no array has been allocated" which is different from "an array has been allocated but I have not put anything in it yet."
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is the difference between `void f1(const Class &c)` and `void f2(Class const &c)`? What is the difference between these below functions ( Look at keyword const ) ?
void f1(const Class &c)
and
void f2(Class const &c)
A: There is no difference. The two versions are interchangeable.
A: There is no difference between const Class& and Class const&; likewise, there is no difference between const Class* and Class const*. Both denote a reference/pointer to a constant Class instance.
However, Class* const is a totally different beast. That is a const pointer to a non-const Class instance.
A: (pedantic answer):
The difference is the name.
The name f1 will differ from f2 - even after mangling
The signatures are exactly the same, so otherwise there would be no difference
A: They're not different at all. Look at points 18.6 and 18.8 in this page for more info.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: is better long and repeated msgs with .volatile flag or shorter but 'un-missable'? I want to make an app that relies in socket.io to offer real-time collaborative editing and I wonder which of these cases is better/faster:
<textarea id="some-id" onkeypress="broadcast()" ... >Type your text here</textarea>
*
*every time a change is made the client broadcasts the whole input with the volatile flag, so if a message is lost, the next one will replace it.
*every time a change is made the client broadcasts only that change and other clients apply it.
Also, are there any other APIs/frameworks/plugins that I can use rather than socket-io for collaborative document editing?
Thank you.
A: Let me answer your question a year after you posted this, because you're probably very impatient by now!
I think you would be better of with sending the change only.
*
*If two persons are typing at the same time, you will lose data if you're overwriting everything, even with very low latency. That is unacceptable.
*Without the volatile flag, the latency will be already very low, like a fraction of a second. (Also depends on the user's connection, of course). Remote persons will probably not notice these tiny delays.
*Documents may get large, so if someone is happily typing away in a big document, you're sending a lot of data around, which is not efficient.
Socket.IO is pretty good for this job: It has great cross-browser compatibility and the overhead is acceptable. If you're only targeting browsers that support HTML5's Websocket, you could use a Websocket package for node.js.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does JNLP (java web start) require server cooperation? I am trying to load a JNLP but my server always return a 404. The path is correct and I haven't modified anything from the demo so I am certain that is not the problem. Is it the case that my hosting simply does not support JNLP and I should find a one that does? Or is it me doing something wrong?
Here is the test
http://www.alexandertechniqueatlantic.ca/test/webstart.jnlp
I am using the supplied demo downloaded from
http://download.oracle.com/javase/tutorialJWS/deployment/webstart/ex6/webstart_ComponentArch_DynamicTreeDemo/dynamictree-webstart.jnlp
A: The only 'co-operation' that JNLP requires from the server (as far as I can recall at this instant) are:
*
*The server must supply all resources requested, the JNLP & any extension JNLP files, Jars, icons etc. The 404 indicates that part is not happening as per plan. Either the JNLP is not where you think it is, or (less likely, given it is the wrong error code) the server has been configured to disallow access to that document or directory.
*The server should provide the correct content-type for the JNLP. We can look into that after you have sorted the 404.
A: Server was blocking JNLP extension from executing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does Windows 7 Explorer support Multi-line Text for custom column? I've implemented a custom property handler for windows explorer using .NET 4.0. Everything is working except columns with multiple values is shown on the same line separated by ";".
I've tried to set the drawControl's control attribute to Default, MultiLineText, and MultiValueText, but still no luck. What I want to achieve is to have each value on a separate line instead of separated by ";".
Here is the propertyDescription of the propdesc file that I registered:
<propertyDescription name="Test.Property" formatID="{A5D0A4B0-EC4D-43DA-86F6-55448D9E9430}" propID="555">
<description>Description</description>
<searchInfo inInvertedIndex="True" isColumn="True" columnIndexType="OnDisk"/>
<typeInfo type="Any" multipleValues="True" isViewable="True" isQueryable="True" isInnate="False"/>
<labelInfo label="Test Property"/>
<displayInfo displayType="String" mnemonics="testproperty">
<drawControl control="MultiLineText" />
</displayInfo>
</propertyDescription>
Here is the implementation of the GetValue method of the IPropertyStore interface:
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern void InitPropVariantFromStringVector([In, Out] string[] prgsz, uint cElems, out PropVariant ppropvar);
public int GetValue(ref PropertyKey key, out PropVariant pv)
{
pv = new PropVariant();
pv.variantType = (short)(VarEnum.VT_VECTOR | VarEnum.VT_LPWSTR);
string[] stringArray = new string[] { "Test1", "Test2" };
InitPropVariantFromStringVector(stringArray, (uint)stringArray.Length, out pv);
return HR_OK;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Android SDK Manager repeatedly gets stuck while downloading
Possible Duplicate:
android SDK and AVD manager getting stuck
This is not the same as some of the other SDK Manager errors people have already posted on SO. Others have posted about permissions problems, and occasionally someone runs into some kind of database error.
In my case, the progress bar will just stop updating, and the whole thing will just sit there indefinitely, even overnight, without an error message. Oh, and it can't be canceled. There is no pattern to when this happens and when it doesn't. I have resorted to installing every single package individually, and even then it freezes about 50% of the time and I have to restart the manager process. It just froze just now while I was typing that sentence.
Has anyone else had this problem?
Edit: I just realized that on my old machine, I used to have to check the box that says "Force https:// sources to be fetched using http://," but on this machine I haven't been forced to do that yet. Maybe that has something to do with it.
A: After unchecking "Force https:// sources to be fetched using http://" in the Settings view, I was able to download a number of updates without problems. It was only 6 updates, but some of them were fairly large and the whole process took a couple hours.
So, I'm going to tentatively mark this as the answer, so it can be referred to by SO users in the future. But if anyone else has this problem, please do try my solution and post a comment here saying whether or not it worked.
A: Unchecking "Force https:// sources to be fetched using http://" also solved the problem for me.
A: The solution that worked for me:
I'm copying this answer from http://code.google.com/p/android/issues/detail?id=21773
Steps:
*
*stop and close sdk manager
*go to the url http://innovator.samsungmobile.com/android/repository/repository.xml which was obtained from action log in sdk manager
*<sdk:url>addon_samsung_GT_2.2_api-8_r01.zip</sdk:url> copy the zip file from the url field of xml doc (addon_samsung_GT_2.2_api-8_r01.zip) and replace repository.xml with the zip file name. The URL should be:
http://innovator.samsungmobile.com/android/repository/addon_samsung_GT_2.2_api-8_r01.zip
*paste the url to your browser and download the file
*copy the file to C:\Program Files\Android\android-sdk\temp folder
*start sdk manager and re-select galaxy tab api and select install, it won't try to download and start immediately unpacking the file.
I guess it would be the same for other failing apis, docs, etc..
A: I was having the same issue on my Windows 7 x64 box. To get things to work I booted my computer into Safe Mode with networking. In safe mode I was able to load eclipse and use the adk manager to install everything.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Scripting in Bash I have a function in bash say parse which takes one argument and function name is f. My file to be processed is somewhat like
a@b@c@
a@d@e@g@
m@n@
t@
I want to give the output as
a@f(b)@f(c)@
a@f(d)@f(e)@f(g)@
m@f(n)@
t@
That is apply function f to all except the first. Any clues so how can I do this?
A: This should do it:
sed 's/@\([^@]*\)/@f(\1)/g'
If all the fields are single characters, you can simplify it a bit (say, using . rather than \([^@]*\)).
A: You could use sed:
sed -e 's/@\(.\)/@f(\1)/g'
A: awk 'BEGIN {OFS=FS="@"} {for (i=2; i<=NF-1; i++) $i="f("$i")"; print}'
A: maybe this is what you want?
e.g. you have a script called sqr.sh:
kent$ cat sqr.sh
#!/bin/bash
echo $(($1*$1))
now you want to apply the function above on your input:
kent$ echo "foo@2@3@4@
0@10@20@
x@"|awk -F'@' -v OFS=@ '{for(i=2;i<=NF;i++) if($i) "./sqr.sh "$i|getline $i; print}'
foo@4@9@16@
0@100@400@
x@
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Use of Iterator in java I have a object type list like
List<Object> getRecords = records.getAllRecords();
ArrayList<String> recordsDetail = new ArrayList<String>();
recordsDetail = this.getRecordsDetail(getRecords.get(3));
model.addAttribute("recordsDetail", getRecords.get(3));
But when I am writing the method like
ArrayList<String> getRecordsDetail(Object records) {
}
Now I don't know how I can Iterate over records as records has some values as vector.
Any help will be appreciated. Thanks
If I do the same thing in JSP using spring MVC its working fine like
<c:forEach var="sData" items="${recordsDetail}">
<tr>
<td>
<table border="0">
<c:forEach var="sValues" items="${sData}" varStatus="colNo">
<c:choose>
<c:when test="${colNo.count> 5 and colNo.count<9}">
<tr>
<td>${sValues} </td>
<tr>
</c:when>
</c:choose>
</c:forEach>
</table>
<hr>
</td>
</tr>
</c:forEach>
But I want to do this processing in spring MVC controller and display the final results in JSP. So I am not able to find the way how i can iterate records in controller class.
A: A few things.
First, don't initialize a local variable then set it immediately to something. Instead, just initialize to the desired value (note List type and not ArrayList type, that is a good practice or maybe just my preference).
List<String> recordsDetail = this.getRecordsDetail(getRecords.get(3));
Next, iterate over records
List<String> getRecordsDetail(Object records)
{
if (records instanceof Vector)
{
Object blam;
Iterator iterator;
Vector recordVector = (Vector)records;
iterator = recordVector.iterator();
while (iterator.hasNext())
{
blam = iterator.next();
// do something with blam.
}
}
}
I don't know the type of the records elements, so I used Object if you know the type, then use that instead of Object.
A: This should be
ArrayList<String> getRecordsDetail(List<Object> records) {
}
If you can be more specific about the type of object returned by records.getAllRecords() you should use List<the-object-type-returned-by-getAllRecords> instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is my custom annotation logging bean null during autowiring? I created a custom annotation for logging following the example in this blog post almost exactly. The main difference that I can see is my LoggerInjector is annotated with @Component.
The annotation works great and I get a non-null Logger instance everywhere except in one case: when I try to log in a method annotated with @Autowired.
For example:
@Repository
public class MyDao
{
@AutowiredLogger
private Logger _logger;
private JdbcTemplate _jt;
@Autowired
public void setDatasource(DataSource ds)
{
_logger.debug("Entering setDs")
_jt = new JdbcTemplate(ds);
_logger.debut("Exiting setDs);
}
}
A NullPointerException is thrown on the first _logger.debug() line.
A snippet from applicationContext.xml:
<mvc:annotation-driven />
<context:component-scan base-package="my.package" />
A snippet from dispatch-servlet.xml:
<mvc:annotation-driven />
<context:component-scan base-package="my.package">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Repository" />
</context:component-scan>
How can I have my @AutowiredLogger injected before the @Autowired methods are run?
A: I don't think you can control which component gets autowired first. An alternate solution is to use InitializingBean to configure the class after everything has been set.
You could something like
@Override
void afterPropertiesSet() {
_logger.debug("Entering setDs")
_jt = new JdbcTemplate(ds);
_logger.debut("Exiting setDs);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Need example EXTJS4 app with dockedItems The following app displays a toolbar on top of some HTML:
Ext.application({
name: 'app',
appFolder: 'app',
launch: function() {
Ext.create('Ext.container.Viewport', {
layout: 'border',
items: [
{
region: 'north',
xtype: 'toolbar',
items: [{
xtype: 'button',
text: 'Button'
}]
},
{
region: 'center',
html: '<img src="resources/images/image.png">'
}]
});
}
});
but the following does not:
Ext.application({
name: 'app',
appFolder: 'app',
launch: function() {
Ext.create('Ext.container.Viewport', {
layout: 'fit',
dockedItems: [{
dock: 'top',
xtype: 'toolbar',
items: [{
xtype: 'button',
text: 'Button'
}]
}],
items: [
{
html: '<img src="resources/images/image.png">'
}]
});
}
});
Unfortunately, I can't find much documentation on using dockedItems. What am I doing wrong?
A: dockedItem is a feature of Ext.panel.AbstractPanel (and sub-classes). It is not supported in e.g. Ext.container.Container or Ext.container.Viewport.
Use a panel instead of the viewport (or alternatively, nest a panel inside the viewport) to show your dockeItems:
Ext.application({
name: 'app',
appFolder: 'app',
launch: function() {
Ext.create('Ext.panel.Panel', {
renderTo: Ext.getBody()',
layout: 'fit',
dockedItems: [{
dock: 'top',
xtype: 'toolbar',
items: [{
xtype: 'button',
text: 'Button'
}]
}],
items: [
{
html: '<img src="resources/images/image.png">'
}]
});
}
});
Working JsFiddle here: http://jsfiddle.net/mistaecko/bDNgB/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Calculate the number of input sequences that could result in the same state of hash table I encountered this problem while preparing for a test.
A hash table of length 10 uses open addressing with hash function h(k)=k mod 10, and linear probing. After inserting 6 values into an empty hash table,
the table is as shown below
0 |
1 |
2 | 42
3 | 23
4 | 34
5 | 52
6 | 46
7 | 33
8 |
9 |
How many different insertion sequences of the key values using the same hash
function and linear probing will result in the hash table shown above?
(A) 10 (B) 20 (C) 30 (D) 40
Answer given in Solutions: c
Could someone please explain how the answer is to be calculated? TIA
A: Since, 33 mod 10 = 3 and it is stored in 7th position, we know that it must have come after 23,34,52,46 and as 52 came before 33 hence, so did 42 (same hash value). We've established that 33 comes last in the sequences.
For the rest of the numbers there are 2 cases :
(1) Considering 52 came after 42,23,34 (as they are stored according to their hash value) which can be rearranged in 3! ways. That means 52 came 4th position and 46 came in 5th.
(2) Considering 52 came after 42,23,34,46 which can be rearranged in 4! ways. That means 52 came at 5th position.
So, total number of insertion sequences = 4! + 3! = 30
A: In a valid insertion sequence, the elements 42, 23 and 34 should appear before 52 and 33, and 46 must appear before 33.
Here number of different sequences = 3! x 5 = 30
In the above expression, 3! is for elements 42, 23 and 34 as they can appear in any order, and 5 is for element 46 as it can appear at 5 different places.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: cakephp, how can I add a class to the url instead of the image I wonder what is the most cakey way to do this. When I do:
echo $this->Html->image('uploadimage.gif', array('alt'=>'Upload Image', 'class'=>'nyroModal', 'url'=>'#test'));
It outputs:
<a href="#test"><img src="/img/uploadimage.gif" alt="Upload Image" class="nyroModal" /></a>
I need it to be:
<a href="#test" class="nyroModal"><img src="/img/uploadimage.gif" alt="Upload Image"/></a>
IE the class is applied to the link rather than the image. How can I do that?
thanks :)
A: I have never used cakePHP but for what I read online instead of giving a url to the image you can do it the other way around, create a link and pass an image, the result should be something like this:
<?php
echo $this->Html->link(
$this->Html->image("uploadimage.gif", array("alt" => "Upload Image")),
"#test",
array("escape" => "false", "class" => "nyroModal")
);
?>
For more info on link you can go here: http://book.cakephp.org/view/1442/link
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Simple 3D projection and Orientation handling? I'm currently working on a quirky retro flight sim and I've run into a few problems with my 3d projects, in so much as I can't find any solid generic documentation on the subject.
How do I convert simple positional vectors in my game world into 2d vectors on screen given the following information:
The cameras position
a cameras orientation ( see below)
a field of view
a height and width of the screen (and aspect ratio)
I'm also looking for a way to store orientations, I've already written a basic vector library but I'm unsure as to how to store rotations for use in both the camera (and projection code) as well as actual handling of rotations of in-game objects. I'm currently looking at using quaternions but it is it possible (and easy) to use quaternions instead of matrices for projection transformations?
Are there any good sources on implementation quaternions in code? Will I have to write a seperate library for complex numbers?
Thank you for your time and any help :)
A: CAUTION: LONG ANSWER!
I've done a similar project in Love2D, and it runs perfectly fast, so I don't see the problem with doing the math yourself in Lua rather than using OpenGL (which isn't exposed anyway).
Contrary to the comments, you should not be discouraged. The math behind 3D orientation and perspective is in fact quite simple, once you get the feel for it.
For orientation, quaternions are probably overkill. I've found that to do 3D projection with rotation, only Vec2, Vec3, and Camera classes are needed. While mathematically there are a few subtle differences, in practicality Vectors of Vectors make perfectly suitable transformation matrices, and transformation matrices make perfectly suitable orientations. A matrix being a vector of vectors has the upside that you only need to write one class to handle both.
To project a vector v, take into account 3 parameters of the camera:
*
*loc, a Vec3 for the camera's position
*trans, a Mat3by3 (also known as a Vec3 of Vec3's) for the inverse of the camera's orientation
*
*(disclaimer: using matrices for camera orientation is technically considered harmful, because small rounding errors can accumulate, but in actual use it's fine)
*zoom, a scaling factor used to determine the perspective. A z (relative to the camera) of zoom is equivalent to being in 2D; that is, no scaling from perspective.
projection works like this:
function Camera:project(v)
local relv -- v positioned relative to the camera, both in orientation and location
relv = self.trans * (v - self.loc) -- here '*' is vector dot product
if relv.z > 0 then
-- v is in front of the camera
local w -- perspective scaling factor
w = self.zoom / relv.z
local projv -- projected vector
projv = Vec2(relv.x * w, relv.y * w)
return projv
else
-- v is behind the camera
return nil
end
end
this assumes that Vec2(0, 0) corresponds to the center of the window, not a corner. Setting that up is a simple translation.
trans should start out as the identity matrix: Vec3(Vec3(1, 0, 0), Vec3(0, 1, 0), Vec3(0, 0, 1)) and be calculated incrementally, making small adjustments every time an orientation change is made.
I get the feeling you already know the basics of matrices, but if you don't, the idea is this:
A matrix is a Vector of Vectors, which can be thought of, at least in this case, as a coordinate system. Each vector can be thought of as one axis of the coordinate system. By changing the elements of the matrix (which are vectors and are thought of as the matrix's columns), you change the meaning of coordinates in that coordinate system. In normal usage, the first component of a vector means move right, the second component means up, and the third component means forward. However, with a matrix, you can make each component point in an arbitrary direction. The definition of dot product is
function Vec3.dot(a, b) return a.x * b.x + a.y + b.y + a.z * b.z end
for a matrix
Vec3(axis1, axis2, axis3)
given the definition of dot product, that matrix dotted with a vector v would yield
axis1 * v.x + axis2 * v.y + axis3 * v.z
which means that the first element of v says how many axis1s to move by, the second element says how many axis2's to move by, and the third element says how many axis3's to move by, with the end result being v, if it were expressed in standard coordinates instead of the coordinates of the matrix. When we multiply a matrix with a vector, we're changing the meaning of the components of the vector. Essentially, its the mathematical expression of a statement like "anything that was to the right is now less to the right and more forward" or anything similar. In one sentence, a matrix transforms a space.
Getting back to the task at hand, to represent a rotation in "pitch" (meaning around the x axis) by an angle theta using a matrix, you could write:
function pitchrotation(theta)
return Vec3(
-- axis 1
-- rotated x axis
-- we're rotating *around* the x axis, so it stays the same
Vec3(
1,
0,
0
),
-- axis 2
-- rotated y axis
Vec3(
0,
math.cos(theta),
math.sin(theta)
),
-- axis 3
-- rotated z axis
Vec3(
0,
-math.sin(theta),
math.cos(theta)
)
)
end
and for "yaw" (around the y axis):
function yawrotation(theta)
return Vec3(
-- axis 1
-- rotated x axis
Vec3(
math.cos(theta),
0,
math.sin(theta)
),
-- axis 2
-- rotated y axis
-- we're rotating *around* the y axis, so it stays the same
Vec3(
0,
1,
0
),
-- axis 3
-- rotated z axis
Vec3(
-math.sin(theta),
0,
math.cos(theta)
)
)
end
and finally "roll" (around the z axis), which is especially useful in a flight sim:
function rollrotation(theta)
return Vec3(
-- axis 1
-- rotated x axis
Vec3(
math.cos(theta),
math.sin(theta),
0
),
-- axis 2
-- rotated y axis
Vec3(
-math.sin(theta),
math.cos(theta),
0
),
-- axis 3
-- rotated z axis
-- we're rotating *around* the z axis, so it stays the same
Vec3(
0,
0,
1
)
)
end
If you visualize what that does to the x, y, and z axes in your head, all those cosines and sines and sign flips might start to make sense. They're all in there for a reason.
Finally, we reach the last step of the puzzle, which is applying these rotations. A nice feature of matrices is that it's easy to compound them. You can transform a transformation very easily - you simply transform each axis! To transform an existing matrix A by a matrix B:
function combinematrices(a, b)
return Vec3(b * a.x, b * a.y, b * a.z) -- x y and z are the first second and third axes
end
what this means is that if you want to apply a change to your camera, you can simply use this matrix combination mechanism to rotate the orientation a little bit each frame. These functions for your camera class will provide an easy way to make changes:
function Camera:rotateyaw(theta)
self.trans = combinematrices(self.trans, yawrotation(-theta))
end
we use negative theta because we want trans to be the opposite of the orientation of the camera, for projection. You can make similar functions with pitch and roll.
With all of these building blocks in place, you should be all set to write 3D graphics code in Lua. You're going to want to experiment with zoom - I generally use 500, but it really depends of the application.
The one piece missing, that really can't be accomplished without OpenGL, is depth testing. If you're drawing anything but points of wireframe, there isn't really a good way to make sure everything draws in the right order. You can sort, but that's inefficient, and it doesn't handle some corner cases where you have to do it pixel by pixel, which is what OpenGL does.
Happy coding! Hope that was helpful!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: maven-exec-plugin throws exception for no apparent reason I type the following in a Windows shell in the root of a Maven project that contains a class with a
public static void main(String[] args)
method that I'd like to run.
mvn exec:java -Dexec.mainClass="com.spp.config.main.SqlGeneratorHarness" -e
The class exists and is compiled in that package
(i.e., target/classes/com/spp/config/main/SqlGeneratorHarness.class).
I see...
+ Error stacktraces are turned on.
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'exec'.
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Invalid task '.mainClass=com.spp.config.main.SqlGeneratorHarness': you must specify a valid
lifecycle phase, or a goal in the format plugin:goal or pluginGroupId:pluginArtifactId:pluginVersion:goal
[INFO] ------------------------------------------------------------------------
[INFO] Trace org.apache.maven.BuildFailureException: Invalid task' .mainClass=com.spp.config.main.SqlGeneratorHarness': you must specify
a valid lifecycle phase, or a goal in the format plugin:goal or pluginGroupId:pluginArtifactId:pluginVersion:goal
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.getMojoDescriptor(DefaultLifecycleExecutor.java:1830)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.segmentTaskListByAggregationNeeds(DefaultLifecycleExecutor.java:462)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:175)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:362)
at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
[INFO] ------------------------------------------------------------------------
[INFO] Total time: < 1 second
[INFO] Finished at: Tue Sep 27 14:33:52 PDT 2011
[INFO] Final Memory: 3M/122M
[INFO] ------------------------------------------------------------------------
I've tried variations like
mvn exec:exec -Dexec.executable="java" [...]
and
mvn org.codehaus.mojo:exec-maven-plugin:1.2.1:java [...]
to no avail. What gives?
I'm running Maven 2.2.1, Java JDK 1.6.0_27 on Windows 7 Enterprise 64-bit.
A snippet from my pom.xml for the exec-maven-plugin is...
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
</plugin>
where the version is set in the <properties>
A: So... revisiting this... if you use Windows PowerShell, you will get the exception I originally reported. If, however, you use cmd.exe, then you should be able to run the class with the command as I posted (with or without wrapping double-quotes).
A: There's something very basic going wrong. Try losing the quotation marks. They're not needed there. In fact, try starting with something simpler, like
mvn -e exec:java -Dexec.mainClass=foo
That should give you the error "An exception occured while executing the Java class. foo", and the root cause should be a ClassNotFoundException:
Caused by: java.lang.ClassNotFoundException: foo
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
Type it out yourself. Don't copy/paste the command from somewhere else.
A: Just a quick checklist:
*
*Rename ~/.m2 folder and run mvn exec:java ... again and let Maven to download everything again from central.
*Check that your exec plugin is downloaded from central. (Check that your local repository contains the same files as the central.)
*Looking for suspicious repository and pluginRepository tags in the pom.xml (and parent poms as well).
*Looking for suspicious repository, pluginRepository and mirror tags in the settings.xml.
*Checking the project in an other machine - copy it and try to build/run exec:java in an other machine.
*Download Maven 3.x and try to run the exec with it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Does Azure Storage Tables have RowKey individually indexed to take advantage in subpartition queries? I need to know if the Azure Storage Tables have indexed the RowKey separately from the PartitionKey in order to do a query of this kind...
Assumption: My table have Forum Posts having PartitionKey = UserEMail, RowKey = PostInstant. So, I want to query like this...
SELECT data FROM forum WHERE PartitionKey="user@company.com" AND RowKey < DateLimit;
(Note: I know that the PostInstant should be written "inversed" to take advantage of ascending sort and thus obtain it in descending order, that's not the point).
As I understand, by explicitly indicating the PartitionKey the query is well going on the path of performance, but after that... will the RowKey be intelligently used to a) give the results sorted and b) stop the scan after reached the DateLimit?
Or, in other words, Does the Azure Storage Table indexing applies to the concatenation of PartitionKey+RowKey, thus only be useful for exact row matching and full table sort?
A: Yes the query that you have written is as efficient as you can write it against Azure tables and it should make use of indexes for both the PartitionKey and the RowKey.
Your results are guaranteed to come back in PartitionKey then RowKey order.
A: The PartitionKey and RowKey are currently the only indexed attributes you can use. However, you are only using one in your question. So, your query will search the entire PartitionKey 'user@company.com' without any further index. If it is a small partition, this might not be a big deal. If it is a big one, then you should also use the RowKey. Note, that while you are specifying an attribute called 'PostInstant', that is not the same as the RowKey. You must specifically query on RowKey (even if it is same as another column name).
So your query would be more like this:
ctx.CreateQuery<Foo>('tablename').Where(s => s.PartitionKey == "user@company.com" && s.RowKey.Compare(DateLimit) > 0);
I am assuming of course that 'DateLimit' is actually a string formatted date (like ticks). If you invert the ordering of ticks you would also invert the comparison operator (>).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: property file path changed during ant build <propertyfile file="${build.dir}/MyProperties.properties">
<entry key="releaseInformation"
type="string"
value="${build.time}"/>
</propertyfile>
When Ant copies my properties file over to the bin directory there is a property in it that has something like "samplePathName=C\:\Users\SomeUser\". But the property from the original file was "samplePathName=C:\Users\SomeUser\". How would the additional backslash end up there? I don't see anything that could possibly cause this to happen. Where should I begin looking other than the build.xml which only contains (relevant) the above line?
A: This is a common problem - the format of property files is defined by Sun (Oracle). Ant is conforming to this, which is why the escaping happens. There's no way round this using the propertyfile task - that's the way it's intended to work. If the file is genuinely a Java property file, then it shouldn't matter - the escaping should be handled correctly when the file is read.
However if you are hoping to use propertyfile to write a name-value config file that's for something else - where the escaping is not wanted - you'll need to adopt a different approach. As mentioned in the answer to a related question - you might use the Ant replace or replaceregexp tasks for this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Admob on android - UUIDs, cookies etc Ok, so I am very new to the world of Android apps (in fact, I've just about got past the hello worlds and understanding the sdk). I was looking into how free apps make money and Admob seems to be one of the most popular ways to put ads on your app - I should state that my study is academic rather than inclined toward how-can-I-make-money-from-this (at least right now :))
Now, I've been toying with the emulator and some apps which use admob and find they send this isu="xxxxx...xxx" (some 32 character hex I believe) to get ads, which from wikis I gather is a unique ID for a device. I'm curious as to how this is a) calculated and b) stored on my device (a cookie perhaps?). I'm pretty sure it won't be easy to answer a) but I would really like to know about b) - after all if there is a cookie on my device, I have every right to know where the little file is!
A: This 32 character hex value is just an MD5 Hash of your Android device ID. The SDK does not record the real device ID of the phone that is requesting ads. You also do not need to specify this in your app to get ads though. All you need is an AdMob Publisher ID to start getting ads, and you can get one for free by registering your app at admob.com.
Check out the AdMob docs for more information on getting started with AdMob.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: I'm Making a set of frameworks. I want to support multiple programming languages I'm Making a set of frameworks.
I want to support multiple programming languages.
My question is what language should i use as the base?
and is there a way to multiple bindings?
I want to support all these programming languages.
C, C++, Java, Ruby, Perl, Python.
A: Check out GObject — it's an open-source C library that adds object-oriented programming functionality for C, and can transparently create bindings for a variety of languages.
And its companion, Vala, is an object-oriented language that compiles down to C+GObject code, to help cut down on the verbosity of C+GObject.
A: Check out SWIG, "Simplified Wrapper and Interface Generator". Given C or C++ code, it can programmatically generate bindings for a variety of languages.
A: I would implement the library in C++. If you need C access, then this is easily done by hand, by providing wrapper functions that take an additional "this" argument.
Before you start though, read the SWIG documentation, in particular its limitations and things to avoid. If you design your C++ interface with SWIG in mind you can get the bindings for a lot of languages generated for you without effort.
Edit: Here is a quick example of a C wrapper for a C++ class. Let's say this is the C++ class to wrap, let's call it test.h:
class Test {
public:
Test();
int do_something(char* arg);
private:
is_valid(); // see below for why you need this method
};
This is your C header test_c.h:
typedef void* TestHandle;
TestHandle newTest();
int deleteTest(TestHandle h);
int Test_do_something(TestHandle h, char* arg);
And your C implementation will be a C++ file with C functions, let's say test_c.cpp:
extern "C" TestHandle newTest()
{
return (void*)new Test();
}
extern "C" int deleteTest(TestHandle h)
{
Test* this = static_cast<Test*>(h);
if (!this->is_valid())
return -1; // here we define -1 as "invalid handle" error
delete this;
return 0; // here we define 0 as the "ok" error code
}
extern "C" int Test_do_something(TestHandle h, char* arg)
{
Test* this = static_cast<Test*>(h);
if (!this->is_valid())
return -1; // here we define -1 as "invalid handle" error
return this->do_something(arg);
}
The is_valid() method is there to guarantee that you are not passed a bad handle. For example, you can store a magic number in all your instances, then is_valid() just ensures the magic number is there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jQuery.ajax is hitting the url of a previous call, no matter which url I pass to it The following call should try to hit "/getSomething". However, it's hitting "/previousSomething", a url fetched previously via jQuery.ajax. I see the request to the old url go out, however neither the "success" nor the "failure" function is getting called.
jQuery.ajax("/getSomething", {
success: function(cartData){
alert("success")
movieCart = cartData;
callback(cartData);
},
failure: function(){
alert("failure");
}
});
This code is running on a nasty corporate site which loads of scripts written by who-knows, multiple versions of jquery imported, etc. I suspect this is a problem called by the generally messy ecosystem my code is running in. Anybody have ideas about specifically what might be going on, or how to fix or even troubleshoot it?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: (#120) Invalid album id I currently have the following code. But the graph api still return (#120) Invalid album id. If i look at $facebook_album or https://developers.facebook.com/tools/explorer/248099655226775/?method=GET&path=213152142082066 it shows an album. So the album does exist.
public function save_facebook(){
Site::debug();
$album_item = new Foto_Album_Item($this['navigatie_obj']['parent_id']);
// File upload activeren
Site::$facebook->setFileUploadSupport(true);
// Facebook album ophalen
$facebook_album = Site::$facebook->api('/'.$album_item['facebook_id']);
// Facebook als gebruiker gebruiken ipv als applicatie
Site::$facebook->setAccessToken( Facebook::$user_access_token );
$user_id = Site::$facebook->getUser();
$facebook_options = array(
'source' => '@'.realpath(Site::$serverpath['album'].$this['navigatie_obj']['parent_id'].'/'.$this['bestand']),
'access_token' => Facebook::$user_access_token,
);
$request_method = '/'.$album_item['facebook_id'].'/photos';
$return = false;
try {
$result = Site::$facebook->api($request_method,'POST',$facebook_options);
$options = array('facebook_id' => $facebook_id ? $this['facebook_id'] : $result['id']);
$return = parent::save($options);
} catch(Exception $e){
Log::error($e,__FILE__,__LINE__);
}
return $return;
}
A: to be able to upload to an album that belongs to a page there are several things you should check (or change):
*
*user should be a page admin.
*user should grant 'manage_pages' permission to the app.
*app should call graph/me/accounts and iterate available accounts to get access_token for the page.
*then you proceed to '/album_object_id/photos' with upload.
error message you get is obviously misleading
hope this helps
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576292",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Input Box Alignment? How can I get my boxes to align with one another if the text in the is longer than the others.
I have this entire form within an unordered list.
I have copied and displayed the code via jsFiddle, you can find what I am speaking of here...
http://jsfiddle.net/EFByC/
A: Your <label> tags were wrapping the <input> tags which was causing the issue of trying to treat them separately with CSS:
http://jsfiddle.net/EFByC/3/
A: I would recommend that you change your form HTML like this
<li><label for="firstname">PATIENT FIRST NAME: </label><input type="text" id="firstname"/></li>
<li><label for="middle">PATIENT MIDDLE INITIAL:(OPTIONAL) </label><input type="text" id="middle" /></li>
<li><label for="last">PATIENT LAST NAME: </label><input type="text" id="last" /></li>
<li><label for="date">DATE OF BIRTH: </label><input type="text" id="date" /></li>
<li><label for="gender">GENDER: </label><input type="text" id="gender" /></li>
<li><label for="id">SUBSCRIBER ID: </label><input type="text" id="id"/></li>
*
*Give each form field a unique ID
*Do not wrap input inside the label
*You can use the for attribute on the label to connect it to an input.
Add a css rule to #form-container label to give them a specific width:
width: 210px;
See demo.
A: Why have you marked the form up in <ul>, this is not nessesary.
For a nicer and more readable layout I suggest that you have your labels on top of the input fields.
Something like this:
http://jsfiddle.net/Claudius/EFByC/9/
A: add a fieldset, put a width on it. make your inputs and labels display:block; float your inputs right
A: You've got a couple of options, really:
*
*Float the inputs to the right, like Kevin suggested (set the width of the UL to control the spacing).
*Pull the input out of the label, and give the label a fixed width (as in Peter's answer).
*Within the label, wrap the label text in a span, and give that span a fixed width (this, like the first option, will let the input stay within the label - see below).
And note that while lots of people are saying that it's bad to have an input inside a label, that's not necessarily true (it's definitely in the standard - see this question for more on that). And wrapping the input in the label lets you get the "click the name and focus the field" behaviour without specifying a bunch of ugly 'for="whatever"' attributes.
Hope this helps!
A: There are several approaches to form styling. I this case you can float the inputs and that will give you the result you want without changing the html.
See demo: http://jsfiddle.net/EFByC/8/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576293",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Add stylesheets and .js files to tinyMCE editor in wordpress? I would like to had some jquery files and stylesheets to the head of the tinyMCE editor of wordpress. Any suggestions on how to do this?
A: Use an own plugin or the tinymce setup paramter
// Adds an observer to the onSaveContent event using tinyMCE.init
tinyMCE.init({
...
setup : function(ed) {
ed.onInit.add(function(ed){
ed.dom.loadCSS( 'url_to_your_css_file' );
});
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to designate a Rack handler Rackup is successfully running any Rack app via Rack's default handler. e.g.:
class RackApp
def call(environment)
[
'200',
{'Content-Type' => 'text/html'},
["Hello world"]
]
end
end
run RackApp.new
But rackup is giving "NoMethodError at / undefined method `call' for nil:NilClass" when the last line is changed to instead use Rack's built-in CGI handler:
Rack::Handler::CGI.run RackApp.new
The same objection is raised for Rack's other built-in handlers. e.g. Rack::Handler::Thin, Rack::Handler::FastCGI, even Rack::Handler::WEBrick (which is the handler Rack selects above in default mode).
What's the correct syntax here?
A: The rackup command reads the config file and starts a server. The Rack::Handler::XXX.run methods also start a server, independently of the rackup command (CGI is slightly different as it isn't actually a server as such).
What happens when you change the line
run RackApp.new
to
Rack::Handler::CGI.run RackApp.new
and run rackup is as follows. The server starts and parses the config file. When the Rack::Handler::CGI.run RackApp.new line is reached it is executed as any other Ruby code would be. In the case of the CGI handler this calls the app and writes the output to the standard output as it would if running as a CGI script (have a look at your terminal when you run rackup). Afterwards the 'rackup' server is started as normal, but without an app to run. When you try to access the page you'll get the NoMethodError, since the app is nil.
Using Rack::Handler::Thin is similar, but in this case, as Thin actually is a web server, it is started and will serve RackApp, but listens on Thin's default port of 8080 (not the rack default of 9292). After stopping Thin (e.g. with Ctrl-C) the default rackup server (Mongrel or Webrick) will start listening on port 9292, again with no app specified so you'll get the NoMethodError.
If you run your modified 'config.ru' as a plain Ruby script rather than using rackup you'll see the same behaviour, but without the rackup server being started. (You'll need to require rack first, so use ruby -rrack config.ru). In the CGI case the output of a single call to your app will be printed to the console, in the Thin case Thin will be started serving your app.
In order to specify the server to use with rackup, you can use the -s option, e.g. rackup -s thin will start the app using Thin (this time on the rackup default port of 9292). You can also do rackup -s cgi but this won't really work in any useful way - it just prints out the html of an error page to the console.
CGI
If you're trying to run your app as a CGI there are a couple of options. You need to create a CGI script that calls your app using the CGI handler. This could itself be a ruby script that calls Rack::Handler::CGI.run directly, in fact you could use your modified config.ru directly (you might want to rename it first and add an explicit require 'rack' line).
Alternatively you can use a shell script which then calls rackup config.ru. In this situation rackup detects that it's running as CGI and automatically uses the correct handler
A: http://guides.rubyonrails.org/rails_on_rack.html (see point 3.5)
also interesting:
http://railscasts.com/episodes/151-rack-middleware
http://railscasts.com/episodes/222-rack-in-rails-3
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Help with a c++ statement The following statement is from WebKit. I am not 100% sure what it means. Any clues?
new ((void*)&nullAtom) AtomicString;
A: It's a placement-new. It means that the AtomicString object will be constructed at the memory location pointed to inside the parentheses (&nullAtom), rather than the usual behavior (constructed on top of a bit of memory taken off of the heap).
A: That's a "placement new".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Database: Sharing two sets of values in a single table? I'll start by saying I am not a DBA and I didn't get to do heavy database development so far (so I hope I'm not asking something obvious).
The Challenge:
*
*I have a dictionary application with pre-defined values.
*New values may be added via online updates.
*Users are not allowed to modify these application-values, but they may add/delete values of their own.
*The database (sqlite3) will contain a small amount of values (~2K-3K).
*The database schema is exactly the same for both user and application values.
Possible solutions:
*
*One way to go about it would be to create two different tables having the same schema, and JOIN the data from both tables when querying the database.
*A different approach would be to have a single table in which application-values will start at ID=0, and user-values will start at ID=100000 (for example). Online updates will merge new values below ID=100000 such that user values will remain intact.
I prefer the second solution - it'll avoid JOINs during runtime and the queries will remain simple.However, an update to the application-values in the first solution would require me to just replace the application table with the new one.
Please let me know what you think:
*
*Which solution is better?
*What are the pros/cons that I'm missing?
*Is there an even-better third solution?
A: Why not just a column 'type' to your table and fill it with user/application?
Personaly I hate meaningfull ID's....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Message box in asp.net website using (DataServer server = new DataServer())
{
server.ExecuteNonQuery(CommandType.Text, updateuser, param);
}
MessageBox.Show("User succesfully updated");
I have a update button when The fields are updated I show a message box, but the problem is the message box is behind the browser. I have to minimize the browser to close the message box, at the same time I am able to navigate in the website without closing the message box, I want to blur out the remaing area in the website when the message box is displayed. How can I do this in my website.
A: In this case you would either want to throw up an alert with JavaScript, or use a dialog of some sort.
To throw up an alert, you can do this:
Page.ClientScript.RegisterStartupScript(GetType(), "UserDialogScript", "alert(\"User successfully updated\");", true);
As for using a dialog, I would suggest the ModalPopupExtender or the jQuery UI Dialog.
ModalPopupExtender:
http://www.asp.net/ajaxlibrary/AjaxControlToolkitSampleSite/modalpopup/modalpopup.aspx
jQuery UI Dialog:
http://jqueryui.com/demos/dialog/
A: Don't do it this way. Instead, emit client side JavaScript to pop up an alert dialog, or add a div that a user can click to make it go away. You can also use a more proper UX convention of adding a message div that simply states "record updated" or similar, in a very specific color, so the user knows what to look for.
The idea of popping up a message box sounds tempting, but stick this out on a server and hit it from a browser on a separate box and you will quickly find out why this is an extremely bad idea.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Exporting to Excel .xlsx from a Python Pyramid project I know about the XLWT library, which I've used before on a Django project. XLWT is very neat but as far as I know, it doesn't support .xlsx which is the biggest obstacle in my case. I'm probably going to be dealing with more than 2**16 rows of information. Is there any other mature similar library? Or even better, is there a fork for the XLWT with this added functionality? I know there are libraries in C#, but if a python implementation already exists, it would be a lot better.
Thanks a bunch!
A: This is pretty good. I used it for a couple of small things:
http://packages.python.org/openpyxl/
A: Another really good alternative, actually what I switched to from Openpyxl is TabLib.
http://tablib.org
A: Export a CSV don't use .xlsx..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Updating a tk ProgressBar from a multiprocess.proccess in python3 I have successfully created a threading example of a thread which can update a Progressbar as it goes. However doing the same thing with multiprocessing has so far eluded me.
I'm beginning to wonder if it is possible to use tkinter in this way. Has anyone done this?
I am running on OS X 10.7. I know from looking around that different OS's may behave very differently, especially with multiprocessing and tkinter.
I have tried a producer which talks directly to the widget, through both namespaces and event.wait, and event.set. I have done the same thing with a producer talking to a consumer which is either a method or function which talks to the widget. All of these things successfully run, but do not update the widget visually. Although I have done a get() on the IntVar the widget is bound to and seen it change, both when using widget.step() and/or widget.set(). I have even tried running a separate tk() instance inside the sub process. Nothing updates the Progressbar.
Here is one of the simpler versions. The sub process is a method on an object that is a wrapper for the Progressbar widget. The tk GUI runs as the main process. I also find it a little odd that the widget does not get destroyed at the end of the loop, which is probably a clue I'm not understanding the implications of.
import multiprocessing
from tkinter import *
from tkinter import ttk
import time
root = Tk()
class main_window:
def __init__(self):
self.dialog_count = 0
self.parent = root
self.parent.title('multiprocessing progess bar')
frame = ttk.Labelframe(self.parent)
frame.pack(pady=10, padx=10)
btn = ttk.Button(frame, text="Cancel")
btn.bind("<Button-1>", self.cancel)
btn.grid(row=0, column=1, pady=10)
btn = ttk.Button(frame, text="progress_bar")
btn.bind("<Button-1>", self.pbar)
btn.grid(row=0, column=2, pady=10)
self.parent.mainloop()
def pbar(self, event):
name="producer %d" % self.dialog_count
self.dialog_count += 1
pbar = pbar_dialog(self.parent, title=name)
event = multiprocessing.Event()
p = multiprocessing.Process(target=pbar.consumer, args=(None, event))
p.start()
def cancel(self, event):
self.parent.destroy()
class pbar_dialog:
toplevel=None
pbar_count = 0
def __init__(self, parent, ns=None, event=None, title=None, max=100):
self.ns = ns
self.pbar_value = IntVar()
self.max = max
pbar_dialog.pbar_count += 1
self.pbar_value.set(0)
if not pbar_dialog.toplevel:
pbar_dialog.toplevel= Toplevel(parent)
self.frame = ttk.Labelframe(pbar_dialog.toplevel, text=title)
#self.frame.pack()
self.pbar = ttk.Progressbar(self.frame, length=300, variable=self.pbar_value)
self.pbar.grid(row=0, column=1, columnspan=2, padx=5, pady=5)
btn = ttk.Button(self.frame, text="Cancel")
btn.bind("<Button-1>", self.cancel)
btn.grid(row=0, column=3, pady=10)
self.frame.pack()
def set(self,value):
self.pbar_value.set(value)
def step(self,increment=1):
self.pbar.step(increment)
print ("Current", self.pbar_value.get())
def cancel(self, event):
self.destroy()
def destroy(self):
self.frame.destroy()
pbar_dialog.pbar_count -= 1
if pbar_dialog.pbar_count == 0:
pbar_dialog.toplevel.destroy()
def consumer(self, ns, event):
for i in range(21):
#event.wait(2)
self.step(5)
#self.set(i)
print("Consumer", i)
self.destroy()
if __name__ == '__main__':
main_window()
For contrast, here is the threading version which works perfectly.
import threading
from tkinter import *
from tkinter import ttk
import time
root = Tk()
class main_window:
def __init__(self):
self.dialog_count = 0
self.parent = root
self.parent.title('multiprocessing progess bar')
frame = ttk.Labelframe(self.parent)
frame.pack(pady=10, padx=10)
btn = ttk.Button(frame, text="Cancel")
btn.bind("<Button-1>", self.cancel)
btn.grid(row=0, column=1, pady=10)
btn = ttk.Button(frame, text="progress_bar")
btn.bind("<Button-1>", self.pbar)
btn.grid(row=0, column=2, pady=10)
self.parent.mainloop()
def producer(self, pbar):
i=0
while i < 101:
time.sleep(1)
pbar.step(1)
i += 1
pbar.destroy()
def pbar(self, event):
name="producer %d" % self.dialog_count
self.dialog_count += 1
pbar = pbar_dialog(self.parent, title=name)
p = threading.Thread(name=name, target=self.producer, args=(pbar,))
p.start()
#p.join()
def cancel(self, event):
self.parent.destroy()
class pbar_dialog:
toplevel=None
pbar_count = 0
def __init__(self, parent, ns=None, event=None, title=None, max=100):
self.ns = ns
self.pbar_value = IntVar()
self.title = title
self.max = max
pbar_dialog.pbar_count += 1
if not pbar_dialog.toplevel:
pbar_dialog.toplevel= Toplevel(parent)
self.frame = ttk.Labelframe(pbar_dialog.toplevel, text=title)
#self.frame.pack()
self.pbar = ttk.Progressbar(self.frame, length=300, variable=self.pbar_value)
self.pbar.grid(row=0, column=1, columnspan=2, padx=5, pady=5)
btn = ttk.Button(self.frame, text="Cancel")
btn.bind("<Button-1>", self.cancel)
btn.grid(row=0, column=3, pady=10)
self.frame.pack()
self.set(0)
def set(self,value):
self.pbar_value.set(value)
def step(self,increment=1):
self.pbar.step(increment)
def cancel(self, event):
self.destroy()
def destroy(self):
self.frame.destroy()
pbar_dialog.pbar_count -= 1
if pbar_dialog.pbar_count == 0:
pbar_dialog.toplevel.destroy()
pbar_dialog.toplevel = None
def automatic(self, ns, event):
for i in range(1,100):
self.step()
if __name__ == '__main__':
main_window()
A: Doing something similar, I ended up having to use a combination of threads and processes - the GUI front end had two threads: one for tkinter, and one reading from a multiprocessing.Queue and calling gui.update() - then the back-end processes would write updates into that Queue
A: This might be a strange approach, but it works for me. Copy and paste this code to a file and run it to see the result. It's ready to run.
I don't have the patience to explain my code right now, I might edit it another day.
Oh, and this is in Python 2.7 I started programming two months ago, so I have not idea if the difference is relevant.
# -*- coding: utf-8 -*-
# threadsandprocesses.py
# Importing modules
import time
import threading
import multiprocessing
import Tkinter as tki
import ttk
class Master(object):
def __init__(self):
self.mainw = tki.Tk()
self.mainw.protocol("WM_DELETE_WINDOW", self.myclose)
self.mainw.title("Progressbar")
self.mainw.geometry('300x100+300+300')
self.main = tki.Frame(self.mainw)
self.RunButton = ttk.Button(self.main, text='Run',
command=self.dostuff)
self.EntryBox = ttk.Entry(self.main)
self.EntryBox.insert(0, "Enter a number")
self.progress = ttk.Progressbar(self.main,
mode='determinate', value=0)
self.main.pack(fill=tki.BOTH, expand=tki.YES)
self.progress.pack(expand=tki.YES)
self.EntryBox.pack(expand=tki.YES)
self.RunButton.pack()
print "The Master was created"
def dostuff(self):
print "The Master does no work himself"
data = range(int(self.EntryBox.get()))
S = Slave(self, data)
print "The Master created a Slave to do his stuff"
print "The Slave gets told to start his work"
S.start()
def myclose(self):
self.mainw.destroy()
return
def nextstep(self):
print "Good job, Slave, I see the result is"
print Master.results.get()
class Slave(threading.Thread):
def __init__(self, guest, data):
print "This is the Slave."
print "Nowdays, Work is outsourced!"
self.data = data
self.guest = guest
threading.Thread.__init__(self)
def run(self):
print "The Slave is outsourcing his work to Calcualte inc."
time.sleep(1)
Outsourcing = Calculate()
Results = Outsourcing.run(self.guest, self.data)
return Results
# unwrapping outside a class
def calc(arg, **kwarg):
return Calculate.calculate(*arg, **kwarg)
class Calculate(object):
def run(self, guest, data):
print"This is Calculate inc. ... how can I help you?"
time.sleep(1)
maximum = int(guest.EntryBox.get())
guest.progress.configure(maximum=maximum, value=0)
manager = multiprocessing.Manager()
queue = manager.Queue()
lock = manager.Lock()
print "Things are setup and good to go"
# Counting the number of available CPUs in System
pool_size = multiprocessing.cpu_count()
print "Your system has %d CPUs" % (pool_size)
# Creating a pool of processes with the maximal number of CPUs possible
pool = multiprocessing.Pool(processes=pool_size)
Master.results = pool.map_async(calc, (zip([self]*len(data), [lock]*len(data),
[queue]*len(data), data)))
for job in range(1, maximum+1):
queue.get() # this is an abuse I think, but works for me
guest.progress.configure(value=job)
# Properly close and end all processes, once we're done
pool.close()
pool.join()
print "All done"
guest.nextstep()
return
def calculate(self, lock, queue, indata):
lock.acquire()
print 'Reading values and starting work'
lock.release()
time.sleep(3) # some work
results = indata # The works results
lock.acquire()
print 'Done'
lock.release()
queue.put("Finished!")
return results
if __name__ == '__main__':
TheMaster = Master()
TheMaster.mainw.mainloop()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to use a pointer's methods in C++? I have a code in which I use a pointer to a class that I made. As an example lets say I have a Person method, and each Person had a name. Now lets say I use a pointer for a person like
Person& * person_;
Now lets say I'm trying to get the name of the person using the pointer I have. If I do something as simple as
person_.getName()
It will return an error saying that it's a non-class type.
My question is: if all I have is the pointer to work with, how do I use the methods of the class it's pointing to?
A: I don't how you got the compiler to even accept Person& * person_, since that's a meaningless declaration (there are no pointers to references). Assuming you actually used Person* person_, simply use the -> operator: person_->getName().
A: It should be person_->getName();
A: You use the pointer notation:
person_->getName()
-> is what you want.
A: person_->getName() is shorthand for (*person_).getName(). Both will work. Also, as @Marcelo pointed out, it should be Person& * person_;
A: person_->getName() is what you should be using.
You can read about it on cplusplus.com
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Jquery Recursive / "InAJAXResponse" usage I'll present my problem in a topic manner bellow, tks in advance for reading!
Function:
$("#someAJAXContainer").load("someHTML.html");
Context: I want to have only one start page and then I'll add a div on the middle where all the content will be loaded dynamicly. Very similiar (if not the same) to a Master page.
...
<body>
<div id='menu'></div>
<div id='someAJAXContainer'></div>
<button>loadAjaxDiv</button>
<div id='footer'></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery-ui.min.js"> </script>
<script src="functions.js></script>
</body>
...
The functions.js would be like this:
$(document).ready(function(){
$("#someAJAXContainer").load("someHTML.html");
$("button").button();
$("#responseA").click(function(event){
alert("the link should no longer took you to jquery.com");
event.preventDefault();
});
});
Problem: When the AJAX Response HTML is loaded on the container it's not linked to already existent JQuery code. So if the response is something like:
<div id ='response'>
<a id = 'responseA' href="http://jquery.com/">jQuery</a>
</div>
The link will take you at the same to jquery.com page :(
So my approach to solve this is using (on the functions.js):
$("#someAJAXContainer").load("someHTML.html", function() {
$("#responseA").click(function(event){
alert("the link should no longer took you to jquery.com");
event.preventDefault();
});
});
But now I'm having multiple levels of inner ajax and it's getting a messy code! I don't like that much the way it's being worked out. So I wonder what kind of errors I might be doing here. Is this even correct at structural, good pratices, level?
Hope I been clear about the issue. I been googling about it and the only answers I've got were similiar to the one proposed before, but it was all very vague.
Regards;
A: Try using live.
$("#responseA").click(function(event){
alert("the link should no longer took you to jquery.com");
event.preventDefault();
});
This will bind the click event only to #responseA element that is in the DOM at start, but wont work for any other that you load later. Live will solve this
$("#responseA").live('click', function(event){
...
});
A: Complementing RealShadow. As I've stated in my reply you can see that .live() won't solve issues where one wants to change elements properties or behaviour, it only allows you to attach events listeners.
Therefore, for a situation like trying to make for a button tag to behave as button, for example:
<div id='response'><buttonOK>ok</buttonOK></div>
The solution that I found more interesting is to add an .ajaxStop() or .ajaxSuccess() event listener. It will work as a $(document).ready(function() {}) for the AJAX calls, so all the AJAX.ready() can be setup on this. One must take into account that the identifier $("#ajaxContainer") must be pointing to the container where the HTML response is loaded so that it can find its newly generated child DOM.
$("#ajaxContainer").ajaxStop(function() {
// Ajax handler called.
$("buttonOK").button();
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Display an image 2nd edition I have a problem with my c++ opencv program. It should show a picture I loaded in, but after debugging only a grey window pops up. Here is my code:
#include <cv.h>
#include <highgui.h>
int main(int argc, char* argv[])
{
IplImage* img = cvLoadImage( "IMG_7321_.jpg" );
cvNamedWindow( "IMG_7321_", CV_WINDOW_AUTOSIZE );
cvShowImage("IMG_7321_", img);
cvWaitKey(0);
cvReleaseImage( &img );
cvDestroyWindow( "IMG_7321_" );
return 0;
}
The .jpg file is in the project folder.
Can anybody tell me what I have to do to get the picture to be shown. Help would be much appreciated!
A: You should check to see if you are successfully loading the file. Try this:
int main(int argc, char* argv[])
{
IplImage* img = cvLoadImage( "IMG_7321_.jpg" );
if (!img) {
fprintf(stderr, "Image not found\n");
return -1;
}
cvNamedWindow( "IMG_7321_", CV_WINDOW_AUTOSIZE );
cvShowImage("IMG_7321_", img);
cvWaitKey(0);
cvReleaseImage( &img );
cvDestroyWindow( "IMG_7321_" );
return 0;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Custom Control that exposes Button Control's OnClick event I need to design a custom control that is basically going to be a fancy button, let's call it CtrlButton.
I want to drop these on my blank form, then go to the Events for my control and specify what to do for the Click event.
If my custom control CtrlButton contained 1 Windows Form Button named button1, could I simply expose the underlying Click event handler for the button1?
public EventHandler Click {
get { return button1.Click; }
set { button1.Click = value; }
}
This code doesn't work! But, that's essentially what I'm trying to do.
EDIT: I see I was awarded Popular Question for this post, yet it still sits there at -1. If this question helps you find your answer, please vote it up.
A: Button.Click is an event, not a property. You can't get and set its value, because it's not a property; you can only add and remove handlers, because it's an event and that's how events work.
But you can write your own event with custom add and remove handlers that wrap the Button:
public event EventHandler Click {
add { button1.Click += value; }
remove { button1.Click -= value; }
}
A: If this is derived from a standard Button control, as this is:
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsControlLibrary1
{
public class RedButton : Button
{
public RedButton()
{
base.BackColor = Color.Red;
}
}
}
the events are available. If you have completely customized to make your own button, you will have to wire up all of the events, ala this post.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Connection error using Rails 3.0 and Mongo 1.4.0 I created a library that would record events to MongoDB from my Rails application. I'm using version 1.4.0 of the mongo gem and Rails 3.0 w/Ruby 1.8.7. The relevant code is:
def new_event(collection, event)
@conn = Mongo::Connection.new("localhost", 27017, :pool_size => 5, :pool_timeout => 5)
@conn.db("event").collection(collection).insert(event)
@conn.close
end
This has worked fine for recording new events as they happen on the site. However, I also need to backfill the db with old events. So I'm doing running a script that basically does this:
SomeModel.find_each do |model|
Tracker.new.new_event("model_event", { ... info from model ... })
end
I'm trying to backfill something on the order of 50k events. As the script runs, I see this:
Tue Sep 27 23:45:20 [initandlisten] waiting for connections on port 27017
Tue Sep 27 23:46:20 [clientcursormon] mem (MB) res:12 virt:78 mapped:0
Tue Sep 27 23:48:49 [initandlisten] connection accepted from 127.0.0.1:51006 #1
Tue Sep 27 23:49:03 [conn1] remove event.application 103ms
Tue Sep 27 23:49:12 [conn1] remove event.listing 127ms
Tue Sep 27 23:49:20 [clientcursormon] mem (MB) res:37 virt:207 mapped:128
Tue Sep 27 23:51:44 [initandlisten] connection accepted from 127.0.0.1:48103 #2
Tue Sep 27 23:51:44 [conn2] end connection 127.0.0.1:48103
Tue Sep 27 23:51:44 [initandlisten] connection accepted from 127.0.0.1:48104 #3
Tue Sep 27 23:51:44 [conn3] end connection 127.0.0.1:48104
Tue Sep 27 23:51:44 [initandlisten] connection accepted from 127.0.0.1:48105 #4
Tue Sep 27 23:51:44 [conn4] end connection 127.0.0.1:48105
Tue Sep 27 23:51:44 [initandlisten] connection accepted from 127.0.0.1:48106 #5
Tue Sep 27 23:51:44 [conn5] end connection 127.0.0.1:48106
The ports (127.0.0.1:XXXXX) and (what I assume are) the Connection Pool #s keep incrementing, until eventually I get this exception from the ruby script:
Failed to connect to a master node at localhost:27017
/var/bundler/turtle/ruby/1.8/gems/mongo-1.4.0/lib/../lib/mongo/connection.rb:526:in `connect'
/var/bundler/turtle/ruby/1.8/gems/mongo-1.4.0/lib/../lib/mongo/connection.rb:688:in `setup'
/var/bundler/turtle/ruby/1.8/gems/mongo-1.4.0/lib/../lib/mongo/connection.rb:104:in `initialize'
A: Just found the solution. I needed to make the connection object a class variable so it was shared across all instances of the Tracker class.
@@conn = Mongo::Connection.new("localhost", 27017, :pool_size => 5, :pool_timeout => 5)
def self.new_event(collection, event)
@@conn.db("event").collection(collection).insert(event)
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android: loading from SQLite Database So I'm still building a Database to support a project of mine. There are two different things to be saved: first, attribute values of some player objects and second, simple values stored in a java class.
ATM my problem lies in the process of loading values of a player object and writing it in the respective class.
Now let's see some code:
Following you see the method I want to use for saving the values in the database.
That works fine atm, but I just realized I'm still passing the contentValues object an extra value for the 'ID' , which I did set - and planned to keep that way - as autoincrement.
Any Idea how to work this in accordingly?
public void savePlayer(Player player[]) {
for (int i = 0; i <= 3; i++) {
playerValues.put("ID", i);
playerValues.put("Name", player[i].getName());
playerValues.put("HP", player[i].getHp());
playerValues.put("Satisfaction", player[i].getsatisfaction());
playerValues.put("Hygiene", player[i].isHygieneInt());
playerValues.put("IsAlive", player[i].isAliveInt());
}
db.insert("playertable", null, playerValues);
}
Okay, hold on to your hats because this might look a bit like spaghetti - the load-method:
public void loadPlayer() {
String[] namecolumn = { "Name" };
String[] intcolumn = { "ID, HP, Satisfaction, Hygiene, IsAlive" };
String[] namesToString = new String[4];
for (int j = 0; j <= 3; j++) {
Cursor playerCursorName = db.query("playertable", namecolumn, "ID="
+ j, null, null, null, null);
namesToString = cursorToString(playerCursorName);
Resource.playerArray[j].setName(namesToString[j]);
}
for (int i = 0; i < 3; i++) {
int[] restToInt;
Cursor playerCursorInt = db.query("playertable", intcolumn, "ID="
+ i, null, null, null, null);
restToInt = cursorToInt(playerCursorInt, 4);
Resource.playerArray[i].setHp(restToInt[i]);
Resource.playerArray[i].setsatisfaction(restToInt[i]);
Resource.playerArray[i].setHygieneInt(restToInt[i]);
Resource.playerArray[i].setAliveInt(restToInt[i]);
}
}
Yeah, I know this looks pretty ugly but let me explain it:
Because there are 4 player objects I planned on iterating through the database entries by using the ID as identifier to get exactly one row at a time and writing the name and the other values of this object in the java class where I want to manage them within my project.
Note: same problem with autoincrement here than in the save method
In addition, I get a CursorIndexOutOfBoundsException when calling loadPlayer because
Index -1 is being requested - isn't that the result of an operation on the database resulting in an error?
Yeah that's pretty much it, I'll provide you with additional code if requested, hope someone can help me
A: You are using Cursors in a slightly odd way here.
The point of a Cursor is to ask SQLite to do the hard work of fetching data for you, and your job is simply to use the cursor to iterate through the returned values.
Firstly, I would change the query here to ask for all values in the table (and perhaps put some condition to constrain what you get back), to make sure your cursor then contains all your values.
Then, I would loop through the cursor's values by using a while loop, (with cursor.moveToPosition(-1) before the loop) moving along the cursor by using cursor.moveToNext().
See the API for more information:
http://developer.android.com/reference/android/database/Cursor.html
With regard to the autoincrement problem, as far as I can remember you can leave out the ID and use db.insert() without that field and the database will provide an ID for you.
You shouldn't have the same issue in your load method because it doesn't make sense to autoincrement when loading, you just get back what's in the database.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What do the keys in Facebook's 'data-ft' JSON structure represent? On Facebook pages, many HTML elements include a 'data-ft' JSON object that is of the form:
data-ft='{
"src":10,
"sty":263,
"actrs":"117307284966434",
"targets":"117307284966434",
"pub_time":1317143005,
"fbid":"153538678072594",
"qid":"5657092603540274768",
"s_obj":5,
"s_edge":1,
"s_prnt":28,
"ft_prefix":"feed_story.top_news",
"ft_story_name":"StreamStoryCreateGeneric_ShareStreamContent_External_Other",
"mf_story_key":"10150331666719785",
"object_id":"153538678072594",
"mf_objid":"153538678072594",
"viewstate_id":"3201743663063655712",
"sub_level":"mid",
"sbj_type":"page",
"is_boulder":"1",
"authentic":1,
"pageid":"117307284966434",
"filter":"h",
"pos":14
}'
What do these keys represent? Some of them are straightforward, such as 'sty' as style, 'actrs' is the Facebook-ID of the original poster, and 'pub_time' is the UNIX epoch representation of the post date & time.
In particular, I am interested in understanding what the 'authentic' key represents, as well as the 'fbid' and 'qid' values.
Thanks for your insight, SO.
A: This is the root of how BFB (Better Facebook user script) can allow filtering, tabbing, etc.
In the HTML source, there is an attribute on each post that looks like this:
data-ft:{
"src":10, "sty":46, "actrs":"14385334364",
"pub_time":1289830690, "fbid":"1485431831867", "s_obj":11, "s_edge":1,
"s_prnt":11, "pos":1, "sec":"new", "filter":"lf",
"app_id":"201278444497"
}
This is the data we need!
BFB parses this when processing each post and extracts the data.
sty = Story type. Each type of story, like wall posts, status updates, pictures, links, etc has a unique story type with its own number. Unfortunately, these are not documented anywhere! I have to figure out the types by observation and trial and error. It's painful. But knowing this type numbers allows BFB to do filtering based on what kind of story it is.
actrs = The unique Facebook id's of the person (or people) that made the post. Again, good for filtering.
pub_time = The time the post was made. This is useful later...
fbid = The unique Facebook ID of the post. Every post has its own ID. At least, it should. See the explanations below for why this is not as reliable as it sounds
app_id = The unique ID of the Facebook application that made this post
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: cakephp auth login problem, only white screen after login I’ve created a small cakePHP application that uses the auth component to manage an admin section for changes.
The problem I’m having ‘only in the production environment’ is that after I login all I can see is a blank white screen. I should be redirected to a ‘dashboard’ view. This blank screen is also what I get with all other ‘admin’ prefixed views that require a logged in user, thus the auth component.
What is strange about this are two things, (1) this works fine in the local host and (2) this application is a copy of one that works fine in both the local host and production.
What I’ve done to try and resolve this is:
-Checked the previous application copy; nothing different found
-Checked that the passwords were hashed
-Checked that the .htaccess file was uploaded in ASCII format (suggested by the host)
Any help with this is appreciated.
Ideally I’d like to understand how to trouble shoot this type of problem.
Thanks, Paul
A: Clear out your tmp cache files anytime you move a cakephp project to a new server or folder. They are located in /app/tmp/cache/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Flex AreaChart gradient fill not applying ratios correctly When doing a gradient fill on an area chart, the gradient ratios are used only between the min and max of the chart. The area below the min is then filled with the last color in the gradient.
To make sure that it was using the ratios only between the min and max I inserted a zero (0) into the chart and the gradient expanded to the full height. I also checked the gradient values by creating a with the gradient fill.
How do i get the ratios to be effective through the entire fill not just between the min and max?
A: The updateDisplayList method in mx.charts.renderers.AreaRenderer is the culprit here.
I believe you will need to create a custom itemRenderer for the area series based on AreaRenderer. From there I think you need to modify the fill method within updateDisplayList to pass the proper bounding region you want.
The fill portion (on/around line 167) would likely be as follows:
fill.begin(g, new Rectangle(0,0,unscaledWidth,unscaledHeight),null);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jquery datepicker with codeigniter issues I'm trying to write a sign up form using CodeIgniter and want to use the jquery datepicker for DOB, but the following isn't working. This is the entire page:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="http://localhost/cc/css/style.css" type="text/css" media="screen" charset="utf-8">
<link rel="stylesheet" href="http://localhost/cc/jquery/css/dot-luv/jquery-ui-1.8.16.custom.css" type="text/css" media="screen" charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>
<script src="http://localhost/cc/jquery/js/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>
<title>CC - Card Central</title>
</head>
<body>
<script>
$(function() {
$( ".datepicker" ).datepicker();
});
</script>
<fieldset>
<legend>Create a new account!</legend>
<fieldset>
<legend>Personal Information</legend>
<form action="http://localhost/cc/index.php/account/create_account" method="post" accept-charset="utf-8">
<input type="text" name="firstname" value="" placeholder="First Name" />
<input type="text" name="middlename" value="" placeholder="Middle Name" />
<input type="text" name="lastname" value="" placeholder="Last Name" />
<input type="text" name="dob" value="" placeholder="Date of Birth" class="datepicker" />
</fieldset>
<fieldset>
<legend>Account Information</legend>
<input type="text" name="username" value="" placeholder="Username" />
<input type="text" name="password" value="" placeholder="Password" />
<input type="text" name="passwordconfirm" value="" placeholder="Password Confirm" />
<input type="submit" name="submit" value="Done!" />
</fieldset>
</fieldset>
</body>
</html>
A: You've forgotten to include the jQuery library :-)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
Put that before the script tag that references jQuery UI and you should be good to go
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Refining the return type of a method in a subclass Say I have the following two classes:
public class A {
protected A create() {
return new A();
}
public A f() {
return create();
}
}
public class B extends A {
@Override
protected B create() {
return new B();
}
}
So if I call f() on an instance of A, it will return another A. And if I call f() on an instance of B, it will return another B since the B.create() method will be called from A.f(). But, the f() method on B is defined to return an object of type A. so this code will not compile:
A a1 = new A();
B b1 = new B();
A a2 = a1.f();
B b2 = b1.f(); //Type mismatch: cannot convert from A to B
Without having to override the f() method in class B, is there any way I can have A.f() return A, while B.f() returns a B? I've messed around a lot with generics but keep hitting a wall.
A:
Without having to override the f() method in class B, is there any way I can have A.f() return A, while B.f() returns a B?
The only problem is in the very last line of code in your question. Just change
B b2 = b1.f();
// to
A b2 = b1.f();
A: I think you've tripped over your own code. The create function versus the f function was confusing you. The following compiles:
class demo {
public class A {
protected A create() {
return new A();
}
}
public class B extends A {
protected B create() {
return new B();
}
}
void d() {
A a1 = new A();
B b1 = new B();
A a2 = a1.create();
B b2 = b1.create();
}
}
When the co-variant create was hidden behind the non-co-variant f, the compiler couldn't "run" the f function and prove it would always return a B.
A: You would also have to override f() as well - your version calls a method that returns A.
public class B extends A {
@Override
protected B create() {
return new B();
}
@Override
public B f() {
return create();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: CSS to keep element at "fixed" position on screen I'm looking for a trick to create a "fixed" HTML object on the browser screen using CSS. I want it to stay in the same position all the time, even when the user scrolls through the document. I'm not sure what the proper term for this is.
It would be like the chat button on Facebook or the Feedback button that is on some websites that follows you throughout the page.
In my situation, I want to keep a div at the absolute bottom-right corner of the screen at all times. Sample CSS appreciated.
A: position: sticky;
The sticky element sticks on top of the page (top: 0) when you reach its scroll position.
See example:
https://www.w3schools.com/css/tryit.asp?filename=trycss_position_sticky
A: You may be looking for position: fixed.
Works everywhere except IE6 and many mobile devices.
A: The easiest way is to use position: fixed:
.element {
position: fixed;
bottom: 0;
right: 0;
}
http://www.w3.org/TR/CSS21/visuren.html#choose-position
(note that position fixed is buggy / doesn't work on ios and android browsers)
A: The tweak:
position:fixed;
works, but it breaks certain options....for example a scrollable menu that is tagged with a fixed position will not expand with the browser window anymore...wish there was another way to pin something on top/always visible
A: Try this one:
p.pos_fixed {
position:fixed;
top:30px;
right:5px;
}
A: position: fixed;
Will make this happen.
It handles like position:absolute; with the exception that it will scroll with the window as the user scrolls down the content.
A: Make sure your content is kept in a div, say divfix.
<div id="divfix">Your Code goes here</div>
CSS :
#divfix {
bottom: 0;
right: 0;
position: fixed;
z-index: 3000;
}
Hope ,It will help you..
A: You can do like this:
#mydiv {
position: fixed;
height: 30px;
top: 0;
left: 0;
width: 100%;
}
This will create a div, that will be fixed on top of your screen. - fixed
A: In order to keep floating text in the same location over an image when changing browser zoom, I used this CSS:
position: absolute;
margin-top: -18%
I think the % instead of fixed pixels is what does it. Cheers!
A: #fixedbutton {
position: fixed;
bottom: 0px;
right: 0px;
z-index: 1000;
}
The z-index is added to overshadow any element with a greater property you might not know about.
A: HTML
<div id="fixedbtn"><button type="button" value="Delete"></button></div>
CSS
#fixedbtn{
position: fixed;
margin: 0px 10px 0px 10px;
width: 10%;
}
A: You can try this code:
<div style="top: 0; position: sticky;">your code</div>
or you can add class/id like this:
html:
<div class="FixedPosition">your code</div>
css:
.FixedPosition{
position: sticky;
top: 0;
}
you may change the "top" if you want it to not be on top of the screen and don't delete the top else it won't work.
I hope this help : )
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "71"
}
|
Q: How could this be optimized?/Class Splitting Not sure if it will actually be more optimized, however What I am trying to do is take all of this code and possibly split it up within different classes? So far it is all just one class but We have been leaning more and more to multiple class projects so I am trying to figure out how I can split this and actually have it help rather then just splitting stuff up to split it up. Any help would be great!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.*;
public class PaintProgram extends JPanel implements MouseListener,ActionListener
{
private int xX1, yY1 , xX2, yY2, choice ;
public static void main(String [] args)
{
new PaintProgram();
}
PaintProgram()
{
JFrame frame = new JFrame("Paint Program");
frame.setSize(1200, 800);
frame.getContentPane().add(this);
JButton button1 = new JButton("Clear");
button1.addActionListener(this);
JButton button2 = new JButton("Filled rectangle");
button2.addActionListener(this);
JButton button3 = new JButton("Filled oval");
button3.addActionListener(this);
JButton button4 = new JButton("Empty rectangle");
button4.addActionListener(this);
JButton button5 = new JButton("Empty oval");
button5.addActionListener(this);
JButton button6 = new JButton("Line");
button6.addActionListener(this);
this.add(button1);
this.add(button2);
this.add(button3);
this.add(button4);
this.add(button5);
this.add(button6);
addMouseListener(this);
frame.setVisible(true);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
if(grid == null){
int w = this.getWidth();
int h = this.getHeight();
grid = (BufferedImage)(this.createImage(w,h));
gc = grid.createGraphics();
}
g2.drawImage(grid, null, 0, 0);
check();
}
BufferedImage grid;
Graphics2D gc;
public void draw()
{
Graphics2D g = (Graphics2D)getGraphics();
int w = xX2 - xX1;
if (w<0)
w = w *(-1);
int h = yY2-yY1;
if (h<0)
h= h*(-1);
switch(choice)
{
case 1:
check();
gc.setColor(Color.YELLOW);
gc.drawRect(xX1, yY1, w, h);
repaint();
break;
case 2:
check();
gc.setColor(Color.CYAN);
gc.drawOval(xX1, yY1, w, h);
repaint();
break;
case 3:
check();
gc.setColor(Color.ORANGE);
gc.drawRect(xX1, yY1, w, h);
gc.fillRect(xX1, yY1, w, h);
repaint();
break;
case 4:
check();
gc.drawOval(xX1, yY1, w, h);
gc.setColor(Color.PINK);
gc.fillOval(xX1, yY1, w, h);
repaint();
break;
case 5:
check();
gc.setColor(Color.MAGENTA);
gc.drawLine(xX1, yY1, xX2, yY2);
repaint();
break;
case 6:
//Acquire clear screen or gay
break;
}
}
public void check()
{
if (xX1 > xX2)
{
int z = 0;
z = xX1;
xX1 = xX2;
xX2 =z;
}
if (yY1 > yY2)
{
int z = 0;
z = yY1;
yY1 = yY2;
yY2 = z;
}
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Empty rectangle"))
{
System.out.println("Empty Rectangle Has Been Selected~");
choice = 1;
}
if (e.getActionCommand().equals("Empty oval"))
{
System.out.println("Empty Oval Has Been Selected!");
choice = 2;
}
if (e.getActionCommand().equals("Filled rectangle"))
{
System.out.println("Filled Rectangle Has Been Selected");
choice = 3;
}
if (e.getActionCommand().equals("Filled oval"))
{
System.out.println("Filled Oval Has Been Selected");
choice = 4;
}
if (e.getActionCommand().equals("Line"))
{
System.out.println("Draw Line Has Been Selected");
choice = 5;
}
if (e.getActionCommand().equals("Clear"))
{
System.out.println("Clear All The Things!!!");
choice = 6;
repaint();
}
}
public void mouseExited(MouseEvent evt){}
public void mouseEntered(MouseEvent evt){}
public void mouseClicked(MouseEvent evt){}
public void mousePressed(MouseEvent evt)
{
xX1 = evt.getX();
yY1= evt.getY();
}
public void mouseReleased(MouseEvent evt)
{
xX2 =evt.getX();
yY2=evt.getY();
draw();
}
}
A: The very first thing you can do is to observe that every selectable option has the following common traits:
*
*They all have a button with a custom text, they;re all added to the main panel and register it as a listener.
*They all draw something, but they do it slightly differently.
*They all contribute to actionPerformed()
Using this observation you can create an abstract DrawOperation class that performs 1 and 3 and the check()/repaint() part of 2. It should also define an abstract method for the variable part of the draw operation. Then you can extend this class to provide the correct draw() method for each operation. (Advanced lesson: look up how anonymous inner classes work and create your operations as AICs.)
A: I would do it like this:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
public class PaintProgram extends JPanel implements MouseListener
{
private int xX1, yY1 , xX2, yY2;
private PaintOperation currentOperation;
private void setCurrentOperation(PaintOperation po) { currentOperation = po; }
private class PaintOperation {
private int choice;
public PaintOperation(final PaintProgram context, String text, int choice) {
this.choice = choice;
final JButton button = new JButton(text);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
context.setCurrentOperation(PaintOperation.this);
context.repaint();
System.out.println("PaintOperation: "+button.getText());
}
});
context.add(button);
}
}
public static void main(String [] args)
{
new PaintProgram();
}
PaintProgram()
{
JFrame frame = new JFrame("Paint Program");
frame.setSize(1200, 800);
frame.getContentPane().add(this);
new PaintOperation(this, "Empty rectangle", 1);
new PaintOperation(this, "Empty oval", 2);
new PaintOperation(this, "Filled rectangle", 3);
new PaintOperation(this, "Filled oval", 4);
new PaintOperation(this, "Line", 5);
setCurrentOperation(new PaintOperation(this, "Clear", 6));
addMouseListener(this);
frame.setVisible(true);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
if (grid == null) {
int w = this.getWidth();
int h = this.getHeight();
grid = (BufferedImage)(this.createImage(w,h));
gc = grid.createGraphics();
}
g2.drawImage(grid, null, 0, 0);
check();
}
BufferedImage grid;
Graphics2D gc;
public void draw()
{
Graphics2D g = (Graphics2D)getGraphics();
int w = xX2 - xX1;
if (w<0)
w = w *(-1);
int h = yY2-yY1;
if (h<0)
h= h*(-1);
switch(currentOperation.choice)
{
case 1:
check();
gc.setColor(Color.YELLOW);
gc.drawRect(xX1, yY1, w, h);
repaint();
break;
case 2:
check();
gc.setColor(Color.CYAN);
gc.drawOval(xX1, yY1, w, h);
repaint();
break;
case 3:
check();
gc.setColor(Color.ORANGE);
gc.drawRect(xX1, yY1, w, h);
gc.fillRect(xX1, yY1, w, h);
repaint();
break;
case 4:
check();
gc.drawOval(xX1, yY1, w, h);
gc.setColor(Color.PINK);
gc.fillOval(xX1, yY1, w, h);
repaint();
break;
case 5:
check();
gc.setColor(Color.MAGENTA);
gc.drawLine(xX1, yY1, xX2, yY2);
repaint();
break;
case 6:
//Acquire clear screen or gay
break;
}
}
public void check()
{
if (xX1 > xX2)
{
int z = 0;
z = xX1;
xX1 = xX2;
xX2 =z;
}
if (yY1 > yY2)
{
int z = 0;
z = yY1;
yY1 = yY2;
yY2 = z;
}
}
public void mouseExited(MouseEvent evt){}
public void mouseEntered(MouseEvent evt){}
public void mouseClicked(MouseEvent evt){}
public void mousePressed(MouseEvent evt)
{
xX1 = evt.getX();
yY1= evt.getY();
}
public void mouseReleased(MouseEvent evt)
{
xX2 =evt.getX();
yY2=evt.getY();
draw();
}
}
A: I'd probably try to bust out that case statement into a class hierarchy first.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can this Java program ever print a value other than zero? I have a favorite C# program similar to the one below that shows that if two threads share the same memory address for counting (one thread incrementing n times, one thread decrementing n times) you can get a final result other than zero. As long as n is reasonably large, it's pretty easy to get C# to display some non-zero value between [-n, n]. However, I can't get Java to produce a non-zero result even when increasing the number of threads to 1000 (500 up, 500 down). Is there some memory model or specification difference wrt C# I'm not aware of that guarantees this program will always yield 0 despite the scheduling or number of cores that I am not aware of? Would we agree that this program could produce a non-zero value even if we can not prove that experimentally?
(Not:, I found this exact question over here, but when I run that topic's code I also get zero.)
public class Counter
{
private int _counter = 0;
Counter() throws Exception
{
final int limit = Integer.MAX_VALUE;
Thread add = new Thread()
{
public void run()
{
for(int i = 0; i<limit; i++)
{
_counter++;
}
}
};
Thread sub = new Thread()
{
public void run()
{
for(int i = 0; i<limit; i++)
{
_counter--;
}
}
};
add.run();
sub.run();
add.join();
sub.join();
System.out.println(_counter);
}
public static void main(String[] args) throws Exception
{
new Counter();
}
}
A: The code you've given only runs on a single thread, so will always give a result of 0. If you actually start two threads, you can indeed get a non-zero result:
// Don't call run(), which is a synchronous call, which doesn't start any threads
// Call start(), which starts a new thread and calls run() *in that thread*.
add.start();
sub.start();
On my box in a test run that gave -2146200243.
A: Assuming you really meant start, not run.
On most common platforms it will very likely produce non zero, because ++/-- are not atomic operations in case of multiple cores. On single core/single CPU you will most likely get 0 because ++/-- are atomic if compiled to one instruction (add/inc) but that part depends on JVM.
Check result here: http://ideone.com/IzTT2
A: The problem with your program is that you are not creating an OS thread, so your program is essentially single threaded. In Java you must call Thread.start() to create a new OS thread, not Thread.run(). This has to do with a regrettable mistake made in the initial Java API. That mistake is that the designer made Thread implement Runnable.
add.start();
sub.start();
add.join();
sub.join();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Benchmarking/Performance testing of the API - REST/SOAP I'm trying to benchmark/ do performance testing of API's at my work. So the client facing is REST format while the backend data is retrieved by SOAP messages. So my question is can some of you share your thoughts on how you implement it (if you have done so in the past/doing it now), am basically interested in avg response time it takes for API to return results for the client
Please let me know if you need any additional information to answer the question
A: Maybe you should give JMeter a try.
A: *
*You can try using Apache Benchmark.This is simple and quick
*Jmeter gives you additional flexibility like adding functional cases along with performance details. Results will be almost similar to Apache Benchmark tool.
*The detailed one which gives Functional Test Result, performance counters settings, Call response time details, CPU and Memory changes along with Load/Stress results, with different bandwidth and browser settings - Visual Studio Team system
I used VSTS2010 for performance testing. Also GET and POST are straight forward. PUT and DELETE need coded version of webtest.
Thanks,
Madhusudanan
Tesco
A: Could not say it any better than Mark, really: http://www.mnot.net/blog/2011/05/18/http_benchmark_rules
A: If you are trying to test the REST -> SOAP calls. One more thing you can consider is to have some stubs created (for backend). This way you can perf test REST -> Stub performance followed by Stub -> SOAP perfomance. This will help in analyzing the individual components.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: JQuery problem with stop() and delay() within animation As you can see on http://jsfiddle.net/FrelCee/5zcv3/4/ , i want to animate those 3 divs when the container is hovered.
Problem is this ugly queue that appears when you fast hover more than once.
I also tried using .stop() function, but then the delay() isn't working.
Here is an example with stop() function and delay() problem : http://jsfiddle.net/FrelCee/FHC99/22/
Does anyone know any better way to this?
Thanks in advance!
A: You just need to supply at least the first parameter to .stop(true, true) to clear the current queue and you can decide if you also want to supply the second parameter to jump to the end of the animation when the next one starts (that's up to you as it gives a slightly different effect). You also need to place the .stop() calls before the .delay() so you aren't clearing the .delay(). See the jQuery doc for .stop() to understand the two parameters for .stop(). When I do that here: http://jsfiddle.net/jfriend00/pYgQr/, it seems to handle fast hover in/out just fine.
// On hover function
var hover = $('#container');
hover.hover(function(){
$(this).find('#first').stop(true, true).animate({left:10}, 600);
$(this).find('#second').stop(true, true).delay(100).animate({left:10}, 600);
$(this).find('#third').stop(true, true).delay(250).animate({left:10}, 600);
}, function() {
$(this).find('#first').stop(true, true).animate({left:-100}, 600);
$(this).find('#second').stop(true, true).delay(100).animate({left:-100}, 600);
$(this).find('#third').stop(true, true).delay(250).animate({left:-100}, 600);
}); // on mouse out hide divs
Also, I don't know why you're doing this at the beginning:
var hover = $('#container');
$(hover).hover(function(){
You can either do this:
var container = $('#container');
container.hover(function(){
or this:
$('#container').hover(function(){
In addition, there is no reason to do:
$(this).find('#first')
These are ids which must be unique in the page so it's better to use:
$('#first')
This will be faster in jQuery because it will be able to just use document.getElementById('first') internally.
A: try this http://jsfiddle.net/5zcv3/5/
you don't have to use both delay and animate, just give animate different speed; the effect is similar
based on my experience, stop is a must
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: License Based Configuration in C# Windows Application I am working on a Windows application in C# (.NET 4.0) and need something to implement some basic ACL rules or more specifically, apply certain configurations based on the user type.
The application has license keys that we are able to use to determine the user type (i.e. User, Installer, Engineer) among other pieces of information.
Based on the type of user, certain features, menus, buttons, and display data will be different. I could just hard code showing and hiding of these elements in the application based on the user type, but we have a permissions matrix that defines the permissions so I would like to create an ACL so we could easily audit the matrix to the application code.
I have looked around but a lot of the ACL and security code in the System.Security namespace seem to be made for Windows and Filesystem ACLs.
Can someone recommend any existing classes (preferably free) that implement simple ACL's in C#.
I just need to be able to do something like this:
ACL acl = new ACL();
acl.addRole("User");
acl.addRole("Manufacturer");
acl.addResource("SpecialButton");
acl.deny("SpecialButton");
acl.allow("SpecialButton", "Manufacturer");
// so later in my app I can do
theUserType = "Manufacturer";
// ...
if (acl.isAllowed(theUserType, "SpecialButton")) {
SpecialButton.Visible = true;
}
I'm not looking to try to stop people from tampering with code at runtime, if they want to go out of their way to do that then they can, but I would like an easy way to create and query the ACL's to determine how the GUI looks and what options are available when the program is loaded based on the key.
It's easy enough to create this but if it is already done then that is even better.
A: If you are deploying your app to Windows 7 or Windows Server 2003/2008, you might want to consider using the free Authorization Manager functionality that comes with Windows.
See here for a full overview from Microsoft.
Essentially, it allows you to define Roles, the Tasks that each Role can perform, and the Operations permissible in each Task.
There is an API which you can use from your C# app to query the Authorization Store, so you can then query what Operations are available to a particular Role. This will give you back an aggregate list of the Operation numbers assigned to that role. Then you can test for the existence of a particular operation (or if it is missing) and customize your UI accordingly.
HTH,
Dean.
A: There really isn't much to what you are talking about.
You have Roles and Roles have Attributes. A single attribute might appear in one or more roles. Simple enough.
The license key defines the role in use. From that, load the list of attributes which could be either a stand alone list of characters ("OPENCONTACT", "EDITCONTACT", DELETECONTACT") or name value pairs (100=OPENCONTACT, 101=EDITCONTACT, etc)
Although you can use AzMan for this, it's a bit more than it sounds like you need.
The Role / Attribute list could be delivered as an encrypted resource that's loaded at runtime...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Structure a python project with 2 different applications I am planning to write a visitors' kiosk in python/GTK. The project will have two applications, the frontend for the kiosk and the backend for management linked to a MySQL DB.
I want both applications to have common code.
I was thinking of structuring the project like so:
project.common - for common code
project.frontend - for the frontend.
project.backend - for the backend.
So:
project/
common
frontend
backend
The problem that I'm going to have is that each application will have its own data_files and I will want the applications packaged separately. The frontend will just run on Linux and the backend will be on Windows(cx_freeze) and Linux.
Can anyone give me any advice?
A: You can have multiple directories (i.e. common/project, frontend/project, and backend/project directories) in your PYTHONPATH with overlapping hierarchies (i.e. each has project top level package), but by default Python will not be happy with this, because it uses the first matching directory it finds and does not search all of them as many other languages do (PHP, Java, etc.), so you will get import errors.
However by putting this in each project/ directory's __init__.py, you are effectively telling Python to keep looking and that this isn't the only place to find code for this package:
import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
Many Pythonistas will shun and mock you for such ridiculous an aberration and declare the foolishness of this endeavor and possibly make unpleasant suggestions about your primate ancestry. "Namespace packages are a terrible idea" they'll say. Prepare to defend your decision. And don't you DARE add those two lines to your source tree without accompanying comments explaining what they do!
This page has a good explanation of some of these concepts:
Explanation: http://www.doughellmann.com/PyMOTW/pkgutil/
If you follow this approach, you can make a distribution with common+frontend and another with common+backend.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: UILocalNotification nil userInfo I try to cancel a Local notification. I attach a dict with a Id for locate it later:
+ (void) send:(NSString*)title actionText:(NSString *)actionText when:(NSDate *)when count:(NSInteger)count option:(NSDictionary *)options
{
UILocalNotification *notif = [[UILocalNotification alloc] init];
//Setup code here...
notif.userInfo = options;
ALog(@"Sending notification %@ %@", notif.alertBody, notif.userInfo);
//Print: Sending notification Task Col 0 0 {id = "1-1"};
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
}
Then when I try to locate it:
+ (void) cancelNotification:(NSString *)theId {
for(UILocalNotification *aNotif in [[UIApplication sharedApplication] scheduledLocalNotifications])
{
if([[aNotif.userInfo objectForKey:@"id"] isEqualToString:theId])
{
// Never come here: userInfo is nil!!!
}
}
}
Always the userInfo is nil. I send the dict:
NSMutableDictionary *info = [[NSMutableDictionary alloc] init];
[info setObject:theId forKey:@"id"];
or
[NSMutableDictionary dictionaryWithObject:theId forKey:@"id"]
with the same result. (theId is NSString)
A: The local notification valid only, it has valid timestamp. So while you are creating make sure that, it has valid timestamp. So that, it will be present in scheduledNotifications of UIApplicaiton.
Please let me know your comments.
eg: localNotification.fireDate = [NSDate date];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: jquery mobile data-icon not appearing on a mobile device I have a mobile web application (.NET MVC) and I'm using JQuery Mobile (beta 3 & jQuery 1.6.3). My question is regarding the attribute 'data-icon' on various elements. For example, I have an element:
<a href="@Url.Action("Index", "Home")" data-icon="home" data-iconpos="notext">Home</a>
When I run the application locally, everything appears as expected. There is a small circular button with the 'home' image inside. When I deploy my application to my host (Arvixe), this same button renders as expected in Chrome, but does not render as expected on my mobile phone (Nexus One). On my phone, the home icon image does not appear at all.
JQuery mobile is referencing the image sprites in the following manner:
background-image:url(images/icons-18-white.png);
I can verify this image does in fact exist in the proper location, as it appears on the desktop browser, I can get to it with a URL (Desktop and Mobile) and my host log shows that requests to that URL are coming back with a 200 response. I have even connected my web application, while hosted to a weinre server, and I can verify the DOM element does have the correct image path. What's even stranger, is that when I go to jquerymobile.com on my phone, the same icons appear, the problem seems isolated to my hosted site.
Is there something I'm overlooking? Thanks.
A: I think I may have solved this. When upgrading from jQuery mobile beta 2 to 3, I did not upgrade the corresponding images as well. Grabbing the updated images seems to have done the trick.
A: Plese place your images folder (which will come from jquery-mobile downloaded zip file) along with your css files.
Ex: If you have copied the .css files to some location named
d:\project\styles\jquery.mobile-1.x.x.css
Then please place the images folder as show below
d:\projects\styles\images
A: you need to set data-role="button" on anchors for them to appear as buttons with jQM (jQuery Mobile).
see here
<a href="#" data-role="button" data-icon="home" data-iconpos="notext">Home</a>
this is the only thing I can think of.
A: The latest jquerymobile has fixed this issue. If not, you need to check the following steps.
*
*check images folder of jquerymobile and jquerymobile CSS are in the same directory
*If you put jquerymobile CSS in separate folder, you need to change "path" in this stylesheet
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How can I create a searchable attribute for a page on Confluence wiki? I want to create a page in my confluence wiki which has a searchable attribute. Right now search is limited to the pages text, and then filtering using tags. It would be great if I could filter further based on defined page attributes.
A: The easiest way is to just add specific labels to that page .. e.g. "info1" and "info2". Afterwards you're able to search for that page using the normal Confluence search and searching for labelText:info1 and labelText:info2.
Another choice is using a combination of the Metadata Plugin and the Reporting Plugin together - they are both available for free at Atlassian's Plugin Exchange.
A: You can use a SQL query to search the Confluence storage format (XML source) of your pages.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: jQuery UI DatePicker with nested_forms Gem I've looked at this but this didn't solve my issue but it's the same circumstance. jQuery is loaded just fine.
Here's my 'nested_form':
<%= f.fields_for :events do |event_form| %>
<%= event_form.text_field :name %>
<%= event_form.text_field :date, :class => 'event_date' %>
<%= event_form.text_field :email %>
<%= event_form.text_field :place %>
<%= event_form.link_to_remove "Remove Event", :class => "remove_task" %>
<% end %>
And here's the JS:
jQuery(document).ready(function($) {
$('.event_date').each(function() {
$(this).datepicker();
});
});
Lastly here's the html that's generated. You can see the jQuery UI adds it's class (hasDatepicker) for DatePicker:
<input class="event_date hasDatepicker" id="group_events_attributes_new_1317162040750_date" name="group[events_attributes][new_1317162040750][date]" size="30" type="text" style="border-top-left-radius: 5px 5px; border-top-right-radius: 5px 5px; border-bottom-left-radius: 5px 5px; border-bottom-right-radius: 5px 5px; ">
Any help would be greatly appreciated. Thanks!
A: Firstly, You can just write this for displaying the datepicker fields rendered from the beginning:
$(function() {
$('.event_date').datepicker();
});
But for the fields created through javascript by nested_forms, you have to intercept the nested:fieldAdded event triggered by the form element after adding fields (see documentation here). You can accomplish it in this way:
$(function() {
$('form').live('nested:fieldAdded', function(event) {
$(event.field).find('.event_date').removeClass('hasDatepicker').datepicker();
});
});
Note the removeClass('hasDatepicker'): without it, the datepicker fields created dinamically by javascript are not initialized correctly.
A: I'm doing the same thing in a form right now. Here's my example with jQuery 1.7.
(function ($) {
var app = {}, opts = { dateFormat: 'yy-mm-dd' }, dateSelector = 'input.event_date:visible';
app.init = function(){
$(window).on('nested:fieldAdded', onFieldAdded);
$(dateSelector).datepicker(opts);
};
function onFieldAdded(e) {
e.field.find(dateSelector).datepicker(opts);
}
$(app.init);
return app;
} (jQuery));
For older versions of jQuery, you would use the following in the init function.
$(window).bind('nested:fieldAdded', onFieldAdded);
What's nicer about what I'm doing, is less repetition (strings for selectors) and I don't call datepicker on hidden elements, so there's no need to call 'removeClass('hasDatepicker') on elements added through nested_forms.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PyCharm code completion: how to prevent space key and "dot" from committing lookup item How does one disable the space key from committing the suggestion when using code completion?
If I attempt to name something "req" for example, when I'm done typing, and enter a "space," I wind up with "request" instead -- this being just one example.
I don't see it anywhere in the keymap, and have seen this mentioned in other places without any apparent solution.
A: There's a 'Preselect the first suggestion' option in IDE Settings | Editor | Code completion section. What is it set to? Try to use 'Smart' and 'Never' options to see which one works better for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Span inside div? problems in ie8? I have span tag inside div tag.
var a = jQuery("<span class = 'B'>");
For some reason i am not able to see the contents of var a on ie., but I can see the contenet on mozilla.
A: You have no div there.
Try this one
var a = jQuery("<span />", {class:'B'}).appendTo('#yourDiv');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Bash and MySQL variables error I have the following script:
#!/bin/sh
Q=`</dev/urandom tr -dc A-Za-z0-9 | head -c30`
mysql -uusername -ppasword accounts -e "update forum set key='$Q' where id='1';"
I have to add back-ticks (``) to "forum", "key" and "id", otherwise it returns me an error:
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key='xdindSG7hK9KaYgs9RISJNqrzmn4LJ' where id='1'' at line 1
But if I add the back-ticks, bash interprets them as variables.
What should I do?
A: Try a HERE document:
#!/bin/sh
Q=`</dev/urandom tr -dc A-Za-z0-9 | head -c30`
mysql -uusername -ppasword accounts <<HERE
update forum set key='$Q' where id='1';
HERE
Try with
cat <<HERE
update forum set key='$Q' where id='1';
HERE
Output:
update forum set key='fnPIOid15anEJ2a3zVL6I1wbRjAKk0' where id='1';
A: Switch the single and double quotes. Single quotes instructs bash to ignore the contents and you will be able to add your back-ticks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: js migrate question When I moved a paragraph of javascript code from a php file to a individual js file, the js doesn't work anymore.
I just simplely removed the "script" tag and paste all the js code into js file.
Did I missing some codes or tags?
The code is
<script>
_i = <?=$k+1?>;
function addlng() {
_id = "lang_"+_i;
$j("#lang_area").append("<div class='lang_addition' id="+_id+"></div>");
$j("#s_lang").clone().appendTo("#"+_id);
$j("#"+_id).append('<span><a href="javascript:void(0)" > <img id="addlng" class="addlng"
src="<?=style_url('mvl/images/').'bullet_blue_collapse.png'?>"
onclick="javascript:sub_img(\''+_id+'\');" /></a></span>');
_i++;
}
function sub_img(obj) {
$j("#"+obj).remove();
}
</script>
A: <?=$k+1?> is php. It outputs the value currently in $k+1. You'll have to look in the php to see what $k is. You'll likely need to keep this in your php file:
<script type="text/javascript">
var _i = <?=$k+1?>;
</script>
Then remove that line for your .js file and make sure that you include your .js file later in your HTML than that script outputted by php.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: mediadisplay complete I am use Mediadisplay in stage. I want to make show button When video is complete.
But not show play button after video completed. How can I do this. Thanks for answers.
general.video_button.onRelease = function(){
general.video.play(0);
general.video_button._visible = false;
}
general.video.complete = function (){
general.video_button._visible = true;
}
A: Ok I am make.
general.video.addEventListener("complete",example);
function example(){
general.video_button._visible = true;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: EditorFor dilemma I understand that Html.EditorFor is the best practice for creating form fields, but I'm really annoyed that I cannot add html attributes to it.
I understand the reason for that, but I just cannot imagine form fields without css class declarations. Is it really the formal best practice to use EditorFor, or should I use TextBoxFor, or even plain HTML element, for defining additional html attributes?
In addition, since I'm planning to handle all form elements using client-side scripts, I don't really need any special server-side functionality, so I'm having a hard time figuring out what advantages do I get from using EditorFor / TextBoxFor.
What do you think about that?
A: you can use templated helpers for Html.EditorFor which really is the only reason to use it in the first place.
here's an mvc2 article, but it's the same in mvc3.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Know of any JQuery slider that also magnifys the current slide? I'm looking to create a similar effect to the one used in the header bar for this page:
http://www.sjlwebdesign.co.uk/portfolio/
Any idea's on a plugin or method that would achieve this effect easily?
Edit: When i say similar, I would like to have an area in the center of a header panel that actually magnifys the image as it slides into the center. Unlike the above example which simply cuts it.
Thanks,
Jai
A: They're not doing anything special with jQuery really, just using the easySlider plugin along with a clever background image to mask the 'inactive' slides.
A: Roundabout is a jQuery carousel that is very dynamic.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to get the rotation and scale between two images with only a Surf Descriptor of each? I'm using Surf for landmark recognition. This is the process I thought:
1) save before hand one Surf Descriptor for each landmark
2) A user takes a photo of a landmark (eg building)
3) A Surf Descriptor is computed for this image (the photo)
4) This descriptor is compared against each landmark descriptor stored
and the one with the lowest DMatch.distance between the 11 closest Feature Points
is choosen as the landmark recognized
5) I want to calculate the rotation and scale-ratio between the image obtained and the
landmark image stored.
My understanding is that I can only get this rotation and scale-ratio through keypoints, because
the Feature Descriptor is only a Unique Reduced Representation for a Keypoint. As such I would
have to save both the keypoints and Feature Descriptors for each landmark. Is that right?
This is what I'm doing right now:
cv::SurfFeatureDetector surf(4000);
..
surf.detect(image1, keypoints1);
surf.detect(image2, keypoints2);
..
cv::SurfDescriptorExtractor surfDesc;
surfDesc.compute(image1, keypoints1, descriptor1);
surfDesc.compute(image2, keypoints2, descriptor2);
..
vector<cv::DMatch> descriptorsMatch;
BruteForceMatcher<cv::L2<float> > brute;
brute.match(desc1, desc2, descriptorsMatch);
//Use only the 11 best matched keypoints;
nth_element( descriptorsMatch.begin(), descriptorsMatch.begin()+10, descriptorsMatch.end() );
descriptorsMatch.erase( descriptorsMatch.begin()+11, descriptorsMatch.end() );
..
for ( .. it = descriptorsMatch.begin(); it != descriptorsMatch.end() .. )
{
distanceAcumulator +=it->distance;
angleAcumulator += abs(keypoints1[it->queryIdx].angle - keypoints2[it->trainIdx].angle) % 180 ;
scaleAcumulator1 +=keypoints1[it->queryIdx].size;
scaleAcumulator2 +=keypoints2[it->trainIdx].size;
}
angleBetweenImages = angleAcumulator/11;
scaleBetweenImages = scaleAcumulator1/scaleAcumulator2;
similarityBetweenImages = distanceAcumulator/11;
..
A: Just comparing scale of descriptors and their rotation is naive and generally will not work. What you need is applying some geometrical model to find relationship between photos. See more in this book http://www.robots.ox.ac.uk/~vgg/hzbook/, especially PART II: Two-View Geometry.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to stream an XElement/XDocument with WCF? I have the following method signature. I cannot change it (i.e. I cannot change the return type).
public Stream GetMusicInfo(string songId)
{
XElement data = dao.GetMusicInfo(songId);
// how do I stream the XElement?
}
How can I stream the XElement/XDocument with WCF?
A: That's reasonably simple, if you don't mind actually fetching all the data in that first line:
public Stream GetMusicInfo(string songId)
{
XElement data = dao.GetMusicInfo(songId);
MemoryStream ms = new MemoryStream();
data.Save(ms);
ms.Position = 0;
return ms;
}
In other words, just write it out in-memory, and return a stream over that in-memory representation. Note the Position = 0; call, which is necessary as otherwise the stream will be positioned at the end of the data.
I would hope that WCF would then just do the right thing with the stream.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to hide UITabBar on a UITabBarController that I didn't subclass? Visually this is what I want
I have a UITabBarController. I want to hide the UITabBar when the user enters the middle tab. The middle tab's loads a view controller of class B. This is the behavior of the popular camera app Instagram. Their middle tab loads up a full screen camera.
------------- ------------- -------------
| VC | | VC | | VC |
| for | | for | | for |
| A | | B | | C |
| | | | | |
|------------ | | |------------
{ A } B | C | | | | A | B { C }
------------- ------------- -------------
Proposed solution from all other related StackExchange questions
We already have dozens of questions on how to hide the UITabBar when a particular view controller is pushed. The general consensus is this:
b.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:b
animated:YES];
My problem is, I never subclassed the UITabBarController. I created it in Interface Builder. I never manually push my view controllers, so the above solution doesn't work for me.
Failure attempt 1
Inside my middle view controller, I turn on hidesBottomBarWhenPushedin the constructor. This had no effect.
@implementation B
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.hidesBottomBarWhenPushed = YES;
}
return self;
}
Failure attempt 2
I also tried assigning my app delegate as a UITabBarControllerDelegate. When the UITabBarController notifies me that a tab has been tapped, I turn on hidesBottomBarWhenPushed only for the middle view controller. This also failed to hide the UITabBar.
#pragma mark UIApplicationDelegate
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
[window addSubview:self.rootViewController.view];
[window makeKeyAndVisible];
self.rootViewController.delegate = self;
}
#pragma mark UITabBarControllerDelegate
- (void) tabBarController:(UITabBarController *)tabBarController
didSelectViewController:(UIViewController *)viewController
{
if ([viewController isKindOfClass:[B class]]) {
viewController.hidesBottomBarWhenPushed = YES;
} else {
viewController.hidesBottomBarWhenPushed = NO;
}
}
A: - (void) hidetabbar:(BOOL)hiddenTabBar
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
for(UIView *view in self.uiTabBarController.view.subviews){
if([view isKindOfClass:[UITabBar class]]) {
if (hiddenTabBar) {
[view setFrame:CGRectMake(view.frame.origin.x, 431, view.frame.size.width, view.frame.size.height)];
} else {
[view setFrame:CGRectMake(view.frame.origin.x, 480, view.frame.size.width, view.frame.size.height)];
}
} else {
if (hiddenTabBar) {
[view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, 431)];
} else {
[view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, 480)];
}
}
}
[UIView commitAnimations];
hiddenTabBar = !hiddenTabBar;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to do a live midi streaming? I'm looking for help in my research
I'm trying to generate live midi so that people can listen to it via a web browser
I'm not sure but I'm guessing there must be a way to set up a midi server to accept connections from my desktop with midi sequencer , sending that midi data to an online midi server where people can connect to and listen to the midi that is generating live right in their web browser
any help appreciated
A: You are going to be better off writing a plugin to handle this. That being said, it is possible to dynamically play MIDI with JavaScript. See this question: generating MIDI in javascript
You could read in the data just like any feed from your web server, and play it back in chunks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Javascript literal escaped in IE but not Firefox, Chrome or Safari I have generated inline code that assigns values to a javascript array. One of the elements of the array should be set to "c:\folder\somefilename". The statement is huge so I omitted most for the sake of brevity:
<SCRIPT type="text/javascript">
var StepsList = {"steps": [
{
"id": "RST4551509111516131001035411012110410849",
"stepAudio": "",
"screenImage": "IO1A.PNG",
"demoNote": "",
"controlRect": {
"top": "297",
"left": "256",
"right": "277",
"bottom": "318"
},
"valueText": "c:\uploadfile.txt",
"label": "Presentation Server File"
[snipped]
</SCRIPT>
The content of the valueText element, "c:\uploadfile.txt" is captured from user input prior to code generation. When this code is executed in Chrome, Firefox, IE5, IE6 or Safari, the literal is not parsed and simply assigned to the array correctly. IE7,8 and 9 throw an error "Expected hexadecimal digit" seeing the "\u" as an escape sequence.
I don't want javascript parsing my literals for escape characters. I have tried the old and putting it in a CDATA tag. Is there a work around for this problem?
TIA,
Eddie
A: If your string will contain a literal backslash, it must be escaped. For example:
{"valueText": "c:\\uploadfile.txt"}
If you're creating the JSON with a library on the server, it would automatically be escaped. That is, please don't generate JSON by hand.
A: Have you tried this?:
"valueText" : "c:\\uploadfile.txt"
A: This MSDN page indicates that the proper way to handle this in JScript (IE) is to use two backslashes.
Note:
If you want to use the literal text \u in a string, then use two backslashes - (\u) — one to escape the first backslash.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Print Alfresco exception I've some problem printing the exception stack trace for Alfresco Exception.
On debug mode, step by step under Eclipse IDE I'm able to see the message when the exception is raised inspecting the Exception object but, when I send the error message to console output it's always null.
The exception is raised by this instruction:
try {
UpdateResult[] results = WebServiceFactory.getRepositoryService().update(cml);
}
catch (Exception ex) {
System.out.println(" " + ex.getStackTrace());
System.out.println("ERROR - createContent : " + ex.getMessage());
}
(in that case I tryed to write on a folder that not exists on repository) and inspecting the ex object on eclipse I can see the message:
java.lang.IllegalStateException: Failed to resolve to a single NodeRef with parameters (store=workspace:SpacesStore uuid=null path=/app:company_home/cm:UploadFromJava), found 0 nodes.
but ex.getMessage() returns null
Anyone could help me?
thanks,
Andrea
A: Implementing a method in this way:
NamedValue setNameProperty(String name) throws AlfrescoRuntimeException
{
try {
return Utils.createNamedValue(Constants.PROP_NAME, name);
}
catch (Exception ex) {
throw new AlfrescoRuntimeException(ex.getMessage());
}
}
The message is correclty printed with e.printStackTrace();
A: Try to replace your package in the log4j.properties from debug to error
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to use Email tag in HTML5 In HTML5 there is a new tag
<input type="email">
when I am using it in a form, the error it shows when i leave it blank or put a non email text or in it looks pretty weird . How can I change the CSS and text for that error box ??
A: For Google Chrome, you could use the following pseudo-classes to style the bubble:
::-webkit-validation-bubble {}
::-webkit-validation-bubble-arrow-clipper {}
::-webkit-validation-bubble-arrow {}
::-webkit-validation-bubble-message {}
Not sure if/when other browsers will support styling the error messages. See the following links for reference:
Styling HTML5 Form Validation Errors
How do you style the HTML5 form validation messages?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Reading response from (simulated) asynchronous file upload with jQuery, IFRAME I am simulating an asynchronous file upload by targeting an iframe, like so:
<form id="upload_form" action="upload.php" method="POST" enctype="multipart/form-data" target="upload_iframe">
<input type="file" name="upload_input" />
<iframe id="upload_iframe" name="upload_iframe" src=""></iframe>
</form>
After a file is selected, the form is submitted like so (using jQuery):
$('#upload_input').change(function() {
$('#upload_form').submit();
});
The file is uploaded, and the JSON response is sent to the iframe. In Firebug, I can see that the iframe's content is:
<html>
<head></head>
<body>{"success":true}</body>
</html>
I am using the iframe's load event to wait for the response. The load event is firing. (It actually fires twice, which is a minor issue.) However, I can't figure out how to read the response. I have tried various calls, but none of them return anything:
$('#upload_iframe').find('body')
$('#upload_iframe').html()
$('#upload_iframe').text()
Is there something I am missing?
A: I have found a solution that works, although it seems less than ideal. This code goes in the iframe load event handler:
if (!$(this)[0].contentDocument.childNodes[0].children[1].childNodes[0])
{
return;
}
var response = $(this)[0].contentDocument.childNodes[0].children[1].childNodes[0].wholeText;
var json = $.parseJSON(response);
A: this should do your work $('#upload_iframe').find('body').text()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django: How can I gzip staticfiles served in dev mode? My django.contrib.staticfiles settings seems to be ok as all static files get served as expected.
However, eg. /static/*.css files do not get gzipped although I have GZipMiddleware turned on.
Fyi. my views html actually does get gzipped, only the files served by the staticfiles app dont. Seems these responses dont go through the middleware chain?
A: The trick is to have the development server run with the '--nostatic' flag set: ./manage.py runserver --nostatic.
One then can user a url pattern for serving the static files like so:
if settings.DEBUG:
static_pattern = r'^%s(?P<path>.*)$' % (settings.STATIC_URL[1:],)
urlpatterns += patterns('django.contrib.staticfiles.views',
url(static_pattern, 'serve', {'show_indexes': True}),
)
When run without --nostatic, django will automatically serve things under STATIC_URL without going through the middleware chain.
Thanks to Dave for his pointers!
A: Is it possible you don't have the GZipMiddleware AT THE TOP of your settings.MIDDLEWARE_CLASSES? That might cause weird behavior.
If this is a production server, though, you probably shouldn't be serving static files with django at all. I'd recommend gunicorn and nginx.
EDIT: If not that, what if you serve the files "manually" via urls.py, using something like:
urlpatterns += staticfiles_urlpatterns() + \
patterns('',
(r'^%s/(?P<path>.*)$' % settings.MEDIA_URL.strip('/'), 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
*[(r'^%s/(?P<path>.*)$' % settings.STATIC_URL.strip('/'), 'django.views.static.serve', {'document_root': path, 'show_indexes': True}) for path in settings.STATICFILES_DIRS]
)
Alternative #3: Nginx is pretty easy to install locally, and you could just point it at your Django server (no need for gunicorn/uwsgi/whatever).
A: In production environment your webserver (Apache/Nginx/IIS) takes care of gzipping static, so doesn't matter whether gzip works in dev or not.
A: additional for Carsten's answer https://stackoverflow.com/a/7673706/8137384
Modern versions contains the helper:
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Format an SQL query in Python without executing it Python has all sort of libraries to interface with databases, which provide a nice way to build SQL queries without worrying about SQL injections. For instance, with sqlite3:
for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
]:
c.execute('insert into stocks values (?,?,?,?,?)', t)
The trouble is, I don't want to execute the query, I just want to format it and get the query as a string. I guess I could escape things myself, but it's not a very elegant solution. There has to be a way to get the formatted queries without actually connecting to a database and running them.
(The context is that I'm writing a filter which prepares a series of SQL statements from the input, but I don't want to run them on a specific database, just save them for later.)
A:
There has to be a way to get the formatted queries without actually connecting to a database and running them
Not really.
The RDBMS handles this internally with "prepared queries" and "bind variables". The "formatted" doesn't actually exist. Anywhere.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do I stop images or flash from loading into the browser? I am creating a web page that accepts a hyperlink from the user and displays that page in an iframe. While rendering the page, I would like to show just the text and simple colors, thats it.
I would like to block all the media files like images and flash scripts from showing up.
If not an extensive one, for the starters, I would like to confine the scope to .gif, .jpeg, .jpg, .png, .swf.
Or does anyone know of a site with similar functionality?
A: You can write a simple dom parser and parse the page before show it in iframe. Then before showing it you can remove whatever you want.
your iframe whould like
<iframe src="your_parser.php"></iframe>
In your parser you can get the content from page using file_get_contents() or curl() it is your choise (i would use curl). Then you can remove the media you want.
A: If you're using Firefox, use the Adblock Plus extension. You can specify the types of items to block via a filter rule. An example (using Safaribooks) looks like this:
||techbus.safaribooksonline.com/static/201109-2191-techbus/images/6.0/*.jpg
However, if you're talking about incorporating functionality into your page to strip out a specific list of content-types, this approach wouldn't help you. You'd need to pull the html source and strip out the offending content-types.
A: also if you are using cms. you should be turn off bbcode image, and embed html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Consume an RSS Feed for Syndication in Jekyll I have two jekyll web sites, and I want to syndicate some of the content (one of the categories) from the source blog to the receiving blog via syndication.
I can see how RSS feeds are automatically created with jekyll, but how does one consume them on another site - so that it looks like those posts are from that second site?
Can I do this in jekyll?
A: The biggest problem is that you jekyll is a static website generator. So you can't do this automatically inside of Jekyll. However, there are two options:
*
*You would need to setup a cron script of some sort that pulls down the RSS feed, creates the jekyll files, runs the jekyll command and uploads it to the web. This can all be automated.
*You could use javascript to display this all. This would basically be writing your own java script (or modifying one you found on the internet). You could use something like this: http://code.google.com/p/jsrss/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why do I get "SOAP Response Version Mismatch" Following is the flex code to import a csv data file via c# webservice.
private function Import():void{
CursorManager.setBusyCursor();
var op:Operation = Operation(_webservice.getOperation('ImportData'));
op.addEventListener(FaultEvent.FAULT,operationFault);
op.addEventListener(ResultEvent.RESULT,operationResult);
var ba:ByteArray = new ByteArray();
ba.writeUTFBytes(objectToXML(datasource.source).toXMLString());
op.arguments = new Array(filename, ba);
op.send();
}
protected function operationFault(e:FaultEvent):void
{
CursorManager.removeBusyCursor();
Alert.show(e.fault + " (" + e.statusCode + ")");
}
protected function operationResult(e:ResultEvent):void
{
datasource.removeAll();
CursorManager.removeBusyCursor();
Alert.show("Success");
}
and following is the c# webservice:
[WebMethod]
public XmlDocument ImportData(String filename, byte[] data)
{
Boolean bReturn = false;
/* .... code to import data .... */
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<response>" + (bReturn ? "true" : "false") + "</response>");
conn.Close();
return xmlDoc;
}
The application works fine on my development environment, whereas when I run it on the production server I get the following error message:
[RPC Fault faultString="SOAP Response Version Mismatch"
faultCode="DecodingError" faultDetail="null"] (404)
Development Environment is:
Win7, MSSQL Server 2005, MS Visual Studio 2010, .NET Framework version 4.0.30319
Live Server:
Win2008 Server, MSSQL Server 2005, IIS7, .NET Framework version 4.0.30319
Can anyone think of a reason regarding why I get the error message above on the live server?
Thanks.
A: I figured the problem. The data file I was trying to import was of 7MB text file. I split it into 2 files and tried to import then it worked. So the problem was the size of the data being transferred to the server.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How does java.util.concurrent.RecursiveTask work? could anyone tell me the logic behind java.util.concurrent.RecursiveTask? I couldn't find the source code either on a very cursory look, so maybe someone can point me to it as well? Thanks.
A: You can look at a hyperlinked source.
A: You could just get the java sources that are delivered with the JDK (src.zip) or decompile that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: DataBinding To Two Sources I have a need to use two listboxes, each bound to a different collection.
i originally had this working with one listbox and binding before the need to bind two came up.
Here is how I was doing that.
<Window x:Class="TeamManager.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc ="clr-namespace:TeamManager"
Title="Game Manager" Height="800" Width="800">
<Window.Resources>
<DataTemplate DataType="{x:Type loc:Game}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"></ColumnDefinition>
<ColumnDefinition Width="100"></ColumnDefinition>
<ColumnDefinition Width="100"></ColumnDefinition>
<ColumnDefinition Width="100"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Name="dateBlock" Grid.Column="0" Grid.Row="1" Text="{Binding Date, StringFormat=d}"></TextBlock>
<TextBlock Name="TimeBlock" Grid.Column="1" Grid.Row="1" Text="{Binding Time}"></TextBlock>
<Button Grid.Row="1" Grid.Column="2" CommandParameter="{Binding Id}" Click="Manage_Click" >Manage</Button>
<Button Grid.Row="1" Grid.Column="3" CommandParameter="{Binding Id}" Click="Delete_Click" Height="16" Width="16">
<Image Source="/Images/DeleteRed.png"></Image>
</Button>
</Grid>
</DataTemplate>
</Window.Resources>
<StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
<StackPanel>
<TextBlock>Upcomming Games</TextBlock>
<ListBox ItemsSource="{Binding}" Name="GameList"></ListBox>
</StackPanel>
<StackPanel Orientation="Vertical" HorizontalAlignment="Left">
<Button Height="30" Width="100" Margin="10,10,10,10" Click="AddGame_Click">Add New Game</Button>
</StackPanel>
</StackPanel>
</StackPanel>
And my code simply set the DataContext of the window to a ObservableCollection
with the need to use TWO collections I created a wrapper class like this
public class AppModel
{
public ObservableCollection<Game> gameCollection { get; set; }
public ObservableCollection<Player> playerCollection { get; set; }
}
And my CS is now setting the DataContext to an object of AppModel
GameDBEntities _entity = new GameDBEntities();
AppModel _model;
public MainWindow()
{
InitializeComponent();
DataContext = model;
}
AppModel model
{
get
{
if (_model == null)
{
_model = new AppModel();
}
if (_model.gameCollection == null)
{
_model.gameCollection = new ObservableCollection<Game>(_entity.Games);
}
if (_model.playerCollection == null)
{
_model.playerCollection = new ObservableCollection<Player>(_entity.Players);
}
return _model;
}
set { }
}
In my Xaml, how can I set the datacontext of the existing listBox to be bound to the Collection Of Games in The AppModel?
Once I get that working I will work on the second listbox on my own.
Thanks!
A: Would changing the Binding to <ListBox ItemsSource="{Binding Path=gameCollection}" Name="GameList"></ListBox> solve your problem?
As per your question you state that you used to set the DataContext to the gameCollection, but now that you have changed this to use the AppModel, you will need to also change your binding as appropriate.
This will essentially change the Binding from being just bound to gameCollection, it will now be set to use AppData.gameCollection.
A: You need to add a Path to the Binding. The DatacContext will be the model, the path should point to either collection:
<ListBox ItemsSource="{Binding gameCollection}" ...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Submit data with ajax & jQuery I need to submit some data via ajax. It is not a form, but there are couple of radiobuttons on the page that belond to a form.
I need to detect which of the two radio buttons is selected when I send ajax request, without submitting the form and append that value to my ajax post. How do I do that?
$.ajax({
url: "ajax.php",
type: "POST",
data: "op="+act+"&radioButton="+id
});
<input class="radioB" type="radio" value="all" name="users" checked> All
<input class="radioB" type="radio" value="some" name="users"> Some
A: There are more options how to check which of the buttons is selected e.g.
$('.radioB:checked').val(); // returns the value or just val() without :checked
$('.radioB').is(':checked'); // can be used in a loop with if statement
So it would transform into:
$.ajax({
url: "ajax.php",
type: "POST",
data: "op="+act+"&radioButton="+$('.radioB:checked').val()
});
A: var act = $(".radioB[name='users']").val();
will save all or some into act
A: This should give an idea of what to check for in regards to the getting radio button status (http://forum.jquery.com/topic/checking-if-certain-radiobutton-is-checked). As to passing that data on via jquery ajax, google that.
A: Just serialize and send the form data:
$.post('ajax.php', $('#myFormId').serialize());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Gesture starts in one UIView, continues in another? In brief: Is there a way to hand-off an in-progress drag gesture from one view to another?
More detail: I'm working on an iPad app. Imagine a situation where there's a playfield in the middle of the screen. On the borders are a bunch of "pieces" that can be dragged onto the playfield.
When one of the pieces is dragged onto the playfield, I want its appearance to change. Though it might be simplest if I had a single view that transformed its appearance when dragged onto the playfield, in my particular case, it's simpler if there is one view for the off-playfield appearance and another for the on-playfield appearance.
The trick is this: while I'm dragging the piece onto the field, I want the drag to continue on once I've gotten rid of my "off-playfield" view and added my "on-playfield" view. Essentially, I want to hand-off the gesture from one view to another, while the user goes through one continuous drag.
Is there a way to do this?
UPDATE: Actually got this working using the single-view approach, but am still curious as to whether a gesture hand-off can be done...
A: I think this isn't possible. What is possible is to have a parent view that contains the "before" view and "after" view. As the drag occurs, that parent view can switch between the two views while maintaining the drag.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PHP grouping by data value My data variable:
1=icon_arrow.gif,2=icon_arrow.gif,3=icon_arrow.gif
I need it to be grouped by the value after =, so in this case it should look like this:
$out = array('icon_arrow.gif' => '1, 2, 3');
The 'icon_arrow.gif' field need to be unique, and can't repeat.
How it can be done?
A: Initialize an array:
$array = array();
Explode the input by ,, store results as an array based on a sub-explode of it by =:
foreach(explode(',', $string) as $p)
{
list($i, $n) = explode('=',$p);
$array[$n][] = $i;
}
Implode then the result with ,:
foreach($array as &$v)
$v = implode(', ', $v);
unset($v);
Done.
A: Just for fun. With no special chars this should also work.
$str="1=icon_arrow.gif,2=icon_arrow.gif,3=icon_arrow.gif,4=x.gif";
$str = str_replace(',', '&', $str);
parse_str($str, $array);
$result = array();
foreach($array as $k=>$v)
$result[$v] = (isset($result[$v]) ? $result[$v] . ", " : "") . $k;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does Sphinx auto update is index when you add data to your SQL? I am curious as to whether or not Sphinx will auto update its index when you add new SQL data or whether you have to tell it specifically to reindex your db.
If it doesn't, does anyone have an example of how to automate this process when the database data changes?
A: The answer is no and you need to tell sphinx to reindex your db.
There are some steps and requirements which you need to know:
*
*Main and delta are requirement
*First run you need to index your main index.
*After the first run, you may index delta by rotating it ( to make sure the service is running and the data on the web is can be used at the time )
*Before you go further step, you need to create a table to mark your "last indexed rows". THe last indexed rows ID could be used for the next indexing delta and merging delta into main.
*You need to merge your delta index to the main index.
as inside the sphinx documents http://sphinxsearch.com/docs/current.html#index-merging
*Restart sphinx service.
TIPS: Create your own program that could execute the index by using C# or other languages. You may try the task schedule of windows also can.
Here is my conf:
source Main
{
type = mysql
sql_host = localhost
sql_user = root
sql_pass = password
sql_db = table1
sql_port = 3306 # optional, default is 3306
sql_query_pre = REPLACE INTO table1.sph_counter SELECT 1, MAX(PageID) FROM table1.pages;
sql_query = \
SELECT pd.`PageID`, pd.Status from table1.pages pd
WHERE pd.PageID>=$start AND pd.PageID<=$end \
GROUP BY pd.`PageID`
sql_attr_uint = Status
sql_query_info = SELECT * FROM table1.`pages` pd WHERE pd.`PageID`=$id
sql_query_range = SELECT MIN(PageID),MAX(PageID)\
FROM tabl1.`pages`
sql_range_step = 1000000
}
source Delta : Main
{
sql_query_pre = SET NAMES utf8
sql_query = \
SELECT PageID, Status from pages \
WHERE PageID>=$start AND PageID<=$end
sql_attr_uint = Status
sql_query_info = SELECT * FROM table1.`pages` pd WHERE pd.`PageID`=$id
sql_query_range = SELECT (SELECT MaxDoc FROM table1.sph_counter WHERE ID = 1) MinDoc,MAX(PageID) FROM table1.`pages`;
sql_range_step = 1000000
}
index Main
{
source = Main
path = C:/sphinx/data/Main
docinfo = extern
charset_type = utf-8
}
index Delta : Main
{
source = Delta
path = C:/sphinx/data/Delta
charset_type = utf-8
}
A: As found in the sphinx documentation part about real-time indexes
Real-time indexes (or RT indexes for brevity) are a new backend that lets you insert, update, or delete documents (rows) on the fly.
So to update an index on the fly you would just need to make a query like
{INSERT | REPLACE} INTO index [(column, ...)]
VALUES (value, ...)
[, (...)]
A: To expand on Anne's answer - if you're using SQL indices, it won't update automatically. You can manage the process of reindexing after every change - but that can be expensive. One way to get around this is have a core index with everything, and then a delta index with the same structure that indexes just the changes (this could be done by a boolean or timestamp column).
That way, you can just reindex the delta index (which is smaller, and thus faster) on a super-regular basis, and then process both core and delta together less regularly (but still, best to do it at least daily).
But otherwise, the new RT indices are worth looking at - you still need to update things yourself, and it's not tied to the database, so it's a different mindset. Also: RT indices don't have all the features that SQL indices do, so you'll need to decide what's more important.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Toggling a boolean with link_to I've read through the relevant Stack questions but still seem to be hitting a routing error with the following code:
Routes.rb
resources :memberships do
put :toggleon
put :toggleoff
end
Memberships_controller.rb
def toggleon
@membership = Membership.find(params[:id])
@membership.update_attributes(:active => true)
if user.id == membership_id
redirect_to root_path
else
redirect_to group
end
end
def toggleoff
@membership = Membership.find(params[:id])
@membership.update_attributes(:active => false)
if user.id == membership_id
redirect_to root_path
else
redirect_to group
end
end
Show.html.erb
<% if this_membership.active %>
<%= link_to 'Pause', this_membership, controller: :memberships, method: :toggleoff, style: 'color:#ccc' %>
<% else %>
<%= link_to 'Start', this_membership, controller: :memberships, method: :toggleon, style: 'color:green' %>
<% end %>
Error text
Started POST "/memberships/13" for 127.0.0.1 at 2011-09-27 23:35:35 +0100
ActionController::RoutingError (No route matches "/memberships/13"):
I can destroy memberships just fine but toggling the membership activity is proving tricky.
Thanks in advance!
Second attempt
<%= link_to("Pause", membership_toggle(@membership), :method => :put, :title => "This toggles it off") %>
<% else %>
<%= link_to("Toggle On", membership_toggle(@membership), :method => :put, :title => "This toggles it on") %>
and
def toggle
@membership = Membership.find(params[:id])
@membership.toggle!(active)
end
and
resources :memberships do
member do
put :toggle
end
end
now gives me this error...
undefined method `membership_toggle' for #<#<Class:0x00000102e69bc0>:0x00000102e66ec0>
A: Links using your routes are going to be:
link_to("Toggle On", membership_toggleon_url(membership), :method => :put, :title => "This toggles it on")
link_to("Toggle Off", membership_toggleoff_url(membership), :method => :put, :title => "This toggles it off")
You need to supply :method => :put to the link_to method given that's what you have the route as in your routes file.
Something like this can be achieved with a single action:
resources :memberships do
member do
put :toggle
end
end
Then you can make use of a single boolean field in your controller by using the Rails toggle method.
This will let you do something like:
@membership.toggle(:on)
A: Try setting the route as being :on => :member.
Also, there's an atomic toggle! method that does what its name implies.
A: Kept having issues with various techniques but eventually found this article:
http://buckybits.blogspot.com/2011/09/simple-ajax-property-toggle-in-rails-30.html
BOOM!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ruby 1.8.7 why .to_yaml converts some Strings to non-readable bytes Parsing some webpages with nokogiri, i've got some issues while cleaning some Strings and saving them with YAML. To reproduce the problem look at this IRB session that reproduces the same problem:
irb(main):001:0> require 'yaml'
=> true
irb(main):002:0> "1,000 €".to_yaml
=> "--- !binary |\nMSwwMDAg4oKs\n\n"
irb(main):003:0> "1,0000 €".to_yaml
=> "--- \"1,0000 \\xE2\\x82\\xAC\"\n"
irb(main):004:0> "1,00 €".to_yaml
=> "--- !binary |\nMSwwMCDigqw=\n\n"
irb(main):005:0> "1 €".to_yaml
=> "--- !binary |\nMSDigqw=\n\n"
irb(main):006:0> "23 €".to_yaml
=> "--- !binary |\nMjMg4oKs\n\n"
irb(main):007:0> "12000 €".to_yaml
=> "--- !binary |\nMTIwMDAg4oKs\n\n"
irb(main):008:0> "1200000 €".to_yaml
=> "--- \"1200000 \\xE2\\x82\\xAC\"\n"
irb(main):009:0> "120000 €".to_yaml
=> "--- \"120000 \\xE2\\x82\\xAC\"\n"
irb(main):010:0> "12000 €".to_yaml
=> "--- !binary |\nMTIwMDAg4oKs\n\n"
To sum up, sometimes .to_yaml outputs are readable while other times the output is unreadable. The most intriguing aspect is that the strings are very similar.
How can I avoid those !binary ... outputs?
A: Whether YAML prefers to dump a string as text or binary is a matter of ratio between ASCII and non ASCII characters.
If you want to avoid !binary as much as possible, you should use the ya2yaml gem. It tries hard to dump strings as ASCII + escaped UTF-8.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Easy way to run procedure in the background I'm running stored procedure from asp.net front-end but it's quite long. What is the easy way on running that thing in the background? I mean if I close the browser, I still want my stored procedure to complete not just die. Also, I would like to perform other actions on the front-end while my procedure is running. Any good solution for that?
A: Both SQL Agent and the Service Broker can do this, though it does take some work on your part.
A: Just launch it in another Thread as so:
'Starts execution of the proc
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim t As New Threading.Thread(AddressOf DoWork)
t.Start()
End Sub
Private Sub DoWork()
Using c As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
c.Open()
Dim command = New SqlCommand("LongTest", c)
command.CommandType=Data.CommandType.StoredProcedure
command.CommandTimeout = 0
command.ExecuteNonQuery()
End Using
End Sub
Here's the sp that I used for my test:
create PROCEDURE dbo.LongTest
AS
BEGIN
WaitFor Delay '00:00:30' --wait for 30 seconds before doing anything
insert into TableImageTest(image)
values(null)
END
A: Use "Asynchronous Processing=true" in your connection string and call the sproc asynchronously as in this link.
http://geekswithblogs.net/frankw/archive/2008/07/05/execute-transact-sql-statement-asynchronously.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to detect crawlers in Asp.net MVC I'm using an action filter that checks what browser version is being used on my site, if it's an older browser I put up a div at the top asking them to upgrade. I don't want web crawlers to get the div message, so I've implemented HttpBrowserCapabilitiesBase.Crawler and it looks like it works for Google, but Bing and the others don't seem to register as crawlers. Strange for a Microsoft product to not notice Bing as a crawler!
Is there some way to add user agents to the crawler property or something?
Thanks!
Edited: I'm using asp.net mvc 3, it looks like I need to user .Browser files(?). Anyone know of a comprehensive set of .Browser files out there for Bing and the rest of the crawlers?
A: You will probably need to update your browscap.ini file as the one shipped with IIS is probably old. You can get a new one at one of the following URLs:
*
*http://browsers.garykeith.com/downloads.asp
*http://owenbrady.net/browsercaps/
browscap.ini usually lives at: c:\windows\system32\inetsrv\browscap.ini
A: We're not using MVC but we do this:
Regex.IsMatch(Request.UserAgent, @"bot|crawler|baiduspider|80legs|ia_archiver|voyager|curl|wget|yahoo! slurp|mediapartners-google", RegexOptions.IgnoreCase);
More options in my answer here:
Detecting honest web crawlers
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Best way to create automated testing in a Java environment I have been tasked with finding the best way to do integrated unit testing. We have a very large Java EE 5 application (desktop). Right now we use a tool called QF-TEST which is pretty cumbersome for large tests and can be difficult to use (easy to break) with any code changes.
We now want to do something that is more standard and gives the developers more control.
I have read a few posts here:
Unit testing in Java EE environment
Automated Testing - kind of cool, although for .Net
Best practice approach for automated testing
easiest Automated testing tool in Java
From the general information I have read JUnit/JUnitEE is probably the best (by best I mean quickest to learn and possibly the JAVA standard).
Is JUnit the way to go for large Java EE applications? What are some other options that others find better (if there are any)?
Thanks!
A: That's a very broad question. It's the topic of many books. Start with JUnit, start reading about test-driven design/development (TDD), and build from there. Ask more specific questions as you come across them. You could start with "Test Infected", a rather old, yet still applicable article on the JUnit site.
A: I think for java I would go with either with junit or testNG frameworks, If you have persistence/data base involved in the application, I would add dbUnit to the mix.
If you have build scripts like maven or ant or gradle, I would also suggest you look into Jenkins and similar tools to automate builds.
I am suggesting maven because it has life cycle events for testing, You can add targets with ant, I have not used gradle but if I was given choice, I would choose gradle
A: JUnit is not the way to go for large Java EE applications, it is a bare minimum.
But since you already have an application writing jUnit tests will not help you, because jUnit is not a testing tool. jUnit is used for TDD and refactoring safety, writing jUnit tests as an afterthought simply does not work.
That said you should learn jUnit4 as soon as possible (it can be done in 60 seconds)
and than learn about TDD (it can be done in 2-3 hours)
and use jUnit for every future code change you make to your application.
As for code you already have, what you need is 'code analyzers'.
That means tools that will check your source code for violated coding standards, code duplication, do code coverage, dependency analysis and complexity monitoring.
(All of these and more exist as eclipse plugins)
You will probably also need some 'java gui testing' framework (to replace QF-TEST)
There are a lot of open source alternatives there, search the web.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How do I use Python's pprint module to pretty print out dictionary key value pairs nested with in a list? I would like to pretty print out each key value pair from dictionaries which are nested in a list. So here is what I am working with:
[{"updated_at":"2011/09/26 22:39:18 +0000","url":"http://diveintopython.net/http_web_services/redirects.html","annotations":[],"user":"name","shared":"yes","tags":"python,handler,opener,urllib2","readlater":"no","created_at":"2011/09/26 22:39:18 +0000","title":"11.7.\xc2\xa0Handling redirects","comments":[],"desc":""},{"updated_at":"2011/09/26 11:09:07 +0000","url":"http://www.polimex.net/sklep/index.php?page=Category&catid=7","annotations":[],"user":"name","shared":"yes","tags":"plastic,snap,buttons,clothing","readlater":"no","created_at":"2011/09/26 11:05:48 +0000","title":"Polimex - Plastic\xc2\xa0accessories","comments":[],"desc":""}]
When I do
from pprint import pprint
data = [{"updated_at":"2011/09/26 22:39:18 +0000","url":"http://diveintopython.net/http_web_services/redirects.html","annotations":[],"user":"name","shared":"yes","tags":"python,handler,opener,urllib2","readlater":"no","created_at":"2011/09/26 22:39:18 +0000","title":"11.7.\xc2\xa0Handling redirects","comments":[],"desc":""},{"updated_at":"2011/09/26 11:09:07 +0000","url":"http://www.polimex.net/sklep/index.php?page=Category&catid=7","annotations":[],"user":"name","shared":"yes","tags":"plastic,snap,buttons,clothing","readlater":"no","created_at":"2011/09/26 11:05:48 +0000","title":"Polimex - Plastic\xc2\xa0accessories","comments":[],"desc":""}]
pprint(data)
the result I get is the same as the original list but in a string
'[{"updated_at":"2011/09/26 22:39:18 +0000","url":"http://diveintopython.net/http_web_services/redirects.html","annotations":[],"user":"name","shared":"yes","tags":"python,handler,opener,urllib2","readlater":"no","created_at":"2011/09/26 22:39:18 +0000","title":"11.7.\xc2\xa0Handling redirects","comments":[],"desc":""},{"updated_at":"2011/09/26 11:09:07 +0000","url":"http://www.polimex.net/sklep/index.php?page=Category&catid=7","annotations":[],"user":"name","shared":"yes","tags":"plastic,snap,buttons,clothing","readlater":"no","created_at":"2011/09/26 11:05:48 +0000","title":"Polimex - Plastic\xc2\xa0accessories","comments":[],"desc":""}]'
How do I make it pretty print the data to look something like this?
[
{
"updated_at":"2011/09/26 22:39:18 +0000",
"url":"http://diveintopython.net/http_web_services/redirects.html",
"annotations":[],
"user":"name",
"shared":"yes",
"tags":"python,handler,opener,urllib2",
"readlater":"no",
"created_at":"2011/09/26 22:39:18 +0000",
"title":"11.7.\xc2\xa0Handling redirects",
"comments":[],
"desc":""
},
{
"updated_at":"2011/09/26 11:09:07 +0000",
"url":"http://www.polimex.net/sklep/index.php?page=Category&catid=7",
"annotations":[],
"user":"name",
"shared":"yes",
"tags":"plastic,snap,buttons,clothing",
"readlater":"no",
"created_at":"2011/09/26 11:05:48 +0000",
"title":"Polimex - Plastic\xc2\xa0accessories",
"comments":[],"desc":""
}
]
A: One possibility comes to mind. Are you supplying a JSON string to pprint? If so, you should first decode it:
pprint(json.loads(data))
A: It um... works right for me. (I cut and pasted your example!) What Python and OS are you using? And are you sure you didn't accidentally add some additional quotes somewhere?
Are you printing to the terminal?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Install node.js on jailed shell I am trying to install node.js on jailed shell of shared web-server. I have managed to install git, and get a copy of node.js. I was compiling like this...
./configure --prefix=~/opt
(I have an ~/opt/bin directory which allows git to execute - so thought it was a good place to put it)
But got errors like this...
/home/sparrow/bin/git/node-v0.4.12/deps/v8/src/platform-linux.cc: In function `void* v8::internal::ThreadEntry(void*)':
/home/sparrow/bin/git/node-v0.4.12/deps/v8/src/platform-linux.cc:587: error: `PR_SET_NAME' was not declared in this scope
/home/sparrow/bin/git/node-v0.4.12/deps/v8/src/platform-linux.cc:587: warning: unused variable 'PR_SET_NAME'
scons: *** [obj/release/platform-linux.o] Error 1
scons: building terminated because of errors.
Waf: Leaving directory `/home/sparrow/bin/git/node-v0.4.12/build'
Build failed: -> task failed (err #2):
{task: libv8.a SConstruct -> libv8.a}
make: *** [program] Error 1
Does anyone know what this error means - and how I can fix my installation?
EDIT: More details...
I had another go, but using ./configure --prefix=~/usr/local/ with similar error - here is the output...
-jailshell-3.00$ ./configure --prefix=~/local
Checking for program g++ or c++ : /usr/bin/g++
Checking for program cpp : /usr/bin/cpp
Checking for program ar : /usr/bin/ar
Checking for program ranlib : /usr/bin/ranlib
Checking for g++ : ok
Checking for program gcc or cc : /usr/bin/gcc
Checking for gcc : ok
Checking for library dl : yes
Checking for openssl : yes
Checking for library util : yes
Checking for library rt : yes
--- libeio ---
Checking for library pthread : yes
Checking for function pthread_create : yes
Checking for function pthread_atfork : yes
Checking for futimes(2) : yes
Checking for readahead(2) : yes
Checking for fdatasync(2) : yes
Checking for pread(2) and pwrite(2) : no
Checking for sendfile(2) : yes
Checking for sync_file_range(2) : no
--- libev ---
Checking for header sys/inotify.h : not found
Checking for header sys/epoll.h : yes
Checking for function epoll_ctl : yes
Checking for header port.h : not found
Checking for header poll.h : yes
Checking for function poll : yes
Checking for header ['sys/types.h', 'sys/event.h'] : not found
Checking for header sys/queue.h : yes
Checking for function kqueue : not found
Checking for header sys/select.h : yes
Checking for function select : yes
Checking for header sys/eventfd.h : not found
Checking for SYS_clock_gettime : yes
Checking for library rt : yes
Checking for function clock_gettime : yes
Checking for function nanosleep : yes
Checking for function ceil : yes
Checking for fdatasync(2) with c++ : yes
'configure' finished successfully (5.075s)
-jailshell-3.00$ make && make install
Waf: Entering directory `/home/sparrow/bin/git/node-v0.4.12/build'
DEST_OS: linux
DEST_CPU: x64
Parallel Jobs: 1
Product type: program
[49/75] copy: src/node_config.h.in -> build/default/src/node_config.h
[50/75] copy: tools/nodejs.pc.in -> build/default/tools/nodejs.pc
[51/75] libv8.a: deps/v8/SConstruct -> build/default/libv8.a
/usr/local/bin/python "/home/sparrow/bin/git/node-v0.4.12/tools/scons/scons.py" -j 1 -C "/home/sparrow/bin/git/node-v0.4.12/build/default/" -Y "/home/sparrow/bin/git/node-v0.4.12/deps/v8" visibility=default mode=release arch=x64 toolchain=gcc library=static snapshot=on
scons: Reading SConscript files ...
scons: warning: Ignoring missing SConscript 'obj/test/release/SConscript'
File "/home/sparrow/bin/git/node-v0.4.12/deps/v8/SConstruct", line 1201, in BuildSpecific
scons: done reading SConscript files.
scons: Building targets ...
g++ -o obj/release/platform-linux.o -c -Wall -W -Wno-unused-parameter -Wnon-virtual-dtor -pedantic -m64 -O3 -fomit-frame-pointer -fdata-sections -ffunction-sections -ansi -fno-rtti -fno-exceptions -Wall -W -Wno-unused-parameter -Wnon-virtual-dtor -pedantic -m64 -O3 -fomit-frame-pointer -fdata-sections -ffunction-sections -ansi -DV8_TARGET_ARCH_X64 -DENABLE_VMSTATE_TRACKING -DENABLE_LOGGING_AND_PROFILING -DENABLE_DEBUGGER_SUPPORT -I/home/sparrow/bin/git/node-v0.4.12/deps/v8/src /home/sparrow/bin/git/node-v0.4.12/deps/v8/src/platform-linux.cc
/home/sparrow/bin/git/node-v0.4.12/deps/v8/src/platform-linux.cc: In function `void* v8::internal::ThreadEntry(void*)':
/home/sparrow/bin/git/node-v0.4.12/deps/v8/src/platform-linux.cc:587: error: `PR_SET_NAME' was not declared in this scope
/home/sparrow/bin/git/node-v0.4.12/deps/v8/src/platform-linux.cc:587: warning: unused variable 'PR_SET_NAME'
scons: *** [obj/release/platform-linux.o] Error 1
scons: building terminated because of errors.
Waf: Leaving directory `/home/sparrow/bin/git/node-v0.4.12/build'
Build failed: -> task failed (err #2):
{task: libv8.a SConstruct -> libv8.a}
make: *** [program] Error 1
-jailshell-3.00$
A: Node.js requires root access which shared servers do not usually provide. Contact your host to check if node commands will work. And by the way, switching from jailshell to normal shell is a prerequisite of node.
You can still follow these steps:
Log in to your account using SSH (if is not enabled for your account contact our support).
At the command prompt, type next commands:
cd ~
wget https://nodejs.org/dist/v6.9.1/node-v6.9.1-linux-x64.tar.xz
Command above will download v6.9.1 version, in case you need diffrent version you can find latest here: https://nodejs.org/en/download/
To extract the Node.js files, type the following command:
tar xvf node-v6.9.1-linux-x64.tar.xz
Now we will rename folder to nodejs name, to do this type the following command:
mv node-v6.9.1-linux-x64 nodejs
Now install node and npm binaries, type the next commands:
mkdir ~/bin
cp nodejs/bin/node ~/bin
cd ~/bin
ln -s ../nodejs/lib/node_modules/npm/bin/npm-cli.js npm
That is all, Node.js and npm are installed on your account. To verify, type the following commands:
node --version
npm --version
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: counting number of words after last occurrence of every word in an array of strings i am working on text. I want to find the number of words after the last occurrence of a particular word in an array of strings.For instance,
String[] array={cat,rat,cat,bat,cat,cat,bat,fat,mat}
and I want to find the last occurrence of every word in this array and the number of words after the last occurrence .
How can I do it???
A: Iterate and count the array backwards and every new word that you encounter this way is the last or only instance of this word in the array. You can i.e. put the words in a hash set to check whether you have seen them already. Whenever you detect a new word this way you get the number of words behind it from the counter or by calculating array.length - currentPosition.
A: There is a solution with RegEx in DotNet if you will work with strings.
To search in an array here is an short example:
using System;
class Program
{
static void Main()
{
//
// Use this array of string references.
//
string[] array1 = { "cat", "dog", "carrot", "bird" };
//
// Find first element starting with substring.
//
string value1 = Array.Find(array1,
element => element.StartsWith("car", StringComparison.Ordinal));
//
// Find first element of three characters length.
//
string value2 = Array.Find(array1,
element => element.Length == 3);
//
// Find all elements not greater than four letters long.
//
string[] array2 = Array.FindAll(array1,
element => element.Length <= 4);
Console.WriteLine(value1);
Console.WriteLine(value2);
Console.WriteLine(string.Join(",", array2));
}
}
Also you can take a look to MSDN Example
Hope that helps
Regards
A: In Ruby:
arr = [:cat,:rat,:cat,:bat,:cat,:cat,:bat,:fat,:mat]
hash = {}
arr.reverse.each_with_index {|item, index| hash[item]=index unless hash.has_key?(item)}
hash
=> {:mat=>0, :fat=>1, :bat=>2, :cat=>3, :rat=>7}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Negative weight graph edges? We all have seen graphs with edge weight where the weight may represent anything from
lengths, costs, etc ..., but what does a negative weight edge stand for ?
e.g lengths my apply to road lengths in real world, is there a similar analogy for negative weight ?
Thanx
A: Imagine that your graph is tracking the molecules that are consumed and produced in a chemical reaction and the edge weights represent the energy produced in the transition. A negative edge weight would be a transition that needs energy to be achieved (for example splitting water into hydrogen and oxygen).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Improving Mergesort. Improvement 3). Use one less copy between input and temp arrays I am currently working on a project for my algorithms class and am at a bit of a standstill. We were assigned to do improvements to merge sort, that was in the book, by implementing specific changes. I have worked fine through the first 2 changes but the 3'rd one is killer.
Merge sort, the one we are improving, copies the contents of the input array into the temporary array, and then copies the temporary array back into the input array. So it recursively sorts the input array, placing the two sorted halves into the temporary array. And then it merges the two halves in the temporary array together, placing the sorted sequence into the input array as it goes.
The improvement is that this double copying is wasteful can be done without. His hint is that: We can make it so that each call to Merge only copies in one direction, but the calls to Merge alternate the direction.
This is supposedly done by blurring the lines between the original and temporary array.
I am not really looking for code as I am confident that I can code this. I just have no idea what i'm supposed to be doing. The professor is gone for the day so I can't ask him until next week when I have his course again.
Has anyone done something like this before? Or can decipher and put it into laymans terms for me :P
The first improvement, simply has it use insertion sort whenever an Array gets small enough that it will benefit greatly, timewise, from doing so.
The second improvement stops allocating two dynamic arrays (the 2 halves that are sorted) and instead allocates 1 array of size n and that is what is used instead of the two dynamic arrays. That's that last one I did. The code for that is :
//#include "InsertionSort.h"
#define INSERTION_CUTOFF 250
#include <limits.h> // needed for INT_MAX (the sentinel)
void merge3(int* inputArray, int p, int q, int r, int* tempArray)
{
int i,j,k;
for (i = p; i <= r; i++)
{
tempArray[i] = inputArray[i];
}
i = p;
j = q+1;
k = p;
while (i <= q && j <= r)
{
if (tempArray[i] <= tempArray[j])
{
inputArray[k++] = tempArray[i++];
}
else
{
inputArray[k++] = tempArray[j++];
}
}
}//merge3()
void mergeSort3Helper(int* inputArray, int p, int r, int* tempArray)
{
if (r - p < INSERTION_CUTOFF)
{
insertionSort(inputArray,p,r);
return;
}
int q = (p+r-1)/2;
mergeSort3Helper(inputArray,p,q,tempArray);
mergeSort3Helper(inputArray,q+1,r,tempArray);
merge3(inputArray,p,q,r,tempArray);
}//mergeSort3Helper()
void mergeSort3(int* inputArray, int p, int r)
{
if (r-p < 1)
{
return;
}
if (r - p < INSERTION_CUTOFF)
{
insertionSort(inputArray,p,r);
return;
}
int* tempArray = malloc((r-p)+1*sizeof(int));
tempArray[r+1] = INT_MAX;
mergeSort3Helper(inputArray,p,r,tempArray);
// This version of merge sort should allocate all the extra space
// needed for merging just once, at the very beginning, instead of
// within each call to merge3().
}//mergeSort3()
A: The algorithm is like this:
A1: 7 0 2 9 5 1 4 3
A2: (uninitialized)
Step 1:
A1 : unchanged
A2: 0 7 2 9 1 5 3 4
Step 2:
A1: 0 2 7 9 1 3 4 5
A2: unchanged
Step 3:
A1: unchanged
A2: 0 1 2 3 4 5 7 9
This involves you copying only one way each time and follows the steps of mergesort. As your professor said, you blur the lines between the work array and the sorted array by alternating which is which, and only copying once things are sorted.
A: I suspect it would be difficult and ultimately unprofitable to avoid all copying. What you want to do instead is to avoid the copy you currently do with each merge.
Your current merge3(inputArray, p,q,r, tempArray) returns the merged result in its original array, which requires a copy; it uses its tempArray buffer only as a resource. In order to do better, you need to modify it to something like merge4(inputArray, p,q,r, outputArray), where the result is returned in the second buffer, not the first.
You will need to change the logic in mergeSort3Helper() to deal with this. One approach requires a comparable interface change, to mergeSort4Helper(inputArray, p,q,r, outputArray), such that it also yields its result in its second buffer. This will require a copy at the lowest (insertion sort) level, and a second copy in the top-level mergeSort4() if you want your final result in the same buffer it came in. However, it eliminates all other unnecessary copies.
Alternately, you could add a boolean parameter to mergeSort4Helper() to indicate whether you want the result returned in the first or second buffer. This value would alternate recursively, resulting in at most one copy, at the lowest level.
A final option might be to do the merging non-recursively, and alternate buffers at each pass. This would also result in at most one copy; however, I would expect the resulting access pattern to be inherently less cache-friendly than the recursive one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: favorites button in the tableviewcells I implemented the following method in my tableviewcontroller for showing favorites with empty star and filled star:
-(IBAction) tapped:(UIButton *)sender
{
if([sender isSelected])
{
//...
[sender setImage:[UIImage imageNamed:@"fav-empty.png"] forState:UIControlStateNormal];
[sender setSelected:NO];
}
else
{
//...
[sender setImage:[UIImage imageNamed:@"fav-filled.png"] forState:UIControlStateNormal];
[sender setSelected:YES];
NSLog(@"%@",sender);
}
}
and I tried to use in this part:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UILabel *recept_neve=[[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 40)];
[recept_neve setTag:1];
UIButton *kedvenc_btn=[UIButton buttonWithType:UIButtonTypeCustom];
[kedvenc_btn setImage:[UIImage imageNamed:@"fav-empty.png"] forState:UIControlStateNormal];//default appereance on the startup
kedvenc_btn.frame=CGRectMake(200, 20, 50, 50);
[kedvenc_btn setTag:2];
[kedvenc_btn addTarget:self action:@selector(tapped:) forControlEvents:UIControlEventTouchUpInside];
[[cell contentView] addSubview:recept_neve];
[[cell contentView] addSubview:kedvenc_btn];
//[(UILabel*) [[cell contentView] viewWithTag:1] setText:[receptek objectAtIndex:indexPath.section*blokk+1]];
//[(UIButton *) [cell contentView] viewWithTag:2];
}
// Configure the cell...
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
[(UILabel*) [[cell contentView] viewWithTag:1] setText:[receptek objectAtIndex:indexPath.section*blokk+1]];
return cell;
}
My problem is that every fifth button in the cells are working as would be the same.
If I tap on the button(empty star) in the first cell, the result will be the following: the first button becoming filled-star, so far so good(the expected behaviour), but in the same time the sixth star becoming filled too. Or if I tap on the second one, the seventh star getting filled and vica versa...
I logged the buttons where I tapping , and I realised, that the memory adresses are equals in the case of buttons above mentioned.
Sorry about my english, and thanks a lot for every help in advance!
A: the problem was that you reused the buttons all the time.
I show you a sample working code to structure a customized UITableViewCell correctly...
Let's do it step by step.
Create a new class called MyObjTableViewCellForSelection and provide these methods. Adapt it to your needs!
@class MyObj;
@interface MyObjTableViewCellForSelection : UITableViewCell
{
MyObj *myObj;
UIImageView *imageView;
UILabel *titleLabel;
}
@property (nonatomic,strong) MyObj *myObj;
@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic,strong) UILabel *titleLabel;
@end
Then the implementation:
@implementation MyObjTableViewCellForSelection
@synthesize myObj;
@synthesize imageView;
@synthesize titleLabel;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
imageView = [[UIImageView alloc] initWithFrame: CGRectZero];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[self.contentView addSubview: imageView];
titleLabel = [[UILabel alloc] initWithFrame: CGRectZero];
[titleLabel setFont:[UIFont systemFontOfSize:14.0]];
[titleLabel setTextColor:[UIColor blackColor]];
[titleLabel setHighlightedTextColor:[UIColor darkGrayColor]];
[titleLabel setLineBreakMode: UILineBreakModeWordWrap];
titleLabel.numberOfLines = 2;
[self.contentView addSubview: titleLabel];
}
return self;
}
-(void) layoutSubviews {
[super layoutSubviews];
[imageView setFrame:CGRectMake(8.0, 10.0, 20.0, 20.0)];
[titleLabel setFrame:CGRectMake(40.0, 1.0, 250.0, 40.0)]; //two lines
}
- (void)setMyObj:(MyObj *)myObjX {
if (myObjX != myObj) {
[myObj release];
[myObjX retain];
//myObj = myObjX; //only with ARC on
}
titleLabel.text = whatever you need accessing myObj
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
// selection has to be adapted to your structure
[super setSelected:selected animated:animated];
switch (myObj.selectedFlag) {
case MYOBJ_STATUS_UNSELECTED:
imageView.image = [UIImage imageNamed:@"EmptyBullet.png"];
break;
case MYOBJ_STATUS_SELECTED:
imageView.image = [UIImage imageNamed:@"GreyBullet.png"];
break;
default:
break;
}
@end
now in your view class you can finally do:
- (MyObj *)myObjForIndexPath:(NSIndexPath *)indexPath {
MyObj* tmpObj = get the corresponding object
return tmpObj;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyObjTableViewCellForSelection *cell = (MyObjTableViewCellForSelection *)[tableView dequeueReusableCellWithIdentifier:@"cellID"];
if (cell == Nil) {
cell = [[ECUTableViewCellForSelection alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellID"];
}
cell.myObj = [self myObjForIndexPath:indexPath]; //the assignment calls setMyObj of CLASS ECUTableViewCellForSelection that you just declared
return cell;
}
So finally that's the clean way of doing it...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: In a class is a variable not accessable from other thread I have an byte array declared in the header of the class. When I want to access it in the audio event Methode of the microphone the array is NOTHING and not available in this class on this point.
Any idea how to declare the array to get access in the other thread?
Regards
Private Class Test1234
Private BufferData(1023) As Byte
Private Sub microphone_BufferReady(sender As Object, e As System.EventArgs) Handles microphone.BufferReady
' Retrieve audio data
microphone.GetData(Me.BufferData)'<-- Is NOTHING
End Sub
End Class
I am asking why Me.BufferData is nothing when I am in the microphone Event. Because it is pre-set on initilizing routine with a size of 1024 Bytes
A: Your BufferData is never initialized, just declared
BufferData As New Byte(1023)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7576524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.