Dataset Preview
Full Screen
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed
Error code:   DatasetGenerationError
Exception:    EmptyDataError
Message:      No columns to parse from file
Traceback:    Traceback (most recent call last):
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1853, in _prepare_split_single
                  for _, table in generator:
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/csv/csv.py", line 188, in _generate_tables
                  csv_file_reader = pd.read_csv(file, iterator=True, dtype=dtype, **self.config.pd_read_csv_kwargs)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/streaming.py", line 75, in wrapper
                  return function(*args, download_config=download_config, **kwargs)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/utils/file_utils.py", line 1212, in xpandas_read_csv
                  return pd.read_csv(xopen(filepath_or_buffer, "rb", download_config=download_config), **kwargs)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/pandas/io/parsers/readers.py", line 1026, in read_csv
                  return _read(filepath_or_buffer, kwds)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/pandas/io/parsers/readers.py", line 620, in _read
                  parser = TextFileReader(filepath_or_buffer, **kwds)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/pandas/io/parsers/readers.py", line 1620, in __init__
                  self._engine = self._make_engine(f, self.engine)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/pandas/io/parsers/readers.py", line 1898, in _make_engine
                  return mapping[engine](f, **self.options)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/pandas/io/parsers/c_parser_wrapper.py", line 93, in __init__
                  self._reader = parsers.TextReader(src, **kwds)
                File "parsers.pyx", line 581, in pandas._libs.parsers.TextReader.__cinit__
              pandas.errors.EmptyDataError: No columns to parse from file
              
              The above exception was the direct cause of the following exception:
              
              Traceback (most recent call last):
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1392, in compute_config_parquet_and_info_response
                  parquet_operations = convert_to_parquet(builder)
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1041, in convert_to_parquet
                  builder.download_and_prepare(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 924, in download_and_prepare
                  self._download_and_prepare(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 999, in _download_and_prepare
                  self._prepare_split(split_generator, **prepare_split_kwargs)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1740, in _prepare_split
                  for job_id, done, content in self._prepare_split_single(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1896, in _prepare_split_single
                  raise DatasetGenerationError("An error occurred while generating the dataset") from e
              datasets.exceptions.DatasetGenerationError: An error occurred while generating the dataset

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

Unnamed: 0
int64
Id
int64
Title
string
Body
string
Tags
string
Tag_Number
string
65
66
What do the parentheses mean when you're declaring/calling a property?
<p><strong>Example 1</strong>:</p> <pre><code>function a(){ return "ok"; } function b(){ this.c = a; } var d = new b(); alert(d.c()); // Result "ok". </code></pre> <p><strong>Example 2</strong>:</p> <pre><code>function b(){ this.c = a(); } var d = new b(); alert(d.c); // Result "ok". </code></pre> <p>What do the parentheses mean in this case?</p>
javascript
[3]
92
93
jQuery Masonry access internal method var
<p>Any advice how to access an internal method var of jQuery Masony? I'm looking to console.log the <code>containerSize</code> property inside the <code>layout</code> method:</p> <p>line 177 > <a href="https://github.com/desandro/masonry/blob/master/jquery.masonry.js" rel="nofollow">query.masonry.js</a></p> <p>I need to retrieve the <code>containerSize</code> after masonry init:</p> <pre><code>$('#container').masonry({ itemSelector: '.box' }); console.log("here i need to retrieve the containerSize"); </code></pre>
jquery
[5]
101
102
reliably detecting line breaks in php
<p>I'm going to build a wee batch search field where someone can enter/paste in a bunch of keywords separated by a linebreak, they might be copied in from excel, word or where-ever.</p> <p>So I plan to use php to explode() that input and loop through it for an SQL search.</p> <p>Do I need to do anything special to reliably detect the line breaks - my understanding is that the character can be different depending on where it's pasted from.</p>
php
[2]
151
152
How to convert QR code to number?
<p>i have created QR-code through this site <a href="http://qrcode.kaywa.com/" rel="nofollow">http://qrcode.kaywa.com/</a> .i have created QR-code for "1". I want read and convert into number.They provided one url for QR code image.Url is <a href="http://qrcode.kaywa.com/img.php?s=8&amp;d=1" rel="nofollow">http://qrcode.kaywa.com/img.php?s=8&amp;d=1</a>" alt="qrcode". how to convert QR code to number using URL.Please help me.</p>
android
[4]
182
183
How to click on multiple links on multiple pages in webBrowser
<p>Iam Unable to do this from past one week. I want to click on multiple links n multiple web pages using webBrowser in C# Following is the code please help me in this regard.</p> <pre><code>public void DoDelete() { int count = 0; if (corruptList.Count &gt; 0) { foreach (string listItem in corruptList) { var th = new Thread(() =&gt; { try { WebBrowser webBrowser = new WebBrowser(); webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBroswer_DocumentCompleted); webBrowser.Navigate(listItem); Thread.Sleep(100); webBrowser.Dispose(); } catch (Exception ex) { throw ex; } this.Invoke(new MethodInvoker(delegate { dataGridView_CorruptLinks.Rows[count].Cells[2].Value = "Deleted"; })); }); th.SetApartmentState(ApartmentState.STA); th.Start(); Thread.Sleep(100); } count++; } } void webBroswer_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { try { WebBrowser webBrowser = sender as WebBrowser; HtmlElementCollection ec = webBrowser.Document.GetElementsByTagName("a"); foreach (HtmlElement item in ec) { if (item.InnerHtml == "Delete this invalid field") { item.InvokeMember("Click"); break; } } } catch (Exception exp) { } } </code></pre>
c#
[0]
205
206
Splitting a list
<p>I've scoured various resources and can't figure out how to do a rather simple operation.</p> <p>Right now, I have a list as follows:</p> <pre><code>li = [['a=b'],['c=d']] </code></pre> <p>I want to transform this into:</p> <pre><code>li = [['a','b'],['c','d']] </code></pre> <p>As I understand it, <code>split("=")</code> only applies to string types. Is there an equivalent method for lists?</p> <p>Pardon the simplicity of my question...</p> <p>-Dan</p>
python
[7]
230
231
PHP Deep Object Copy/Clone
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/185934/how-do-i-create-a-copy-of-an-object-in-php">How do I create a copy of an object in PHP?</a> </p> </blockquote> <p>What is the best accepted way in PHP to perform a <strong>deep</strong> object copy/clone?</p> <p>I have found some examples using serialize which i think suffers from some issues.</p>
php
[2]
238
239
What does "function() { get: function(...) { ... } }" in JavaScript mean?
<p>I found the following code snippet <a href="http://www.yearofmoo.com/2012/10/more-angularjs-magic-to-supercharge-your-webapp.html#you-should-be-using-custom-services" rel="nofollow">here</a>:</p> <pre><code>App.factory('myHttp',['$http',function($http) { return function() { get: function(url, success, fail) { $http.get(url).success(function(response) { return response.data; }).error(fail); } }; }]); </code></pre> <p>I wonder what does this syntax mean:</p> <pre><code>function() { get: function(...) { ... } } </code></pre>
javascript
[3]
243
244
jQuery - var is underfined
<p>I have following script:</p> <pre><code> $('.news ul li').hide(); $('.news ul li:first-child').show(); function Roller() { var CurrectNews = $('.news ul li').filter(':visible'); var FirstNews = $('.news ul li:first-child'); if ( $(CurrectNews).is(':last-child') ){ $(CurrectNews).fadeOut('slow'); $(FirstNews).fadeIn('slow'); } else { $(CurrentNews).fadeOut('slow'); $(CurrentNews).next().fadeIn('slow'); } } setInterval(Roller, 5000); </code></pre> <p>When I run it, FireBug is saying that <code>CurrentNews is underfinded</code>. Why?</p> <p>When I watch for <code>$('.news ul li').filter(':visible');</code> it does find 1 element, as expected.</p> <p>Any suggestion much appreciated. </p>
jquery
[5]
259
260
Conflicting event-handling in jQuery
<p>I have a <code>&lt;div&gt;</code> like this:</p> <pre><code>&lt;div id="Field1"&gt; &lt;label id="label1"&gt;Name&lt;/label&gt;&lt;br/&gt; &lt;input type="text" data-attr="text" style="..." id="input1"/&gt;&lt;br/&gt; &lt;label id="instr1"/&gt; &lt;div class="xfb-row-options1"&gt; &lt;a class="button-delete" src="..." style="..."&gt;-&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I already have a jQuery function:</p> <pre><code>$("#fb_contentarea_col1down21 div").live("click", function(){ // some stuff to change the properties of the Field, // like changing the field name, size. return false; }); </code></pre> <p>I have a <code>&lt;div&gt;</code> with a "delete" image button inside it, and I want to delete this on clicking "<code>button-delete1</code>". I tried it with:</p> <pre><code>$("#fb_contentarea_col1down21 div div .button-delete1").live("click", function(){ //deleting the Div Field1 return false; }); </code></pre> <p>Now both my functions conflict. When I click on "<code>button-delete1</code>", my function #1 gets executed and shows me an error.</p>
jquery
[5]
295
296
Accessing localhost of PC from USB connected Android mobile device
<p>I have an android device (Samsung galaxy tab) connected to my PC via USB .</p> <p>I want to use WebServices and run a web page which is located on my local xampp server of my PC on my android device .</p> <p>I can achieve it if I have both , my PC and android device , connected on the same wireless network .</p> <p>However is it possible to access the localhost page without any wireless connection , using only USB connection .</p> <p>(PS : This same scenario works when I run the app on an emulator and use the ip 10.0.2.2 to access the localhost on my PC)</p>
android
[4]
389
390
insatll php-fpm patch for php5.2.x
<p>I have php 5.2.17 and i download relevent php-fpmm file "php-5.2.17-fpm-0.5.14.diff.gz " form php-fpm.rg But I don't know how to install this patch i use slackware 13.1 x64</p>
php
[2]
435
436
how to remove underline for anchor link in jquery
<p>i have anchor tag in jquery as </p> <pre><code>success: function(result) { $('#MyGrid tbody').append('&lt;tr&gt;&lt;td&gt;&lt;a STYLE="text-decoration:none" href="#"&gt;&lt;font color=black&gt;&lt;strong&gt;' + result.name+ '&lt;/font&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;'); </code></pre> <p>to remove the underline i have added style property ,but it is not removing the underline.How can i remove the underline for anchor tag?</p> <p>thanks, michaled</p>
jquery
[5]
469
470
How to Get UIImagePickerController as First screen in TabBarApplication
<p>How to open Photo Library in First screen as pushviewcontroller in tabBarApplication.</p>
iphone
[8]
504
505
'Global' may not respond to '+setShow'
<p>hai I am new iphone. In my application there is warning 'Global' may not respond to '+setShow' [Global setShow:True]; Please help me.</p> <p>Thank you</p>
iphone
[8]
521
522
simple example for .blockUI in jquery
<p>HI please guide me to the purpose of blockUI with an simple demonstration </p> <p>-Thanks</p>
jquery
[5]
566
567
How the game will search for other online users and will display the list of all users?
<p>I am asking this question as a small part of my question series regarding game programming .</p> <p>Refer <a href="http://stackoverflow.com/questions/3131780/multiplayer-game-in-iphone-concept-strategy-design">this</a> question as the main one .</p> <p>Now suppose I want to develop one small board game on iphone that is multiplayer . so how it will handle how many users are online and displaying them .</p> <p>Suppose it is an online multiplayer casino game .</p> <p>Then suppose it have to show currently playing tables and users on them .</p> <p>So what can we do in iphone to do this sort of thing .</p> <p>Thanks .</p>
iphone
[8]
664
665
how to check for multiple switch statement in c#
<p>i need to check more than one statement in switch statement to evalute like</p> <pre><code> int a=5; switch(a) { case 4,5: console.write("its from 4 to 5); break; } </code></pre>
c#
[0]
750
751
Regexp for numbers with delimeters
<p>I would like to know how can I create a regexp to match the pattern 3,231 or 3,231,201 in php ? Thanks</p>
php
[2]
751
752
Update sqlite database when server database get updated
<p>I am working on a updating a database on a mobile device which is using sqlite db, which should get updated as server updates his/her database ie wamp server. can anyone suggests me any ideas how I can achieve this, I don't want to to read the whole server database as it will create unwanted data usage reading the whole database just for a single update or for multiple update. Update is on my product table and only price field is updated by server side. </p>
android
[4]
761
762
rounding autoSumForm values
<p>I have searched for a few days now trying to find a solution. I have looked at the php.net info, but it seems to be in a different format to my code below. Please could someone show me how to round this sort of calculation. Thank you</p> <pre><code>function startCalc(){ interval = setInterval("calc()",1); } function calc(){ one = document.autoSumForm.firstBox.value; two = document.autoSumForm.secondBox.value = ((one*20) + (110*20))/17; three = document.autoSumForm.thirdBox.value; four = document.autoSumForm.fourthBox.value = ((three*20) + (150*20))/17; five = document.autoSumForm.fifthBox.value; six = document.autoSumForm.sixthBox.value = ((five*20) + (250*20))/17; seven = document.autoSumForm.seventhBox.value = (four*1) - (two*1); eight = document.autoSumForm.eigthBox.value = (six*1) - (two*1); } function stopCalc(){ clearInterval(interval); } </code></pre>
javascript
[3]
780
781
Order in conditional statements
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/9438043/php-false-place-in-condition">php false place in condition</a> </p> </blockquote> <p>I have noticed that a lot of PHP code uses conditional statements like CONST == VARIABLE. I grew up with the syntax always articulated in reverse. Is there a reason for this structure? </p> <p>Example:</p> <pre><code> // this is the way I see it most typically represented in PHP if ( false == $foobar ) { // do this } // this is the way I normally do it if ( $foobar == false ) { // do this } </code></pre>
php
[2]
781
782
java.util.UUID.fromString not checking length
<p>When I looked into the implementation of <code>java.util.UUID.fromString</code>, I found that it doesn't check for the UUID length. Is there any particular reason for this? It only checks the components separated by "-".</p> <pre><code>String[] components = name.split("-"); if (components.length != 5) throw new IllegalArgumentException("Invalid UUID string: "+name); </code></pre> <p>Should it also throw IllegalArgumentException when length is not 36?</p> <p>Currently, without the length checking, numbers are automatically prepended with 0's if less than the component length or shifted if more. The downside is, if one entered a UUID string with a missing digit, it is accepted as valid and prepended with 0. This is hard to debug.</p> <p>For example, this "12345678-1234-1234-1234-123456789ab" becomes "12345678-1234-1234-1234-0123456789ab". Notice the '0' added? And this "12345678-1234-1234-1234-123456789abcd" becomes "12345678-1234-1234-1234-23456789abcd" with the '1' removed.</p> <p>To push this even further, the string "1-2-3-4-5" will also be treated as valid and becomes "00000001-0002-0003-0004-000000000005".</p> <p>Edit: To clarify my question, is this a bug or done on purpose to follow some standard or principle?</p>
java
[1]
786
787
Guard code after switch on enum is never reached
<p>I have just hit a confusing problem when trying to compile some code using g++ 4.4.3.</p> <p>The code below compiles fine, but instead of hitting the expected assert when I pass an 'invalid' enum value, the function just returns 1. What I find even stranger is that when I uncomment the lines pertaining to the E3 enum value, things start working as expected.</p> <p>The fact that there is no default entry in the switch block is by design. We compile with the -Wall option to get warnings of unhandled enum values.</p> <pre><code>enum MyEnum { E1, E2, //E3 }; int doSomethingWithEnum(MyEnum myEnum) { switch (myEnum) { case E1: return 1; case E2: return 2; //case E3: return 3; } assert(!"Should never get here"); return -1; } int main(int argc, char **argv) { // Should trigger assert, but actually returns 1 int retVal = doSomethingWithEnum(static_cast&lt;MyEnum&gt;(4)); std::cout &lt;&lt; "RetVal=" &lt;&lt; retVal &lt;&lt; std::endl; return 0; } </code></pre>
c++
[6]
788
789
how to do php 4 dimension array sorting
<p>Cassandra Json format looks like this</p> <pre><code> "recommendResult":[{ "mediaId":"", "mediaEntry":[{ "user1":{ "name":"sooin", "rating":"3", "views":"2", "like":"ture", "comment":"good" }, "user2":{ "name":"sara", "rating":"1", "views":"4", "like":"ture", "comment":"good!" } }], "view":"4", "rating":"4", "like":"10", "smallUrl":"/photo/smallUrl", "largeUrl":"/photo/largeUrl", "title":"aaaa" }] </code></pre> <p>Here is my php code</p> <pre><code>$rows=$column_family-&gt;get_range(); $count=0; foreach($rows as $key =&gt; $columns) { $returnkey[$count]=array('mediaId'=&gt;$key, 'columns'=&gt;$columns,'user'=&gt;array_slice($columns,1,2)); $count++; } natcasesort($returnArray['key']['comment']['photoInfo']['view']); print_r($returnArray['key']['comment']['photoInfo']['view']); </code></pre> <p>I am trying to sort based on views. i try to use natcasesort but it does not work. Any thought for that. Thank you.</p>
php
[2]
805
806
How can I unserialize std class()
<p>I have serialize values in data base, i fetch them from database then when i do </p> <pre><code>&lt;pre&gt; print_r($DataValues) &lt;/pre&gt; </code></pre> <p>it shows me value like this </p> <pre><code>[0] =&gt; stdClass Object ( [categories] =&gt; a:1:{i:38;s:21:"Summer Market Session";} ) [1] =&gt; stdClass Object ( [categories] =&gt; a:1:{i:38;s:21:"Summer Market Session";} ) [2] =&gt; stdClass Object ( [categories] =&gt; a:2:{i:38;s:21:"Summer Market Session";i:39;s:21:"Autumn Market Session";} ) </code></pre> <p>i want to get only the value after unserializing it, i tried to unserialize but is show bolean false</p> <p>&amp; when i try to print the value after running for each value it shows me below mentioned error</p> <p><strong>Catchable fatal error: Object of class stdClass could not be converted to string</strong> </p> <p>I dont know how i do this i was trying all unserialize tactics what i know &amp; also i tried to store value in array by using foreach loop but i am fail..</p> <p>Kindly help how can i get value of it after unserilize it...??</p>
php
[2]
905
906
Simple Javascript loop that repeats each second
<p>I'm writing a code to move a character in a browser game. I managed to get the pixels it must move per second both horizontally and vertically.</p> <p>pxsecx is the number of pixels it must move horizontally per second pxsecy is the same but vertically</p> <p>Basically it should += them to the current horizontal and vertical position.</p> <p>I need the loop to keep repeating itself every second until the element position meets the new position (newx). </p> <p>This is as far as I have gone:</p> <pre><code>&lt;body onmousedown="showCoords(event)"&gt; &lt;script type="text/javascript"&gt; function showCoords(evt){ oldx = parseInt(document.getElementById("character").style.left); oldy = parseInt(document.getElementById("character").style.top); width = parseInt(document.getElementById("character").style.width); height = parseInt(document.getElementById("character").style.height); newx = evt.pageX - width/2; newy = evt.pageY - height/2; disx = newx - oldx; disy = newy - oldy; diag = parseInt(Math.sqrt(disx*disx + disy*disy)); speed = 50; secs = diag/speed; pxsecx = disx/secs; pxsecy = disy/secs; while(document.getElementById("character").style.left&lt;newx) { document.getElementById("character").style.left += pxsecx; document.getElementById("character").style.top += pxsecy; } } &lt;/script&gt; </code></pre> <p>Everything works until the while where I have no idea how to do make it work every second. I'm testing it here: <a href="http://chusmix.com/game/movechar.php" rel="nofollow">http://chusmix.com/game/movechar.php</a></p> <p>How do I make it repeat that once a second so it works?</p> <p>thanks</p>
javascript
[3]
920
921
Buttons on a Sliding Drawer? - Android
<p>Okey, so I've implemented a button on a Sliding drawer in a android application I'm building. The only problem is that when I press the button the whole sliding drawer is pressed and it slides up.</p> <p>I know I can disable 'press to slide up' in the XML, but that does not seem to work as the sliding drawer still is pressed just without the slide up.</p> <p>If I call the slidingDrawer.lock(); function the button actually works but then the sliding drawer can't slide up or even be pressed up.</p> <p>Any one have a simple solution to this problem?</p>
android
[4]
960
961
Just a small problem regarding javascript BOM question
<p>The question is this:</p> <p><b>Create a page with a number of links. Then write code that fires on the window onload event, displaying the href of each of the links on the page.</b></p> <p><i>And this is my solution</i></p> <pre><code>&lt;html&gt; &lt;body language="Javascript" onload="displayLink()"&gt; &lt;a href="http://www.google.com/"&gt;First link&lt;/a&gt; &lt;a href="http://www.yahoo.com/"&gt;Second link&lt;/a&gt; &lt;a href="http://www.msn.com/"&gt;Third link&lt;/a&gt; &lt;script type="text/javascript" language="Javascript"&gt; function displayLink() { for(var i = 0;document.links[i];i++) { alert(document.links[i].href); } } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><i>This is the answer provided by the book</i></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script language=”JavaScript” type=”text/javascript”&gt; function displayLinks() { var linksCounter; for (linksCounter = 0; linksCounter &lt; document.links.length; linksCounter++) { alert(document.links[linksCounter].href); } } &lt;/script&gt; &lt;/head&gt; &lt;body onload=”displayLinks()”&gt; &lt;A href=”link0.htm” &gt;Link 0&lt;/A&gt; &lt;A href=”link1.htm”&gt;Link 2&lt;/A&gt; &lt;A href=”link2.htm”&gt;Link 2&lt;/A&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Before I get into the javascript tutorial on how to check user browser version or model,I was using the same method as the example,by acessing the <code>length</code> property of the <code>links</code> array for the loop,but after I read through the tutorial,I find out that I can also use this alternative ways,by using the method that the test condition will evalute to true only if the <code>document.links[i]</code> return a valid value,so does my code is written using the valid method??If it's not,any comment regarding how to write a better code??Correct me if I'm wrong,I heard some of the people say "a good code is not evaluate solely on whether it works or not,but in terms of speed,the ability to comprehend the code,and could posssibly let others to understand the code easily".Is is true??</p>
javascript
[3]
974
975
Two way communication in two android emulators
<p>I have a server client code in one file, running fine for the client to server when using redir add tcp:clientEmulatorPort:serverEmulatorPort</p> <p>but for the server side to reply back to client I have redirection issue of the ports as redir add tcp:serverEmulatorPort:clientEmulatorPort because now server emulator has to generate response to client emulator, does anyone have idea how can I perform this second port redirection or any other way of two way communication? everything else is working fine because I have checked that over devices just want to run it over 2 emulators as well. </p> <p>Any help is appreciated, thanks</p>
android
[4]
975
976
How can I convert Double Date to std::string
<p>I got the Date value from the method from the following code</p> <pre><code> DATE dDate; hr = pADsUser-&gt;get_PasswordLastChanged(&amp;dDate); // pADsUser is pointer variable of IADsUser </code></pre> <p>Date type is discribed in the link <a href="http://msdn.microsoft.com/en-us/library/82ab7w69%28v=vs.71%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/82ab7w69%28v=vs.71%29.aspx</a></p> <p>How can I convert this kind of Date to string so that I can print it in console.</p> <p>I am not using MFC Dlls for this application. so I cannot use the COleDateTime type also.</p> <p>Is there any built in method available or Do I need to calculate the date manually?</p>
c++
[6]
989
990
Split based by a-z character in an alphanumeric string in python
<p>I have strings like "5d4h2s", where I want to get 5, 4, and 2 from that string, but I also want to know that 5 was paired with d, and that 4 was paired with h, etc etc. Is there an easy way of doing this without parsing char by char?</p>
python
[7]
1,010
1,011
javascript call a privileged method
<p>If I call the killSwitch() outside the onkeypress, I'll cause an error. But inside the onkeypress function, I worked just fine. Why?</p> <p><code></p> <pre><code>// this works fine var ClassA = function() { var doc = document; // killSwitch(); doc.onkeypress = function(e){ killSwitch(); } this.killSwitch = function(){ alert('hello world'); } } var myClass = new ClassA(); </code></pre> <p></code></p>
javascript
[3]
1,012
1,013
About "undefined refence to" in C++
<p>=)</p> <p>I have a question about "undefined reference to" in C++.</p> <p>Here in this code i have the next:</p> <pre><code>#include "HelloWorldAgent/helloworldagent.hh" int main() { HelloWorldAgent agent; agent.run(); } </code></pre> <p>In another C++ file is the next code:</p> <pre><code>#ifndef _HELLOWORLDAGENT_HH_ #define _HELLOWORLDAGENT_HH_ #include "../../HumanoidAgent/humanoidagent.hh" /** * A friendly robot */ class HelloWorldAgent : public bats::HumanoidAgent { /** * Initialize agent * * Called a single time when starting up the agent. Put all your initialization stuff here. */ virtual void init(); /** * Think cycle * * Called at each cycle after a message from the server is received and parsed. Put all your thinking and acting stuff here. */ virtual void think(); public: /** * The Constructor * * Sets this agent's teamname to "Hello". Consider putting initialization stuff in init() instead of here. */ HelloWorldAgent() : HumanoidAgent(std::string("Hello")) { } }; #endif </code></pre> <p>I try to compile it with g++ </p> <p>$ g++ -I /usr/include/eigen -I /usr/include/sigc++-2.0 -I /usr/lib/sigc++-2.0/include helloworld.cc</p> <p>And gives me the next error:</p> <p>In file included from /usr/lib/gcc/i486-slackware-linux/4.5.2/../../../../include/c++/4.5.2/ext/hash_map:60:0, from HelloWorldAgent/../../HumanoidAgent/../WorldModel/../Hashclasses/hashclasses.hh:25, from HelloWorldAgent/../../HumanoidAgent/../WorldModel/worldmodel.hh:54, from HelloWorldAgent/../../HumanoidAgent/humanoidagent.hh:46, from HelloWorldAgent/helloworldagent.hh:44, from helloworld.cc:1: /usr/lib/gcc/i486-slackware-linux/4.5.2/../../../../include/c++/4.5.2/backward/backward_warning.h:28:2: warning: #warning This file includes at least one deprecated or antiquated header which may be removed without further notice at a future date. Please use a non-deprecated interface with equivalent functionality instead. For a listing of replacement headers and interfaces, consult the file backward_warning.h. To disable this warning use -Wno-deprecated. /tmp/cc1cjIEs.o: In function <code>main': helloworld.cc:(.text+0x29): undefined reference to</code>bats::HumanoidAgent::run()' /tmp/cc1cjIEs.o: In function <code>HelloWorldAgent::HelloWorldAgent()': helloworld.cc:(.text._ZN15HelloWorldAgentC2Ev[_ZN15HelloWorldAgentC5Ev]+0xfd): undefined reference to</code>vtable for HelloWorldAgent' /tmp/cc1cjIEs.o: In function <code>HelloWorldAgent::~HelloWorldAgent()': helloworld.cc:(.text._ZN15HelloWorldAgentD2Ev[_ZN15HelloWorldAgentD5Ev]+0xb): undefined reference to</code>vtable for HelloWorldAgent' collect2: ld returned 1 exit status</p> <p>I don't know what could it be, maybe i'm doing something wrong. Any ideas ?</p> <p>Thanks in advance. =)</p> <p>PS: No, it is not homework, it is just for fun =)</p>
c++
[6]
1,038
1,039
remembering of a select menu option with jquery
<p>Hello to everybody and thanks in advance for reading this... I have 4 dynamically dependent select menus. The menus correspond to state, county, area, neighborhood. The dynamic dependence is achieved through a jquery script.What i want to accomplish is to make the menus remember the last option selected by a user for each menu. So i thought that if i can grab the url parameters that would do the trick. So i modified the script in this way....</p> <pre><code>getCounty: function (results) { if(!results) return; var allCounties = $("&lt;option value=\"All\"&gt;All Counties &lt;/option&gt;"); counties.html(results); counties.prepend(allCounties); var w = $.query.get("county_id"); if(w) { counties.val(w).attr('selected', true); } else { counties.val("All").attr('selected', true); } </code></pre> <p>Is the <code>$.query.get</code> function correct? Is there anything else wrong with my code? I have to admit i am not a jquery expert...The code works just fine if i type</p> <pre><code>counties.val(3).attr('selected',true) </code></pre> <p>The third option of the select menu gets selected. Any suggestion will be highly appreciated!! </p> <p>Ok i resolved the problem by using </p> <pre><code>function getUrlVars() { var vars = {}; var parts = window.location.href.replace(/[?&amp;]+([^=&amp;]+)=([^&amp;]*)/gi, function(m,key,value) { vars[key] = value; }); return vars; } </code></pre> <p>And after</p> <pre><code> var county = getUrlVars()["county_id"]; if (county) counties.val(county).attr('selected',true); else counties.val("All").attr('selected',true); </code></pre>
jquery
[5]
1,053
1,054
Problems with loading a BitmapPalette from image file
<p>I want to load a palette from a bitmap file I have created. The file is 256 px wide and 1 px high.</p> <p>I use</p> <pre><code>BitmapImage image = new BitmapImage(); image.BeginInit(); image.UriSource = new Uri("image.bmp", UriKind.RelativeOrAbsolute); image.EndInit(); myPalette = new BitmapPalette(image, 256); </code></pre> <p>The strange thing is, that the <code>Count</code> property of <code>myPalette.Colors</code> is only 244!</p> <p>Is there something wrong with my code?</p>
c#
[0]
1,161
1,162
Any Default Pass By Reference DataTypes in C++?
<p>I understand that unlike C# ( where class is passed by reference and struct is passed by default), both structure and class in C++ are passed by value into a method, unless it is explicitly modified to pass by reference.</p> <p>i.e.,</p> <pre><code>// this is a method that passes by reference void PassReferenceOp(MyClass &amp;myclass, MyStruct &amp;myStruct) { } // this is a method that passes by value void PassReferenceOp(MyClass myclass, MyStruct myStruct) { } </code></pre> <p>My question is, is it that there is no data structure, data types in C++ that passes into a method by reference? That no matter I am using <code>std::list</code>, <code>std::list::iterator</code>,<code>std::map</code>, or any data types I create, be it struct or class, all are pass by reference?</p>
c++
[6]
1,191
1,192
Cannot use string offset as an array (What does it mean?)
<p>The code below is more or less a chunk of my code. The <code>$servername</code> and <code>$monthlyincome</code> variables are not actually static as shown here but I changed them so I could add less code here.</p> <p>If I run this code... </p> <pre><code>$servername="Server1"; $months = array('January','February','March','April','May','June','July','August','September','October','November','December'); for ($i=0;$i&lt;=24;$i++) { $new_time = mktime(0,0,0,date("m")+$i,1,date("Y")); $months_array[date("Y",$new_time)][date("m",$new_time)] = "x"; } $overallincome = 0; foreach ($months_array AS $year=&gt;$month) { foreach ($month AS $mon=&gt;$x) { $monthlyincome = 3; $overallincome += $monthlyincome; $$servername[$months[$mon-1]." ".$year]['monthlyincome']=$monthlyincome; $$servername[$months[$mon-1]." ".$year]['overallincome']=$overallincome; } } </code></pre> <p>I get this error...</p> <p>Cannot use string offset as an array in on line 123</p> <p>Line 123 is this line... <code>$$servername[$months[$mon-1]." ".$year]['monthlyincome']=$monthlyincome;</code></p> <p>I can't figure out what I am doing wrong. I have checked other posts on SO with the same error but nothing made sense to me.</p>
php
[2]
1,193
1,194
How to : Python Convert Bytes to Readable ASCII/Unicode
<p>this is the bytes i have received,and i would like to convert byte[5] + byte[6] + byte[7] + byte[8] to ASCII readable text.</p> <pre><code>s=b'0f0000004e52303947303531363400' </code></pre> <p>bytes[5]~[8] ASCII/UNICODE is NR09</p> <p>please help thanks.</p>
python
[7]
1,206
1,207
Insert Query is inserting only first row from the result set in the database table
<p>I am fetching records from table EmployeeLeave and storing it in a result set. Then I am inserting this result set in a database table but I am able to insert only the first row of the result set instead of all the rows.<br> How can i insert all the rows of the result set?</p> <pre><code>r = stmt.executeQuery("select * from EmployeeLeave where EmployeeNo='"+empno+"'"); while(r.next()) { for(int i=0;i&lt;=r.getRow();i++) { int empid = r.getInt(1); String leave = r.getString(2); r = stmt.executeQuery("insert into ApprovedLeave values('"+empid+"','"+leave+"','True')"); } } </code></pre>
java
[1]
1,216
1,217
hiding and showing certain field with jquery validation
<pre><code>rules: { firstname: "required", lastname: "required", birthdate: { date: true, required: true, minimumAge: true }, consent: { required: function(element) { return getAge($("#birthdate").val()) &lt; 18; $("#consent").show(); } } }); $("#consent").hide(); </code></pre> <p>I want to show a check box for consent if the age of the user is below 18, From the above code why isn't working?</p>
jquery
[5]
1,227
1,228
Safe way to initialize a derived class
<p>I have a base class:</p> <pre><code>class CBase { public: virtual void SomeChecks() {} CBase() { /* Do some checks */ SomeChecks(); /* Do some more checks */ } }; </code></pre> <p>and a derived class:</p> <pre><code>class CDerived : public CBase { public: virtual void SomeChecks() { /* Do some other checks */ } CDerived() : CBase() {} }; </code></pre> <p>This construction seems to be a bit weird but in my case this is required, because CBase does some checks and CDerived can mix some checks in between them. You can see it as a way to "hook" functions in the constructor. The problem with this construction is that while constructing CDerived first a CBase is constructed and there is no awareness of CDerived (so overloaded function SomeChecks() is not called).</p> <p>I could do something like this:</p> <pre><code>class CBase { public: void Init() { /* Do some checks */ SomeChecks(); /* Do some more checks */ } virtual void SomeChecks() {} CBase(bool bDoInit=true) { if (bDoInit) { Init(); } } }; class CDerived : public CBase { public: virtual void SomeChecks() { /* Do some other checks */ } CDerived() : CBase(false) { Init() } }; </code></pre> <p>This isn't really safe, because I want the constructor with the false parameter be protected, so only derived classes can call it. But then I'll have to create a second constructor (that is protected) and make it take other parameters (probably unused because is constructor is called when Init() does not have to be called).</p> <p>So I'm quite stuck here.</p> <p><strong>EDIT</strong> Actually I want something like this:</p> <pre><code>class CBase { protected: void Init() { /* Implementation of Init ... */ } CBase() { /* Don't do the Init(), it is called by derived class */ } public: CBase() { Init(); } // Called when an object of CBase is created }; class CDerived : public CBase { public: CDerived() : CBase() { Init(); } }; </code></pre> <p>It seems to me it is impossible to have 2 constructors with the same arguments being protected and public?</p>
c++
[6]
1,245
1,246
Returning images/HTML using custom URI protocol on Android
<p>I'm wondering if it's possible to return web content through Android's ability to register custom URI protocols for launching apps, rather than launching the app itself, such that myapp://images/logo.png will return the image logo.png to a WebView</p> <p>I'm working on a tool for a company to open document libraries in Android. The libraries are just zip files with HTML, images, XML, etc.. The desktop version uses a custom URI protocol handler already, so as a result all the HTML files in the library are hard-coded to use it.</p> <p>Is there any way of implementing this? I'd rather not modify the DOM on load by injecting JavaScript, but from searching around it seems like the only way. Hopefully someone here will be able to tell me otherwise.</p> <p>Thanks, Daniel</p>
android
[4]
1,264
1,265
javascript rounding
<p>I want to round <code>TheCount / 5</code> to the next highest integer. When <code>TheCount = 12</code></p> <p>I tried:</p> <pre><code>Math.round(TheCount / 5); </code></pre> <p>but it returns 2 and I need it to return 3.</p> <p>How does rounding to the next highest integer work?</p> <p>Thanks.</p>
javascript
[3]
1,275
1,276
How Writing XMl file usning XMLStreamWriter in android
<p>i want create XML file here is my following code </p> <pre><code>String fileName = "jasstech.xml"; XMLOutputFactory xof = XMLOutputFactory.newInstance(); XMLStreamWriter xtw = null;** try { xtw = xof.createXMLStreamWriter(new FileOutputStream(fileName), "UTF-8"); xtw.writeStartDocument("UTF-8", "1.0"); xtw.writeStartElement("root"); xtw.writeComment("This is an attempt to create an XML file with StAX"); xtw.writeStartElement("foo"); xtw.writeAttribute("order", "1"); xtw.writeStartElement("meuh"); xtw.writeAttribute("active", "true"); xtw.writeCharacters("The cows are flying high this Spring"); xtw.writeEndElement(); xtw.writeEndElement(); xtw.writeStartElement("bar"); xtw.writeAttribute("order", "2"); xtw.writeStartElement("tcho"); xtw.writeAttribute("kola", "K"); xtw.writeCharacters("Content of tcho tag"); xtw.writeEndElement(); xtw.writeEndElement(); xtw.writeEndElement(); xtw.writeEndDocument(); } catch (XMLStreamException e) { e.printStackTrace(); } catch (IOException ie) { ie.printStackTrace(); } </code></pre> <p>The above Same Code is Working Fine in JAVA project But In Android Project gives following Error </p> <pre><code>03-03 07:48:40.778: ERROR/AndroidRuntime(719): Uncaught handler: thread main exiting due to uncaught exception 03-03 07:48:40.788: ERROR/AndroidRuntime(719): com.kochar.xml.stream.FactoryConfigurationError: Provider com.ctc.wstx.stax.WstxOutputFactory not found 03-03 07:48:40.788: ERROR/AndroidRuntime(719): at com.kochar.xml.stream.XMLOutputFactory.newInstance(XMLOutputFactory.java:23) </code></pre>
android
[4]
1,354
1,355
How to convert the following string to date or calendar object?
<p>Have a string like 2011-03-09T03:02:10.823Z, how to convert it to Date or calendar object?</p>
java
[1]
1,361
1,362
how do I add totals to a label when check the checkbox and then click submit?
<p>I have two checkboxes that prepopulate a radiobutton. When I select yes on the checkbox it open the radio button that's checked as true with text as a number. I would like to know how to select a single checkbox and display it as a total when I click submit button and it display my single checkbox number as a total in a label end if I select and checked both checkboxes it must add up both checkboxes radiobutton button numbers and display as a total so if single checkbox is selected display the single total end if both checkboxes is selected add up the two numbers and display total in a label when you click submit. Any help will do and be well appreciated Thanks</p> <p>Heres my code:</p> <pre><code>Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click Dim number1 As Double Dim number2 As Double Dim answer As Double Dim total As Integer number1 = Double.Parse(RadioButton1.Text) number2 = Double.Parse(RadioButton2.Text) If CheckBox1.Checked = True Then answer = number1 answerLbl.Text = answer.ToString() ElseIf CheckBox2.Checked = True Then answer = number2 answerLbl.Text = answer.ToString() ElseIf CheckBox1.Checked = True And CheckBox2.Checked = True Then answerLbl.Text = total.ToString() End If End Sub </code></pre>
asp.net
[9]
1,401
1,402
Parse .php and return as variable
<p>So say I have a file page.php</p> <pre><code>&lt;html&gt; Hello &lt;?php echo $world;?&gt; &lt;/html&gt; </code></pre> <p>I want to create a variable and assign it 'Hello world' using page.html</p> <p>Something like</p> <pre><code>$world = 'world'; $mypage = parse_file('page.php'); </code></pre> <p>I suppose I could wrap the entire file in doublequotes as such </p> <pre><code>$mypage="&lt;html&gt; Hello $world &lt;/html&gt;"; </code></pre> <p>but doublequote parsing is inefficient. Is there any easy of doing this without having to write a script that parses page.html?</p>
php
[2]
1,425
1,426
if passowrd and username matches(in action form) then how to navigate to further page on the succesful if statement
<p>Friends i am a newbie in php and trying to learn it more and more...</p> <p>I am telling you my problem what i am facing</p> <p>i have a employee signinform which have one username box and one password box with signin button..Now on the action page of this signinform i have given adress of signinvarification form..which matches the entered username and password with the database record.If username and password matches then it shows you have successfully login..otherwise not login...</p> <p>NOw i have one page in which i have employee pictures..</p> <p>Now what i want....????</p> <p>i want that as the employee signin then that login successfully msj does not display and directly the page which have employee pictures displayed..if sign in is successfull(means if password and usermae are matching).</p> <p>what i can do in this...</p> <p>i am thinking that on the if condition if username and password matches then after this i have to write the whole code which i have written for employee picture page on the signinvarification form...</p> <p>is there any possiblitye that simply i give the adress of that employee picture page and as password are matches it directly navigate to that picture page..</p> <p>plz tell me...I have given u full information which i can give</p>
php
[2]
1,436
1,437
Trying to write a code to keep asking the user the same dialog until they get it correct
<p>I have a code here and I'm not sure how to keep asking a question until the user answers the correct answer</p> <pre><code>while ((stringSize &gt;= 0) &amp;&amp; (stringSize &lt;= 4) &amp;&amp; (stringSize &gt;= 8)){ if ((stringSize &gt;= 0) &amp;&amp; (stringSize &lt;= 4) &amp;&amp; (stringSize &gt;= 8)){ System.out.println("no"); input = JOptionPane.showInputDialog(null, "Enter a word"); } if (secondChar == '+' &amp;&amp; ((stringSize &gt;= 4) &amp;&amp; (stringSize &lt;= 8))) { break; } } if (secondChar == '+' &amp;&amp; ((stringSize &gt;= 4) &amp;&amp; (stringSize &lt;= 10))){ } System.out.println("yes"); </code></pre>
java
[1]
1,455
1,456
UIImageView positioning problems?
<p>i wrote the following code:</p> <pre><code>-(void)viewDidLoad{ JumpVelocity = 10; aStandRightArray = [[NSArray alloc] initWithObjects:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"aStandR1" ofType:@"png"]], [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"aStandR2" ofType:@"png"]], [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"aStandR3" ofType:@"png"]], [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"aStandR2" ofType:@"png"]], nil]; aJumpRightArray = [[NSArray alloc] initWithObjects:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"aJumpR" ofType:@"png"]], nil]; aStandRight = [[UIImageView alloc] initWithFrame:CGRectMake(0, 242, 55, 65)]; aStandRight.animationImages = aStandRightArray; aStandRight.animationDuration = 0.5; [self.view addSubview:aStandRight]; aJumpRight = [[UIImageView alloc] initWithFrame:CGRectMake(0, 234, 69, 65)]; aJumpRight.animationImages = aJumpRightArray; [self.view addSubview:aJumpRight];} -(IBAction)buttonJumpRight:(id)sender{ [aStandRight stopAnimating]; [aStandRight removeFromSuperview]; [aJumpRight startAnimating]; jumpTimer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(playerJumpRight) userInfo:nil repeats:YES];} -(void)playerJumpRight{ [aJumpRight removeFromSuperview]; aJumpRight.center = CGPointMake(aJumpRight.center.x + JumpVelocity, 234); [self.view addSubview:aJumpRight]; if(aJumpRight.center.x &gt;= 84.0) { [jumpTimer invalidate]; jumpTimer = nil; [aJumpRight stopAnimating]; aStandRight.center = CGPointMake(84, 242); [aStandRight startAnimating]; [self.view addSubview:aStandRight]; } </code></pre> <p>}</p> <p>basically what i am trying to do here is load up a standing animation, then when the user presses the buttonJumpRight button i stop then unload the standing animation. after that i load up the jump animation and begin to move it across the screen with the playerJumpRight function.</p> <p>everything seems to work fine with two exception:</p> <ol> <li><p>the jump animation moves like expected along the x axis but for some reason does not keep its original y position which in the code above is "234".</p></li> <li><p>when the jump animation x position meets the requirements for the if statement everything works like expected newly created position for the standing animation is way off of the desire position of (84, 242).</p></li> </ol> <p>i been searching for quite some time, trying out many different possible solutions but fail at every try. please excused my newbieism as i just start coding for ios/objective c.</p> <p>i greatly appreciate any help you can offer. </p>
iphone
[8]
1,554
1,555
Geo Fencing in Android
<p>I am trying to build geo fencing in my android application. however i am not clear with this idea. whenever user opens my app, i want to see if he is in any AMC theater. how do i do that? should i use latitude longitude values or i should use physical address? if i use lat lon values how accurate will the output be? if i go for physical address, how time efficient will it be? i have currently written a code wherein i have hardcoded the values. but thats not going to work for real app. my app can track users coordinates but i am not clear how this data can b put to use.</p>
android
[4]
1,603
1,604
android virtual keyboard listener
<p>Though i have asked the question before but dint get any proper answer. I have an EditText when edit text is focused android virtual keyboard pops up, i have added Done button to the keyboard using ime option from property window. Now i want to perform some action by pressing the Done button. How to do this? Please any body help.</p> <p>Thanks &amp; Regards </p>
android
[4]
1,663
1,664
PHP: keeping the username in field
<p>How do i do if i want to keep the username in the field if the users entered incorrect password, so the person doesnt need to retype the username? Should i use sessions for this?</p>
php
[2]
1,666
1,667
Is there any differents between $GLOBALS["test"] and global $test?
<p>can any one please let me know the basic differences between </p> <pre><code>$GLOBALS["test"] and global $test </code></pre> <p>and, will it make sense that, if i use <code>$GLOBALS["test"]</code> instead of <code>$_SESSION['test']</code>?</p>
php
[2]
1,699
1,700
is it safe to use Debug Folder files for distribution?
<p>is it safe to use Debug Folder files for distribution ? or I should use release folder .</p> <p>I use vs 2008 express edition .</p>
c#
[0]
1,700
1,701
how do i put xml tagnames to be the elements in a drop down list using c#?
<p>I need to figure out how to get "Nancy" as an element in a drop down list.</p> <p>This is the XML file</p> <pre><code>&lt;employees&gt; &lt;employee employeeid="1"&gt; &lt;firstname&gt;Nancy&lt;/firstname&gt; &lt;lastname&gt;Davolio&lt;/lastname&gt; &lt;homephone&gt;(206) 555-9857&lt;/homephone&gt; &lt;notes&gt;&lt;![CDATA[includes a BA in psychology from Colorado State University in 1970. She also completed "The Art of the Cold Call." Nancy is a member of Toastmasters International.]]&gt;&lt;/notes&gt; &lt;/employee&gt; &lt;employees/&gt; </code></pre>
c#
[0]
1,719
1,720
How do you "break" out of a function?
<p>Given a function that returns a value, is it possible to exit the function given a certain condition without returning anything? If so, how can you accomplish this?</p> <p>Example:</p> <pre><code>int getNumber () { . . . } </code></pre> <p>So say you are in this function. Is there a way to exit it without it doing anything?</p>
c++
[6]
1,735
1,736
Why can I not call these JQuery/Javascript Functions in an external script file?
<p>I am writing a lot of JQuery code in a page and have decided to move some of the functions out to a separate file. So, file #1 has nothing but function definitions:</p> <pre><code>function doSomething() { ... } function doSomethingElse() { ... } </code></pre> <p>In the main page, I have placed my JQuery at the end of the file - following the optimization techniques found in Zakas' book "High Performance Javascript".</p> <p>So, at the very end of the file (but before the closing body tag) I have:</p> <pre><code>&lt;script type="text/javascript" src="/scripts/MyFunctions.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; doSomething(); doSomethingElse(); .... &lt;/script&gt; </code></pre> <p>Note that the final Javascript scripts are loaded - and run - after the page is loaded and the DOM declared. However, I get an error every time that says <strong>'doSomething' is undefined.</strong></p> <p>This works without problem if the functions are included in the main script. It is only when I pull them outside that I get this error. Now, my guess is that the first file hasn't being fully loaded/compiled when the second one makes its calls. But it seems to me that the last script (essentially acting in the "Ready" role) should be the one compiled last. When I look at JQuery and other JS files, they start with anonymous functions rather than just launching right in to function definitions so clearly there is something else going on.</p> <p>Note that I don't <em>think</em> it is a problem loading/finding the file: I've tried various paths to ensure that the path is correct and that hasn't fixed the issue.</p> <p>Does anyone have a clue why my functions aren't being found?</p> <p>Update: If I take the file contents exactly as they are found and put it into the first script tag rather than loading it from the file, this works fine. But I have checked the script file name repeatedly and it is correct. So it is something about the process of loading it from an external file.</p> <p>UPDATE: Solved. I ran it through FireBug as keegan and dskrepps suggested and it jumped right out at me. I had an ASP.NET variable that I was placing in the scripts but, of course, ASP.NET isn't parsing the file or replacing variables. When Javascript saw these replaceable values, it was dying on a parse error that wasn't reported. So - the file was NOT being loaded and it isn't a Javascript function call issue at all. Instead, it was an error between the keyboard and the seat. ;-)</p> <p>Thanks to everyone who helped!</p>
javascript
[3]
1,747
1,748
check if a collection is empty in java : Which is the best method
<p>I have two ways of comparing if a List is empty or not</p> <pre><code>if (CollectionUtils.isNotEmpty(listName)) </code></pre> <p>and </p> <pre><code>if(listName != null &amp;&amp; listName.size() != 0) </code></pre> <p>My arch tells me that the former is better than latter. </p> <p>But I think latter is better. Can anyone please clarify it.</p>
java
[1]
1,753
1,754
Countdown timer with pause and resume
<p>I want to do countdown timer with pause and restart.Now i am displaying countdown timer By implenting ontick() and onfinish().please help me out.HEre is th code for countdown timer</p> <pre><code>final CountDownTimer Counter1 = new CountDownTimer(timervalue1 , 1000) { public void onTick(long millisUntilFinished) { System.out.println("onTick method!"(String.valueOf(millisUntilFinished/1000)));long s1=millisUntilFinished; } public void onFinish() { System.out.println("Finished!"); } } </code></pre>
android
[4]
1,799
1,800
Attributes not available when overwriting __init__?
<p>I'm trying to overwrite a <code>__init__</code> method, but when I call the super method the attributes created in that method are not available. I can see that it's not an inheritance problem since <code>class B</code> still has the attributes available.</p> <p>I think the code sample will explain it better :-)</p> <pre><code>Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; class A(object): ... def __init__(self, *args, **kwargs): ... self.args = args ... self.kwargs = kwargs ... &gt;&gt;&gt; a = A('a', 'b', key='value') &gt;&gt;&gt; print a.args, a.kwargs ('a', 'b') {'key': 'value'} &gt;&gt;&gt; class B(A): ... pass ... &gt;&gt;&gt; b = B('b', 'c', key_b='value_b') &gt;&gt;&gt; print b.args, b.kwargs ('b', 'c') {'key_b': 'value_b'} &gt;&gt;&gt; class C(A): ... def __init__(self, *args, **kwargs): ... print 'class C' ... super(A, self).__init__(*args, **kwargs) ... &gt;&gt;&gt; c = C('c', 'd', key_c='value_C') class C &gt;&gt;&gt; print c.args, c.kwargs Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'C' object has no attribute 'args' &gt;&gt;&gt; class D(A): ... def __init__(self, *args, **kwargs): ... super(A, self).__init__(*args, **kwargs) ... print 'D' ... &gt;&gt;&gt; d = D('d', 'e', key_d='value D') D &gt;&gt;&gt; print d.args, d.kwargs Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'D' object has no attribute 'args' &gt;&gt;&gt; </code></pre>
python
[7]
1,831
1,832
Does replacing the content of a span raise an event?
<p>If I replace the content of a span using the syntax below, does it raise an event?:</p> <pre><code>$("#container").html(data); </code></pre> <p>I am trying to refresh another div whenever the content of #container changes, but I don't know which #container event to bind. I am using jQuery.</p> <p>Any assistance appreciated.</p> <p>UPDATE: Here is a more comprehensive code listing...</p> <pre><code>$.post(addUri, myForm.serialize(), function(data) { $("#container").html(data); }, 'html'); </code></pre>
jquery
[5]
1,845
1,846
What do return -1, 1, and 0 mean in this Javascript code?
<p>Here is the context:</p> <pre><code>function compare (value1, value2) { if(value1 &lt; value2) { return -1; } else if (value1 &gt; value2) { return 1; } else { return 0; } } var values = [0, 6, 8, 5]; values.sort(compare); alert(values); // 0,5,6,8 </code></pre> <p>does <code>-1</code> return the last argument? Like when using <code>-1</code> in an array?</p>
javascript
[3]
1,848
1,849
Programming a strobe light with C++ - create a frequency dialog box
<p>Hi: I have connected a photographic flash gun to my PC using a relay switch connected via the serial port. The following program successfully fires the flash as a strobe:</p> <pre><code>#include &lt;windows.h&gt; //Initialise Windows module int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nFunsterStil) { //Define the serial port precedure HANDLE hSerial; int freq = 4; int iterations = 10; int x; for ( x = 0; x &lt; iterations; x++) { //Fire the flash (open the serial port, and immediately close it) hSerial = CreateFile("COM1",GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); CloseHandle(hSerial); //Sleep in between flashes for specified duration Sleep (1000/freq); } return 0; } </code></pre> <p>What I would like to do is have the flash fire at a frequency defined by the user (in Hz). Basically, this program, plus a dialog box that allows the user to choose values for 'freq' and 'iterations' before the thing starts flashing.</p> <p>I have successfully implemented dialog boxes in previous projects by including the following code at the start of my main.c file:</p> <pre><code>#ifdef WIN32 #include &lt;w32_dialogs.h&gt; #endif </code></pre> <p>And using something along these lines where the actual dialog box should occur:</p> <pre><code>#ifdef WIN32 edit_dialog(NULL,"Dialog Title", "Please enter variable:", variable,260); #endif# </code></pre> <p>So, based on this, I have updated the code to the following:</p> <pre><code>#include &lt;windows.h&gt; #ifdef WIN32 #include &lt;w32_dialogs.h&gt; #endif //Initialise Windows module int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nFunsterStil) { //Define the serial port precedure HANDLE hSerial; int freq = 4; int iterations = 10; int x; //Buffers for variable entry into text box char freq_buf[256]; char iterations_buf[256]; //Convert dialog buffer to useable values sprintf( freq_buf, "%lf", freq); sprintf( iterations_buf, "%lf", iterations); #ifdef WIN32 edit_dialog(NULL,"Enter frequency", "Please enter frequency:", freq_buf,260); #endif# #ifdef WIN32 edit_dialog(NULL,"Enter iterations", "Please enter number of iterations:", iterations_buf,260); #endif# freq = atoi(freq_buf); iterations = atoi(iterations_buf); for ( x = 0; x &lt; iterations; x++) { //Fire the flash (open the serial port, and immediately close it) hSerial = CreateFile("COM1",GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); CloseHandle(hSerial); //Sleep in between flashes for specified duration Sleep (1000/freq); } return 0; } </code></pre> <p>However, this does not compile. I am using Dev-C++ (I usually use VC++ but couldnt get it to work there either)</p> <p>The errors are: - 'w32_dialogs.h': no such file or directory; 'sprintf' is undeclared; and 'edit_dialog' is undeclared.</p> <p>It looks to me that this is a simple case of not being able to find the w32_dialogs.h file. How do I set this up in Dev-C++?</p>
c++
[6]
1,918
1,919
Limiting a table in a foreach loop to 5 rows
<p>How do I limit the table below to 5 rows?</p> <pre><code> echo "&lt;table class='sidetable2'&gt;"; $blacklist = array($submission, 'DESPITE', 'FARE', 'DECENT', 'AMAZING', 'WOULD', 'DISLIKE', 'HATE', 'OKAY', 'JUST', 'NOTHING', 'CURRENTLY', 'BASICALLY', 'BIT', 'COME', 'WANT', 'TOO', 'HERE', 'EATING', 'EAT', 'WAS', 'TRIED', 'TRY', 'MAKES', 'HAS', 'EVEN', 'THINK', 'BETTER', 'YET', 'MORE', 'LOVE', 'WHILE', 'WHERE', 'WRONG', 'FIND', 'EVER', 'RIGHT', 'BEST', 'HAVE', 'WE', 'WAY', 'GREAT', 'NICE', 'HOW', 'RESTAURANTS', 'RESTAURANT', 'EXCELLENT', 'FORGET', 'THEY', 'REALLY', 'MISS', 'VERY', 'LOOKING', 'YOU\'LL', 'CAN\'T', 'WON\'T', 'PLACE', 'ABOUT', 'FOR', 'MOST', 'GOOD', 'CAN', 'GET', 'THING', 'DON\'T', 'BY', 'YOUR', 'BE', 'YOU', 'BRING', 'THAT\'S', 'LITTLE', 'OTHER', 'MANAGES', 'ATE', 'ATE', 'EAT', 'SO', 'SOMEHOW', 'MAKE', 'ALL', 'UP', 'THEM', 'AS', 'THEM', 'YOU\'RE', 'WILL', 'ONLY', 'IF', 'GO', 'DO', 'I\'VE', 'HAD', 'TO', 'SOME', 'FOOD', 'THIS','DOES', 'NOT', 'IT.', 'IT,', 'SEEM', 'END', 'THERE\'S', 'WHETHER', 'DOUBT', 'WHAT', 'WHICH', 'RECOMMEND', 'THE', 'IS', 'A', 'IT\'S', 'OUT', 'JAN', 'IT', 'IT', 'IT', 'LIKE', 'THAN', 'WITH', 'SEEMS', 'WHICH', 'THAT', 'SAY', 'AT', 'ON', 'AN', 'BUT', 'APART', 'STILL', 'ARE', 'OR', 'TEST', 'IN', 'IT', 'AND', 'SET', 'TO', 'NO', 'OF', '', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'BB', 'CC', 'DD', 'EE', 'FF', 'GG', 'HH', 'II', 'JJ', 'KK', 'LL', 'MM', 'NN', 'OO', 'PP', 'QQ', 'RR', 'SS', 'TT', 'UU', 'VV', 'WW', 'XX', 'YY', 'ZZ'); foreach($result as $word =&gt; $count1) { if (in_array($word, $blacklist)) continue; echo '&lt;tr&gt;'; echo '&lt;td&gt;'; echo "$word"; echo '&lt;/td&gt;'; echo '&lt;td&gt;'; echo "$count1 "; echo '&lt;/td&gt;'; echo '&lt;/tr&gt;'; } echo "&lt;/table&gt;"; </code></pre>
php
[2]
1,936
1,937
javascript countdown
<pre><code>&lt;span id="count_down"&gt;&lt;/span&gt;&lt;/p&gt; &lt;script type="text/javascript"&gt; var bum=0 var seconds=7 function display() { if (bum&lt;=0){ bum=9 seconds-=1 } if (seconds&lt;=-1){ seconds+=1 } else bum-=1 document.getElementById('count_down').innerHTML=seconds setTimeout("display()",100) } display() &lt;/script&gt; </code></pre> <p>It's count down from 7 to 0. I wanna this script to count down from 7 to 1 and instead of 0 showing display text like: omg, zero reached! or smth. And if can please make this script more "beautifier" or more simple, because in my mind var bum doesn't needed.</p>
javascript
[3]
1,952
1,953
C# how to generate a proper error quickly for testing purposes
<p>I have some code in my error handler I need to test against a realistic error. How can I generate an error that has a full stack trace and is just as realistic as a runtime error. </p> <p>I am using a general catch on an exception. So do not need a specific type of exception in this particular case. </p> <p>Thanks</p>
c#
[0]
1,983
1,984
How to dynamically select a method call in Python?
<p>I have a code similar to this:</p> <pre><code>if command == "print": foo_obj.print() if command == "install": foo_obj.install() if command == "remove": foo_obj.remove() </code></pre> <p><code>command</code> is a string (I define it by parsing command line arguments, but that's beyond the point). Is there a way to replace the above chunck of code with something similar to this?</p> <pre><code>foo_obj.function(command) </code></pre> <p>For the recored I'm using Python 2.7</p>
python
[7]
2,039
2,040
Javascript: read number of any value
<p>I'm trying to apply a tooltip to a foreach loop, but I need the javascript to read the attribute "mystickytooltip" with a number at the end. </p> <pre><code>&lt;div id="mystickytooltip{$smarty.foreach.cart.iteration}" class="stickytooltip"&gt; </code></pre> <p>Will output </p> <pre><code>&lt;div id="mystickytooltip1" class="stickytooltip"&gt; &lt;div id="mystickytooltip2" class="stickytooltip"&gt; &lt;div id="mystickytooltip3" class="stickytooltip"&gt; </code></pre> <p>And I need the javascript to read "mystickytooltip(ANYVALUE)" is this possible? My JS knowledge sucks. </p> <pre><code>//stickytooltip.init("targetElementSelector", "tooltipcontainer") stickytooltip.init("*[data-tooltip]", "mystickytooltip") </code></pre> <p>Thanks.</p>
javascript
[3]
2,057
2,058
java hashmap basic question
<pre><code>HashMap model1 = wordobject.getMap(); Set sample = model1.keySet(); Iterator it = sample.iterator(); </code></pre> <p>== Can you please explain me the above 3 lines? I see that we are trying to get the hash table from the object and get it assigned to the HashMapmodel1.</p> <p>1) what is keyset? 2) what does .iterator do?</p>
java
[1]
2,107
2,108
Modify Meta Refresh any time there is an AJAX postback
<p>I have a meta refresh that redirects to a page when the application times out.</p> <pre><code>&lt;meta http-equiv="refresh" content="1200;url=/SessionExpired.aspx"&gt; </code></pre> <p>But when a user is interacting with that page, the redirect will obviously fire regardless of whether the user has been working interactively via AJAX postbacks.</p> <p>How can I reset the meta refresh countdown whenever the user is perceived to be continuing an interaction with the page? (via an AJAX postback, for example).</p> <p>I'm working with ASP.NET Web Forms using UpdatePanel to AJAXify my page.</p> <p>Thanks,</p> <p>Richard</p>
asp.net
[9]
2,142
2,143
Handling the "Enter" / "Return" key in Chrome
<p>I have an AJAX-y type page. When the user clicks "GO" I need to execute a specific javascript function. I also want to simulate the "GO" click when a user hits "Enter" or "Return. Please note that I do not want to "submit" the page. The reason why is because i am doing everything via JavaScript.</p> <p>To handle the "Enter" / "Return" key press in IE and FireFox, I am using the following code:</p> <pre><code>$(document).ready(function () { $('#root').keypress(function(e) { if (e.keyCode == '13') { goButton(); } }); }); </code></pre> <p>Unfortunately, this code is not working in Chrome. The goButton() function gets called. The problem though is the page gets submitted. What am I doing wrong?</p>
javascript
[3]
2,173
2,174
C# Language updates
<p>How often has the C# language standard been updated and what is the current version?</p>
c#
[0]
2,242
2,243
what does the role of l.strip() in this statement
<pre><code>lines = [l.split() for l in inpf.readlines() if l.strip()] </code></pre> <p>In the above statement, what does <code>l.strip()</code> do? </p> <pre><code>lines = [l.split() for l in inpf.readlines()]. </code></pre> <p>Will the above statement will not suffice?</p>
python
[7]
2,247
2,248
What is the difference between an interface and a class in Java?
<p><br> can any one give precise difference between an interface and class in java.</p> <p><strong>Duplicate:</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/258285/is-a-java-interface-an-abstract-class">http://stackoverflow.com/questions/258285/is-a-java-interface-an-abstract-class</a></li> <li><a href="http://stackoverflow.com/questions/639592/why-are-interfaces-preferred-to-abstract-classes">http://stackoverflow.com/questions/639592/why-are-interfaces-preferred-to-abstract-classes</a></li> </ul>
java
[1]
2,280
2,281
Access point name manipulation in android
<p>In my android application I need to turn data roaming off. Because data roaming is a system preference that can only be read, not written (it belongs to Settings.Secure) , I'm thinking to get the Access Point Names of the phone and change/invalidate them so a data service won't be available when I detect the phone is roaming. I'm thinking it's a good idea and I could obtain the desired behavior but in order to be able to do this I need to know a couple of things first:</p> <p>1.How to modify an APN ?</p> <p>2.What field of the APN should be geven a empty value like "", in order to make it unusefull: name ?, proxy? , server ?, APN ?...</p> <p>3.Which APN should be modified , or all of them should be treated the same way ?.</p> <p>Thanks</p>
android
[4]
2,284
2,285
prefer conversion operator over conversion constructor
<p>I have the following code snippet:</p> <pre><code>class A { public: A() : x_(0), y_(0) {} A(int x, int y) : x_(x), y_(y) {} template&lt;class T&gt; A(const T &amp;rhs) : x_(rhs.x_), y_(rhs.y_) { } int x_, y_; }; class B { public: B() {} operator A() const { return A(c[0],c[1]); } int c[2]; }; void f() { B b; (A)b; // &lt;&lt; here the error appears, compiler tries to use // template&lt;class T&gt; A(const T &amp;rhs) } </code></pre> <p>Why compiler uses <code>A</code>'s constructor? How can I make it use <code>B</code>'s conversion operator to <code>A</code>?</p> <p>I use MSVS2010 compiler. It gives me these errors:</p> <pre><code>main.cpp(9): error C2039: 'x_' : is not a member of 'B' main.cpp(17) : see declaration of 'B' main.cpp(28) : see reference to function template instantiation 'A::A&lt;B&gt;(const T &amp;)' being compiled with [ T=B ] main.cpp(9): error C2039: 'y_' : is not a member of 'B' main.cpp(17) : see declaration of 'B' </code></pre> <p><strong>UPD</strong>: All right, implicit convert as Nawaz said really works. Let's make it more complicated, how make the following code work?</p> <pre><code>void f() { std::vector&lt;B&gt; b_vector(4); std::vector&lt;A&gt; a_vector( b_vector.begin(), b_vector.end() ); } </code></pre> <p><strong>UPD</strong>: <code>A</code> is the class in 3rd party lib which code I can't edit, so I can't remove <code>A</code>'s converting constructor.</p> <p><strong>UPD</strong>: the simplest solution I've found for the moment is to define specialization of converting constructor for <code>B</code>. It can be done outside of 3rd party lib:</p> <pre><code>template&lt;&gt; A::A( const B &amp;rhs ) : x_(rhs.c[0]), y_(rhs.c[1]) {} </code></pre>
c++
[6]
2,338
2,339
Why list doesn't have safe "get" method like dictionary?
<pre><code>&gt;&gt;&gt; d = {'a':'b'} &gt;&gt;&gt; d['a'] 'b' &gt;&gt;&gt; d['c'] KeyError: 'c' &gt;&gt;&gt; d.get('c', 'fail') 'fail' &gt;&gt;&gt; l = [1] &gt;&gt;&gt; l[10] IndexError: list index out of range </code></pre>
python
[7]
2,344
2,345
Capitalizing the first character of a string - Java
<p>I've looked all over for how to capitalize the first character of a string, but nothing I've found has helped. For my method to work, I need to set a user entered string to lower case.</p> <pre><code>sourceText = enterText.getText(); char chr = sourceText.charAt(0); </code></pre> <p>so I have a boolean that's true if the first character is uppercase.</p> <pre><code>boolean upperCase = Character.isUpperCase(chr); sourceTextLower = sourceText.toLowerCase(); </code></pre> <p>Cool stuff happens here, and the final product is another string called translatedTextString and an if statement</p> <pre><code>String s2 = ""; if(upperCase == true) { int x = translatedTextString.length(); s2 = translatedTextString.substring(0,1).toUpperCase().concat(translatedTextString.substring(1, x)); } //translatedText is a label translatedText.setText(s2); </code></pre> <p>However, when I run the program, the first character of my result is still lower case. So my questions is: is this even the right way to go about doing this? If so, what am I doing wrong, and if not, how can I do it correctly?</p>
java
[1]
2,399
2,400
typeof (undefined variable) causing error...?
<pre><code>alert(typeof QuizParser.Parser.otherdata['response_set']['answers']["slide_" + _index]['trt']);​ </code></pre> <p>Why? Shouldn't this simply alert the string <code>undefined</code>? If this is wrong, how should I check to see if that variable is defined or not?</p>
javascript
[3]
2,418
2,419
dispatcher python
<p>hy all, I have the following "wrong" dispatcher:</p> <pre><code>def _load_methods(self): import os, sys, glob sys.path.insert(0, 'modules\commands') for c in glob.glob('modules\commands\Command*.py'): if os.path.isdir(c): continue c = os.path.splitext(c)[0] parts = c.split(os.path.sep ) module, name = '.'.join( parts ), parts[-1:] module = __import__( module, globals(), locals(), name ) _cmdClass = __import__(module).Command for method_name in list_public_methods(_cmdClass): self._methods[method_name] = getattr(_cmdClass(), method_name) sys.path.pop(0) </code></pre> <p>It produces the following error:</p> <p>ImportError: No module named commands.CommandAntitheft</p> <p>where Command*.py is placed into modules\commands\ folder</p> <p>can someone help me?</p> <p>One Possible solution (It works!!!) is:</p> <pre><code> def _load_methods(self): import os, sys, glob, imp for file in glob.glob('modules/commands/Command*.py'): if os.path.isdir(file): continue module = os.path.splitext(file)[0].rsplit(os.sep, 1)[1] fd, filename, desc = imp.find_module(module, ['./modules/commands']) try: _cmdClass = imp.load_module( module, fd, filename, desc).Command finally: fd.close() for method_name in list_public_methods(_cmdClass): self._methods[method_name] = getattr(_cmdClass(), method_name) </code></pre> <p>It still remains all risks suggested by bobince (tanks :-) )but now I'm able to load commands at "runtime"</p>
python
[7]
2,428
2,429
max file name length in Android
<p>I am trying give a name for a file that I am creating. I just want to know that what is the max file name length in Android ?</p> <p>Is there a specification for a file name? Can I use characters like <code>-</code> or <code>&gt;</code> ? </p>
android
[4]
2,442
2,443
(Python) algorithm to randomly select a key based on proportionality/weight
<p>I'm a bit at a loss as to how to find a clean algorithm for doing the following:</p> <p>Suppose I have a dict k:</p> <pre><code>&gt;&gt;&gt; k = {'A': 68, 'B': 62, 'C': 47, 'D': 16, 'E': 81} </code></pre> <p>I now want to randomly select one of these keys, based on the 'weight' they have in the total (i.e. sum) amount of keys. </p> <pre><code>&gt;&gt;&gt; sum(k.values()) &gt;&gt;&gt; 274 </code></pre> <p>So that there's a </p> <pre><code>&gt;&gt;&gt; 68.0/274.0 &gt;&gt;&gt; 0.24817518248175183 </code></pre> <p>24.81% percent change that A is selected.</p> <p>How would you write an algorithm that takes care of this? In other words, that makes sure that on 10.000 random picks, A will be selected 2.481 times?</p>
python
[7]
2,444
2,445
Python having problems writing/reading and testing in a correct format
<p>I’m trying to make a program that will do the following:</p> <ul> <li>check if auth_file exists <ul> <li>if yes -> read file and try to login using data from that file - if data is wrong -> request new data</li> <li>if no -> request some data and then create the file and fill it with requested data</li> </ul></li> </ul> <p>So far:</p> <pre><code>import json import getpass import os import requests filename = ".auth_data" auth_file = os.path.realpath(filename) url = 'http://example.com/api' headers = {'content-type': 'application/json'} def load_auth_file(): try: f = open(auth_file, "r") auth_data = f.read() r = requests.get(url, auth=auth_data, headers=headers) if r.reason == 'OK': return auth_data else: print "Incorrect login..." req_auth() except IOError: f = file(auth_file, "w") f.write(req_auth()) f.close() def req_auth(): user = str(raw_input('Username: ')) password = getpass.getpass('Password: ') auth_data = (user, password) r = requests.get(url, auth=auth_data, headers=headers) if r.reason == 'OK': return user, password elif r.reason == "FORBIDDEN": print "Incorrect login information..." req_auth() return False </code></pre> <p>I have the following problems(understanding and applying the correct way):</p> <ul> <li>I can't find a correct way of storing the returned data from req_auth() to auth_file in a format that can be read and used in load_auth file</li> </ul> <p>PS: Of course I'm a beginner in Python and I'm sure I have missed some key elements here :(</p>
python
[7]
2,524
2,525
Trying to use file encryption but am getting an error with File.Encrypt(FileName) returning an exception
<p>I tried codeproject help as well as MSDN but no success. Here is a copy of my test code returning an exception:</p> <pre><code> private void button2_Click(object sender, EventArgs e) { File.Decrypt("Text.pvf"); string[] DataFile = File.ReadAllLines("Text.pvf"); if (DataFile[5] == "6") MessageBox.Show("Encrypt/Decrypt successful"); //Application.Exit(); } private void button1_Click(object sender, EventArgs e) { string[] DataFile = new string[6]; DataFile[0] = "1"; DataFile[1] = "2"; DataFile[2] = "3"; DataFile[3] = "4"; DataFile[4] = "5"; DataFile[5] = "6"; File.WriteAllLines("Text.pvf", DataFile); File.Encrypt("Text.pvf"); </code></pre> <p>At the line: "<code>File.Encrypt("Text.pvf");</code>", I get an IOException and it says:'The request is not supported.'. Now the button1 method is called first. I do not know why this error comes up.</p> <p>My pc: Windows7 64bit, .net 4.0, file system is NTFS as needed for File.Encryption method.</p> <p>Please copy and paste my code to see if you can maybe spot the error. Perhaps I am missing something. Please help</p>
c#
[0]
2,571
2,572
C++ interview - testing potential candidates
<p>I have to interview some C++ candidates over the next few weeks and as the most senior programmer in the company I'm expected to try and figure out whether these people know what they are doing.</p> <p>So has anybody got any suggestions?</p> <p>Personally I hate being left in a room to fill out some C++ questions so I'd rather do a more complex test that I can chat with the interviewee about their approaches and so forth as we go along. ie it doesn't matter whether they get the right answers or not its how they approach the problem that interests me. I don't care whether they understand obscure features of the language but I do care that they have a good solid understanding of pointers as well as understanding the under lying differences between pointers and references. I would also love to see how they approach optimisation of a given problem because solid fast code is a must, in my opinion.</p> <p>So any suggestions along these lines would be greatly appreciated!</p>
c++
[6]
2,643
2,644
update the number of the person in file
<p>Aslam o alikum I am making a project using file handling in c++ like address book, in which user enter New record search previous record and update the previous record.</p> <p>But when it come to update , the problem occur is the previoud record remain at the same place and new record is added,but i want that the previous record will delete from my file. please give me the easiest sollution</p>
c++
[6]
2,650
2,651
javascript date problem
<p>my problem datetime now Add 63 day.</p> <p>javascript code:</p> <pre><code>var aDate = new Date(); var ax_year = aDate.getFullYear(); var ax_mon = aDate.getDate(); var ax_day = aDate.getDay(); var axDate = ax_mon + '.' + ax_day + '.' + ax_year; </code></pre> <p>axDate = now 28.05.2010 </p> <p>i need axDate + 63 day = 31.07.2010 how to make</p>
javascript
[3]
2,654
2,655
Comparing uibutton clicks
<p>I want to be able to control certain functions when a button is clicked either by having a bool or another variable know how many times the button was clicked. For example if the button was clicked once i want to make it display an NSLOG of lets say 1, if its pressed twice i want NSLOG of 2, however once you press it again I cant find a way to get it back to 1..</p>
iphone
[8]
2,738
2,739
Is there an equivalent in PHP to .NET's datasets?
<p>ASP.NET has the concept of a dataset to capture the data and build relationships with the data, and maintain good performance without having persistent SQL connections.</p> <p>Is there something similar in PHP that I can use?</p>
php
[2]
2,800
2,801
how to add the text of a select box and the text of form input into a hidden field
<p>I' trying to add a text of select box and the some text from a form into a hidden field,I can get the text of a select box but I can get the required text from form, can anyone help please.</p> <pre><code> &lt;form&gt; &lt;select name="select" id="select"&gt; &lt;option&gt;Select your pizza&lt;/option&gt; &lt;option value="6.65"&gt;NY, 10&amp;quot;, £6.65&lt;/option&gt; &lt;option value="8.95"&gt;NY, 12&amp;quot;, £8.95&lt;/option&gt; &lt;option value="11.95"&gt;NY, 16&amp;quot;, £11.95&lt;/option&gt; &lt;option value="3.45"&gt;Chicago, 7&amp;quot;, £3.45&lt;/option&gt; &lt;option value="6.65"&gt;Chicago, 10&amp;quot;, £6.65&lt;/option&gt; &lt;option value="8.95"&gt;Chicago, 12&amp;quot;, £8.95&lt;/option&gt; &lt;option value="11.95"&gt;Chicago, 16&amp;quot;, £11.95&lt;/option&gt; &lt;option value="19.95"&gt;Chicago, Beast 24&amp;quot; x 18&amp;quot;, £19.95&lt;/option&gt; &lt;/select&gt; &lt;/form&gt; &lt;form id="toppings"&gt; &lt;span class="descriptionsPizza"&gt;EXTRA CHEESE&lt;/span&gt; &lt;input name="minus1" type="button" class="button minus" id="minus1" value=" - " /&gt; &lt;input name="textfield1" type="text" id="textfield1" class="valfield" size="2" maxlength="2" value="0" /&gt; &lt;input name="add1" type="button" class="button add" id="add1" value=" + " /&gt; &lt;span class="descriptionsPizza"&gt;HAM&lt;/span&gt; &lt;input name="minus2" type="button" class="button minus" id="minus2" value=" - " /&gt; &lt;input class="valfield" name="textfield2" type="text" id="textfield2" size="2" maxlength="2" value="0"/&gt; &lt;input name="add2" type="button" class="button add" id="add2" value=" + " /&gt; &lt;/form&gt; $(function() { //functions to change the quantity field by pressing the + and - buttons // add buttons $(".add").click(function(){ var $this = $(this); var quantity = parseInt($this.siblings(".valfield").val(), 10) + 1; $(this).siblings(".valfield").val(quantity); }); // minus buttons $(".minus").click(function(){ var $this = $(this); var quantity = parseInt($this.siblings(".valfield").val(), 10) - 1; if(quantity &lt; 0) quantity = 0; $(this).siblings(".valfield").val(quantity); }); $('input[name=my-add-button]').click(function() { var randomNumber = Math.floor((Math.random() * 9000) + 100); $('input[name=my-item-id]').val(randomNumber); $('input[name=my-item-name]').val( $("#select :selected").text() ); $('input[name=my-item-price]').val( $('#update_price').val() ); }); </code></pre> <p>so I need to add the toppings name (the text in the span tag) if the quantity of that topping is greater than 0 add the text in the span into the hidden field as well as the selected text box.</p> <p>thanks for any help. </p>
jquery
[5]
2,826
2,827
Reference images storing in android
<p>I have developed an app for image comparison. now i am storing the reference images on sdcard and the app is working fine. my problem is that.. if anyone removed the sdcard then the app will not be work. is there any method to store the reference images in the app itself so that any user can download and can use the app?? im using android 2.2</p>
android
[4]
2,855
2,856
Why is using TransactionScope's default constructor harmful?
<p>Why is it harmful to use <code>TranscationScope</code>'s default constructor? </p> <p>Can someone point me to explanation of this?</p>
c#
[0]
2,867
2,868
Trigger is not working in my case
<p>Hi all i am trying to fire click event of a on input changing in it.But it is not working. Please someone find mistakes i have done in my code.Below is my HTML</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="radio" id="a"&gt;&lt;div class="x"&gt;&lt;label for="a"&gt;ClickHere&lt;/label&gt;&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="checkbox" id="b"&gt;&lt;div class="x"&gt;&lt;label for="b"&gt;ClickHere&lt;/label&gt;&lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="radio" id="c"&gt;&lt;div class="x"&gt;&lt;label for="c"&gt;ClickHere&lt;/label&gt;&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="checkbox" id="d"&gt;&lt;div class="x"&gt;&lt;label for="d"&gt;ClickHere&lt;/label&gt;&lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>Below is my Jquery code.. </p> <pre><code> $('TABLE TBODY TR').delegate(':radio','change',function() { $(this).parents('td').trigger('click') if(($(this).parents('TD').find('input').filter(':checked').length)*1 &gt; 0) { $(this).parents('TR').children('td').not($(this).parent('TD')).find('input').prop('checked',false) $(this).parents('TD').find('input').prop('checked','checked') } }); $('TABLE TBODY TR').delegate(':checkbox','change',function() { $(this).parents('td').trigger('click') if($(this).parents('TD').find('input').length &gt; 1) { if(($(this).parents('TD').find('input').filter(':checked').length)*1 &gt; 0) { $(this).parents('TD').find(":radio").prop('checked',$(this).prop('checked')) $(this).parents('TR').children('TD').not($(this).parent('TD')).find('input').prop('checked',false) $(this).closest('TR').children('TD').not($(this).parent('TD')).find(':radio').prop('checked',false); } } if(($(this).parents('TD').find('input').filter(':checked').length)*1 &gt; 0) { $(this).parents('TR').children('TD').not($(this).parent('TD')).find('input').prop('checked',false) } }); $('TABLE TBODY TR').delegate('TD','click',function() { alert("Clicked index is"+$(this).index()) }); </code></pre>
jquery
[5]
2,874
2,875
Jquery onClick but on Tab
<p>This code works fine when the user clicks a field. I want it so that when they tab (press the alt key) or ANY key.. no matter what happens, if this field is active, run this jQuery code. So far I only know .click()</p> <pre><code>jQuery(document).ready(function(){ $("#fullname").click(function(){ $("#note_email").fadeIn(); }); }); &lt;input type="text" name="fullname" id="fullname" value="" /&gt;&lt;div style="display:none" id="note_email"&gt;Your name is case sensitive&lt;/div&gt; </code></pre>
jquery
[5]
2,909
2,910
Simpletron sentinel-controlled loop
<p>I'm currently using Java How to program 9/e of Deitel and I'm currently stuck on an exercise at the Simpletron programing challenge which states:</p> <p>Now write SML programs to accomplish each of the following tasks: a) Use a sentinel-controlled loop to read 10 positive numbers. Compute and display their sum.</p> <p>I've written the Simpletron class and it works fine with the example programs the book gives. But I'm really confuse about this question.</p> <p>Wouldn't it require to dynamically compute the address each time a new value is entered?</p> <p>I can make it hardcoded to accept only 10 values and immediately do the rest of the task.</p> <p>But how on earth am I going to make it behave like the following pseudo code?</p> <pre><code>while input is not -1 insert input at addr addr++ </code></pre> <p>Below is a sample program of Simpletron which outputs the largest number:</p> <pre><code>00 +1009 (Read A) 01 +1010 (Read B) 02 +2009 (Load A) 03 +3110 (Subtract B) 04 +4107 (Jump if negative to 07) 05 +1109 (Write A) 06 +4300 (Halt) 07 +1110 (Write B) 08 +4300 (Halt) 09 +0000 (Variable A) 10 +0000 (Variable B) </code></pre> <p>So basically 10 is the read command and 09 is the address so 1009 reads input and stores it at address 09.</p> <p>Any ideas?</p>
java
[1]
2,978
2,979
How to get and disect the query string appended into a url? PHP
<p>I am trying to develop a PHP class which would enable me to get the query string appended into a url and process it according to the variables passed. How can this be done?</p> <p>Eg</p> <pre><code>www.example.com?var1=a&amp;var2=b&amp;var3=c </code></pre> <p>now I want to get <code>?var1=a&amp;var2=b&amp;var3=c</code> section and process it based on the variables.</p> <p>Thanks for your responses</p> <p>but I want a means by which I can get the whole query string since I wont be sure of the variable names that will be sent into the URL thus the $_GET method wont work properly.</p> <p>Thanks</p>
php
[2]
3,040
3,041
CVXOPT output suppression with MOSEK
<p>I'm using the optional MOSEK solver with CVXOPT Quadratic Programming, i.e.</p> <pre><code>sol = cvxopt.solvers.qp(-Q,-p,G,h,A,b,solver='mosek') </code></pre> <p>Now without using the MOSEK solver, i.e.</p> <pre><code>sol = cvxopt.solvers.qp(-Q,-p,G,h,A,b) </code></pre> <p>Terminal output generated by CVXOPT can be suppressed with the command</p> <pre><code>cvxopt.solvers.options['show_progress'] = False </code></pre> <p>However, this does not work when using the MOSEK solver option. The MOSEK solver, which I have within a couple of loops, produces a lot of output I'm not interested in, meaning I can't see the output I am interested in (i.e what I choose to output using 'print').</p> <p>Does anyone know if it's possible to suppress the MOSEK output? Or if not, a potential work around (pipe the output to a file or something)?</p> <p>Many thanks!</p> <p>Dan</p> <p>p.s Sorry I couldn't include more specific tags (I'm not allowed to create new tags).</p>
python
[7]
3,050
3,051
jQuery change var by event in real time - not work
<p>How make change "aspectRatio" in settings <a href="https://github.com/trentrichardson/UberUploadCropper/blob/master/example-advanced/index.php" rel="nofollow">https://github.com/trentrichardson/UberUploadCropper/blob/master/example-advanced/index.php</a> in real time.</p> <pre><code>$(function() { $.("#test1").click( function () { $ratio = 1; }); $.("#test2").click( function () { $ratio = 2; }); $('#UploadImages').uberuploadcropper({ ... 'aspectRatio': $ratio, </code></pre> <p>It not work. Why? How it is correct to make?</p>
jquery
[5]
End of preview.
README.md exists but content is empty.
Downloads last month
32