text
stringlengths
8
267k
meta
dict
Q: How can I create (in Javascript), a tool to identify the longest repeated pattern in a series of numbers? Alright, long story short, what I overall am attempting to do, is test the level of randomness in a series of multiple thousands of " previously generated seemingly "random" numbers. I've already written something that will test for the probability of numbers with great success, however, the next step is identifying repeating or recurring patterns. I'd prefer to get this part done in javascript, so as to avoid having to teach myself another language for the time being. Now, obviously, I could just use regex and punch in some random sequences myself, but that is not ideal, and would take an infinite amount of time to get the results I'm after. A: Ah, I missed a number of your comments above. I believe this is what you're looking for: function findLongestMatch(StringOfNumbers) { var matches = StringOfNumbers.match(/(.{2,})(?=.*?\1)/g); if (!matches) { return null; } var longestMatch = matches[0]; var longestMatchLength = longestMatch.length; for (matchIndex = 1; matchIndex < matches.length; matchIndex++) { if (matches[matchIndex].length > longestMatchLength) { longestMatch = matches[matchIndex]; longestMatchLength = longestMatch.length; } } return longestMatch; } It'll be slow, but it'll get the job done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: awk åäö umlaut-chars has length of 2 I'm using awk (mac os x) to print only lines that are n characters and longer. If I try it on a text file (strings.txt) that looks like this: four foo bar föö bår fo ba fö bå And I run this awk script: awk ' { if( length($0) >= 3 ) print $0 } ' <strings.txt The output is: four foo bar föö bår fö bå (The last two lines should not have been printed). It seems like words that contain umlaut-characters (å, ä, ö...) count as two characters. (The input file is saved in UTF8 format.) A: BSD awk (a.k.a BWK awk), as preinstalled on macOS (still true as of macOS 10.13), is - sadly - NOT Unicode-aware. Your choices are: * *IF you know that the characters involved fit into a single-byte encoding such as ISO-8859-1, you can use iconv as follows: iconv -f UTF-8 -t ISO-8859-1 file | awk 'length >= 3' | iconv -f ISO-8859-1 -t UTF-8 *Install a different awk implementation that is Unicode-aware, such as gawk (GNU Awk) or mawk; e.g., via Homebrew: * *brew info gawk *brew info mawk *Use a different preinstalled tool that is Unicode-aware, such as sed: sed -n '/^.\{3,\}/p' file A: Try setting your locale: LC_ALL=en_US.UTF-8 awk 'length >= 3' infile Change en_US.UTF-8 to your correct locale. A: if you're absolutely sure that your input is already 100% "well-formed" UTF8 texts, then you can simply count length with this short snippet, with non-unicode aware versions of awk : `mawk/mawk2/nawk/gawk -b 'BEGIN { FS = "^$" } { bytes += length($0) gsub(/[\200-\301\365-\377]+/,"") # if u know it's well-formed # then once you clean out all continuation # bytes, you're only left with ASCII and # the multi-byte leading bytes of \xC2-\xF4 chars += length($0) } END { printf("rows = %\047.f | "\ "UTF8 chars = %\047.f | "\ "bytes = %\047.f\n",\ NR, \ NR+chars,\ NR+bytes) }' # remove the \047 for mawk2 and don't worry about locale settings at it. as long as you're in gawk byte mode, or any of the non-unicode aware variants, this works just fine. This shall properly count any single point spec'ed in Unicode 13. * *ps : having UTF16 surrogate pairs doesn't necessarily constitute "well-formed" UTF8 per se. performance wise, it beats gnu-wc binary rather handily - about +67% faster on multi-byte heavy input, some +134% on multi-byte lighter input : first file time pvE0 < "${m3t}" | mawk2 'BEGIN { FS = "^$" …. } in0: 1.85GiB 0:00:16 [ 114MiB/s] [ 114MiB/s] [============================>] 100% rows = 12494275. | UTF8 chars = 1285316715. | bytes = 1983544693. pvE 0.1 in0 < "${m3t}" 0.07s user 0.78s system 5% cpu 16.575 total time pvE0 < "${m3t}" | gwc -lcm in0: 1.85GiB 0:00:27 [68.0MiB/s] [68.0MiB/s] [============================>] 100% 12494275 1285316715 1983544693 pvE 0.1 in0 < "${m3t}" 0.07s user 0.80s system 3% cpu 27.838 total second file in0: 988MiB 0:00:03 [ 316MiB/s] [ 316MiB/s] [============================>] 100% rows = 5983333. | UTF8 chars = 969069988. | bytes = 1036334374. pvE 0.1 in0 < "${m3s}" 0.04s user 0.60s system 20% cpu 3.177 total time pvE0 < "${m3s}" | gwc -lcm in0: 988MiB 0:00:07 [ 135MiB/s] [ 135MiB/s] [============================>] 100% 5983333 969069988 1036334374 pvE 0.1 in0 < "${m3s}" 0.04s user 0.39s system 5% cpu 7.318 total A: try this: $ echo "four foo bar föö bår fo ba fö bå "|awk ' {x=$0;gsub(/./,"x",x); if( length(x) >= 3 ) print $0 } ' output four foo bar föö bår
{ "language": "en", "url": "https://stackoverflow.com/questions/7578497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Code signing certificate across Multiple OS Platforms - Relating to Adobe Air packages I am developing an application in Flex using Adobe Flash Builder 4.5 and I want to distribute this as an AIR package so that it will work on multiple Operating Systems. I am wanting to target the usual suspects :- Windows [what I currently develop on] Apple [As I understand I need an actual Mac in order to package it] ? Blackberry Playbook. [Again I believe I need the actual Playbook etc] ? I also want to eventually deploy the application to the Mobile platform. So that also means targetting Android. Now as far as I am aware, and all research indicates this, I can develop my single application in Flash Builder 4.5 and then deploy to all these platforms. Am I correct in this? Now to my real question. Obviously I am aware that the application needs to be digitally signed, so can I purchase ONE digital certificate to sign for ALL Operating Systems? The reason I am confused on this is because I know there is something I need to purchase from Apple ($99 per year reacurring) but is that just to distribute via iTunes network or is that a certificate as well ? Presuming it is, can I use said certificate for all the above platforms ? As you can tell I am probably getting everything all crossed up and confusing myself LOL, so some help would be greatly appreciated.Regards Anthoni EDIT:- Found this link [url]http://codesigning.ksoftware.net/[/url] Apparently it is a Comodo code signing certificate and it lists the platforms as both Adobe AIR AND Apple. Has anyone experiance with this code certificate ? A: Comodo certificates do work on all of the platforms you mentioned.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Parsing and applying function on parsed values in bash scripting I have the following in my script : function processurl { } some_text%%%url1%%%url2%%%url3%%% with number of urls varying between 0 to any finite number (in case of 0 the string is some_text%%%) I want to apply processurl to the urls and give the output as : some_text%%%processurl url1%%%processurl url2%%%processurl url3%%% Any clues on how to do this? A: in a language like awk you cannot pass a function as an argument. So you have to do it the other way round. First you have to split the input, the process it and join it again. You can do it like this: This will split the input: awk -F"%%%" '{for(i=2;i<=NF;i++){if (i==NF){print ""}else print $i}}' file Now you can read it linewise and apply your function, which you should save in a shell script "processurl": | while read url; do ./processurl $url; done And join it again: awk 'BEGIN{RS=""}{for (i=1;i<=NF;i++) {if (i==NF){printf "\s%%%%%%\n",$i}else{printf "%s%%%%%%",$i}}}' HTH Chris A: this is actually the same question as this(also from you) Scripting in Bash you could save your processURL function as a script, expecting the parameter, and in awk sending $i to this script, and get result. (you could use getline in awk). see my answer in the other question, there is an example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: To store value of a table variable into a variable of my own in selenium Hi i am using selenium with testng and right now i have to store a value present in the page to some variable but i am having much problem regarding this This is the main part of the page source where i need to store the value "2" in some variable. I don't understand whether non-truncated-text will give me the value because their are too many such same lines are their with different values. here is my page source . < non-truncated-text="2"> A: You can use storeTable ( tableCellAddress, variableName ) to get text from a table. Selenium has many store functions to store values on the page into variables. See Selenium Reference for a list of functions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the cell tower area using the CellID and LAC in Android? I am able to get the Cell Id and LAC(Local Area Code). But don't know how to decode the location. I should not connect to internet and should get the cell tower location using Cell Id and LAC. If remember the basic model phones(Not built on Android) have an option to get that. The option is something like "Cell Info Display". If we enable it it used to show the current area on Phone main screen. Is there any way to get the local area where the phone connected to on Android? A: There is a tutorial about this on AndDev.org: Poor mans GPS - Cell(Tower)ID / Location Area Code -Lookup A: Android's Network provider does this for you. If you are using any Android phone you have this facility of getting your location from your Cell ID. A: You can you this android app to convert gsm location into gps coordinates GPS Convertor. Enter gsm coordinates as follow: * *cellid *';' *loc_area_code e.g: 123;456 Click 'Start Conversion' button to return GPS coordinates
{ "language": "en", "url": "https://stackoverflow.com/questions/7578507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Java ZipOutputStream only deflate certain files / deflate filter This is a two part question, really. Preface: I use WinRAR to compress files. It gives you the option of only compressing certain files. I can filter by file extension so that, say, JPEG files are not compressed, while other files are. * *Can this be done with ZIP files in general, or is it only a WinRAR/RAR format capability? *If it is possible do to with the ZIP format, is there a way I can do that using Java's ZipOutputStream class? Or, perhaps using some other ZIP Java implementation? To clarify, I would like to tell my ZipOutputStream to only compress files with a particular extension. Is this possible? Thanks A: Yes, you can do it with ZipOutputStream. Before each file (or when you want to change it) call setLevel with a constant from Deflater, in your case Deflater.NO_COMPRESSION. The documentation on this should be clearer. You could easily make a subclass of ZipOutputStream that overrides putNextEntry to handle this logic. A: ZipOutputStream has methods to control if subsequent entries are to be deflated, and with which compression level. This can also be specified on the ZipEntry level (where it takes precedence).
{ "language": "en", "url": "https://stackoverflow.com/questions/7578508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: grep or splice on large array I have a large array of hashes, about 0.5Gb, stored in memory, and I need to remove some elements from it, about 10% spread around the whole array. What is likelier to work best, doing a grep, or identifying the elements that need deleting, and splice-ing them out? Thanks, Simone A: Benchmark it? I would guess, not knowing what your data really looks like, that grep would be faster than multiple calls to splice for an array with a lot of elements. A: If you know which elements you want to keep, then you can just index them with an array slice: @want = @all[ @wanted ]; or @all = @all[ @wanted ]; As to which of grep and splice is fastest, splice will be quickest, as all it needs to do is shift some pointers around in C, and delete the things you no longer keep from memory, grep will need to a bit more work as it requires a call to your selection function for every member of the original list. A: If you already know which elements you are interested in removing that it will be by definition faster as you won't have to search form them, only remove them. Otherwise, grep is your best bet for a fast filtering method. A: splice may go to O(n^2) under conditions you describe (as it moves array content around), and grep/slice would allocate O(n) extra memory (probably, much less than 500GB, but still...). There is a linear solution with no extra memory though, but looks more like C than like Perl: sub inplace_grep { my ($code, $array) = @_; # move elements backwards for (my ($to, $from)=(0,0); $from < @$array; $from++) { $code->($array->[$from]) or next; $array->[$to++] = $array->[$from]; }; # remove tail splice @$array, $to; }; Update: on grep memory usage -- you can do a quick test for extra memory allocation by using large amounts of data and looking for brk syscall. On my system (linux, perl 5.10) it does. strace -e trace=brk perl -MTime::HiRes -wle \ 'print "start ".time; my @array = 1..10**7; print "alloc ".time; @array = grep { $_ %2 } @array; print "grep ".time'
{ "language": "en", "url": "https://stackoverflow.com/questions/7578517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I split and embolden this string with JavaScript? I have this string and I used string.bold() method to make bold the string. While debugging this JavaScript I found that this string is appended with bold tag, with the HTML tag <B>6,00,234</B>. Now I need to show this bold result in one area and I need to show the same result without this bold option in another area. Using JavaScript how can I achieve this? string result = 6,00,234 A: Like this: var str = "<B>6,00,234</B>"; var result = str.replace(/<[^>]+>/g,''); // 6,00,234 A: How about using JavaScript's split method? var str = "6,00,234"; var arr = new Array(); arr = str.split(","); A: I believe you're saying how would you extract the content between the tag? If so, regular expressions groups are useful for that. For example: var aString = '<B>6,00,234</B>'; //the original string var regex = /(<B>)([\w,\d]+)(<\/B>)/g; //regular expression var match = regex.exec(aString); //get the match for that string console.log(match[2]); //should give you your number This works because when you execute your regular expression, you will get the match but split into three, which is why you indicated three parenthesis blocks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JSP duplicate if included multiple time let say i have this global.jsp that include a database configuration and connection. I know this is not the best way to do this, and I didn't allow to use anything else then a pure jsp. The problem is when is this file is included in more than once then i got re-declaration error. Is there any way to do this ? something like IFDEF on C perhaps. Thanks. A: Check the jsp include concept here is the simple detail and difference of the include directive tag and include action tag should use the include directive (<%@ include file="relativeURL" %>): if the file includes static text if the file is rarely changed (the JSP engine may not recompile the JSP if this type of included file is modified) if you have a common code snippet that you can reuse across multiple pages (e.g. headers and footers) should use the <jsp:include /> for content that changes at runtime to select which content to render at runtime (because the page and src attributes can take runtime expressions) for files that change often here are the links * *http://javapapers.com/jsp/difference-between-jsp-include-directive-and-jsp-include-action/ *http://www.geekinterview.com/question_details/701 *http://www.daniweb.com/web-development/jsp/threads/105695
{ "language": "en", "url": "https://stackoverflow.com/questions/7578524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to append the text to text file in blackberry I want to append the text to a text file in blackberry ,how can i do it A: Checkout this code. This basically writes log to a file in SD Card. You can customize the way you want. Enjoy. static String pFilePath = "SDCard/BlackBerry/pictures/Log.txt"; public static void writeLog(String data) { FileConnection fc = null; OutputStream lStream = null; Date d = new Date(); Calendar c = Calendar.getInstance(); String time = new String(); if (pFilePath != null) { try { fc = (FileConnection) Connector.open("file:///" + pFilePath, Connector.READ_WRITE); if (null == fc || fc.exists() == false) { fc.create(); } lStream = fc.openOutputStream(fc.fileSize()); c.setTime(d); time = c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND) + ":" + c.get(Calendar.MILLISECOND); data = "\n" + time + "(" + (System.currentTimeMillis() - currentTimeMillies) + " ms)" + " -- " + data; currentTimeMillies = System.currentTimeMillis(); lStream.write(data.getBytes()); } catch (Exception ioex) { ioex.printStackTrace(); } finally { if (lStream != null) { try { lStream.close(); lStream = null; } catch (Exception ioex) { } } if (fc != null) { try { fc.close(); fc = null; } catch (Exception ioex) { } } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7578525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Twig: Selecting certain blocks and rendering them I am intergrating the twig templating engine into a PHP application. In particular, I would like to use the twig engine to render forms. Having had a look at how symfony2 uses twig to render form widgets, they have a huge template file which contains all the widgets like so: (...) {% block password_widget %} {% spaceless %} {% set type = type|default('password') %} {{ block('field_widget') }} {% endspaceless %} {% endblock password_widget %} {% block hidden_widget %} {% set type = type|default('hidden') %} {{ block('field_widget') }} {% endblock hidden_widget %} {% block email_widget %} {% spaceless %} {% set type = type|default('email') %} {{ block('field_widget') }} {% endspaceless %} {% endblock email_widget %} {% block test_widget %} {% spaceless %} <div> {{test}} <div> {% endspaceless %} {% endblock test_widget %} (...) The question I have is how can I "grab" blocks out of this template and render them? So far, I am able to load the template, and call get blocks to get all the blocks: twig = new \Twig_Environment($loader, array('cache' => 'cache')); $template = $twig->loadTemplate('view\form_div_layout.html.twig'); //var_dump($template->getBlocks()); //try getting all blocks $template->displayBlock('test_widget', array('test' => 'test')); echo $template->render(); Unfortunately, I am not able to render just the 'test_widget' block in this case. What should I do to retrieve the 'test_widget' block from the template and then insert it into a different template to render the whole form? A: If you are using Symfony and want to be able to still have access to the global variables (app, app.user, etc) then this works great: private function renderBlock($template, $block, $params = []) { /** @var \Twig\Environment $twig */ $twig = $this->get('twig'); /** @var \Twig\TemplateWrapper $template */ $template = $twig->load($template); return $template->renderBlock($block, $twig->mergeGlobals($params)); } I just added this has a private function on my controller. Works great. Thanks to @F21 for pointing me in the right direction. A: This is great! I also wanted to add that there is a hasBlock function which allows you to do validation before you attempt to do the template rendering. This allows you to validate the template is built as expected, or in my case have optional blocks. For what it's worth, here's an example from one of my console apps which sends notification emails $templateContent = $this->getContainer()->get('twig')->loadTemplate('FTWGuildBundle:AuctionNotification:notificationEmail.html.twig'); $body = $templateContent->renderBlock('body', array('siteDomain' => $siteClient->getSiteDomain(), 'staticContentDomain' => $siteClient->getStaticContentDomain(), 'batch' => $batch->getNotifications(), 'auction_notification_lockout_period' => $this->getContainer()->getParameter('auction_notification_lockout_period'))); $subject = ($templateContent->hasBlock("subject") ? $templateContent->renderBlock("subject", array('batchSize' => $batch->getSize(), 'batch' => $batch)) : "Auction House Notifications"); A: Turns out that one should use $template->renderBlock('blockname', array('test' => 'test')); instead. This will make twig render that block and then return a string containing the markup for that block. One can then use echo to display it or insert it into other templates. Full example: $loader = new \Twig_Loader_Filesystem(array('/my-template-root')); $twig = new \Twig_Environment($loader, array('debug' => true)); $template = $twig->loadTemplate('view\form_div_layout.html.twig'); $result = $template->renderBlock('blockname', array('test' => 'test')); echo $result; A: Note: hasBlock won't work if the template extends or embeds a parent block. see https://github.com/twigphp/Twig/issues/450
{ "language": "en", "url": "https://stackoverflow.com/questions/7578526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: SQL DELETE STATEMENT problem with returned rowcount I have a statement like this: DELETE TABLENAME WHERE COLUMN = NUMBER; SELECT @@ROWCOUNT AS RC; if i run it from the code (classic asp) i get Error:Item cannot be found in the collection corresponding to the requested name or ordinal. the DB is sql server 2005 express. if i run this line in query analyzer it works! the column i refer to has a constraint to another table in the db do you guys know where to stat looking for the fix for it? UPDATE - please try to explain this now the first line is the connection string we had on the regular servers, when we needed to upload the code to a new server with sql 2005 express we changed to the second one cause the first one didn't work for us (i tried in the servername local ip: 127.0.0.1) and the second was the actual server name. now i have changed the first one to connect to the server name and it works. even deleteing and retreving the @@rowcount. but now it feels like a slower connection so the website work slow! any idea for making it better? ConnectionString = "Server=**ServerName**;Driver={SQL Server};UID=**Username**; PWD=**password**;database=**dbname**;Data Provider=SQLOLEDB;Network Library=DBMSSOCN;" ConnectionString = "PROVIDER=SQLOLEDB; Data Source =**servername**; Trusted_Connection=Yes; Initial Catalog=**dbname**;User Id=**username**; Password=**password**;" A: If you want to count the number of affected rows, you could use this instead: conn.Execute("DELETE FROM TABLENAME WHERE COLUMN = " & number, rows_affected) Response.Write rows_affected A: Add SET NOCOUNT ON; as without that another recordset is returned causing the issue SET NOCOUNT ON;DELETE TABLENAME WHERE COLUMN = NUMBER; SELECT @@ROWCOUNT AS RC; A: @@ Rowcount is a T-SQL call that can only run from the database. You can instantiate it in a stored proc and then call the delete and return the @@rowcount from the stored proc. This is for ASP.NET but instead of writting this in the page load just handle it in the header http://support.microsoft.com/kb/306574 A: This code assumes that there are two record sets in the query, the first probably being the row count (why people are suggesting SET NOCOUNT ON). m_Conn.Execute(strSql).NextRecordset.Fields(strReturnedValueName).Value so it will execute and not return the value (this code works in hundreds of our websites but now on a new server it is not working – When you run the code on this server, does it show the number of rows? If not, the something is turning on NOCOUNT, so your ASP code is not getting the expected number of recordset objects back. Rather than assume you will always get two recordsets back, I would loop through the recordset until the returned recordset is empty, something along these lines. The code below is not tested, it basically grabs the first field from each record set until the last one. This way, regardless of the setting of NOCOUNT, you should always get the value from your final SQL statement DIM rs set rs=Server.CreateObject("ADODB.recordset") set rs = m_Conn.Execute(strSql) do while rs is not nothing val = rs(0).value rs = rs.NextRecordSet enddo
{ "language": "en", "url": "https://stackoverflow.com/questions/7578530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: searching a line and pulling a percentage out as an integer So after my script runs a batch file it executes the shell command: adb shell dumpsys cpuinfo > sample.txt which then if you open sample.txt you see this: 0% 71/msm_battery: 0% user + 0% kernel <br> 0% 79/kondemand/0: 0% user + 0% kernel <br> 0% 115/rild: 0% user + 0% kernel <br> 0% 118/gpsd: 0% user + 0% kernel <br> 0% 375/com.android.systemui: 0% user + 0% kernel <br> 0% 415/com.nuance.nmc.sihome: 0% user + 0% kernel <br> 0% 498/com.google.process.gapps: 0% user + 0% kernel / faults: 6 minor <br> 0% 1876/com.wssyncmldm: 0% user + 0% kernel <br> What im trying to do is if the user wants com.google.process.gapps it will return 0% from the text file. However this text file updates every second and com.google.process.gapps will not always be 0% and will not always be in the same place. I have figured out how to search for com.google.process.gapps and return the entire line as a string, what I havent figured out yet is how to search the entire file and just return the first 0% as just a 0 and as an integer instead of a string. Dont worry about the repeating every second thing I already have that coded, all i need is help figuring out is how to write the search array and to return the first value as an int Can anyone point me in the right direction? ........................................ I couldnt figure out the "add comment" thing so I am just reposting in here. So if I go off your code I get this: Dim line As String = TextBox1.Text 'where textbox1 could equal com.google, etc. Dim Matches As MatchCollection = Regex.Matches(line, "[0-9]+%") For Each Match As Match In Matches Dim Percent As Integer = Integer.Parse(Match.Value.TrimEnd("%"c)) TextBox9.Text = Percent Next I know I am missing one key part, and that is to load the entire text file. maybe something like: Dim searchfile As String = IO.File.ReadAllLines("C:\sample2.txt") but then how would I Regex.matches(line, "[0-9]+%") in searchfile 'C:\sample2.txt Thanks again for your help A: Edit: To add to your ammended question... The easiest way is to use RegEx. This code will extract every integer followed by a % symbol on the line as an Integer. This function takes two parameters. The first is the search term, such as "com.google" which identifies the line to read. If the term is not found, the function throws an ArgumentException. The second parameter is which percentage value to read. Use 0 for the first, 1 for the second, or 2 for the third. Imports System.IO Imports System.Text.RegularExpressions Public Class Form1 Public Function GetPercentage(term As String, percentage As Integer) As Integer ' Read all lines from the file. Dim lines As String() = File.ReadAllLines("C:\sample2.txt") ' Find the appropriate line in the file. Dim line As String Using reader As New StreamReader("C:\sample2.txt") Do line = reader.ReadLine() If line Is Nothing Then Throw New ArgumentException("The term was not found.") If line.Contains(term) Then Exit Do Loop End Using ' Extract the percentage value. Dim Matches As MatchCollection = Regex.Matches(line, "[0-9]+%") Dim Match As Match = Matches(percentage) Dim Text As String = Match.Value.TrimEnd("%"c) Return Integer.Parse(Text) End Function End Class
{ "language": "en", "url": "https://stackoverflow.com/questions/7578533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: saving html & sign in database I am trying to work out, how I save & signs, I need this due to our customers business sometime have the & sign instead of and. I thought it might be a preg thing but i am not sure A: You shouldn't have any problems storing ampersands in your database (unless it's Oracle). When displaying the data in an HTML page, make sure you encode it appropriately, eg <?php echo htmlspecialchars($row['col'], ENT_COMPAT, 'UTF-8') ?> A: There shouldn't be a problem storing ampersands in the database as &. When you retrieve the data from the database, you should convert HTML entities before displaying them in the browser. So & would become &amp; in your HTML source.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I persuade ggplot2 geom_text to label a specified date in a time series plot? I am using ggplot2 to plot simple line charts of time series data. One difficulty I have run into is labelling specific points corresponding to x-axis values i.e. dates. library(ggplot2) library(scales) date <- c("2011-09-19","2011-09-20","2011-09-21", "2011-09-22","2011-09-23","2011-09-26","2011-09-27") price <- c(100,110,105,115,120,115,125) tmp <- data.frame(date,price) tmp$date <- as.Date(tmp$date) p <- ggplot(tmp,aes(tmp$date,tmp$price)) p <- p + xlab("Date") p <- p + ylab("Price") p <- p + layer(geom = "line") p <- p + opts(title="Simple price plot") print(p) What I would like to do is add an annotation to a specific date, which might be a maximum or a minimum value or something else of note. So far all the permutations of geom_text I have used have failed to get the effect I want (or indeed anything useful). There are a few questions on this on SO but most seem related to scatter charts rather than time series; I haven't been successful in trying to adapt them. I have also spent some time with the documentation but my understanding is still limited. Any pointers would be appreciated. A: To add text to ggplot, use geom_text: Method 1: Add a column of labels to your data.frame: tmp$note <- LETTERS[1:7] ggplot(tmp,aes(date, price, label=note)) + geom_line() + geom_text(vjust=0, colour="red") Method 2: Add a specific label: ggplot(tmp,aes(date, price, label=date)) + geom_line() + geom_text(data=tmp[3, ], label="Something of note", vjust=1)
{ "language": "en", "url": "https://stackoverflow.com/questions/7578536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: how to use if condition in rjs? I pass parameter with url called var which is containing value 'event'. I want to check this variable in rjs file and load a modal dialog box. Following is my code. page<<" if (:var== "event") {" page<< "$j ('#create_evnt_dialog').dialog({ title: 'New Trainer', modal: true, width: 500, close: function(event, ui) { $j ('#create_evnt_dialog').dialog('destroy') } });" page << '}else{' page.replace_html 'create_evnt', :partial => 'add_events' page << "}" I could not check variable event in rjs file.how can i do this? This is my Ajax link :: <%= link_to_remote 'Add new event', :url => {:controller => 'events', :action => 'new' }, :with=>"'var=' + escape('event')" %> <%= link_to_remote 'Add new holidays', :url => {:controller => 'events', :action => 'new' }, :with=>"'var=' + escape('holy')" %> This is my controller code :: def new @event = Event.new @trainers= Trainer.all @countries= Country.all @venues= Venue.all @var=params[:var] if(@var == 'holy') @event.trainer_id='0'#If we save holiday as event we put 0 to trainer and venue @event.venue_id='0' end end A: Just you can use if params[:template] == "viewer" render :action => "viewer_destroy.js.rjs" else render :action => "destroy.js.rjs" end A: I think you have to use ruby syntax like this: if (<%= :var %> == "event") { or all in ruby <% if :var == "event" %> <% end %>
{ "language": "en", "url": "https://stackoverflow.com/questions/7578537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Issue while changing viewport in sencha i am a very beginner to Sencha touch frame work. I am trying work with the viewport, but i am stuck with a strange problem. it throws "Uncaught TypeError: Cannot read property 'isComponent' of undefined exception. I know this question might be little unusual but i need to resolve this somehow. I have a java script file where i have login screen. var App = new Ext.Application({ name: 'MyApp', useLoadMask: true, launch: function () { MyApp.views.loginPanel = new Ext.form.FormPanel({ scroll: 'vertical', standardSubmit : false, items: [ { xtype: 'fieldset', instructions: 'Please enter the information above.', defaults: { required: true, labelAlign: 'left', labelWidth: '50%', labelHeight: '50%' }, items: [ { xtype: 'textfield', name : 'username', id: 'username', label: 'user Name', useClearIcon: true, autoCapitalize : false }, { xtype: 'passwordfield', name : 'password', id: 'password', label: 'Password', useClearIcon: false } ] } ], dockedItems: [{ xtype: 'toolbar', dock: 'top', title: 'Login Screen' }, { xtype: 'toolbar', dock: 'bottom', items: [{ text: 'Exit', ui: 'confirm', handler: function() { form.exit(); } }, {xtype: 'spacer'}, { text: 'Reset', handler: function() { form.reset(); } }, { text: 'Login', ui: 'action', handler: function() { //TODO: handle the event MyApp.views.viewport.setActiveItem('nextScreen', { type: 'slide', direction: 'right' }); } } ] } ] }); MyApp.views.viewport = new Ext.Panel({ fullscreen: true, layout: 'card', cardAnimation: 'slide', items: [MyApp.views.loginPanel, MyApp.views.nextScreen] }) } }); Now i have the nextScreen.js file. I am loading the JS file in my login.html. My nextScreen.js looks like this: var opt = [ {text: 'Alabama', value: 'AL'}, {text: 'Alaska', value: 'ALS'}, {text: 'Indiana', value: 'IN'} ]; var stateList = new Ext.form.Select({ label : 'State', width: '100%', name: 'selectField', layout:'auto', options: opt, autoLoad : true, autoDestroy : true }); MyApp.views.nextScreen = new Ext.Panel({ fullscreen: true, id:'nextScreen', layout: 'fit', style: 'background-color:white', scroll:'vertical', html:'sample screen', items: [stateList] }); Ext.reg('nextScreen', MyApp.views.nextScreen); A: You don't really need Ext.reg('nextScreen', MyApp.views.nextScreen); in your code. Check when you are loading the nextScreen.js file. It should come before your main JS file - the file where you have the App variable. Anyway I'm not sure what the whole app look like but you may want to reconsider your app's architecture. A: One thing is that the second parameter to Ext.reg needs to be a constructor function, not an instance. To create a constructor based on Ext.Panel you could do something like MyApp.views.nextScreen = Ext.apply( Ext.Panel,{ fullscreen: true, id:'nextScreen', layout: 'fit', style: 'background-color:white', scroll:'vertical', html:'sample screen', items: [stateList] }); It doesn't look like you need to create your own type of component though, so you can probably omit the call to Ext.reg.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Paramiko starts a SSH proccess and it dies..why? Below is my code. When log into the server and I run ps aux | grep python I see all of the process start and then die after a second or two. If I run the command in the server..it works. I have tried with nohup.whithout nohup etc I am out of an explanation. This is a long process that should take hours. key = paramiko.RSAKey.from_private_key_file(rsa_private_key) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname,port,username=username,pkey=key) #stdin, stdout, stderr = ssh.exec_command('tar -xf /home/ubuntu/opt.tar.gz') stdin, stdout, stderr = ssh.exec_command('ls') #stdin, stdout, stderr = ssh.exec_command(bash) stdin, stdout, stderr = ssh.exec_command('ls') stdin, stdout, stderr = ssh.exec_command('export DISPLAY=localhost:0') stdin, stdout, stderr = ssh.exec_command('nohup python /home/ubuntu/Optimization/pvServer2.py &') stdin, stdout, stderr = ssh.exec_command('nohup python /home/ubuntu/Optimization/pvServer2.py &') stdin, stdout, stderr = ssh.exec_command('nohup python /home/ubuntu/Optimization/pvServer2.py &') stdin, stdout, stderr = ssh.exec_command('python /home/ubuntu/Optimization/pvServer2.py &') stdin, stdout, stderr = ssh.exec_command('python /home/ubuntu/Optimization/pvServer2.py &') stdin, stdout, stderr = ssh.exec_command('python /home/ubuntu/Optimization/pvServer2.py &') stdin, stdout, stderr = ssh.exec_command('python /home/ubuntu/Optimization/pvServer2.py &') ssh.close() A: Try checking the output of the command. There may be an error been written, and you won't see it with your current code. Try doing: stdin, stdout, stderr = ssh.exec_command('python /home/ubuntu/Optimization/pvServer2.py') print 'exit_code: %d' % stdout.channel.recv_exit_status() print stdout.read() print stderr.read() Once you have figured out what is wrong, and fixed it, then you can return to using nohup. I think what is wrong is the way you are calling the export DISPLAY command. This won't affect the env of the other commands you are running. You need to do something like this: stdin, stdout, stderr = ssh.exec_command('sh -c "export DISPLAY=localhost:0; python /home/ubuntu/Optimization/pvServer2.py"')
{ "language": "en", "url": "https://stackoverflow.com/questions/7578546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: codeigniter 2 and smarty 3 : multi array of stdClass results returned - how do i display these in smarty My Sql function getLive_projects has this query - $query = "SELECT p.* FROM projects p WHERE p.live = 1 ORDER BY client_name ASC"; $response = $this->db->query($query)->result(); My Controller : // get live projects $data['live_projects'] = $this->projects->get_live_projects(); // load the projects with the data $this->parser->parse("projects.tpl", $data); The data in my template looks like this when I use {$live_projects|print_r} Array ( [0] => stdClass Object ( [id] => 1 [client_name] => client one [dev_url] => clientone.com [live_url] => clientone.com [version] => 1.0 [live] => 1 ) [1] => stdClass Object ( [id] => 2 [client_name] => client two [dev_url] => clienttwo.com [live_url] => clienttwo.com [version] => 3.1 [live] => 1 ) ) How can I output this in my template? I tried {foreach from=$live_projects item=$project} and then tried to use {$project->client_name} but that didn't work. Should the object not be available to me when I loop over the array? Have I missed something obvious? Am I going about this in the right way? I just want to loop over the returned results and display each one as a row in my template. I have searched the forums but was unable to find an answer that solved my issue - any help would be much appreciated. There are some example out there about using $live_projects[0]->id but how can this be incorporated into output from smarty where many items are returned in the result set. A: You were almost there! When defining the name of your item variable, you don't have to include the '$' sign. Change your code to: {foreach from=$live_projects item=project} {$project->client_name} {/foreach} That should do the trick.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript sqlite database error : "Error processing SQL: undefined " while inserting and selecting data from/to table I am trying to store data from webservices using javascript, sqlite. getting some error like db.transaction(populateDB, errorCB, successCB); populateDB is not executing at all. and while reading data from table(and same database )giving me error like "Error processing SQL: undefined ". applied many tricks but no solution till now. my SELECT Code is function queryDB(tx) { db.transaction(function(tx) { tx.executeSql('SELECT * FROM vact_geography', [], LoadGeo, errorCB); }); } function LoadGeo(tx, results) { var len = results.rows.length; alert("Region table: " + len + " rows found."); //arr = new Array(); for (var i=0; i<len; i++){ // alert("Row = " + i + " geo_id = " + results.rows.item(i).geo_id + " geo_name = " + results.rows.item(i).geo_name); //arr.push(results.rows.item(i).geo_name); //alert(results.rows.item(i).regionname); //alert("assigned"); var src_Geo = document.getElementById("src_target") ; var Des_Geo = document.getElementById("Des_target") ; //alert("Row Should be printed"); src_Geo.options[src_Geo.options.length] = new Option(results.rows.item(i).geo_name, results.rows.item(i).geo_id); Des_Geo.options[Des_Geo.options.length] = new Option(results.rows.item(i).geo_name, results.rows.item(i).geo_id); } } and and code for populate data is function startup() { alert("Entered in Str"); $.get("http://example.in/projects/vact1/api.php?usn=user&pwd=***&var=database", function(Jdata) { alert("1st api call"); var j; j=Jdata.timestamp; $.get("http://example.in/projects/vact1/api.php?usn=user&pwd=***&var=validity&timestamp="+j+"", function(Tdata) { alert("2st api call"); var i; i=Tdata.UpdateNeeded; alert("http://example.in/projects/vact1/api.php?usn=user&pwd=***&var=validity&timestamp="+j+""); if(i) { db = window.openDatabase("Database", "1.0", "PHGsample", 200000); db.transaction(populateDB, errorCB, queryDB); alert("Enterd"); } else { queryDB(); } }); }); } Any suggestion ? i was implementing for [link] Waroze.com Thanks in Advance A: So, how did you go on this one? I see that it's over 12 months old. Is populateDB defined? How do you know it's not getting that far? You know that in this case populateDB would get passed the transaction object, and you'd use that to tx.sqlExecute() the sql - right?
{ "language": "en", "url": "https://stackoverflow.com/questions/7578564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: rails - is it ok to install multiple gems doing the same thing? I am curious as to if it's okay to install multiple gems that perform the same function into one app. What are the protocols for doing or not doing this? Example: * *using multiple gems in one model - Using auth logic to authenticate user and using devise for email confirmation *using multiple gems in different models - Using sunspot for search in your blog model and using metasearch in your products model Thanks A: Unless there are constants overlapping, you should be okay, technically-speaking. For instance, dynamic methods like Model.search being provided by two different gems could cause issues. This may not occur if the gem allows you to specify which models to hook into. And, as others have pointed out, gems may also have conflicting dependencies. Whether or not this is acceptable, and/or redundant, well.. A: In my personal opinion, it is ok, as long as the gems are different enough so that the benefit is worth it. If they only perform the same function, it would be beneficial to use only one of them. My example here is will_paginate and kaminari. I used will_paginate a long time (even in Rails 3 the beta version), then found kaminari through a webinar of Ryan Bates and switched in one application completely to kaminari. This has a price tag, and is only worth if you will stay with that decision. To use both, you as a developer has to know both of them, with the differences, and the different options. I don't think that it is worth. A: It is fine. But, sometimes gems have conflicting dependencies. You might want to make sure you don't run into that issue. Look at Gemfile.lock for dependencies. Personally, it is better to keep it clean unless there is a strong reason to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What are the ways to develop a Book like app? I have a situation here, I want to replicate an app which will look like a book for content of book I'll have a XML feed that feed will have information pertaining to contents and number of pages. The situation is number of pages will vary every time so can you suggest me a way to show varied number of pages every time + how to apply the flip animation while user is browsing these pages. Please enlighten me on this. Regards Ankit A: create fliping book with images I have implemented AFK Page Flipper from this list and is very easy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: asp.net c# reflection, creating more instance then expected I have a helper method here in class. It returns all the instances of a given interface in all the app domain dlls. public static class Helper { public static List<T> GetOfType<T> () { var t = from asm in AppDomain.CurrentDomain.GetAssemblies() from type in asm.GetTypes() where !type.IsInterface && !type.IsAbstract && typeof(T).IsAssignableFrom(type) select (T)Activator.CreateInstance(type); return t.List(); } } Edit Now say i have interface IUserContent { string URL {get;set;} } and a implementation say PhotoContent public class PhotoContent { public string URL {get;set]} } now when i say var c = Helper.GetOfType<IUserContent>(); It gives me 9 instances of IUserContent all pointing to photocontent That is the problem. I couldnt understand what is the reason. Can someone help here. Regards Parminder A: The first thing to do is to get the full name: foreach(var obj in c) { Console.WriteLine(c.GetType().AssemblyQualifiedName); } that gives you the full type-names (including assemblies) of the types invovled. My guess would be that the type has been accidentally declared in multiple assembles or namespaces. A: You have two from clauses in your LINQ query. Could it be that this causes the results to be returned multiple times? I would try using SelectMany instead: var t = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(a => a.GetTypes()) .Where(type => !type.IsInterface && !type.IsAbstract && typeof(T).IsAssignableFrom(type)) .Select(type => (T)Activator.CreateInstance(type));
{ "language": "en", "url": "https://stackoverflow.com/questions/7578571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to verify date format using selenium How can I verify that a date displayed on the web page fits a particular format with Python bindings for Selenium-RC? A: I would grab the date (using whatever selector is appropriate), then try to parse it with Python's strftime. If the parser raises an exception the date is likely incorrect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make file downloads accessible by only some users in your system What is a good way for making only certain users in my web application able to download a certain file? For instance, if a user purchased a pdf on my website, what methods could I use so that only the people who purchased this pdf could download it? I've read that I could store file names as GUID's and then just rename them upon download. I am looking for a method that is secure, practical and would work with amazon s3 web services.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mod_rewrite doesn't work properly I'm having trouble getting a (very) simple mod_rewrite to work. Here's my code... # Enable Rewrite Engine RewriteEngine on #Create friendly URL RewriteRule ^libs/jquery.html$ libs/loader.php [L] Basically I'm trying to get mydomain.com/libs/jquery.html to pull up the page libs/loader.php This is my entire .htaccess file - what's going wrong here? A: Not sure if that's it, but I noticed that you wrote 'on' instead of 'On'. Also, are there maybe query params at work so your regex does not match? Jan
{ "language": "en", "url": "https://stackoverflow.com/questions/7578578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Who calls the probe() of driver How does probe() call gets called? Who calls it? As per my understanding, __init() registers driver and then somehow probe() is called to register the device data and irq etc. How exactly it happens? I am working on touchscreen driver and its __init registers itself to i2c driver. Then probe expect i2c_client data which returns null. I want to track where it gets filled. A: Lets consider an example of a platform device driver: * *The starting trigger function for the driver->probe() callback is the module_init() macro called while loading the driver; this macro is defined in include/linux/module.h. *module_init(my_driver_init) has the callback to my_driver_init() function. my_driver_init() function should have a call to platform_driver_register(my_driver) *platform_driver_register(my_driver) assigns my_driver -> probe() handle to generic drv -> probe() and calls the driver_register(my_driver) function. *driver_register(my_driver) function adds my_driver to the platform bus and calls driver_attach() function. *In the same way, even the platform_device needs to attach to the platform bus. *Finally, only if the driver_match_device() returns success based on the .name & .id_table of the driver matches in the platform devices list that comes either from ACPI/DTS, then the driver_probe_device() gets called that has the drv->probe() callback. A: Long story short: the probe() function of the driver is called as a result of calling the register_driver for that specific bus. More precisely, it's called by the probe() of that bus_type structure. In your case: i2c_bus_type. Here's the call chain in your I2C case: * *i2c_register_driver *driver_register *bus_add_driver *driver_attach *__driver_attach (for your device) *driver_probe_device *really_probe *i2c_device_probe (this is what dev->bus->probe is for an i2c driver) *your_probe_function A: @iSegFault : probe() will be called to make sure that the device exist and the functionality is fine.If device is not hot-pluggable, functionality of probe() can be put inside init() method.This will reduce driver's run time memory footprint. P.S link Probe() happens at the time of device boot or when device is connected.For a "platform" device the probe function is invoked when a platform device is registered and it's device name matches the name specified on the device driver. P.S link The i2c_detect function probes the I2C adapter, looking for the different addresses specified in the addr_data structure. If a device is found, the chip_detect function then is called. P.S link. One link that will surely clear your doubt. P.S link In kernel 2.4.29, i can show you that how does probe happen ? Please see below (File name: drivers/acorn/char/pcf8583.c) static struct i2c_driver pcf8583_driver = { name: "PCF8583", id: I2C_DRIVERID_PCF8583, flags: I2C_DF_NOTIFY, attach_adapter: pcf8583_probe, /* This will be called from i2c-core.c P.S see below function i2c_add_driver()*/ detach_client: pcf8583_detach, command: pcf8583_command }; File Name: drivers/i2c/i2c-core.c int i2c_add_driver(struct i2c_driver *driver) { ........................ ........................ /* now look for instances of driver on our adapters */ if (driver->flags& (I2C_DF_NOTIFY|I2C_DF_DUMMY)) { for (i=0;i<I2C_ADAP_MAX;i++) if (adapters[i]!=NULL) /* Ignore errors */ driver->attach_adapter(adapters[i]); /*This is a location from where probe is called. Pointer **driver** is of type **pcf8583_driver** which you have passed into this function*/ } ADAP_UNLOCK(); return 0; } Few important links: * *http://www.slideshare.net/varunmahajan06/i2c-subsystem-in-linux2624 *http://www.programering.com/a/MjNwcTMwATM.html *http://www.linuxjournal.com/article/6717 *http://www.developermemo.com/2943157/ *http://free-electrons.com/doc/kernel-architecture.pdf *http://www.techques.com/question/1-3014627/Probe-problem-when-writing-a-I2C-device-driver In PCI for kernel-2.4.29, it gets called when vendor and device id are identified. PCI bus driver do this for you. Please see below code: File Name: drivers/pci/pci.c static int pci_announce_device(struct pci_driver *drv, struct pci_dev *dev) { const struct pci_device_id *id; int ret = 0; if (drv->id_table) { id = pci_match_device(drv->id_table, dev); /* check for device presence*/ if (!id) { ret = 0; goto out; } } else id = NULL; dev_probe_lock(); if (drv->probe(dev, id) >= 0) { /* This is a location from where probe is called*/ dev->driver = drv; ret = 1; } dev_probe_unlock(); out: return ret; } A: I have prepared a graph that traces platform drive's probe function. You are working with I2C driver which AFAIK is a platform driver. I hope this helps you to trace the issue. Also, look into following link to see the discussion on kernelnewbies. https://www.mail-archive.com/kernelnewbies%40kernelnewbies.org/msg12423.html A: Probe function will be called for every interface of the detected device except the ones which are already registered. A: Probe function will gets called when name will match form drivers structure to device structure. Below mentioned eg for both driver and device structure. 1: Driver Structure static struct driver your_driver = { .driver = { .name = YUR_NAME, }, eg. static struct i2c_driver l3gd20_driver = { .driver = { .name = l3gd20_gyr, } 2: Device Structure static structure device your_devices = { .name = YUR_NAME, }, eg. static struct i2c_board_info mxc_i2c2_board_info[] __initdata = { { I2C_BOARD_INFO("l3gd20_gyr", 0x6a), }, Note: When name(l3gd20_gyr) from driver and device will match your probe will gets call.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "42" }
Q: Method not found on runtime I have an ASP.Net c# project trying to access methods in a class in another project. It's working for first half of methods in the class but not for the other half of the methods in the class which I recently added. They compile, but they throw a method not found exception at run-time. Does anyone have any ideas I could try? I've tried: * *recreating the .sln file *Subbing in another class library project, which I know works. It appears that the error is in my main project that calls the method in the other project. A: had the same problem, in my case setting the optimizeCompilations to false in the webconfig solved the problem A: "Method not found" is a very specific error, which means a method it expected (i.e. was there at compile time) simply is not present. This usually means that the files you are deploying are different to what you think they are - specifically, I would wager that you are deploying the old version of the library (which lacks your additions). Check the dlls deployed to the web-server against what you think they should be. A: I had a very similar problem and found that an older version of the assembly had been installed to the GAC. After I uninstalled that version, the project compiled and ran correctly. So check the GAC (C:\Windows\Assembly) to be sure it's not listed there. A: I encountered this same exception too, though my problem was different, I had a method in one of my library originally looking like this: public void WriteMessage(string msg) { ... } and there were some new request for modification and it turned into this: public void WriteMessage(string msg, int code = 100) { ... } after that, I updated the project that is using this library with newly compiled binary, it started to throw this exception. After many attempts, nothing worked, even project clean, rebuild, removing and re-adding the reference, then I tried to modify the project's method call from: ... library.WriteMessage('hello!'); ... to: ... library.WriteMessage('hello!', 100); ... and then compiled the project, it solved the problem, after that I changed it back to: ... library.WriteMessage('hello!'); ... and now it magically fixed everything, maybe there were some kind of cached metadata left somewhere that isn't being updated, and by changing the way the method is called somehow clearly remind it that the method's signature is different, yet not so different. Hope this can help someone facing the same problem that I experienced. A: Look, this must be the weirdest cause ever, but after a whole morning trying everything, rebuilding the project from scratch, etc, I noticed that the single only thing that would avoid the problem was if my library had a different assembly name. I had a ghastly suggestion from the back of my mind that I had installed previous dll versions in the GAC, but I already checked that and besides, it was never my intention. But following that trail I found out this dll (and all the others from the project !) where installed in C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE !!!!!! Aaaargh ! Guess I'm the only one that somehow messed this up, but I have no clue why, I just thought I could spare someone else this frustation in the remote possibility that someone is so unlucky !! A: I had the same issue. In my case, it was caused by the addition of an [optional argument][1]. So first you would have: referencingAssembly: referencedAssembly.DoStuff(firstArgument, secondArgument) referencedAssembly: public void DoStuff(string firstArgument, string secondArgument) { //stuff to do } Then you add an optional parameter to the method, but you don't provide that argument while calling it. referencingAssembly: referencedAssembly.DoStuff(firstArgument, secondArgument)//unchanged referencedAssembly: public void DoStuff(string firstArgument, string secondArgument, string thirdArgument = "default value") { //stuff to do } Locally, this will build and run fine since the newly build referencingAssembly.dll will have a reference to the DoStuff(string, string, string) method. But when you only deploy the changed referencedAssembly (thinking: the added argument was optional, and the referencingAssembly still works), the old version of referencingAssembly will throw a MethodNotFound since it seeks a method with the signature DoStuff(string, string), which is no longer present in the referencedAssembly since we added the extra (optional) argument. A possible solution could be an overload: referencedAssembly: public void DoStuff(string firstArgument, string secondArgument)//original method { DoStuff(firstArgument, secondArgument, "default value") } public void DoStuff(string firstArgument, string secondArgument, string thirdArgument)//new overload of the method { //stuff to do } Or deploying the newly build referencingAssembly (which will refer to the method with signature DoStuff(string, string, string)). [1]: https://msdn.microsoft.com/en-us/library/dd264739.aspx A: I encountered the same issue when i was running an application with nuget package managed dlls. It turns out when I try to update the dlls from nuget package manager, it did not update my test layer. I suggest you to check the version of dlls you are referring to. Go to ObjectBrower in VS and check on the dlls and check the referring location: make sure you are referring to the latest dlls. A: Two projects in your solution : project A and project B. Both projects use the nuget package "DoStuff", but different versions of the DoStuff package: * *project A references version 1.1 of DoStuff. *project B references version 1.0 of DoStuff. *project B references project A. version 1.1 has a new method, that is used in project A. when project B uses project A, you'll get this MethodNotFoundException, because project B's version of DoStuff doesn't know what project A is talking about. To prevent this, we have a unit test in place that fails if projects are using different versions of the same nuget package. A relatively simple doorstop that has saved us a couple of headaches in the past years. A: I have faced this kind of problem but was able to solve it. I emptied my bin and debug folder and tried building the project again. it worked, at least for me. Or try to clean the solution and try rebuilding it. But of course, posting a part of your code could be more helpful. A: I had the same problem, then I changed the method name to a different name, and changed the references . Then it worked great. I don't know what the problem was, but it looks like there is a bug when changing a method name in some circumstances, is not applied to the whole system. A: I was faced with the same issue, I even cleaned and rebuilt the solution but it didn't help. When I published the application, the old version of the dll was in the bin folder. So I changed the assembly version in the assemblyinfo file. Finally it started working. The new version is available in bin folder. A: My case was a little variation of the other ones here ; but it might help someone. I just added an optional argument in a library and got that message from the GUI using the library. The problem was caused by the GUI and one of its libraries referencing the same library but one was not up to date. I have * *GUI referencing LibA and LibZ *LibA referencing LibZ So I just removed all "bin" and "obj" folders of both LibA and GUI, made sure to have the updated DLL of LibZ in both, and everything worked again. A: It may be a late response: But one possible remedy is to clean up Temporary ASP.NET files folder: I.e., C:\Windows\Microsoft.NET\Framework\vX.X.XXXXX\Temporary ASP.NET Files Deleting the folders related to your website, and rebuild the solution. A: If you were referencing another project as .exe, you have to rebuild it as .dll, to do that you have to set the referenced project to class library into the project settings then build it and referencing the dll into the project were the method was missing. A: Little late to the party. Check the contents of the GAC. If your .dll is already in there then you need to remove it. Use the developer command prompt run as admin and type gacutil -u {name of your dll} A: I just had this issue: Project X is a library used by other projects, it contains dll Y. Project A contains an older version of dll Y, and project A calls code in project X that is from dll Y. The older version of the dll was used when calling code from that dll. Whereas other projects that did not have dll Y referenced, just used the up to date dll Y in project X. Make sure you update the dll/nuget package in all projects that contain it. A: The error also occurred when I had an Action as parameter. I passed a method without wrapping it in a new Action(..). DLL had this: public bool ShowMyForm(bool showConnectionWindow, Action onCloseNotify) {...} Test app called the DLL like so: private void onFormClose() { MessageBox.Show("Form Closed"); } private void ShowForm() { mydll.ShowMyForm(true, onFormClose ); // bug here: wrap in Action } When I changed the call to mydll.ShowMyForm(true, new Action(onFormClose) ); the exception disappeared. The exception text is just misleading - the method is there, but the type of the parameter gave a runtime exception. Too bad it is not picked up at compile time, though. A: In my case I deployed to a .NET 3.0 PC (Windows XP) while the compile target has been .NET 3.5. I really wonder why there is not a more basic warning... Problem has been usage of DataContract from System.Runtime.Serialisation. A: I had this problem when I had copied the solution to a different location on another machine. The Build folder just needed to be changed. Don't ask me why but the solution was built in the build folder (we'll call this folder A) then an old copy was copied from folder B to folder C. At runtime it couldn't find my latest code because it was looking at an older version in folder C. In Properties for the solution in the Build tab, I changed the Output Path to folder B. It then built the latest version in folder B which it copied to folder C and it all worked again. The bit I don't know is why we have folder C in the first place. I have a codedUI Testing solution and folder C is "C:\Users\\Documents\MyCodedUISolution\TestResults\_ 2017-04-20 11_31_29\Out". What this is used for and why it's created, I don't know but if old code is copied here because you change the Output Path or you move the solution without changing the Output Path to what's needed then you're in trouble. A: In my case I had changed the return type of a method from IQueryable to IEnumerable. I had recompiled and uploaded the DLL containing the method but not the DLL with code which calls the method. So the calling DLL was still expecting the method with the previous return type and couldn't find it. A: I was not able to fix it with any of the suggested answers. I could not find any old versions of the custom assembly. I literally searched everywhere with the tool Everything. In debug mode it showed the right version of the assembly but it still could not find the method. Enabling Automatic Binding in the .csproj file fixed it for me <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> I was targeting a package of .NET Framework 4.5 in my project. The above setting is not needed if all packages in the project target .NET Framework 4.5.1 or higher. A: In addition to Nirman's answer - don't forget clear temp files in C:\Users\UserName\AppData\Local\Temp\Temporary ASP.NET Files location. I changed class field type from enum to string and after that got error System.MissingMethodException: Method not found: 'DatnesVeidi DatnesModel.get_DatnesVeids()' when rendering Razor view. None of the previous suggestions helped, just clearing user local temp files. A: For others visiting this question in future: I had this problem testing a replacement netstandard2.0 library that was being integrated with another project. A few other projects within the ecosystem also depended on this replacement library. When testing the new library in the system, the MissingMethodException occured. In my case, we had changed implementations of a base class's abstract method in the new library but we hadn't rebuild the projects that were dependent on the new library. This must have caused the expected abstract implementation of the method to be missing at runtime. It could help to ensure that all dependencies are being rebuilt. A: I know this is a very old question but maybe this will help out somebody. I had the exactly same issue. Fixing the problem was actually deleting all project files that I recently published from the web-server, cleaning and rebuilding the project and publishing it again. After doing that I got the exception 'The file has not been pre-compiled and cannot be requested'. Turned out that I had a assembly missing. The error message is definitely very misleading and it took me 3 days to fix that issue. A: I'm posting the answer in the hope of helping someone that got stucked like I was. I had the following error: Method not found: 'Microsoft.Scripting.Hosting.ScriptEngine IronPython.Hosting.Python.CreateEngine() I tried may on the suggested solution, including (but not limited to) using gacutil.exe /u IronPython developer console ad admin, but nothing worked for me except the following: 1- Going to C:\Windows\Microsoft.NET\ 2- Search for "IronPython" 3- Delete every folder I found, in my case was: C:\Windows\Microsoft.NET\assembly\GAC_MSIL\IronPython C:\Windows\Microsoft.NET\assembly\GAC_MSIL\IronPython.stdlib A: In my case I manually updated Nuget packages without updating their version numbers. The packages were loaded from my local cache, even if I completely reinstalled the packages, because the version numbers were not updated. Once I incremented the version numbers of my Nuget packages, the method could be found.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "57" }
Q: Jquery DatePicker Tooltip Format This is my query i need the tooltip for all the days eg: when mouse over moves to the sep/27/2011. tooltip should display should show as "Tuesday,September 27,2011". How to do implement this?.This is my jquery datepicker <script type="text/javascript"> $(function() { $( "#<%= this.txtFrom.ClientID %>" ).datepicker({ showOn: 'both', buttonImage: "Images/calendar.gif", buttonImageOnly: true, showmonth:true, autoSize: true, changeMonth: true, changeYear: true, showAnim: 'slideDown', buttonText: "", duration: 'fast', showOtherMonths: true, selectOtherMonths: true }); $(".ui-datepicker-trigger").mouseover(function() { $(this).css('cursor', 'pointer'); }); }); </script > Finally i found the solution: beforeShowDay: function(date) { return [true, '', $.datepicker.formatDate('DD, MM d, yy', date)]; }, Then //otheroptions A: Think you will need to have it on onSelect method: $( "#<%= this.txtFrom.ClientID %>" ).datepicker({ showOn: 'both', buttonImage: "Images/calendar.gif", buttonImageOnly: true, showmonth:true, autoSize: true, changeMonth: true, changeYear: true, showAnim: 'slideDown', buttonText: "", duration: 'fast', showOtherMonths: true, selectOtherMonths: true, // all your other options above. onSelect: function(dateText, inst) { var d = new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay), format = $.datepicker.formatDate( 'DD, d MM, yy', d ) this.alt = format; //You may want to use title instead of alt, depending on what element you are using. } }); Im using the alt text in this example to give you the format on the input live example: http://jsbin.com/eliwut/
{ "language": "en", "url": "https://stackoverflow.com/questions/7578587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to increase limits on sockets on osx for load testing? I'm creating a load tester that uses libev to create lots of open tcp connections to an app i'm working on. Currently it bombs out at 256 connections, due to the nofiles limit: ulimit -n 256 I can increase this to 1024 by doing the below: ulimit -n 1024 But i cannot increase it further. Ideally i want to set it to 1048576. It gives the following error: ulimit: open files: cannot modify limit: Invalid argument How can i increase the ulimit further on osx? A: (answer updated to use -S as several commenters suggested) $ sysctl kern.maxfiles kern.maxfiles: 12288 $ sysctl kern.maxfilesperproc kern.maxfilesperproc: 10240 $ sudo sysctl -w kern.maxfiles=1048600 kern.maxfiles: 12288 -> 1048600 $ sudo sysctl -w kern.maxfilesperproc=1048576 kern.maxfilesperproc: 10240 -> 1048576 $ ulimit -S -n 256 $ ulimit -S -n 1048576 $ ulimit -S -n 1048576 A: One more thing: Limit on ports is 65535. So you may not get as many as you want to. A: Try running as root (e.g. do a "sudo -s" before running the ulimit command and your program). Note that I'm not sure that 1-million-plus TCP sockets at once is realistically achievable (although I'm interesting in hearing about what happens when you try it ;^)) Also, check out this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "38" }
Q: Is it possible to read cookie/session value while executing PHP5 script through command prompt? I need to read some values from cookie or session when I am executing my php script using command prompt. How can I do that? How to access cookie or session value from Windows command prompt? A: There are no cookies in the CLI, so... yeah. You can pass the desired session name as an argument or environment variable and then use session_name() to set it in your script. A: Cookies are sent from the user's web browser. When you execute a php script from the command line, there is no browser to send or receive cookies. There is no way to access or save cookies and nothing is sent to the script except the parameters you pass on the command line. That being said, there is a way to read a session that someone with a browser has already accessed if you know their PHPSESSID cookie. Let's say someone has accessed your script with a web browser and their PHPSESSID is a1b2c3d4, and you want to execute the script with their session. Execute the following at the command line. php -r '$_COOKIE["PHPSESSID"] = "a1b2c3d4"; session_start(); require("path_to_php_script.php");' Where path_to_php_script.php is the path to the php script you want to execute. And actually, you shouldn't have to start the session if the php file you want to execute starts the session itself. So, you may want to actually try this command: php -r '$_COOKIE["PHPSESSID"] = "a1b2c3d4"; require("path_to_php_script.php");' OK, now let's say you don't want to access someone's session, but you just want to execute the script as if you already had a session. Just execute the previous command, but put in any sessionid you want. And your session will remain intact between calls to the script as long as you use the same PHPSESSID every time you call the script. A: You should try this: exec('php -r \'$_COOKIE["'.session_name().'"]="'.$_COOKIE[session_name()].'";include("file_path.php");\''); Then on your script, do this: session_start(); @session_decode(@file_get_contents(session_save_path().'/sess_'.$_COOKIE[session_name()])); And now you have your session ready to be used! Remember that the function session_save_path() will get the "default" path, set in .ini files. You can always use a custom path to load the session.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: cassandra secondary index return results in lexical rowkey order, even with RandomPartitioner? As far as I understand, a Cassandra secondary index is stored as an internal CF, where the rowkeys are the values within the index, and the columns are rowkeys back to the original CF being indexed. Is it possible to have the columns of the index store the original CF rowkey values? Then, since columns within the index row are sorted, a query for a particular value in the index theoretically could return rowkeys in sorted value order. This is how I would do it if I was to manually maintain my own index CF (I'd have my manual index CF sort its columns as strings), I'm curious if the same can be done with built-in secondary indexes. A hopefully clarifying example... I have 5 rows with 2 columns each (identifier is to easily distinguish the rows, birth_date is being indexed), each row with a UTF8 key (in this case a single char string): [default@demo] create column family users with comparator=UTF8Type ... and column_metadata= ... [{column_name: identifier, validation_class: LongType} ... ,{column_name: birth_date, validation_class: LongType, index_type: KEYS}]; 86518c00-e9f7-11e0-0000-242d50cf1fde Waiting for schema agreement... ... schemas agree across the cluster [default@demo] set users['a']['identifier'] = 1; Value inserted. [default@demo] set users['a']['birth_date'] = 1975; Value inserted. [default@demo] set users['c']['identifier'] = 3; Value inserted. [default@demo] set users['c']['birth_date'] = 1975; Value inserted. [default@demo] set users['b']['identifier'] = 2; Value inserted. [default@demo] set users['b']['birth_date'] = 1975; Value inserted. [default@demo] set users['x']['identifier'] = 5; Value inserted. [default@demo] set users['x']['birth_date'] = 1975; Value inserted. [default@demo] set users['f']['identifier'] = 4; Value inserted. [default@demo] set users['f']['birth_date'] = 1975; Value inserted. Now when I make an index query, I get the users rows back in what appears to be reverse order of their rowkeys' md5 hashes (looking at the identifier, the result order is x,b,f,c,a): [default@demo] get users where birth_date = 1975; ------------------- RowKey: ff => (column=birth_date, value=1975, timestamp=1317231030507000) => (column=identifier, value=5, timestamp=1317231030504000) ------------------- RowKey: 0b => (column=birth_date, value=1975, timestamp=1317231030502000) => (column=identifier, value=2, timestamp=1317231030500000) ------------------- RowKey: 0f => (column=birth_date, value=1975, timestamp=1317231031992000) => (column=identifier, value=4, timestamp=1317231030509000) ------------------- RowKey: 0c => (column=birth_date, value=1975, timestamp=1317231030498000) => (column=identifier, value=3, timestamp=1317231030494000) ------------------- RowKey: 0a => (column=birth_date, value=1975, timestamp=1317231030491000) => (column=identifier, value=1, timestamp=1317231030476000) 5 Rows Returned. My question is, is there a way to have the internal index CF use 'a', 'b', 'c', 'f', 'x' as its column names, so that when I make an index query, I get back the users rows in lexical rowkey order. A: The reason you can't do this is, the index ordering has to match the partitioner ordering, or you couldn't "page" through resultsets across multiple nodes (without having to do scatter/gather for each query, anyway). We do have https://issues.apache.org/jira/browse/CASSANDRA-1599 open to allow custom ordering, so you should watch that issue for updates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Entity Framework 4.1 DbContext generator problems I am new to Entity Framework 4.1 and I really wanted to transition to POCO classes for my model. I found that this was very easy using the "DbContext Generator" item provided when you install EF 4.1. It did exactly what I wanted it to do and generated the DbContext object and all the POCOs for my existing EDMX model. I ran the app and tested that it was still working. It was. Happy with this I deleted the EDMX file and the T4 templates and began reorganizing my new POCOs. However, after getting it to build properly again I encountered a runtime problem. When instantiating the DbContext it is unable to find the metadata files: .csdl, .ssdl, & .msl (I really don't know what they are, just that they are part of all EF connection strings). After putting back my EDMX it ran fine again. I really don't want the EDMX file anymore. I would really like to stick to POCO classes and forget that the EDMX ever existed; especially because I don't want it running those T4 templates and regenerating my POCOs. I have four related questions: * *Why do I have to keep the edmx in my project? *Is there a workaround for this? *What happens when you do true "code-first" with EF 4.1, where does it get those metadata files from? *What are those metadata files anyway? A: You should read this. It describes the different project types. The short answer is you need the .edmx file when using the dbcontext generator. If you want to use Code First, you have to either describe the model by hand or use the Entity Framework power tools CTP1 to reverse engineer a code first model. A: * *The EDMX file is responsible for embedding the CSDL, SSDL, & MSL metadata resources in the assembly at compile-time. *Yes. You will need Entity Framework Power Tools CTP 1. See Mystere Man's answer on this question for a link. This will be a true conversion from an existing database to code-first. What this means is that your code will drive the schema going forward, not the other way around. *When you are doing true code-first development the CSDL, SSDL, & MSL metadata resources are still there. They are simply inferred from your object model when you build. Because the code controls the model and schema, it is able to infer these resources on its own. There are some instances though where it does not know what to infer from the code. For instance, if you change an entity property name it has no way of knowing if you intended to delete the old column (property name) and add a new column with the new name, or if you intended to keep the old column and rename it with the new name. This is why there is no good data/schema migration with EF code-first and why it drops and recreates the entire database each time you change your model in code. This shortcoming of the DbContext API is definitely the biggest issue and is currently being worked on by the ADO.NET team as noted on Scott Hansleman's blog post. For now I have personally opted to modify the database manually and then simply update my C# code to reflect it. This requires some decent knowledge of how these things work and I'm still practicing. Another way to do this is to leave the EDMX file there, update it like you normally would, and let it regenerate your POCOs when things change. However that is almost no different than doing classic EF updates as any changes to the POCOs will be overwritten when they are regenerated. Yet another solution is to again leave the EDMX file there and update it when things change, but set the "Transform Related Text Templates On Save" property to false. http://www.codetunnel.com/content/images/TransformRelatedTextTemplatesOnSave.jpg This prevents the EDMX from running your T4 templates and regenerating your POCOs. So you would simply update it to ensure that the metadata resources remain accurate. But then you would manually modify your POCOs to reflect any changes to the model/schema. This still requires a lot more work than just letting it generate your code but it's good for learning in my humble opinion. *The CSDL, SSDL, & MSL are metadata resources for EF. They help EF determine how to map result sets to your object model and vice versa. It is the bridge between the database schema and your code. No matter what way you use EF these resources are there, only differing in the way they are generated. A: That doesn't work this way. If you decide to use DbContext Generator you are saying that your mapping will be described in EDMX file. During compilation EDMX file is decomposed to three separate files with .ssdl, .csdl and .msl extensions. These metadata files describes your database, entities and mapping from database to entities. These files are by default stored as resources in your compiled assembly and referenced from connection string passed to your DbContext instance. You must keep your EDMX file in the project if you want to use DbContext created by generator. It is same mapping approach as was used in EFv1 and EFv4 = it is not code first. Code first means no EDMX and no T4 template to generate mapping and code for you. In normal way code first means that you write your classes before you have any database and a database is created by EF. Many people are using this approach with existing database and mapping they classes to existing database manually but it requires some knowledge / experience with EF (or you can ask targeted questions here and we will help you). Metadata are needed for context to perform mapping and SQL command generation. EDMX mapping strategy uses metadata defined in mentioned XML files. Code first mapping strategy uses some default conventions, fluent-API or data annotations to get metadata from compiled code. There is separate project allowing to generate code first mapping from existing database - I pointed that project in your previous question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I debug this Hibernate/JPA slow query issue? I have a Hibernate/JPA query which performs a simple query based on an indexed field in the database. The table is fairly large with around 28 million records but when using the database directly the query returns instantaneously, with Hibernate+JPA it takes over 20 seconds. The database is PostgreSQL 9.0.4. This is an extract of the logs including the relevant query and from the timestamps you can see a long delay between the query getting issued and opening the ResultSet. 2011-09-28 06:26:38,019 [http-thread-pool-8080(5)] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0) 2011-09-28 06:26:38,019 [http-thread-pool-8080(5)] DEBUG org.hibernate.jdbc.ConnectionManager - opening JDBC connection 2011-09-28 06:26:38,020 [http-thread-pool-8080(5)] DEBUG org.hibernate.SQL - select pafaddress0_.address_id as address1_0_, pafaddress0_.admin1 as admin2_0_, pafaddress0_.admin2 as admin3_0_, pafaddress0_.admin3 as admin4_0_, pafaddress0_.barcode as barcode0_, pafaddress0_.building_name as building6_0_, pafaddress0_.building_number as building7_0_, pafaddress0_.country_name as country8_0_, pafaddress0_.dependent_locality as dependent9_0_, pafaddress0_.dependent_street as dependent10_0_, pafaddress0_.dept_name as dept11_0_, pafaddress0_.double_dep_locality as double12_0_, pafaddress0_.dps as dps0_, pafaddress0_.mailsort as mailsort0_, pafaddress0_.org_name as org15_0_, pafaddress0_.pca_id as pca16_0_, pafaddress0_.pobox as pobox0_, pafaddress0_.postcode as postcode0_, pafaddress0_.postcode1 as postcode19_0_, pafaddress0_.postcode_type as postcode20_0_, pafaddress0_.street as street0_, pafaddress0_.su_org_indicator as su22_0_, pafaddress0_.subbuilding_name as subbuil23_0_, pafaddress0_.posttown as posttown0_, pafaddress0_.trad_county as trad25_0_, pafaddress0_.type as type0_, pafaddress0_.udprn as udprn0_ from paf pafaddress0_ where pafaddress0_.pca_id=? limit ? 2011-09-28 06:27:01,897 [http-thread-pool-8080(5)] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open ResultSet (open ResultSets: 0, globally: 0) 2011-09-28 06:27:01,900 [http-thread-pool-8080(5)] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close ResultSet (open ResultSets: 1, globally: 1) 2011-09-28 06:27:01,900 [http-thread-pool-8080(5)] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1) 2011-09-28 06:27:01,900 [http-thread-pool-8080(5)] DEBUG org.hibernate.jdbc.ConnectionManager - aggressively releasing JDBC connection 201 My Entity has no complex associations and there are no indications in the logs as to what is going on during this long delay. @Entity @Table(name = "paf") @NamedQueries({ @NamedQuery(name = "PafAddress.findByPcaId", query = "SELECT a FROM PafAddress a where a.pcaId=:pcaId ") }) public class PafAddress implements Serializable, Identifiable<Long> { private static final long serialVersionUID = -5831210090000717285L; @Id @Column(name = "address_id") private Long id; private String postcode; @Column(name = "posttown") private String town; @Column(name = "dependent_locality") private String dependentLocality; @Column(name = "double_dep_locality") private String doubleDepLocality; @Column(name = "street") private String street; @Column(name = "dependent_street") private String dependentStreet; @Column(name = "building_number") private String buildingNumber; @Column(name = "building_name") private String buildingName; @Column(name = "subbuilding_name") private String subbuildingName; @Column(name = "pobox") private String pobox; @Column(name = "dept_name") private String deptName; @Column(name = "org_name") private String orgName; @Column(name = "udprn") private String udprn; @Column(name = "postcode_type") private String postcodeType; @Column(name = "su_org_indicator") private String suOrgIndicator; @Column(name = "dps") private String dps; @Column(name = "postcode1") private String postcode1; @Column(name = "admin1") private String admin1; @Column(name = "admin2") private String admin2; @Column(name = "admin3") private String admin3; @Column(name = "trad_county") private String tradCounty; @Column(name = "country_name") private String countryName; @Column(name = "mailsort") private String mailsort; @Column(name = "barcode") private String barcode; @Column(name = "type") private String type; @Column(name = "pca_id") private Double pcaId; public PafAddress() { } Any ideas as to why this query is performing so badly or how I can determine the cause? A: I've discovered the problem: I enabled auto_explain in PostgreSQL for queries taking >1 second which enabled me to see the query plan in the logs. see http://www.postgresql.org/docs/current/static/auto-explain.html For the Hibernate/JPA query: Limit (cost=0.00..13.12 rows=2 width=469) -> Seq Scan on paf pafaddress0_ (cost=0.00..943043.74 rows=143753 width=469) Filter: ((pca_id)::double precision = 7912139::double precision) Native database query: QUERY PLAN Limit (cost=0.00..7.03 rows=2 width=469) -> Index Scan using paf_pca_idx on paf pafaddress0_ (cost=0.00..505649.83 rows=143753 width=469) Index Cond: (pca_id = 7912139::numeric) It was slow because a sequential scan was being performed instead of using the index, seemingly as a result of a type mismatch between my entity and database field. The entity property was a 'Double', whilst the database type was 'numeric' and the query explanation shows a cast of the database field occurring to double double precision. I changed my database field type to double precision and the query is now performing as expected. A: If the sql is the same, the bottleneck must be the process of creating the individual java objects for each record. I assume it returns a large number of records, you could try to limit this number.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578611", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Database Sorting depending on Integer? in my database having some row's , in every row having three column's(id, name, moves, time). i want to sort the rows depending on the moves this is the integer value. i tried like this but unlucky. public Cursor fetchAllNotes() { return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_NAME, KEY_MOVES,KEY_TIME}, null, null, null, null, KEY_MOVES); } used like this private void getallrows() { // get all the contacts.. db.open(); Cursor c = db.fetchAllNotes(); if (c.moveToFirst()) { do { Sorting(c); } while (c.moveToNext()); } db.close(); } moves i have like 15, 45, 21, 11, 10,75,33 i want like this 10,11,15,21,33,45,75 A: Try this - return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_NAME, KEY_MOVES,KEY_TIME}, null, null, null, null, KEY_MOVES + " ASC"); or return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_NAME, KEY_MOVES,KEY_TIME}, null, null, null, null, KEY_MOVES + " DESC"); EDIT - 1: If you want to display name,you can use like this, private void getall() { db.open(); Cursor c = db.fetchAllNotes(); int i=1; if (c.moveToFirst()) { do { DisplayContact(c.getString(c.getColumnIndex(KEY_NAME))); i++; } while (c.moveToNext()); } db.close(); } A: Why dont u make query in such a way which return the sorted data itself ??? Try out This query : SELECT * FROM DATABASE_TABLE ORDER BY KEY_MOVES ASC or db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_NAME, KEY_MOVES,KEY_TIME}, null, null, null, null, KEY_MOVES + " ASC"); Hope u get it...
{ "language": "en", "url": "https://stackoverflow.com/questions/7578617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What are some specific applications of finite state automata? There are several topics discussing finite state automata, but none that I've seen that go into detail about real world applications. What are some concrete examples of finite state automata in action? A: Most popular application of FSMs are parsers of various kind. As for real life example is my markup (HTML/XML) parser (tokenizer to be precise): HTML_XML_Scanner
{ "language": "en", "url": "https://stackoverflow.com/questions/7578618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: anchor + Link to base URL If I'm on a page like http://localhost/balibar.co/?dating=dating-articles-and-information and I want to have anchor that links to the base URL being http://localhost/balibar.co Is there a way to do this without hard coding the URL? I've tried: <a href="/"></a> <a href="#"></a> will have a few domains use this page so I don't want to hard code the domain name if possible. A: Assuming the page can load fine as http://localhost/balibar.co/ then a relative path with a single dot (.) will take you to it <a href="./"></a> I believe you can also use a single dot by itself without the slash <a href="."></a> The single dot (.) in the relative path represents the current directory. A: If you would like all URLs to be relative to that base URL, you can use HTML's <base> tag in your <head> like so: <base href="http://localhost/balibar.co/"> A: The HTML <base> tag may suit your needs. <html> <head> <base href="http://www.yahoo.com/images/" /> </head> <body> <!-- Links to http://www.yahoo.com/images/ --> <a href=".">Top-level link</a> </body> </html> Note that the href attribute will also affect your image and artifact urls, e.g. . More info here A: <head> <base href="http://www.google.com" /> </head> <body> <a href="">Google?</a> </body> That link will now go to google.com Here is the proof: http://jsfiddle.net/3wXCJ/ You use HTML's <base> tag to specify the base url for all elements that use the href attribute. Now, any tag with an href or src attribute that is empty, it will automatically go to the url you specified in the base tag by default. A: <a href="/"></a> only works if the host sees balibar.co as an index page. Otherwise you'll have to go <a href="/balibar.co"></a> A: from what I understand about SEO, you are better off coding the domain name, rather than an anchor. because you have several domain names, I would use PHP to first figure out what domain name is currently used, and then write it to the link: <a href="<?php echo 'http://'.$_SERVER['SERVER_NAME']; ?>">
{ "language": "en", "url": "https://stackoverflow.com/questions/7578620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Java recursively print array in reverse The array is an array of strings. The array is {"hello", "how", "are", "you", "?"} It sort of works, but the output mixes up the last 2 elements, and when I run my program the output comes out as you ? are how hello, it should be ? you are how hello. I put in a print statement to see what my left and right are and if they switch, but that didn't help since they only printed out the start values and nothing else. Why is it printing out wrong? Is it not doing the recursion? This is my method. It has to be done with divide and conquer. public void outrev() { outrev(0, a.length - 1); } private void outrev(int left, int right) { System.out.println("left a[" + left + "] is " + a[left]); System.out.println("right a[" + right + "] is " + a[right]); int mid; if (left > right) { //do nothing } else if (left == right) { System.out.print(a[left]); } else { mid = (left + right) / 2; outm(mid + 1, right); System.out.print(a[mid] + " "); outm(left, mid - 1); } } A: public void outrev() { List<String> arr = Arrays.asList(a); outrev(arr); } private void outrev(List<String> arr) { System.out.println(arr.get(arr.size() - 1)); if(arr.size() != 1){ outrev(arr.subList(0, arr.size() - 1)); } } You have to import import java.util.Arrays; import java.util.List; Dunno if that breaks your homework's rules. Notice out outrev calls itself, but stops calling itself once the list is one item in length? That is the primary tenant of recursion, i.e. a function that calls itself, and has a terminating condition. In your original code outrev isn't really calling itself; you are overloading outrev in one case however, but that is different than recursion -- unless outm, which you didn't define was intended to be a call to outrev. You should also have this program check to make sure that the list isn't empty, as your teacher could throw that at you, and the code would fail in that case. Remember, with recursion, it's best to think about in terms of: 1) What to do when I have zero items. 2) What to do when I have one item. 3) How to handle every other case where my list has more than one item.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to stop webserver (implemented through web.py and threading) I have implemented simple webserver using web.py. And through multithreading module, I am able to run multiple instances of webserver listening on separate ports. Now all the instnces are listening http requests forever. and I want to step a particular thread. Is there a way to stop an instance from listening (or kill particular thread altogether.) A: api.py import web import threading urls = ( '/', 'index', ) class index: def GET(self): return "I'm lumberjack and i'm ok" def run(): app = web.application(urls, globals()) t = threading.Thread(target=app.run) t.setDaemon(True) # So the server dies with the main thread t.setName('api-thread') t.start() frame.py import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import * import api app = QApplication(sys.argv) web = QWebView() api.run() web.load(QUrl("http://0.0.0.0:8080/")) web.show() sys.exit(app.exec_())
{ "language": "en", "url": "https://stackoverflow.com/questions/7578629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: What is the difference between (char)0 and '\0'? in C What is the difference between using (char)0 and '\0' to denote the terminating null character in a character array? A: They're both a 0, but (char) 0 is a char, while '\0' is (unintuitively) an int. This type difference should not usually affect your program if the value is 0. I prefer '\0', since that is the constant intended for that. A: The backslash notation in a character literal allows you to specify the numeric value of a character instead of using the character itself. So '\1'[*] means "the character whose numeric value is 1", '\2' means "the character whose numeric value is 2", etc. Almost. Due to a quirk of C, character literals actually have type int, and indeed int is used to handle characters in other contexts too, such as the return value of fgetc. So '\1' means "the numeric value as an int, of the character whose numeric value is 1", and so on. Since characters are numeric values in C, "the character whose numeric value is 1" actually is (char)1, and the extra decoration in '\1' has no effect on the compiler - '\1' has the same type and value as 1 in C. So the backslash notation is more needed in string literals than it is in character literals, for inserting non-printable characters that don't have their own escape code. Personally, I prefer to write 0 when I mean 0, and let implicit conversions do their thing. Some people find that very difficult to understand. When working with those people, it's helpful to write '\0' when you mean a character with value 0, that is to say in cases where you expect your 0 is soon going to implicitly convert to char type. Similarly, it can help to write NULL when you mean a null pointer constant, 0.0 when you mean a double with value 0, and so on. Whether it makes any difference to the compiler, and whether it needs a cast, depends on context. Since '\0' has exactly the same type and value as 0, it needs to be cast to char in exactly the same circumstances. So '\0' and (char)0 differ in type, for exactly equivalent expressions you can either consider (char)'\0' vs (char)0, or '\0' vs 0. NULL has implementation-defined type -- sometimes it needs to be cast to a pointer type, since it may have integer type. 0.0 has type double, so is certainly different from 0. Still, float f = 1.0; is identical to float f = 1; and float f = 1.0f, whereas 1.0 / i, where i is an int, usually has a different value from 1 / i. So, any general rule whether to use '\0' or 0 is purely for the convenience of readers of your code - it's all the same to the compiler. Pick whichever you (and your colleagues) prefer the look of, or perhaps define a macro ASCII_NUL. [*] or '\01' - since the backslash introduces an octal number, not decimal, it's sometimes wise to make this a bit more obvious by ensuring it starts with a 0. Makes no difference for 0, 1, 2 of course. I say "sometimes", because backslash can only be followed by 3 octal digits, so you can't write \0101 instead of \101, to remind the reader that it's an octal value. It's all quite awkward, and leads to even more decoration: \x41 for a capital A, and you could therefore write '\x0' for 0 if you want. A: Zero can mean a lot of different things in C. You should use the null character '\0', because then there can be no confusion over that your intention is string termination. If you set a char to 0, that can mean null termination, but it can also mean that you are just using the char as an 8-bit integer for calculations, rather than as part of a string. This can be confused further if you are also using pointers in the same code and compare them against zero, which is then a null pointer. A: Character array means You are taking String so I advise you to use '\0' at the end of character Array after reading all the Characters of from user because 0 is simple Character but '\0' is NULL which indicates end of String.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Is "Selects Against ALL_SYNONYMS Perform Badly on 10g Release 10.2 [ID377037.1]" fixed for Oracle 11.2.0.1? The metalink article [ID377037.1] I have states that the issue applies to Oracle 10.2.0.1 to 10.2.0.4 but there is no resolution to the issue. Does anyone know if this issue is fixed on Oracle 11.2.0.1? A: Apparently not, the 9.2 version is still faster. But the difference isn't large, and if you're very worried about performance it looks like DBA_SYNONYMS is almost as fast. (But you'd want to think carefully before granting access to DBA_ views.) The performance of these data dictionary objects fluctuate wildly, the times here are very rough estimates: --0.3 seconds: select count(*) from all_synonyms; --0.1 seconds: select count(*) from sys.all_synonyms_920x; --0.2 seconds: select count(*) from dba_synonyms; --0.125 seconds: select * from all_synonyms where synonym_name = 'APEX_ITEM'; --0.03 seconds: select * from sys.all_synonyms_920x where synonym_name = 'APEX_ITEM'; --0.05 seconds: select * from dba_synonyms where synonym_name = 'APEX_ITEM'; A: Metalink Doc ID 1242844.1 says poor performance of ALL_SYNONYMS in 11.2.0.1 and 11.2.0.2 is fixed in 11.2.0.3. The document also provides the DDL to retrofit the 11.2.0.3 view to the earlier releases. A: It's not fixed in 11.2.0.3, we are running 11.2.0.3.6 and getting problems with ALL_SYNONYMS. Toad queries ALL_SYNONYMS when it starts and the Toad users are complaining about connection time since the upgrade. I've found that if you add the RULE hint to the view it improves the performance massively. In our case down from 30secs to 4secs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Benchmarking Zend Framework with a plugin I have created this plugin to benchmark the performance of my Zend Framework Project http://pastebin.com/HD9MpRfR One odd thing that happens is that sometimes the generated values are negative, Unit: Microseconds Routing: 0.0013879999999999 Dispatch : -0.477942 Dispatch Loop: -0.470018 Total : -0.430279 Why is this? A: Your code is calling microtime(). I think you need to call it like this: microtime(true). According to the PHP documentation: If used and set to TRUE, microtime() will return a float instead of a string, as described in the return values section below. So, you are substracting strings every time. It might lead to strange results. Also, check the returned *Start and *End values, maybe there is some problem in the logic of your plugin (I didn't review it in detail). An alternative technique could be to store these values in Zend_Registry instead of member variables. Maybe your plugin is being called several times, for startup and shutdown (this would reset the values of the member variables). Hope that helps,
{ "language": "en", "url": "https://stackoverflow.com/questions/7578638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Command Line API and waitForDataInBackgroundAndNotify I am new to objective c. i am using following code to execute command line API in objective c. code is working fine for me. but why this code is using NSRunLoop? -(void)uploadData { setenv([@"PASSWORD" UTF8String], [mPassword UTF8String], 1); [task setLaunchPath:executablePathRoot]; [task setArguments:array]; NSPipe *pipe = [NSPipe pipe]; NSPipe *errorPipe = [NSPipe pipe]; [task setStandardOutput:pipe]; [task setStandardError:errorPipe]; //keeps your log where it belongs //[task setStandardInput:[NSPipe pipe]]; NSFileHandle *outFile = [pipe fileHandleForReading]; NSFileHandle *errFile = [errorPipe fileHandleForReading]; [task launch]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(terminated:) name:NSTaskDidTerminateNotification object:task]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(outData:) name:NSFileHandleDataAvailableNotification object:outFile]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(errData:) name:NSFileHandleDataAvailableNotification object:errFile]; [outFile waitForDataInBackgroundAndNotify]; [errFile waitForDataInBackgroundAndNotify]; NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; while(!terminated) { if (![[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) { break; } [pool release]; pool = [[NSAutoreleasePool alloc] init]; } [pool release]; [self appendDataFrom:outFile to:output]; [self appendDataFrom:errFile to:error]; //[task waitUntilExit]; [task release]; } -(void) outData: (NSNotification *) notification { NSLog(@"outData"); NSFileHandle *fileHandle = (NSFileHandle*) [notification object]; [self appendDataFrom:fileHandle to:output]; [fileHandle waitForDataInBackgroundAndNotify]; //Checks to see if data is available in a background thread. } -(void) errData: (NSNotification *) notification { NSLog(@"errData"); NSFileHandle *fileHandle = (NSFileHandle*) [notification object]; [self appendDataFrom:fileHandle to:output]; [fileHandle waitForDataInBackgroundAndNotify]; } - (void) terminated: (NSNotification *)notification { NSLog(@"Task terminated"); [[NSNotificationCenter defaultCenter] removeObserver:self]; terminated =YES; } A: This is to make the method uploadData synchronous. The execution cannot quit the while loop until the terminated flag is set YES. The following call [NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]] allows the app to process other events. So, when the NSTaskDidTerminateNotification received the terminated flag will be changed and the while loop finishes. However, there is no need to allocate an autorelease pool here. Also, the code is excessive. It can much simpler: while(!terminated) { [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; } Update: Taking into account ughoavgfhw's comments, let's make the call even safer by including the result of runMode: beforeDate: into the condition. while(!terminated && [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
{ "language": "en", "url": "https://stackoverflow.com/questions/7578647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: BingoBoard Segmentation Fault I keep getting a segmentation fault with this Bingo Board I'm trying to create in C++. Valgrind didn't tell me much more than this: ==2734== Memcheck, a memory error detector ==2734== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al. ==2734== Using Valgrind-3.6.1 and LibVEX; rerun with -h for copyright info ==2734== Command: ./Bingo ==2734== ==2734== Invalid read of size 1 ==2734== at 0x5D0A436: vfprintf (vfprintf.c:1620) ==2734== by 0x5DBF8ED: __printf_chk (printf_chk.c:37) ==2734== by 0x400FC0: generate(int, int) (in /home/holland/Code/cpp/Bingo-build-desktop-Desktop_Qt_4_7_4_for_GCC__Qt_SDK__Release/Bingo) ==2734== by 0x400B69: main (in /home/holland/Code/cpp/Bingo-build-desktop-Desktop_Qt_4_7_4_for_GCC__Qt_SDK__Release/Bingo) ==2734== Address 0x62 is not stack'd, malloc'd or (recently) free'd ==2734== ==2734== ==2734== Process terminating with default action of signal 11 (SIGSEGV) ==2734== Access not within mapped region at address 0x62 ==2734== at 0x5D0A436: vfprintf (vfprintf.c:1620) ==2734== by 0x5DBF8ED: __printf_chk (printf_chk.c:37) ==2734== by 0x400FC0: generate(int, int) (in /home/holland/Code/cpp/Bingo-build-desktop-Desktop_Qt_4_7_4_for_GCC__Qt_SDK__Release/Bingo) ==2734== by 0x400B69: main (in /home/holland/Code/cpp/Bingo-build-desktop-Desktop_Qt_4_7_4_for_GCC__Qt_SDK__Release/Bingo) ==2734== If you believe this happened as a result of a stack ==2734== overflow in your program's main thread (unlikely but ==2734== possible), you can try to increase the size of the ==2734== main thread stack using the --main-stacksize= flag. ==2734== The main thread stack size used in this run was 8388608. ==2734== ==2734== HEAP SUMMARY: ==2734== in use at exit: 86,091 bytes in 276 blocks ==2734== total heap usage: 2,819 allocs, 2,543 frees, 246,187 bytes allocated ==2734== ==2734== LEAK SUMMARY: ==2734== definitely lost: 0 bytes in 0 blocks ==2734== indirectly lost: 0 bytes in 0 blocks ==2734== possibly lost: 0 bytes in 0 blocks ==2734== still reachable: 86,091 bytes in 276 blocks ==2734== suppressed: 0 bytes in 0 blocks ==2734== Rerun with --leak-check=full to see details of leaked memory ==2734== ==2734== For counts of detected and suppressed errors, rerun with: -v ==2734== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4) Here's my code: #include <vector> #include <iostream> #include <algorithm> #include "board.h" #define MIN 0 #define MAX 15 using std::vector; using std::random_shuffle; using std::cout; using std::endl; void generate(int numRows, int numColumns) { std::vector<int> b; std::vector<int> i; std::vector<int> n; std::vector<int> g; std::vector<int> o; char * bingo = "bingo"; for(int index = MIN; index <= 15; index++) { b.push_back(index); i.push_back(index + 15); n.push_back(index + 30); g.push_back(index + 45); o.push_back(index + 60); } std::random_shuffle(b.begin(), b.end()); std::random_shuffle(i.begin(), i.end()); std::random_shuffle(n.begin(), n.end()); std::random_shuffle(g.begin(), g.end()); std::random_shuffle(o.begin(), o.end()); for (int i = 0; i <= 5; i++) { printf(" %s ", bingo[i]); } for (int j = 0; j <= 15; j++) { printf(" %d %d %d %d %d \n", b.back(), i.back(), n.back(), g.back(), o.back()); //b.pop_back(); //i.pop_back(); //n.pop_back(); //g.pop_back(); //o.pop_back(); } delete bingo; } A: The problem is with: delete bingo; where bingo is not pointing to memory obtained from use of new but is pointing to a string literal. Also the format specifier or the argument to printf is incorrect: printf(" %s ", bingo[i]); %s expects argument to be a char * but your argument type is integer. Either change the format specifier to say %c or %d OR change the argument.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JQuery Ajax load non local pages with links disabled Sorry everybody, I'm kind of a newbie to Ajax and Json. Thanks in advance for any help! Here's the situation: I have a webpage that I created with several links on it. Most of these links point to pages on Wikipedia or various academic sources. When my page loads, I need all links to be enabled. But when I load the wikipedia/academic pages, I need them to load with the links disabled. The point is to present the user with a list of sources so they can fill out a questionnaire, but while filling out the questions I don't want them to get distracted by other things on the source pages or be able to navigate more than 1 step away from the questionnaire. A: Okay, I did it. You have to open the page in an iframe and cover the iframe with a div that uses a transparent background. This way you can see the iframe, but you can't touch it. I got the method from here: http://webdeveloper.com/forum/showthread.php?t=182260 And this is my proof: http://jsfiddle.net/MarkKramer/jwQtd/ Note: Notice how the div doesn't cover the whole Iframe, I have it set just wide enough to cover the iframe, but to still show the scroll bar so you can see the web page and you can scroll up and down it, but you can't click on it. Here is the source: <div id="framecover" style=" position:absolute; width:(same as iframe -30px for the scroll bar); height:(same as iframe); top:(use to set over iframe) right:(use to set over iframe) z-index:(higher than iframe); background-color: transparent;" <!--change the bg-color to see where the div is when youre positioning it--> ></div> <iframe src="_whatever you want_" width="_y_" height="_x_"> <!--Fallback for older browsers--> <p>Your browser does not support iframes.</p> </iframe>
{ "language": "en", "url": "https://stackoverflow.com/questions/7578652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: .Net Runtime Assembly Binding I have a rather unusual problem and need some ideas. I maintain two codebases that are 99% identical. A new project has come along that under some runtime condition needs to use code base A and in other conditions use precompiled code base B. I have abstracted the functionality into an interface for the project and plan to have two implementation assemblies that reference the different code bases. I plan on using a service locator pattern to instantiate the object. So it looks a little like this. Assembly A (Website) Assembly B Libraries -------------------------------|--------------------|------------- Project -> Service Locator -> Implementation A -> Code Base A -> Implementation B -> Code Base B My concerns lie around in loading the same named assemblies of code base a and b and having runtime conflicts. What is the best approach for this scenario and why? A: It sounds to me that if you give each assembly a different name it would effectively solve the problem. Even though the code base in each assembly would be nearly identical, assemblies are identified by name (and other characteristics), so naming them differently would ensure that they don't collide. The types (classes etc.) inside each assembly use the assembly name to build their fully qualified names, so you shouldn't have any conflicts there. However, the interface behind which you hide the assembly types must be defined in a third library (which might be your consuming library).
{ "language": "en", "url": "https://stackoverflow.com/questions/7578658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JQuery animate always removes display:none and adds display:block to inline css I'm running some simple jquery for animation over a group of images. Some of the images are hidden and some are not. But it seems jquery is just making them all visible, I want to animate these with changing how they display. $('.productImageLarge').animate({ width: 185, height: 185 }); JQuery automatically makes them all display:block. Is it possible to animate without changing the display visibility. Thanks A: If you set the specify the display property and add a !important declaration jQuery will restore the display property after it completes its animation. For example, if you run this command on the jQuery homepage it will set the first book image to display:inline, animate it and then validate that the resulting HTML has the correct display property. $($(".jq-bookImg").get(0)) .css("display","inline !important") .animate({ width: 85, height: 185 }, function(){ console.log("display propery is " + $(this).css("display")); } );
{ "language": "en", "url": "https://stackoverflow.com/questions/7578669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby on Rails object serialization I have an items object which is a hash and I want to store it in database table. Migration: t.string :items Writing: items: items.to_json Reading: @order.items # returns a string, not a hash as needed. How do I solve this? A: You should add to your model the serialize declaration: class Xyzzy < ActiveRecord::Base serialize :items end Optionally you may specify a class: serialize :items, Hash so an exception will be thrown if the 'items' object happens to be of some other class. Also, the column in the database should be declared as :text, because the default length of the :string column is mere 255 characters, and it may be too short for a serialized object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Append to end of line to specific lines I am writing a shell script and need some help. This script will take a file name as input and will modify that input file according to some logic. Now, this file will be modified only specific lines, I will get to know the line number though. So after getting to know the line number, how do I append some text to end of that line? The text to be appended will keep changing for each line. Example : The input files contain a list of file names. Input file is abc.txt, with content: a.c; b.c; c.c; d.c; This abc.txt is input to the script, the script should pick up the file names from abc.txt and check where the files are present in a specified directory. I have another script which gives the name of the directory if the file is there in that location. If the output of other script is some folder name then it should modify the input file. For example, if a.c and c.c files are present in dirctory 'somefolder1' and 'somefolder2' (respectively), then expected output is: a.c;somefolder1; b.c; c.c;somefolder2; d.c; This is the logic I am using: MAX_LINES=`wc -l ${CHECKOUT_FILE}.tmp |awk '{print $1}'` COUNTER=0 #Logic while [ $COUNTER -ne $MAX_LINES ] do COUNTER=`expr $COUNTER + 1` LINE_READ=`sed -n ${COUNTER}p ${CHECKOUT_FILE}.tmp` PROGRAM_NAME=`echo $LINE_READ | cut -f 1 -d ";" ` FOLDER_NAME=`${CLEARCASE}/somescript.sh ${PROGRAM_NAME} ${CHECKOUT_COUNTRY}` if [ $FOLDER_NAME = 'NOTFOUND' ] ; then echo $FOLDER_NAME continue else sed -e '${COUNTER}s/$/${FOLDER_NAME};/' < ${CHECKOUT_FILE}.tmp > temp.txt fi done A: I don't know how to do it in sh, but I've done a little Python script: #!/usr/bin/env python import sys mapping = { 2: 'second', 4: 'fourth', } def main(src, dst): with open(src, 'r') as f: lines = f.readlines() new_lines = process(lines) with open(dst, 'w') as f: f.write(''.join(new_lines)) def process(lines): for l, s in mapping.items(): lines[l+1] = '%s %s\n' % (lines[l+1].rstrip('\n'), s) return lines if __name__ == '__main__': main(sys.argv[1], sys.argv[2]) It's easy to use: first you define the mapping on top of the script, where you have a line_number: 'text to append' pairs. Then save the script as append.py and run it as python append.py src dst where src is the filename you want to process, dst is the filename to save. A: Try this: $ linenum=4 $ sed -e "${linenum}s/\$/text to add/" < input.txt > output.txt A: you can include this inside a loop like awk '{if(NR==<your line number>)print $0,<your additional text>;else print}' your_file >>temp_file rm your_file mv temp_file your_file NR stands for line number in awk.so we are checking for NR == lets say line 3. if NR is 3 the print $0,"your text" $0 is complete line which will be appended by "your text" if not line 3 the else{print}-this will print the complete line. Or a more easy form in sed : pearl[ncm_o11.2_int.@].525> cat file1 a b c d e f pearl[ncm_o11.2_int.@].526> sed '1s/$/vijay/g' file1 avijay b c d e f This sed command will append to the end of the line the desired text. '<line_number>s/search/replace' ' 1 s/ $ / vijay ' here is the awk solution: pearl[ncm_o11.2_int.@].534> awk '{if(NR==1)print $0,"vijay";else print}' file1 a vijay b c d e f
{ "language": "en", "url": "https://stackoverflow.com/questions/7578676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ruby prawn gem, table position using prawn gem i display table in the pdf file.. now i want to set position of the table, please guide me how to work on this.. i used the following code to genrate pdf report, pdftable = Prawn::Document.new pdftable.table([["Name","Login","Email"]], :column_widths => {0 => 80, 1 => 80, 2 => 80, 3 => 80}, :row_colors => ["d5d5d5"]) @users.each do|u| pdftable.table([["#{u.name}","#{u.login}","#{u.email}"]], :column_widths => {0 => 80, 1 => 80, 2 => 80, 3 => 80 }, :row_colors => ["ffffff"]) thanks A: You can use function indent() in combination with functions move_down and move_up, so for example setting table at position(50,20) (relative to your cursor position) will look like this: move_down 20 indent(50) do #this is x coordinate pdftable.table([["Name","Login","Email"]], :column_widths => {0 => 80, 1 => 80, 2 => 80, 3 => 80}, :row_colors => ["d5d5d5"]) @users.each do|u| pdftable.table([["#{u.name}","#{u.login}","#{u.email}"]], :column_widths => {0 => 80, 1 => 80, 2 => 80, 3 => 80 }, :row_colors => ["ffffff"]) end ` A: You probably need to create a bounding_box around the table. See the documentation for bounding boxes. Also: Do you realize you are creating a new table for the header and for each user? A: You need to include a dependency to prawn-layout (in addition to prawn) into your Gemfile: # Gemfile ... gem 'prawn' gem 'prawn-layout' ... then run a bundle install from the console, to let bundler download the new gem. After this, you must include, where you want to generate your PDF, in addition to the prawn requirement, also the prawn/layout requirement: # your_pdf_builder_lib.rb require 'prawn' require 'prawn/layout' Done this, the only thing you have to write to center your table is something like this: # your_pdf_builder_lib.rb require 'prawn' require 'prawn/layout' ... def build_pdf p = Prawn::Document.new(:page_size => "A4") ... data = [["header 1", "header 2"], [data_col1, data_col2], ...] # your content for table ... p.table data, :position => :center # :position => :center will do the trick. ... p.render end
{ "language": "en", "url": "https://stackoverflow.com/questions/7578678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why should I overload a C++ operator as a global function (STL does) and what are the caveats? Why would I want to overload a C++ operator() as global and not member function. For example, the == operator. Why is this done? for example in STL libraries. A: If I remember correctly, operator = must be a member function. Regarding operator ==, I figure you don't actually mean global but free function instead (STL does not define operators globally). There are a couple of things to consider, one is decoupling from the class itself: If your operator can be defined in terms of the public interface of your class, then you are better off implementing it that way to keep the access to the implementation internals to the bare minimum. The other fundamental advantage is the possibility to implemement an operator where your type comes as the second operand, consider equality between types T and U: bool operator ==( T const& t, U const& u ){ ... } bool operator ==( U const& t, T const& u ){ ... } If objects of type T and U can be equally compared, then it makes sense that both t == u and u == t are valid and both yield the same result. If you were defining this operator as a member function, then one would be within the implementation of T and the other within the implementation of U. Now consider U is a 3rd party type outside your control, or even better is a fundamental type such as int, now there is no other way for you to provide such operator but to provide the free function version of it. A: The usual rule is for operators which modify the left hand object to be members, and binary operators which return a new object to be free functions; the main motivation for the latter is because the compiler will not convert the left hand side to match a member; if your class supports any implicit conversions, then all of the usual binary operators should be free functions, so that the same rules of conversion apply for the left hand side and the right hand side, e.g.: class Complex { public: Complex(double r, double i = 0.0); bool operator==( Complex const& other ) const; }; Complex a; // ... if ( a == 1.0 ) // OK // ... if ( 1.0 == a ) // error. but: class Complex { public: Complex(double r, double i = 0.0); friend bool operator==( Complex const& lhs, Complex const& rhs ) const; }; Complex a; // ... if ( a == 1.0 ) // OK // ... if ( 1.0 == a ) // OK One elegant way of achieving this is to define the basic operations in terms of member functions—for things like + or -, these would be operator+= and operator-=; for comparison, you'd need to define an arbitrary conventions, a member isEqual, or compare (which would return <, == or > zero according to the results, then inherit from a template along the lines of: template <typename T> class ArithmeticOperators { friend T operator+( T const& lhs, T const& rhs ) { T result( lhs ); result += rhs; return result; } // And so on, for all of the binary operators. }; class Complex : public ArithmeticOperators<Complex> { public: // ... Complex& operator+=( Complex const& other ); // etc. }; Note that there is some argument for making the operator <op>= functions free functions as well: the fact that the free function will take a non-const reference as its first argument, and thus requires an lvalue (like the built-in operator <op>=). This doesn't seem to be the usual practice, however, probably because operator= must be a member, and it seems more natural to treat the operator <op>= in the same mannter. A: The rules for matching a member function against an argument are different from the rules for matching the first argument of a free function. I'm not certain exactly how they are different, but since they are different it's actually preferable to implement most binary operators as free functions instead of member functions in order that argument matching operates symmetrically for both arguments. There is an except for postfix ++, but that's because it isn't really a binary operator, and only plays one when you overload it in order to have a way of distinguishing between it and prefix ++.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to extract an XML document from a BLOB column in Oracle thats been compressed in Java I have a table in Oracle 11G (11.1) that has a BLOB column containing XML documents. The XML document has been written to the table using a java program and has been serialised and compressed using java.util.zip deflator. Is there a simple way to extract this document using SQL or PLSQL to reverse the process used to create the BLOB column to get back the original XML document ? I identified a piece of java from a web application that reads the column that looks like the code below but for support purposes, would like to be able to access the column data from the back end. private IntegrationStagingDataBean fromObjectToBean(StagedMessage message) throws ServerException { IntegrationStagingDataBean bean = new IntegrationStagingDataBean(); bean.setBusinessId(message.getBusinessId()); bean.setBusinessType(message.getBusinessType()); bean.setCreateTime(message.getCreateTime()); bean.setDeleted(message.hasBeenDeleted() ? "Y" : "N"); bean.setErrorMessage(message.getErrorMessage()); bean.setId(message.getId()); bean.setStoreId(message.getStoreId()); bean.setMessageDirection(message.getMessageDirection().getDbCode()); bean.setMessageFamily(message.getMessageFamily().getDbCode()); bean.setMessageType(message.getMessageType().getDbCode()); bean.setProcessed(message.hasBeenProcessed() ? "Y" : "N"); bean.setRetryCount(message.getRetryCount()); bean.setUpdateTime(message.getUpdateTime()); try { bean.setSerializedDeo(ObjectUtils.toByteArray(new CompressedObject(message.getDeo()))); } catch (IOException ioex) { throw new ServerException("Problem setting compressed serialized object", ioex); } return bean; } private StagedMessage fromBeanToObject(IntegrationStagingDataBean bean) throws ServerException { DataExchangeObject deo = null; Blob blob = (Blob) bean.getSerializedDeo(); try { CompressedObject compressedObject = (CompressedObject) new ObjectInputStream(blob.getBinaryStream()).readObject(); deo = (DataExchangeObject) compressedObject.recoverObject(); } catch (Exception e) { throw new ServerException("Couldn't uncompress/deserialize DEO from BLOB", e); } ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ and found the following additional functions spread across a handful of packages which indicate it is using the java function deflater from java.util.zip.*; public CompressedObject(Object object) throws IOException { dataToSend = null; if(object != null) dataToSend = ObjectUtils.toCompressedByteArray(object); } public static final byte[] toCompressedByteArray(Object o) throws IOException { return compressByteArray(toByteArray(o)); } public static final byte[] compressByteArray(byte input[]) { Deflater compressor = new Deflater(9); compressor.setInput(input); compressor.finish(); ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length); byte buf[] = new byte[1024]; int count; for(; !compressor.finished(); bos.write(buf, 0, count)) count = compressor.deflate(buf); try { bos.close(); } catch(IOException e) { } return bos.toByteArray(); } public static final byte[] decompressByteArray(byte arr[]) { Inflater decompressor = new Inflater(); decompressor.setInput(arr); ByteArrayOutputStream bos = new ByteArrayOutputStream(arr.length); byte buf[] = new byte[1024]; while(!decompressor.finished()) try { int count = decompressor.inflate(buf); bos.write(buf, 0, count); } catch(DataFormatException e) { } try { bos.close(); } catch(IOException e) { } return bos.toByteArray(); } Thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Median code explanation My professor wrote this median function and I don't understand it very well. Can someone please explain the part about i = len(list)/2 and median = avg() and the else statement? def avg_list(numbers): sum = 0 for num in numbers: sum += num avg = float(sum)/len(numbers) print avg def median(list): list.sort() if len(list)%2 == 0: #have to take avg of middle two i = len(list)/2 median = avg() else: #find the middle (remembering that lists start at 0) i = len(list)/2 median = list return median To add from an example I saw, for even list length: def median(s): i = len(s) if not i%2: return (s[(i/2)-1]+s[i/2])/2.0 return s[i/2] This works very well but I don't understand the last return s[i/2]? For odd list length: x = [1,2,5,2,3,763,234,23,1,234,21,3,2134,23,54] median = sorted(x)[len(x)/2] Since x has a list length of odd, wouldn't the [len(x)/2] be a floating number index? I'm not getting this all the way? Any explanation better than mine is much appreciated. A: We're missing some code here, but we can puzzle it out. The comments here are instructive. When we check: if len(list)%2 == 0: Then we're checking to see if the list is of even length. If a list has an even number of members, then there is no true "middle" element, and so: #have to take avg of middle two i = len(list)/2 median = avg() We assume that the avg() function is going to return the average of the two middle elements. Since you didn't include a definition of an avg function, it's possible that this is really supposed to be an avg_list function taking the middle two elements of the list. Now, if the list is of odd length, there is a middle element, and so: else: #find the middle (remembering that lists start at 0) i = len(list)/2 median = list Now this looks kinda wrong to me too, but my guess is that the intention is that this should read: median = list[i] That would be us returning the middle element of the list. Since the list has been sorted, that middle element is the true median of the list. Hope this helps! A: I'm sure it's trying to say, "If the list is of odd size, just take the central element; otherwise take the mean of the central two elements" - but I can't see that that's what the code is actually doing at all. In particular: * *It's calling an avg() function (not avg_list, note) but without any arguments *It's ignoring the value of i after computing it in the same way in both branches Are you sure that's the complete code which is meant to work? A: You can also decide to always return the average of the middle sub-array of the ordered list: For instance return the average of [4,5] out of [1,2,3,4,5,6,7,8], and that of [5] out of [1,2,3,4,5,6,7,8,9]. A python implementation would be: def median(a): ordered = sorted(a) length = len(a) return float((ordered[length/2] + ordered[-(length+1)/2]))/2 A: Why this is is very wrong, line by line: def median(list): # 1 list.sort() # 2 if len(list)%2 == 0: #have to take avg of middle two i = len(list)/2 # 3 median = avg() # 4 else: #find the middle (remembering that lists start at 0) i = len(list)/2 # 5 median = list # 6 return median #1: It's a bad idea to give your variables the same name as data types, namely list. #2: list.sort() will modify the list that is being passed. One would expect a getter like median() not to do that. #4 It calls a function avg() with no arguments, which is completely meaningless, even if such a function was defined. #3 and #5 are calculated the same way regardless of the if branch taken. Regardless, i is never used. #6 It sets median to the original list, which makes zero sense. Here's how I would rewrite this (while maintaining clarity): def median(alist): srtd = sorted(alist) # returns a sorted copy mid = len(alist)/2 # remember that integer division truncates if len(alist) % 2 == 0: # take the avg of middle two return (srtd[mid-1] + srtd[mid]) / 2.0 else: return srtd[mid] Also, the avg_list() function (which is not used nor could be used in median()) could be rewritten as: def avg_list(numbers): return float(sum(numbers))/len(numbers) sum() is a function that returns the sum of all elements in an iterable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: write a dictionary to plist on iphone I want to add a new dictionary to the existing plist file, how can I do that, I can read from the file, but with the same approach, writing doesn't work. My plist structure looks like this: Root Array |__item0 Dictionary |__item1 Dictionary |__item2 Dictionary The code of writing to the file looks like this: NSFileManager *fileManager = [NSFileManager defaultManager]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentDirectory = [paths objectAtIndex:0]; NSString *plistPath = [documentDirectory stringByAppendingPathComponent:@"list.plist"]; if (![fileManager fileExistsAtPath:plistPath]) { plistPath = [[NSBundle mainBundle] pathForResource:@"list" ofType:@"plist"]; } NSMutableArray *dataRoot = [NSMutableArray arrayWithContentsOfFile:plistPath]; NSMutableDictionary *item = [[NSMutableDictionary alloc] init]; [item setObject:@"value1" forKey:@"1"]; [item setObject:@"value2" forKey:@"2"]; [item setObject:@"value3" forKey:@"3"]; [dataRoot addObject:item]; [dataRoot writeToFile:plistPath atomically:YES]; [item release]; Can anyone help me with this, thanks! I have updated my code, but it still doesn't work...And the problem is list.plist file doesn't get copied to ~/Documents directory. A: I think code is not wrong. Have you check plistPath, dataRoot, and item? They have correct value? A: You can only save primitive types by default. try out this link. http://deadpanic.com/howtosave He explains how to save any object to disk by using NSCoding protocol. If you are working only with primitives then I apologize for wasting your time. But this is the path I took to write my custom stuff to disk. And I thought it was just an array issue. Edit: I just noticed... It looks like you are trying to write to an array in the Main Bundle. These files are read only. You need to save a copy of the file in the Documents directory. try this out to find the documents directory NSFileManager *fileManager = [NSFileManager defaultManager]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; // Change your plistPath to be this plistPath = [documentsDirectory stringByAppendingPathComponent:@"list.plist"]; [dataRoot writeToFile:plistPath atomically:YES]; put your plist in this folder and you can write to it. A: NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"list.plist"]; if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { bingoArray = [[NSMutableArray alloc] initWithContentsOfFile:filePath]; } [bingoArray writeToFile:filePath atomically:YES]; A: You are trying to write the main bundle which is no-no on iOS. Please read the A Few Important Application Directories. But your coding boils down to the following: * *Check if plist is not in Application_Home/Documents/ *Copied original plist from main bundle is the answer to step 1 is false. *Open the plist in the Documents directory *Update NSMutableArray *Write to file the plist
{ "language": "en", "url": "https://stackoverflow.com/questions/7578690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fatal error: Call to undefined method Facebook::require_frame() in /home/wubb/public_html/facebook/fbml.php on line 15 I am trying to integrate friend invite for facebook in my website. I am using php. I included the code: <?PHP // Get these from http://developers.facebook.com $api_key = 'xxx'; $secret = 'xxx'; // Names and links $app_name = "Application name"; $app_url = "app-url"; // Assumes application is at http://apps.facebook.com/app-url/ $invite_href = "invite.php"; // Rename this as needed require_once 'facebook.php'; $facebook = new Facebook($api_key, $secret); $facebook->require_frame(); $user = $facebook->require_login(); if(isset($_POST["ids"])) { echo "<center>Thank you for inviting ".sizeof($_POST["ids"])." of your friends on <b><a href=\"http://apps.facebook.com/".$app_url."/\">".$app_name."</a></b>.<br><br>\n"; echo "<h2><a href=\"http://apps.facebook.com/".$app_url."/\">Click here to return to ".$app_name."</a>.</h2></center>"; } else { // Retrieve array of friends who've already authorized the app. $fql = 'SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1='.$user.') AND is_app_user = 1'; $_friends = $facebook->api_client->fql_query($fql); // Extract the user ID's returned in the FQL request into a new array. $friends = array(); if (is_array($_friends) && count($_friends)) { foreach ($_friends as $friend) { $friends[] = $friend['uid']; } } // Convert the array of friends into a comma-delimeted string. $friends = implode(',', $friends); // Prepare the invitation text that all invited users will receive. $content = "<fb:name uid=\"".$user."\" firstnameonly=\"true\" shownetwork=\"false\"/> has started using <a href=\"http://apps.facebook.com/".$app_url."/\">".$app_name."</a> and thought it's so cool even you should try it out!\n". "<fb:req-choice url=\"".$facebook->get_add_url()."\" label=\"Put ".$app_name." on your profile\"/>"; ?> <fb:request-form action="<? echo $invite_href; ?>" method="post" type="<? echo $app_name; ?>" content="<? echo htmlentities($content,ENT_COMPAT,'UTF-8'); ?>"> <fb:multi-friend-selector actiontext="Here are your friends who don't have <? echo $app_name; ?> yet. Invite whoever you want -it's free!" exclude_ids="<? echo $friends; ?>" /> </fb:request-form> <?PHP } ?> [[Image:multi-friend-selector.png]] Here I included facebook.php file I downloaded from the github .I tried many versions of phpSDK but still the following error is coming Fatal error: Call to undefined method Facebook::require_frame() Can anybody suggest which version conatain this function or how to solve this issue. I have lost a lot of time trying to solve this. So respond as soon as possible. A: Trikode, Make sure you are using the most recent version of the php sdk: https://github.com/facebook/facebook-php-sdk. There is a really easy to follow guide here to help you get started: https://developers.facebook.com/docs/reference/php/
{ "language": "en", "url": "https://stackoverflow.com/questions/7578699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: .load() jquery with Servlet Is it possible to load the contents in a div through a servlet via .load() jquery ? I tried this $('#getDetails').load('getDetails'); But its not working !! What can be an alternative to this ? Thanks A: Did you read the documentation? If there's one parameter, it must be a URL. getDetails alone apparently isn't. A: Your servlet has to override method doGet, like this: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // implementation } In the web.xml, you put servlet mapping, like this: <servlet> <servlet-name>MyServlet</servlet-name> <servlet-class>com.example.myservlet.MyServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServlet</servlet-name> <url-pattern>/servlet</url-pattern> </servlet-mapping> </servlet> Then, you call servlet from JQuery context, like this: function someFunction() { $("#yourDivId").load("./servlet"); } Cheers!! A: got it. I changed the method of servlet to do get, and passed a parameter with servlet name. $('#getDetails').load('getDetails?process=u'); Its working now. Thanks ..
{ "language": "en", "url": "https://stackoverflow.com/questions/7578703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django ckeditor with wordcount Does anyone know how to integrate this wordcount plugin with the existing django-ckeditor apps? Either https://github.com/dwaiter/django-ckeditor or https://github.com/shaunsephton/django-ckeditor/. Specifically, I'm stuck at Step 4 For your CKEditor instance, use the following HTML markup (content can be any element name you wish, so long as the hidden field has its element name in the format elementWordCount) <label for="content">Content</label> <textarea class="ckeditor" name="content"></textarea> <input name="contentWordCount" type="hidden" value="250" /> Where do I insert that Input element? I'm using the widget btw. Alternative solutions to having a wordcount plugin are welcome. A: I'm the author of https://github.com/shaunsephton/django-ckeditor/. I've just updated the repo to support widget template customization. You should now be able to integrate the wordcount plugin by specifying it as part of the CKEDITOR_CONFIGS setting: CKEDITOR_CONFIGS = { 'default': { 'extraPlugins': 'wordcount', } } and then overriding the ckeditor/widget.html template to look like this: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script> <input name="contentWordCount" type="hidden" value="250" /> <textarea{{ final_attrs|safe }}>{{ value }}</textarea> <script type="text/javascript"> CKEDITOR.replace("{{ id }}", {{ config|safe }}); </script> I've loaded jQuery here through Google APIs just as an example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is binary search optimal in worst case? Is binary search optimal in worst case? My instructor has said so, but I could not find a book that backs it up. We start with an ordered array, and in worst case(worst case for that algorithm), any algorithm will always take more pairwise comparisons than binary search. Many people said that the question was unclear. Sorry! So the input is any general sorted array. I am looking for a proof which says that any search algorithm will take at least log2(N) comparisons in worst case(worst case for the algo in consideration). A: Worst case for which algorithm? There's not one universal "worst case." If your question is... "Is there a case where binary search takes more comparisons than another algorithm?" Then, yes, of course. A simple linear search takes less time if the element happens to be the first one in the list. "Is there even an algorithm with a better worst-case running time than binary search?" Yes, in cases where you know more about the data. For example, a radix tree or trie is at worst constant-time with regard to the number of entries (but linear in length of the key). "Is there a general search algorithm with a better worst-case running time than binary search?" If you can only assume you have a comparison function on keys, no, the best worst-case is O(log n). But there are algorithms that are faster, just not in a big-O sense. ... so I suppose you really would have to define the question first! A: Yes, binary search is optimal. This is easily seen by appealing to information theory. It takes log N bits merely to identify a unique element out of N elements. But each comparison only gives you one bit of information. Therefore, you must perform log N comparisons to identify a unique element. More verbosely... Consider a hypothetical algorithm X that outperforms binary search in the worst case. For a particular element of the array, run the algorithm and record the questions it asks; i.e., the sequence of comparisons it performs. Or rather, record the answers to those questions (like "true, false, false, true"). Convert that sequence into a binary string (1,0,0,1). Call this binary string the "signature of the element with respect to algorithm X". Do this for each element of the array, assigning a "signature" to each element. Now here is the key. If two elements have the same signature, then algorithm X cannot tell them apart! All the algorithm knows about the array are the answers it gets from the questions it asks; i.e., the comparisons it performs. And if the algorithm cannot tell two elements apart, then it cannot be correct. (Put another way, if two elements have the same signature, meaning they result in the same sequence of comparisons by the algorithm, which one did the algorithm return? Contradiction.) Finally, prove that if every signature has fewer than log N bits, then there must exist two elements with the same signature (pigeonhole principle). Done. [update] One quick additional comment. The above assumes that the algorithm does not know anything about the array except what it learns from performing comparisons. Of course, in real life, sometimes you do know something about the array a priori. As a toy example, if I know that the array has (say) 10 elements all between 1 and 100, and that they are distinct, and that the numbers 92 through 100 are all present in the array... Then clearly I do not need to perform four comparisons even in the worst case. More realistically, if I know that the elements are uniformly distributed (or roughly uniformly distributed) between their min and their max, again I can do better than binary search. But in the general case, binary search is still optimal. A: Binary search has a worst case complexity of O(log(N)) comparisons - which is optimal for a comparison based search of a sorted array. In some cases it might make sense to do something other than a purely comparison based search - in this case you might be able to beat the O(log(N)) barrier - i.e. check out interpolation search. A: It depends on the nature of the data. For example the English language and a dictionary. You could write an algorithm to achieve better than a binary search by making use of the fact that certain letters occur within the English language with different frequencies. But in general a binary search is a safe bet. A: I think the question is a little unclear, but still here are my thoughts. Worst case of Binary search would be when the element you are searching for is found after all log n comparisons. But the same data can be best case for linear search. It depends on the data arrangement and what you are searching for but the worst case for Binary search would end up to be log n. Now, this cannot be compared with same data and search for linear search since its worst case would be different. The worst case for Linear search could be finding an element which happens to be at the end of the array. For example: array A = 1, 2, 3, 4, 5, 6 and Binary Search on A for 1 would be the worst case. Whereas for the same array, linear search for 6 would be the worst case, not search for 1.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: sqlFile refactoring in liquibase can't find file on the classpath The documentation for the <sqlFile> custom refactoring tag says that the classpath will be searched for the file. However I cannot get it to find my file, despite it being in the classpath. The changeset element is: <changeSet author="rebecca" id="9.1 - LoanIQ GoLive"> <comment>No rollback script exists</comment> <sqlFile path="v9.1-loaniqgolive.sql"/> </changeSet> The ant task is: <updateDatabase changeLogFile="@{changelog}" driver="com.microsoft.sqlserver.jdbc.SQLServerDriver" url="jdbc:sqlserver://${database.host}:${database.port};databaseName=${database.name}" username="${database.user}" password="${database.password}" promptOnNonLocalDatabase="false" dropFirst="false" classpathref="liquibase.path"/> The build reports that the liquibase path is: [echo] The liquibase path = D:\Program Files\Jenkins\jobs\Deploy GMM\workspace\app\build\database;D:\Program Files\Jenkins\jobs\Deploy GMM\workspace\app\build\tools\liquibase\liquibase.jar;D:\Program Files\Jenkins\jobs\Deploy GMM\workspace\app\build\lib\sqljdbc.jar I have confirmed that v9.1-loaniqgolive.sql is definitely in the path (1st element). Yet I get this error: D:\Program Files\Jenkins\jobs\Deploy GMM\workspace\app\build\ant\functions\db.xml:56: liquibase.exception.ChangeLogParseException: Invalid Migration File: <sqlfile path=v9.1-loaniqgolive.sql> -Unable to read file at liquibase.parser.core.xml.XMLChangeLogSAXParser.parse(XMLChangeLogSAXParser.java:132) My config looks OK, but it doesn't work. How can I solve this or debug further? A: One quick suggestion I have is to run Ant with -verbose and -debug command line parameters. This puts out a lot of logging but generally helps get you closer to the source of the problem. I will try to create an equivalent Ant task against one of my dbs and respond with any updates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Project Euler Problem 10 - Efficient Algorithm I attempted Project Euler's problem 10 using the very easy algorithm and the running time looks like hours. So I googled for an efficient algorithm and found this by Shlomif Fish. The code is reproduced below: int main(int argc, char * argv[]) { int p, i; int mark_limit; long long sum = 0; memset(bitmask, '\0', sizeof(bitmask)); mark_limit = (int)sqrt(limit); for (p=2 ; p <= mark_limit ; p++) { if (! ( bitmask[p>>3]&(1 << (p&(8-1))) ) ) { /* It is a prime. */ sum += p; for (i=p*p;i<=limit;i+=p) { bitmask[i>>3] |= (1 << (i&(8-1))); } } } for (; p <= limit; p++) { if (! ( bitmask[p>>3]&(1 << (p&(8-1))) ) ) { sum += p; } } I have problems understanding the code. Specifically, how does this bit shifting code able to determine whether a number is prime or not. if (! ( bitmask[p>>3]&(1 << (p&(8-1))) ) ) { /* It is a prime. */ sum += p; for (i=p*p;i<=limit;i+=p) { bitmask[i>>3] |= (1 << (i&(8-1))); } } Can someone please explain this code block to me, especially this part ( bitmask[p>>3]&(1 << (p&(8-1)? Thank you very much. A: The code is a modified Sieve of Eratosthenes. He is packing one number into one bit: 0 = prime, 1 = composite. The bit shifting is to get to the correct bit in the byte array. bitmask[p>>3] is equivalent to bitmask[p / 8] which selects the correct byte in the bitmask[] array. (p&(8-1)) equals p & 7, which selects the lower 3 bits of p. This is equivalent to p % 8 Overall we are selecting bit (p % 8) of byte bitmask[p / 8]. That is we are selecting the bit in the bitmask[] array which represents the number p. The 1 << (p % 8) sets up a 1 bit correctly located in a byte. This is then AND'ed with the bitmask[p / 8] byte to see if that particular bit is set or not, thus checking whether p is a prime number. The overall statement equates to if (isPrime(p)), using the already completed part of the sieve to help extend the sieve. A: The bitmask is acting as an array of bits. Since you can't address bits individually, you first have to access the byte and then modify a bit within it. Shifting right by 3 is the same as dividing by 8, which puts you on the right byte. The one is then shifted into place by the remainder. x>>3 is equivalent to x/8 x&(8-1) is equivalent to x%8 But on some older systems, the bit manipulations may have been faster. The line sets the ith bit, where i has been determined not to be prime because it is a multiple of another prime number number: bitmask[i>>3] |= (1 << (i&(8-1))); This line checks that the pth bit is not set, which means it is prime, since if it wasn't prime it would have been set by the line above. if (! ( bitmask[p>>3]&(1 << (p&(8-1))) ) )
{ "language": "en", "url": "https://stackoverflow.com/questions/7578713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to create a scrollable div with padding on top and bottom without extra markup on the inside? I have created a fiddle to illustrate my question. Basically I'd like to have a container with scrollable content that has a padding on the top and the bottom. [Edit:] This padding should be visible while scrolling, so that at any given time you have the same distance from the edge to the content. <div class="container"> <!-- pure content, no extra wrapper --> <h1>This is how I'd like it</h1> <p> ... </p> </div> I can only achieve the effect by adding an extra wrapper to the inside of the container. Does anyone know of another workaround that doesn't introduce another element? <div class="container"> <!-- extra wrapper, me unhappy --> <div class="inner"> <h1>This is how I can do it</h1> <p> ... </p> </div> </div> A: The simplest solution I could think of is adding a thick border around the box of same background color as that of the box, and reducing width/height accordingly. [Thickness of border = required padding on any side] & [border color = background color of the box ] A: Try using the following CSS. .container { padding-top:10px; padding-bottom:10px; height: 80px; /* Set your desired value here */ width: 200px; /* Set your desired value here */ overflow-x: scroll; /* for horizontal scroll-bar */ overflow-y: scroll; /* for vertical scroll-bar */ white-space: nowrap; /* needed only if you want to disable text-wrapping. */ }
{ "language": "en", "url": "https://stackoverflow.com/questions/7578724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: progress bar not showing the step by step progress in iphone Hi all im using progress bar for indicating the status of xml parsing in my app.but it is not showing the step by step updation,instead the progress bar is loading after the entire xml parsing is over,till that time it is stuck and not showing any progress.how to solve this issue.can anyone help me please. I use the below code IBOutlet UIProgressView * threadProgressView; threadProgressView.progress = 0.0; [self performSelectorOnMainThread:@selector(makeMyProgressBarMoving) withObject:nil waitUntilDone:NO]; - (void)makeMyProgressBarMoving { float actual = [threadProgressView progress]; if (actual < 1) { threadProgressView.progress = actual + ((float)1/(float)10); [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(makeMyProgressBarMoving) userInfo:nil repeats:NO]; } else{ /* something else */ } } A: * *Create a timer on the main thread for every 1/10th of a second. Have it hit your "makeMyProgressBarMoving" function. myTimer = [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(makeMyProgressBarMoving) userInfo:nil repeats:YES]; Then edit your function to look like this: - (void)makeMyProgressBarMoving { float actual = [threadProgressView progress]; if (actual < 1) { threadProgressView.progress = actual + ((float)1/(float)10); return; } //if you got here that means the progress view is greater than 1 so now you can kill your timer that you had running every 1/10th of a second. [myTimer invalidate]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7578732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Adding a timestamp property to a relation in Symfony2 I am trying to model a simple comment system with 2 entities - User and Post. The User class has the regular properties, and the Post class looks like this: class Post { /** * @var integer $id * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * User who posted activity * * @var User * @ORM\ManyToOne(targetEntity="Acme\AppBundle\Entity\User") */ protected $user; /** * @var string $text * * @ORM\Column(name="text", type="string", length=255) */ private $text; /** * @var datetime $timestamp * * @ORM\Column(name="timestamp", type="datetime") */ private $timestamp; } I need to make a simple association - Users can favourite posts. The logical thing to do would be to add ManyToMany association in User class to Post like so @ORM\ManyToMany(targetEntity="Post") Which would then create a mapping table with user_id and post_id as primary keys. Now my problem is that I need to add a timestamp property to track when the user liked a post. One possibility is to create a new Entity "FavouritePost", map it to both User and Post class using ManyToOne association, and add a timestamp property to it. 1) Is this the right/only way to do it in Symfony2? 2) If I want to select the most recent 15 posts, and check if the currently logged in user has liked the posts, how can I write a query for that? Any help appreciated, as I am drawing a blank on how to do it via Symfony A: 1) Yes you may create a jointure table, and so its FavouritePost entity. 2) You should use a Repository to create all special queries : @ORM\Entity(repositoryClass="Acme\AppBundle\Repository\FavouritePostRepository") Then it's easy Doctrine queries, like you will make much more.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Having issues accessing a method just a quick question in relation to accessing a method inside another class. I know it sounds simple but nowhere I look can answer it for me.. so here it goes. This is in one class.. (only leaving in the relevant bits because most of the other stuff is just formatting and passing around values.) public class ContactManager extends JFrame{ public void getData()throws FileNotFoundException{ ... ... private class thehandler implements ActionListener { public void actionPerformed(ActionEvent event) { if (event.getSource() == viewButton && selectedIndex != -1){ ViewContact view = new ViewContact(); view.pack(); view.setVisible(true); public class ViewContact extends JFrame { ... ... private class viewhandler implements ActionListener { public void actionPerformed(ActionEvent event){ if (event.getSource() == updateButton){ getData(); //this method i want to use thats in the contact manager window is what im having issues with. } I know the syntax is wrong for accessing a method in another class I just wanted to show what i am trying to do. I cannot create another instance of the contact manager class because I am already using it.. :S at least i think that's the issue. I hope I have left in enough relevant information and thank you in advance for assistance with this. A: The short answer to your question is that you can pass an appropriate instance of ContactManager to the ViewManager and call getData() as required: class ViewManager extends JFrame { private ContactManager cm; public ViewManager(ContactManager cm) { this.cm = cm; } private class Handler implements ActionListener { public void actionPerformed(ActionEvent e) { cm.getData(); } } } The longer answer is that it might be better to separate your business logic from your view logic and put the getData method into a business-layer class: class DataSource { public Data getData(); } class ContactManager extends JFrame { private DataSource dataSource; public ContactManager(DataSource dataSource) { ... } } class ViewContact extends JFrame { private DataSource dataSource; public ViewContact(DataSource dataSource) { ... } } This decouples the classes that are responsible for fetching/managing data from the classes that are responsible for displaying it. It means you can change the view without affecting the way data is stored, or you can change the way data is stored without affecting the view. A: Why not create a constructor for ViewContact() that accepts a reference to your ContactManager instance? For example: ViewContact myContact = ViewContact (this); A: You can call data()! You can create another class-instance of ContactManager too. You can also create instances of ViewContact using: ContactManager m = new ContactManager(); JFrame contact = m.new ViewContact(); You even can instance thehandler using this: ContactManager manager = new ContactManager(); Object b = null; for (Class<?> clazz : ContactManager.class.getDeclaredClasses()) { if (clazz.getSimpleName().equals("thehandler")){ for (Constructor<?> constructor : clazz.getDeclaredConstructors()) { constructor.setAccessible(true); b=constructor.newInstance(manager); break; } break; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7578744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Change image on UILongPressGestureRecognizer? I am working on SMS application for Iphone .. And now i want to change image of my chat bubble on longpress ( like while i copy the contant ).. i have this code .. if (longPressRecognizer.state == UIGestureRecognizerStateBegan) { [self becomeFirstResponder]; //NSIndexPath *pressedIndexPath = [tblOutgoingMessagesRecords indexPathForRowAtPoint:[longPressRecognizer locationInView:tblOutgoingMessagesRecords]]; NSIndexPath *pressedIndexPath = [tblOutgoingMessagesRecords indexPathForCell:(UITableViewCell *)longPressRecognizer.view]; if (pressedIndexPath && (pressedIndexPath.row != NSNotFound) && (pressedIndexPath.section != NSNotFound)) { [self becomeFirstResponder]; NSLog(@" Presssed on Copy "); I just want to change my Chat bubble color to blue while i lonpress it for copy .. As like in iphone default has done i want to do same ... Can any one help me ... A: It seems you have to check if the state is UIGestureRecognizerStateRecognized to change the Chat bubble's color, if (longPressRecognizer.state == UIGestureRecognizerStateRecognized) { // Change Chat bubble's color to blue } A: check color to red when long press gesture begin condition if (longPressRecognizer.state == UIGestureRecognizerStateBegan) { [self becomeFirstResponder]; // change image from here //NSIndexPath *pressedIndexPath = [tblOutgoingMessagesRecords indexPathForRowAtPoint:[longPressRecognizer locationInView:tblOutgoingMessagesRecords]]; NSIndexPath *pressedIndexPath = [tblOutgoingMessagesRecords indexPathForCell:(UITableViewCell *)longPressRecognizer.view]; if (pressedIndexPath && (pressedIndexPath.row != NSNotFound) && (pressedIndexPath.section != NSNotFound)) { [self becomeFirstResponder]; NSLog(@" Presssed on Copy "); } } else if (longPressRecognizer.state == UIGestureRecognizerStateChanged) { //load original image here... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7578746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: vcov.polr is giving negative diagonal elements (mwe included) I don't know too much about ordered logits so perhaps I'm doing something silly, but the following seems straightforward and I don't know why vcov.polr gives me negative diagonals. I tried to follow the code in vcov.polr but got lost so I don't know what is wrong. Thanks for your help! temp_fc <- structure(list(the_index = c(4, 3, 3, 4, 4, 1, 3, 2, 3, 3, 3, 4, 4, 4, 1, 4, 4, 1, 4, 3, 4, 3, 3, 1, 4, 2, 4, 4, 4, 4, 3, 4, 1, 4, 4, 3, 4, 4, 2, 4, 1, 4, 4, 2, 3, 1, 4, 2, 1, 1, 4, 1, 4, 4, 4, 4, 1, 4, 3, 1, 4, 3, 4, 1, 4, 2, 3, 1, 4, 4, 1, 3, 2, 3, 2, 3, 3, 4, 1, 1, 4, 4, 4, 4, 1, 4, 4, 2, 4, 4, 4, 1, 1, 4, 3, 2, 4, 4, 1, 1), age = c(39L, 40L, 23L, 33L, 24L, 22L, 15L, 43L, 59L, 58L, 20L, 39L, 33L, 21L, 34L, 44L, 27L, 53L, 60L, 34L, 17L, 20L, 19L, 21L, 57L, 56L, 36L, 30L, 16L, 17L, 16L, 71L, 49L, 42L, 72L, 36L, 18L, 19L, 62L, 20L, 55L, 79L, 69L, 46L, 28L, 50L, 40L, 21L, 57L, 31L, 38L, 60L, 56L, 59L, 21L, 26L, 53L, 49L, 51L, 59L, 32L, 56L, 25L, 46L, 42L, 70L, 65L, 50L, 42L, 53L, 29L, 63L, 34L, 29L, 65L, 31L, 70L, 52L, 76L, 37L, 24L, 28L, 45L, 47L, 48L, 55L, 65L, 28L, 28L, 31L, 24L, 41L, 43L, 34L, 69L, 65L, 48L, 24L, 32L, 18L)), .Names = c("the_index", "age"), row.names = c("1006", "1040", "1085", "1115", "1130", "1144", "1162", "1164", "1176", "1178", "1181", "1192", "1223", "1258", "1259", "1307", "1311", "1330", "1338", "1368", "1401", "1411", "1443", "1444", "1515", "1538", "1600", "1628", "1632", "1683", "1692", "1701", "1710", "1784", "1790", "1793", "1799", "1873", "1897", "1904", "1908", "1982", "1988", "2015", "2029", "2052", "2065", "2077", "2088", "2095", "2163", "10345", "10355", "10372", "10388", "10397", "10414", "10415", "10417", "10421", "10428", "10430", "10456", "10480", "10490", "10492", "10509", "10587", "10600", "10607", "10609", "10617", "10625", "10626", "10630", "10640", "10674", "10684", "10686", "10687", "10700", "10703", "10713", "10730", "10740", "10747", "10750", "10762", "10792", "10794", "10803", "10820", "10824", "10830", "10833", "10835", "10857", "10888", "10917", "10933"), class = "data.frame") library(MASS) model_temp <-factor(the_index) ~ age + I(age^2) the_OL <- polr(model_temp,temp_fc,method="logistic", Hess=TRUE) diag(vcov(the_OL)) #this gives negative values #so of course the following will have an error: summary(the_OL) A: I think this is due to your use of non-orthogonal polynomials in your model formulae; this appears to be causing the computational issues. With your code I get: > the_OL2 <- polr(model_temp,temp_fc,method="logistic", Hess=TRUE) > AIC(the_OL2) [1] 254.6934 If I refit using orthogonal polynomials via poly(), I seem to get the same fit but without the numerical issues of negative variances: > the_OL <- polr(factor(the_index) ~ poly(age, 2), temp_fc, method="logistic", + Hess=TRUE) > AIC(the_OL) [1] 254.6934 > diag(vcov(the_OL)) poly(age, 2)1 poly(age, 2)2 1|2 2|3 3.38608675 3.65981581 0.05958267 0.04704916 3|4 0.04103139 The residual deviances reported for the two models are the same and the fitted values from the two models are almost the same (near as matters).
{ "language": "en", "url": "https://stackoverflow.com/questions/7578752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Thread Executing the Same code block - passing parameters from a dataset c# Let me preface my question by stating that I am a casual developer, so I don't really know what I am doing past the basics. This is developed in c# and .net 3.5. The core of what my current application is doing is to connect to remote servers, execute a WMI call, retrieve some data and then place this data into a database. It is a simple healthcheck application. The basic code runs fine, but I ran into an issue where if a few servers were offline, it would take 1 minute to timeout (which is realistic because of network bandwidth etc). I had an execution of the application run for 45 minutes (because 40 servers were offline) which is not efficient, since the code executed for 45 minutes and 40 minutes wait time. After some research I think that using threads would be the best way to get around it, if I spawned a thread for each of the servers as it was processing. Here is my thread code: for (int x = 0; x < mydataSet.Tables[0].Rows.Count; x++) { Thread ts0 = new Thread(() => executeSomeSteps(mydataSet.Tables[0].Rows[x]["IPAddress"].ToString(), mydataSet.Tables[0].Rows[x]["ID"].ToString(), connString, filepath)); ts0.Start(); } The dataset contains an ID reference and an IP Address. The execute some steps function looks like this: static void executeSomeSteps(string IPAddress, string ID, string connstring, string filepath) { string executeStuff; executeStuff = funclib.ExecuteSteps(IPAddress, ID, connstring, filepath); executeStuff = null; } And execute some steps inserts data into a database based on returned wmi results. This process works fine as mentioned earlier but the problem is that some of the threads in the above for loop end up with the same data, and it executes more than once per server. There are often up to 5 records for a single server once the process completes. From the research I have done, I believe it might be an issue with more than one thread reading the same x value from the dataset. So now onto my questions: Assume there are 10 records in the dataset: Why are there more than 10 executions happening? Will I still gain the performance if I lock the dataset value? Can someone point me into the right direction regarding how to deal with variable data being passed to a static function by multiple threads? A: What Davide refers to is that at the time you thread is executed the captured values from Rows[x] may be different (are even likely to be different) than when the delegate was created. This is because you the for loops goes on while the threads start running. This is a very common gotcha. It may even happen without servers timing out. The solution to this "modified closure" problem is to use new variables for each thread: for (int x = 0; x < mydataSet.Tables[0].Rows.Count; x++) { string ip = mydataSet.Tables[0].Rows[x]["IPAddress"].ToString(); string id = mydataSet.Tables[0].Rows[x]["ID"].ToString(); Thread ts0 = new Thread(() => executeSomeSteps(ip, id, connString, filepath)); ts0.Start(); } You may even encounter a System.ArgumentOutOfRangeException because when the for loop has finished, the last x++ may have executed, making x 1 higher than the row indexes. Any thread reaching its Rows[x] part will then throw the exception. Edit This issue kept bugging me. I think what you describe in your comment (it looked like extra records were being generated by one iteration) is exactly what the modified closure does. A few threads happen to start roughly at the same time, all taking the value of x at that moment. You must also have found that servers were skipped in one time lap, I cannot image that not happening.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# Object construction outside the constructor When it comes to designing classes and "communication" between them, I always try to design them in such way that all object construction and composing take place in object constructor. I don't like the idea of object construction and composition taking place from outside, like other objects setting properties and calling methods on my object to initialize it. This especially gets ugly when multiple object try to do thisto your object and you never know in what order your props\methods will be executed. Unforunatly I stumbl on such situations quite often, especially now with the growing popularity of dependecy injection frameworks, lots of libraries and frameworks rely on some kind of external object initialization, and quite often require not only constructor injection on our object but property injection too. My question are: * *Is it ok to have objects that relly on some method, or property to be called on them after which they can consider them initialzied? *Is ther some kind of pattern for situations when your object acting is receiver, and must support multiple interfaces that call it, and the order of these calls does matter? (something better than setting flags, like ThisWasDone, ThatWasCalled) A: Is it ok to have objects that relly on some method, or property to be called on them after which they can consider them initialzied? No. Init methods are a pain since there is no guarantee that they will get called. A simple solution is to switch to interfaces and use factory or builder pattern to compose the implementation. @Mark Seemann has written a article about it: http://blog.ploeh.dk/2011/05/24/DesignSmellTemporalCoupling.aspx Is there some kind of pattern for situations when your object acting is receiver, and must support multiple interfaces that call it, and the order of these calls does matter? (something better than setting flags, like ThisWasDone, ThatWasCalled) Builder pattern. A: I think it is OK, but there are implications. If this is an object to be used by others, you need to ensure that an exception is thrown any time a method or property is set or accessed and the initialization should have been called but isn't. Obviously it is much more convenient and intuitive if you can take care of this in the constructor, then you don't have to implement these checks. A: I don't see anything wrong in this. It may be not so convinient, but you can not ALWAYS use initialization in ctor, like you can not alwats drive under green light. These are dicisions that you made based on your app requirements. * *It's ok. Immagine if your object, for example, need to read data from TCP stream or a file that ciuld be not present or corrupted. Raise an exception from ctor is baaad. *It's ok. If you think, for example, about some your DSL language compiler, it can looks like: A) find all global variables and check if there mem allocation sum sutisfies your device requierements B) parse for errors C) check for self cycling And so on... Hoe this helps. A: Answering (1) Why not? An engine needs the driver because this must enter the key for the car, and later power-on. Will a car do things like detecting current speed if engine is stopeed? Or Will the car show remaining oil without powering-on it? Some programming goals won't be able to have their actors initialized during its object construction, and this isn't because it's a non-proper way of doing things but because it's the natural, regular and/or semantically-wise way of representing its whole behavior. Answering (2) A decent class usage documentation will be your best friend. Like answer to (1), there're some things in this world that should be done in order to get them done rightly, and it's not a problem but a requirement. Checking objects' state using flags isn't a problem too, it's a good way of adding reliability to your object models, because its own behaviors and consumers of them will be aware about if things got done as expected or not. A: First of all, Factory Method. public class MyClass { private MyClass() { } public Create() { return new MyClass(); } } Second of all, why do you not want another class creating an object for you? (Factory) public class MyThingFactory { IThing CreateThing(Speed speed) { if(speed == Speed.Fast) { return new FastThing(); } return new SlowThing(); } } Third, why do multiple classes have side effects on new instances of your class? Don't you have declarative control over what other classes have access to your object?
{ "language": "en", "url": "https://stackoverflow.com/questions/7578761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: OCaml: Does storing some values to be used later introduce "side effects"? For a homework assignment, we've been instructed to complete a task without introducing any "side-effects". I've looked up "side-effects" on Wikipedia, and though I get that in theory it means "modifies a state or has an observable interaction with calling functions", I'm having trouble figuring out specifics. For example, would creating a value that holds a non-compile time result be introducing side effects? Say I had (might not be syntactically perfect): val myList = (someFunction x y);; if List.exists ((=) 7) myList then true else false;; Would this introduce side-effects? I guess maybe I'm confused on what "modifies a state" means in the definition of side-effects. A: No; a side-effect refers to e.g. mutating a ref cell with the assignment operator :=, or other things where the value referred to by a name changes over time. In this case, myList is an immutable value that never changes during the program, thus it is effect-free. See also http://en.wikipedia.org/wiki/Referential_transparency_(computer_science) A: A good way to think about it is "have I changed anything which any later code (including running this same function again later) could ever possibly see other than the value I'm returning?" If so, that's a side effect. If not, then you can know that there isn't one. So, something like: let inc_nosf v = v+1 has no side effects because it just returns a new value which is one more than an integer v. So if you run the following code in the ocaml toplevel, you get the corresponding results: # let x = 5;; val x : int = 5 # inc_nosf x;; - : int = 6 # x;; - : int = 5 As you can see, the value of x didn't change. So, since we didn't save the return value, then nothing really got incremented. Our function itself only modifies the return value, not x itself. So to save it into x, we'd have to do: # let x = inc_nosf x;; val x : int = 6 # x;; - : int = 6 Since the inc_nosf function has no side effects (that is, it only communicates with the outside world using its return value, not by making any other changes). But something like: let inc_sf r = r := !r+1 has side effects because it changes the value stored in the reference represented by r. So if you run similar code in the top level, you get this, instead: # let y = ref 5;; val y : int ref = {contents = 5} # inc_sf y;; - : unit = () # y;; - : int ref = {contents = 6} So, in this case, even though we still don't save the return value, it got incremented anyway. That means there must have been changes to something other than the return value. In this case, that change was the assignment using := which changed the stored value of the ref. As a good rule of thumb, in Ocaml, if you avoid using refs, records, classes, strings, arrays, and hash tables, then you will avoid any risk of side effects. Although you can safely use string literals as long as you avoid modifying the string in place using functions like String.set or String.fill. Basically, any function which can modify a data type in place will cause a side effect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to debug Javascript + PHP + Web services Disclaimer: May be a insane question but I have suffered a lot so came here. I am working on a legacy application which uses JS + PHP + Web services (Written in spring). Flow of the application : Whenever any web service is called from JS it is redirected to one php file. The php file authenticates the user(using one web service) and then forwards the request to actual web service. How can I debug this application ? I have debugged JS using Firebug and servr side code using Eclipse but never debugged such a application. ~Ajinkya. A: I think there are a variety of things that need to be done, and I must say this question is sufficiently general as to not have a straight answer so I will do my best. As xdazz mentioned, var_dump (and die) are necessary from the PHP standpoint. Whenever anything is returned to JS console.log it. In addition, ensure XHTTP requests are turned on for Firebug or alternatively view the output of each request in the Chrome Network tab. With a combination of console.log, var_dump, and die, you can trace non-functioning parts of the application repeatedly step by step until you come across the bug. Alternatively, and in the long run you ought to be doing this anyway, build error handling code into all the PHP code that is only activated when a debug flag is set to true. This way you can get detailed error messages and then when you deploy, you can turn them off to avoid compromising security. A: If you are needing to inspect the entire lifecycle of a Web service request in your scenario you will need to combine a several techniques. Considering the fact that the scope of your scenario spans from client to server you will need to decide with what you will persist the information you need to inspect. Personally, I would choose the path of least resistance which in my case would probably be cookies. With that being said you should be able chronologically log the necessary information via JavaScript and PHP, both before, during and after the request and even redirect has occurred. This strategy would then allow for the information logged with cookies to then be dumped or analyzed via JavaScript, WebKit inspector or Firebug. Again, this is probably how I would handle such a scenario. Lastly, you can apply different storage strategies to this technique such as using a session or database for persistence. Note: You can use something like WebKit Inspector, and possibly Firebug, to analyze data transmitted and received for GET, POST and even WebSocket requests.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I ignore a certain file type in a certain directory and its sub-directory in Git? How can I ignore a certain filetype only in one directory and its sub-directory? To explain what I mean imaging the following setup * *anotherdir/ * *seeme1.iml *foldertoignore/ * *ignoreme1.iml *seeme3.txt *anotherignorefolder/ * *ignoreme2.iml *seeme4.txt *seeme5.iml I want to be able to do is tell git (using .gitignore file) to ignore *.iml but only under the directory foldtertoignore. I was thinking this would work foldertoignore/*.iml But that only found ignoreme1.iml not ignoreme2.iml I know how to tell it to ignore *.iml except for a specific directory. This is the reverse of that. Any thoughts? A: .gitignore rules are applied recursively from the containing directory. Simply create the file foldertoignore/.gitignore with *.iml as contents. >>foldertoignore/.gitignore echo '*.iml' git add foldertoignore/.gitignore git commit -m 'Ignore .iml files in foldertoignore and its subfolders' A: You can try this: /foldertoignore/**/*.iml It may or may not work depending on fnmatch implementation in your OS I suppose. Alternative is: *.iml !/anotherdir/*.iml !/*.iml
{ "language": "en", "url": "https://stackoverflow.com/questions/7578774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How to default p element to "Normal" style in CKEditor If I add a paragraph style to the CKEdtior eg: format_p: { element : 'p', attributes : { 'style' : 'FONT-SIZE:16px;color:#000000;FONT-STYLE:normal;FONT-FAMILY:Arial, Helvetica, sans-serif;font-weight:normal;' } } The default style when pressing the enter key is blank. However, if I set the style to "Normal" the style is applied and subsequent p's created by clicking the enter key include the style above. What I want is for all paragraphs (tag 'p') to use the "Normal" style by default. Is there a way to achieve this? A: I think you have use 'contentsCss', have you try 'dataProcessor' like this : CKEDITOR.on('pluginsLoaded', function (event) { event.editor.dataProcessor.dataFilter.addRules({ elements: { p: function (element) { // element.attributes } } }); event.editor.dataProcessor.htmlFilter.addRules ({ elements: { p: function (element) { // element.attributes ... } } }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7578776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Finding the exact selected text index in html document which works on safari and google chrome how to find index of selected text that is not dependent on window size and resolution? i have implemented it on IE but that code doesn't work on google chrome and safari as they dont support createrange method of javascript. this the code for IE to find start and end position range = doc.selection.createRange(); range.execCommand("BackColor", false, colour); var sourceSelEnd = range.boundingLeft; var sourceSelStart = parseInt(sourceSelEnd); sourceSelStart = sourceSelStart - (range.text.length); Please help in finding start index or position of selected text. Position() and Offset() are changing on window resize and resolution change A: I believe the following should do what you are looking for though it is admittedly contrived to illustrate the functionality: function getRangeAttributes() { var currentRange = window.getSelection().getRangeAt(0); return {'startContainer':currentRange.startContainer,'startOffset':currentRange.startOffset,'endContainer':currentRange.endContainer,'endOffset':currentRange.endOffset,'textLength':currentRange.toString().length} } Please see the following for more information: https://developer.mozilla.org/en/DOM/range
{ "language": "en", "url": "https://stackoverflow.com/questions/7578779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: exec() command not working I am using exec() function to run my commands on centos server. All was working fine untill i used command: $command= ffmpeg -i input video.mp4 -vf fade=out:0:5 output.mp4 The command is ok as it is running on server via command line but when i execute it using php it is not giving the output. I have already created a video from ffmpeg using the exec() function but this command is not working. What can be the reason i am confused how a command can run on server but not work while executing from php. Other command i executed using exec() function is : $command = ffmpeg -i %d.jpg -y -s 320x240 -aspect 4:3 output.mp4 and it is working perfectly and the video is also created but previous command is not giving video as output. Please guide me... A: Try debugging you command execution. For ffmpeg you need to pipe the output with 2>&1 to see it: exec($command." 2>&1", $output); echo "<pre>"; var_dump($output); echo "</pre>";
{ "language": "en", "url": "https://stackoverflow.com/questions/7578780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Paging a HTML page using C# Can anyone give me some idea abt how to page a HTML page? The HTML page contains texts, video & pics. Tags include P, STRONG, BR, I, Table, UL... A: Try look here: http://www.aspxtutorial.com/post/2011/02/02/How-Paging-Works-in-the-DetailsView-Control.aspx http://www.pcreview.co.uk/forums/paging-data-results-t3333991.html Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to check alignment of text using selenium RC verify alignment of text or any other element in web page using selenium rc. i use python, is there any budy who can help with this. A: In case text alignment is coded directly in HTML you could do what you want using the assertElementPresent() method and a suitable XPath locator. For example to check the following text <p id="paragraph" align="right">Text text text text text text text</p> you could use selenium.isElementPresent("//p[@id='paragraph' and @align='right']"); A: you can utilize getAttribute command for example String align = selenium.getAttribute("ele_locator@align");
{ "language": "en", "url": "https://stackoverflow.com/questions/7578786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to find the radius of visible MKMapView visible screen area? I want to know the radius of visible area in iphone screen, as I will zoomout and zoom in the visible area will change, so I want to know the radius of that particular area, how can I do it? A: Its not radius what is required. You need to use the region parameter from mapView. Check out apple docs, it is pretty much clear from those. Go thru this tutorial. It will help you a lot icode blog mapkit demo specifically you need to set something like this.. MKCoordinateSpan span = [self coordinateSpanWithMapView:self centerCoordinate:centerCoordinate andZoomLevel:zoomLevel]; MKCoordinateRegion region = MKCoordinateRegionMake(centerCoordinate, span); [self setRegion:region animated:animated]; where span can be calculated as - (MKCoordinateSpan)coordinateSpanWithMapView:(MKMapView *)mapView centerCoordinate:(CLLocationCoordinate2D)centerCoordinate andZoomLevel:(NSUInteger)zoomLevel { // convert center coordiate to pixel space double centerPixelX = [self longitudeToPixelSpaceX:centerCoordinate.longitude]; double centerPixelY = [self latitudeToPixelSpaceY:centerCoordinate.latitude]; // determine the scale value from the zoom level NSInteger zoomExponent = 20 - zoomLevel; double zoomScale = pow(2, zoomExponent); // scale the map’s size in pixel space CGSize mapSizeInPixels = mapView.bounds.size; double scaledMapWidth = mapSizeInPixels.width * zoomScale; double scaledMapHeight = mapSizeInPixels.height * zoomScale; // figure out the position of the top-left pixel double topLeftPixelX = centerPixelX - (scaledMapWidth / 2); double topLeftPixelY = centerPixelY - (scaledMapHeight / 2); // find delta between left and right longitudes CLLocationDegrees minLng = [self pixelSpaceXToLongitude:topLeftPixelX]; CLLocationDegrees maxLng = [self pixelSpaceXToLongitude:topLeftPixelX + scaledMapWidth]; CLLocationDegrees longitudeDelta = maxLng - minLng; // find delta between top and bottom latitudes CLLocationDegrees minLat = [self pixelSpaceYToLatitude:topLeftPixelY]; CLLocationDegrees maxLat = [self pixelSpaceYToLatitude:topLeftPixelY + scaledMapHeight]; CLLocationDegrees latitudeDelta = -1 * (maxLat - minLat); // create and return the lat/lng span MKCoordinateSpan span = MKCoordinateSpanMake(latitudeDelta, longitudeDelta); return span; } Cheers :) A: I might be misunderstanding the question, but isn't it as simple as: - (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated { CGFloat latD = mapView.region.span.latitudeDelta; CGFloat lngD = mapView.region.span.longitudeDelta; NSLog(@"This is the latitude delta of the visible map: %f", latD); NSLog(@"This is the longitude delta of the visible map: %f", lngD); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7578788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to show activities inside of a running activity? I want to show my activities inside of a running activity. I need something like frame in html language that is used for showing other pages inside a page. I know Tabhost has this ability. Which one of other controls has this ability? Thanks, A: Google introduced fragments in Android 3.0 and upper to create a portion of user interface in an Activity. But it is not two Activity, becuase activity <> window. For lower version you can manually load xml layout in your activity. A: The Fragment API is really your best choice, it's quite easy to use and you can dynamicly add them to your Activity Layout (take a look to Framgent For All - google Article) by code using the FragmentManager, this feature it's since 3.0 altough Google also released a pretty nice Compatibility Package that you can download out of the SDK Manager and added to your project like this Fragment For All:
{ "language": "en", "url": "https://stackoverflow.com/questions/7578789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to run a timer at the TOP of each second? (when millis = 000) In my application, I have used the number of System.Threading.Timer and set this timer to fire every 1 second. My application execute the thread at every 1 second but it execution of the millisecond is different. In my application i have used the OPC server & OPC group .one thread reading the data from the OPC server (like one variable changing it's value & i want to log this moment of the changes values into my application every 1 s) then another thread to read this data read this data from the first thread every 1s & second thread used for store data into the MYSQL database . in this process when i will read the data from the first thread then i will get the old data values like , read the data at 10:28:01.530 this second then i will get the information of 10:28:00.260 this second.so i want to mange these threads the first thread worked at 000 millisecond & second thread worked at 500 millisecond. using this first thread update the data at 000 second & second thread read the data at 500 millisecond. My output is given below: 10:28:32.875 10:28:33.390 10:28:34.875 .... 10:28:39.530 10:28:40.875 However, I want following results: 10:28:32.000 10:28:33.000 10:28:34.000 .... 10:28:39.000 10:28:40.000 How can the timer be set so the callback is executed at "000 milliseconds"? A: First of all, it's impossible. Even if you are to schedule your 'events' for a time that they are fired few milliseconds ahead of schedule, then compare millisecond component of the current time with zero in a loop, the flow control for your code could be taken away at the any given moment. You will have to rethink your design a little, and not depend on when the event would fire, but think of the algorithm that will compensate for the milliseconds delayed. Also, you won't have much help with the Threading.Timer, you would have better chance if you have used your own thread, periodically: * *check for the current time, see what is the time until next full second *Sleep() for that amount minus the 'spice' factor *do the work you have to do. You'll calculate your 'spice' factor depending on the results you are getting - does the sleep finishes ahead or behind the schedule. If you are to give more information about your apparent need for having event at exactly zero ms, I could help you get rid of that requirement. HTH A: I would say that its impossible. You have to understand that switching context for cpu takes time (if other process is running you have to wait - cpu shelduler is working). Each CPU tick takes some time so synchronization to 0 milliseconds is impossible. Maybe with setting high priority of your process you can get closer to 0 but you won't achive it ever. A: IMHO it will be impossible to really get a timer to fire exactly every 1sec (on the milisecond) - even in hardcore assembler this would be a very hard task on your normal windows-machine. A: I think first what you need to do: is to set right dueTime for a timer. I do it so: dueTime = 1000 - DateTime.Now.Milliseconds + X; where X - is serving for accuracy and you need select It by testing. Then Threading.Timer each time It ticks running on thread from CLR thread pool and, how tests show - this thread is different each time. Creating threads slows timer, because of this you can use WaitableTimer, which always will be running at the same thread. Instead of WaitableTimer you can using Thread.Sleep method in such way: Thread.CurrentThread.Priority = Priority.High; //If time is really critical Thread.Sleep (1000 - DateTime.Now + 50); //Make bound = 1s while (SomeBoolCondition) { Thread.Sleep (980); //1000 ms = 1 second, but something ms will be spent on exit from Sleep //Here you write your code } It will be work faster then a timer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: External read-only DB, my local DB, inconsistency There's a service A that works with DB1, there's service B that works with DB1 and DB2. Service A has read-write access to DB1 and doesn't work with DB2 at all. Service 2 has read-write access to DB2 and read-only access to DB1. The idea is, I'm developing service 2 and concerned about the inconsistency. Service 2 is like a "plugin" to service 1, so DB2 may be thought of as "some more data related with DB1 entities". There's no way I can explicitly synchronize with Service 1 and it's DB, there's no way I can receive any notifications when entities are removed, changed or new entities appear. The question is, what's the right approach for service 2 to make all this stuff consistent? I'm thinking about scheduling copying of entities from DB1 to DB2, so the only thing that really works with DB1 is that "copier". Then, Service 2 will only work with DB2 and there should be no problems. This seems to be quite trivial, so I really like this approach. Any other ideas? Some more details: DB1 is like 2 tables with summary of 1M rows. Both DBs are on the same server. The server is MS SQL 2005/2008. Service 2 is in .NET. A: The "periodic copy" option is a good idea, and will work well if your requirements can handle a bit of a lag between when a record is added / updated in DB1 vs. when it shows up in DB2. If your application can't handle that lag, then the approach I would take is essentially a 2-pronged method where you still do the periodic sync from DB1 to DB2, but then also have your application copy over data from DB1 into DB2 if it finds that something it needs in DB2 isn't there yet. For example, say you have a user that needs to update some special profile information that is stored in DB2 (a common "plugin" scenario). * *When the user goes into your plugin's portion of the application to set this special bit of information, your app will first look for that user in DB2. *If the user's info isn't in there yet (a new user, for example), * *then you go to DB1 to get the data and populate it into DB2. *You can then procede with saving the special profile information as you normally would. Depending on the performance requirements you have, the "copy as needed" method may be enough on it's own and may not need an additional "sync everything" periodic process. Having the extra sync process, however, may reduce the number of "misses" your application will have on DB2 if it looks for information that isn't there and has to fetch it from DB1.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to use reload data in table view while working with two view? I have two classes. In my first class i have table view which contains list of countries. And in my second view i have a picker which contain sorting by name. And i have button in my first class. On this button click i go on second class. In second class when i click on picker like sorting by name then the picker value store into NSMutableString. So i want that when i go back to my first view i want to show list according to the second class picker value. I use table reload in the viewWillAppear method of first view but its not working. Sometimes it crashes. -(void)viewWillAppear:(BOOL)animated { if(secondClassObj.isActStrPicker>=0) { sortByResultStr=[[NSString alloc]init]; sortByResultStr=[secondClassObj pickerValueStr]; NSLog(@"picker class value of sorting string fetech %@ if part sssssss",sortByResultStr); } else { //the else part is not working NSLog(@"picker class value fetech %@ else part sssssss",[cmpnyPickCheckObj isActStrPicker]); } [countrytableView reloadData]; } And i want that table shows value according to isActStrPicker(string) when i come back on this first view. Thanks for helping me A: Try Call NSNotificationCenter You can reload the tableView when you are not in that VIEW; 1. First In FirstVC.m, register a NSNotificationCenter, like this [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadtableview) name:@"ReloadTableView" object:nil]; -(void)reloadtableview { //reload tableview } 2*.Call this method to ask them to reload tableview:* [[NSNotificationCenter defaultCenter] postNotificationName:@"ReloadTableView" object:nil];
{ "language": "en", "url": "https://stackoverflow.com/questions/7578796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to disable status bar / notification bar on android programmatically? i create a lockscreen application.. this application is triggered by SMS.. when a SMS containing command was received, it will display a lock screen activity. my lockscreen activity is using TYPE_KEYGUARD for disabling a home screen button. When device screen turn off and then i turn it on again, my problem is status bar / notification bar still appear on my screen. this is a problem because the user still can access some program through status bar / notification bar even the device is being locked. so i want to dissapear this status bar / notification bar so that the user (theft) can't access that device anymore.. Please help me to solve this.. A: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().requestFeature(Window.FEATURE_NO_TITLE); } A: requestWindowFeature(Window.FEATURE_NO_TITLE); only disables the activity's title bar, not the notification bar at the top. Use this theme in android manifest for your activity : "Theme.NoTitleBar.Fullscreen" did work for me. It hides the notification bar. A: On Android 4.0 and lower Option 1: <application ... android:theme="@android:style/Theme.Holo.NoActionBar.Fullscreen" > ... </application> Option 2: public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // If the Android version is lower than Jellybean, use this call to hide // the status bar. if (Build.VERSION.SDK_INT < 16) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } setContentView(R.layout.activity_main); } ... } on Android 4.1 and Higher View decorView = getWindow().getDecorView(); // Hide the status bar. int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN; decorView.setSystemUiVisibility(uiOptions); // Remember that you should never show the action bar if the // status bar is hidden, so hide that too if necessary. ActionBar actionBar = getActionBar(); actionBar.hide(); And for Android 4.6(Api 19) and higher use the Immersive Full-Screen Mode Reference from Google A: I think what you're trying to do is programmatically set an activity as fullscreen. If so, consider the following: requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); Source: http://www.androidsnippets.com/how-to-make-an-activity-fullscreen
{ "language": "en", "url": "https://stackoverflow.com/questions/7578804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Serial port handshake. What the difference between Hardware and None handshaking? I'm trying to determine the difference when I open serial port with hardware handshake and none handshake. It seems that in both cases I have to control RTS/CTS signals (just tested it with one COM device). So what the difference between opening serial port with hardware handshake and without handshaking? From my previous understanding, when we work without handshaking, we don't care about RTS/CTS and DTR/DSR signals. Just send and receive data whenever we want. Was I wrong? One more question. Can we work without handshaking in full duplex mode only? A: As you probably know, the issue is "flow control". Like the Clash song "Should I stay or should I go?". RTS/CTS is hardware control. XON/XOFF is software control. Otherwise, "just keep going". This link might explain further: http://www.lammertbies.nl/comm/info/RS-232_flow_control.html I suspect that when you were asking about "handshaking" with respect to "duplex", perhaps you meant this: http://en.wikipedia.org/wiki/RS-232 In older versions of the specification, RS-232's use of the RTS and CTS lines is asymmetric: The DTE asserts RTS to indicate a desire to transmit to the DCE, and the DCE asserts CTS in response to grant permission. This allows for half-duplex modems that disable their transmitters when not required, and must transmit a synchronization preamble to the receiver when they are re-enabled. 'Hope that helps! A: The difference is more about whether the kernel will pay attention to the CTS/RTS lines when deciding whether to send more data or not. With hardware handshaking turned on, it will. With it set to none, it won't, even though the CTS/RTS lines may stay asserted, so that the peer will know it can send data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: WCF Client is unable to see endpoint but WCF Client can connect to base address I get the following error when i try to consume my wcf service Could not find endpoint element with name 'http://localhost:8080/Provider/basic' and contract 'Provider.IProvider' in the ServiceModel client configuration section I can however connect to my base address through the WCF Test Client on http://localhost:8080/Provider I've tried updating my service reference and that didn't work, Anyone know what is wrong with my setup public ServiceHost ProviderServiceHost { get; set; } private void StartProvider() { if (ProviderServiceHost != null) Abort(); ProviderServiceHost = new ServiceHost(typeof(Provider), new Uri("http://localhost:8080/Provider")); var binding = new BasicHttpBinding { Name = "basicBinding", HostNameComparisonMode = HostNameComparisonMode.WeakWildcard, Security = { Mode = BasicHttpSecurityMode.None } }; var metadataBehavior = ProviderServiceHost.Description.Behaviors.Find<ServiceMetadataBehavior>(); if (metadataBehavior == null) { metadataBehavior = new ServiceMetadataBehavior { HttpGetEnabled = true }; ProviderServiceHost.Description.Behaviors.Add(metadataBehavior); } ProviderServiceHost.AddServiceEndpoint(typeof(IProvider), binding, "http://localhost:8080/Provider/basic"); ProviderServiceHost.Open(); } My client is connecting like this private static ProviderClient _proxy = new ProviderClient(http://localhost:8080/Provider/basic); If i don't put in an address then i get this exception Message "Could not find default endpoint element that references contract 'Provider.IProvider' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element." string A: Are you using client side configuration? As it appears you're using the ClientBase proxy I expect you've used 'Add Service Reference...' and are just the default configuration file. The overload that you're using is new ServiceClient(string endpointConfigurationName) - the string value represents a Name, not an Address. If you check your configuration file you should see a client section has been added: <client> <endpoint address="http://localhost:8080/Provider/basic" binding="basicHttpBinding" bindingConfiguration="basicBinding_IProvider" contract="ServiceReference1.ITest" name="basicBinding_IProvider" /> </client> So if you change your Client constructor to use this Name property it should work better for you. private static ProviderClient _proxy = new ProviderClient("basicBinding_IProvider"); On the other hand if you are not using a configuration file and want to specify the address in code, you can use a different ClientBase constructor: using System.ServiceModel; // ... _client = new ProviderClient(new BasicHttpBinding(), new EndpointAddress("http://localhost:8080/Provider/basic")); There are a number of different overloads in the ClientBase class (your ProviderClient) which allow you to specify various properties.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to send emails from an address without logging into the server I'm building an asp.net application for a client that requires a confirmation email to be sent. I've gotten the code working but the only problem is that I can't get the code to work with their web host (godaddy). Is there a way to send emails with the from address marked as the clients' without having to use godaddy? (essentially faking it) A: Be careful or you'll lose your emails to spam filters. Specifically, see the Reverse PTR record discussion here: http://www.codinghorror.com/blog/2010/04/so-youd-like-to-send-some-email-through-code.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7578824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problems upgrading MVC Mini Profiler to latest release I've been using Mini Profiler in dev and production (azure) for a while and LOVE it. It tried to upgrade to the latest release today via NUGET. The DLL get's placed in the bin but my site gets an error. If I go back to the old dll it works fine. Does anyone know how to fix this? Server Error in '/' Application. Could not load file or assembly 'MvcMiniProfiler, Version=2.0.4177.17902, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.IO.FileLoadException: Could not load file or assembly 'MvcMiniProfiler, Version=2.0.4177.17902, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Assembly Load Trace: The following information can be helpful to determine why the assembly 'MvcMiniProfiler, Version=2.0.4177.17902, Culture=neutral, PublicKeyToken=null' could not be loaded. WRN: Assembly binding logging is turned OFF. To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1. Note: There is some performance penalty associated with assembly bind failure logging. To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog]. Stack Trace: [FileLoadException: Could not load file or assembly 'MvcMiniProfiler, Version=2.0.4177.17902, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)] MyGlobal.application_BeginRequest(Object sender, EventArgs e) in C:\Users\Nate\Documents\Visual Studio 2010\Projects\TrainerRoad\com.TrainerRoad.DataAccess\MyGlobal.cs:15 System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +270 Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.237 A: Be sure to read the documentation on http://code.google.com/p/mvc-mini-profiler/ In particular: * *Ensure you remove all the modifications you made to web.config. *If you are profiling Entity Framework grab the MiniProfiler.EF package *If you are running latest EF see: Problem using SQL Server CE with Entity Framework code-first and ASP.NET MVC 3 and mvc miniprofiler There is not MiniProfiler version 2.0.4177.17902 so I really do not know where it is coming from.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error while saving Application settings: "There was a problem saving your changes. Please try again later." call-for-help: we are keep getting the illustrated error after hitting "save changes" in the application settings dashboard ... the changes are saved though ... any link where we can report our app issue? http://awesomescreenshot.com/046la8j4f A: This is not a problem with your app.. This happens sometimes because your app server might have taken a longer time to update on FB servers and the connection timed out... Nothing to worry about you an try again A: I had the same issue and solved it by checking all the icons and screenshots. I made sure that they all was in the same format (.png) and then it worked! I guess the issue, for me, is that i used different formats.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use RED5 to enable live broadcast from a file? Is it possible to set up RED5 in a way where different users logging in at different times will be seeing the stream from an elapsed time period since the broadcast started? Say, my prescheduled broadcast starts at 10:00AM, is it possible for the user logging in at 10:05AM to start viewing the stream from the 5 minutes mark from video start? Much like a prerecorded online radio. Thanks in advance. A: Check out the examples: http://red5.googlecode.com/svn/java/example/trunk http://red5.googlecode.com/svn/flash/trunk/ You might be able to use these for what you need: http://red5.googlecode.com/svn/java/example/trunk/oflaDemo/ http://red5.googlecode.com/svn/flash/trunk/simpleSubscriber.fla http://red5.googlecode.com/svn/flash/trunk/simpleBroadcaster.fla These do no create a recorded just the live feed, like radio.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: VS2010: Exclude a project from build I have a solution that has a wcf service that connects to SQl server. When I am offline I have another service that I use for development and testing that stores to in memory storage. I would like to exclude the test service from my Team build as I do not wish to deploy this to the customer etc. How do I do this? A: In VS2010, select Build | Configuration Manager .... In the Configuration Manager dialog, select in the active configuration list. Enter a name (eg. TeamBuild) and select to copy from Release. Click OK. Now make sure that only projects are checked that you want to have build a scheduled team build (exclude your test service). Click OK, save you solution and check it in. In your Team build definition, under Build process, select the solution you just have saved and under the Configuration tab, select the TeamBuild configuration. Now, only the projects that you have selected are build.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: questions about multicast We all know that udp is not reliable,by learning unix network programming I add some hdrs about seq and ts to make udp reliable.the idea is simple.when the receiver receives a packet,it must send a ack packet,there is also something about the round trip time algothrim to estimate the rto.But to multicast,a sender sends a packet to a multicast addr, all host in that multicast group must send a ack packet.Even if the seq is right and acks comes in time,we are still not sure whether all host got the packet,because we don't know the host number.maybe one or more host's ack packet is lost. I wonder if I can get the number of the host on a specific multicast group or perhaps there is a better idea to make mulitcast reliable. A: Try to talk to you network admin and ask him to make your network transmitting reliably. I have 2Gbps multicast all around my network in europe, middle east, asia, north and south america and never lost a single packet - all switches are "voip ready", so this way they automatically internally prioritize the multicast traffic and this is the best way to approach this problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Logic / Algorithm for this Series I have an array of characters from a to z, my task is to extract the vowels out of this array, the series that will extract the indexes of vowels goes like this, 1, 5, 9, 15, 21, 25... i am unable to create this series through loops, these numbers are actually the vowels in the array. I don't want Vowel Matching technique, i want the logic for the sequence given above. A: If you really want to do this algorithmically, you could: int v = 1; for (int i = 0; i < 6; i++) { printf("%d\n", v); v += 4 + (i & 2); } ...but I'm not sure I see the point. A: I would consider the solution proposed by Greg Hewgill to be the more appropiate one, where you have int vowels[] = {1, 5, 9, 15, 21, 25}; and vowels[i] is your function. However, if you want a math function Wolfram Alpha proposes: (z(z((9-5z)z-11)+5))/((z-1)^4)+1 http://www.wolframalpha.com/input/?i=1%2C+5%2C+9%2C+15%2C+21%2C+25 That said, I don't see a point in using it instead of the array. A: You can doubtlessly find a formula for the sequence, but is that the right approach? Whether a character is a vowel or not isn't determined by whether it is a member of a sequence or not; it is purely arbitrary, and not necessarily the same from one language to another: y is a vowel in some languages, a consonant in others, and can be either in English; 27, 28 and 29 don't exist in English, but are vowels in Swedish, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Finding Navigate driving directions using Google Maps in iphone i'm developing an iPhone app which embed a mapView made with mkmapkit. I got two coordinates and I'm tracing the direction between these two points.But I need step by step directions how can get this step by step directions if any one knows please help me ..... here i am attaching screen shot what i need:http://www.myappdemo.com/Screen%20shot.png thanks for advance A: You can use google API for it. http://maps.googleapis.com/maps/api/directions/xml?origin=Brooklyn,NY&destination=Manhattan,NY&sensor=false
{ "language": "en", "url": "https://stackoverflow.com/questions/7578849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python expand OSX path with spaces in it I'm trying to modify the plist file at: /Volumes/MacintoshHD/Users/christian/Library/Application Support/iPhone Simulator/4.3.2/Library/Preferences/com.apple.Accessibility.plist Here's my noob python script: import plistlib import os.path #set path prefs_path = os.path.expanduser("~/Library/Application\ Support/iPhone\ Simulator/5.0/Library/Preferences/com.apple.Accessibility.plist") #parse prefs = plistlib.readPlist(prefs_path) I get IOError: 2, 'No such file or directory' If I remove the backslashes from the path I get ExpatError: 'not well-formed (invalid token): line 1, column 8' Update Ignacio Vazquez-Abram's answer suggests that the file is corrupted. It's still editable with Xcode and viewable with Quicklook. Also the simulator works fine. When I open it in textmate all I see is this: bplist00ÿ D _ApplicationAccessibilityEnabled_VOTQuickNavEnabled_AccessibilityEnabled]ScreenCurtain_"VoiceOverTouchRotorItemsPreference_AXInspector.enabled_AXInspector.frame_AXInspectorEnabled Ø"%(+.147:=@“ YRotorItemWEnabledYCharacter “ TWord “ TLine “ VHeader “ TLink “ [FormElement “# ZTableStart “&YListStart“)YLandmarks“,[VisitedLink“/^NonVisitedLink“2VButton“5YTextField“8UImage“;ZStaticText“>\InternalLink“ATZoom_{{0, 0}, {276, 166}} ;Pguö∞ƒŸ⁄€‹›Òˆ#().56;@AFRSXcdistyÉÑâïñõ™´∞∑∏Ω«»Õ”‘Ÿ‰Â͘¯˝F Are the iPhone simulator plists not editable by python or is this a corrupted file? Is there a way around this? A: The expat error means that you've gotten to the file, but there's something wrong with it. Open the file and verify that it's not been corrupted. EDIT: Aaah, it's a binary plist. Yeah, plistlib can't handle those. You want libplist instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7578850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redirect from old domain to new one (SEO friendly) I changed the custom domain on my Heroku app to a new one. Now I will create a new Heroku app which only purpose will be to redirect to the first app. I read in Google Webmasters that I should do a 301 redirect like this: http://old.com/anypath/123 to http://new.com/anypath/123 How do I do it in Rails? A: In your controller action: redirect_to "http://new.com#{request.request_uri}", :status => 301 However, Heroku has what may be a slightly better option for you documented in their dev center: class ApplicationController before_filter :ensure_domain APP_DOMAIN = 'myapp.mydomain.com' def ensure_domain if request.env['HTTP_HOST'] != APP_DOMAIN # HTTP 301 is a "permanent" redirect redirect_to "http://#{APP_DOMAIN}#{request.request_uri}", :status => 301 end end end A: Put this in a before filter in the ApplicationControlller: class ApplicationController before_action :redirect_if_old protected def redirect_if_old if request.host == 'old.com' redirect_to "#{request.protocol}new.com#{request.fullpath}", :status => :moved_permanently end end end A: You can do this in the routes.rb file rather than a controller: Rails.application.routes.draw do constraints(host: 'old.com') do get '(*)', to: redirect(host: 'new.com') end # your existing routes here end This will do a 301 redirect, which is the default for the redirect route helper
{ "language": "en", "url": "https://stackoverflow.com/questions/7578853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Encoding Japanese characters How would I encode the following: chapter_mapping = {'chapter': ' チャプター'} so I can call chapter_mapping['chapter']. Thank you. A: You'll also need to add a header to your file in python 2: # -*- coding: utf-8 -*- chapter_mapping = {'chapter': u'チャプター'} A: Always use unicode literals. chapter_mapping = {'chapter': u' チャプター'}
{ "language": "en", "url": "https://stackoverflow.com/questions/7578854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sending POST request in iPhone using ASIHTTPRequest 1.6.2 I am using ASIHTTPRequest 1.6.2 lib for all http transactions in IPhone. But i dont know, how can i post the data with ASIHTTPRequest in iPhone? Can you please give me the code snippet which will work in in iphone? I am using the following code for this. But i am getting response code as 0. Please help me to understand where i am going wrong. ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; [request setPostValue:inputXml forKey:@"inputXml"]; [request setPostValue:@"qftS6TJN343343V84hw=" forKey:@"key"]; [request setPostValue:@"1.2" forKey:@"version"]; [request setRequestMethod:@"POST"]; [request startAsynchronous]; A: Here's the how to page. It covers all types of requests such as get, form post, custom post, put, etc... http://allseeing-i.com/ASIHTTPRequest/How-to-use Here's how to set it up in your XCode project: http://allseeing-i.com/ASIHTTPRequest/Setup-instructions Those instructions and snippets should work in iOS. A: You should use ASIFormDataRequest: ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; [request setPostValue:@"Ben" forKey:@"first_name"]; [request setPostValue:@"Copsey" forKey:@"last_name"]; [request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"]; A: Following is the sample code... ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url]; [request appendPostData:[reqString dataUsingEncoding:NSUTF8StringEncoding]]; [request setRequestMethod:@"POST"]; [request setDelegate:self]; [request setTimeOutSeconds:60]; [request startAsynchronous]; You will get detail guidance from here. A: ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:]]; NSMutableDictionary *dicData = [[NSMutableDictionary alloc] initWithCapacity:1]; [dicData setObject:txtPassword.text forKey:@"Password"]; [dicData setObject:txtEmailID.text forKey:@"Email"]; [request setPostBody:[[[self parseJsonFromObject:dicData] dataUsingEncoding:NSUTF8StringEncoding] mutableCopy]]; [request setRequestHeaders:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"application/json", @"Content-Type", nil]]; [request setDelegate:self]; [request setDidFinishSelector:@selector(signUpWithEmailFinish:)]; [request setDidFailSelector:@selector(signUpWithEmailFail:)]; [request startAsynchronous]; (void)signUpWithEmailFinish:(ASIHTTPRequest *)request { if (request.responseStatusCode == 200) { NSDictionary *responseMessage = [self objectFromJson:request.responseString]; NSLog(@"ResponseMEssage=%@",responseMessage); if (responseMessage) { if ([responseMessage objectForKey:@"user"] == nil) { NSLog(@"duplication not allowed"); [self animation:0]; return; } [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_LOGIN_SUCCESS object:nil]; NSLog(@"Registration Complete"); UserLoginPage *userLogin=[[UserLoginPage alloc]init]; [self.navigationController pushViewController:userLogin animated:YES]; return; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7578856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check whether a string is a valid HTTP URL? There are the Uri.IsWellFormedUriString and Uri.TryCreate methods, but they seem to return true for file paths, etc. How do I check whether a string is a valid (not necessarily active) HTTP URL for input validation purposes? A: After Uri.TryCreate you can check Uri.Scheme to see if it HTTP(s). A: Try this to validate HTTP URLs (uriName is the URI you want to test): Uri uriResult; bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp; Or, if you want to accept both HTTP and HTTPS URLs as valid (per J0e3gan's comment): Uri uriResult; bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps); A: As an alternative approach to using a regex, this code uses Uri.TryCreate per the OP, but then also checks the result to ensure that its Scheme is one of http or https: bool passed = Uri.TryCreate(url, UriKind.Absolute, out Uri uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps); A: Try that: bool IsValidURL(string URL) { string Pattern = @"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$"; Regex Rgx = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase); return Rgx.IsMatch(URL); } It will accept URL like that: * *http(s)://www.example.com *http(s)://stackoverflow.example.com *http(s)://www.example.com/page *http(s)://www.example.com/page?id=1&product=2 *http(s)://www.example.com/page#start *http(s)://www.example.com:8080 *http(s)://127.0.0.1 *127.0.0.1 *www.example.com *example.com A: This would return bool: Uri.IsWellFormedUriString(a.GetAttribute("href"), UriKind.Absolute) A: Problem: Valid URLs should include all of the following “prefixes”: https, http, www * *Url must contain http:// or https:// *Url may contain only one instance of www. *Url Host name type must be Dns *Url max length is 100 Solution: public static bool IsValidUrl(string webSiteUrl) { if (webSiteUrl.StartsWith("www.")) { webSiteUrl = "http://" + webSiteUrl; } return Uri.TryCreate(webSiteUrl, UriKind.Absolute, out Uri uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps) && uriResult.Host.Replace("www.", "").Split('.').Count() > 1 && uriResult.HostNameType == UriHostNameType.Dns && uriResult.Host.Length > uriResult.Host.LastIndexOf(".") + 1 && 100 >= webSiteUrl.Length; } Validated with Unit Tests Positive Unit Test: [TestCase("http://www.example.com/")] [TestCase("https://www.example.com")] [TestCase("http://example.com")] [TestCase("https://example.com")] [TestCase("www.example.com")] public void IsValidUrlTest(string url) { bool result = UriHelper.IsValidUrl(url); Assert.AreEqual(result, true); } Negative Unit Test: [TestCase("http.www.example.com")] [TestCase("http:www.example.com")] [TestCase("http:/www.example.com")] [TestCase("http://www.example.")] [TestCase("http://www.example..com")] [TestCase("https.www.example.com")] [TestCase("https:www.example.com")] [TestCase("https:/www.example.com")] [TestCase("http:/example.com")] [TestCase("https:/example.com")] public void IsInvalidUrlTest(string url) { bool result = UriHelper.IsValidUrl(url); Assert.AreEqual(result, false); } Note: IsValidUrl method should not validate any relative url path like example.com See: Should I Use Relative or Absolute URLs? A: public static bool CheckURLValid(this string source) { Uri uriResult; return Uri.TryCreate(source, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp; } Usage: string url = "htts://adasd.xc."; if(url.CheckUrlValid()) { //valid process } UPDATE: (single line of code) Thanks @GoClimbColorado public static bool CheckURLValid(this string source) => Uri.TryCreate(source, UriKind.Absolute, out Uri uriResult) && uriResult.Scheme == Uri.UriSchemeHttps; Usage: string url = "htts://adasd.xc."; if(url.CheckUrlValid()) { //valid process } A: All the answers here either allow URLs with other schemes (e.g., file://, ftp://) or reject human-readable URLs that don't start with http:// or https:// (e.g., www.google.com) which is not good when dealing with user inputs. Here's how I do it: public static bool ValidHttpURL(string s, out Uri resultURI) { if (!Regex.IsMatch(s, @"^https?:\/\/", RegexOptions.IgnoreCase)) s = "http://" + s; if (Uri.TryCreate(s, UriKind.Absolute, out resultURI)) return (resultURI.Scheme == Uri.UriSchemeHttp || resultURI.Scheme == Uri.UriSchemeHttps); return false; } Usage: string[] inputs = new[] { "https://www.google.com", "http://www.google.com", "www.google.com", "google.com", "javascript:alert('Hack me!')" }; foreach (string s in inputs) { Uri uriResult; bool result = ValidHttpURL(s, out uriResult); Console.WriteLine(result + "\t" + uriResult?.AbsoluteUri); } Output: True https://www.google.com/ True http://www.google.com/ True http://www.google.com/ True http://google.com/ False A: This method works fine both in http and https. Just one line :) if (Uri.IsWellFormedUriString("https://www.google.com", UriKind.Absolute)) MSDN: IsWellFormedUriString A: Uri uri = null; if (!Uri.TryCreate(url, UriKind.Absolute, out uri) || null == uri) return false; else return true; Here url is the string you have to test. A: I've created this function to help me with URL validation, you can customize it as you like, note this is written in python3.10.6 def url_validator(url: str) -> bool: """ use this func to filter out the urls to follow only valid urls :param: url :type: str :return: True if the passed url is valid otherwise return false :rtype: bool """ #the following regex is copied from Django source code # to validate a url using regax regex = re.compile( r"^(?:http|ftp)s?://" # http:// or https:// r"(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|" # domain... r"localhost|" # localhost... r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})" # ...or ip r"(?::\d+)?" # optional port r"(?:/?|[/?]\S+)$", re.IGNORECASE, ) blocked_sites: list[str] = [] for site in blocked_sites: if site in url or site == url: return False # if none of the above then ensure that the url is valid and then return True otherwise return False if re.match(regex, url): return True return False
{ "language": "en", "url": "https://stackoverflow.com/questions/7578857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "351" }
Q: WebBrowser Control with Tabs I need to have tab view of the new IE versions in the WPF WebBrowser control. How can I achieve it? Do I have to use TabControl and host WebBrowser control in each of its tab items? I thought there could be some better way to have a Tabbed view in WebBrowser control itself because some of the features are very conveniently managed by the IE plugin itself such as "Open in Tab" option, "Drag and Arrange Tab order", open new tab with default url etc. If I go the TabControl way then I will have to recreate all this functionalitites. Any wild inputs are welcome. :-) Thx. EDIT Solution to achieve how to enable "Open in Tab" Right Click option in your WebBrowser control. using System; using System.Runtime.InteropServices; namespace TabbedBrowsing { public enum INTERNETFEATURELIST { FEATURE_OBJECT_CACHING = 0, FEATURE_ZONE_ELEVATION = 1, FEATURE_MIME_HANDLING = 2, FEATURE_MIME_SNIFFING = 3, FEATURE_WINDOW_RESTRICTIONS = 4, FEATURE_WEBOC_POPUPMANAGEMENT = 5, FEATURE_BEHAVIORS = 6, FEATURE_DISABLE_MK_PROTOCOL = 7, FEATURE_LOCALMACHINE_LOCKDOWN = 8, FEATURE_SECURITYBAND = 9, FEATURE_RESTRICT_ACTIVEXINSTALL = 10, FEATURE_VALIDATE_NAVIGATE_URL = 11, FEATURE_RESTRICT_FILEDOWNLOAD = 12, FEATURE_ADDON_MANAGEMENT = 13, FEATURE_PROTOCOL_LOCKDOWN = 14, FEATURE_HTTP_USERNAME_PASSWORD_DISABLE = 15, FEATURE_SAFE_BINDTOOBJECT = 16, FEATURE_UNC_SAVEDFILECHECK = 17, FEATURE_GET_URL_DOM_FILEPATH_UNENCODED = 18, FEATURE_TABBED_BROWSING = 19, FEATURE_SSLUX = 20, FEATURE_DISABLE_NAVIGATION_SOUNDS = 21, FEATURE_DISABLE_LEGACY_COMPRESSION = 22, FEATURE_FORCE_ADDR_AND_STATUS = 23, FEATURE_XMLHTTP = 24, FEATURE_DISABLE_TELNET_PROTOCOL = 25, FEATURE_FEEDS = 26, FEATURE_BLOCK_INPUT_PROMPTS = 27, FEATURE_ENTRY_COUNT = 28 } public enum DWFLAGS { SET_FEATURE_ON_THREAD = 0x00000001, SET_FEATURE_ON_PROCESS = 0x00000002, SET_FEATURE_IN_REGISTRY = 0x00000004, SET_FEATURE_ON_THREAD_LOCALMACHINE = 0x00000008, SET_FEATURE_ON_THREAD_INTRANET = 0x00000010, SET_FEATURE_ON_THREAD_TRUSTED = 0x00000020, SET_FEATURE_ON_THREAD_INTERNET = 0x00000040, SET_FEATURE_ON_THREAD_RESTRICTED = 0x00000080 } public static class IEFeatureSetBehavior { [DllImport("urlmon.DLL")] public static extern Int32 CoInternetSetFeatureEnabled(INTERNETFEATURELIST featureEntry, Int32 dwFlags, bool fEnable); [DllImport("urlmon.DLL")] public static extern Int32 CoInternetIsFeatureEnabled(INTERNETFEATURELIST featureEntry, Int32 dwFlags); public static void EnabledTabbedBrowsing() { var lr = 0; var featureToEnable = INTERNETFEATURELIST.FEATURE_TABBED_BROWSING; if (CoInternetSetFeatureEnabled(featureToEnable, (Int32)DWFLAGS.SET_FEATURE_ON_PROCESS, true) == 0) { if (CoInternetIsFeatureEnabled(featureToEnable, (Int32)DWFLAGS.SET_FEATURE_ON_PROCESS) != 0) { lr = 2; } else { lr = 1; } } } } } We just need to call the IEFeatureSetBehavior.EnabledTabbedBrowsing(); in your Window's constrcutor. All the WebBrowser controls will now enable the Open in Tab right click option \ wheel click \ Ctrl + Click. But this will not host a aTabControl in your WebBrowser control. The option opens the IE browser instance with the relevant link opened as a Tab. :( But nonetheless there is another way. We can be aware of the tabbed browsing request. If a user tries to call tabbed browsing, an event is raised by the WebBrowser control. We can handle this event and based on that create a new TabItem with another web browser control in it which is part of a WPF TabControl that wraps our previous web browser control. Cheers. :-) A: The way you suggested (putting the WebBrowser control into a TabControl) is probably as good as it gets. That beeing said, you will still be running into walls quickly because the WebBrowser control is very limited. All you can bassically do with it, is open a URL and scroll and click in it. You don't get APIs for the DOM which you'd need if you would like to provide a context menu action like "Open in new tab". That also beeing said, you might want to have a look at Awsomium wich is a much more sophisticated web browser control but unfortunately might not be free for you. A: FEATURE_TABBED_BROWSING
{ "language": "en", "url": "https://stackoverflow.com/questions/7578860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to sort xpath using php i searched through the website and couldnt find exact result for my question. i need to search through the xml file and sort the output by the order in date descending. <?xml version="1.0"?> <entries> <entry> <date>1299565881</date> <action>made an action under category</action> <user>Admin</user> </entry> <entry> <date>1299566115</date> <action>Item deleted</action> <user>Admin</user> </entry> </entries> here is my code <?php $data = simplexml_load_file($filename); if($to_date_int>$global_date) $op = $data->xpath('/entries/entry[date<='.$to_date_int.']'); else $op = $data->xpath('/entries/entry'); Thanks in advance.. A: Since $op will be an array of the matching entry elements, you could use PHP's array sorting functions to sort by their associated date elements. function sort_entries_by_date($a, $b) { return (int) $b->date - (int) $a->date; } usort($op, 'sort_entries_by_date'); (If you're using PHP 5.3, the named function could be placed by an inline anonymous function.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7578862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }