pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
11,635,412 | 0 | Ribbon button should be hidden based on lead status - CRM 2011 <p>I have custom button in lead ribbon. The custom button should be hidden when lead is qualified. How can I do that? Can any one please explain. I appreciate. </p> |
30,391,341 | 0 | <p>You could try writing a small wrapper around the <code>List</code> of your object type, and giving it a string based <code>[]</code> overloaded accessor. Like this:</p> <pre><code>public class ComplexType { public string PropertyName { get; set; } public string Layer { get; set; } public string DisplayName { get; set; } } public class DebuggableList : List<ComplexType> { public ComplexType this[string key] { get { return this.FirstOrDefault(i => i.PropertyName == key); } } } class Program { static void Main(string[] args) { var myList= new DebuggableList(); myList.Add(new ComplexType { DisplayName = "XXX", Layer = "YYY", PropertyName = "ZZZ" }); myList.Add(new ComplexType { DisplayName = "AAA", Layer = "BBB", PropertyName = "CCC" }); myList.Add(new ComplexType { DisplayName = "DDD", Layer = "EEE", PropertyName = "FFF" }); } } </code></pre> <p>In the watch window, you can then access your desired object using <code>myList["XXX"]</code>, and the object with <code>PropertyName</code>=="XXX" will be displayed.</p> |
3,581,176 | 0 | <p>Not without writing it somewhere. You have the following options:</p> <p>1- Write it to a file (or touch a file and check for its existence)</p> <p>2- Manually update a CONFIG file with a GLOBAL variable </p> <p>3- Use a database.</p> |
26,779,155 | 0 | Can't edit Security Roles from Non-Default Business Unit <p>When "customising the system" in Dynamics 2013, I cannot see any roles outside of the default business unit (even if I move my "System, Customiser user" to the business unit in question. I have tried a solution and the defauilt solution. How do you see all roles in all business units to customise the roles?</p> |
33,854,390 | 0 | FFMPEG: How to encode for seekable video at high key frame interval <p>I'm looking for an ffmpeg comand that's best used if I'm controlling a video to mouse control on "requestAnimationFrame". Basically, it needs to be fast-seeking and encoded at a high key frame interval. I can't seem to nail down what parameters aid in fast-seeking and high key frames. </p> <p>thanks! Johnny</p> |
8,009,131 | 0 | <p>We use nsb_$endpoint_$function where $function = error or audit. $function is left off for just the endpoint. We also make this match the Display Name and Service Name when installing the host. Our admins like being able to match the process to the service and then to the queue.</p> |
13,678,635 | 0 | <p>One solution can be <code>NSNotifications</code>. Post a notification when mute button is tapped and add observer on each of the view where you want play/mute sounds.</p> <p>See this <a href="http://iphonebyradix.blogspot.com/2011/07/nsnotificationcenter-tutorial.html" rel="nofollow">NSNotificationCenter Tutorial</a> for how to post and add observe for <code>NSNotification</code></p> |
25,718,273 | 0 | <p>change below code</p> <pre><code> $http.get('http://localhost/json/search.php', { params: searchkeyword }, </code></pre> <p>to </p> <pre><code> $http.get('http://localhost/json/search.php', { params: $scope.searchkeyword }, </code></pre> |
31,979,638 | 0 | <p>Using following methods you could identify how GC behaves on weak references. Option 1:</p> <p>-verbose:gc </p> <p>This argument record GC behaviour whenever GC kicks into picture. You could take the log file when you want to check did GC gets into action, It could be checked from the GC logs. For Interactive GC analysis try the log with <a href="http://www.ibm.com/developerworks/java/jdk/tools/gcmv/" rel="nofollow">http://www.ibm.com/developerworks/java/jdk/tools/gcmv/</a> </p> <p>Option 2 :</p> <p>Collect Heap dump and user event and load it in <a href="https://www.ibm.com/developerworks/java/jdk/tools/memoryanalyzer/" rel="nofollow">https://www.ibm.com/developerworks/java/jdk/tools/memoryanalyzer/</a></p> <p>Write OQL(Object Query language) on OQL section select * from package(s).classname and click on ! on the tool bar It will give list of objects of that type Right click on the objects -> Path to GC roots -> Exclude soft/weak/Phantom references If suspect object does not have any strong reference then it will show NULL else you will get information on who is holding the strong references on the suspected object.</p> |
8,091,042 | 0 | Extract DataTable values using Linq "C#" <p>I have a datatable dtRecords with values like this:</p> <p><strong>RollNo</strong> <strong>Name</strong></p> <p>120 john</p> <p>121 johney</p> <p>122 sam </p> <p>I want to add those values in a list box like the below format.</p> <p>RollNo:[RollNo] , Name: [Name] </p> <p>Note : [RollNo] is ColumnName Identification Format</p> <p><strong>Expected output:</strong></p> <p>RollNo: 120 ,Name: John</p> <p>RollNo: 121 ,Name: Johney</p> <p>I can achieve this using a for loop but is there some other way such as using linq or any other concept.</p> <p>Please include examples with your suggestions.</p> <p>I tried using the linq code below but I didn't get the proper output. </p> <pre><code>string mystring="RollNo:[RollNo] , Name: [Name]"; List<DataColumn> cols = ClsGlobal.dtRecords.Columns.Cast<DataColumn>().ToList(); dtRecords.AsEnumerable().ToList().ForEach(r => cols.ForEach(c =>listBox1.Items.Add(mystring.Replace("[" + c.ColumnName + "]", r[c.ColumnName].ToString())))); </code></pre> |
1,958,343 | 0 | A little php help with this string formatting <p>I have a string in this format:</p> <pre><code> /SV/temp_images/766321929_2.jpg </code></pre> <p>Is there any small piece of code to get the numbers BEFORE the underscore, BUT AFTER temp_images/? In this case I want to get <strong>766321929</strong> only... ?</p> <p>Thanks</p> |
30,748,583 | 0 | MySQL select as special and the output exclude null version <p>This is my sql statement, as you can see the the select SELECT category as special, how can I only get special is NOT NULL.</p> <pre><code>SELECT p.product_id, (SELECT price FROM oc_product_special ps WHERE ps.product_id = p.product_id AND ps.customer_group_id = '1' AND ((ps.date_start = '0000-00-00' OR ps.date_start < NOW()) AND (ps.date_end = '0000-00-00' OR ps.date_end > NOW())) ORDER BY ps.priority ASC, ps.price ASC LIMIT 1) AS special FROM oc_product_to_category p2c LEFT JOIN oc_product p ON (p2c.product_id = p.product_id) WHERE AND p.status = '1' AND p.date_available <= NOW() AND p2c.category_id = '20' GROUP BY p.product_id ORDER BY p.sort_order ASC LIMIT 0,5 </code></pre> <p>With above statement, I have the following output: <img src="https://i.stack.imgur.com/3MDsz.png" alt="enter image description here"></p> <p>I tried add the WHERE after the date_available, then I got no result out. I try to use <code>special</code> IS NOT NULL it showed: Unknown column 'special' in 'where clause'</p> <p>Anyone can help in this matter? Thanks!</p> |
21,928,273 | 0 | Object Oriented JavaScript: the patterns for private/public <p>All-</p> <p>There is a classic pattern of implementing information hiding in Javascript as described by the great Douglas Crockford here:</p> <p><a href="http://javascript.crockford.com/private.html" rel="nofollow">http://javascript.crockford.com/private.html</a></p> <p>I am also aware of another one I demonstrate here: <a href="http://jsfiddle.net/TvsW6/4/" rel="nofollow">http://jsfiddle.net/TvsW6/4/</a></p> <p>And summarized as such:</p> <pre><code>function LogSystem(anotherPrivateVar) { //. . var _setting1; this.setting2; function _printLog(msg) { $("#" + _divId).append(msg + "<br/>"); }; return { printLog :function(msg) { console.log("PRINTING:" + msg); _printLog(msg); }, logSetting_pub: function() { this.printLog("PUB: Setting1 is: " + _setting1); this.printLog("PUB: Setting2 is: " + this.setting2); } //.. }; }; </code></pre> <h2>QUESTIONS</h2> <p>Are there any other patterns beside these two that implement public and private methods and members in JavaScript? And are there names for these two patterns? And do you have a preference for the two (or more!)</p> <p>Thank you so much for your help. I am finding that knowing advanced topics in raw JavaScript are rare skills and I'd like to have them!</p> |
13,138,156 | 0 | <p>If you need to avoid the final slide back to the first and just restart, I would suggest a slight change over Pushpesh's answer:</p> <pre><code>$(document).ready(function() { var currentPosition = 0; var slideWidth = 500; var slides = $('.slide'); var numberOfSlides = slides.length; var slideShowInterval; var speed = 900; var lastSlideReached = false; slides.wrapAll('<div id="slidesHolder"></div>'); slides.css({ 'float' : 'left' }); $('#slidesHolder').css('width', slideWidth * numberOfSlides); slideShowInterval = setInterval(changePosition, speed); function changePosition() { if( ! lastSlideReached ) { if(currentPosition == (numberOfSlides-1)) { lastSlideReached = true; } else { currentPosition++; } moveSlide(); } else { resetSlide() } } function moveSlide() { $('#slidesHolder').animate({'marginLeft' : slideWidth*(-currentPosition)}); } function resetSlide(){ currentPosition = 0; $('#slidesHolder').css('marginLeft', currentPosition ); lastSlideReached = false; } </code></pre> <p>});</p> <p>cheers</p> |
17,220,303 | 0 | GCC - error while compiling <p>I try to create an exe program, by compiling codes in assembler and C:</p> <p>gcc -m32 aaa aaa.s aaa.c</p> <p>And I get an error:</p> <p>gcc: aaa : No such file or directory</p> <p>In C file a only include stdio.h. I've read that the problem might be that gcc can't find this library, but i'm not sure if that's the case and even if so, what should I do to make it work?</p> |
19,192,220 | 0 | <p>There's no need for inheritance here. Just use <code>std::function</code> to store the member function pointers and <code>std::bind</code> to bind together the member function pointer and the object instance.</p> <pre><code>#include <functional> #include <map> #include <string> #include <iostream> struct Apple { void Red () { std::cout << "aa\n"; } }; struct Orange { void Blue () { std::cout << "bb\n"; } }; int main() { std::map<std::string, std::function<void()>> m; Apple a; Orange o; m["apple"] = std::bind(&Apple::Red, a); m["orange"] = std::bind(&Orange::Blue, o); m["apple"](); m["orange"](); } </code></pre> <p>Output:</p> <pre><code>aa bb </code></pre> |
1,721,525 | 0 | <p>No, you can't, but you can pass the <code>:allow_nil => true</code> option to return nil if the master is nil.</p> <pre><code>class User < ActiveRecord::Base delegate :company, :to => :master, :allow_nil => true # ... end user.master = nil user.company # => nil user.master = <#User ...> user.company # => ... </code></pre> <p>Otherwise, you need to write your own custom method instead using the delegate macro for more complex options.</p> <pre><code>class User < ActiveRecord::Base # ... def company master.company if has_master? end end </code></pre> |
5,667,859 | 0 | <p>Use the same genre array that backs the genre tables as the data source for the modal table. In the modal table didSelectRowWIthIndexPath, get the genre string from that array. Now you have lots of choices for how to get the genre item back to your detail table view controller. You could post a notification, you could use a KeyValue Observer, you could pass a reference to the detail VC to the modal and then the modal can set an exposed attribute on the detail VC, etc. Then the detail vc would add that genre value to whatever array is back it's data, and then you call reloadData on the detail VC table. Your modal VC would have to do something like [navigationController popViewController:animated] to dismiss itself.</p> |
11,052,078 | 0 | SQL Server factors that can contribute to high CPU usage <p>I am trying to figure out or enlist factors that contribute to persistent high CPU utilization related to SQL Server</p> <p>Here are few that I came up with</p> <p>a) Compilation or Frequent Recompilation of stored procs or queries</p> <p>b) Poor performing queries that perform huge sort or ended up using Hash Join </p> <p>c) Parallelism (multiple threads are span so it can keep CPU busy)</p> <p>d) Looping construct in T-SQL for e.g. WHILE Loop or use of CURSOR</p> <p>e) Missing or inappropriate indexes that leads to table scan</p> <p>What are other SQL server operations can lead for a high CPU use? </p> |
8,435,774 | 0 | <p>Check out <a href="http://incubator.apache.org/lucene.net/" rel="nofollow">lucene.net</a>. While it won't directly integrate with your collection you can index things in memory using the RAMDirectory. </p> |
21,981,708 | 0 | Grails - How to check, if a link is pointed to correct location using Geb? <p>I have a link <code><a herf="redirect_url" class="class_name">link</a></code> that is pointed to some page. How can i check if, the link is pointed to correct location using Geb?</p> |
16,984,929 | 0 | double array in cell, how to indexing? <p>I have an cell including array as below format</p> <pre><code>a{x,y,z}(i,j) </code></pre> <p>a is 3 dimensional cell and each cell have i*j array</p> <pre><code>a <79x95x68 cell> val(:,:,1) = Columns 1 through 2 [6x6 double] [6x6 double] [6x6 double] [6x6 double] [6x6 double] [6x6 double] </code></pre> <p>i want to rearrange that as below format</p> <pre><code>a{i,j}(x,y,z) </code></pre> <p>how to? any good idea? i have to do iteration?</p> <p>matlab say, a{:,:}(x,y,z) is bad cell referencing.........</p> |
37,010,539 | 0 | Wrong button sizes while using wpf xceed toolkit wizard <p>I'm using the wizard from the wpf xceed toolkit. The problem is that the buttons are not the same sizes. All examples I can find show the buttons the same sizes. When I use it, the Cancel and Finish buttons are larger, and the Cancel button is clipped on the left side. Has anyone else experienced this, and do you have solutions? </p> <p>Thanks.</p> |
33,479,106 | 0 | <p>You never define <code>data_from_file</code>, you just try to read from it in the <code>contects_from_file</code> method.</p> <p>Perhaps you meant <code>numbers_from_file</code> instead of <code>data_from_file</code>?</p> |
33,538,956 | 0 | <p>The syntax as the following:</p> <pre><code>ObjectName obj=Class.forName("object name full name").newInstance(); </code></pre> <p>For example, you have class named Car, which is resided in com.toyota package. Then you can instantiate Car object using the following statement:</p> <pre><code>Car car=(Car)Class.forName("com.toyota.Car").newInstance(); </code></pre> |
8,191,465 | 0 | <p>I don't think <code>ping</code> is a useful test -- ICMP packets are often dropped on the floor these days -- it isn't the reliable diagnostic that it once was. Sure, if it responds, you've got that -- but if you get a timeout, the most likely answer is a firewall (perhaps Amazon's group policies) <code>DROP</code>s the packet on the floor.</p> <p>Incidentally:</p> <pre><code>$ host bret-truchan.com $ host www.bret-truchan.com www.bret-truchan.com is an alias for bret-truchan.com.s3-website-us-east-1.amazonaws.com. bret-truchan.com.s3-website-us-east-1.amazonaws.com is an alias for s3-website-us-east-1.amazonaws.com. s3-website-us-east-1.amazonaws.com has address 207.171.163.1 $ HEAD www.bret-truchan.com 404 Not Found Date: Sat, 19 Nov 2011 02:35:15 GMT Server: AmazonS3 Client-Date: Sat, 19 Nov 2011 02:35:15 GMT Client-Peer: 207.171.163.213:80 Client-Response-Num: 1 Client-Transfer-Encoding: chunked X-Amz-Error-Code: NoSuchBucket X-Amz-Error-Detail-BucketName: www.bret-truchan.com X-Amz-Error-Message: The specified bucket does not exist X-Amz-Id-2: MKHMddVEYia5cV0iU33QLg7vt6FgM69jyu+jKjTsh1aVuUR8seGwQQT2sfZrSlu9 X-Amz-Request-Id: 6681133093178B5F </code></pre> <p>If anything, it looks like the hostname <code>www.bret-truchan.com</code> is being used for the bucket -- and you said the bucket was named <code>bret-truchan.com</code> instead. That is probably the reason for the <code>404</code> response.</p> <p>But the dropped <code>ping</code> packets are probably due to Amazon's firewalling.</p> |
38,485,812 | 0 | <p>I believe this is happening because of caching in Google Play App. Usually, Google Play app cache refreshes once every 24 hours. </p> <p>@poqueque's solution works if you want to clear cache through command line. You can also goto App settings on the phone and clear data/cache of Google Play app. Make sure to log back into your Google Play account after you do this. </p> <p>Does anyone know a solution to force refresh Google Play cache through code or query purchases without using cache to get up to date info? </p> |
27,561,164 | 0 | <p>Here is an answer using <a href="http://jsoup.org/download" rel="nofollow">Jsoup</a> and <a href="http://mvnrepository.com/artifact/org.json/json/20140107" rel="nofollow">JSON</a> as dependencies: </p> <pre><code>final String HTML = "<table cellspacing=\"0\" style=\"height: 24px;\">\r\n<tr class=\"tr-hover\">\r\n<th rowspan=\"15\" scope=\"row\">Network</th>\r\n<td class=\"ttl\"><a href=\"network-bands.php3\">Technology</a></td>\r\n<td class=\"nfo\"><a href=\"#\" class=\"link-network-detail collapse\">GSM</a></td>\r\n</tr>\r\n<tr class=\"tr-toggle\">\r\n<td class=\"ttl\"><a href=\"network-bands.php3\">2G bands</a></td>\r\n<td class=\"nfo\">GSM 900 / 1800 - SIM 1 & SIM 2</td>\r\n</tr> \r\n<tr class=\"tr-toggle\">\r\n<td class=\"ttl\"><a href=\"glossary.php3?term=gprs\">GPRS</a></td>\r\n<td class=\"nfo\">Class 12</td>\r\n</tr> \r\n<tr class=\"tr-toggle\">\r\n<td class=\"ttl\"><a href=\"glossary.php3?term=edge\">EDGE</a></td>\r\n<td class=\"nfo\">Yes</td>\r\n</tr>\r\n</table>"; Document document = Jsoup.parse(HTML); Element table = document.select("table").first(); String arrayName = table.select("th").first().text(); JSONObject jsonObj = new JSONObject(); JSONArray jsonArr = new JSONArray(); Elements ttls = table.getElementsByClass("ttl"); Elements nfos = table.getElementsByClass("nfo"); JSONObject jo = new JSONObject(); for (int i = 0, l = ttls.size(); i < l; i++) { String key = ttls.get(i).text(); String value = nfos.get(i).text(); jo.put(key, value); } jsonArr.put(jo); jsonObj.put(arrayName, jsonArr); System.out.println(jsonObj.toString()); </code></pre> <p>Output (formatted):</p> <pre><code>{ "Network": [ { "2G bands": "GSM 900 / 1800 - SIM 1 & SIM 2", "Technology": "GSM", "GPRS": "Class 12", "EDGE": "Yes" } ] } </code></pre> |
7,849,410 | 0 | Already initialized constant warnings <p>I'm using Nokogiri code to extract text between HTML nodes, and getting these errors when I read in a list of files. I didn't get the errors using simple embedded HTML. I'd like to eliminate or suppress the warnings but don't know how. The warnings come at the end of each block:</p> <pre><code>extract.rb:18: warning: already initialized constant EXTRACT_RANGES extract.rb:25: warning: already initialized constant DELIMITER_TAGS </code></pre> <p>Here is my code:</p> <pre><code>#!/usr/bin/env ruby -wKU require 'rubygems' require 'nokogiri' require 'fileutils' source = File.open('/documents.txt') source.readlines.each do |line| line.strip! if File.exists? line file = File.open(line) doc = Nokogiri::HTML(File.read(line)) # suggested by dan healy, stackoverflow # Specify the range between delimiter tags that you want to extract # triple dot is used to exclude the end point # 1...2 means 1 and not 2 EXTRACT_RANGES = [ 1...2 ] # Tags which count as delimiters, not to be extracted DELIMITER_TAGS = [ "h1", "h2", "h3" ] extracted_text = [] i = 0 # Change /"html"/"body" to the correct path of the tag which contains this list (doc/"html"/"body").children.each do |el| if (DELIMITER_TAGS.include? el.name) i += 1 else extract = false EXTRACT_RANGES.each do |cur_range| if (cur_range.include? i) extract = true break end end if extract s = el.inner_text.strip unless s.empty? extracted_text << el.inner_text.strip end end end end print("\n") puts line print(",\n") # Print out extracted text (each element's inner text is separated by newlines) puts extracted_text.join("\n\n") end end </code></pre> |
22,385,125 | 0 | <p>The problem was with my properties. When I've omited <code>set</code>, I got this error...</p> <pre><code>[DataContract] public class YoloClassRO { private int k = 42; [DataMember] public int K { get { return k; } } } [DataContract] public class YoloClassRW { private int k = 42; [DataMember] public int K { get { return k; } set { k = value; } } } </code></pre> <p><code>YoloClassRW</code> - works</p> <p><code>YoloClassRO</code> - not</p> <p>Well described <a href="http://stackoverflow.com/questions/1873741/wcf-exposing-readonly-datamember-properties-without-set">Exposing readonly DataMember properties without set</a>.</p> |
40,149 | 0 | <p>Something like this should be good:</p> <pre><code>MyConfigurationDialog dialog = new MyConfigurationDialog(); //Copy the dictionary so that the dialog can't mess with our settings dialog.Settings = new Dictionary(existingSettings); if(DialogResult.OK == dialog.Show()) { //grab the settings that the dialog may have changed existingSettings["setting1"] = dialog.Settings["setting1"]; existingSettings["setting2"] = dialog.Settings["setting2"]; } </code></pre> |
17,252,426 | 0 | <p>WinRT has <code>GetFileFromPathAsync()</code> method of class <code>StorageFile</code>, but you can not open any file with that method. Only option you have is to use <code>StorageItemMostRecentlyUsedList</code> class. Which is useful to get the token for all the files that was saved to either <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.accesscache.storageapplicationpermissions.mostrecentlyusedlist" rel="nofollow">most recently used files list</a> or <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.accesscache.storageapplicationpermissions.futureaccesslist" rel="nofollow">future access list</a>. To save token for the which was accessed from <code>FileOpenPicker</code>, you need to use <code>StorageApplicationPermissions</code> class. Here I'm giving you how to save token for a file & how to retrieve token for & access that file.</p> <p>To save token</p> <pre><code>FileOpenPicker openPicker = new FileOpenPicker(); openPicker.ViewMode = PickerViewMode.Thumbnail; openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; openPicker.FileTypeFilter.Add(".jpg"); openPicker.FileTypeFilter.Add(".jpeg"); openPicker.FileTypeFilter.Add(".png"); StorageFile file = await openPicker.PickSingleFileAsync(); if (file != null) { // Add to most recently used list with metadata (For example, a string that represents the date) string mruToken = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file, "20130622"); // Add to future access list without metadata string faToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file); } else { // The file picker was dismissed with no file selected to save } </code></pre> <p>To retrieve file using token</p> <p><s>StorageItemMostRecentlyUsedList MRU = new StorageItemMostRecentlyUsedList();</p> <p>StorageFile file = await MRU.GetFileAsync(token);</s></p> <p><strong>UPDATE</strong></p> <pre><code>await StorageApplicationPermissions.MostRecentlyUsedList.GetFileAsync(token); </code></pre> |
15,832,273 | 0 | <p>Maybe set up a regular view controller. Then add a collection view, make the cell very large. In that collection view cell add a label on the side (this will become the light blue box). Then right next to it add a table view with sections. The header would be the red and dark blue area.</p> <p>This would work, but you need the flexibility of starting as a view controller, and doing the collection and table view through delegates</p> |
8,014,250 | 0 | <p>The problem is caused because the address you use to start tomcat (in normal or debug mode) is already taken by another process.</p> <p>You need to check the ports you are using in the you conf file (e.g. your_TOMCAT_HOME_DIR_/conf/server.xml), to see if they are not already used </p> <p>Here you can look at the port used for</p> <ul> <li>starting Tomcat: default value 8080 </li> <li>stopping Tomcat: default value 8005</li> <li>using with AJP protocoll: default value 8009</li> </ul> <p>and if you are using Tomcat in debug mode (through jdpa or jdwp ), please make sure to use a different port than all the previous configured ports</p> |
3,326,797 | 0 | <p>You could add <code>line-height:30px;</code> to your <code>li</code> elements, (<em>the same as the height of the menu bar</em>)</p> <p><strong><a href="http://www.jsfiddle.net/d5jTf/" rel="nofollow noreferrer">Demo</a></strong></p> |
23,504,102 | 0 | <p>Instead of <code>Redirect</code> you can use <code>RedirectMatch</code> directive for its regex capability:</p> <pre><code>RedirectMatch 301 ^/cars/?$ https://www.mydomain.com/cars/carshome/ </code></pre> |
24,668,733 | 0 | <p>I made a silly mistake: I was using the wrong root XSD.</p> <p>As such, the solution was to define a root XSD containing the DocHeader.xsd and the DocBody.xsd as components.</p> |
15,030,909 | 0 | <p>CallumD's solution worked for me, and seemed the most consistent with the techniques recommended in the rest of Michael Hartl's tutorial. But I wanted to tighten up the syntax a little to make it more consistent with the other specs in the same tutorial:</p> <pre><code>it "should not be able to delete itself" do expect { delete user_path(admin) }.not_to change(User, :count) end </code></pre> |
10,152,052 | 0 | <p>You can send a direct update statement to the Oracle Engine in this way.</p> <pre><code>using (OracleConnection cnn = new OracleConnection(connString)) using (OracleCommand cmd = new OracleCommand("UPDATE TABLE1 SET BIRHDATE=:NewDate WHERE ID=:ID", cnn)) { cmd.Parameters.AddWithValue(":NewDate", YourDateTimeValue); cmd.Parameters.AddWithValue(":ID", 111); cnn.Open(); cmd.ExecuteNonQuery(); } </code></pre> <p>EDIT:</p> <p>If you don't know which fields are changed (and don't want to use a ORM Tool) then you need to keep the original DataSource (a datatable, dataset?) used to populate initially your fields. Then update the related row and use a OracleDataAdapter.</p> <pre><code>using(OracleConnection cnn = new OracleConnection(connString)) using (OracleCommand cmd = new OracleCommand("SELECT * FROM TABLE1 WHERE 1=0", cnn)) { OracleAdapter adp = new OracleDataAdapter(); adp.SelectCommand = cmd; // The OracleDataAdapter will build the required string for the update command // and will act on the rows inside the datatable who have the // RowState = RowState.Changed Or Inserted Or Deleted adp.Update(yourDataTable); } </code></pre> <p>Keep in mind that this approach is inefficient because it requires two trip to the database. The first to discover your table structure, the second to update the row/s changed. Moreover, for the OracleDataAdapter to prepare the UpdateCommand/InsertCommand/DeleteCommand required, it needs a primary key in your table.</p> <p>On the contrary, this is handy if you have many rows to update.</p> <p>The last alternative (and probably the fastest) is a StoredProcedure, but in this case you need to go back to my first example and adapt the OracleCommand to use a StoredProcedure, (Add all fields as parameters, change CommandType to CommandType.StoredProcedure and change the text of the command to be the name of the StoredProcedure). Then the StoredProcedure will choose which fields need to be updated. </p> |
3,698,683 | 0 | <p>You should replace the ArrayList with an ObservableCollection<string> which will communicate to the ListBox when its contents change.</p> |
22,352,969 | 0 | <p>You just need to specify the <code><th></code> tag when you <code>bind</code> the <code>click event</code>.</p> <p><em>Updated link:</em></p> <p>Here is <strong><a href="http://jsfiddle.net/VB5um/1/" rel="nofollow">a simple example.!</a></strong></p> <p><em>Another Update</em></p> <p>and here is <strong><a href="http://jsfiddle.net/Sbb5Z/1283/" rel="nofollow">another example</a></strong> according your requirement you only need to change</p> <p>this:</p> <pre><code>$(document).bind('contextmenu', function (event){ $("#contextmenu").kendoMenu({ position: "relative", orientation: "vertical"}).show(); event.preventDefault(); }); </code></pre> <p>to this:</p> <pre><code>$(".k-header").bind('contextmenu', function (event){ $("#contextmenu").kendoMenu({ position: "relative", orientation: "vertical"}).show(); event.preventDefault(); }); </code></pre> |
23,753,887 | 0 | While converting date string into Date object getting NaN-NaN-NaN in Jquery? <p>Jquery + rails 4 + Mac + Safari</p> <pre><code><script> function get_next_week_schedule(pre_date_index){ var date = $('#next_week_'+ pre_date_index).attr('value'); alert(date); //2014-06-02 var myDate = new Date(date); alert(myDate); // NaN-NaN-NaN } </script> </code></pre> <p>This script is running on Mozilla and crome but while using Mac OS and Safari Browser its showing NaN-NaN-NaN while conversion of date string to Date Object. </p> |
29,126,463 | 0 | Angularjs $scope is confusing me <p>I really need some help here... I´m trying for hours now and can´t get it to work...</p> <p>I have a .json file with 100 products like this:</p> <pre><code>[{ "ean": "3613132010420", "brand": "NewBrand", "desc": "A description", "feature1": "", "feature2": "", "feature3": "", "feature4": "", "feature5": "", "img": "", "metric": { "gender": "female", }, "score":"" }, { "ean": "3613132010420", "brand": "NewBrand", "desc": "A description", "feature1": "", "feature2": "", "feature3": "", "feature4": "", "feature5": "", "img": "", "metric": { "gender": "female", }, "score":"" }] </code></pre> <p>I read the json with $http and put everything in $scope.products. The data is shown in a list, everything is fine. Now I want to filter the products and alter the score variable (after swipe on a option slider). </p> <p>The view should then also be updated due to the angular data-binding.</p> <p>How can I change this variable in the $scope? This is what I tried and nothing works:</p> <pre><code>$('.find-style-slider .slick-list').bind('touchstart click', function(){ angular.forEach($scope.products, function(value, key) { $scope.products[key].score = '25'; //nothing happens var obj = { score: '25' }; $scope.products[key].push(obj); //Uncaught TypeError: undefined is not a function $scope.products.splice(key, 0, obj); //no error but $scope variable does not change $scope.products[key].unshift(obj); //Uncaught TypeError: undefined is not a function }); }); </code></pre> <p>Do I need to update something or $apply()? I would be thankful for any help/hint...</p> <p><strong>Edit:</strong> I think the $scope is not working like I thought.... I fill the $scope.products with a service:</p> <pre><code>productService.initDb().then(function(products) { $scope.products = products; }); </code></pre> <p>When I put this </p> <pre><code> var obj = { score: '25' }; $scope.products.splice(0, 0, obj); </code></pre> <p>INSIDE the initDb function then the first elements gets updated! But not outside.</p> <p>The question is now: WHY? And how can I access the $scope.products from outside the service function?</p> <p>I thought the $scope is the same for the whole controller... <em>confused</em></p> |
15,691,866 | 0 | <p>Basically you need to find the li.k-item and pass it to the select method. Here comes the jQuery:</p> <pre><code>var ts = $('#tabstrip').data().kendoTabStrip; var item = ts.tabGroup.find(':contains("What you look for")'); ts.select(item); </code></pre> |
6,342,781 | 0 | javax.validation.ConstraintValidationException: validation failed for classes <p>I am developing a web application using <code>Spring 3.1</code>, <code>Hibernate 3</code> and <code>Hibernate Validator</code> 4 in the backend. I'm using <code>JSR 303</code> for the validation. This is done via annotations in the domain class.</p> <pre><code> public class StaffMember implements Serializable { @NotNull @Size(max = 30) // All letters, spaces and hyphens are allowed @Pattern(regexp = "^[^0-9_.]+$", message = ("Es sind nur Buchstaben, Leerzeichen und Bindestrich erlaubt.")) private String firstname; } </code></pre> <p>I have written a test class for testing the CRUD operations in the DAO class. This class runs without errors for valid data. Now I want to edit an existing object. Therefore I change the first name. I specify an invalid name because I want to write a negative test case.</p> <pre><code>// Allows Spring to configure the test @RunWith(SpringJUnit4ClassRunner.class) // Define which configuration should be used @ContextConfiguration(locations = { "classpath:portal-test.xml" }) @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback=false) // All methods are transactional @Transactional public class StaffMemberDAOTest { private StaffMember staffMember, nextStaffMember; @Autowired private StaffMemberDAO staffMemberDao; @Autowired private Validator validator; @Test(expected = ConstraintViolationException.class) @Transactional @Rollback(true) public void testUpdateStaffMemberWithInvalidData() { System.out.println("--- update a staffMember (with invalid data) ---"); // check if database is empty Assert.assertEquals(0, staffMemberDao.getAllStaffMembers().size()); // add staffMember createStaffMember(); // validate Set<ConstraintViolation<StaffMember>> violations = validator .validate(staffMember); // object is valid if(violations.size() == 0) { staffMemberDao.addStaffMember(staffMember); } else { System.out.println("Object is not valid."); } // get staffMember StaffMember staffMemberExpected = staffMemberDao.getStaffMember(staffMember.getStaffMemberID()); // check data Assert.assertEquals(staffMember, staffMemberExpected); // edit data staffMemberExpected.setFirstname("George No 1"); // validate Set<ConstraintViolation<StaffMember>> violationsUpdate = validator .validate(staffMemberExpected); // object is valid if(violationsUpdate.size() == 0) { staffMemberDao.editStaffMember(staffMemberExpected); } else { System.out.println("Object is not valid."); } } </code></pre> <p>The system rightly raises the following error message: javax.validation.ConstraintValidationException In this case the expected exception must to be indicated. In JUnit 4 is this possible about @Test(expected). </p> <p>I do this but i get the following error message: </p> <pre><code>java.lang.AssertionError: Expected exception: javax.validation.ConstraintViolationException at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:32) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:236) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) javax.validation.ConstraintViolationException: validation failed for classes [de.softwareinmotion.portal.domain.StaffMember] during update time for groups [javax.validation.groups.Default, ] at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:155) at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreUpdate(BeanValidationEventListener.java:102) at org.hibernate.action.EntityUpdateAction.preUpdate(EntityUpdateAction.java:235) at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:86) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:185) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) at org.hibernate.event.def.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:64) at org.hibernate.impl.SessionImpl.autoFlushIfRequired(SessionImpl.java:1185) at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1261) at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102) at de.softwareinmotion.portal.persistence.StaffMemberDAO.getAllStaffMembers(StaffMemberDAO.java:37) at de.softwareinmotion.portal.persistence.StaffMemberDAO$$FastClassByCGLIB$$ae2a690a.invoke(<generated>) at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:688) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:621) at de.softwareinmotion.portal.persistence.StaffMemberDAO$$EnhancerByCGLIB$$8fbc7a01.getAllStaffMembers(<generated>) at de.softwareinmotion.portal.persistence.StaffMemberDAOTest.tearDown(StaffMemberDAOTest.java:542) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:37) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:236) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) </code></pre> <p>Here is my portal-test.xml file:</p> <pre><code><?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <context:property-placeholder location="classpath:jdbcTest.properties" /> <context:annotation-config/> <tx:annotation-driven transaction-manager="transactionManager"/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${db.driverClass}" /> <property name="url" value="${db.jdbcUrl}" /> <property name="username" value="${db.user}" /> <property name="password" value="${db.password}" /> </bean> <!-- Hibernate config --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="annotatedClasses"> <list> <!-- Each domain class must be listed here --> <value>de.softwareinmotion.portal.domain.StaffMember</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">create</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- Necessary for validation --> <bean name="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <!-- <property name="validationMessageSource"> <ref bean="resourceBundleLocator"/> </property> --> </bean> <!-- <bean name="resourceBundleLocator" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="/WEB-INF/validation-messages" /> </bean> --> <!-- Each DAO object must be declared here! --> <bean id="staffMemberDao" class="de.softwareinmotion.portal.persistence.StaffMemberDAO"> <property name="sessionFactory" ref="sessionFactory"/> </bean> </beans> </code></pre> <p>What I'm doing wrong? Can anybody help me?</p> |
27,918,363 | 0 | redirect() is giving header() error even though nothing is being output to the browser <p>So basically, I'm getting an error message which reads:</p> <blockquote> <p>Cannot modify header information - headers already sent by (output started at D:\xampp\htdocs\star\application\controllers\process_login.php:1)</p> </blockquote> <p>I know what is the meaning of that error but I can't figure out where the output was started. I've no whitespaces in the <code>process_login.php</code> file nor anything <code>echo</code>-ed out as well.</p> <p>I access the login form via the <code>http://localhost/star/index.php/star</code> URL</p> <p><strong>star Controller</strong></p> <pre><code>class Star extends CI_Controller { public function index() { $this->load->view('login'); } } </code></pre> <p>On form submit, I'm posting to the process_login Controller.</p> <p><strong>process_login Controller (it doesn't even have a closing tag to avoid whitespace)</strong></p> <pre><code><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Process_login extends CI_Controller { public function index() { $this->load->library('form_validation'); $this->form_validation->set_rules('userid', 'Username', 'required'); $this->form_validation->set_rules('password', 'Password', 'required|callback_check_valid['.trim($this->input->post('userid')).']'); if ($this->form_validation->run() == FALSE) { $this->load->view('login'); } else { redirect('dashboard'); // this is the problem area } } public function check_valid($pw, $un) { if($un) { $this->load->model('user'); if($this->user->is_authenticated($un, $pw)) { return true; } else { $this->form_validation->set_message('check_valid', 'Invalid login. Please try again!'); return false; } } } } /* End of file process_login.php */ </code></pre> <p><strong>dashboard Controller</strong></p> <pre><code>class Dashboard extends CI_Controller { public function index() { $this->load->view('admin_area', array('page_title'=>'Dashboard'); } } </code></pre> <p>I'm assuming the <code>process_login.php:1</code> means the output started from Line 1 of that file? If so, I don't have any output or whitespace in that file. Then why is it that I'm getting the error?</p> <h2>Debugging</h2> <p>After removing everything from the <code>process_login.php</code> file, I'm still getting the same error. This is what the stripped down version of the file looks like:</p> <pre><code><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Process_login extends CI_Controller { public function index() { redirect('dashboard'); } } </code></pre> <p>I'm starting to think the problem might be in some other file which are being loaded before this controller file. Hence, it's saying that the output started from <strong>Line 1</strong>.</p> |
8,441,221 | 0 | how to override the page being viewed <p>I copied the pages_controller.php to my app/controllers folder, then i created a view and placed it under pages. I have a custom_layout.ctp under views. The problem I am having is that the view I placed under pages is displaying with the default look of cakephp but i want to use my custom_layout. I tried by adding the last line on this code but nothing...</p> <pre><code><?php /** * Static content controller. * * This file will render views from views/pages/ * * PHP versions 4 and 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package cake * @subpackage cake.cake.libs.controller * @since CakePHP(tm) v 0.2.9 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Static content controller * * Override this controller by placing a copy in controllers directory of an application * * @package cake * @subpackage cake.cake.libs.controller * @link http://book.cakephp.org/view/958/The-Pages-Controller */ class PagesController extends AppController { /** * Controller name * * @var string * @access public */ var $name = 'Pages'; /** * Default helper * * @var array * @access public */ var $helpers = array('Html', 'Session'); /** * This controller does not use a model * * @var array * @access public */ var $uses = array(); /** * Displays a view * * @param mixed What page to display * @access public */ function display() { $path = func_get_args(); $count = count($path); if (!$count) { $this->redirect('/'); } $page = $subpage = $title_for_layout = null; if (!empty($path[0])) { $page = $path[0]; } if (!empty($path[1])) { $subpage = $path[1]; } if (!empty($path[$count - 1])) { $title_for_layout = Inflector::humanize($path[$count - 1]); } $this->set(compact('page', 'subpage', 'title_for_layout')); $this->render(implode('/', $path)); $this->layout = 'custom_layout'; } } </code></pre> |
15,826,343 | 0 | Change row color of gridview by database Values <p>I am making a application in asp.net which shows the values in gridview from the database.In database i am having a colmn named as StatusId which has a value of 1 or 2 or 3.</p> <p>I tried to show the grid view rows in different color by their statusId values. But it never works. How can i do it in asp.net.</p> <p>Here is my code</p> <pre><code>protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { Connection.Open(); SqlCommand Command1 = Connection.CreateCommand(); Command1.CommandText = "Select statusColor from status where statusId=(Select statusId from fileInfo where userId=(Select userId from userInfo where email='" + Session["email"].ToString() + "'))"; for (int i = 0; i < GridView1.Rows.Count; i++) { using (SqlDataReader reader = Command1.ExecuteReader()) { while (reader.Read()) { statusId = reader["statusColor"].ToString(); } GridView1.RowStyle.BackColor = Color.FromName(statusId); } } foreach (GridViewRow row in GridView1.Rows) { row.BackColor = Color.Green; } SqlCommand com = new SqlCommand("gridcolor", Connection); com.CommandType = CommandType.StoredProcedure; com.Parameters.AddWithValue("@statusId", statusId); com.Parameters.Add("@statusColor", SqlDbType.NVarChar, 30); com.Parameters["@statusColor"].Direction = ParameterDirection.Output; com.ExecuteNonQuery(); string msg = (string)com.Parameters["@statusColor"].Value; Connection.Close(); } </code></pre> <p>What is the mistake i am doing here?</p> <p><strong>EDIT</strong></p> <p>I have the color codes which are stored in the database named as statusColor. I have to apply those color to these status.</p> |
30,085,992 | 0 | <p>I found this:</p> <p><a href="https://github.com/facebook/stetho/issues/42" rel="nofollow">https://github.com/facebook/stetho/issues/42</a></p> <p>TL;DR: If you are using proguard add this to your config:</p> <p><code>-keep class com.facebook.stetho.** {*;}</code></p> |
13,755,211 | 0 | <p>What happens if you used the following instead:</p> <pre><code>$(this).attr('id') == "upright" </code></pre> |
13,869,598 | 0 | <p>The bulk of the integer operations for 32B vectors are in the AVX2 extension (not the initial AVX extension, which is almost entirely floating-point operations). Intel's most recent <a href="http://software.intel.com/sites/default/files/m/f/7/c/36945" rel="nofollow">AVX Programming Reference</a> has the complete details; you may also want to look at Intel's <a href="http://software.intel.com/en-us/blogs/2011/06/13/haswell-new-instruction-descriptions-now-available" rel="nofollow">blog post</a> announcing some of the details.</p> <p>Unfortunately, you cannot use the floating-point min or max operations to simulate those operations on integer data, as a significant number of integers map to NaN values when interpreted as floating-point data, and the semantics for NaN comparisons don't do what you would want for integer comparisons (you also would need to deal with the fact that floating-point encodings are sign-magnitude, so the ordering of negative values is "reversed", and that +0 and -0 compare equal).</p> |
19,556,997 | 0 | <pre><code>var tomatch = "nn"; var sets= new Array() sets[0]='nnd'; sets[1]='nndha'; sets[2]='ch'; sets[3]='gn'; for(var i=0; i < sets.length ; i++){ if(sets[i].indexof(tomatch) !== -1){ return sets[i]; } } </code></pre> |
7,197,592 | 0 | <p>This strike me as odd- Why do you use</p> <pre><code>label.text = [[NSString alloc] initWithString:@"Manufacture :"]; </code></pre> <p>as opposed to</p> <pre><code>label.text = @"Manufacture :"; </code></pre> <p>The way it is, your not releasing your strings. using the @"xxx" short hand creates a string that is autoreleased. Not confident that this is the cause of your problem but screwy memory mgmt with strings can produce effects like your seeing. So cleaning it up would be a good start.</p> <p>Also, make sure that in IB you made the cell have a reference to the file owners' vehicleSearchCell property. More of a stab in the dark.</p> |
28,662,875 | 0 | C++ sending Joystick directional input to program <p>I'm trying to spoof a PS3 controller and send analog stick directional input to a specific program, but i can't figure out how the INPUT.hi struct works. I can send keypresses over with</p> <pre><code>INPUT keys; keys.type = INPUT_KEYBOARD; keys.ki.dwFlags = KEYEVENTF_SCANCODE; keys.ki.wScan = 0x11;//hex for 'w' key SendInput(1, &keys, sizeof(INPUT)); Sleep(60);//delay to ensure game doesnt drop keypress keys.ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP; SendInput(1, &keys, sizeof(INPUT)); </code></pre> <p>and i believe that sending over joystick commands would work similarly, something like </p> <pre><code>INPUT analogSticks; analogSticks.type = INPUT_HARDWARE; analogSticks.hi.uMsg = WM_INPUT; analogSticks.hi.wParamL = //what are the values for these? analogSticks.hi.wParamH = //what are the values for these? SendInput(1, &analogSticks, sizeof(INPUT)); </code></pre> <p>but trying out different values for wParamL and wParamH doesnt do anything. Am i doing something wrong, and/or is there a way i can input specific angles, say, if i were to put in 45, i could generate a joystick signal that would correspond to that angle, much like i can do with keypresses?</p> |
5,266,486 | 0 | Android gps : how to check if a certain point has been reached? <p>I am working on an Android app and I need to make sure that the device has reached a certain point described with lat and lon. The only thing that I can think of is to have something like that :</p> <pre><code> Location initLoc = theManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); double lat = initLoc.getLatitude(); double lon = initLoc.getLongitude(); MyPoint firstPoint = getPoints().get(0); double dist = CalcHelper.getDistance1(lat, lat, firstPoint.getLat(), firstPoint.getLon()); while(dist > 30){ initLoc = theManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); lat = initLoc.getLatitude(); lon = initLoc.getLongitude(); dist = CalcHelper.getDistance1(lat, lon, firstPoint.getLat(), firstPoint.getLon()); } </code></pre> <p>But that causes the program to crash. I would be very appreciative if you could lead me to the right direction here.</p> <p>Let me take the opportunity to ask a further question. As I said I am new to Android and GPS and having in mind there is little documentation and information on how to properly develop applications that work with GPS I am working in blind basically. So my question is:</p> <p>This is how the onLocationChanged method looks like:</p> <pre><code> public void onLocationChanged(Location location) { double lat = location.getLatitude(); double lon = location.getLongitude(); MyPoint firstPoint = MainScreen.dataset.getPoints().get(0); double dist = CalcHelper.getDistance1(lat, firstPoint.getLat(),lon, firstPoint.getLon()); if(dist < 10){ Context context = getApplicationContext(); CharSequence text = "Start reached. Starting moving on track"; int duration = 6000; Toast toast = Toast.makeText(context, text, duration); toast.show(); }else{ Context context = getApplicationContext(); CharSequence text = "Distance until start: "+dist; int duration = 6000; Toast toast = Toast.makeText(context, text, duration); toast.show(); } } </code></pre> <p>What I am trying to do is to make the program determine when I have reached the start of a track I have supplied as a set of points. So, when I start the program I receive a reasonable estimate on the distance. The problem is, when I start moving, the distance does not seem to be updated, it gets updated but after moving 50meters, it says i have only moved 5 say. On the other hand, when I start the application and I am less than 10m away from the starting point, it detects it properly. So basically, while I am moving with the device, the onLocationChanged method does not seem to give me the correct location that I am now on. Can you tell me what I might be doing wrong ? </p> |
18,914,829 | 0 | Facebook login integration in my PHP code gives error <p>When I click on the Facebook login button I got this error.</p> <blockquote> <p>Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.</p> </blockquote> <pre><code>This is my website url:-http://192.168.1.234/photogallery/login.php </code></pre> <p>in my app settings i have written this Website with Facebook Login</p> <pre><code>Site URL: http://192.168.1.234/photogallery/login.php </code></pre> <p>Then what's the problem in site url?</p> <p>Thanks in advance... :)</p> <pre><code>public function getLoginUrl($params=array()) { $this->establishCSRFTokenState(); $currentUrl = $this->getCurrentUrl(); // if 'scope' is passed as an array, convert to comma separated list $scopeParams = isset($params['scope']) ? $params['scope'] : null; if ($scopeParams && is_array($scopeParams)) { $params['scope'] = implode(',', $scopeParams); } return $this->getUrl( 'www', 'dialog/oauth', array_merge(array( 'client_id' => $this->getAppId(), 'redirect_uri' => $currentUrl, // possibly overwritten 'state' => $this->state), $params)); } protected function getCurrentUrl() { if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') { $protocol = 'https://'; } else { $protocol = 'http://'; } $currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; $parts = parse_url($currentUrl); $query = ''; if (!empty($parts['query'])) { // drop known fb params $params = explode('&', $parts['query']); $retained_params = array(); foreach ($params as $param) { if ($this->shouldRetainParam($param)) { $retained_params[] = $param; } } if (!empty($retained_params)) { $query = '?'.implode($retained_params, '&'); } } // use port if non default $port = isset($parts['port']) && (($protocol === 'http://' && $parts['port'] !== 80) || ($protocol === 'https://' && $parts['port'] !== 443)) ? ':' . $parts['port'] : ''; // rebuild return $protocol . $parts['host'] . $port . $parts['path'] . $query; } </code></pre> |
17,084,305 | 0 | <p>Dear if you are working on a local server just like XAMPP or APPSERV or whatsoever you have to install mail server on you local machine </p> <p>and if you are working on a real host server make sure the the php setting in the server allow you to use mail function cuse many server has stop this function.</p> <p>so i recommend you to use smtp to send mail take a look here </p> <p><a href="http://email.about.com/od/emailprogrammingtips/qt/PHP_Email_SMTP_Authentication.htm" rel="nofollow">http://email.about.com/od/emailprogrammingtips/qt/PHP_Email_SMTP_Authentication.htm</a></p> <p>and there is a supper powerful library to send email PHPMailer </p> <p><a href="https://code.google.com/a/apache-extras.org/p/phpmailer/" rel="nofollow">https://code.google.com/a/apache-extras.org/p/phpmailer/</a></p> |
4,587,394 | 0 | <p>1) For most delegate callback methods, if you provide a parameter-accepting callback the parameter will be the "sender", i.e. the source control. You might need this parameter if you are using the same delegate method to handle the callbacks for multiple controls. Or, if you want to affect some change on the source control in the callback, and you haven't otherwise stored a pointer to it.</p> <p>2) The only time you MUST include the callback definition in the interface definition is if you want to hook up the callback using Interface Builder. If you forget the implementation itself, the callback will likely crash the app as most controls that use callback-delegate methods dont first check to see that the method exists.</p> |
29,247,890 | 0 | <p>When posting questions in future, it really helps to include the error message. Here it is.</p> <blockquote> <p>ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from attraction join ticketBooking using(attractionID)</p> </blockquote> <p>Your basic syntax error here is immediately before 'from attraction', we find</p> <pre><code> set @package1=(select(sum(ticketprice*numTickets) </code></pre> <p>The problem here is that SELECT() is not valid syntax. Correct syntax is SELECT followed by a space. This appears to be an extra unmatched bracket, so you can simply remove it like so:</p> <pre><code>delimiter // create trigger estimatedCost_bi after insert on ticketBooking for each row begin set @package1=(select sum(ticketprice*numTickets) from attraction join ticketBooking using(attractionID) join package using(packageNo) where package.packageNo=new.packageNo); </code></pre> <p>update package join ticketBooking using(packageNo)</p> <p>set estimatedCost = @package1</p> <p>where ticketBooking.packageNo=new.packageNo; end// delimiter ;</p> |
27,291,145 | 1 | A mistake in installing gensim <p>I can't install gensim successfully through many ways.For I'm a freshman in coding,it's difficult for me to understand the following information.</p> <hr> <pre><code>**C:\Python27\Lib\site-packages\gensim-0.10.3>python setup.py install Traceback (most recent call last): File "setup.py", line 22, in <module> from setuptools import setup, find_packages, Extension File "C:\Python27\lib\site-packages\setuptools\__init__.py", line 12, in <modu le> from setuptools.extension import Extension File "C:\Python27\lib\site-packages\setuptools\extension.py", line 7, in <modu le> from setuptools.dist import _get_unpatched File "C:\Python27\lib\site-packages\setuptools\dist.py", line 16, in <module> from setuptools.compat import numeric_types, basestring File "C:\Python27\lib\site-packages\setuptools\compat.py", line 19, in <module > from SimpleHTTPServer import SimpleHTTPRequestHandler File "C:\Python27\lib\SimpleHTTPServer.py", line 27, in <module> class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): File "C:\Python27\lib\SimpleHTTPServer.py", line 208, in SimpleHTTPRequestHand ler mimetypes.init() # try to read system mime.types File "C:\Python27\lib\mimetypes.py", line 358, in init db.read_windows_registry() File "C:\Python27\lib\mimetypes.py", line 258, in read_windows_registry for subkeyname in enum_types(hkcr): File "C:\Python27\lib\mimetypes.py", line 249, in enum_types ctype = ctype.encode(default_encoding) # omit in 3.x! UnicodeDecodeError: 'ascii' codec can't decode byte 0xb6 in position 6: ordinal not in range(128)** </code></pre> <hr> <p>Thanks for help!</p> |
15,876,596 | 0 | <p>Try this.</p> <p>((?<=\=)\s*N?[a-zA-Z0-9.!?#$=@&%'^+|_~-/()*{}`]+)'</p> |
6,334,498 | 0 | Recognize "Invalid" URLs without Trying to Resolve Them <p>I'm building a Facebook App which grabs the URLs from various sources in a user's Facebook acount--e.g., a user's likes.</p> <p>A problem I've encountered is that many Facebook entries have string which are not URLs in their "website" and "link" fields. Facebook does no checking on user input so these fields can essentially contain any string.</p> <p>I want to be able to process the strings in these field such that URLs like <code>"http://google.com"</code>, <code>"https://www.bankofamerica.com"</code>, <code>"http://www.nytimes.com/2011/06/13/us/13fbi.html?_r=1&hp"</code>, <code>"bit.ly"</code>, <code>"www.pbs.org"</code> are all accepted.</p> <p>And all the strings like <code>"here is a random string of text the user entered"</code>, <code>"here'\s ano!!! #%#$^ther weird random string"</code> are all rejected.</p> <p>It seems to me the only way to be "sure" of a URL is to attempt to resolve it, but I believe that will be prohibitively resource intensive.</p> <p>Can anyone think of clever way to regex or otherwise analyze these strings such that "a lot" of the URLS are properly captured--80%? 95% 99.995% of URLs?</p> <p>Thanks!</p> <hr> <p>EDIT: FYI, I'm developing in Python. But a language agnostic solution is great as well.</p> |
27,895,780 | 0 | Duplicating several UI components in App Inventor 2 <p>Is there any way to duplicate several UI components in <a href="http://ai2.appinventor.mit.edu/" rel="nofollow noreferrer">App Inventor 2</a>?</p> <p>E.g. in the following screenshot I would like to duplicate the RedHorizontalArrangement layout as well as the label and the TextBox it contains.</p> <p><img src="https://i.stack.imgur.com/Qq6sa.png" alt="enter image description here"></p> |
3,803,790 | 0 | <p>You cannot update a dll while it is in use, however you can.</p> <ul> <li>Make a copy of the dll with a new file name</li> <li>Load the copy of the dll into an app domain</li> <li>Talk to that app domain with .net remoting</li> <li>When the original dll changes repeat the above</li> </ul> <p>This is what Asp.net does under the covers. So another option is to use Aps.net to host your app.</p> |
3,753,690 | 0 | <p><strong>EDIT</strong></p> <p>You can continue using the same models and hence keep the references throughout the app. Just that, because of your new database schema you'll have to set the table name for the particular model.Also you can use the alias_attribute method, to so you can continue referring to the old attribute names even if you have changed the column names in your table.For ex:</p> <pre><code>class Book < ActiveRecord::Base set_table_name 'publications' set_primary_key 'id' alias_attribute :id,:publication_id end </code></pre> |
36,267,786 | 0 | <p>This is because this function only press the key and not release it. You must call robot.keyRelease(); once after calling keypress() or call it for all the keys when closing the application.</p> |
24,200,387 | 0 | <p>You are using latest one so it get like this. Don't worry about it.</p> <pre><code> public class MainActivity extends ActionBarActivity </code></pre> <p>instead of </p> <pre><code>public class MainActivity extends Activity </code></pre> <p>Remove all code in your MainActivity except <code>OnCreate()</code>. Then you follow your tutorial.</p> <p>You onCreate should be</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } </code></pre> |
26,345,236 | 0 | <p>In order to fix the 'shifting' of the entire page, add this between the second and third sub-story element (Basically, where a new row starts). That issue is caused by float positioning of elements of different heights.</p> <pre><code><div style="clear:both;"></div> </code></pre> |
22,556,051 | 0 | WebStart Application is not working in Java 7 u45 <p>My Eclipse RCP application ( launched with WebStart (.jnlp)) crashes on startup while launching with Java 7 u45 (working fine in java6).</p> <p>I've added to the manifest:<br> Permissions: all-permissions<br> Codebase: *<br> Trusted-Library: true </p> <p>This removed error dialog popup. But I still have a startup issue. I see following messages (Missing Application-Library-Allowable-Codebase) in java console while downloading many jarfs/plugins</p> <pre><code>security: JAVAWS AppPolicy Permission requested for: http://vspdlpd05.atldev.com/PDTeller-v73allyusdev2ix/app/plugins/j2ee_1.6.0.jar ruleset: finding Deployment Rule Set for title: Profile Direct Teller Wrappering Feature location: http:vspdlpd05.atldev.com/PDTeller-v73allyusdev2ix/app/features/com.fnis.ally.teller.wrapper_2.0.0.jnlp jar location: vspdlpd05.atldev.com/PDTeller-v73allyusdev2ix/app/plugins/j2ee_1.6.0.jar jar version: null isArtifact: true ruleset: no rule applies, returning Default Rule network: Created version ID: 1.7.0.51 network: Created version ID: 1.5+ network: Created version ID: 0+ security: Missing Application-Library-Allowable-Codebase manifest attribute for: http://vspdlpd05.atldev.com/PDTeller-v73allyusdev2ix/app/plugins/j2ee_1.6.0.jar </code></pre> <p>Whereas the same changes (modified all the manifest files with above attributes) done in to a different repository seems to be working fine with java 7 u45.</p> <p>Any help would be appreciated.</p> |
35,761,888 | 0 | Why does c++ stick to this kind of symbol system? <p>The system I mean is the one where anything you want to reference has to be prototyped or defined either above your current line or in a referenced header, not sure if this has a name. </p> <p>I'm cool with headers but sometimes the necessity of forward prototypes forces me into writing really disjointed and hard to manage snippets. </p> <p>I get why it was a thing once upon a time but is there any reason modern c++ can't bring us the convenience of allowing definitions in any order, anywhere like the plethora of newer managed languages?</p> |
21,924,596 | 0 | <p>Based on your question, I don't think inheritance is the best tool for the job. I say its not the best choice because you are not dealing with an "is a" relationship. I think you should consider using Events and Delegates to handle the communication between forms and subforms. The following MSDN article provides a good overview of <a href="http://msdn.microsoft.com/en-us/library/edzehd2t%28v=vs.110%29.aspx" rel="nofollow">Handling and Raising Events</a>. You also may want to refresh yourself on the .NET <a href="http://msdn.microsoft.com/en-us/library/vstudio/system.componentmodel.inotifypropertychanged%28v=vs.110%29" rel="nofollow">INotifyPropertyChanged Interface</a> if you using data binding in the subforms. </p> |
32,085,596 | 0 | <p>The if statement is not reachable because you always showed <code>button1content</code></p> <pre><code> $('#button1content').toggle('show'); </code></pre> <p>So <code>var wasVisible = $("#button1content").is(":visible");</code> will always result to true</p> |
1,190,042 | 0 | <p>I've had a lot of luck with <a href="http://www.elevatesoft.com/prodinfo?action=view&product=dbisam&no=1" rel="nofollow noreferrer">DBISAM</a>. It's been superseded by <a href="http://www.elevatesoft.com/prodinfo?action=view&product=edb&no=1" rel="nofollow noreferrer">ElevateDB</a>, which I would use for new projects.</p> <p>I also like that I can do an XCopy install.</p> |
2,719,700 | 0 | CIL and JVM Little endian to big endian in c# and java <p>I am using on the client C# where I am converting double values to byte array.</p> <p>I am using java on the server and I am using writeDouble and readDouble to convert double values to byte arrays.</p> <p>The problem is the double values from java at the end are not the double values at the begin giving to c# </p> <p>writeDouble in Java Converts the double argument to a long using the doubleToLongBits method , and then writes that long value to the underlying output stream as an 8-byte quantity, high byte first.</p> <p>DoubleToLongBits Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "double format" bit layout.</p> <p>The Program on the server is waiting of 64-102-112-0-0-0-0-0 from C# to convert it to 1700.0 but he si becoming 0000014415464 from c# after c# converted 1700.0</p> <p>this is my code in c#:</p> <pre><code> class User { double workingStatus; public void persist() { byte[] dataByte; using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { bw.Write(workingStatus); bw.Flush(); bw.Close(); } dataByte = ms.ToArray(); for (int j = 0; j < dataByte.Length; j++) { Console.Write(dataByte[j]); } } public double WorkingStatus { get { return workingStatus; } set { workingStatus = value; } } } class Test { static void Main() { User user = new User(); user.WorkingStatus = 1700.0; user.persist(); } </code></pre> <p>thank you for the help.</p> |
14,620,735 | 0 | update row in mysql table in jsp <p>i´m trying to update rows in <code>mysql table</code>, i´m using <code>html form</code> for data insertion. In html form attribute <code>value</code> i´m using an existing data from database.</p> <p>Edit.jsp</p> <pre><code><form action="Update.jsp"> <% Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select u.login,i.name,i.surname,i.age,i.tel,i.email,a.street,a.town,a.zip,ul.name,t.name from users u join info i on i.user_id=u.user_id join user_level ul on ul.ulevel=u.ulevel join teams t on t.team_id=u.team_id join adress a on a.info_id=i.info_id where u.login='" + session.getAttribute("uzivatel") + "'"); while (rs.next()) { %> <div class="well well-large"> <font size="2"><b>Welcome, </b></font><font color="RED"><i><%= session.getAttribute("uzivatel")%></i></font><br> <b>Name:</b> <input type="text" name="name" value="<%= rs.getString(2)%>"><input type="text" name="surname" value="<%= rs.getString(3)%>"> <br> <b>Age:</b> <input type="text" name="age" value="<%= rs.getString(4)%>"><br> <b>Telephone:</b> <input type="text" name="tel" value="0<%= rs.getString(5)%>"><br> <b>E-mail:</b> <input type="text" name="email" value="<%= rs.getString(6)%>"><br> <b>Adress:</b> <input type="text" name="street" value="<%= rs.getString(7)%>"><input type="text" name="town" value="<%= rs.getString(8)%>"><input type="text" name="zip" value="<%= rs.getString(9)%>"><br> <b>User level:</b> <%= rs.getString(10)%><br> <b>Team:</b> <%= rs.getString(11)%><br> <input type="submit" name="Submit" value="Update" /> </div> </form> </code></pre> <p>Update.jsp</p> <pre><code><% String name = request.getParameter("name"); String surname = request.getParameter("surname"); String age = request.getParameter("age"); String telephone = request.getParameter("tel"); String email = request.getParameter("email"); String street = request.getParameter("street"); String town = request.getParameter("town"); String zip = request.getParameter("zip"); try { Connection conn = null; Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"); Statement st1 = null; st1 = conn.createStatement(); System.out.println(session.getAttribute("uzivatel")); st1.executeUpdate("UPDATE users JOIN info ON users.user_id = info.user_id" + " JOIN adress ON info.info_id = adress.info_id" + "SET info.name = '"+name+"',info.surname = '"+surname+"'," + "info.age = '"+age+"',info.tel = '"+telephone+"',info.email = '"+email+"'," + "adress.street = '"+street+"',adress.town = '"+town+"',adress.zip = '"+zip+"'," + "WHERE users.login ='" + session.getAttribute("uzivatel") + "' "); response.sendRedirect("AdministrationControlPanel.jsp"); } catch (Exception e) { System.out.println(e.getMessage()); } %> </code></pre> <p>When I pressed the Submit button, it redirected me to <code>Update.jsp</code> and nothing was changed.</p> |
21,497,181 | 0 | gradle, Could not expand ZIP appcompat-v7:19.0.1 <p>I've a problem with android studio adn gradle to import appcompat-v7.</p> <p>So here is my build.gradle in the src directory</p> <pre><code>apply plugin: 'android' apply plugin: 'android-apt' def AAVersion = '3.0.1' android { compileSdkVersion 19 buildToolsVersion "19.0.1" defaultConfig { minSdkVersion 10 targetSdkVersion 19 versionCode 1 versionName "1.0" packageName "com.test" } buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } } apt { arguments { resourcePackageName android.defaultConfig.packageName androidManifestFile variant.processResources.manifestFile } } dependencies { // You must install or update the Support Repository through the SDK manager to use this dependency. // The Support Repository (separate from the corresponding library) can be found in the Extras category. compile 'com.android.support:support-v4:19.0.1' // You must install or update the Support Repository through the SDK manager to use this dependency. // The Support Repository (separate from the corresponding library) can be found in the Extras category. compile 'com.android.support:appcompat-v7:19.0.1' // android annotations compile "org.androidannotations:androidannotations-api:$AAVersion" apt "org.androidannotations:androidannotations:$AAVersion" } </code></pre> <p>But I get the following error</p> <pre><code>Execution failed for task ':app:prepareComAndroidSupportAppcompatV71901Library'. > Could not expand ZIP '/opt/android-sdk/extras/android/m2repository/com/android/support/appcompat-v7/19.0.1/appcompat-v7-19.0.1.aar'. </code></pre> <p>How can I solve my problem ? Thx in advance</p> |
31,906,682 | 0 | Javascript: What is the benefit of two sets of parentheses after function call <p>I understand that in Javascript a function can return another function and it can be called immediately. But I don't understand the reason to do this. Can someone please explain the reason and benefit why you might want to do this in your code? Also, is the function that returns 'hello' considered a closure? </p> <pre><code>function a () { return function () { console.log('hello'); } } //then calling the function a()(); </code></pre> |
36,926,078 | 0 | <p>A variation of your overall approach but with the same end result.</p> <pre><code>PATTERN = '^v (%S+) (%S+) (%S+)$' fo = io.open('object.lua','w') i = 1 for line in io.lines('file.txt') do if line:match(PATTERN) then line = line:gsub(PATTERN,'Node'..i..'= {x=%1, y=%2, z=%3}') print(line) fo:write(line,'\n') i = i + 1 end end fo:close() </code></pre> |
39,927,136 | 0 | Javascript swapping values <p>I need to be able to go through a randomized 3 x 3 matrix and check to see if the numbers are in order (i.e. that the top row is 1-3, center 4-6 and bottom 7-9). So far i wrote this function in JS:</p> <pre><code>function winningorder(topleft, topcenter, topright, centerleft, centercenter, centerright, bottomleft, bottomcenter, bottomright){ if(document.getElementById(topleft).innerHTML = 1 && document.getElementById(topcenter).innerHTML = 2 && document.getElementById(topright).innerHTML = 3 && document.getElementById(centerleft).innerHTML = 4 && document.getElementById(centercenter).innerHTML = 5 && document.getElementById(centerright).innerHTML = 6 &&document.getElementById(bottomleft).innerHTML = 7 && document.getElementById(bottomcenter).innerHTML = 8 && document.getElementById(bottomright).innerHTML = 9){ setTimeout(function(){ alert("Well Done!"); }, 250); } </code></pre> <p>I do not know if i need to put all the locations (the HTML id of each cell) as the parameters, so that is my first question. Secondly, where would i put my function in the HTML code. the code is:</p> <pre><code><table border=1> <tr class="numberrow"> <td id="topleft" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)" ></td> <td id="topcenter" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"></td> <td id="topright" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"></td> </tr> <tr class="numberrow"> <td id="centerleft" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"></td> <td id="centercenter" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"></td> <td id="centerright" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"></td> </tr> <tr class="numberrow"> <td id="bottomleft" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"></td> <td id="bottomcenter" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"></td> <td id="bottomright" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"></td> </tr> </code></pre> <p></p> <p>My first though was to use an onchange event and run the function but that is not working. Thanks for any help!</p> |
29,712,671 | 0 | <p>Can I have a second please...</p> <blockquote> <p>WTTTTFFFFFFF</p> </blockquote> <p>ok now that I got that out, the problem was that I declared the <code>physicsBody</code> AFTER setting the <code>categoryBitMask</code>. so switching this:</p> <pre><code>override func didMoveToView(view: SKView) { physicsWorld.contactDelegate = self physicsBody?.categoryBitMask = PhysicsCategory.Scene physicsBody?.contactTestBitMask = PhysicsCategory.Player physicsWorld.gravity = CGVectorMake(0, -2) physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)//this line moves up physicsBody?.usesPreciseCollisionDetection = true setUpPlayer() } </code></pre> <p>to this:</p> <pre><code>override func didMoveToView(view: SKView) { physicsWorld.contactDelegate = self physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)//to here physicsBody?.categoryBitMask = PhysicsCategory.Scene physicsBody?.contactTestBitMask = PhysicsCategory.Player physicsWorld.gravity = CGVectorMake(0, -2) physicsBody?.usesPreciseCollisionDetection = true setUpPlayer() } </code></pre> <p>fixed this issue...</p> |
27,612,892 | 0 | <p>You could transform the data you received into an <code>Ember.Object</code> and add it to a controller property.</p> <p>Sample controller code:</p> <pre><code>Ember.Controller.extend({ objects: [], jsonRequest: function() { Ember.$.ajax({/* your request */}).then(function(data) { var object = /* code to turn the data into an object for display */; this.get('objects').pushObject(object); }.bind(this)); } }); </code></pre> <p>Then in your template, you can just iterate over the model array:</p> <pre><code>{{#each object in objects}} display object properties here {{/each}} </code></pre> <p>The specifics of how to turn the JSON into an object for display, and how to display the object, are dependent on your needs.</p> |
1,410,828 | 0 | <p>After much research last night, I found this as the answer for the server side. Then write a php script for the client side. Then have ajax call the client which calls the server. Only problem is some of the extensions have to be manually installed.</p> <p><a href="http://php-mag.net/itr/online_artikel/psecom,id,484,nodeid,114.html" rel="nofollow noreferrer">http://php-mag.net/itr/online_artikel/psecom,id,484,nodeid,114.html</a></p> |
18,612,094 | 0 | <p>instead of using a long cast you should cast to size_t.</p> <p>int val= (int)((size_t)arg);</p> |
37,388,012 | 0 | <p>Give <code>display: inline-block;</code> and change to <code>background-size: 100%;</code> will work for you.</p> <pre><code>.tjbtn, .tjbtn--orange, .tjbtn--green { font-size: 1em; color: #fff; text-decoration: none; font-weight: bold; background-repeat: no-repeat; background-size: 100%; background-position: center center; padding: 1em; line-height: 3em; text-transform: uppercase; letter-spacing: 2px; background-image: url("http://tj.cadman.ws/button_bg_orange.svg"); display: inline-block; } </code></pre> <p><strong><a href="https://jsfiddle.net/ob0nmytt/" rel="nofollow">Fiddle</a></strong></p> |
35,848,633 | 0 | <p>To get the data in ASCII add CCSID 1208 (819 is not possible) in the XmlSerialize function and make sure that the ifs-file doesn't exist. Otherwise it would keep the file CCSID</p> <pre><code> XMLSERIALIZE( XMLDOCUMENT( XMLELEMENT(NAME "document", XMLELEMENT(NAME "elements", XMLAGG(elements.element) ) ) ) AS CLOB CCSID 1208 INCLUDING XMLDECLARATION ) AS Response </code></pre> <p>And make sure that your machine QCCSID is set to something other than 65535 (that's always causing lots of Problems with conversion aka not converting automatically).</p> |
38,550,133 | 1 | vectorizing sliding window 2d correlation <p>I have two matrices, call them matrix A and matrix B.</p> <ul> <li>A is n_1*n_2</li> <li>B is m_1*m_2</li> </ul> <p>for the sake of simplicity I will assume <code>n_1<m_1</code>, <code>n_2<m_2</code>.</p> <p>I would like to calculate the sliding window correlation between the two, i.e. I convert A to be <code>n_1*n_2</code> vector, and I run 2 loops over B on for rows the other for columns, iteration I pick the first <code>n_1,n_2</code> rows and columns of B, convert them to a vector and then calculate the correlation between them.</p> <p>Is there a way of vectorizing it to reduce the loops?</p> |
30,044,755 | 0 | composer create-project - command donot work <p>I have my project on github containing composer.json in the root directory. This is how my composer.json code looks like:</p> <pre><code>{ "name": "vendor/projectname", "description": "My first Composer project", "authors": [ { "name": "John Deo", "email": "[email protected]" } ], "prefer-stable": true, "minimum-stability": "dev", "require": { "php": "~5.3" } } </code></pre> <p>I had defined/submited my package on packagist.org.</p> <p>Now when I try to get the project in my localhost using <code>composer create-project - commands</code> one of its work and another do not work.</p> <pre><code>1. composer create-project -s dev vendor/projectname >> WORKS 2. composer create-project vendor/projectname >> DO NOT WORK </code></pre> <p>Can someone please tell why the second command does not work. What am I missing or doing wrong? Please Help!</p> |
398,193 | 0 | <p>This is what transactions are for. Your booking code should BEGIN a transaction, confirm that the time is available using SELECT, and if it is available, INSERT or UPDATE the database to make the reservation, finally COMMITing the transaction. </p> <p>If the time is not available, either don't INSERT or UPDATE the database to make the reservation, or ROLLBACK the transaction.</p> |
11,368,162 | 0 | 8Bit Grayscale Bitmap to Array <p>I am wondering, from here how would I go about storing the pixel values into a matrix? I would like to print out the intensity (grayscale) value.</p> <p>Example Array[5] = 4 Or Array[3][1] = 17</p> <p>I really have no idea how to go about this. All the examples I see seem way to complicated, is there a simple way to do this?</p> <pre><code>#include <stdio.h> #include <stdlib.h> #include <string.h> struct BitMap { short Type; long Size; short Reserve1; short Reserve2; long OffBits; long biSize; long biWidth; long biHeight; short biPlanes; short biBitCount; long biCompression; long biSizeImage; long biXPelsPerMeter; long biYPelsPerMeter; long biClrUsed; long biClrImportant; }Header; int main( void ){ FILE *BMPFile = fopen ("MriHotrod.bmp", "rb"); if(BMPFile == NULL){ return; } unsigned char DataBuff[128*128]; int i; int j; memset(&Header, 0, sizeof(Header)); fread(&Header.Type, 2, 1, BMPFile); fread(&Header.Size, 4, 1, BMPFile); fread(&Header.Reserve1, 2, 1, BMPFile); fread(&Header.Reserve2, 2, 1, BMPFile); fread(&Header.OffBits, 4, 1, BMPFile); fread(&Header.biSize, 4, 1, BMPFile); fread(&Header.biWidth, 4, 1, BMPFile); fread(&Header.biHeight, 4, 1, BMPFile); fread(&Header.biPlanes, 2, 1, BMPFile); fread(&Header.biBitCount, 2, 1, BMPFile); fread(&Header.biCompression, 4, 1, BMPFile); fread(&Header.biSizeImage, 4, 1, BMPFile); fread(&Header.biXPelsPerMeter, 4, 1, BMPFile); fread(&Header.biYPelsPerMeter, 4, 1, BMPFile); fread(&Header.biClrUsed, 4, 1, BMPFile); fread(&Header.biClrImportant, 4, 1, BMPFile); printf("\nType:%hd\n", Header.Type); printf("Size:%ld\n", Header.Size); printf("Reserve1:%hd\n", Header.Reserve1); printf("Reserve2:%hd\n", Header.Reserve2); printf("OffBits:%ld\n", Header.OffBits); printf("biSize:%ld\n", Header.biSize); printf("Width:%ld\n", Header.biWidth); printf("Height:%ld\n", Header.biHeight); printf("biPlanes:%hd\n", Header.biPlanes); printf("biBitCount:%hd\n", Header.biBitCount); printf("biCompression:%ld\n", Header.biCompression); printf("biSizeImage:%ld\n", Header.biSizeImage); printf("biXPelsPerMeter:%ld\n", Header.biXPelsPerMeter); printf("biYPelsPerMeter:%ld\n", Header.biYPelsPerMeter); printf("biClrUsed:%ld\n", Header.biClrUsed); printf("biClrImportant:%ld\n\n", Header.biClrImportant); fread(DataBuff, sizeof(DataBuff), 128*128, BMPFile); for(i=0; i<20; i++){ printf("%d\n", DataBuff[i]); } fclose(BMPFile); return 0; } Output Type:19778 Size:17462 Reserve1:0 Reserve2:0 OffBits:1078 biSize:40 Width:128 Height:128 biPlanes:1 biBitCount:8 biCompression:0 biSizeImage:0 biXPelsPerMeter:0 biYPelsPerMeter:0 biClrUsed:256 biClrImportant:0 0 0 0 0 1 1 1 0 2 2 2 0 3 3 3 0 4 4 4 0 </code></pre> <p>I think the header info is correct, and the number of elements is correct (16384). I am just unsure how to print out the pixel values. The above is clearly not right...</p> <p>Does this have to do with padding?</p> <p>Thanks!</p> |
21,418,662 | 0 | <p>It might be trying to attach the event before the element is ready. Be sure to attached the handler after the DOM is fully loaded.</p> <pre><code>$(function() { $('#hello-world').submit(function(ev) { ev.preventDefault(); // to stop the form from submitting alert("form submitted"); }); }); </code></pre> <p><a href="http://api.jquery.com/ready/" rel="nofollow">http://api.jquery.com/ready/</a></p> |
34,264,327 | 0 | <p>I put the params driver-memory 40G in the spark-submit,and Then solve it.</p> |
30,131,708 | 0 | Not able to generate a unique user-number <p>I have a problem when I'm trying to generate a unique customer-id in my application. I want the numbers to start from 1 and go up. I have a register-class using tree-map that generates the next customer-number using this code:</p> <pre><code>public String generateNumber() { int number = 1; for(Map.Entry<String, Forsikringkunde> entry : this.entrySet()) { if(entry.getValue().getNumber().equals(String.valueOf(number))) { number++; } }return String.valueOf(number); } </code></pre> <p>When I generate customers in my application I get duplicates of the numbers even though I iterate through the map. When creating a customer I create the object, run this method, use a set-method for the ID and adds it to the register, but it doesn't work. Anyone have a solution?</p> |
34,487,352 | 0 | <p>You could search for any characters <strong>not</strong> in the list (a "negated <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp#character-sets" rel="nofollow">character set</a>"):</p> <pre><code>var badUsername = /[^a-zA-Z0-9_]/; console.log(!badUsername.test("HELO $")); </code></pre> <p>or more simply</p> <pre><code>var badUsername = /\W/; </code></pre> <p>since <code>\W</code> is defined as</p> <blockquote> <p>Matches any character that is not a word character from the basic Latin alphabet. Equivalent to <code>[^A-Za-z0-9_]</code>.</p> </blockquote> <p>If you prefer to do a positive match, using anchors as other answers have suggested, you can shorten your regexp by using <code>\w</code>:</p> <pre><code>var goodUsername = /^\w+$/; </code></pre> |
26,521,132 | 0 | <p>I disagree with the solution suggesting 2 left joins. I think a table-valued function is more appropriate so you don't have all the coalescing and additional joins for each condition you would have.</p> <pre><code>CREATE FUNCTION f_GetData ( @Logic VARCHAR(50) ) RETURNS @Results TABLE ( Content VARCHAR(100) ) AS BEGIN IF @Logic = '1234' INSERT @Results SELECT Content FROM Table_1 ELSE INSERT @Results SELECT Content FROM Table_2 RETURN END GO SELECT * FROM InputTable CROSS APPLY f_GetData(InputTable.Logic) T </code></pre> |
39,565,298 | 1 | pandas dataframe look ahead optimization <p>What's the best way to do this with pandas dataframe? I want to loop through a dataframe, and find the nearest next index that has at least +/-2 value difference. For example: [100, 99, 102, 98, 103, 103] will create a new column with this [2, 2, 3, 0, N/A], 0 means not find.</p> <p>My solution performance is n * log(n). Any brilliant people could please show me a better performance solution?</p> |
31,001,033 | 0 | <p>I have faced certain issue when UI doesn't responds well one of issue was realetd with Jtable data and updating it in non swing thread. So you can try putting your code in a Swing thread,precisely in a Worker thread</p> <pre><code>SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { for (int i = 0; i < table1.getRowCount(); i++) { int modelIndex = table1.convertRowIndexToModel(i); String status = table1.getModel().getValueAt(modelIndex, 9).toString(); if (status.equalsIgnoreCase("Cleared")) { deleteRow(table1, table1Model, i); } } return null; } public void deleteRow(JTable table, DefaultTableModel model, int rowNo) { try{ model.removeRow(rowNo); model.fireTableDataChanged(); table.setModel(model); }catch(ArrayIndexOutOfBoundsException |NullPointerException a){} } }; worker.execute(); </code></pre> |
26,748,141 | 0 | can't find mpif.h compiling error? <p>i have download a big ecosystem model (Ecosystem Demography) which must e compiled in linux and it uses MPI and hdf5. i have installed the mpich (on centOS 7) to compile the ED model with Gfortran compiler. but it gives me the famous error </p> <pre><code>Can't find file: mpif.h </code></pre> <p>i have looked for the file by "which mpif.h" and it returns nothing so i set the PATH as follow :</p> <pre><code>PATH=/home/hamid/edpacks/mpich-install/bin:$PATH export PATH </code></pre> <p>now which mpif.h returns the path to the file but again when i try to ./install the model it give me the same error. problem is i don't know how to set this path and also path to mpich from inside the model. Do i have to set the path from include file or makefile? </p> |
40,629,423 | 0 | <p>It is not too pretty but you could use your first list and then select from the second list with <code>FirstOrDefault</code>.</p> <p>The last <code>Where</code> is to be sure you do not include nulls if the first <code>SelectedUser</code> is not found in the <code>objValidateUserList</code> list.</p> <pre><code>var sortedList = SelectedUser.Select( sortedListUser => objValidateUserList.FirstOrDefault(nonSortedListUser => nonSortedListUser.value == sortedListUser)) .Where(x => x != null); </code></pre> <p>Hope it helps!</p> |
26,202,667 | 0 | In AngularJS, how does $scope get passed to scope? <p>I'm a bit confused with the use of <strong>$scope</strong> in controllers and of <strong>scope</strong> in directives. Please verify if my understanding is correct (and also provide some alternative ways how to do this).</p> <p>Let's say I have an html:</p> <pre><code><div ng-controller="app1_Ctrl"> . . . <input type="text" ng-model="value"/> <input type="checkbox" /> <button ng-click="submit()"></button> </div> </code></pre> <p>And my main.js</p> <pre><code>(function() { angular.module('mainApp', ['app1']); })(); </code></pre> <p>And my app1 looks like this (based on official AngularJS documentation <a href="https://docs.angularjs.org/guide/directive" rel="nofollow">here</a>)</p> <pre><code>(function() { var app = angular.module('app1', []); app.controller('app1_Ctrl', ["$scope", function($scope) { . . . }]); app.directive('app1_Dir1', [function() { function link(scope, element, attr) { scope.$watch(attr.someAttrOfCheckBox, function() { // some logic here }); function submit() { // some logic here } } return link; }]); })(); </code></pre> <p>How does $scope.value passed in scope in directive so that I can do some manipulations there? Will ng-click fire the function submit() in the directive link? Is it correct to use scope.$watch to listen for an action (ticked or unticked of course) in checkbox element?</p> <p>Many thanks to those who can explain.</p> |
39,661,459 | 0 | <p>I had the same problem, that it ended there and even refreshing the simulator didn't make the packager to go on. Than I figured it out: I was still connected to the Internet via a VPN, so the simulator couldn't connect to the packager. Simply closing the VPN solved the issue.</p> |
Subsets and Splits