text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: How to hide a text after 5 sec using jQuery? How can I hide the #results after 5 secs ? I tried this but it does not work.
$('#results').hide().html(data).fadeIn('slow').delay(5000).hide();
What I had is this one
$('#results').hide().html(data).fadeIn('slow');
A: Do you mean something like:
$('#results').hide().html(data).fadeIn('slow');
setTimeout(function() {
$('#results').hide();
}, 5000);
A: Put a duration on your hide() call and it will work like this:
$('#results').hide().html(data).fadeIn('slow').delay(5000).hide(1);
The issue is that hide() without any parameters is just an immediate operation. It doesn't go through the fx queue so therefore, it doesn't come after the .delay(5000). But, if you give a duration to the function like .hide(1), then it becomes an animation and it goes through the fx queue and thus will come after the .delay(5000).
You can see it work here: http://jsfiddle.net/jfriend00/wzbtU/
From the jQuery doc for hide():
When a duration is provided, .hide() becomes an animation method.
A: You'd have to use setTimeout.
setTimeout("$('#results').hide().html(data).fadeIn('slow');", 5000);
The reason why .delay(5000) doesn't work is because .hide() isn't included in the animation queue.
A: The jQuery's fadeOut method is nifty:
$('#results').delay(3000).fadeOut('slow');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Can hunchentoot host CGI application? We have a CGI application developed using python, which can be hosted in erlang YAWS easily:
>cat ~/yaws.conf
...
<server 192.168.1.2>
port = 8000
listen = 0.0.0.0
docroot = /media/G/www/qachina/
access_log = false
appmods = <cgi-bin, yaws_appmod_cgi>
</server>
...
Now we want to host the application in a lisp web server. Maybe hunchentoot can do it ?
Sincerely!
A: Probably something to do with EOL characters.
From Chunga API docs, you can see the read-line* function expects a CR as EOL marker, which is not the default for *nixes. The following should make it work (it works for me):
(setf chunga:*accept-bogus-eols* t)
EDIT: further reading the description of *accept-bogus-eols* I can see why this is the normal behavior of Chunga: the library itself conforms to RFC2616 (HTTP 1.1) in which the HTTP protocol's default EOL marker is CRLF.
A: I have installed hunchentoot-cgi and tested it. The following is a simple python script file:
>cat cgi-bin/nav.py
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
print "Content-type: text/html\n\n"
print """from Python"""
when i visited http://127.0.0.1:8000/cgi-bin/nav.py, hunchentoot reported:
11111111111111111
**End of file, but expected #\Newline.**
[2011-12-28 13:35:16 [ERROR]] error in handle-cgi-script from URL /cgi-bin/nav.py
127.0.0.1 - [2011-12-28 13:35:16] "GET /cgi-bin/nav.py HTTP/1.1" 200 - "-"
"Opera/9.80 (X11; FreeBSD 8.2-RELEASE i386; U; zh-cn) Presto/2.10.229 Version/11.60"
By hackiing hunchentoot-cgi.lisp, i found the function "handle-cgi-script" reported the error:
(handler-case
(with-input-from-program (in path nil env)
(format t "11111111111111111~%")
(chunga:with-character-stream-semantics
(loop for line = (chunga:read-line* in)
until (equal line "")
do
(format t "22222222222222222:~A~%" line)
(destructuring-bind (key val)
(ppcre:split ": " line :limit 2)
(setf (hunchentoot:header-out key) val))
(format t "22222222222222222~%")))
(format t "33333333333333333~%")
(let ((out (flexi-streams:make-flexi-stream
(tbnl:send-headers)
:external-format tbnl::+latin-1+)))
(copy-stream in out 'character))
(format t "33333333333333333~%"))
(error (error)
(format t "~A~%" error)
(tbnl:log-message* :error "error in handle-cgi-script from URL ~A"
(tbnl:request-uri*))))
Any suggestion is appreciated!
A: Strange behavior about "merge-pathnames":
* (merge-pathnames "nav.py" "/media/E/myapp/cgi-bin/")
#P"/media/E/myapp/cgi-bin/nav.py"
it works normally in SBCL REPL. However, when hacking "create-cgi-dispatcher-and-handler", i add the following lines:
(defun create-cgi-dispatcher-and-handler (uri-prefix base-path &optional content-type)
;...
(format t "SName=~A SPath=~A BPath=~A~% the path is ~A~%" script-name script-path base-path (merge-pathnames script-path base-path))
;...
Calling it as below:
(pushnew (hunchentoot-cgi::create-cgi-dispatcher-and-handler
"/cgi-bin/"
(make-pathname :name "cgi-bin/" :type nil :version nil :defaults *this-file*)
) *dispatch-table* :test #'equal)
Then visiting http://127.0.0.1:8000/cgi-bin/nav.py, it reports:
SName=/cgi-bin/nav.py SPath=nav.py BPath=/media/E/myapp/cgi-bin/
the path is /media/E/myapp/nav.py
In a short word:
(merge-pathnames "nav.py" "/media/E/myapp/cgi-bin/") returns #P"/media/E/myapp/cgi-bin/nav.py" in REPL. But it returns "/media/E/myapp/nav.py" in hunchentoot-cgi.lisp.
Sincerely!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: forcing a definite size on a select multiple element When a select multiple element is empty (without any options), the dimensions of the element become zero and shows only the scroll bar , also the element resizes according to the size of the data of the options . How can i create a select multiple element with a definite size which does not change irrespective of the above two factors?
Thanks in advance
A: Use CSS:
select.multiple {
width: 200px;
height: 400px;
}
The above assumes your select has class="multiple", but obviously you can set your CSS selector to ID or whatever suits, and of course you'll set the dimensions and units to suit your specific case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: build rules for xcode / iPhone Im incorporating the facebook SDK into an update and i get compiler warnings for four files,in one of my targets each file gets two warnings like these.
[WARN]warning: no rule to process file '$(PROJECT_DIR)/APP_NAME/Facebook.h' of type sourcecode.c.h for architecture armv7
[WARN]warning: no rule to process file '$(PROJECT_DIR)/APP_NAME/Facebook.h' of type sourcecode.c.h for architecture armv6
and in the other target each file only generates one warning,
[WARN]warning: no rule to process file '$(PROJECT_DIR)/APP_NAME/FBConnect.h' of type sourcecode.c.h for architecture i386
in the documentation for the facebook SDK they tell me to add i386 to the valid architectures in the build settings, but they dont say anything about any 'build rules' the strange thing is that I already incorporated the same facebook SDK into another app without a single problem. The only difference that I can see is that this project already had two targets, and (each of) these warnings are only coming from one of them. Can anybody give me a clue how to make a build rule for these four files? do I need build rules for armv6 and armv7 AND i386?
the build settings are exactly the same except for a different -info.plist and different .pch file each. I should add that the facebook functionality is working fine on the simulator but not in any test device using either of the build targets.
thanks so much.
A: http://dhilipsiva.blogspot.in/2012/10/xcode-warning-no-rule-to-process-file.html
The list should only have .m files. I don't know if we can put a .c file in it, but there should not be any other filetype. I fond that some developers even dragged Javascript files into the compiled sources. If you are facing the same problem, you should probably remove any non '.m' files from list of compiled sources. Here is how you do it, assuming you are running on Xcode4.
Open up your project target's "Build Phases" tab. (Click on the project, then the target's name, and then on the "Build Phases" tab).
In the the compiled sources section, make sure that you dont have any files other than .m files.
Happy Hacking.
A: Assuming you're using Xcode 4, it's likely that the dependency checker is confused because there are .h files in list of C files to be compiled.
So.... Navigate to your target's "Build Phases" tab. (Click on the project, then click on the target's name, then click on the "Build Phases" tab.)
Ensure that you didn't drag any .h files into the "Compile Sources" section.
It's common, when importing code, to just drag the whole lot into that section, not realizing that .h files aren't technically compiled, and the dependency checker isn't smart enough to spit out more helpful error message.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
}
|
Q: Is there a good way of switching between different debugging environments on windows mobile emulator I've got a .NET CF (C#) mobile application that I run on a windows emulator. This application uses a sqlce database, and also is controlled by a number of config-like files. I frequently need to change back and forth between different debugging environments - i.e. I need different versions of the database as well as the config files - b/c the application is being used differently in each of the environments.
My initial thought was to use different emulators for different environments, but this doesn't seem very convenient. I could use the standard emulator for one environment and the professional environment in another, but sooner or later, I'll run out of emulator types. My VS solution (2008, btw) has something like 30 projects - so, I'd have to change the emulator type for each of the projects, which doesn't really help.
Another idea I had was to write a simple winforms or console app which could switch-out the environments for me (on the same emulator). That is, the app could copy the db and config files from some archive location on my machine, and when I switch to a new environment, it could copy the db from the emulator so that I'd always have the latest state archived. The problem I ran into with this is that there doesn't seem to be a way to access the file system of the activesync-connected emulator in code. Sure, I can see everything in Windows Explorer, but it doesn't seem available from code b/c the emulator doesn't have a drive letter.
Has anyone else been in a similar situation, and how have you dealt with it? I'd really like to get the second approach working (b/c then I could keep archives of my test data), but really anything that means I no longer have to manually copy these dbs + config files back and forth (in Windows Explorer) would help. Thanks.
A: You should be able to save multiple copies of the emulator. The procedure below is how we do it. You could also use the same emulator instance with a local folder mounted on \Storage Card, and just swap out different files before staring your debugging. I'd go with the first option as there's less chance of screwing up, and less work in the long run.
*
*In Visual Studio, select Tools > Options…, select Device Tools–Devices from the tree.
*Select the emulator of choice from the Show devices for platform: drop down; select for example Pocket PC 2003 SE Emulator from the list and click the Save As… button.
*Enter in the Save As dialog and click OK button.
*Select from the Devices: list, and click the Properties… button.
*In the Properties dialog, click the Emulator Options… button.
*In the General tab, check Specify RAM size:, Shared folder: enter C:\Storage Card. IMPORTANT! Be sure to create a C:\Storage Card folder on your drive before launching the emulator. (optional) In the Display tab, check Skin radio and enter path to you skin Click OK button.
*To target the emulator for your project, select from the Target Device dropdown in the Device toolbar.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I select an entire row which has the largest ID in the table? How would I do something like this?
SQL SELECT row FROM table WHERE id=max(id)
A: SELECT *
FROM table
WHERE id = (SELECT MAX(id) FROM TABLE)
A: You could use a subselect:
SELECT row
FROM table
WHERE id=(
SELECT max(id) FROM table
)
Note that if the value of max(id) is not unique, multiple rows are returned.
If you only want one such row, use @MichaelMior's answer,
SELECT row from table ORDER BY id DESC LIMIT 1
A: One can always go for analytical functions as well which will give you more control
select tmp.row from ( select row, rank() over(partition by id order by id desc ) as rnk from table) tmp where tmp.rnk=1
If you face issue with rank() function depending on the type of data then one can choose from row_number() or dense_rank() too.
A: You can not give order by because order by does a "full scan" on a table.
The following query is better:
SELECT * FROM table WHERE id = (SELECT MAX(id) FROM table);
A: You could also do
SELECT row FROM table ORDER BY id DESC LIMIT 1;
This will sort rows by their ID in descending order and return the first row. This is the same as returning the row with the maximum ID. This of course assumes that id is unique among all rows. Otherwise there could be multiple rows with the maximum value for id and you'll only get one.
A: Try with this
SELECT top 1 id, Col2, row_number() over (order by id desc) FROM Table
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604893",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "163"
}
|
Q: Sorting gigantic binary files with C# I have a large file of roughly 400 GB of size. Generated daily by an external closed system. It is a binary file with the following format:
byte[8]byte[4]byte[n]
Where n is equal to the int32 value of byte[4].
This file has no delimiters and to read the whole file you would just repeat until EOF. With each "item" represented as byte[8]byte[4]byte[n].
The file looks like
byte[8]byte[4]byte[n]byte[8]byte[4]byte[n]...EOF
byte[8] is a 64-bit number representing a period of time represented by .NET Ticks. I need to sort this file but can't seem to figure out the quickest way to do so.
Presently, I load the Ticks into a struct and the byte[n] start and end positions and read to the end of the file. After this, I sort the List in memory by the Ticks property and then open a BinaryReader and seek to each position in Ticks order, read the byte[n] value, and write to an external file.
At the end of the process I end up with a sorted binary file, but it takes FOREVER. I am using C# .NET and a pretty beefy server, but disk IO seems to be an issue.
Server Specs:
*
*2x 2.6 GHz Intel Xeon (Hex-Core with HT) (24-threads)
*32GB RAM
*500GB RAID 1+0
*2TB RAID 5
I've looked all over the internet and can only find examples where a huge file is 1GB (makes me chuckle).
Does anyone have any advice?
A: At great way to speed up this kind of file access is to memory-map the entire file into address space and let the OS take care of reading whatever bits from the file it needs to. So do the same thing as you're doing right now, except read from memory instead of using a BinaryReader/seek/read.
You've got lots of main memory, so this should provide pretty good performance (as long as you're using a 64-bit OS).
A: Use merge sort.
It's online and parallelizes well.
http://en.wikipedia.org/wiki/Merge_sort
A: If you can learn Erlang or Go, they could be very powerful and scale extremely well, as you have 24 threads. Utilize Async I/O. Merge Sort.
And since you have 32GB of Ram, try to load as much as you can into RAM and sort it there then write back to disk.
A: I would do this in several passes. On the first pass, I would create a list of ticks, then distribute them evenly into many (hundreds?) buckets. If you know ahead of time that the ticks are evenly distributed, you can skip this initial pass. On a second pass, I would split the records into these few hundred separate files of about same size (these much smaller files represent groups of ticks in the order that you want). Then I would sort each file separately in memory. Then concatenate the files.
It is somewhat similar to the hashsort (I think).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: zend, how to use jquery ajax to submit a form? i have a Zend Form and i would like to use jquery to do some ajax posting.
if ($this->getRequest()->isPost()) {
$data = $form->getValues();
$image_id = $this->usermedia->crop_image($userObj->user_id, $data);
}
the crop_image saves the data:
$new_image_id = $this->getDbTable()->createRow($new_row_data)->save();
return $new_image_id;
if the form is posted then run a function and give me back an $new_image_id.
all this happens in a modal window that loads a iframe with the form.
what i want is when i submit the form to grab that $new_image_id from inside the iframe, close the modal window and place it on my original page
any ideas on how this can be done?
thanks
edit:
A: Just render that variable into a javascript variable:
var newImageId = "<?php echo $new_image_id ?>";
Then you can use:
http://api.jquery.com/load/
jQuery's wonderful .load() method to send that id to an external PHP page that then pulls it from the database and renders it to HTML. .load() will pull that all back in to your current page. You can then define a callback from .load() which gets rid of the modal.
Edit:
If your code is such that rendering the variable to a javascript variable is not practical, you can render it to the DOM itself, say as an element attribute... then get it using .content()
jQuery/JavaScript: accessing contents of an iframe
Bear in mind same origin policy:
http://en.wikipedia.org/wiki/Same_origin_policy
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Client and Server fail to communicate I have a client/server program in c. While the server runs, I can send it command via telnet and it works fine. In addition, nmap reports the port to be open. Similarly, I can successfully use (connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) if my IP is the address of google. However, If I try and use 127.0.0.1 to connect I get a -1 response from connect(). I'm using ports in the 13000 range.
Is there a reason why telnet would be able to communicate with my server but my client program could not?
A: You either have a local firewall that is preventing your client program from connecting (you may need to whitelist the client program if this is on Windows) or you're filling in the IP address you pass to connect incorrectly. Depending on the OS you're using you should either check errno or GetLastError() to see what went wrong.
A: You'd better get details about the problem with strerror(errno) if under linux, many reasons may lead to the disconnection.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Where to put jQuery code for DOM manipulation in Codeigniter I have some jQuery code that deals with DOM manipulation, simple stuff like fadeIn(), etc...
Is the best practice to put
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
and any script associated with manipulating the HTML on a CI view right on the view.php file?
Thanks
A: That's eminently reasonable. If you're using jQuery you should probably wrap your manipulation code in a ready call.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Associative Container as Function Template Parameter I would like to know how I would write a function that can accept as a parameter an associative container that itself accepts two or more template parameters. For example, if I want to write a function that works for std::map, I could write something like what is shown below.
template <class Map, class Key, class Value, class Compare, class Allocator>
void foo(Map<Key, Value, Compare, Allocator>& map);
However, this will not work for boost::unordered_map, since boost::unordered_map accepts five template parameters. I could accept the map as a single template parameter and use the traits that it should support in order to deduce the key and value types later, but for nested maps, the code becomes very verbose and difficult to maintain. Is there an easier way to write such a function but still have it work for any associative container that accepts any number of template parameters greater than or equal to two?
Please note that accepting iterators instead of containers as parameters will not suffice, because I need more information about the container on which the iterator operates than what the iterator can provide.
Thank you very much!
A: Why not just use the simple approach with a single template parameter:
template <typename C> void foo(const C & container)
{
typedef typename C::key_type key_type;
typedef typename C::mapped_type mapped_type;
// etc.
}
You can add some member-type-checking typetraits is you want additional checks that those member types exist, but that might not give any additional benefit.
Alternatively, you could do some generic pattern matching, though only with classes, not functions:
template <typename> struct AtLeastTwo;
template <typename K, typename V, typename ...Args>
struct AtLeastTo<K, V, Args...>
{
// now have types K and V
};
typedef std::unordered_map<int, Foo, MyHash> map_type;
AtLeastTwo<map_type> m;
// ...
A: A type does not convey information on whether it is an associative sequence, such is a semantic meaning. If you wan't to support all kinds of associative sequence, as per the standard interface, your best bet is to go with a single template parameter and use traits to introspect its key/value type and so on.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Overriding the look of baked-in Android features The Android app I'm working on makes use of Android's baked-in speech-input feature, but I want to alter the look of the speech-input dialog to be more of an aesthetic match with the rest of my program. Is there a way to substitute my own assets? Is it a simple matter of overriding the layout xml that the parent class references? Thanks in advance for your time!
A: yes you can make a custom dialog and use setContentView(R.layout.something)
A: I am afraid it is as easy as substituting a layout.
You need to manage your own speech recognition flow by using the SpeechRecognizer class.
There's a lot of details involved in using it, but it appears that you can customize the UI experience if you can.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Try-Catch and Delete[] issue I'm having a bit of a problem with a try-catch situation, here goes the code (it's pretty simple):
struct Something
{
int A, B, C;
Something()
{
A = B = C = 0;
}
~Something()
{
cout << "Destructor " << endl;
}
};
int main()
{
Something * s = new Something;
//Something * s = new Something[5];
try
{
delete[] s;
}
catch(exception& e)
{
delete s;
}
return 0;
}
What I intend to do is to first try to delete the pointer as an array, if it fails, make a simple delete.
So, when I first try it with an array of 'Something's (as in the commented line), itr worked perfectly. But when I try it as it is now, I get a horrible error.
Any ideas?
A: What your trying to do is neither legal C++ nor does it make sense.
An allocation with new must be followed by a deletion with delete, and an allocation with new[] by delete[]; this must happen precisely like that, and everything else is undefined behaviour.
You cannot "try and see if you wrote correct code". Exceptions signal exceptional runtime behaviour, but your error is a static, compile-time error that cannot be handled, but must be fixed.
However, there should never be a point in your code where you don't know what a given pointer means! Since the language is statically typed, you should in principle always have knowledge of the involved types. And if you want to pass objects around (possibly polymorphically), then anything that requires dynamic allocation should be wrapped in its own manager class (like shared_ptr or unique_ptr).
A: Deleting a pointer as an array (or vica versa) is incorrect and undefined. It won't throw an exception.
You should consider RAII. For example, create a class which contains the pointer as a member. The constructor allocates the memory, and the destructor deletes it.
Then you've got a few options:
(1) Have two constructors, one for a single item and one for an array. Place a boolean in the class that holds whether the pointer points to one item or an array, and check this on destruction and call the appropriate delete function.
(2) Make your class a template class that takes a boolean template parameter and resolve this choice at compile time.
A: You completely misunderstand the semantics of try/catch. They don't catch errors, they catch exceptions. You can only rely on an exception being created if you throw it yourself or do something that's guaranteed to throw an exception. Calling delete on a pointer allocated with new[] is not guaranteed to throw an exception, in fact, it's not guaranteed to do anything specific.
A: So my c++ skills are rusty but delete[] is called where you've called new[]. You haven't called new[] in your example.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Adding a Second Page To an App I have an app that has too much information in one spot so I wanted to add in a next button
that would lead to a new page for more information. Is there an easy way to do this? (I am currently a novice user).
Thanks for the help.
A: You can create a new activity page2 and have a button listener on page1 that leads to page2. Or you can use ScrollView or SlidingDrawer too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Adding UIButton top bar of a navigation controller that pushes to another viewController I have a UIButton that pushes to another view controller using the following code. How do I go about putting this UIButton to the top bar of a navigation controller.
-(IBAction) nextButtonPressed {
TipsViewController *objYourViewController = [[TipsViewController alloc] initWithNibName:@"TipsViewController" bundle:nil];
[self.navigationController pushViewController:objYourViewController animated:YES];
[TipsViewController release];
}
I was thinking of adding something like: self.navigationItem.rightBarButtonItem somewhere, but can't figure out the syntax.
Here's something else I tried with the following code: I can get a "Next" button in the top bar of the Navigation Controller. How would I get it to push to another view controller?
UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"Next" style:UIBarButtonItemStylePlain target:self pushViewController:anotherButton animated:YES];
self.navigationItem.rightBarButtonItem = anotherButton;
[anotherButton release];
thanks for any help.
A: When you init your UIBarButtonItem, do you see a parameter called action: ? Mention a selector there:
UIBarButtonItem *bar = [[UIBarButtonItem alloc] initWithTitle:@"Next" style:UIBarButtonItemStyleBordered target:self action:@selector(Next:)];
The above item should be your rightBarButton as you want it to be.
And this would be your selector:
-(void)Next:(id)sender {
[self.navigationController pushViewController:nextViewController animated:YES];
}
A: UIBarButtonItem addButton=[[UIBarButtonItem alloc]initWithTitle:@"+" style:UIBarButtonItemStyleBordered target:self action:@selector(method)];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SearchView focused when hiding the ActionBar menu I have an ActionBar with a SearchView. The hidden/overflow menu items are shown on the right in a drop-down list when the menu button is selected. When the drop-down menu is hidden, the SearchView is focused and the keyboard shows. Is there a way to stop the keyboard from showing (except for the case where the SearchView is touched)?
Regards,
Julius.
Edit added code below:
Here is how I initialise it:
SearchManager searchManager = (SearchManager) mActivity.getSystemService(Context.SEARCH_SERVICE);
((SearchView) mSearchView).setSearchableInfo(searchManager.getSearchableInfo(mActivity.getComponentName()));
mSearchView.setIconifiedByDefault(mIconified);
mSearchView.setOnQueryTextListener(this);
mSearchView.setOnCloseListener(this);
mSearchView.setFocusable(false);
mSearchView.setFocusableInTouchMode(false);
if(null!=mQuery)
mSearchView.setQuery(mQuery, false);
Edit 2:
Here is what I do when the user wants to start the search:
@Override
public boolean onQueryTextSubmit(String query) {
// Hide keyboard
InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(
FragmentActivity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mSearchView.getWindowToken(), 0);
...
mSearchView.setFocusable(false);
mSearchView.setFocusableInTouchMode(false);
return true;
}
A: try call setFocusable(false) on SearchView when you init it.
A: try calling mSearchView.clearFocus() on your initialization of the searchView. That worked for me when I had a similar problem.
A: I instantiated a search view when creating the options menu in a fragment and none of the above methods worked for me.
However, I was able to solve the problem by holding a reference to the SearchView, NOT setting the SearchView's iconified setting in onCreateOptionsMenu(), but setting it on a post when the fragment resumed like follows:
@Override
public void onResume() {
super.onResume();
getView().post(new Runnable() {
public void run() {
if (mFilterView.isIconfiedByDefault()) {
mFilterView.setIconifiedByDefault(false);
mFilterView.clearFocus();
}
}
});
}
A: Call requestFocus() for another view, ideally your results view, e.g.
_resultsFragment.getView().requestFocus();
A: I have just been pulling my hair out over the same issue.
I tried android:focusable="false". I tried the InputMethodManager. I tried creating a dummy view to take the focus but nothing worked.
I finally solved it with the following code inside onCreateOptionsMenu():
final ViewTreeObserver observer = mSearchView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
@Override
public void onGlobalLayout() {
observer.removeOnGlobalLayoutListener(this);
mSearchView.clearFocus();
}
});
The issue was that at every point in the Fragment's lifecycle the menu had not been created yet. The onCreateOptionsMenu() method was being called after onResume(), but only on some devices I tested on, which is really strange.
The above code makes sure that clearing the focus is done after any focus changes during creation of the page.
I hope this helps someone else, it would have saved me a lot of time to know this from the start.
A: When you set up your SearchView in your XML layout file (if you're using one), just use this:
android:focusable="false"
With this approach, your SearchView won't gain focus until you touch it...no matter where or if you "init" it in your code, or you hide your menu, or any other activity that might not have occurred in your debugging. This also eliminates the possible need to track where you are calling
setFocusable(false) //essentially does the same thing
in your code multiple times as the accepted answer suggests.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Where do I get the jersey-guice package? I would like to use Jersey and Guice together and I have found this tutorial, and a reference to jersey-juice here.
However, I'm not using Maven. I downloaded the main jersey package, but it does not include jersey-juice. Where do I get that package? All the links I've found are to a Java.net page that indicates that the file isn't found.
A: Sorry for the confusing link. You can find jersey-guice on maven central - this link has all the versions - just click on the jar link next to the version you want:
http://search.maven.org/#search|gav|1|g%3A%22com.sun.jersey.contribs%22%20AND%20a%3A%22jersey-guice%22
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: JTable cell value change listener Which listener can be used to react to the event of JTable cell value change? I tried using TableModelListener but either I got something wrong, or this listener doesn't react on changing the contents of a cell.
I need to act either to changing the content of a cell or to cell losing focus. What is the best way to do this? Thanks.
A: class extends JTable {
....
(inside contructor)
addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ("tableCellEditor".equals(evt.getPropertyName())) {
if (isEditing())
processEditingStarted();
else
processEditingStopped();
}
}
});
... (end constructor)
protected void processEditingStopped() {
System.out.println("save " + editingRow + ":" + editingColumn);
}
protected void processEditingStarted() {
System.out.println("edit " + editingRow + ":" + editingColumn);
if (editRow > -1 && editColumn > -1)
oldValue = (String) model.getValueAt(editRow, editColumn);
}
}
more details here: http://tips4java.wordpress.com/2009/06/07/table-cell-listener/
A: Easy way to react to values changing is to customize a table model and react to setValueAt().
If you're looking to make sure edits "stick" when it loses focus, call this on the table.
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
A: As mentioned by Bill, it maybe easier to "watch" the model rather than the JTable, I used this and was able to track changes by column and row:
list.getModel().addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
System.out.println("Column: " + e.getColumn() + " Row: " + e.getFirstRow());
}
});
As mentioned in my comment to their answer, it doesn't detect if a change occured only that the cell was edited. So you'll need to check against the original value somehow. But this saved me messing with my JTable constructor.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: usage of XSD in fixing errors in xml? I am just wondering if we can make XSD to fix the errors it finds in the xml itself rather than reporting them.
Thanks
A: No, XSD describes the structural rules for a document.
XSLT or XQuery would be more appropriate tools fix errors found in the XML.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: difference between System.exit() and killProcess() What's the difference if I call System.exit() vs. killProcess().
I am interested in difference only
A:
What should we use?
No one, read this Is quitting an application frowned upon?
A: I dont think There is any difference. although with System.exit(), you should call runFinalizersOnExit first
A: It looks like System.exit() is just as good in every respect as kill -- but much simpler and less dependent on other things.
Some have suggested that runFinalizersOnExit be set but according to the docs that is considered unsafe and is phased out as of 1.0 -- so I guess ignore that part.
Contrary to other suggestions, finish() does not end the Linux process which is running the app and does not free up all the memory used by the app.
Granted, android is designed so that for many cases there's no particular need to actually exit an app (At the cost of a slight pause later, android will kill your old apps when it needs their memory) -- however if you do want for any reason to kill your app System.exit() seems to be the idea way. It shuts down the java virtual machine which is running your app - so all resources, memory, and threads will be completely flushed out.
(Note that you can specify in your manifest file that some threads should run in different linux processes -- in which case System.exit() would probably only kill part of your app - but that's more advanced stuff.)
As a matter of fact, I just ran adb shell ps|grep app and I see the com.example.android.lunarlander sample app which I haven't run in about a week -- still in memory, still taking up almost 100000 bytes of memory.
A: Neither. Use finish(). See this, and the link aromero recommended. Let Android do what what it is meant to do: manage your activity life-cycle. It was designed this way for a reason.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: New to logging in general, but what should I log in an MVC3 application? I'm really new to logging, and I've decided it's time to take the plunge and start working it into my applications from now on.
I'm going to be using NLog as I hear it's very fast and simple to set up.
What type of information should I be concerned about logging? What information should be considered superfluous and unnecessary?
On a more specific line, where should I be placing my _logger.Info("Foo"); calls? Within each ActionMethod in my controllers?
A: You should look at ELMAH
It is the easiest thing to setup using nuget. And it provides awesome logging for asp.net MVC (logs all exceptions and the request associated with it), all the effort you have to do is to install the package in your application. :)
http://code.google.com/p/elmah/
A: The importance of logging cannot be explained in a word or two.
Logging forms an essential part of investigation by your application support L2 and L3 teams. They need the logs to respond to what has happened, bugs and so on.
Since logging forms non functional concern of any application, it is a cross cutting concern in terms of Aspect Oriented Programming, many aop frameworks like aspectJ is used in the Java development wing to implement logging, together with mature loggers.
A: http://www.dotnetlogging.com/ provides good tools for logging in .net
A: We use log4net and ELMAH. ELMAH is used for anything top level or unhandled.
We log (log4net) every method. We wrote a macro to inject logging enter/exit code (although there is a product out there that will inject this instrumentation in your compiled code)
For other steps we log out debug info (loading record id 15) log.Debug(...)
other times info "processing customer JOHN' using log.Info(..)
when we catch an exception we
log.Error()
Then we deploy our application and set our logging level to debug for the first bit of time, then switching over to "info" once its running smoothly.
This provides quite a bit of detail, but its up to you to decide where. Im just saying we log details in virtually every method.
also remember when you catch exceptions and log them, do now rethrow them. IE DO NOT
throw ex;
just simply
throw;
log4net can be found here:
http://logging.apache.org/log4net/
and a nuget package is available for automatic configuration at
http://nuget.org/List/Packages/log4net
ELMAH is available via nuget as well for automatic configuration although there are extra steps you need to take to work with MVC. Check out:
How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is there any functionality in git to check multiple git repos under a directory? I've got multiple git repos under a directory, and I was wondering whether there was some functionality in git to iterate each directory, check whether there are any uncommitted changes and report those to me?
I could run this every morning to ensure everything is up to date.
It's just that on any one day, I'll be working with multiple repos and I'll forget to commit my changes, which can cause conflicts when I realise much later on to commit them.
Chris
A: Andy is right (in the comments): if the parent directory is itself the root directory of a parent repo, with all the subdirectories as submdules, then git status can detect any changes in one of them.
You can also use (with submodules) git diff
git submodule foreach --recursive git diff --name-status
Without submodules, see a scripting solution at "git: Find all uncommited locals repos in a directory tree".
A: I wrote a command-line tool gita for this purpose. It can display the status of all repos, including the edit status, the relation to remote branch, etc. It also batch executes commands from any working directory.
You can also group the repos. For your project structure, you can run
gita add -r <root>
which will automatically add the subordinate repos into a group.
Then gita ll root will display the relevant information. gita <command> root will batch run the command on repos in the root group. You can surely run command on specified repos from any working directory too.
There are other functionalities such as setting context, defining custom commands, etc. Installation is pip3 install -U gita. You can find more information on github.
The gita ll command shows 3 possible symbols next to the branch name, which indicates
*
*+: staged changes
**: unstaged changes
*_: untracked files/folders
The branch names are colored in 5 ways
color
meaning
white
local has no remote
green
local is the same as remote
red
local has diverged from remote
purple
local is ahead of remote (good for push)
yellow
local is behind remote (good for merge)
A: Maybe https://metacpan.org/module/rgit might help :)
A: Add this alias to your .gitconfig file and then you can run git status-all from a parent directory to get the status of all git repositories recursively.
[alias]
status-all = "!for d in `find . -name \".git\"`; do echo \"\n*** Repository: $d ***\" && git --git-dir=$d --work-tree=$d/.. status; done"
A: I don't think git has this build in, thus some time ago I created a script to do this: https://github.com/mnagel/clustergit
clustergit allows you to run git commands on multiple repositories at once. It is especially useful to run git status recursively on one folder. clustergit supports git status, git pull, git push, and more.
A: In case someone needs a one liner:
rootdir=$(pwd);for folder in $(ls -p | grep /);do cd "$rootdir/$folder";git status; cd $rootdir; done
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I use LazyLoading with gallery and BaseAdapter? I am using this code to Create a BaseAdapter for a Gallery:
private class ImageAdapter extends BaseAdapter {
/** The parent context */
private Context myContext;
/** URL-Strings to some remote images. */
public String[] mImageURLs = {
urlImage1,
urlImage2,urlImage3,urlImage4,urlImage5,urlImage6,urlImage7};
String [] myRemoteImages = {imageUrl,imageUrl2,imageUrl3,imageUrl4,imageUrl5,imageUrl6,imageUrl7};
/** Simple Constructor saving the 'parent' context. */
public ImageAdapter(Context c) { this.myContext = c; }
/** Returns the amount of images we have defined. */
public int getCount() {
return this.myRemoteImages.length;
}
/* Use the array-Positions as unique IDs */
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/** Returns a new ImageView to
* be displayed, depending on
* the position passed. */
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(this.myContext);
try {
URL aURL = new URL(myRemoteImages[position]);
Log.v("ImageLoader", "Remote images set");
i.setTag(mImageURLs[position]);
URI imageUri = null;
SharedPreferences myPrefs = getSharedPreferences("imageUri", 0);
SharedPreferences.Editor myPrefsEdit = myPrefs.edit();
//Setting the Uri of aURL to imageUri.
try {
imageUri = aURL.toURI();
myPrefsEdit.putString("uris", imageUri.toString());
myPrefsEdit.commit();
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//Testing to see if images are already in cache, if not then we load the images from the web and save them to the cache.
if (new File(new File(myContext.getCacheDir(), "thumbnails"), "" + imageUri.hashCode()).exists()) {
Log.v("Loader", "File exists in cache. Now pulling from the cache");
String cachFile = myContext.getCacheDir() +"/thumbnails/"+imageUri.hashCode();
FileInputStream fis;
try {
fis = new FileInputStream(cachFile);
Bitmap bm = BitmapFactory.decodeStream(fis);
i.setImageBitmap(bm);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
Log.v("Loader", "Image loaded from cache");
/* Set the Width/Height of the ImageView. */
if (Build.VERSION.SDK_INT >= 11) {
i.setLayoutParams(new Gallery.LayoutParams(450, 300));
} else {
i.setLayoutParams(new Gallery.LayoutParams(200, 200));
}
} catch (FileNotFoundException e) {
Log.e("DEBUGTAG", "Remtoe Image Exception", e);
}
//If images are not in cache... Here we download the images from the URL, and save them to cache.
} else {
Log.v("Loader", "Images are not in cache, Downloading images now....");
URLConnection conn = aURL.openConnection();
conn.setUseCaches(true);
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
Log.v(imageUrl, "Retrieving image");
/* Apply the Bitmap to the ImageView that will be returned. */
i.setImageBitmap(bm);
putBitmapInDiskCache(imageUri, bm);
Log.v("Loader", "Image saved to cache");
/* Set the Width/Height of the ImageView. */
if (Build.VERSION.SDK_INT >= 11) {
i.setLayoutParams(new Gallery.LayoutParams(450, 300));
}
What I want to do is use lazyloading for the gallery instead of downloading the images here and then setting them to the gallery. It is to sluggish and too expensive.
As you can see I have the starter code above. How can I use LazyLoading with this?
A: Maybe you could have a look at WebImageView from Droid Fu
http://brainflush.wordpress.com/2009/11/23/droid-fu-part-2-webimageview-and-webgalleryadapter/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Freehand Drawing on Entire Screen I'm trying to make a simple little tool that would allow a user to switch from normal operation to a mode where all application messages are disabled and they can use the mouse to do some freehand drawing, then switch modes again to keep their drawing on the screen while they do whatever other normal stuff they want. This could, if I decide, evolve into a nice thing you could use to use a decorated screen by saving the decorations you do and loading them later.
When I started this (which was over half a year ago, soon after discovering the Windows API) I just did global mouse tracking and painted a circle wherever it was to a GetDC(NULL) hdc. The problems, of course, were that it would disappear when anything under it updated and would still have the mouse messages put through, so if I held down the button on the desktop, for example, it would put resizing rectangle things throughout the paintings.
Today, after finally having some spare time since the last major work on this most of that 6 months ago, I decided to remake it and see if I could achieve what I wanted. I made a transparent, topmost, WS_CHILD, layered, maximized window (basically the screen doesn't change, but there's a window on top of everything letting messages through). Next, I made it so that when it was in painting mode, it would set the alpha value to 1 and let the user paint. The thing I didn't realize until I did it was that since the alpha value of the window was 1, none of the painting would be visible.
Next, I tried using GetDC(NULL), but remembered that gets erased when something updates.
Now I just thought of using bitmaps and dcs to repeatedly store the screen into a dc, paint on another dc, and then copy it back to the one with the stored screen with transparency for the parts that aren't drawn on, and copy that back to the screen, but I'm losing a bit of heart. Here's my source code for that (the mask function is taken from this tutorial). Please tell me if some of this is unnecessary. I've used bitmaps for double buffering sure, but I'm not all that sure on where I need them.
//Global mask since it takes longer to make
HBITMAP mask;
//Window Procedure Start
HDC screenDC; //hdc for entire screen
screenDC = GetDC (NULL); //get DC for screen
HDC memDC = CreateCompatibleDC (screenDC); //create DC for holding the screen+paint
HBITMAP bm = CreateCompatibleBitmap (screenDC, GetSystemMetrics (SM_CXSCREEN), GetSystemMetrics (SM_CYSCREEN)); //create bitmap for memDC
HDC paintDC = CreateCompatibleDC (screenDC); //create DC to paint on
HBITMAP paintBM = CreateCompatibleBitmap (screenDC, GetSystemMetrics (SM_CXSCREEN), GetSystemMetrics (SM_CYSCREEN)); //create bitmap for paintDC
SelectObject (memDC, bm); //select bitmap into memDC
SelectObject (paintDC, paintBM); //select painting bitmap into paintDC
BitBlt (memDC, 0, 0, GetSystemMetrics (SM_CXSCREEN), GetSystemMetrics (SM_CYSCREEN), screenDC, 0, 0, SRCCOPY); //copy screen to memDC
SetBkColor (paintDC, RGB(0,0,0)); //set background of paintDC to black so it's all transparent to start
//WM_CREATE
mask = CreateBitmapMask (bm, RGB(0,0,0)); //create black mask (paint colours are limited 1-255 now)
//painting is done into paintDC
//at end of Window Procedure
SelectObject (paintDC, mask); //select mask into paintDC
BitBlt (memDC, 0, 0, GetSystemMetrics (SM_CXSCREEN), GetSystemMetrics (SM_CYSCREEN), paintDC, 0, 0, SRCAND); //this in combination with the next should make it bitblt with all of the black taken out I thought
SelectObject (paintDC, paintBM); //select bitmaps into DCs
SelectObject (memDC, bm);
BitBlt (memDC, 0, 0, GetSystemMetrics (SM_CXSCREEN), GetSystemMetrics (SM_CYSCREEN), paintDC, 0, 0, SRCPAINT); //second part of transparent bitblt
BitBlt (screenDC, 0, 0, GetSystemMetrics (SM_CXSCREEN), GetSystemMetrics (SM_CYSCREEN), paintDC, 0, 0, SRCCOPY); //copy memDC back to screen
DeleteObject (paintBM); //delete stuff
DeleteObject (mask);
DeleteDC (memDC);
DeleteDC (paintDC);
ReleaseDC (hwnd, screenDC);
//CreateBitmapMask() (taken directly from http://www.winprog.org/tutorial/transparency.html
HBITMAP CreateBitmapMask(HBITMAP hbmColour, COLORREF crTransparent)
{
HDC hdcMem, hdcMem2;
HBITMAP hbmMask;
BITMAP bm;
// Create monochrome (1 bit) mask bitmap.
GetObject(hbmColour, sizeof(BITMAP), &bm);
hbmMask = CreateBitmap(bm.bmWidth, bm.bmHeight, 1, 1, NULL);
// Get some HDCs that are compatible with the display driver
hdcMem = CreateCompatibleDC(0);
hdcMem2 = CreateCompatibleDC(0);
SelectObject(hdcMem, hbmColour);
SelectObject(hdcMem2, hbmMask);
// Set the background colour of the colour image to the colour
// you want to be transparent.
SetBkColor(hdcMem, crTransparent);
// Copy the bits from the colour image to the B+W mask... everything
// with the background colour ends up white while everythig else ends up
// black...Just what we wanted.
BitBlt(hdcMem2, 0, 0, bm.bmWidth, bm.bmHeight, hdcMem, 0, 0, SRCCOPY);
// Take our new mask and use it to turn the transparent colour in our
// original colour image to black so the transparency effect will
// work right.
BitBlt(hdcMem, 0, 0, bm.bmWidth, bm.bmHeight, hdcMem2, 0, 0, SRCINVERT);
// Clean up.
DeleteDC(hdcMem);
DeleteDC(hdcMem2);
return hbmMask;
}
I know that code may very well be horrible. I'm taking all suggestions into account, it's just that I'm not too clear with this subject, and don't get everything that's happening, which makes it hard to fix. This code runs for me by pretty much putting a fullscreen black rectangle every so often.
My main question is: Is there any way I can paint onto the screen without it getting erased when windows underneath update? The only real thing I can think of now would be to store all of the locations of the tiny line segments the user draws and keep redrawing them on top of the screen. At first glance it seems very inefficient and wasteful of memory.
Also, I was pretty sure while writing this that I didn't need any code examples for the theoretical stuff before the supplied code segments. Most of it is gone now, but this really is more of a theory issue.
EDIT:
I just found out about the TransparentBlt function which seemed perfect for the situation, so I tried using that instead of the SRCPAINT and SRCAND BitBlts and it produced the same result: a black rectangle covering the screen, sometimes having parts disappear when my mouse moves over things.
A: Simplest way, perhaps:
When in non-drawing mode, use SetLayeredWindowAttributes to set a 'transparency key' color for the transparent window. Make the window's alpha fully opaque, but fill the window (FillRect or similar) with that key color, and it will all appear transparent. Then anything you draw in the non-key color will appear as solid, on top of all the windows beneath the transparent layered window.
To go into drawing mode, one approach is to create a new window with a captured bitmap of the desktop immediately under your transparent layer. Or avoid the bitmap, and make it slightly non-transparent and all a solid color - eg so it looks like the desktop is "greyed out". The key thing is that this window is not completely transparent, so it will be able to receive mouse input that you can then use to draw on the actual transparent layer.
A: I think you would be best of by creating a snapshot of the screen and save that in a bitmap (in the form of a memory DC) BEFORE you show a window which displays the contents of the memory DC in fullscreen. That way you actually fetch the messages caused by clicks etc on your own window and process them as usual.
*
*Capture screen contents
*Create window (full screen) and use captured contents
*Do some drawing
*Save the content (as bmp or anything fancy)
*Close the window and return to regular desktop
Good idea?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What is the holdup on the first WCF call via the serviceProxy? There are a lot of similar questions, but they all deal with server-side slowness - this is all about client-side issues.
1st call takes 900ms.
2nd call takes 20 ms.
I narrowed the slowness on the first call to serviceProxy.Method(). Fiddler reports that the actual time on the wire for the 1st call is 16 ms. Since the 2nd call is massively faster, I am forced to conclude the problem occurs with some WCF client-side instantiation code that fires when the first method call takes place.
Facts:
*
*The connection to the server occurs via wsHttpBinding
*The objects are encoded with the Protobufs.NET library by Marc Gravell
*Questions here on SO that do address client-side issues like mine recommend making the 1st call on a background thread to just get the slowness out of the way. However, that's addressing the symptoms, not the underlying cause.
Any ideas why the slowdown occurs on the 1st post?
A: A common server slowness on start is IIS app pool spin up but in your question you stated that even though the first request was 900 ms, only 16 ms was spent on the server request according to fiddler. If that's true, it suggests something is going on client side.
One possibility is that some client apps that serialize objects generate and compile serialization code for those data types at runtime, which can result in slow start-up performance
http://msdn.microsoft.com/en-us/library/aa751883.aspx
http://msdn.microsoft.com/en-us/library/ms733901.aspx
I'm not familiar with protobuffs but compiling serialization code is trade off which makes the first call significantly slower but makes subsequent calls faster.
Not sure if that's your initial cost but it's a possibility.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: flashdata not being stored between redirects when using Tank Auth I'm using the latest version of Codeigniter and tank_auth 1.0.9 on a site I'm building.
When using set_flashdata() and flashdata() respectivly, nothing is being returned on redirect but if I set sess_use_database to FALSE in the config it works.
I've searched around and couldn't find an answer -- Has anyone else run into this issue and fixed it?
A: I was having the same issue and figured out the problem. If you're storing sessions in the database, it will not work.
Tank Auth runs this code from the main library ( $this->tank_auth->logout() ):
$this->delete_autologin();
// See http://codeigniter.com/forums/viewreply/662369/ as the reason for the next line
$this->ci->session->set_userdata(array('user_id' => '', 'username' => '', 'status' => ''));
$this->ci->session->sess_destroy();
Then it runs this code from the auth controller ( $this->_show_message() ):
$this->session->set_flashdata('message', $message);
redirect('/auth/');
The problem is that since sess_destroy() was run prior to setting the flashdata, there is no database row to add the flashdata to, so the flashdata never gets set.
At this point there are a few solutions:
Option 1:
Add $this->ci->session->sess_create(); immediately after $this->ci->session->sess_destroy(); in function logout() in application/libraries/Tank_auth.php
This works because you are creating a new blank session where flashdata can be stored. A potential con for this is that you are performing more operations on the database (delete+insert).
Option 2:
Comment out/delete $this->ci->session->sess_destroy(); in function logout() in application/libraries/Tank_auth.php
This works because the session is not destroyed, allowing CI to perform only an update query to add flashdata. This is probably better than option 1 unless you absolutely need to destroy the session.
Option 3:
Set $config['sess_use_database'] to FALSE.
This works because a session is automatically created when it is requested again, as opposed to how it works when you store sessions in the database. Potentially less secure.
In the end, it is up to you to decide which option is best for your application.
A: if tank_auth does any internal redirects then you may lose the flash data on that redirect request.
A: Exactly.
CodeIgniter documentation specifies here:
http://codeigniter.com/user_guide/libraries/sessions.html
=============================
Destroying a Session
To clear the current session:
$this->session->sess_destroy();
Note: This function should be the last one called,
and **even flash variables will no longer be available**.
If you only want some items destroyed and not all, use unset_userdata().
=============================
I've digged into the system/libraries/Session.php file and saving flashdata triggers the sess_write() method which only UPDATES the database as you said.
A: To me a better fix is checking to make sure the session exist before setting the flashdata in show_message().
function _show_message($message)
{
// Patch for show_message() after logout(). Make sure the session exist before set_flashdata().
if(!$this->session->sess_read())
{
$this->session->sess_create();
}
$this->session->set_flashdata('message', $message);
redirect('/auth/');
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Maximum and Minimum values for ints How do I represent minimum and maximum values for integers in Python? In Java, we have Integer.MIN_VALUE and Integer.MAX_VALUE.
See also: What is the maximum float in Python?.
A: In Python integers will automatically switch from a fixed-size int representation into a variable width long representation once you pass the value sys.maxint, which is either 231 - 1 or 263 - 1 depending on your platform. Notice the L that gets appended here:
>>> 9223372036854775807
9223372036854775807
>>> 9223372036854775808
9223372036854775808L
From the Python manual:
Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals (including binary, hex, and octal numbers) yield plain integers unless the value they denote is too large to be represented as a plain integer, in which case they yield a long integer. Integer literals with an 'L' or 'l' suffix yield long integers ('L' is preferred because 1l looks too much like eleven!).
Python tries very hard to pretend its integers are mathematical integers and are unbounded. It can, for instance, calculate a googol with ease:
>>> 10**100
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L
A: If you want the max for array or list indices (equivalent to size_t in C/C++), you can use numpy:
np.iinfo(np.intp).max
This is same as sys.maxsize however advantage is that you don't need import sys just for this.
If you want max for native int on the machine:
np.iinfo(np.intc).max
You can look at other available types in doc.
For floats you can also use sys.float_info.max.
A: sys.maxsize is not the actually the maximum integer value which is supported. You can double maxsize and multiply it by itself and it stays a valid and correct value.
However, if you try sys.maxsize ** sys.maxsize, it will hang your machine for a significant amount of time. As many have pointed out, the byte and bit size does not seem to be relevant because it practically doesn't exist. I guess python just happily expands it's integers when it needs more memory space. So in general there is no limit.
Now, if you're talking about packing or storing integers in a safe way where they can later be retrieved with integrity then of course that is relevant. I'm really not sure about packing but I know python's pickle module handles those things well. String representations obviously have no practical limit.
So really, the bottom line is: what is your applications limit? What does it require for numeric data? Use that limit instead of python's fairly nonexistent integer limit.
A: I rely heavily on commands like this.
python -c 'import sys; print(sys.maxsize)'
Max int returned: 9223372036854775807
For more references for 'sys' you should access
https://docs.python.org/3/library/sys.html
https://docs.python.org/3/library/sys.html#sys.maxsize
A: If you just need a number that's bigger than all others, you can use
float('inf')
in similar fashion, a number smaller than all others:
float('-inf')
This works in both python 2 and 3.
A: The sys.maxint constant has been removed from Python 3.0 onward, instead use sys.maxsize.
Integers
*
*PEP 237: Essentially, long renamed to int. That is, there is only one built-in integral type, named int; but it behaves mostly like the old long type.
...
*
*The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).
A: You may use 'inf' like this:
import math
bool_true = 0 < math.inf
bool_false = 0 < -math.inf
Refer: math — Mathematical functions
A: Python 3
In Python 3, this question doesn't apply. The plain int type is unbounded.
However, you might actually be looking for information about the current interpreter's word size, which will be the same as the machine's word size in most cases. That information is still available in Python 3 as sys.maxsize, which is the maximum value representable by a signed word. Equivalently, it's the size of the largest possible list or in-memory sequence.
Generally, the maximum value representable by an unsigned word will be sys.maxsize * 2 + 1, and the number of bits in a word will be math.log2(sys.maxsize * 2 + 2). See this answer for more information.
Python 2
In Python 2, the maximum value for plain int values is available as sys.maxint:
>>> sys.maxint # on my system, 2**63-1
9223372036854775807
You can calculate the minimum value with -sys.maxint - 1 as shown in the docs.
Python seamlessly switches from plain to long integers once you exceed this value. So most of the time, you won't need to know it.
A: For Python 3, it is
import sys
max_size = sys.maxsize
min_size = -sys.maxsize - 1
A: code given below will help you.
for maximum value you can use sys.maxsize and for minimum you can negate same value and use it.
import sys
ni=sys.maxsize
print(ni)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1147"
}
|
Q: SQLAlchemy - build query filter dynamically from dict So I have a dict passed from a web page. I want to build the query dynamically based on the dict. I know I can do:
session.query(myClass).filter_by(**web_dict)
However, that only works when the values are an exact match. I need to do 'like' filtering. My best attempt using the __dict__ attribute:
for k,v in web_dict.items():
q = session.query(myClass).filter(myClass.__dict__[k].like('%%%s%%' % v))
Not sure how to build the query from there. Any help would be awesome.
A: You're on the right track!
First thing you want to do different is access attributes using getattr, not __dict__; getattr will always do the right thing, even when (as may be the case for more convoluted models) a mapped attribute isn't a column property.
The other missing piece is that you can specify filter() more than once, and just replace the old query object with the result of that method call. So basically:
q = session.query(myClass)
for attr, value in web_dict.items():
q = q.filter(getattr(myClass, attr).like("%%%s%%" % value))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "39"
}
|
Q: Converting aggregate operators from SQL to relational algebra I have several SQL queries written that I want to convert to relational algebra. However, some of the queries use aggregate operators and I don't know how to convert them. Notably they use COUNT and GROUP BY.. HAVING operators.
Here is the schema:
Sailors(sid, sname, rating)
Reserves(sid, bid, price)
Boats(bid, bname)
Here is an example of what I'm doing: find the bids and bnames of all boats reserved by exactly 2 sailors.
SELECT B.bid, B.bname
FROM Boats B, Reserves R
WHERE B.bid = R.bid
GROUP BY R.bid
HAVING 2 = (SELECT COUNT(*)
FROM Reserves R2
WHERE R2.bid = B.bid);
Allowable relational algebra operations: selection, projection, join, conditional join, rename, union, intersection, cross-product, division
A: This is only half an answer...
The relation "boats reserved by two or more sailors" can be found using conditional join and projection, which are both in your set of allowed operations:
SELECT DISTINCT R1.bid
FROM Reserves AS R1
JOIN Reserves AS R2
ON R1.bid = R2.bid
AND R1.sid < R2.sid;
The relation "boats reserved by three or more sailors" can be found using conditional join (twice) and projection, which are both in your set of allowed operations:
SELECT DISTINCT R1.bid
FROM Reserves AS R1
JOIN Reserves AS R2
ON R1.bid = R2.bid
AND R1.sid < R2.sid
JOIN Reserves AS R3
ON R1.bid = R3.bid
AND R2.sid < R3.sid;
If we had a minus operator e.g. EXCEPT in Standard SQL:
SELECT DISTINCT R1.bid
FROM Reserves AS R1
JOIN Reserves AS R2
ON R1.bid = R2.bid
AND R1.sid < R2.sid
EXCEPT
SELECT DISTINCT R1.bid
FROM Reserves AS R1
JOIN Reserves AS R2
ON R1.bid = R2.bid
AND R1.sid < R2.sid
JOIN Reserves AS R3
ON R1.bid = R3.bid
AND R2.sid < R3.sid;
If we had restriction (WHERE in SQL) and a semi difference (a.k.a. antijoin) operator (e.g. NOT IN in SQL):
SELECT DISTINCT R1.bid
FROM Reserves AS R1
JOIN Reserves AS R2
ON R1.bid = R2.bid
AND R1.sid < R2.sid
WHERE R1.bid NOT IN (
SELECT DISTINCT R1.bid
FROM Reserves AS R1
JOIN Reserves AS R2
ON R1.bid = R2.bid
AND R1.sid < R2.sid
JOIN Reserves AS R3
ON R1.bid = R3.bid
AND R2.sid < R3.sid
);
...but your set of allowed operations does not include restriction, semi difference or minus :(
A: "I was reading a book with a chapter on relational algebra and it didn't mention aggregate functions for them at all".
Literature on the relational algebra typically limits itself to the portion of the algebra that makes it closed over relations. An algebra is closed over a set of types (I'm probably expressing myself a bit sloppily, but the main idea is right) if none of the operators of the algebra returns a value of a type that isn't a member of that set of types the algebra is closed over.
If all you have (or want to consider in a book) is the set of all relation types, and you want to write a treatment of the algebra, then you cannot define an operator that returns an integer (COUNT), or a float (HARMONICMEAN), or a date (MIN(<date column>)), or whatever similar kind of thing, without breaking the 'closed' property of the algebra.
That is not to say that such aggregation operations are useless (of course not). They're typically just not exactly relevant in a context where the primary purpose is to explain JOIN, PROJECT, RESTRICT, etc.
EDIT
supplementary piece of answer regarding GROUP BY ... HAVING. You noticed correctly that this SQL construct is nontrivial stuff when it comes to algebra equivalents. The gist of it is that the set of algebra operators that you mention, lacks an operator that is needed to achieve such stuff, and this operator is GROUP. GROUP takes an input relation, and produces an output relation in which one of the attributes is relation-valued.
For example, GROUP ( RESERVES , SAILORS_AND_THEIR_BID ( SID , PRICE ) ) would produce a relation of degree 2, with attributes BID and SAILORS_AND_THEIR_BID. The latter attribute is relation-valued, so that the expression COUNT(SAILORS_AND_THEIR_BID) becomes valid in the context of a RESTRICT condition applied to this relation, such that you can write ( GROUP ( RESERVES , SAILORS_AND_THEIR_BID ( SID , PRICE ) ) ) WHERE COUNT(SAILORS_AND_THEIR_BID) = 2.
A: Building on onedaywhen's answer:
Yes, the lack of a set difference operator does hurt. It should totally be allowed. However, we can express set difference with set complement and intersection:
B - A = B ∩ A'
i.e. the difference of B and A is in fact B's intersection with A's complement. We have the intersection as an allowed operator, and while a relation's proper complement is an ugly thing, the complement of an R1 ⊆ R relative to R (i.e. the stuff in R that aren't in R1) can be found easily with a join:
SELECT DISTINCT R0.x
FROM R as R1
JOIN R as R0 ON R1.x<>R0.x
WHERE R1.x=val
is the complement relative to R of
SELECT DISTINCT R.x FROM R WHERE R.x=val
So, here comes a solution to the riddle, I think: it's easy to get all the boats reserved by two or more guys: select all the boats that are in the reserves table, take the cartesian product of the result with itself, then select each row that has different sailor1 and sailor2. In the unwieldy relational algebra notation they taught me:
π( R.bid ) (
σ( R.bid=R2.bid and R.sid<R2.sid )( R x ρ(R, R2) )
)
(where π is the projection operator, σ is the selection operator, and ρ is the rename operator)
This nets the id's of all the boats reserved by two or more people. Now I'm going to get all the boats that were reserved by two or less guys. To do this, I'll select all the boats reserved by three or more guys, and take the set's complement by selecting all the rows from the original table which aren't present in that set. It won't be pretty, but here it goes:
π(R.bid)(σ(R.bid<>R1.bid)(
π(R.bid)(R)
x
π(R1.bid) (
σ( R1.bid=R2.bid and R2.bid=R3.bid and R1.sid<R2.sid and R2.sid<R3.sid )( ρ(R, R1) x ρ(R, R2) x ρ(R, R3) )
)
))
You see, I select all the rows which have the property, then select all the rows from the original table which aren't these, netting us all the rows which don't have the property, here meaning all the boats not reserved by three or more people, the boats reserved by two or less persons.
To get the boats with exactly two guys reserving them, simply intersect this with the set of boats reserved by more than one guy.
π( R.bid ) (
σ( R.bid=R2.bid and R.sid<R2.sid )( R x ρ(R, R2) )
) ∩ π( R.bid ) (
σ(R.bid<>R1.bid)(
π(R.bid)(R)
x
π(R1.bid) (
σ( R1.bid=R2.bid and R2.bid=R3.bid and R1.sid<R2.sid and R2.sid<R3.sid )( ρ(R, R1) x ρ(R, R2) x ρ(R, R3) )
)
)
)
Ugh. It's so ugly it hurts. I wish I knew a nicer notation.
SQLishly, it might look like this, I think:
(SELECT DISTINCT R1.bid
FROM Reserves AS R1
JOIN Reserves AS R2 ON R1.bid = R2.bid AND R1.sid < R2.sid
) INTERSECT (
SELECT DISTINCT R.bid
FROM Reserves AS R1
JOIN Reserves AS R2 ON R1.bid = R2.bid AND R1.sid < R2.sid
JOIN Reserves AS R3 ON R1.bid = R3.bid AND R2.sid < R3.sid
JOIN Reserves AS R ON R.bid<>R1.bid
)
Please note that this is exactly onedaywhen's solution, except I expressed set difference as taking the intersection with the complement.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: macro: does #define a(b) ({... c;}) means a(b) returns c? I have this code in linux kernel:
#define task_cred_xxx(task, xxx)
({
__typeof__(((struct cred *)NULL)->xxx) ___val;
rcu_read_lock();
___val = __task_cred((task))->xxx;
rcu_read_unlock();
___val;
})
I never saw macro defined like this before, does that mean this is task_cred_xxx(task, xxx) returns ___val?
Thanks!
A: Correct. It will return ___val. However, block expressions like these are a GNU extension and isn't actually part of the C standard.
http://www.toofishes.net/blog/gcc-compound-statement-expressions/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MVC3 Model Lifecycle I'm hoping someone can clarify how a model should progress through postbacks given the following example:
MyModel
public class MyModel
{
public string Text { get; set; }
public List<RadioButtonListItem> Options { get; set; }
public MyModel()
{
//Initialize the options.
this.Options = new List<RadioButtonListItem>()
{
//Setting Text, Value and Group Name. 3rd is selected by default.
new RadioButtonListItem("Item 1", "1", "Options"),
new RadioButtonListItem("Item 2", "2", "Options"),
new RadioButtonListItem("Item 3", "3", "Options", true)
};
}
}
RadioButtonListItem
public class RadioButtonListItem
{
[HiddenInput]
public string Value { get; set; }
[HiddenInput]
public string Text { get; set; }
[HiddenInput]
public string GroupName { get; set; }
[HiddenInput]
public string SelectedValue { get; set; }
[TemplateVisibility(ShowForEdit = false)]
public override bool Selected { get { return string.Equals(this.Value, this.SelectedValue); } set { this.SelectedValue = (value ? this.Value : null); } }
public RadioButtonListItem() { }
public RadioButtonListItem(string value, string text, string groupName) : this(value, text, groupName, false) { }
public RadioButtonListItem(string value, string text, string groupName, bool selected)
{
//...
}
}
*
*Controller fires Index view, passing a new model. Options are defaulted, third option is selected by default.
*Now, the form fields that are rendered include basically the entire model, including the value, text and group name of each RadioButtonListItem.
*User fills in the form and clicks Submit button.
*HttpPost controller receives the model. The model is repopulated from the posted data, including the RadioButtonListItems and all of their properties.
*Some form entry is incorrect so the same model instance is sent back to the view, that way the user's entries and selections are preserved.
*The user fixes the error, re-submits the form, all is good.
Summary
This seems weird to me because I don't really think you should have to send back the original metadata so that the model state can be persisted. But if you don't send it back, what do you do? I can think of only one other option: during the post-back create a second model instance and copy the user's selections to the new instance and feed that back to the view.
But that doesn't seem right to me. Can someone clarify how this is supposed to work?
A: I wasn't thinking clearly when I asked this question. The items in the list, of course, don't need to be sent back with the post data. You simply keep a separate list in the model which you initialize in the constructor and then have an int field which is the ID or key of the item that was selected from the list.
The model looks like this:
[Required]
[DataType("RadioButtonList")]
[Display(Name = "Format", Order = 2)]
[AdditionalMetadata("Style", "Wide")]
[AdditionalMetadata("List", "Items")]
public int? SelectedItem { get; set; }
[TemplateVisibility(ShowForDisplay = false, ShowForEdit = false)]
public List<ListItem> Items { get; set; }
It points to it's own list with the AdditionalMetaData attribute. So you can easily have the RadioButtonList EditorTemplate load up the list and just send back which item was selected. That value will be populated in the SelectedItem property.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to syslog-ng to remote facility i have a host running syslog-ng. it does all it's stuff locally fine (creating log files etc). however, i would like to forward ALL of it's logs to a remote machine - specifically to one facility on the remote machine (local4). i tried playing around with rewrite (set-facility) and templates within the destination (syntax errors) - but to no avail.
destination remote_server {
udp(\"172.18.192.8\" port (514));
udp(\"172.18.192.9\" port (514));
};
rewrite r_local4 {
set-facility(local4);
};
filter f_alllogs {
level (debug...emerg);
};
log {
source(local);
filter(f_alllogs);
rewrite(r_local4)
destination(remote_server);
};
A: AFAIK, currently it is not possible to modify the facility of a message in syslog-ng.
Is there a special reason you want to do it?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Assigning NSDictionary keys to NSStrings I'm importing a txt file with a list of first and last names. Each new name is on it's own line, so I imported them into a NSMutableArray and then split them with componentsSeparatedByString:@"\n". I then want to sort the names via their last name. I have found this Sort collections, but I'm lost at how I would tell my NSStrings that are within my Array to have the key's firstName and lastName. Obviously I'd have to make an NSDictionary, but can you do a for loop where by I say something like anything before the " " (space) is firstName, and anything after is the lastName.
Hopefully I've been clear enough,
Thanks in advance.
EDIT: This is all going to be displayed in a UITableView, if that changes/helps.
A: Personally, I would make a simple class called Name that has a property for firstName and a property for lastName. You can then loop through the array and to create your Name instances, add them to an NSMutableArray and then sort the array. You can go the dictionary route if you want of course.
Here is an example:
NSMutableArray *namesList = [NSMutableArray arrayWithCapacity:0];
for (NSString *name in originalArray) {
NSArray *tempArray = [name componentsSeparatedByString:@" "];
Name *newNameInstance = [[Name alloc] init];
newNameInstance.firstName = [tempArray objectAtIndex:0];
newNameInstance.lastName = [tempArray objectAtIndex:1];
[namesList addObject:newNameInstance];
}
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"lastName"
ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [namesList sortedArrayUsingDescriptors:sortDescriptors];
This code hasn't been checked but it should work. I haven't taken care with memory management so please be mindful of that.
Update
Sorry, should be [tempArray objectAtIndex:0]. Fixed it above.
Since firstName and lastName are strings then they should be declared as NSString. Try not to use id for a property unless you have a really good reason.
Update 2
If you want to check the values do this:
for (Name *name in sortedArray) {
NSLog(@"%@", name.firstname);
NSLog(@"%@", name.lastName);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Pulling and storing SMS numbers with PHP and Twilio So I'm new to using Twilio (and my PHP is a bit rusty) but currently the code responds to text with data depending on if you give it the right data, otherwise, it just asks you to try it again. So that's the bit that works. However, what I'm hoping to do, is to pull the numbers of incoming SMS texts and temporarily store them in a cookie so I can can have a different response based on their previous responses.
Does that make sense?
A: Yes! Twilio makes this really simple. Any cookies you set will be saved between two numbers (your incoming phone number and the sender). All the code and explanation is here: http://www.twilio.com/docs/quickstart/sms/tracking-conversations
Here's a quick snippet from that page which should do what you want:
<?php
// start the session
session_start();
// get the session varible if it exists
$counter = $_SESSION['counter'];
// if it doesnt, set the default
if(!strlen($counter)) {
$counter = 0;
}
// increment it
$counter++;
// save it
$_SESSION['counter'] = $counter;
// make an associative array of senders we know, indexed by phone number
$people = array(
"+14158675309"=>"Curious George",
"+14158675310"=>"Boots",
"+14158675311"=>"Virgil",
);
// if the sender is known, then greet them by name
// otherwise, consider them just another monkey
if(!$name = $people[$_REQUEST['From']])
$name = "Monkey";
// output the counter response
header("content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<Response>
<Sms><?php echo $name ?> has messaged <?php echo $_REQUEST['To']." ".$counter ?> times</Sms>
</Response>
A: Just use $from = $_REQUEST['From'];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: trying to use jquery tooltip plugin, object has no method "tooltip" I'm using this tooltip: http://flowplayer.org/tools/demos/tooltip/index.html
I have the following lines in my html file:
<script src="/javascripts/home.js" type="text/javascript"></script>
<script src="http://cdn.jquerytools.org/1.2.6/jquery.tools.min.js" type="text/javascript"></script>
<script type="text/javascript" src="/scripts/jquery.min.js"></script>
<div id="boo">
<img src="image1.jpg" title="this thing is a tool"/>
<img src="image2.jpg" title="this thing is also tool"/>
</div>
I have the following line in my home.js file:
$("#boo img[title]").tooltip();
I have the following line in my css file:
.tooltip {
display:none;
background:transparent url(/tools/img/tooltip/black_arrow.png);
font-size:12px;
height:70px;
width:160px;
padding:25px;
color:#fff;
}
I get this error:
Uncaught TypeError: Object [object Object] has no method 'tooltip'
I'm at my wits end. I feel like I've followed the example on the site exactly, but no idea what's going on.
A: Got this problem too, and it was because of an old version of jquery lost in the sources folder, was jquery v1.6.2.
If it can help someone... Have a nice day!
A: You should reorder your js files:
<script type="text/javascript" src="/scripts/jquery.min.js"></script>
<script src="http://cdn.jquerytools.org/1.2.6/jquery.tools.min.js" type="text/javascript"></script>
<script src="/javascripts/home.js" type="text/javascript"></script>
A little more explanation for anyone else having this problem:
Scripts are loaded in the order they're called, so you want to load jQuery first, then any plugins, then your custom code.
A: Wrap $("#boo img[title]").tooltip(); in $(function(){ }); so you end up with:
$(function(){
$("#boo img[title]").tooltip();
});
Why:
The $(function()... is a short cut to execute that code on the domReady event. So at that point all of the jquery files, and the page, will be loaded far enough for your javascript to work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Onclick Event Issue in IE 7 I'm thoroughly confused now. Exclusively in IE7 my onclick function fails to execute. However, when I run it in IE's console, it works just fine.
I've tried the following combinations:
onclick="loadStatsRSH('h',2)" href="javascript:void(0)"
onclick="loadStatsRSH('h',2);return false;" href="javascript:void(0)"
onclick="loadStatsRSH('h',2);return false;" href="#"
onclick="loadStatsRSH('h',2)" href="#"
onclick="javascript:loadStatsRSH('h',2);return false;" href="#"
onclick="javascript:loadStatsRSH('h',2);" href="javascript:void(0)"
There are other which I've tried, but now I feel its getting silly. Can anyone give me a hint why IE7 would complain about my onclick?
A: It works fine here: http://jsfiddle.net/jfriend00/KHY52/ in any version of IE I try it in with this HTML:
<a onclick="loadStatsRSH('h',2);return false;" href="#">Click here</a>
One possibility is that your loadStatsRSH function isn't in the global scope and thus the browser can't find it (though it would be unlikely that that would be a problem in only IE).
If you want further help, the problem is probably caused by parts of your web page that you haven't disclosed as there is nothing wrong with the choices you have above. I'd suggest describing/showing more of your HTML and more of your script.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Rails3 ActionMailer deliveries in development environment Is it possible to send mailers in the development environment?
I've added this to my development.rb file:
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.smtp_settings = {
:address => "mail.email.com",
:port => 25,
:domain => 'email.com',
:user_name => 'email@email.com',
:password => 'password',
:authentication => 'plain',
:enable_starttls_auto => true }
Then I run UserMailer.welcome_email(@user).deliver in rails console which returns #<Mail::Message:2265713480, Multipart: true, Headers: <Date: Thu... but I never actually receive the email. Is there something else I need to configure?
Oh, and if I check ActionMailer::Base.deliveries it returns an empty hash => [].
A: Needed to add the following to environments/development.rb:
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.perform_deliveries = true
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Generate a random uuid in a maven archetype I need to create a random UUID and write it to the generated project. Currently, I ask the user to fill in a random UUID each time a project is created, and I would like this to be done automatically.
Right now, I have in my archetype-metadata.xml the following required property:
<requiredProperty key="randomUuid">
<defaultValue>12345678-1234-1234-1234-12345678abcd</defaultValue>
</requiredProperty>
Then I refer to ${randomUuid} inside my archetype resources to write this UUID into the generated project.
Any better approach ?
Thanks!
A: I found myself needing the same thing, so here is what I did to make this work:
<requiredProperty key="testUUID">
<defaultValue>${package.getClass().forName("java.util.UUID").getMethod("randomUUID").invoke(null).toString()}
</defaultValue>
</requiredProperty>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Symfony 2 passing a variable to a form class to dynamically create a hidden field in the form I am working on a blogging sort of tool on symfony 2 framework where a post can have many comments. I have a one to many relationship established between posts and comments in the respective entities. When a post is displayed on the home page, I want a comment form underneath it where users can post comments. In order to post a comment, I have to pass a hidden field in the form for the postID but I am having trouble doing so. Below is all my code..
The controller:
<?php
namespace Issh\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Issh\MainBundle\Form\Post\CommentForm;
use Issh\MainBundle\Form\Post\PostForm;
use Issh\MainBundle\Entity\IsshPost;
use Issh\MainBundle\Entity\IsshComment;
class HomeController extends Controller
{
public function indexAction()
{
return $this->render('IsshMainBundle:Home:index.html.php');
}
public function postAction()
{
$em = $this->get('doctrine')->getEntityManager();
$request = $this->get('request');
$post = new IsshPost();
$form = $this->createForm(new PostForm(), $post);
if ('POST' == $request->getMethod())
{
$form->bindRequest($request);
$post->setIsshUser($this->get('security.context')->getToken()->getUser());
if ($form->isValid())
{
$em->persist($post);
$em->flush();
return $this->redirect($this->generateUrl('home'));
}
return $this->render('IsshMainBundle:Home:IsshPost.html.php', array(
'form' => $form->createView()));
}
else
{
$em = $this->getDoctrine()->getEntityManager();
$posts = $em->getRepository('IsshMainBundle:IsshPost')->getLatestPosts();
return $this->render('IsshMainBundle:Home:IsshPost.html.php', array(
'form' => $form->createView(), 'posts' => $posts));
}
}
public function commentAction($postID = null)
{
$em = $this->get('doctrine')->getEntityManager();
$request = $this->get('request');
$comment = new IsshComment();
$form = $this->createForm(new CommentForm($postID), $comment); // need to pass postID here so it can be set as hidden field
if ('POST' == $request->getMethod())
{
$form->bindRequest($request);
$comment->setIsshUser($this->get('security.context')->getToken()->getUser());
if ($form->isValid()) {
$em->persist($comment);
$em->flush();
return $this->redirect($this->generateUrl('home'));
}
}
else
{
return $this->render('IsshMainBundle:Home:IsshComment.html.php', array(
'form' => $form->createView()));
}
}
}
Here is the post form:
<?php
namespace Issh\MainBundle\Form\Post;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class PostForm extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('text','text');
}
public function getName()
{
return 'postForm';
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Issh\MainBundle\Entity\IsshPost'
);
}
}
?>
The comment form (doesn't work yet):
<?php
namespace Issh\MainBundle\Form\Post;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class CommentForm extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('text','text');
}
public function getName()
{
return 'commentForm';
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Issh\MainBundle\Entity\IsshComment'
);
}
}
?>
The post template:
<?php if(!empty($form)): ?>
<form action="<?php echo $view['router']->generate('post') ?>" method="post" <?php echo $view['form']->enctype($form) ?> >
<?php echo $view['form']->errors($form) ?>
<?php echo $view['form']->row($form['text']) ?>
<?php echo $view['form']->rest($form) ?>
<input type="submit" />
</form>
<?php endif; ?>
<?php if(!empty($posts)): ?>
<?php foreach ($posts as $post): ?>
<p><?php echo $post->getText();?></p>
<?php
//embed comment controller in view
echo $view['actions']->render('IsshMainBundle:Home:comment',array('postID' => $post->getId()));
?>
--------------------------------------
<?php endforeach; ?>
<?php endif; ?>
The comment template:
<?php if(!empty($form)): ?>
<form action="<?php echo $view['router']->generate('comment') ?>" method="post" <?php echo $view['form']->enctype($form) ?> >
<?php echo $view['form']->errors($form) ?>
<?php echo $view['form']->row($form['text']) ?>
<?php echo $view['form']->rest($form) ?>
<input type="submit" />
</form>
<?php endif; ?>
<?php if(!empty($comments)): ?>
<?php foreach ($comments as $comment): ?>
<p><?php echo $comment->getText();?></p>
--------------------------------------
<?php endforeach; ?>
<?php endif; ?>
A: You could declare a constructor in your form class and pass the postID to the form.
class CommentForm extends AbstractType
{
private $postId;
public function __construct($postId = null)
{
$this->postId = $postId;
}
public function buildForm(FormBuilder $builder, array $options)
{
...
}
You can now access the postID as $this->postId anywhere in the form.
A: You can simply add an options to buildForm method like that:
$form = $this->get('form.factory')->create(new FormType(), array( 'key' => 'var'));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Codeigniter PHP Fatal error: Call to a member function item() on a non-object when call $this->config->item(‘config_item’) $this->config->item('config_item')
PHP Fatal error: Call to a member function item() on a non-object
Anyone knows how to fix this kind of problem? Or anyone ever been had same stuff?
The error happens on every call of config item rather in libraries classes (e.g. form_validation class) or in application controller.
If I print_r($this->config) it shows array of config content.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7604999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to open a page in previous window? I have number of buttons in my page. when one of them is clicked a popup opens.the user browses some links there and click one of them. I want this webpage be displayed in the same page that the button exits. can you please give me a clue how I should do that?
A: To access the parent window from a child window, use the parent property of the window object as such:
window.parent.location.href = "some URL";
The code of course should exist in the child window.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why is 0 == "" true in JavaScript Why is 0 == "" true in JavaScript? I have found a similar post here, but why is a number 0 similar an empty string? Of course, 0 === "" is false.
A: 0 == ''
The left operand is of the type Number.
The right operand is of the type String.
In this case, the right operand is coerced to the type Number:
0 == Number('')
which results in
0 == 0
From the Abstract Equality Comparison Algorithm (number 4):
If Type(x) is Number and Type(y) is String, return the result of
the comparison x == ToNumber(y).
Source: http://es5.github.com/#x11.9.3
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
}
|
Q: Interrupt queue or file write operation in iOS I work with large images on the iPhone, so saving them to disk can take several seconds, and sometimes an instruction to delete the image comes when it hasn't finished saving. I would like to interrupt the saving process and delete the file inmediatly, without waiting for it to save first, but I can't find any way to interrupt the queue or the saving operation.
@interface YMSavedImage : NSObject {
UIImage *image;
NSString *path;
dispatch_queue_t imageAccess;
...
}
@end
@implementation YMSavedImage
- (id)init
{
...
imageAccess = dispatch_queue_create("imageAccessQueue", NULL);
...
}
- (void)save
{
dispatch_async(imageAccess, ^(void) {
[UIImagePNGRepresentation(image) writeToFile:path atomically:YES]; // This takes several seconds.
});
}
- (void)delete
{
dispatch_sync(imageAccess, ^(void) {
if ([fileManager fileExistsAtPath:path]) {
[fileManager removeItemAtPath:path error:NULL];
}
});
}
...
@end
A: writeToFile:atomically: is going to want to write all of the data to file in one shot. You would be better off grabbing an NSFileHandle and quickly writing subsections of the data, after each atomic write you could check to see if the user has requested to cancel saving.
I'd suggest something like:
- (void)save
{
dispatch_async(imageAccess, ^{
// Create an empty file to populate
[[NSFileManager defaultManager] createFileAtPath:_imageFilePath contents:nil attributes:nil];
// Grab a handle on the file
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:_imageFilePath];
NSData *imageData = UIImagePNGRepresentation(_image);
// Store how long the image is
NSUInteger totalLength = [imageData length];
// Store how many chunks we should need with the set kDesiredChunkSize
NSUInteger chunks = totalLength / kDesiredChunkSize;
NSUInteger i = 0;
// Walk through the image chunk by chunk and check if we are cancelled after each atomic operation
for (i = 0; i < chunks; i++) {
[handle seekToEndOfFile];
[handle writeData:[imageData subdataWithRange:NSMakeRange(i * kDesiredChunkSize, kDesiredChunkSize)]];
if (__userCancelledSave) { // The user asked us to cancel,
[[NSFileManager defaultManager] removeItemAtPath:_imageFilePath error:nil]; // FIXME: Handle this error
return;
}
}
// Write any remaining data that's less than one chunk in size
NSUInteger sizeDifference = totalLength - (chunks * kDesiredChunkSize);
if (sizeDifference > 0) {
[handle seekToEndOfFile];
[handle writeData:[imageData subdataWithRange:NSMakeRange(chunks * kDesiredChunkSize, sizeDifference)]];
}
});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Textfield display issues in some versions of Flash Player I was just wondering if anyone else has come across some strange textfield display issues in any of the recent Flash Player releases. Both IE and FF were having display problems, both in slightly different ways. FF would simply display the text as if it were a single line field, no wordwrap, whereas IE would display the text vertically, Chinese style. These are classic dynamic text fields, compiled in CS5 by the way.
The issue seems to occur when you assign text to a field when its x coordinate is off the stage, then move it onto the stage after this. I so far haven't found anyone else mentioning this problem on the interwebs, which I find strange, as it is a pretty bizarre one! Incidentally, the same thing was happening with the textfields on a workmate's AIR application.
These problems for me were occurring in FP 10.3.183.5 in IE, and FP 10.3.183.7 in FF. I updated FF's player to the latest (10.3.183.10) and the problem appears to be resolved. Hopefully this is the end of it, but it's just a little disconcerting, as you never know what version your clients will be using!
I'm not able to post images here yet, but I've included links to screenshots of the problem occuring in IE, and also it displaying properly in the latest player in FF. I've left a border on the textfield to show you it's dimensions.
Any insights (or simply someone else saying they have also come across this issue so I don't feel alone haha) would be much appreciated,
Cheers.
-> problem in 10.3.183.5
-> no problem in 10.3.183.10
edit: Here's a link (don't have enough rep to post more links yet) Here is the URL to a dummy swf that has the problem: mattlukins[dot]com[dot]au/misc/dumb_textfield_thing.zip
(screenshot: i1096[dot]photobucket[dot]com/albums/g338/el_mateo/IE-flash-103183_dummy_screenshot.jpg). I've since updated my FP version in IE to the latest, and sure enough it's ok now, but if anyone is still running 10.3.183.5 then you might be able to see the bug still.
A: This is a known bug that has been fixed in the latest version of Flash. See https://bugbase.adobe.com/index.cfm?event=bug&id=2941694
Also another question about it: Workaround for TextField bug in FP 10.3.183.5 and 10.3.183.7
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Using Google's regex library RE2 for C++: linking errors I'm trying to use Google's regex library, RE2, in my C++ code but cannot get it to compile. Here is a simple test program that I wrote:
#include <iostream>
#include <re2/re2.h>
using namespace std;
using namespace re2;
int main (int argc, char **argv)
{
cout << "hello world" << endl;
int matchResult;
matchResult = RE2::FullMatch("hello", "h.*o");
cout << "matchResult = " << matchResult << endl;
return 0;
}
When I try to compile it using this g++ command:
g++ -I /usr/local/include -o test main.cc
I get these errors:
/var/tmp//ccOMm5QM.o(.text+0x1f2): In function `main':
: undefined reference to `re2::RE2::RE2(char const*)'
/var/tmp//ccOMm5QM.o(.text+0x210): In function `main':
: undefined reference to `re2::RE2::FullMatch'
/var/tmp//ccOMm5QM.o(.text+0x227): In function `main':
: undefined reference to `re2::RE2::~RE2()'
/var/tmp//ccOMm5QM.o(.text+0x275): In function `main':
: undefined reference to `re2::RE2::~RE2()'
/var/tmp//ccOMm5QM.o(.gnu.linkonce.t._ZNK3re217VariadicFunction2IbRKNS_11StringPieceERKNS_3RE2ENS4_3ArgEXadL_ZNS4_10FullMatchNES3_S6_PKPKS7_iEEEclES3_S6_+0x27): In function `re2::VariadicFunction2<bool, re2::StringPiece const&, re2::RE2 const&, re2::RE2::Arg, &(re2::RE2::FullMatchN(re2::StringPiece const&, re2::RE2 const&, re2::RE2::Arg const* const*, int))>::operator()(re2::StringPiece const&, re2::RE2 const&) const':
: undefined reference to `re2::RE2::FullMatchN(re2::StringPiece const&, re2::RE2 const&, re2::RE2::Arg const* const*, int)'
I tried using the "-L" option:
g++ -I /usr/local/include -L/usr/local/lib -libre2 -o test main.cc
But get this error:
/usr/bin/ld: cannot find -libre2.so
Even though the library exists:
$ ls -l /usr/local/lib/libre2*
-rwxr-xr-x 1 root root 9322236 Sep 28 12:00 /usr/local/lib/libre2.a
lrwxr-xr-x 1 root root 15 Sep 28 12:00 /usr/local/lib/libre2.so -> libre2.so.0.0.0
lrwxr-xr-x 1 root root 15 Sep 28 12:00 /usr/local/lib/libre2.so.0 -> libre2.so.0.0.0
-rwxr-xr-x 1 root root 3597784 Sep 28 12:00 /usr/local/lib/libre2.so.0.0.0
Any ideas as to what I'm missing?
A: The -l option means to add a library to link to. So, when you say -libre2, it means "link to the library ibre2", which is probably not what you meant. Use -lre2.
A: update LD_LIBRARY_PATH to include the re2 library path
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Can I avoid Captcha dialog when posting picture using Feed Dialog in iOS SDK? I am using the dialogs in Facebook iOS SDK to allow users's of our app to share a link on their news feed (SDK downloaded today to ensure I have latest version). This was working last week and began behaving differently last Friday after an outage of the API service and a capture dialog is now appearing before the user can post. But the captcha image doesn't load and it says Unknown Error in the top right corner of the captcha dialog which is ugly and seems incorrect.
Has the Facebook API changed recently to now require captcha when posting picture or link? If I remove either picture or link from the params then the post dialog loads fine. I've tried a variety of different urls for my picture or link value and nothing seems to work except removing that param completely which I don't want to do. Can I post a picture or link without the captcha step?
This is my code.
- (void)publishStream:(NSString *)postName caption:(NSString *)caption
{
SBJSON *jsonWriter = [[SBJSON new] autorelease];
NSDictionary* actionLinks = [NSArray arrayWithObjects:[NSDictionary
dictionaryWithObjectsAndKeys:
@"Company Website",
@"name",
@"http://mycompanysiteurl.com",
@"link",
nil], nil];
NSString *actionLinksStr = [jsonWriter stringWithObject:actionLinks];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
kAppId, @"app_id",
@"http://mypictureurl.png", @"picture",
postName, @"name",
caption, @"caption",
actionLinksStr, @"actions",
nil];
[_facebook dialog:@"feed" andParams:params andDelegate:self];
}
I've tried various combinations of permissions when authorizing too with no luck (publish_stream, read_stream, publish_actions, photo_upload).
Not sure if I'm missing something obvious by I've been trying to fix this for days and have not found a solution other than removing the picture or link which is not an option for me due to requirements.
Thanks in advance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is there a way to pause animateWithDuration once it has started? I'm using animateWithDuration method to animate a textView with lyrics to a song that scrolls as the song plays. It works fine, but I included a pause button for the song and obviously when paused the animation continues scrolling. Is there a way to pause this. I looked at the class reference from Apple and saw there were a few delay methods, but those are meant for use before the animation begins. So was just curious if there was a way to pause/restart the animation when the user pauses/unpauses the song. Thanks in advance.
A: You may start a new animation that moves your textView to the current/displayed position with Duration: 0.0f (when pressing the Pause button), it will cancel/skip the previous animation ;-)
A: You could count how much time passed since the start of animation and calculate the offset at the moment of pausing.
There should be a more simpler solution though.
Maybe NSString drawAtPoint in drawRect, using a timer to repeatedly call drawRect to update the position.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Moving A Body With A Texture I am using Farseer Physics Engine to build a "Monster Dash" like game targeted for the PC using C# and XNA,
I am trying to move a body with it's texture, the texture is built from parts so they all should move together, basically it looks like this:
public void Update()
{
tilingFloorPosition.X += (floorMoveSpeed / MeterInPixels);
_tilingFloorBody.Position = tilingFloorPosition;
// Update the textures position
for (int i = 0; i < texturePositions.Length; i++)
{
texturePositions[i].X += floorMoveSpeed;
}
}
But whenever my player lands on top of the floor he just goes through it like there is nothing there, what am I doing wrong?
A: If the player is falling through the floor then I can only assume that either the floor's body isn't actually in position, or the two bodies are not colliding. Can you confirm that the floor is indeed positioned correctly? If you're able, turn on the Farseer Debug View. If so, then the collision must not be occurring.
Check:
*
*That both the player and the floor are not sensors.
*That they are not within the same CollisionCategory and at least one of them is included within the others CollidesWithCategory.
*That you have not added one of the bodies to the others IgnoreBody list.
*That the body types will collide. See: Farseeer Body Types.
Also, it may be worth noting that it is possible that manually setting the position could skip the collision. Try instead setting the LinearVelocity.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does this model test pass on CentOS, but fail on Mac OS X (Lion)? This spec passes just fine on my CentOS development box, but fails when run on my Macbook (10.7).
app/models/issue.rb
class Issue < ActiveRecord::Base
has_attached_file :cover_image,
:styles => {
:thumbnail => ["80x80>"],
:large => ["600x600>"]
},
:path => ":rails_root/public/images/issues/:id/:style_:basename.:extension",
:url => "issues/:id/:style_:basename.:extension"
validates_attachment_content_type :cover_image, :content_type => ['image/jpeg', 'image/png']
attr_protected :cover_image_file_name, :cover_image_content_type, :cover_image_file_size
end
spec/models/issue_spec.rb
require 'spec_helper'
describe Issue do
it 'should not accept invalid image types' do
%w[spec/factories/assets/docs/image.jpg spec/factories/assets/docs/image.txt].each do |file_path| #image.jpg is a text file with a .jpg extension
issue = Factory.build(:issue, :cover_image => File.new(Rails.root + file_path))
issue.should have(2).errors_on(:cover_image)
end
end
end
On my CentOS development box, I get no failures when I run the test. On my Macbook I get this error:
Failure/Error: issue.should have(2)errors_on(:cover_image)
expected 2 errors on :cover_image, got 0
On both machines if I try to create an issue by uploading one of the invalid image types in a browser, it fails with the error message I expect and passes if I use a valid image type.
paperclip-2.4.2
rspec-2.6.0
factory_girl_rails-1.2.0
CentOS: ImageMagick-6.2.8 (yum package)
Mac OS X: ImageMagick-6.7.2-0 (Macports)
A: It seems my whole approach to testing paperclip was off.
Paperclip Shoulda Matchers are working on both machines.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: get Well Known Text from lat long I can get easily a lat,long pair from the Google Maps API:
from googlemaps import GoogleMaps
gmaps = GoogleMaps(GOOGLEMAPS_API_KEY)
gmaps.address_to_latlng('Jose Javier Diaz 440 Cordoba Argentina')
>>>> (-31.4464489, -64.191219899999993)
And I have a model like this:
from django import models
class MaapPoint(models.Model):
geom = models.PointField(srid=DEFAULT_SRID)
But I can't find a way to get the wkt from the latlng returned by gmaps.
Any pointer?
A: In django, contrib.gis there are helpers for this.
>>> from django.contrib.gis.geos import Point
>>> Point(0,1).wkt
'POINT (0.0000000000000000 1.0000000000000000)'
A: Shapely provides a nice API for that:
>>> import shapely
>>> from shapely.wkt import dumps, loads
>>> pt1 = loads('POINT (0.0000000000000000 0.0000000000000000)')
>>> pt1
<shapely.geometry.point.Point object at 0x1011436d0>
>>> dumps(pt1)
'POINT (0.0000000000000000 0.0000000000000000)'
>>> pt3 = shapely.geometry.point.Point(2, 3)
>>> dumps(pt3)
'POINT (2.0000000000000000 3.0000000000000000)'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Reading from a file in android In the following code:
fileInputStream = new FileInputStream(new File(pathToOurFile) );
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Printing buffer is giving some random value, instead of what is there in file. buffersize is properly calculating the size of the file.
Can you tell wat is going wrong?
A: Try this..
private void ReadFile(AssetManager manager, String sourceFileName,
String destinationFileName) throws IOException {
// Read file from AccessManager
InputStream inputStream = manager.open(sourceFileName);
OutputStream outputStream = new FileOutputStream(destinationFileName);
Log.d("-->", "src: " + sourceFileName);
Log.d("-->", "Des: " + destinationFileName);
byte[] buffer = new byte[3072];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
outputStream = null;
inputStream = null;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: how to add static block to magento product description I want to modify the product pages in my Magento store (I'm using version 1.4.2) so that a particular static block is appended to the description. I'm using the easytab system right now, but many of my customers can't find the information that I want to present to them when it's in a tab other than the default tab.
How can I adjust the template so that the static block I want (it's the same for every product) appears on product pages after the description block?
A: You'll need to edit the file /template/catalog/product/view.phtml in your current theme. Find this line:
<?php echo $this->getChildHtml('description') ?>
Then below it add this:
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('extrainformation')->toHtml(); ?>
The 'extrainformation' part being the identifier of the static block you created.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Are there any caveats of using a git repository inside another git repository? Is it considered as a good practice? (I know there are some similar questions but I think none apply exactly to this one, so I decided to ask it.)
I never did repository nesting myself, but I'm in a situation that it would become handy. I just would like to know if there is any kind of know caveat it can cause that later would add difficulties for the main repository administration.
Also, in case it's okay to do that (repositories inside a repository), I would like to know if there is any kind of guide or specific repository configuration to achieve that without later problems.
thanks for reading.
A: As long as the two repositories does not track the same file then you're all good.
Just add the directory where the 'child' repository is in into the .gitignore file of the 'parent' repository so that the parent repository ignores everything inside the child repository.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MSG BOX prob in c# I'm a Beginner in c# so It's not encouraging to me see you voting down on my basic question...
This is a button to show in a message Box the result of my select from my BD.
I get errors : Argument '2': cannot convert from 'object' to 'string',
Argument '3': cannot convert from 'object' to 'System.Windows.Forms.MessageBoxButtons'
Thank's for helping me!
private void Button1Click(object sender, EventArgs e)
{
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "Select id_Client,numéro_Teléphone from Clients";
SqlDataReader thisreader = thisCommand.ExecuteReader();
while (thisreader.Read())
{
MessageBox.Show(thisreader["id_Client"],thisreader["numéro_Teléphone"]);
}
thisreader.Close();
thisConnection.Close();
}
A: Try,
MessageBox.Show(thisreader["id_Client"].ToString() + " " +
thisreader["numéro_Teléphone"].ToString());
Read MSDN doc for more details.
EDIT:
Use System.Text.StringBuilder to append strings.
System.Text.StringBuilder sb=new System.Text.StringBuilder();
while (thisreader.Read())
{
sb.Append("\n" + thisreader["id_Client"].ToString() + " " +
thisreader["numéro_Teléphone"].ToString());
//or
//sb.Append(string.Format("\n{0} {1}",thisreader["id_Client"],thisreader["numéro_Teléphone"]));
}
MessageBox.Show(sb.ToString());
A: Couple things I would add here.
I don't think the call
thisreader["id_Client"].ToString()
is DBNull safe, meaning if the actual value back from the database is NULL this might cause a problem.
Secondly, your connection to the database server will not be closed until a user has clicked through all of the MessageBoxes. That might not be expected behavior. I almost always use a DataTable and a SqlDataAdapter to fill it, that way I know I have all my data back from the server and my connection has been closed so I am not using up extra resources on the server.
Also another things, since you are new to C# your
thisreader.Close();
thisConnection.Close();
might not get executed, you need to either do a
try / catch / finally
or a
using()
statement. Just giving you some best practices stuff to think about.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I hide a vertical scrollbar (without disabling it)? I have a list but want to hide the scrollbar but still keep the functionality. If I put verticalScrollPolicy="off", this disables scrolling via the mousewheel on windows (100% of my users use windows). How can I hide the scrollbar visually but keep the ability to scroll via the keyboard as well as the mousewheel?
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:s="library://ns.adobe.com/flex/spark" height="100%" width="100%">
<s:Group>
<s:List id="listy" width="50%" height="100">
<mx:ArrayCollection>
<fx:String>Flash</fx:String>
<fx:String>Director</fx:String>
<fx:String>Dreamweaver</fx:String>
<fx:String>ColdFusion</fx:String>
<fx:String>Flash</fx:String>
<fx:String>Director</fx:String>
<fx:String>Dreamweaver</fx:String>
<fx:String>ColdFusion</fx:String>
<fx:String>Flash</fx:String>
<fx:String>Director</fx:String>
<fx:String>Dreamweaver</fx:String>
<fx:String>ColdFusion</fx:String>
</mx:ArrayCollection>
</s:List>
</s:Group>
A: I believe the way you'd want to do it to set a custom skin for the List, which then sets a custom skin for the Scroller component within it. In the Scroller skin, you could set the scrollbar as visible=false.
A: Just type:
<s:Scroller id="myScroller" verticalScrollBar="{new VScrollBar()}">
This code solve my problem=)
A: Ive been looking for a solution for this question , and I think it's a problem many people ancounter , so I decided to answer this question although its quite old.
The solution for your problem is real simple. You simply make a custom skin for the scroller and inside the scroller simply set the vertical scroller "alpha" property set to zero
<s:VScrollBar id="verticalScrollBar" visible="false" alpha="0"/>
Hope this will help someone
A: You could use verticalScrollPolicy="off" and create a listener for the mouse scroll event to trigger the scrolling when the mouse is hovering the list.
A: In order to hide scrollbars but still have access to scrolling functionality, you need to create a custom skin and a css style.
*
*Create a custom skin for the VScrollBar with the following settings:
Host Component: spark.components.VScrollBar
Select "Create as copy of:", and select "spark.skins.spark.VScrollBarSkin"
*Edit the "SparkSkin" tag in your custom skin by adding "minWidth="0" minHeight="0" width="0" height="0" alpha="0" visible="false" contentBackgroundAlpha="0""
Original
<s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:fb="http://ns.adobe.com/flashbuilder/2009" minWidth="15" minHeight="35"
alpha.disabled="0.5" alpha.inactive="0.5" >
Customized
<s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:fb="http://ns.adobe.com/flashbuilder/2009" minWidth="0" minHeight="0" width="0" height="0" alpha="0" visible="false" contentBackgroundAlpha="0">
*Then edit your custom skin by adding "alpha="0" visible="false" width="0"" to each of the elements:
Original:
<s:Button id="track" top="16" bottom="15" height="54"
focusEnabled="false" tabEnabled="false"
skinClass="spark.skins.spark.VScrollBarTrackSkin" />
<s:Button id="thumb"
focusEnabled="false" visible.inactive="false" tabEnabled="false"
skinClass="spark.skins.spark.VScrollBarThumbSkin" />
<s:Button id="decrementButton" top="0" enabled.inactive="false"
focusEnabled="false" tabEnabled="false"
skinClass="spark.skins.spark.ScrollBarUpButtonSkin" />
<s:Button id="incrementButton" bottom="0" enabled.inactive="false"
focusEnabled="false" tabEnabled="false"
skinClass="spark.skins.spark.ScrollBarDownButtonSkin" />
Customized:
<s:Button id="track" top="16" bottom="15" height="54" alpha="0" visible="false" width="0"
focusEnabled="false" tabEnabled="false"
skinClass="spark.skins.spark.VScrollBarTrackSkin" />
<s:Button id="thumb" alpha="0" visible="false" width="0"
focusEnabled="false" visible.inactive="false" tabEnabled="false"
skinClass="spark.skins.spark.VScrollBarThumbSkin" />
<s:Button id="decrementButton" top="0" enabled.inactive="false" alpha="0" visible="false" width="0"
focusEnabled="false" tabEnabled="false"
skinClass="spark.skins.spark.ScrollBarUpButtonSkin" />
<s:Button id="incrementButton" bottom="0" enabled.inactive="false" alpha="0" visible="false" width="0"
focusEnabled="false" tabEnabled="false"
skinClass="spark.skins.spark.ScrollBarDownButtonSkin" />
*Add a style to your css (change "assets.skins" to the location of your skin file in your project):
s|List s|VScrollBar {
skinClass: ClassReference("assets.skins.VerticalScrollBarHidden");
}
This style will only apply to List components, so the scroll bar will still be visible for other components. If you want to remove scrollbars altogether, remove "s|List" from the style definition.
*Finally add the stylesheet to your application mxml component (replace "assets/css/Styles.css" with the location of your stylesheet):
<fx:Style source="assets/css/Styles.css"/>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is there a way to make only certain sizes of an image download through css? Basically what I am asking is, is there a way to have say a 1000x1000 pixel image and simply have some sort of code, whether html, css, or anything else to only download a resized verison of 100x100 pixels. Is there any way to do this? I would like to know before resizing each of my pictures and uploading them and linking those photos to the original larger version. Thanks.
A: You can't do it with HTML/CSS but it is possible with a server side language like PHP. Here's a script that will allow you to resize images.
The catch is that resizing images can be a server intensive process. You should try to make sure that once you've created a resized version of an image, it's cached on the server for subsequent requests.
Along those lines, the flow should be:
*
*Image request comes in.
*Does the resized thumbnail exist in the server's cache? If yes, serve the thumbnail.
*If no, create the thumbnail, place it in the server cache and serve it.
Note: James brought up a good point in the comments. If the images you're resizing are going to change (updated/edited), you'll need to keep track of their large image's last modified date when you create the thumbnail (as part of the filename or in a database).
That way, when you check the cache, you'll be able to tell if the thumbnail needs to be regenerated.
A: You can create an account on imageshack.us (create the account to make sure your images don't get deleted) and then upload the image in different sizes and link to whatever size you want. (You don't have to do the resizing yourself, you can do it on imageshack when you upload) That way you get the image in whatever size you want and without putting any load at all on your server.
That's what I do and it works wonderfully
Example:
http://img52.imageshack.us/img52/1825/lakesunset.jpg
http://img12.imageshack.us/img12/6420/lakesunsetf.jpg
Both came directly from imageshack. Just uploaded the image twice and resized one on imageshack.
Then to display the thumbnail and link it to the larger one just use this code:
<a href="DIRECT LARGE IMAGE URL"><img src="DIRECT SMALL IMAGE URL"/></a>
Example:
http://img12.imageshack.us/img12/6420/lakesunsetf.jpg
Sorry, I've never done any server side programming since I'm not a professional and I'm poor, so I can't help you if that's what you're looking for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JQuery Unbind event when removing a class So I have a couple of divs with a class "turn". Then in Jquery I have
$(".turn").click(function(){
...some code...
if (..) $(this).removeClass("turn");
});
which I expect to remove the handler, so I can't click on it anymore. But I still want to be able on the other divs that has that class.
This is not working (I believe is because JQuery doesn't remove the handlers when a class is removed)
I've also tried with
$('.turn?).live(click,...) and $(this).die()
and
$('.turn?).bind()/$(this).unbind()
But neither of those seems to work.
Can I get some hint about how to do this?
Thanks
A: The correct method for this is to use unbind
$(".turn").click(function(){
...some code...
if (..) $(this).unbind("click");
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: translating C++ snippet I am working on porting a framework from C++ to Java, and it is turning out to be harder than I expected, as I don't know a whole lot about C++. I came across this one snippet that I don't really understand. If someone could tell me what the lines marked do that would be awesome.
/** Heap data, stored as a vector */
std::vector< std::pair< _Tp, _Val > > data;
/** Maps objects to their positions in the data vector */
std::map< _Tp, int> mapping;
//I understand that this method takes a pair of type <_Tp, _Val>
template <class _Tp, class _Val>
void Heap<_Tp,_Val>::push(std::pair< _Tp, _Val > x)
{
int index=data.size();
//Here is where I run into trouble
//I can't seem to figure out what this line is doing
//I know it is inserting a Key-Value pair into the map
//but why is .second being called? and what exactly is this if statement
//checking?
if (mapping.insert(std::make_pair(x.first,index)).second)
{
data.push_back(x);
percolate_up(index);
}
}
A:
The insert member function returns a pair whose bool component returns true if an insertion was made and false if the map already contained an element whose key had an equivalent value in the ordering, and whose iterator component returns the address where a new element was inserted or where the element was already located.
So that code is adding an element to the map, and if the element wasn't already there it pushes the data into the vector.
A: The insert member function used here returns a pair<iterator, bool>, where the bool member is true if an insertion was made. So, the if statement is seeing if the insert call actually added a record to the map.
You might find it useful to refer to the documentation of the standard library when working with C++ - here's the MSDN page on map::insert.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Can't find CMake created executable file I am new to Cmake, I was trying to build an executble program from a Fortran code using Cmake-GUI. As per the program instruction I created the Cmakelists.txt. I then launched the Cmake-GUI and nominated the source directory and binaries directory and then used the configure and generate options to create my executable file. Everything seemed to have ran ok. Howover, when I checked my bin folder the .exe file that i was hoping to find is nowhere to be seen, instead I have cmake_Install.cmake and Makefile in the binaries folder. I opened these file with a text editor and they seem to be script file. Can somebody please tell me what I should do with these files to create the executale file. or if this is a sign of the cmake build process failing.
A: I don't know CMake for fortran, but cmake in general will create the makefiles / visual studio projects etc. We cmake into a bin directory, then go in there and run make. It doesn't build the source, it builds the make files.
A: Did you build the source?
CMake just create the makefiles and projects structures to compile using a make tool. I don't know how to compile it for Fortran, but in Linux for a C++ project, I just have to open a terminal, go to the build folder (your bin folder) and run make or make all and it compile the whole project.
I think that your problem is that your project is not compiled, so there is not any binary files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Tab Pages (Signed_Request / OAuth 2.0 / SSL) I just wanted to make sure I understand the requirements of the upcoming October 1st deadline! I know that canvas apps require using OAuth 2.0, I am just wondering if tab pages have to require it? I am just building a fan gateway page and I'm using the signed_request to check if they like the page already, but I have no need for additional permissions, so is authentication/asking for app permissions even necessary?
A: No, you will not need to worry about OAuth 2.0 if you aren't prompting for permissions. You will however need an SSL certificate for your fan page tab.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Test that two function variables point to the same function? How can I test that two function variables point to the same function?
test = lm
test2 = lm
test == lm # error: comparison (1) is possible only for atomic and list types
test == test2 # error: comparison (1) is possible only for atomic and list types
A: Try:
identical(test, lm)
identical(test, test2)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How can I perform SQL ORDER BY exposure, focal and iso (in numeric not string) The columns for Exposure, Focal, and Iso are not being sorted properly. It seems like they are all being interpreted as strings and sorted as such. For example, if I sort Exposure down, the values can look like this:
1/800, 1/800, 1/800, 1/80, 1/675, 1/640, 1/60, 1/500
If I sort the Focal, it can look like this:
1.4, 1.4, 1.4, 14.0, 14.0, 1.3, 13.0, 1.2, 1.2, 12.0, 1.0, 10.0
and if I sort by ISO, it can look like this:
800, 800, 800, 80, 80, 640, 640, 60, 500, 500, 50
EDIT: My other question (and answers) for doing all this in one single sql query.
A: I tested this on Oracle
with
w_data AS(
select '1/800' exposure from dual union all
select '1/80' from dual union all
select '1/675' from dual union all
select '1/640' from dual union all
select '1/500' from dual
)
select *
from w_data
order by 1 / to_number(substr(exposure, 3, length(exposure)))
For focal you do ORDER BY to_number(focal) and the same for ISO.
Note that exposure example will only work if first 2 characters are always '1/'. I can rewrite it for more general case, like '2.9/700', if you wish
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: In jQuery, can I store elements using .data() onto another element for fast retrieval? Can I use the data() function to store a dom element (or a jQuery element) onto another element? (see code below)
Does it store it by value or by reference? Is it good practice?
I want to be able to quickly and easily find the slave element (see code below) of a master element, like so:
$slave = $('.some .path .to .slave');
$master = $('.some .path .to .master');
$master.data('slave', $slave);
$master.click(function (){ $(this).data('slave').toggle() });
(obviously the code is stupid, but I'm actually looping through a lot of master and slave elements.)
A: You can store whatever you want, whether or not you should.
JS variables are references to objects, no? (That's only partially rhetorical–what else would a DOM query return other than a reference? A deep copy?)
A: I know you can do this:
var slavePath=$('.some .path .to .slave');
var master=$('.some .path .to .master').data('slave', slavePath);
master.click(function(){ $($this.data('slave')).toggle()});
Just store the selector to the slave, not the whole object.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Asp.net MVC does not display the template editing I have the classes:
public class PersonDetailsModel
{
public string FistName
{
get;
set;
}
public string LastName
{
get;
set;
}
public string Email
{
get;
set;
}
}
public class RegisterCoupleModel
{
public PersonDetailsModel Groom
{
get;
set;
}
public PersonDetailsModel Bride
{
get;
set;
}
public string UrlKeyword
{
get;
set;
}
public string ReCaptcha
{
get;
set;
}
}
folder Shared > EditorTemplates
PersonDetailsModel.cshtml
@model BindSolution.AndMarried.ViewModel.PersonDetailsModel
<div class="editor-label">
@Html.LabelFor(m => m.FistName)
</div>
<div class="editor-field">
@Html.EditorFor(m => m.FistName)
@Html.ValidationMessageFor(m => m.FistName)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.LastName)
</div>
<div class="editor-field">
@Html.EditorFor(m => m.LastName)
@Html.ValidationMessageFor(m => m.LastName)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.Email)
</div>
<div class="editor-field">
@Html.EditorFor(m => m.Email)
@Html.ValidationMessageFor(m => m.Email)
</div>
In my View:
@Html.EditorForModel()
Only the UrlKeyword and ReCapcha fields are displayed!
Why Asp.net MVC not use templantes in shared folder to display my nested type PersonDetailsModel ?
A: You know, you could have just edited your other question. :)
Anyway, i don't think that will work. You either need to control the entire template yourself, or let MVC do it all itself. (i could be wrong)
Create an editor template for RegisterCoupleModel:
@model BindSolution.AndMarried.ViewModel.RegisterCoupleModel
@Html.EditorFor(model => model.Groom)
@Html.EditorFor(model => model.Bride)
@Html.EditorFor(model => model.UrlKeyword)
@Html.EditorFor(model => model.ReCapcha)
Or you could use a [UIHint("PersonDetailsModel"] attribute on your Groom and Bride properties in your ViewModel.
Read up on the remarks section in EditorForModel for how this all works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Object synchronization method was called from an unsynchronized block of code I receive an exception in production with message "Object synchronization method was called from an unsynchronized block of code" on Mutex.ReleaseMutex() in following code:
Mutex Mutex
{
get { return mutex ?? (mutex = new Mutex(false, mutexName)); }
}
[NonSerialized]
Mutex mutex;
public void Log(/*...*/)
{
Mutex.WaitOne();
try
{
/*...*/
}
finally
{
Mutex.ReleaseMutex();
}
}
There may be saveral processes which can use mutexes with different and same mutextName.
And still I am not sure how that exception can happen there.
A: This code:
Mutex Mutex
{
get { return mutex ?? (mutex = new Mutex(false, mutexName)); }
}
That is not thread safe, more than one Mutex may get created. Using pretend time, let's look at this example:
Thread A | Thread B
-------------------------------------
Enters
Is Null? (yes) Enters
Create Mutex Is Null? (yes) <- Thread A hasn't assigned it yet.
Assign mutex Create Mutex
Use Mutex Assign mutex <- Oops! We just overwrote the mutex thread A created!
Release Mutex <- Oops! We are trying to release the mutex Thread B created without owning it!
Hopefully that illustration isn't garbage.
Using the System.Lazy<T> class is a thread-safe way of doing lazy initialization, if you really want to do that with your mutex.
private Lazy<Mutex> _lazyMutex = new Lazy<Mutex>(() => new Mutex(false, "MyMutex"));
Mutex Mutex
{
get { return _lazyMutex.Value; }
}
Given that, why are you trying to lazy initialize your Mutex? How are you disposing of it?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: A class like UITextView, but with the ability to handle URL clicks I am wondering if there is something already like this out there. But I basically want something like UITextView to display text with embedded links. However, I want to be able to handle the URL clicks as a delegate.
I've read a few posts like the following:
How to intercept click on link in UITextView?
However, I really don't want to override the openURL method. My app works with lots of webServer data, and I don't want to keep creating exceptions for different hosts in the openURL method.
I guess my questions is, is there another way to intercept the click on UITextView?
My alternative is to write my own, with a UIScrollView, and use a TTTAttributedLabel (https://github.com/mattt/TTTAttributedLabel) inside it. But am looking for suggestions, or alternatives.
Thanks.
A: You may use UIWebView + Local HTML instead of UITextView.
And use the -(BOOL )webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType )navigationType delegate to handle the URL clicks,like:
-(BOOL )webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType )navigationType
{
NSURL * clickedURL=[request URL];
//Do something here.
return NO;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What UIKit classes respond usefully to sizeThatFits? Is there a list anywhere of the UIKit classes that respond meaningfully to -(CGSize)sizeThatFits:(CGSize)size (and, by extension, -(void)sizeToFit)?
The UIView docs mention UISwitch and UIImageView. I know UILabel does, but I don't see it documented anywhere.
Trial and error and pray Apple doesn't change their mind? Seems insane.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do you sort numeric values stored in a hashmap then in an ArrayList in Java? I have an ArrayList.
Each element is a HashMap lookup for my values.
1 of the values is numeric.
I'm using Collections.sort() for alpha sorting. But the numbers are getting alpha sorted, instead of numeric sorted.
protected ArrayList<HashMap<String, String>> myAccountList;
String Name = myAccountList.get(i).get("accountName");
Double balance = Double.valueOf(myAccountList.get("accountBalance")); //is a number stored as a string
So I have the sort working on accountName just fine.
Collections.sort(myAccountList, new Comparator(){
public int compare(Object o1, Object o2) {
HashMap<String,String> old1 = (HashMap<String, String>) o1;
HashMap<String,String> old2 = (HashMap<String, String>) o2;
return old1.get("accountName").compareToIgnoreCase(old2.get("accountName"));
}
});
How would I sort the field accountBalance as a number? I doubt it matters, but I'm programming an Android app.
A: It looks like you're using a HashMap where you should design your own class:
public class Account {
public final String name;
public final Double balance;
public Account(String name, Double balance) {
this.name = name;
this.balance = balance;
}
}
(Note: currently this class is immutable. To make it mutable, change the fields from public final to private and add getters/setters)
Then you can store them in a List<Account> and sort accordingly:
//sort by name
Collections.sort(myAccountList, new Comparator<Account>(){
public int compare(Account acc1, Account acc2) {
return acc1.name.compareTo(acc2.name);
}
});
//sort by balance
Collections.sort(myAccountList, new Comparator<Account>(){
public int compare(Account acc1, Account acc2) {
return acc1.balance.compareTo(acc2.balance);
}
});
Note the use of a Comparator with the generic type parameter <Account>, so you don't have to cast the compareTo() arguments from Object.
A: You will have to do something like this:
Double.valueOf(old1.get("accountBalance")).compareTo(Double.valueOf(old2.get("accountBalance")));
To sort by both the account name and balance, you would check if the first compare is 0 (they are equal) and if so, return the accountBalance compare, assuming you are sorting by account name first.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Hot to add a loading class until the form data are returned using jQuery? On submit, I would like to add a .loading class in the #results until the data are returned, so the class is removed.
How does the code change ?
$(function(){
$("#myform").submit(function(event){
event.preventDefault();
$.post('mail.php', $("#myform").serialize(), function(data) {
$('#results').hide().html(data).fadeIn('slow').delay(2000).hide(1);
});
});
});
A: If I understand you correctly:
$(function(){
$("#myform").submit(function(event){
event.preventDefault();
// Add the class here:
$("#results")
.show()
.addClass("loading");
$.post('mail.php', $("#myform").serialize(), function(data) {
$('#results')
.hide()
.html(data)
.fadeIn('slow')
.delay(2000)
.hide(1)
.removeClass("loading"); // Remove the class here.
});
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: jQuery mobile loads a page into DOM even when I don't ask it to Here is the scenario:
(fyi, in the following, when I say 'window.location=...' it is triggered by a button tap)
I have three pages: 1.html, 2.html, 3.html. I navigate following way:
1.html --- window.location="2.html" ---> 2.html
2.html --- <a href="3.html" /> ---> 3.html
click Back button
2.html --- window.location="1.html" --> 1.html
In last step 1.html loads but then contents of 2.html are loaded inside the DOM replacing contents of 1.html so I'm on 1.html but see contents of 2.html.
What is happening? Why does jQuery mobile think that it has to load contents of 2.html?
I'm pretty sure it has to do with history and Back button. If I just navigate between 1.html and 2.html without using Back button, it works.
update Here is code http://jsfiddle.net/x6bxN/ To reproduce you'll want to take code from HTML box and separate it into three separate files.
A: What looks to be happening is you're navigating outside the scope of jQM, but 1.html is in location.hash.
Hash changes that occur independently of a click, such as when a user
clicks the back button, are handled through the hashchange event,
which is bound to the window object using Ben Alman's hashchange
special event plugin (included in jQuery Mobile). When a hash change
occurs (and also when the first page loads), the hashchange event
handler will send the location.hash to the $.mobile.changePage()
function, which in turn either loads or reveals the referenced page.
I assume location.hash has the initial 1.html when it loads but doesn't track the new page while using window.location to navigate to a new page. Since you are using the browser back button jQM uses the last tracked location which in your case is 1.html.
I would suggest using jQM's $.mobile.changePage() if you need to track the location.
More on jQM Navigation can be found in the docs:
*
*http://jquerymobile.com/demos/1.0rc1/docs/pages/page-navmodel.html
*http://jquerymobile.com/demos/1.0rc1/docs/api/events.html
*http://jquerymobile.com/demos/1.0rc1/docs/api/methods.html
A: If you want jQuery mobile to handle the history and back button you need to use $.mobile.changePage to change the page (as opposed to window.location=..).
More info here: http://jquerymobile.com/demos/1.0rc1/docs/api/methods.html
A: Have you tried to specifically set data-ajax="false" on your links? Or rel="external", although this is supposed to only be used if you want to change to another domain.
If you don't set either one, I'm afraid JQM hijacks.
Try if it works with data-ajax="false".
Actually I have a similar issue with regular JQM-Ajax-links. I want pages to load via Ajax, but if I do like this:
*
*go to page1
*go to page2a
*go to page2b = reloads page1...
Very annoying and I already filed an issue on Github, but since you don't want to use Ajax you should be ok.
Let me know if it works.
A: a wild guess. you didn't hardcode css class ui-page-active into the .ui-page element right? becuase that would cause both page to appear.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Play an Audio File and Pause at Various Times on iOS Say that I have an audio file and an collection of time information about particular segments of that audio file, namely their startTime and endTime. What I would like to do is play the audio file sequentially, starting at the beginning and moving segment by segment through the file.
So, for example, let's say that I have data like the following:
Segment 1 - startTime: 1.0s, endTime: 3.4s
Segment 2 - startTime: 3.4s, endTime: 5.0s
Segment 3 - startTime: 7.8s, endTime: 9.5s
...
I want to play through the audio file sequentially, segment by segment. It will start 1.0s into the file, play until 3.4s, then pause and wait for the user to press a button. Once the user presses the button, it will play from 3.4s to 5.0s, then from 7.8s to 9.5s, etc...
The user will also have the possibility to 'scrub' the audio (but not inside the gaps in-between segments), so although I am playing through sequentially, the possibility exists of returning to a previous segment, in which case this process will repeat (ie. if the user scrubs to a previous or later segment it will pause when it reaches the end of that segment).
What is the best way to accomplish this goal? It seems that I can use AVAudioPlayer, but I don't see a way to pause it exactly at the endTime, other than polling the currentTime repeatedly. AVPlayer and AVPlayerItem looks like another possibility, but if I understand the documentation, there is only one player item at a time...so I suppose I will need to handle replacing AVPlayerItems in order to make the scrubbing function work.
Are there any suggestions about how to best accomplish this goal?
A: Off the top of my head, either breakup the file into individual segments and play them at the desired time, or pause them using the AVAudioPlayer's function [(name of your audio player) pause]; then resume play when the button's touch up inside fires with [(name of our audio player) play];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Adding name attribute results in ID value becoming property of the document object in IE and Opera? Consider this HTML source code:
<form id="foo1" name="x"> Form 1 </form>
<form id="foo2"> Form 2 </form>
As you can see, we define two FORM elements.
In Chrome, Safari and Firefox, both document.foo1 and document.foo2 return undefined.
However, in IE and Opera, document.foo1 returns a reference to the corresponding FORM element, whereas document.foo2 returns undefined.
Live demo: http://jsfiddle.net/zrmEm/2/
So, the first form does have its ID-named property in the document object, and the second form doesn't. And this difference is the result of adding the name attribute to the first form.
Now, where's the logic in that? Is this a known behavior?
A: In all browsers, the value of a form's name attribute is added as a property of the document object, and also as a property of the document.forms collection.
If you are using ids, the values are added only as properties of the forms collection.
IE was always confused about name and id attributes. In IE (version 8 tested), the id is added a property of the document only if there is also a name for that form (it might be the same or different to the id).
So if you always use document.forms['name-or-id'] then life is sweet. As long as you don't have forms with names that are the same as other forms with ids, then all bets are off.
A: This is basically a quirk that Microsoft introduced way back in the dark days of the browser wars. (circa IE4)
The end result is that in IE, forms would be added as variables to the document scope, so that you could reference them as document.form1.
This was non-standard, but that didn't really seem to matter back then (at least not to the browser vendors).
Many of the non-standard features that were added at the time to one browser or another ended up being implemented by the others, became de-facto standards, and eventually ended up as official standards.
This particular feature, however, did not. It remains non-standard.
Microsoft have retained most of their old non-standard functionality even in newer versions of their browser, in an effort to retain backward compatibility for old code (many corporate intranets were written by Microsoft-trained 'experts', and use these features, so they need to keep them, otherwise no-one will ever upgrade past IE6).
Back in those days, Opera was the young pretender in the browser world. It was updated often, had innovative features, and ran much quicker than the competition. They were doing back then for the browser world what Chrome has been doing more recently.
However because of the escalating standards war, the only way Opera could compete was by being compatible, and they went to great lengths to reverse-engineer all the features (and even in some cases the bugs) in IE so that sites written for IE would also work in Opera.
This was clearly one of those features, and this is why IE and Opera both share the same quirk today.
The other browsers on the market today do not have the same history. Firefox is ultimately derived from Netscape Navigator, so while it may have its own quirks dating back to those days, but it won't share IE's. And the webkit browsers have a much more recent provenance (it is derived from the KDE Project's KHTML engine), so again it never had the history where it was trying to emulate IE's quirks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Can everyone resize their iframe the way CityVille does? CityVille seems to have a version of the FB API that allows them to go 100% width/height within a Facebook iframe. Is this only for them? How can this be achieved?
Thanks!
A: Have you tried the following javascript ?
FB.Canvas.setSize({ width: 600, height: 880 });
but before that you will need to go to the apps settings under advance tab and change your canvas option
A: They've finally opened up fluid canvas size to everyone.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Want to Transfer Remove image to Image hosting site I try to find a solution to transfer image to remove server with php..
For Example i have image http://example.com/image.jpg.. and want to transfer this link/file to http://postimage.org or any other image hosting service.. if you have any solution in PHP Please let me know..
EDIT:
After transfer image file its shows me the download link.. Special for http://postimage.org site..
Thanks,
A: Post image has an upload from url feature:
http://postimage.org/index.php?um=url
Enter the url to your image there and submit.
A: This is a very open question, but I'll try to answer it.
If you want to upload pictures to a image hosting site, you need to search for one that has an API.
I would recommend imgur for starting.
It has free (limited) access to its API by just registering and it is very simple to use.
Read about it here.
It even has an example for uploading images in PHP:
<?
$filename = "image.jpg";
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
// $data is file data
$pvars = array('image' => base64_encode($data), 'key' => IMGUR_API_KEY);
$timeout = 30;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/upload.xml');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$xml = curl_exec($curl);
curl_close ($curl);
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: ImageView on tableViewCell doesnt appear? I have a tableView and you can add cells. and it doesnt show my image on the left hand side of the newly added cells. I'm using the default cell style and here is my code:
This is the button that allows us to add a cell.
- (IBAction)outlet1:(id)sender {
[cart.cells addObject:@"1"];
cart.cell.imageView.image = [UIImage imageNamed:@"paddle1.png"];
}
Please help! I checked the name of the image and it seems good. Thanks!
A: It would be better to place the image to the UITableViewCell inside the cellForRowAtIndexPath method, by setting the image to cell.imageView.image
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Remove everything but the domain with PHP My current js formula removes http://, https://, www and anything after '/'.
function cleanUrl(url) {
return url.replace(/^(http(s)?:\/\/)?(www\.)?/gi,"");
}
E.G:
http://www.google.com/piza
returns google.com
How can I do remove everything but the domain in one step but with PHP?
A: Use parse_url().
$domain = parse_url($url, PHP_URL_HOST);
Do note that www.example.com and example.com are technically entirely separate entities that can point at totally different sets of records.
A: You could use preg_replace with your current regex and get the same result:
http://php.net/manual/en/function.preg-replace.php
A: The function parse_url() is quite powerful, and the example usage from php.net will shed some light on what kinds of things you can do with it:
<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH);
?>
The above example will output:
Array
(
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
)
A: You can combine the regex you have (with a little modification) and Use parse_url()Docs to do the main work:
function cleanUrl($url) {
return preg_replace('/^(www\.)?/i',"", parse_url($url, PHP_URL_HOST));
}
As ceejayoz wrote, you might want to keep www. as part of the domain name.
A: There is a much easier way ;)
<?php
echo $_SERVER['HTTP_HOST']
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Installing .deb from MobileSafari Does anyone know how to make .deb files install directly from MobileSafari on the iPhone/iPod touch/iPad? I know it's possible, as seen with the 'lima' project, but I have no idea what it's supposed to be written in, or how. If someone could tell me I'd be grateful. Thanks in advance.
A: While this is not a detailed answer to your question, it shows the way on doing it:
1st: A download plugin for MobileSafari to actually download the .deb
2nd: Once the download has been completed you execute dpkg -i /path/to/package.deb (for example via system()
But this won't take care about dependencies and other things which is important when dealing with DEBIAN packages. For that you'll have to utilize the apt library like Cydia does.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Configuring network settings in Google TV emulator Can anyone please help me in configuring proxy settings on my google tv emulator? In other Android emulators,we have an option to set the proxy and port in the Network settings. Couldn't find a similar one in Google TV emulator.
I am totally stuck at this part. Don't know how to configure network settings in GTV emulator.
Any help is greatly appreciated.
A: You can control the network settings by including specific parameters when you run the emulator. These parameters are described at:
http://developer.android.com/guide/developing/devices/emulator.html#emulatornetworking
HTTP proxy settings are available.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android: onDraw method using DrawPoint() causing jitter and distortion on canvas I am developing an app which draws more or less a two-dimensional matrix of values to a canvas. The values of this matrix are scaled to Alpha levels to illustrate intensity, and the coordinates for the matrix are simply extrapolated from row and column indexes. Below is my onDraw routine.
public void onDraw(Canvas canvas, float [][] spectrum, float nsegs,int seglen) {
//canvas.translate(0,0);
//alpha = 0;
int canHeight = canvas.getHeight();
int canWidth = canvas.getWidth();
//float[] array = generateData(512);
float [] spec = new float[seglen];
final float bw = (float)(canWidth-2)/nsegs;
final float bh = (float)(canHeight-2)/(float) seglen;
for (int i = 0;i<seglen;i++){
spec[i] = spectrum[i][index]; // One column at a time
}
float max = maxVal(spec);
float min = minVal(spec);
xcoor = index;
for (int n = 0; n < seglen; n++){
//Scale value to alpha (0-255)
alpha =(int)Math.round((((spec[n] - min)/max)*255.0));
ycoor = n;
paint.setAlpha(alpha);
canvas.drawPoint(xcoor,ycoor, paint);
}
index = (int) (index +1);
if (index == nsegs-1){
index = 0;
}
}
Here paint configuration is pre-defined as:
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
paint.setStrokeWidth(2);
This program draws one pixel at a time, fills one column of pixels equal to the number of elements in a column of the matrix. Then it starts on the next column, where the previous column is still displayed and so forth. At this stage when all columns are full it stars from the first column again, drawing on top of previous elements.
The Problem: The tailing columns although already drawn appear to flicker and jump around, as does the Alpha. I have attempted to canvas.save() and canvas.restore() to capture the entire canvas and restore it after a column is printed. I have double checked all my row and column indexing and alpha vales to ensure the coordinates increment as per desired (and they do). This is very similar to the sample APIdemo DrawPoints.java, however there are three primary differences.
*
*I am using DrawPoint not DrawPoints, and
*I don't use "canvas.setColour" as it removes the tailing columns from the canvas.
*This onDraw function is operating in a Thread which extends SurfaceView
Any idea's would be much appreciated, thank you for your time.
A: In the case above, I was using a SurfaceView instead of a View. Out of the Android dev docs
Note: On each pass you retrieve the Canvas from the SurfaceHolder, the previous state of the Canvas will be retained. In order to properly animate your graphics, you must re-paint the entire surface. For example, you can clear the previous state of the Canvas by filling in a color with drawColor() or setting a background image with drawBitmap(). Otherwise, you will see traces of the drawings you previously performed.
The Solution, re-draw the entire canvas each time to prevent the jitter.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: show different controllers for one tab depending on some condition When user taps on Favourites tab, I need to show:
*
*Introduction of how to add favourite, if there is no favourite
*Otherwise show the list of favourites
So when user taps on the tab button, I need to check if there is any favourite then decide which controller to use, how do I do this?
Thanks!
A: If the introduction is static, with no significant user interaction, you can place the introduction into a subview that is on top in the view containing the list of favorites. Set its frame size to cover up the favorites list. (It will be dismissed by the user with the code below.) Call this the introductionView. One way to put the introductionView on top is to add that subview last when you create the list-of-favorites view.
In your view controller for your list of favorites, go to viewWillAppear and add these lines:
(If there are already favorites, this assumes the user has been through the introduction.)
if (*some test whether there are already favorites on the list*)
introductionView.hidden = YES;
else
introductionView.hidden = NO;
Add some code to run when the user presses the dismiss button
- (void) dismissHit{
introductionView.hidden = YES;
}
This will always show the introductionView when the favorites tab is hit, unless there are some favorites already on the list. Read the UIView class reference and the UIViewController class reference. Look at the methods listed to get a better feel what this is doing.
Good luck.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Python ConfigParser interpolation from foreign section With Python ConfigParser, is it possible to use interpolation across foreign sections? My mind seems to tell me I've seen that it's possible somewhere, but I can't find it when searching.
This example doesn't work, but it's to give an idea of what I'm trying to do.
[section1]
root = /usr
[section2]
root = /usr/local
[section3]
dir1 = $(section1:root)/bin
dir2 = $(section2:root)/bin
Note that I'm using Python 2.4.
A: You do have access to the special-case [DEFAULT] section. Values defined here can be accessed via interpolation from other sections even for older versions of Python.
A: In python 3.2 and up this is perfectly valid:
[Common]
home_dir: /Users
library_dir: /Library
system_dir: /System
macports_dir: /opt/local
[Frameworks]
Python: 3.2
path: ${Common:system_dir}/Library/Frameworks/
[Arthur]
nickname: Two Sheds
last_name: Jackson
my_dir: ${Common:home_dir}/twosheds
my_pictures: ${my_dir}/Pictures
python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
Edit:
I just saw that you are using python 2.4, so no, section interpolation cannot be done in python 2.4. It was introduced in python 3.2 - See section 13.2.5 - ConfigParser Interpolation of values.
class configparser.ExtendedInterpolation
An alternative handler
for interpolation which implements a more advanced syntax, used for
instance in zc.buildout. Extended interpolation is using
${section:option} to denote a value from a foreign section.
Interpolation can span multiple levels. For convenience, if the
section: part is omitted, interpolation defaults to the current
section (and possibly the default values from the special section).
For example, the configuration specified above with basic
interpolation, would look like this with extended interpolation:
[Paths]
home_dir: /Users
my_dir: ${home_dir}/lumberjack
my_pictures: ${my_dir}/Pictures
Values from other sections can be fetched as well:
[Common]
home_dir: /Users
library_dir: /Library
system_dir: /System
macports_dir: /opt/local
[Frameworks]
Python: 3.2
path: ${Common:system_dir}/Library/Frameworks/
[Arthur]
nickname: Two Sheds
last_name: Jackson
my_dir: ${Common:home_dir}/twosheds
my_pictures: ${my_dir}/Pictures
python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
A: If you're stuck with python 2.7 and you need to do cross-section interpolation it is easy enough to do this by hand using regexps.
Here is the code:
INTERPOLATION_RE = re.compile(r"\$\{(?:(?P<section>[^:]+):)?(?P<key>[^}]+)\}")
def load_something_from_cp(cp, section="section"):
result = []
def interpolate_func(match):
d = match.groupdict()
section = d.get('section', section)
key = d.get('key')
return cp.get(section, key)
for k, v in cp.items(section):
v = re.sub(INTERPOLATION_RE, interpolate_func, v)
result.append(
(v, k)
)
return result
Caveeats:
*
*There is no recursion in interpolation
*When parsing many sections, youll need to somehow guess current section.
A: I have run into this in the project I'm working on right now, and I implemented a quick extension to the ConfigParser.SafeConfigParser class in which I have overwritten the get() function. I thought some may find it useful.
import re
import ConfigParser
class ExtParser(ConfigParser.SafeConfigParser):
#implementing extended interpolation
def __init__(self, *args, **kwargs):
self.cur_depth = 0
ConfigParser.SafeConfigParser.__init__(self, *args, **kwargs)
def get(self, section, option, raw=False, vars=None):
r_opt = ConfigParser.SafeConfigParser.get(self, section, option, raw=True, vars=vars)
if raw:
return r_opt
ret = r_opt
re_oldintp = r'%\((\w*)\)s'
re_newintp = r'\$\{(\w*):(\w*)\}'
m_new = re.findall(re_newintp, r_opt)
if m_new:
for f_section, f_option in m_new:
self.cur_depth = self.cur_depth + 1
if self.cur_depth < ConfigParser.MAX_INTERPOLATION_DEPTH:
sub = self.get(f_section, f_option, vars=vars)
ret = ret.replace('${{{0}:{1}}}'.format(f_section, f_option), sub)
else:
raise ConfigParser.InterpolationDepthError, (option, section, r_opt)
m_old = re.findall(re_oldintp, r_opt)
if m_old:
for l_option in m_old:
self.cur_depth = self.cur_depth + 1
if self.cur_depth < ConfigParser.MAX_INTERPOLATION_DEPTH:
sub = self.get(section, l_option, vars=vars)
ret = ret.replace('%({0})s'.format(l_option), sub)
else:
raise ConfigParser.InterpolationDepthError, (option, section, r_opt)
self.cur_depth = self.cur_depth - 1
return ret
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: LazyLoading images into a Gallery If you check out this answer.
Lazy load of images in ListView
Fedor has provided a tutorial on how to lazy load with image view.
But he said it can be used with Gallery with minor modifications.
How do i go about doing this with minor modifications?
Ive Tried this so far.
This is the BaseAdapter
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private String[] data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, String[] d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item, null);
TextView text=(TextView)vi.findViewById(R.id.text);;
ImageView image=new ImageView(this.activity);
text.setText("item "+position);
imageLoader.DisplayImage(data[position], activity, image);
return vi;
}
}
And then in my activity i do this..
LazyAdapter adapter=new LazyAdapter(MainMenu.this, myRemoteImages);
((Gallery) findViewById(R.id.gallery))
.setAdapter(adapter);
It doesnt seem to be working though.
Nothing is showing up
A: Here is something that I managed to work out. After implementing Fedor's code in a GridView, you must be aware that in the ImageLoader class file there is a class named decodeFile(). In that class Fedor's code automatically resizez the image so that it can become a small thumbnail. You have just to comment the "rescaling" part and your image will appear in full in the GalleryView.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to include files relative to the current executing script in psql? I have a PostgreSQL script (say, MAIN.sql in ~/sql/) which has lines like
\i components/helper-functions.sql
This include works fine if the $PWD is the same as the directory of my script (~/sql/), but if it is not, it looks for the included file relative to the $PWD instead of relative to MAIN.sql.
So if I call the script from ~/, it would look for ~/components/helper-functions.sql and not for ~/sql/components/helper-functions.sql.
I think a new \ir directive is going to be included in 9.2 for exactly this problem, but I'm running 8.3
A: Pass the directory name in as a psql variable and use that to assemble the absolute path to included files, e.g.,
$ cat ./tmp/foo.sql
\echo 'This is foo.'
\set abs_bar_sql :DIR '/bar.sql'
\i :abs_bar_sql
$ cat ./tmp/bar.sql
\echo 'This is bar.'
$ psql -f ./tmp/foo.sql -v DIR=$PWD/tmp
This is foo.
This is bar.
It's not pretty, but that's why \ir is being added after all.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: CSS3 Animation Scale Not Working as Expected in Safari The desired effect is working in Firefox and Chrome, but not Safari.
The Animation is to behave as follows:
*
*Pan Immediately to the left
*Zoom in
*Slowly Pan to the right
*Zoom out
These all work fine except that in Safari, there is no Zooming Out.
I can't for the life of me figure out why.
Please, any help is appreciated.
#frame {
position:relative;
width:660px;
margin:5% auto 0;
height:177px;
border:1px solid #999;
overflow:hidden;
-webkit-transform:scale(.5);
}
.paper {
position:absolute;
top:0;
left:0;
width:660px;
height:177px;
}
.scribble {
position:absolute;
top:0;
left:0;
width:0;
height:177px;
}
.green {
background:url(scribble1.png) no-repeat 0 0;
top:0;
}
.red {
background:url(scribble2.png) no-repeat 0 0;
top:45px;
}
.blue {
background:url(scribble3.png) no-repeat 0 0;
top:82px;
}
/*
* Add Zoom-in Routine
*
*/
@-webkit-keyframes zoomin {
0% {
-webkit-transform: scale(1);
}
100% {
-webkit-transform: scale(2);
}
}
/*
* Add Zoom-out Routine
*
*/
@-webkit-keyframes zoomout {
0% {
-webkit-transform: scale(2);
}
100% {
-webkit-transform: scale(1);
}
}
/*
* Add Pan Routine
*
*/
@-webkit-keyframes pan {
0% {
left:660px;
}
50% {
left:-80px;
}
100% {
left:0;
}
}
/*
* Add Draw Routine
*
*/
@-webkit-keyframes draw {
0% {
width:0;
}
100% {
width:660px;
}
}
/*
* Begin Animation
*
*/
.paper {
-webkit-animation:
pan 10s ease-out,
zoomin 3s ease,
zoomout 5s 5s ease;
-webkit-animation-fill-mode:forwards;
}
.green {
-webkit-animation:draw 10s ease;
-webkit-animation-fill-mode:forwards;
}
.red {
-webkit-animation:draw 9s linear;
-webkit-animation-fill-mode:forwards;
}
.blue {
-webkit-animation:draw 8s ease-in-out;
-webkit-animation-delay:2s;
-webkit-animation-fill-mode:forwards;
}
<body>
<div id="frame">
<div class="paper">
<div class="scribble blue"></div>
<div class="scribble green"></div>
<div class="scribble red"></div>
</div>
</div>
</body>
</html>
The demonstration and live Code can be viewed at: http://blindmikey.com/dev/animation/scribbles2.php
A: I had a similar problem and found my answer here: Safari: Absolutely positioned DIVs not moving when updated via DOM
In short, set the transform style in a setTimeout() by itself for Safari 5.1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is there a way to turn off implicit type conversion in SQL Server? As the title indicates:
Is there a way to turn off implicit type conversion in SQL Server?
I want the following simple SQL to generate an error
SELECT 'a' WHERE 1='1'
A: There is no way to disable it.
It has been requested though: see the proposed SET OPTION STRICT ON MS Connect request which comes from Erland Sommarskog
However, it is utterly predictable according to datatype precedence rules
Your example of a foreign key is interesting because an actual FOREIGN KEY constraint requires the same datatype, length and collation.
A: There is no way to disable the implicit conversions in SQL server, though some searching will show that it is something a number of people have asked for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: convert datetime to string in PHP I am getting my datetime using this function
function wilTime($frmt,$tz){
$date = date_create(date($frmt));
date_timezone_set($date, timezone_open($tz));
return date_format($date, $frmt);
}
the first parameter of the function is the format and the second one is the timezone is. All I want is to convert it to String so I can using strstr() function with it so I can get the date and the time separately.
I tried using the strstr() with the return of this function but it does not show anything.
Thanks for any help =)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Validation of dates based on the user inputs Given the Following code,how can I trap a function where in it would only allow a user a certain range of date to choose from the datepicker.
Ex.
If the user chooses the Monthly on the dropdown, it would only allow the user a range of 28 days. if the user chooses a Weekly, the system would only allow 5 days, and Daily for only 2days...
Scenario1:
Date from: 2011-09-01
Date to: 2011-09-31
Result: (prompt) you are only allowed to input within 28 days.
Scenario2:
Date from: 2011-09-01
Date to: 2011-09-20
Result: it will proceed to another page.
If the user chooses an invalid selection, the system will prompt.
Thanks in advance.
<select size="1" name="duration" id="duration" style="position:relative; top:-212px; left:-440px; width:100px;">
<option value="0">Monthly</option>
<option value="1">Weekly</option>
<option value="2">Daily</option>
</select>
</dd>
</dl>
<dl>
<dt style="float:left;"><label for="fname" id = "label">Date From:</label></dt>
<dd><input type="text" name="timestamp" id="calendar1" class="calendarFocus" size="54"/>
</dd>
</dl>
<dl>
<dt style="float:left;"><label for="fname" id ="label">Date To:</label></dt>
<dd><input type="text" name="timestamp1" id="calendar2" class="calendarFocus" size="54"/>
</dd>
</dl>
A: Add an onchange event call to a Javascript function with your business logic.
<select onchange="callYourFunction(this)" ...>
In the function you would then do something like this:
<script type="text/javascript">
function callYourFunction(oe) {
The Javascript function would then check the value of the select dropdown (oe is the object), and prompt using alerts().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Come October 1st, can I iframe non-SSL sites within my SSL-Enabled FB App? Since FB is requiring all iframed apps to be hosted under SSL come October 1st, how will this affect people like me who have apps that iframe content from non-SSL domains?
For example:
My app domain is: https://myfbapp.com/appfolder
In my index.php file in my /appfolder, I have images and iframed sites that aren't SSL. For example, I might have a couple of images embedded on my site that are from tinypic. Since they use a non-SSL format for their pictures, what would happen?
This question applies to all non-SSL content being embedded or iframed on your SSL enabled app domain/folder.
A: I believe Facebook will just be checking for the ssl cert. However, your browser may complain about the mixture of secure and unsecure items when then they are served in this way.
A: Hey i hope this link help you
Facebook Secure Browsing (HTTPS), iFrame Tabs & Mixed Content Warnings
*Files that MUST Be HTTPS to Avoid the Mixed Secure and Nonsecure Content Warning:
Images — <img /> tag;
External CSS (.css) and JavaScript (.js) files
or put the images in same directory appfolder and relative link.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605148",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Retrieving old builds for re-deployment in Jenkins I have built an automated deployment system using Jenkins, Subversion and ANT on a set of environments. It all works, allowing me to deploy old tagged releases to a set of environments or automatically deploy the latest build using the Subversion Release Manager within Jenkins.
The problem is on the client site, we have to utilise Perforce (which does not currently have a Release Manager plugin within Jenkins [don't really want to write one, but possible]). What is the best way to setup up Jenkins to be able to deploy certain releases to environments? I started looking at Ivy and Artifactory as a possibility.
If anyone has any suggestions, or any guides online, that would be great!
A: We currently build a WAR file for each Subversion checkin - and make this available with the copy artifact plugin. Redeploy is merely a matter of executing the deploy task for this WAR.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Widget CSS being interfered with by external page CSS Just created a javascript widget that injects the content on the 3rd party site using DOM. I include a css file with the widget. However, I keep running into instances where the external pages css will interfere with the widget css and add something weird like a background image or border too my widget elements that I don't have defined in my css. Any easy way to go around this? I've already added
!important
to all the css rules. Thanks!!
A: As in my opinion, I, with no doubt, say that in the external css, not the widget css, have added something that would add the border or background to ALL divs. You might want to check that out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does a vector have to store the size twice? This is a rather academic question, I realise it matters little regarding optimization, but it is just out of interest.
From what I understand, when you call new[size], additional space is allocated to store the size of the allocated array. This is so when delete [] is called, it is known how much space can be freed.
What I've done is written how I think a vector would roughly be implemented:
#include <cstddef>
template <class T>
class Vector
{
public:
struct VectorStorage
{
std::size_t size;
T data[];
};
Vector(std::size_t size) : storage(new VectorStorage[size])
{
storage->size = size;
}
std::size_t size()
{
return storage->size;
}
~Vector()
{
delete[] storage;
}
private:
VectorStorage* storage;
};
As far as I can tell, size is stored twice. Once in the VectorStorage object directly (as it needs to be so the size() function can work) but again in a hidden way by the compiler, so delete[] can work.
It seems like size is stored twice. Is this the case and unavoidable, or is there a way to ensure that the size is only stored once?
A: Vectors don't usually store the size. The usual implementation keeps a pointer past the end of the last element and one past the end of the allocated memory, since one can reserve space without actually storing elements in it. However, there is no standard way to access the size stored by new (which may not be stored to begin with), so some duplication is usually needed.
A: Yes. But that's an implementation detail of the heap allocator that the compiler knows nothing about. It is almost certainly not the same as the capacity of the vector since the vector is only interested in the number of elements, not the number of bytes. And a heap block tends to have extra overhead for its own purposes.
A: std::vector does not allocate memory; std::allocator, or whatever allocator you give the vector, is what allocates the memory. The allocator interface is given the number of items to allocate/deallocate, so it is not required to actually store that.
A: You have size in the wrong place -- you're storing it with every element (by virtue of an array of VectorStorage), which also contains an array (per instance of VectorStorage) of T. Do you really mean to have an array inside an array like that? You're never cleaning up your array of T in your destructor either.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Can't find html table on source code of a website I'm a member in a website and there's a huge (automatically generated) HTML table on this PHP page that is only available to me and I wanted the table source code because I want to copy it to a HTML page on my computer to then process it with a program.
The problem is that when I right-click to display the page source code it works. However, I'm tired of looking at the source code and inside all the linked JavaScript files. I can't seem to find the table or any data of it on the scripts/page source codes.
I can select the table data and copy it, but it is just the data. It doesn't say anything about flash, so I'm assuming it's not flash. The data of the scripts/pages isn't obfuscated, it's easily human-readable.
I used Google Chrome's 'inspect element' and it worked.
I was thinking on doing a PHP script that would import data from a similar table, but I will have to know more about a lot of stuff mentioned here.
What can I be doing wrong or what can cause this kind of behavior?
A: Two possible reasons could be that the table may be returned from an AJAX call to another page that returns the HTML for the table, or they could be generating the table's html code and contents on the fly from a list of values coming from javascript or some other source rather than serving the HTML output to you from the server side.
Something you can do to figure it out is see if there are any empty div or other html elements where the table appears to be inserted, and search their javascript files for references to those elements. That may shed some light on how they populate it.
Feel free to update your question with the raw html (where you don't see the table) and maybe some javascript and we can look. Use pastebin if it is a lot of content.
A: Would it help to use the Firefox plugin called Firebug?
Using this plugin you can click on an area of a page to see the code displayed in the Firebug section at the bottom of your window.
Here are the details: https://getfirebug.com/whatisfirebug
A: Maybe the table is generated with a JS script, if that's the case, doing right click and "View source" would not show you the html. You need to use something like Chrome's devtools. Open google chrome and visit that page, once there, right click the table and select "Inspect element", the devtools will open and then you'll see the table's code, right click it's opening tag and select "Copy as html".
Let me know if that works :)
A: Try a developer extension like http://getfirebug.com/ The underlying source code may not reflect output due to how much the DOM can be modified by javascript with extensive use of ajax. This plugin will permit you to view elements as they're interacting with the browser.
A: its probably that the table is dynamically generated on the fly so looking at the source code won't actually give you much. try looking at the "GENERATED" source code or inspecting the DOM using Firebug, or the Developer tools of chrome/safari.
Or better yet, try your hand at web scraping:
http://vancouverdata.blogspot.com/2011/02/how-to-web-scraping-xpath-html-google.html
Although I'm not sure if it'll work for pages that need a login. But hey, at least you learned something new :p
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Field 'user_data' doesn't have a default value in CI 2.0.3 I used CI's user guide to create my session table.
CREATE TABLE IF NOT EXISTS `sessions` (
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(16) DEFAULT '0' NOT NULL,
user_agent varchar(120) NOT NULL,
last_activity int(10) unsigned DEFAULT 0 NOT NULL,
user_data text NOT NULL,
PRIMARY KEY (session_id),
KEY `last_activity_idx` (`last_activity`)
);
This error shows whenever I have $db['default']['stricton'] = TRUE in my database.php
Error Number: 1364
Field 'user_data' doesn't have a default value
INSERT INTO sessions (session_id, ip_address, user_agent,
last_activity) VALUES ('2b92823888c4c5eb4b5b2ae25282ce9e',
'192.168.1.4', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1
(KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1', 1317346730)
Filename: libraries/Session.php
Line Number: 327
However, I want to enforce strict SQL.
A: From the reference - BLOB and TEXT columns cannot have DEFAULT values.
The BLOB and TEXT Types
You should add user_data field in your INSERT statement.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Implement right-clicking context menu using PopupControlExtender? Is it possible to implement a context menu which appears when users perform a right-click on an item of interest using the PopupControlExtender?
From investigations so far, it seems like the PopupControlExtender only works with left-clicks or the other choices are to write your own control or implement the entire solution in jQuery.
If it is possible to do a right-click with the PopupControlExtender, may I get some code examples?
A: Just have a hidden button on the form for the PopupControlExtender, then capture the right click and call document.getElementById('bla').click();
JS:
$('#element').mousedown(function(event) {
switch (event.which) {
case 1:
//alert('Left mouse button pressed');
break;
case 2:
//alert('Middle mouse button pressed');
break;
case 3:
document.getElementById('bla').click();
break;
default:
//alert('You have a strange mouse');
}
});
Markup:
<asp:button id="bla" runat="sever" style="display:none"/>
.....PopupControlExtender code...etc
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: form_tag action not working in rails I have this form in my application.html.erb.
<%= form_tag(:action=>"index", :controller=>"posts") %>
<p>
// code here
</p>
I dont understand why is this getting directed to posts->create instead of posts->index?
Thanks.
A: You seem to be a little mixed up with respect to the uses for each action. Here's a quick summary of typical RESTful usage:
Index -> view a list of items
New/Edit -> form where items are added or edited
Create/update -> controller action where items are created/updated
The reason your routes file is not taking you to index is because index is not an action where posts are typically created or updated. The best way is to go RESTful. Unless you have a very unusual situation, the best way to set your system up is probably a little like this:
# routes.rb
resources :posts
# application.html.erb (or better: posts/_form.html.erb).
<% form_for @post do |f| %>
<% end %>
# posts controller, whichever action you want to use
def new
@post = Post.new
end
By putting the form in a partial called form you can access it in new, edit, or wherever else you need to manipulate a post in your system.
A: Basically, Rails observes and obeys "RESTful" web service architecture. With REST and Rails, there are seven different ways to interact with a server regarding a resource. With your current code, specifying the form's action as index doesn't make sense: Rails' form helpers can either POST, PUT or DELETE.
If you wanted to create a post, then redirect to the index, you can do so in the applicable controller action:
class PostsController < ApplicationController
...
def create
@post = Post.new
respond_to do |format|
if @post.save
format.html { redirect_to(:action => 'index') }
end
end
While your form would look like:
<% form_for @post do |f| %>
# put whatever fields necessary to create the post here
<% end %>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Very basic request response web server in NodeJS I am learning node JS and want to create a very basic single purpose web service that runs
a windows command (to create a new user in ejabberd chat server) on the server where the client can pass in a specific argument to the command (using ajax I imagine).
I've been using the basic 'createServer' tutorial as a template:
var sys = require('util')
var http = require('http');
var exec = require('child_process').exec;
var path = '"C:\\Program Files\\ejabberd-2.1.8\\bin\\ejabberdctl"';
http.createServer(function (req, res) {
var cmd = path + ' register nodeuser ejabberhost xxxxxx';
var child = exec(cmd, function (error, stdout, stderr) {
var msg;
if (error !== null) {
msg = 'Error : ' + error;
}
else{
msg = stdout;
}
// this will prob be JSON
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(msg);
});
}).listen(1337, "localhost");
console.log('Server running at http://localhost:1337/');
In the above code 'nodeuser' needs to be replaced with an argument passed from the client in the request, using ajax. How could I tweak this code to achieve that?
A: Input sanitation issues aside, here's how you would do this:
http.createServer(function (req, res) {
var dataInput;
if (req.url === '/foo') {
req.on('data', function (chunk) {
dataInput = chunk.toString();
})
}
if (dataInput !== undefined) {
var cmd = path + ' register nodeuser ejabberhost ' + dataInput;
}
...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is wrong with Facebook and Twitter APIs? Is anyone else noticing that facebook and twitters APIs aren't working?
For facebook even if I allow my application to have access to my wall
$facebook->getUser()
Is always 0... When I try to open getLoginUrl it just open pop-up and redirect it instantly to success return link...
Here is code:
require_once 'src/base_facebook.php';
require_once 'src/facebook.php';
$app_id = 'xxx';
$app_secret = 'xxx';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'oauth' => true,
'cookie' => true
));
$req_perms = "publish_stream";
$user = $facebook->getUser();
if (!$user)
{
$loginUrl = $facebook->getLoginUrl(array('display' => 'popup', 'redirect_uri' => 'http://xxxx.com/return_close.php?success=1', 'cancel_url' => 'http://xxxx.com/return_close.php?success=0','req_perms' => $req_perms, 'scope' => $req_perms));
}
And for twitter it's like someone mistyped return link...
When I open getAuthorizeURL and when I log in it redirects me to this URL:
https://twitter.comoauth_callback/?oauth_token=yA2xjLsVRm9tIuVEysXnCV8R7TISW8tF94uznn7zlw&oauth_verifier=Io1N2I8zOEzJeBWI77WXFMqmMRNDfCrXZGQxXmxJLbI
Yes, https://twitter.comoauth_callback/ is right, there is no / after .com, it's together, so I get not found page...
It's like both APIs have serious problems... Facebook sometimes work and sometimes doesn't, it's buggy a lot...
Facebook library downloaded from OFFICIAL GitHub page. Tried versions:
v3.1.1
v3.1.0
v3.0.1
And none of those work...
Update
Return URL ( redirect_uri ) MUST have facebook class included in file...
There is so many examples/documentations and none of those had this explained...
So, Facebook fixed... Twitter still not working...
A: Well, nothing is broken in the API. Where did you get the above code? and if you come up with it then based on what resource?
First of all, take a look at the example of the OFFICIAL PHP-SDK, you'll notice the following:
*
*Only the facebook.php file has been included, why not base_facebook.php? well because it's included in the facebook.php file!
*Developers used to use req_perms but now to request permissions you just need to use scope
*Take a look inside base_facebook.php for the params the Facebook() class expect: appId, secret and fileUpload ONLY
*Only use the display parameter if you know what you are doing!
*Use proper indentation with your code, it makes your life (and others!) much easier!
This been said, this is a rewrite of your code:
require 'src/facebook.php';
$app_id = 'xxx';
$app_secret = 'xxx';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret
));
$req_perms = "publish_stream";
$user = $facebook->getUser();
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array('display' => 'popup', 'redirect_uri' => 'http://xxxx.com/return_close.php?success=1', 'cancel_url' => 'http://xxxx.com/return_close.php?success=0', 'scope' => $req_perms));
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is strategy pattern helpful for this scenario? I have two classes A & B and both class implements the interface ISomeInterface. But some properties are not required for both class A & B.
But in the client app I am calling the same ISomeInterface to invoke both the classes. The problem which I have is I don't want Dictionary<string, string> & TypedDataSet, IList<Record> properties in the same interface. But the clients needs to use this IsomeInterface.
Actually DataValues() property is only applicable to class A.
Similarly MetaData() and RecordCollection() properties are applicable to class B.
Also, if I introduce a new class C in future and that needs a separate property like this then my code will look ugly which I don't want.
So, Is there any way I can still use the same IsomeInterface in my client app and have the appropriate properties in the corresponding classes?
I think I need to use Strategy Design pattern but got confused on how to implement the same. correct me if I am wrong?
See below:
interface ISomeInterface
{
string Id{get; set;}
void Display();
Dictionary<string, string> DataValues{get;};
TypedDataSet MetaData{get; }
IList<Record> RecordCollection{get; }
}
public class A: ISomeInterface
{
public string Id
{
return "A1";
}
void Display()
{
Console.Writeline("class A");
}
public Dictionary<string, string> DataValues()
{
return new Dictionary<string, string>();
}
public TypedDataSet MetaData()
{
//I dont want this method for class A
throw new NotImplementedException();
}
public IList<Record> RecordCollection()
{
//I dont want this method for class A
throw new NotImplementedException();
}
}
public class B: ISomeInterface
{
public string Id
{
return "B1";
}
void Display()
{
Console.Writeline("class B");
}
public Dictionary<string, string> DataValues()
{
//I dont want this method for class B
throw new NotImplementedException();
}
public TypedDataSet MetaData()
{
return new TypedDataSet();
}
public IList<Record> RecordCollection()
{
IList<Record> rc = null;
//do something
return rc;
}
}
Client App -
Main()
{
ISomeInterface a = new A();
a.Display();
Dictionary<string, string> data = a.DataValues();
ISomeInterface b = new B();
b.Display();
TypedDataSet data = b.MetaData();
IList<Record> rc = b.RecordCollection();
}
A: Strategy does not really work for you in this case.
We must question why you must call ISomeInterface when its implementing classes do not support all methods. It is probably best to have several inheriting interfaces.
*
*ISomeInterface
*
*IClassAInterface
*IClassBInterface
Then, pick which Interface is most appropriate for usage.
interface ISomeInterface
{
string Id{get; set;}
void Display();
}
interface IClassAInterface
{
Dictionary<string, string> DataValues{get;};
}
interface IClassBInterface
{
TypedDataSet MetaData{get; }
IList<Record> RecordCollection{get; }
}
The example usage you given isn't really helpful - you already know which class you are instantiating (new A() and new B()) so the interfaces aren't going to give you any added abstraction. So let us think of an example where this technique is more useful:
public class SomeCollection
{
public ICollection<T> retrieveItems<T>() where T : ISomeInterface
{
//... retrieve relevant instances.
}
}
Then
var col = new SomeCollection();
// Populate...
var someInterfaces = col.retrieveItems<ISomeInterface>();
foreach(ISomeInterface instance in someInterfaces){
instance.Display();
}
var classAInterfaces = col.retrieveItems<IClassAInterface>();
// etc.
So I guess in the end, if you're trying to get a bunch of "RecordCollection" from a collection of As and Bs, you really need to rethink your design.
A: A principle of software design that applies here is that classes should not be forced to implement methods of interfaces that they will not use. So the interface should only have methods and properties on it that all classes that implement the interface will use.
Other than that I think it depends a lot on what you are trying to model in your domain and your existing application, etc, as to what sort of solution you choose. i.e. more specific information is needed to give further advice.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: adding Progress Bar to my dataCall function - Android How do I add a Progress Bar when a user selects a spinner item that triggers a http request. Do I add it to the class doing the http request (dataCall) or the main activity that has the spinner in it?
I have a class DataCall that when called does a http call to a php script that gets data from a MySQL database and returns data in a JSON format. This class is called after a spinner item is selected. The data returned is added to another spinner in the same activity. I am trying to show the progress wheel when the class DataCall is doing its thing. Below is my code for calling DataCall from my MainActivity and the code from DataCall .
MainActivity that calls DataCall (See below) when the spinner is selected. When DataCall returns data it updates another spinner with the new data.
statespinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,long arg3)
{
int id = parent.getId();
if (spinner1_count2 < spinner1_count1 ) {
spinner1_count2++; }
else
{
city.clear();
String item = statespinner.getSelectedItem().toString();
String spinnerContentType = "city";
String spinnerURL = "getStoreCity.php?state=" + item;
//CALLING DATACALL BELOW
String city_data = DataCall.getJSON(spinnerURL,spinnerContentType);
Log.d(TAG, city_data);
String state_spinner_log = "STATE SPINNER";
Log.d(TAG, state_spinner_log);
JSONArray jsonArray;
try {
cityjsonArray = new JSONArray(city_data);
for (int i=0; i<cityjsonArray.length(); i++)
{
String styleValue2 = cityjsonArray.getJSONArray(i).getString(0);
Log.d(TAG, styleValue2);
city.add(styleValue2);
adapter2.notifyDataSetChanged();
}
//
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
DataCall Class:
public class DataCall extends Activity {
private static final String TAG = "MyApp";
public static String getJSON(String myUrlString, String contentType){
String line = null;
String tag_value = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://www.mywebsite.com/getdata/" + myUrlString);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
line = "<results status=\"error\"><msg>Can't connect to server1</msg></results>";
} catch (MalformedURLException e) {
line = "<results status=\"error\"><msg>Can't connect to server2</msg></results>";
} catch (IOException e) {
line = "<results status=\"error\"><msg>Can't connect to server3</msg></results>";
}catch (Exception anything) {
//Whatever
}
return line;
}
}
A: I think you're going to have to move this web call out to a different thread as it will take an unknown amount of time to run and may cause an ANR.
If you use ASyncTask it has an inbuilt mechanism for updating a progress bar as the background thread runs. There is a lot of valuable information at this link
http://www.vogella.de/articles/AndroidPerformance/article.html
Hope this helps, m
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WebView memory leak in android app I'm using a layout with a webview ... every time I load a page in the web view I notice in the task manager that I get a memory leak... seems like my webview keeps in memory all pages' data... how can I avoid this behavior?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.