source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0032507975.txt" ]
Q: Navigation bar for split view controller is darker when inside a tab bar controller If you place a split view controller inside a tab bar controller the navigation bar and tab bar are darker on the left side. I've attached a screenshot. I created this by creating a Master-Detail Application and then adding a tab bar controller. How do you correct this issue? A: At the time of writing (May 2017) this bug still exists. I can't believe Apple doesn't take care of this. The worse part is that if you rotate your device, open the master from the side and rotate back, the translucent bars switch place and suddenly the master has a working translucent bar and the detail has not. :/ The only possible fix I was able to come up with, was to get rid of UITabBarController and instead build my own implementation of a tab bar controller using a plain UIViewController with a UITabBar at the bottom and the UIViewController containment API. This means a lot of coding to reinvent the wheel. Its sad to not make use of UITabBarController but thats how it is. You have to make a trade off between the container controller and all its nice features like the "More" controller you get for free vs having translucent bars. If you can live without translucent bars, I'd still go for UITabBarController over do all the coding. On the other hand, one could replace the UITabBar with a UICollectionView and have more than 6 items without having the need for a "More" controller at all.
[ "stackoverflow", "0030469648.txt" ]
Q: Trying to "fix" navigation position on scroll I'm trying to figure out how to get my navigation to stick to the top of the page when the window scrolls down. I've seen a few examples on how to do this (found one that worked, but made my menu's click function stop working) but I haven't been able to get it to work myself. Here is my jsFiddle jQuery (code in question) /* Code to "fix" navigation */ $(window).scroll(function(){ var menu = $("#navbar"); var menuWidth = $("#wrapper").css("width"); var menuPos = menu.offset(); var menuTopPos = menuPos.top; if ( $(window).scrollTop() > (menuTopPos) ) { menu.css("position", "fixed").css("top", "0px").css("left", "0px").css("width", menuwidth); } else { menu.css("position", "relative").css("width", "100%"); } }); HTML (basic structure) <div id="wrapper"> <div id="header"> (Header stuff goes here) </div> <div id="navbar> <ul class="nav-tabs"> (Menu goes here)</ul> </div> </div> When I just make my #navbar position:fixed; it clearly then ignores all layout formatting and expands past my website's layout. For this reason I'm trying to set the width to the page's #wrapper, which is set to only be a certain width of the page. Edited to show header content in layout A: Alright, I figured it out. My problem was that I was trying to figure out the top position of #navbar, but #navbar was my menu and theoretically always moving, and so the top position was always changing. What I had to do was to find the top position of #navbar, but then fix the position of the UL .Nav-Tabs inside of it. Then I realized that resizing the screen messed up the navigation so I added an event listener to change the width of the navigation as the screen resized. EDIT: Oh yeah! Here's the updated jsFiddle. So like this: jQuery var menu = $(".nav-tabs"); /* set menu to UL, not DIV */ $(window).scroll(function(){ var wrapperWidth = $("#wrapper").css("width"); var menuPos = $("#navbar").offset(); /* find top of DIV */ var menuTopPos = menuPos.top; if ( $(window).scrollTop() > menuTopPos ) { menu.css("position", "fixed"); menu.css("top", "0px"); menu.css("width", wrapperWidth); } else { menu.css("position", "relative"); menu.css("width", "100%"); } }); // code to check menu width against wrapper width on resize $(window).resize(function(){ var menuWidth = menu.css("width"); var wrapperWidth = $("#wrapper").css("width"); if ( menuWidth != wrapperWidth ) { menu.css("width", wrapperWidth); } })
[ "stackoverflow", "0023235899.txt" ]
Q: OR condtion in Smarty Hi I want to use OR Condition in smarty please help me {if $productgroup.gid neq '69' or $productgroup.gid neq '68' or $productgroup.gid neq '27' or $productgroup.gid neq '31' or $productgroup.gid neq '70' or $productgroup.gid neq '71'} <select name="name" id="name" onchange="plan()"> <option value="1">Car</option> </select> {/if} A: There should be no quotation between numeric during the if condition: {if $productgroup.gid neq 69 or $productgroup.gid neq 68 or $productgroup.gid neq 27 or $productgroup.gid neq 31 or $productgroup.gid neq 70 or $productgroup.gid neq 71} <select name="name" id="name" onchange="plan()"> <option value="1">Car</option> </select> {/if}
[ "stackoverflow", "0038169687.txt" ]
Q: Assigning a structure to a structure array in MATLAB I am trying to assign a structure to an empty structure array. For example- a=struct([]); a(1)=b; where b is a structure itself containing multiple fields, ex: b=struct('ID',1,'pass',34); But this doesn't work. I can do the following- a(1).field=b; but this makes other portions of the code cumbersome. actually in my code, b is coming from a separate function which will be called several times. I just need to add the returned structures to a structure array. Or any other suggestions would be nice. A: You need a to be a proper structure array, i.e. initialise it with the compatible set of fields: a = struct('ID', {}, 'pass', {}); b = struct('ID', 1, 'pass', 34); a(1) = b;
[ "stackoverflow", "0004317049.txt" ]
Q: arp command - what does it all mean? *and* getting a wireless router MAC address from IP When I type in arp -a in my bash shell, I get output that looks like the following: ? (10.0.0.1) at 0:f0:7f:43:e8:68 on en1 ifscope [ethernet] box1.google.com (10.0.0.3) at 0:1f:fe:fe:ca:d4 on en1 ifscope [ethernet] box2.google.com (10.0.0.2) at 0:2:a3:45:90:bf on en1 ifscope [ethernet] box3.google.com (10.0.0.50) at 78:e7:df:7c:34:c on en1 ifscope [ethernet] box4.google.com (10.0.0.230) at 0:80:74:c9:50:d5 on en1 ifscope [ethernet] box5.google.com (10.0.0.256) at 0:23:df:91:4f:9e on en1 ifscope [ethernet] box6.google.com (10.0.0.458) at 0:15:9:89:36:68 on en1 ifscope [ethernet] ? (10.0.0.179) at 0:2a:32:f0:f4:d0 on en1 ifscope [ethernet] box7.google.com (10.0.0.283) at 0:27:16:66:2d:ef on en1 ifscope [ethernet] box8.google.com (10.0.0.386) at 0:13:eb:91:d8:b5 on en1 ifscope [ethernet] box9.google.com (10.0.0.287) at 0:1c:25:10:d8:89 on en1 ifscope [ethernet] ? (10.0.0.255) at (incomplete) on en1 ifscope [ethernet] ? (172.17.122.255) at (incomplete) on vmnet8 ifscope [ethernet] ? (172.17.254.1) at 0:50:56:c0:0:1 on vmnet1 ifscope permanent [ethernet] ? (172.17.254.255) at (incomplete) on vmnet1 ifscope [ethernet] What does all of this mean? I loosely understand that I'm seeing domain names, IP addresses (internal IP addresses?), and MAC addresses. How do I find the MAC address for the wireless router that I'm connected to? Why are there so many entries here? I figured that there would only be one for my computer, one for the wireless router, one for the cable modem, and then possibly some other things upstream... but I'm seeing other computers that are not mine. Furthermore, I am not seeing my computer. Also, could I somehow use information like this to find the MAC addresses for wireless routers in public? What if I can not connect to said public routers? A: At a guess 10.0.0.1 looks like the gateway. Why do you want to find the MAC address for the router you are on? Also, if you cannot connect to a wireless router then you won't be able to find it with this command, there are some other commands you can use to scan for wireless signals. You don't see your computer on there because this is your local arp table, why would you need to know where you are? You're already there.
[ "stackoverflow", "0057533997.txt" ]
Q: Issue with a regular expression How can I write a regular expression to return the value of the mesh volume? The file containing this information is printed below. Mesh Bounding Box Size 13119.671875 13057.258789 5996.836426 Mesh Bounding Box Diag 19457.128906 Mesh Bounding Box min -6823.634277 -6530.717773 0.000000 Mesh Bounding Box max 6296.037598 6526.541016 5996.836426 Mesh Surface Area is 373208000.000000 Mesh Volume is 48660.9190912000000 Mesh Total Len of 2430 Edges is 1946449.875000 Avg Len 801.008179 Mesh Total Len of 2430 Edges is 1946449.875000 Avg Len 801.008179 (including faux edges)) Thin shell (faces) barycenter: -228.323471 -0.174702 1865.262939 Vertices barycenter -175.590256 7.494401 2809.697754 I am able to get the volume of the mesh (which is 48660.9190912000000) using the following: \d+[.]*\d+$ but it also matches all the other numbers. I tried (Mesh Volume is)\w+\d+[.]*\d+$ but it fails to find any match. Could someone help me with that? If I group the numbering as the following, can I return the value of the volume as \1? (Mesh Volume is)\w+(\d+[.]*\d+)$ My goal is to find a working regular expression to use in MATLAB regexp function. A: You could try something like this: %float_pattern = "[0-9.]+"; float_pattern = "\d+(?:\.\d+)?"; pattern = "Mesh Volume is (?<MeshVolume>" + float_pattern + ")"; matches = regexp(information, pattern, 'match') tokens = regexp(information, pattern, 'tokens') names = regexp(information, pattern, 'names') if isfield(names, "MeshVolume") fprintf("Mesh Volume = %f m^3\n", names.MeshVolume); else fprintf("Failed to find mesh volume.\n"); end
[ "unix.stackexchange", "0000100846.txt" ]
Q: Compression Level Mksquashfs Here I'm trying to create a squashfs filesystem but the resulting image is bigger than the original version and not because I added a file or anything as I only modified some configuration files. What I'm trying to do is modify the existing squashfs filesystem on a live usb and delete some info to start the OS in a login shell. Since I fixed an amount of space to the EXT4 partition I need the modified squashf to have the same size as the original. I can do the changes while the live system is running but since I'm making a script to automate this process I need to do it before creating the live usb itself. The problem comes when recreating the image as the resulting file is about 400mb larger than the original and when I use the -b 4096/1Mbyte option the image is about 800mb larger when the original file is about 2.2gb. I did the same before to add my script to the filesystem and it worked great but now I can't understand what happen this time. I searched my backup of .bash_history but with no luck How can I reduce the image size?? What I'm doing wrong, anyone?? Edit: # Create Directories mkdir /mnt/kali-iso mkdir /mnt/squash mkdir /tmp/squash_mod # Mount ISO And Squashfs Image mount /root/kali.iso /mnt/kali-iso mount /mnt/kali-iso/live/filesystem.squashfs /mnt/squash -o loop # Copy All Files To A Temp Directory To Modify Them cp -rf /mnt/squash/* /tmp/squash_mod cp /root/foo.sh /tmp/squash_mod/root/Desktop/ # Create Squashfs mksquashfs /tmp/squash_mod filesystem.squashfs Or # mksquashfs /tmp/squash_mod filesystem.squashfs -b 4096 # or 1Mbyte Results from "du" command: du -ch /mnt/squash | grep "total" = 6.6G total du -ch /tmp/squash_mod | grep "total" = 7.2G total There are some discrepancies between the same folders, their size are different: "/tmp/squash_mod/sbin = 8.8mb" "/mnt/squash/sbin = 8.5mb" "/tmp/squash_mod/var = 309mb" "/mnt/squash/var = 282mb" "/tmp/squash_mod/bin = 7.0mb" "/mnt/squash/bin = 6.8mb" A: Cannot comment so I'm writing an answer: 1) I agree with Patrick that the most probably source of your problems is hardlink 'multiplication'. With a normal cp you create as many copies of a hardlinked file as the hardlink count was. Use rsync or cp -a instead. 2) An even better solution would be to simply unsquashfs the image so you can skip the loop mount step. 3) Digging even deeper, you can play around with aufs or unionfs :)
[ "stackoverflow", "0033972073.txt" ]
Q: How to show one element when click on the another element with css? I've used this css code for showing the element when click on the search id tag. This is possible with jquery but I want to do this with css only. Please advise. #open_search:active #search{ display: block; transition: all 100ms ease-in-out; } html <div class="row-fluid"> <div class="span2 language pull-right"> <div class="language-object"> </div> </div> <span id="open_search" class=" btn glyphicon glyphicon-search"></span> <div id="search" class="span3 pull-left"> <span id="dnn_dnnSearch_ClassicSearch"> <span class="searchInputContainer" data-moreresults="مشاهده نتایج بیشتر" data-noresult="نتیجه‌ای یافت نشد"> <input name="dnn$dnnSearch$txtSearch" maxlength="255" size="20" id="dnn_dnnSearch_txtSearch" class="NormalTextBox" autocomplete="off" placeholder="جستجو..." type="text"> <a class="dnnSearchBoxClearText"></a> </span> <a id="dnn_dnnSearch_cmdSearch" class="SearchButton pull-left" href="javascript:__doPostBack('dnn$dnnSearch$cmdSearch','')">Search</a> </span> <span id="close_search" class="btn glyphicon glyphicon-remove "></span> </div> <div id="login" class="span5 pull-left"> <div id="dnn_dnnLogin_loginGroup" class="registerGroup"> <a id="dnn_dnnLogin_enhancedLoginLink" title="ورود" class="LoginLink" rel="nofollow" onclick="this.disabled=true;" href="http://localhost/dnn_test/Login?returnurl=%2fdnn_test%2fskin2">&nbsp;ورود&nbsp;</a> </div> <div id="dnn_dnnUser_registerGroup" class="registerGroup"> <ul class="buttonGroup"> <li class="userDisplayName list-inline"> <a id="dnn_dnnUser_enhancedRegisterLink" title="ثبت‌نام" rel="nofollow" href="http://localhost/dnn_test/Register?returnurl=http%3a%2f%2flocalhost%2fdnn_test%2fskin2">&nbsp;ثبت‌نام</a> </li> </ul> </div> </div> </div> If it is not possible with css, then please help to do this with jquery. A: Css: #search { display: none; transition: all 100ms ease-in-out; } #search.active { display: block; } jQuery: $(function(){ $("#open_search").click(function(){ $("#search").toggleClass("active"); }); });
[ "stackoverflow", "0009368543.txt" ]
Q: Remove index.php from CodeIgniter URLs I'm trying to access CodeIgniter URLs without 'index.php'. Here's the steps I've taken: Checked mod_rewrite is enabled - I set a rule to redirect all requests to google, which worked. Also checked that 'AllowOverride All' was set Added an .htaccess file with the following: RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] Set my directory structure on the webserver as follows: /home/wwwsunde/ -> application -> system -> public_html -> index.php -> .htaccess Updated my application/config files so that the system and application paths are '../system' and '../application' Try to access the site from 2 URLs http://109.234.194.207/~wwwsunde/index.php/welcome/membership WORKS http://109.234.194.207/~wwwsunde/welcome/membership DOES NOT WORK I've also set CodeIgniter's index page variable to blank as per the guide The error message shown: The requested URL /home/wwwsunde/public_html/index.php/welcome/membership was not found on this server. I'm out of ideas as to what could be wrong - it's an Apache or server issue but I'm not sure what... A: Oh... I know why... make this your rewrite rule: RewriteRule .* index.php/$0 [PT] The [L] you had was just a 'last rule' but wouldn't do the quit rewrite you want to quietly handle the background shell game. It would be an endless loop. If this doesn't work, specify the full URL in the rewrite like: RewriteRule .* http://109.234.194.207/~wwwsunde/index.php/$0 [PT]
[ "stackoverflow", "0027440024.txt" ]
Q: C++ update txt file method I'm trying to write a code to update the content of some .txt files after i've done some operations over their content;This is the method. I have 2 cases. 1)update of "dir.txt" 2)update of "ext.txt" depends on param; In the void main() I perform operations over vectors ext and dir and now I want to delete all content of the file and rewrite a vector which has been modified; I already have a valid function to read from the file data and write it in the vectors; void update(string type){ vector<string>aux; string file; int nr=0; if (type=="dir"){ for (int i = 0; i < this->dir_no; i++) aux.push_back(dir[i]); file = "directoare.txt"; nr=dir_no;} else if (type == "ext"){ for (int j = 0; j < ext_no; j++) aux.push_back(ext[j]); file ="extensii.txt"; nr = ext_no; } else return; if (f){ f.close(); f.open(file, std::fstream::out | std::fstream::trunc); for (int i = 0; i < nr; i++) f << aux[i] << "\n"; } else cout << "Couldn't update! error " << endl; } PROBLEM: the code doesn't have any compilation errors but everytime i call it in main() function, cleans the content of my file without writting anything; I assume it's a silly logic mistake but I;ve been looking for hours at this point and I can't see it;btw f is a fstream which i declared in the class Thank you for your help. I did update my code and started using strings because is something people tell me very often. I'm not really used to it so it's not my first option.I'm trying to change that. Anyway,apparently using char was one part of the problem. The other one was that I hadn't close the file after writting to it. Thanks again for your help A: First of all, you should use std::string instad of char* in C++ 1. String comparsion You can't compare char arrays with ==. You have to use strcmp() instead. You can use operator== with std::string. 2. If-else Should look like if(...) { //code } else if(...) { //code } else { //code } 3. Better formatting Maybe you think that it's not that important, but it can definitly help you with debugging and it's a way better for future readers of your code (including you)
[ "stackoverflow", "0035156864.txt" ]
Q: Ajax search feature not working in django App I'm following a tut from Mike hibbert and have tried to modify it a bit to suit my needs but it's not working. I wanted to use his way because my way was breaking the DRY rule, I had to write search logic for each of my views I thought it might be the order my js But I dont think it is. I could be wrong, as I am fairly new to prgramming. I'm not sure but i think the issue may be with my search being on the nav which I nav in an include. Heres my code views.py def search_title(request): if request.method == "POST": search_text = request.POST['search_text'] else: search_text = '' posts = Post.objects.filter( Q(title__contains=search_text)| Q(content__contains=search_text) ) context = { "posts": posts } return render(request, "posts/ajax_search.html", context) my nav.html <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="{% url 'posts:list' %}">HiSPANIC HEiGHTS</a> </div> <div id="navbar" class="collapse navbar-collapse"> <form method="POST" action=" " class="navbar-form navbar-right"> <div class="input-group">{% csrf_token %} <input type="text" name="search" id="search" placeholder="search" value="{{ request.GET.q }}" class="form-control" style="width: 350px"> <ul id="search-results"> </ul> <span class="input-group-btn"> <button type="submit" class="btn btn-primary"><span style="font-size:1.4em" class="glyphicon glyphicon-search"></span> </button> </span> </div> </form> <ul class="nav navbar-nav"> <li><a href="{% url 'posts:list' %}">Home</a></li> <li><a href="{% url 'posts:sewp' %}">Sewp</a></li> {% if user.is_authenticated %} <li><a href="{% url 'admin:index' %}">Admin</a></li> <li><a href="{% url 'posts:create' %}">Create</a></li> {% endif %} </ul> </div><!--/.nav-collapse --> </div> base.html {% load staticfiles %} <html> <head> <title> {% block head_title %} try django 1.9 {% endblock head_title %}</title> <link rel="stylesheet" href='{% static "css/base.css" %}'/> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous"> {% include "includes/nav.html" %} {% include "includes/messages_display.html" %} <div class="container"> {% if title == "posts" %} <div class="jumbotron" style="margin-top: 80px"> {% block jumbotron %}{% endblock jumbotron %} </div> {% endif %} {% block content %}{% endblock content %} </div> <!-- Latest compiled and minified JavaScript --> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"> </script> <script src="{% static 'js/ajax.js' %}"></script> <script src="{% static 'js/jquery.bootstrap-autohidingnavbar.js' %}"></script> <script> $("nav.navbar-fixed-top").autoHidingNavbar(); </script> ajax.js $(function(){ $('#search').keyup(function() { $.ajax({ type: "POST", url: "/posts/search/", data: { 'search_text': $('#search').val(), 'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val() }, success: searchSuccess, dataType: 'html' }); }); }); function searchSuccess(data, textStatus, jqXHR) { $('#search-results').html(data); } my posts/urls.py urlpatterns = [ url(r'^$', post_list, name='list'), url(r'^tag/(?P<slug>[\w-]+)/$', tag_list, name="tag_list"), url(r'^create/$', post_create, name='create'), url(r'^sewp$', sewp, name='sewp'), url(r'^(?P<slug>[\w-]+)/$', post_detail, name='detail'), url(r'^(?P<slug>[\w-]+)/edit/$', post_update, name='update'), url(r'^(?P<id>\d+)/delete/$', post_delete, name='delete'), url(r'^search/', search_title), ] I see no errors in the network, I've switched back and forth from GET to POST, just trying to tweak things to make it work but nothing has changed. My jquery is from a CDN but I don't think that's an issue, but I am a newb and could be wrong. any help with this will be appreciated A: Move your search url definition to the top of the urlpatterns list, so it doesn't get masked by the post_detail wildcards: urlpatterns = [ url(r'^$', post_list, name='list'), url(r'^search/', search_title), url(r'^tag/(?P<slug>[\w-]+)/$', tag_list, name="tag_list"), url(r'^create/$', post_create, name='create'), url(r'^sewp$', sewp, name='sewp'), url(r'^(?P<slug>[\w-]+)/$', post_detail, name='detail'), url(r'^(?P<slug>[\w-]+)/edit/$', post_update, name='update'), url(r'^(?P<id>\d+)/delete/$', post_delete, name='delete'), ] From the docs: Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL. And your post_detail regexp certainly matches search/.
[ "stackoverflow", "0035191293.txt" ]
Q: Is using 'if (variable == true)' in an if statement any different than 'if (variable)'? So I've recently been looking around some code online and have found people using both of the following statements, which has made me curious as to whether or not there is a difference between them. if (true == true) { ... } - if (true) { ... } What I assume happens with the first statement is that it is checked whether or not the fact that true equals true is true (sorry if I am being a bit confusing) and that the second statement simply checks to see if true equals true. A: The only different here is that true == true gets evaluated as true. Likewise if you put false == false it evaluates as true. Just putting true it doesn't need to be evaluated, it's just true. Often you'll see people put if (flag == true) when they could equally well just put if (flag). The verbose approach is often used to explicitly show what's going on - it perhaps reads a little clearer. I think it reads better when doing the opposite - i.e. if (!flag) versus if (flag == false). I get the feeling that the code you've seen online has just taken a redundant extra step from if (flag) to if (flag == true) to if (true == true) when they know, for whatever reason, that flag is always true.
[ "stackoverflow", "0055424875.txt" ]
Q: Use Vulkan VkImage as a CUDA cuArray What is the correct way of using a Vulkan VkImage as a CUDA cuArray? I've been trying to follow some examples, however I get a CUDA_ERROR_INVALID_VALUE on a call to cuExternalMemoryGetMappedMipmappedArray() To provide the information in an ordered way. I'm using CUDA 10.1 Base code comes from https://github.com/SaschaWillems/Vulkan, in particular I'm using the 01 - Vulkan Gears demo, enriched with the saveScreenshot method 09 - Capturing screenshots Instead of saving the snapshot image to a file, I'll be sending the snapshot image into CUDA as a CUarray. I've enabled the following instance and device extensions: std::vector<const char*> instanceExtensions = { VK_EXT_DEBUG_REPORT_EXTENSION_NAME, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME, VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME }; std::vector<const char*> deviceExtensions = { VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME, VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME, VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME, VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME }; I have a VkImage, created as follows: // Create the linear tiled destination image to copy to and to read the memory from VkImageCreateInfo imageCreateCI(vks::initializers::imageCreateInfo()); imageCreateCI.imageType = VK_IMAGE_TYPE_2D; // Note that vkCmdBlitImage (if supported) will also do format conversions if the swapchain color format would differ imageCreateCI.format = VK_FORMAT_R8G8B8A8_UNORM; imageCreateCI.extent.width = width; imageCreateCI.extent.height = height; imageCreateCI.extent.depth = 1; imageCreateCI.arrayLayers = 1; imageCreateCI.mipLevels = 1; imageCreateCI.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageCreateCI.samples = VK_SAMPLE_COUNT_1_BIT; imageCreateCI.tiling = VK_IMAGE_TILING_LINEAR; imageCreateCI.sharingMode = VK_SHARING_MODE_EXCLUSIVE; imageCreateCI.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; VkExternalMemoryImageCreateInfoKHR extImageCreateInfo = {}; /* * Indicate that the memory backing this image will be exported in an * fd. In some implementations, this may affect the call to * GetImageMemoryRequirements() with this image. */ extImageCreateInfo.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_KHR; extImageCreateInfo.handleTypes |= VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR; imageCreateCI.pNext = &extImageCreateInfo; // Create the image VkImage dstImage; VK_CHECK_RESULT(vkCreateImage(device, &imageCreateCI, nullptr, &dstImage)); // Create memory to back up the image VkMemoryRequirements memRequirements; VkMemoryAllocateInfo memAllocInfo(vks::initializers::memoryAllocateInfo()); VkDeviceMemory dstImageMemory; vkGetImageMemoryRequirements(device, dstImage, &memRequirements); memAllocInfo.allocationSize = memRequirements.size; // Memory must be host visible to copy from memAllocInfo.memoryTypeIndex = vulkanDevice->getMemoryType(memRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); VkExportMemoryAllocateInfoKHR exportInfo = {}; exportInfo.sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR; exportInfo.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR; memAllocInfo.pNext = &exportInfo; VK_CHECK_RESULT(vkAllocateMemory(device, &memAllocInfo, nullptr, &dstImageMemory)); VK_CHECK_RESULT(vkBindImageMemory(device, dstImage, dstImageMemory, 0)); From there I'll: Get the Vulkan Memory Handler: int CuEncoderImpl::getVulkanMemoryHandle(VkDevice device, VkDeviceMemory memory) { // Get handle to memory of the VkImage int fd = -1; VkMemoryGetFdInfoKHR fdInfo = { }; fdInfo.sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR; fdInfo.memory = memory; fdInfo.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR; auto func = (PFN_vkGetMemoryFdKHR) vkGetDeviceProcAddr(device, "vkGetMemoryFdKHR"); if (!func) { printf("Failed to locate function vkGetMemoryFdKHR\n"); return -1; } VkResult r = func(device, &fdInfo, &fd); if (r != VK_SUCCESS) { printf("Failed executing vkGetMemoryFdKHR [%d]\n", r); return -1; } return fd; } Import the memory: CUDA_EXTERNAL_MEMORY_HANDLE_DESC memDesc = { }; memDesc.type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD; memDesc.handle.fd = getVulkanMemoryHandle(device, memory); memDesc.size = extent.width*extent.height*4; CUDA_DRVAPI_CALL(cuImportExternalMemory(&externalMem, &memDesc)); And map the memory: This is the step that it is failing. CUarray CuEncoderImpl::getCUDAArrayFromExternalMemory(const VkExtent3D &extent,const CUexternalMemory &m_extMem) { CUmipmappedArray m_mipmapArray; CUresult result = CUDA_SUCCESS; CUarray array; CUDA_ARRAY3D_DESCRIPTOR arrayDesc = { }; arrayDesc.Width = extent.width; arrayDesc.Height = extent.height; arrayDesc.Depth = 0; arrayDesc.Format = CU_AD_FORMAT_UNSIGNED_INT32; arrayDesc.NumChannels = 4; arrayDesc.Flags = CUDA_ARRAY3D_SURFACE_LDST; CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC mipmapArrayDesc = { }; mipmapArrayDesc.arrayDesc = arrayDesc; mipmapArrayDesc.numLevels = 1; mipmapArrayDesc.offset = 0; CUDA_DRVAPI_CALL(cuExternalMemoryGetMappedMipmappedArray(&m_mipmapArray, m_extMem, &mipmapArrayDesc)); CUDA_DRVAPI_CALL(cuMipmappedArrayGetLevel(&array, m_mipmapArray, 0)); return array; } I've been trying multiple combinations of the parameters, but failed so far. The error point to an invalid parameter, but I'm not sure how to find what's wrong. Only thing that had worked is to map the Vulkan image memory to a host buffer and then copying it into the CUDA array... but I guess that's expensive and I'd like to avoid it if possible. A: For the record, I finally got this to work. Some notes and the modifications I had to do to the code listed in the question: Vulkan-CUDA interoperability is advertised as a feature of CUDA 10, see CUDA 10 Features revealed The tiling of the image that is going to be mapped had to be `VK_IMAGE_TILING_OPTIMAL imageCreateCI.tiling = VK_IMAGE_TILING_OPTIMAL; The memory for that image must be allocated with the VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT memAllocInfo.memoryTypeIndex = vulkanDevice->getMemoryType(memRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); The memory descriptor when importing the memory should use the memory size that was returned in the memory requirements (size below is memRequirements.size from the code creating the image): CUDA_EXTERNAL_MEMORY_HANDLE_DESC memDesc = { }; memDesc.type = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD; memDesc.handle.fd = getVulkanMemoryHandle(device, memory); memDesc.size = size; CUDA_DRVAPI_CALL(cuImportExternalMemory(&externalMem, &memDesc)); Finally the mapped array is described as being CU_AD_FORMAT_UNSIGNED_INT8 with four channels and with a CUDA_ARRAY3D_COLOR_ATTACHMENT CUDA_ARRAY3D_DESCRIPTOR arrayDesc = { }; arrayDesc.Width = extent.width; arrayDesc.Height = extent.height; arrayDesc.Depth = 0; arrayDesc.Format = CU_AD_FORMAT_UNSIGNED_INT8; arrayDesc.NumChannels = 4; arrayDesc.Flags = CUDA_ARRAY3D_COLOR_ATTACHMENT; CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC mipmapArrayDesc = { }; mipmapArrayDesc.arrayDesc = arrayDesc; mipmapArrayDesc.numLevels = 1; mipmapArrayDesc.offset = 0; CUDA_DRVAPI_CALL(cuExternalMemoryGetMappedMipmappedArray(&m_mipmapArray, m_extMem, &mipmapArrayDesc)); After those changes, I was able to get it to work. I few the changes were glaring mistakes on my side (like the size), a few things I found carefully re-reading the documentation for the 100th time, others were guesses at hints in the documentation and, finally, a lot of trial and error.
[ "stackoverflow", "0020590555.txt" ]
Q: How can I optimize this IN clause in mysql? I have following table structure: CREATE TABLE listing_attributes ( id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, listing_id INT, attribute_id INT, value LONGTEXT, FOREIGN KEY ( attribute_id ) REFERENCES item_type_attributes ( id ) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY ( listing_id ) REFERENCES listing( id ) ON DELETE CASCADE ON UPDATE CASCADE ); CREATE INDEX attribute_fk ON listing_attributes ( attribute_id ); CREATE INDEX listing_fk ON listing_attributes ( listing_id ); and this one: CREATE TABLE vw_search( listing_type_css_class VARCHAR(45), override_listing_image_url VARCHAR(200), override_listing_image TINYINT DEFAULT 0, listing_type_priority INT DEFAULT 0, main_image VARCHAR(255), title VARCHAR(255), new_listing INT, listing_type_name VARCHAR(100), location_name VARCHAR(255), location_group VARCHAR(100), location_id INT DEFAULT 0, create_date TIMESTAMP DEFAULT '0000-00-0000:00:00' NOT NULL, expiry_date DATETIME, has_expired INT, should_show INT, price DECIMAL(19,2) NOT NULL, description LONGTEXT, view_count INT DEFAULT 0 NOT NULL, id INT DEFAULT 0 NOT NULL, category_id INT NOT NULL, created_by_user_id INT NOT NULL, dealer_id INT DEFAULT 0, disable_price_in_listings TINYINT DEFAULT 0, business_image VARCHAR(200), non_expiry INT DEFAULT 0 ); The query running is this: SELECT COUNT(DISTINCT id) as total FROM ( SELECT * , ( select value from listing_attributes where attribute_id=81 and listing_id=l.id ) as '81', ( select value from listing_attributes where attribute_id=78 and listing_id=l.id ) as '78' from vw_search l WHERE category_id IN ('884','882','880','885','871','949','873','875','876','434','424','422','423','425','426','546','750','752', '754','756','759','763','766','774','947','770','778','783','781','786','428','547','430','431','414','415', '712','420','548','432','433','418','419','959','961','960','358','359','360','364','361','363','357','1003', '560','1002','1006','1004','1007','1005','561','377','380','553','554','555','1021','556','557','559','558', '435','436','437','438','439','441','443','550','442','549','444','445','446','447','448','449','450','451', '714','452','551','453','454','455','456','615','459','460','461','462','463','464','468','469','466','467', '470','811','472','816','473','813','728','476','474','799','795','803','721','806','475','477','1009','479', '480','481','482','828','483','484','485','385','384','386','387','388','389','1018','833','500','504','502', '501','503','487','488','489','490','491','1020','493','494','495','498','497','496','421','975','1000','976', '973','977','951','511','512','509','513','515','514','838','840','412','413','1016','1014','1019','86','399' ,'397','398','1008','521','522','526','523','524','525','528','1053','535','529','530','850','533','532','1052', '969','968','966','965','539','538','967','1012','1013','1011','1024','1022','1023','541','542','545','543','544', '297','296','298','300','299','301','302','303','304','305','306','307','308','318','310','311','314','319','356','312', '313','315','316','317','717','941','718','723','726','719','38') ) as t WHERE ( `81` LIKE CONCAT('%','Honda','%') ) AND ( `78` BETWEEN CONVERT('1900', UNSIGNED INTEGER) AND CONVERT('2014', UNSIGNED INTEGER) ) AND (price BETWEEN CONVERT('2000', UNSIGNED INTEGER) AND CONVERT('5000', UNSIGNED INTEGER) ) AND (has_expired=0 OR non_expiry = 1) AND should_show=1 Obviously, this query is not efficient, and taking huge time to execute. Please suggest me a best way to optimize it. Adding Results of EXPLAIN command as per peterm below: id,select_type,table,type,possible_keys,key,key_len,ref,rows,Extra 1,PRIMARY,<derived2>,ALL,NULL,NULL,NULL,NULL,3386,"Using where; Using temporary; Using filesort" 2,DERIVED,l,ALL,category_fk,NULL,NULL,NULL,4660,"Using where" 2,DERIVED,u,eq_ref,PRIMARY,PRIMARY,4,tradezone.l.created_by_user_id,1, 2,DERIVED,lt,eq_ref,PRIMARY,PRIMARY,4,tradezone.l.listing_type_id,1, 2,DERIVED,<derived5>,ALL,NULL,NULL,NULL,NULL,5021, 5,DERIVED,l,ALL,NULL,NULL,NULL,NULL,4660, 5,DERIVED,lt,eq_ref,PRIMARY,PRIMARY,4,tradezone.l.listing_type_id,1, 5,DERIVED,bi,eq_ref,"user_unique,user_fk_idx,user_id",user_unique,4,tradezone.l.created_by_user_id,1, 5,DERIVED,u,eq_ref,PRIMARY,PRIMARY,4,tradezone.l.created_by_user_id,1, 5,DERIVED,lo,eq_ref,PRIMARY,PRIMARY,4,tradezone.l.location_id,1, 5,DERIVED,c,eq_ref,PRIMARY,PRIMARY,4,tradezone.l.category_id,1, 5,DERIVED,hd,ref,hot_deals_listing_fk_idx,hot_deals_listing_fk_idx,4,tradezone.l.id,1, 9,"DEPENDENT SUBQUERY",lp,ref,listing_id_fk,listing_id_fk,4,tradezone.l.id,1,"Using where; Using filesort" 8,"DEPENDENT SUBQUERY",p,ref,listing_id_idx,listing_id_idx,5,tradezone.l.id,1,"Using where; Using filesort" 6,"DEPENDENT SUBQUERY",p,ref,listing_id_idx,listing_id_idx,5,tradezone.l.id,1,"Using where; Using filesort" 3,"DEPENDENT SUBQUERY",listing_attributes,ref,"listing_fk,attribute_fk",listing_fk,5,func,2,"Using where" A: Try to rewrite this query in this way: SELECT distincd( id ) FROM vw_search l JOIN listing_attributes l81 ON l81.listing_id=l.id AND l81.attribute_id=81 AND l81.value LIKE CONCAT('%','Honda','%') JOIN listing_attributes l78 ON l78.listing_id=l.id AND l78.attribute_id=78 AND l78.value BETWEEN CONVERT('1900', UNSIGNED INTEGER) AND CONVERT('2014', UNSIGNED INTEGER) WHERE l.category_id IN ('884','882','880' ....... ......................... .......................,'719','38' ) AND l.price BETWEEN CONVERT('2000', UNSIGNED INTEGER) AND CONVERT('5000', UNSIGNED INTEGER) AND (l.has_expired=0 OR l.non_expiry = 1) AND l.should_show=1
[ "stackoverflow", "0047237872.txt" ]
Q: Is memory released after each iteration while mapping over a list? Sorry if this is a beginner's question, but I need to be sure. When a function is called it may create temporary objects whose memory allocation should be released upon exit. My question is: When a function is mapped over a list, is the memory allocated by each function call released immediately or only after the whole list has been processed? This is an example, what the code does specifically is not meaningful, except that two objects (newList and newRec) are created within each function call. Will the memory allocated to newList and newRec be released after each "iteration" or will all memory be released only after the call to List.map exits? This probably should be easily figured out for a loop in an imperative language but I do not know how the F# compiler deals with such cases. type MyRecord = { AList: int list; Name: string } let myRecord = { AList = [1..100]; Name = "SomeRecord" } let foo (arec: MyRecord) i = let newList = arec.AList |> List.filter (fun x -> x >= i) let newRec = { arec with AList = newList } List.sum newRec.AList let res = [1..100] |> List.map (foo myRecord) A: Neither. F# has automatic memory management based on garbage collection. What causes a block of memory to be freed is not a syntactic condition, but a runtime condition. A block of memory is freed after it becomes unreachable. An object is reachable if there is a way to get at it from variables in the current scope. While the function foo is executing, newList and newRec are reachable, so they won't be freed. When the function returns, newList and newRec are no longer directly reachable, but what makes them freeable is that they are no longer indirectly reachable either. Consider the following variation of foo: let bar (arec: MyRecord) i = let newList = arec.AList |> List.filter (fun x -> x >= i) let newRec = { arec with AList = newList } newRec.AList When bar returns, the newRec object is no longer reachable, but the newList object still is, since it's returned by the function and therefore can be used by the function's caller. Automatic memory management means that you don't have to care about the life time of objects. In particular, it's impossible to attempt to access an object that has been freed¹: by construction, if you can access an object, it's reachable and thus not freed. In the specific case of foo, as soon as a call to foo returns, the newRec and newList objects that it created become unreachable. This doesn't necessarily mean that they'll be freed immediately; they will be freed, at the latest, during the next full garbage collector run. How long unreachable objects remain without being freed is a matter of garbage collector quality; it's a compromise between memory usage and performance (running the GC very often leaves little uncollected garbage but costs CPU time; running the GC very rarely consumes little CPU time but leaves a lot of uncollected garbage). In any case, the fact that you're calling foo multiple times via List.map is not relevant to memory management. Nothing special happens when List.map returns. ¹ Except by interacting with code written in other languages that use unmanaged memory. A: This is really a question about .NET rather than F#. The F# compiler can do things to increase or decrease allocation/deallocation, but as long as it doesn't produce code that holds on to references for longer than necessary, .NET should be able to release (garbage collect) the unused memory. For a simple function like List.map this should definitely be the case. The question of when exactly memory will be released is a very complex one on a platform like .NET, which has an advanced garbage collector that has been finely tuned with a lot of engineering resources over many years. It's a question I personally can't even begin to answer. However, I can demonstrate something with this simple experiment. In our mapping function, let's create a list with a million items in it and return its length: [1 .. 100] |> List.map (fun _ -> [1 .. 1_000_000].Length) When we map this function on a list with 100 items, it runs successfully and I get a result on my machine. Now let's return the actual million-long list in the mapping function and run it on a hundred-long list again: [1 .. 100] |> List.map (fun _ -> [1 .. 1_000_000]) This results in an exception: Exception of type 'System.OutOfMemoryException' was thrown. This shows that we can't fit a hundred lists with a length of 1 million in memory. But if the first piece of code was able to run, then it must be possible to fit at least 1 million-long list in memory at a time. Therefore, we can infer that there must be some garbage collection of intermediate lists happening before List.map finishes processing all items. However, it doesn't necessarily happen immediately after each iteration.
[ "stackoverflow", "0013520362.txt" ]
Q: Java structure - Is there ever a need to nest try statements? I have just been thinking about this, as it is possible but I want to know if it is considered "bad practice". I believe it is, but I want to ask for views on it to check my opinion. Is it bad to do something like this: try{ something(); somethingelse(); try{ foo(); bar(); }catch(Exception e){ e.printStackTrace(); } somethingelseagain(); }catch(Exception e){ e.printStackTrace(); } I think there should never be a need to do this, since anything that throws an exception would trigger the first catch anyway. Views are greatly appreciated. A: In your example, as written, the inner catch is a bit redundant. However, nested catches would have more use in circumstances such as: catching different exceptions doing something different in the handler block for the two catches inner catch might catch the exception, do something, then re-throw the same exception which the out catch block could catch Also, don't forget the potential use of the finally block, which can execute cleanup code even if an exception was caught. You should generally try to catch the most explicitly typed (i.e. specific) exception(s) as possible. The subject of exceptions is an interesting one, and not without controversy.
[ "stackoverflow", "0016134303.txt" ]
Q: Dropping Message into Message box in android HI I was wondering if there was way that I could place a message in my inbox when application is started. What I wanna do is that when I run my application I want that a message from number let say that is 034556343, body of the message would be "Application has started" should be in my Inbox of the phone. any Ideas? A: If you want to manually put some SMS to your inbox with a sender name then, ContentValues my_values = new ContentValues(); values.put("address", "034556343");//sender name values.put("body", "Application has started"); getContentResolver().insert(Uri.parse("content://sms/inbox"), my_values); You will also need the following permissions: <uses-permission android:name="android.permission.READ_SMS"/> <uses-permission android:name="android.permission.WRITE_SMS"/> Keep in mind that the SMS content provider isn't actually part of the SDK, and this code is not guaranteed to work on all past, present and future devices.
[ "math.stackexchange", "0002838107.txt" ]
Q: Volume when the region bounded by $x=y^2$ and $x=y+2$ is revolved about the $y$-axis How do you find the volume of the solid created when the region bounded by $x=y^2$ and $x=y+2$ is revolved about the $y$-axis? Thank you. A: You need to calculate $Volume = \int_a^bdV$, where finding $dV$ is most of the work. You begin by choosing to either divide the bounded area into horizontal rectangles each with height $dy$, or vertical rectangles with width $dx$. In either case, $dV$ is the expression for the volume of the solid obtained by revolving a general rectangle (of thickness either $dx$ or $dy$) about the axis in question. This solid with volume $dV$ will be either a thin disk/washer or a thin-walled cylinder. In this case, using horizontal rectangles will be much simpler. Rotating a horizontal rectangle about the y-axis creates a thin washer. The bounded area lies in the domain $$-1\le y \le 2.$$ In this domain, the distance from the y-axis to the left side of one of the horizontal rectangles is $$y^2$$ and the distance from the y-axis to the right side of a rectangle is $$y+2.$$ The horizontal rectangles have a thickness (height) of $$dy.$$ So now having determined the dimensions of the general horizontal rectangle, we can express the volume $dV$ of the solid created by rotating one of these rectangles around the y-axis as $$dV=[\pi \cdot (Outer Radius)^2 - \pi \cdot (InnerRadius)^2 ] \cdot (thickness) $$$$=[\pi \cdot (y+2)^2 - \pi \cdot (y^2)^2]\cdot dy$$ $$=\pi \cdot [(y+2)^2-(y^2)^2]\cdot dy$$ $$dV=\pi \cdot (-y^4 + y^2 + 4y + 4)\cdot dy$$ All that is left is to integrate, with limits of integration $y=-1$ and $y=2$: $$Volume = \int_{-1}^2dV$$ $$= \int_{-1}^2\pi \cdot (-y^4 + y^2 + 4y + 4)\cdot dy$$ $$= \pi [- \frac{1}{5} y^5 + \frac{1}{3} y^3 + 2y^2 + 4y]_{-1}^2$$ $$Volume = \frac{72 \pi}{5} = 14.4 \pi (units^3)$$
[ "gis.stackexchange", "0000087514.txt" ]
Q: Open source tool to convert a DEM to a 3D model I would like to convert a DEM (Digitial Elevation Model) file (e.g. from SRTM) into a 3D model that I can then edit with regular 3D modeling tools (e.g. Meshlab/Blender/etc.). However I'm using Ubuntu Linux. So, is there any open source programmes / tools that can do this? And if so, can you give me a simple guide for how to convert a DEM to a 3D model. (command line programmes perferred) A: Blender has a Python API. Therefore, I use Python in Blender and import the GDAL libraries and construct a Blender-native mesh directly from the GIS data. The only thing you need to be careful of is that the version of GDAL you have matches the version of Python in the Blender release you are using. EDIT Plugins: If you don't want to write your own script using the Blender Python API and GDAL, there are some plugins which are available as standard which may help: Import DXF There are importers for OBJ, X3D and VRML and some 3D GIS systems will export to these (e.g. ArcScene and NVIZ) though this route is maybe necessarily strictly free. There is an add-on for XYZ data but it is non-standard and aimed mainly at molecular data, though perhaps you could bend it to your will. For a full range of off-the-shelf importers for Blender see here. There is a PDS .IMG importer in Blender but GDAL can only read PDS IMG files (not to be confused with Erdas IMG files which are different). So, really, your best bet if you have a GeoTiff, ASC or just about any other height data raster is to write a little script to iterate over the raster as there is no ready-made plugin for most use-cases, unless you can export your DTM to DXF, VRML or OBJ. A: I have found that NVIZ (which is a part of the GRASS package) is a useful tool for visualizing DEM data as a 3D model. In order to install the GRASS plugin (if you already have QGIS installed), just navigate to Plugins --> Manage and Install Plugins --> Get More and install GRASS. Make sure it is checked in your Manage and Install Plugins list! Once you have GRASS installed start by adding your raster layer. You can do so by navigating to Layer -> Add Raster Layer -> Select Then create a new mapset in GRASS. Do so by navigating to Plugins -> GRASS -> New Mapset or use the GRASS tool bar that should be visible. A. Select a location for your GRASS dataset B. Enter a new location name of your choice C. Select your desired projection D. Select a region from the drop down list or manually select one using lat/long coordinates (you can look up the lat/long of your location on the web) E. Enter a new mapset name and then click Finish. Next you'll want to load your DEM or raster layer into GRASS. You'll do this by A. Navigating to Plugins -> GRASS -> Open GRASS tools B. Under “Modules List”, select “r.in.gdal.qgis” C. Under “Loaded layer”, select your layer from the dropdown list, and name the output file D. Click “Run” Now you need to add GRASS raster layer to you mapset A. Navigate toPlugins -> GRASS -> Add GRASS raster layer or click on . B. Select your location and mapset, and then select your layer and Click “OK” You might want to color your raster. If so, A. Make sure you selected the correct output raster layer B. Navigate to Plugins -> GRASS -> Open GRASS tools C. Under the “Modules List”, click on “r.colors.table”. D. Select the input layer, and then choose a“Type of color table” E. Hit “Run”. NOW for the fun part. Visualizing in 3D using NVIZ. So you'll want to A. Set a specific map region for 3D modeling by navigating to Plugins -> GRASS -> Edit Current GRASS Region. Then either manually select the desired region by drawing a red frame with your mouse or set the coordinates in the dialogue box that appears. (This helps NVIZ determine what resolution to use) B. Navigate to Plugins -> GRASS -> Open GRASS tools C. Under “Modules List”, select “nviz” D. Select the raster for Elevation and Color (they can be the same one), and click on the square to the right (which means “Use region of this map”) E. Hit "Run" Then play around with different views, heights and lighting until you have the desired image! Hope this helps and please let me know if you have any questions!
[ "stackoverflow", "0028326283.txt" ]
Q: Invoke a jQuery function on div clicking on different div I've a jQuery validation function. function validationCheck() { if($(this).val()==''){ $(this).addClass('validation-error'); return false; } } I need to invoke this function when I click on a button. $('#stepbutton1').click(function(){ $("#geocomplete").validationCheck(); //Call the function (this wont work) }); How can I invoke this function to check the validation on the id stepbutton1 ? A: You need to pass an element to the function as an argument: function validationCheck(element) { if($(element).val()==''){ $(this).addClass('validation-error'); return false; } } And then call it accordingly: $('#stepbutton1').click(function(){ validationCheck('#geocomplete'); }); A: Add function to jQuery prototype, it will be small jQuery plugin $.fn.validationCheck = function () { var $this = $(this); if ($this.val() == ''){ $this.addClass('validation-error'); return false; } } $('#stepbutton1').click(function(){ $("#geocomplete").validationCheck(); }); .validation-error { border: 1px solid #f00; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="stepbutton1">stepbutton1</button> <input id="geocomplete" />
[ "stackoverflow", "0054927421.txt" ]
Q: Find duplicate accounts (more than 1000) in Excel My client has more than 1000 accounts in Excel. For each account, it has an account name, stock name, and the allocation for each stock. The number of stocks in each account varies. The file looks like the following: Account Name Stock Name Stock Allocation MN001 ABC 40% MN001 ABD 60% MN002 ABC 50% MN002 ABD 40% MN002 EFG 10% MN003 ABC 20% MN003 ABD 40% MN003 QWE 40% MN004 ABC 40% MN004 ABD 60% MN005 ABC 20% MN005 ABD 40% MN005 QWE 40% How to find out whether there are duplicate accounts in the list? In the above sample case, MN001 and MN004 are duplicates. MN003 and MN005 are also duplicates. They are duplicates because they have the same stocks and the amount for each stock is the same. I have been working on this for the past few days. Many thanks for your help! The desired output: Account Name Duplicate(s) MN001 MN004 MN002 No duplicate MN003 MN005 MN004 MN001 MN005 MN003 A: Create a new column as a key for concatenating the first two columns =CONCATENATE(B2,C2) or =B2&C2 Key Account Name Stock Name Stock Allocation MN001ABC MN001 ABC 40% MN001ABD MN001 ABD 60% MN002ABC MN002 ABC 50% MN002ABD MN002 ABD 40% MN002EFG MN002 EFG 10% Then do a conditional formatting rule for duplicates on the key column EDIT: As per the comments With the data in columns A:C starting row 2 D2 = =IF(A2<>A1,B2&C2,D1&B2&C2) E2 = =AND(A3<>A2,COUNTIF(D:D,D2)>1) Results in Account Name Stock Name Stock Allocation Key Is Duplicate MN001 ABC 0.4 ABC0.4 FALSE MN001 ABD 0.6 ABC0.4ABD0.6 TRUE MN002 ABC 0.5 ABC0.5 FALSE MN002 ABD 0.4 ABC0.5ABD0.4 FALSE MN002 EFG 0.1 ABC0.5ABD0.4EFG0.1 FALSE MN003 ABC 0.2 ABC0.2 FALSE MN003 ABD 0.4 ABC0.2ABD0.4 FALSE MN003 QWE 0.4 ABC0.2ABD0.4QWE0.4 TRUE MN004 ABC 0.4 ABC0.4 FALSE MN004 ABD 0.6 ABC0.4ABD0.6 TRUE MN005 ABC 0.2 ABC0.2 FALSE MN005 ABD 0.4 ABC0.2ABD0.4 FALSE MN005 QWE 0.4 ABC0.2ABD0.4QWE0.4 TRUE
[ "german.stackexchange", "0000018910.txt" ]
Q: "Sich vorkommen" vs "Sich fühlen" In welchen Fällen wird sich vorkommen anstatt sich fühlen verwendet (bzw. bevorzugt)? Kann man im Kontext "You'll feel __" vorkommen benutzen? Also, beispielsweise: Du wirst dir da unruhig vorkommen. A: Der Unterschied zwischen beiden Phrasen ist sehr subtil, aus dem Englischen ins Deutsche kann man einen Satz nur mit genügend Kontext übersetzen, umgekehrt kann man wohl nur to feel verwenden. Wie Kilian Foth schon sagte, wird sich vorkommen typischerweise eher im negativen Kontext und auf sich selbst bezogen verwendet. Man umschreibt die Umstände, in denen man sich befindet, oder leitet eine Erklärung für die Umstände ein. Eine Aussage mit sich vorkommen satt mit sich fühlen wird oft verwendet, wenn man nicht so leicht Worte für eine komplexe Situation findet. Man kann die Aussagen, die sich mit sich vorkommen bilden lassen, aber auch mit sich fühlen umschreiben. Der Unterschied ist sehr subtil, es kommt dann stark auf mehr Erklärungen und Details an. Folgende Sätze sich (mit den genannten Unterschieden) gleichwertig: Ich komme mir veralbert/verarscht vor. / Ich fühle mich veralbert/verarscht. (Über mich wird subtil gescherzt, ich weiß aber, dass das nicht ernst gemeint ist) Ich komme mir missverstanden vor. / Ich fühle mich missverstanden. (Ich habe etwas gesagt, das missverstanden wurde. Ich weiß aber mit ziemlicher Sicherheit, dass es verstanden wurde) Ich komme mir fehl am Platz vor. / Ich fühle mich fehl am Platz. (Meine Kollegen sind viel kompetenter als ich, das gibt mir das Gefühl, hier nicht richtig zu sein.) Er sagte mir, er kam sich veralbert/verarscht vor. / Er sagte zu mir, er fühlte sich veralbert/verarscht. (Er sagte zu mir: "Ich komme mir veralbert/verarscht vor.") Mit sich fühlen wird sowohl mit positivem als auch negativem Inhalt verwendet. Einer negativen Aussage betonst Du die Aussage etwas mehr. Ich fühle mich gut. (Ich habe gerade meine Schwester wiedergesehen) Ich fühle mich krank. (Ich bin erkältet) Ich fühle mich nicht ernst genommen. (Auch wenn ich sage 1+1=2, glaubt man mir nicht. Allerdings: Wenn ein Komiker dies nach einem gelungenen Witz sagt, meint er es natürlich komisch ;) Er sagte mir, er fühle sich gut. (Er sagte zu mir: "Ich fühle mich gut".) Abgrenzungen: Eine positive Beschreibung mit sich vorkommen ist jedoch unüblich: Ich komme mir glücklich vor. Ich komme mir gut vor. Grammatikalisch sind die Sätze zwar korrekt, aber ihr Inhalt ist missverständlich oder kann gar falsch (als nicht ernst gemeint) aufgefasst werden. Der Satz Ich komme mir gut vor. (Ich habe gerade, nach vielen Fehlschlägen, ein paar Erfolge gehabt, das muntert mich auf und lässt mich positiv denken.) drückt aber eher Unsicherheit über die Aussage aus. Du sprichst über jemand anderes: Jetzt wird's verrückt: Wenn Du über jemand anderes mit Hilfe von vorkommen sprichst, meinst Du das Gesagte (eher) nicht wie Du es gesagt hast und sprichst etwas herablassend mit deinem Gegenüber: Du kommst Dir wohl gut vor, hm? (Dein Gegenüber hat dich durchschaut, er hat erkannt, dass Du ihn belogen hast und dich sicher fühlst) Du kommst Dir wohl schlau vor, oder? (Dein Gegenüber hat versucht, Dich zu täuschen, Du hast ihn jedoch durchschaut und willst ihn verunsichern.) Sonderfälle: Ich komme mir vor, wie der größte Glückspilz aller Zeiten. Hier wird etwas Positives mit sich vorkommen beschrieben. Die Person ist definitiv glücklich (sie meint es ernst), aber auf Grund der Umstände kann der Gesprächspartner bzw. Leser dies vielleicht nicht glauben oder Du drückst damit (im obigen Beispiel) extreme Freude aus Arzt: Wie geht es Ihnen? Patient: Ich komme mir komisch vor. […] (Der Patient kann sein Befinden nicht genau beschreiben.) Im Zweifel: drückst Du dich mit sich fühlen aus und gibst zusätzliche "Informationen" fragst bei Sätzen beider Phrasen genauer nach
[ "stackoverflow", "0011748065.txt" ]
Q: IOS Enterprise updates over-the-air hopefully this is an easy question, tho, I cannot find any specific answers. we've gone thru all the steps to update our enterprise app OTA. My question is, can I use AFNetworking to make the call? or what is the best way to call the link. (currently afnetworking is giving me errors but it may be something on our side.) I am using afnetworking exclusively, so would rather not change unless I have to. thanks in advance itms-services://?action=download-manifest&url=http://ourServer/Setup/manifest.plist NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:kiPADSetupLink]]; [request setTimeoutInterval:300]; NSLog(@"begin downloading app update"); AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { // handle success } failure:^(AFHTTPRequestOperation *operation, NSError *error) { // handle error } ]; [operation start]; A: No, you need the system to open that URL, you can't access it yourself. Use UIApplication's openURL: method.
[ "dba.meta.stackexchange", "0000000888.txt" ]
Q: Post Deleted Answer? The question below has an answer that was down-voted and then deleted by the owner. I was going to post something similar to the deleted answer. Would it be permissible to copy the deleted answer and post it as my own. If so should I cite them as the source or not cite them to respect their privacy? Or would proper protocol require me to create text of my own that says the same thing using my own words? Create a "barrier" (prevent parallel execution) in Oracle PL/SQL? A: Odds are they deleted it for a reason. I often find that I've written an answer, hit submit, then found that I missed something obvious. Write it in your own words, reread both, then post.
[ "stackoverflow", "0009648062.txt" ]
Q: why the sub Process couldn't access its data, in python the output is like this, so strange, as I thought in the run function, it should also output the list data list running [] append list [1] list running [] append list [1, 2] list running [] append list [1, 2, 3] list running [] append list [1, 2, 3, 4] list running [] append list [1, 2, 3, 4, 5] from multiprocessing import Process class A(Process): def __init__(self): Process.__init__(self) self.list = [] def append_list(self, item): self.list.append(item) print 'append list', self.list def run(self): while True: print 'list running', self.list import time time.sleep(2) a = A() a.start() i = 0 while True: i+=1 import time time.sleep(2) a.append_list(i) A: the fact that you are calling a function on the process class, doesn't mean it runs in the sub process. when you create your A object, the list is in the main process. when you run start() on it, the list gets copied to the child process (well, not exactly, but let's assume it for simplicity). then when the parent process calls the function, you are appending to a list that's only in the memory of the parent process. the one in the child, even though it has the same name, now belongs to a different python process. If you want to share state between processes, you need to use shared memory objects, or queue objects. see here: http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes
[ "stackoverflow", "0007532261.txt" ]
Q: AJAX and FormsAuthentication, how prevent FormsAuthentication overrides HTTP 401? In one application configured with FormsAuthentication, when a user access without the auth cookie or with an outdated one to a protected page, ASP.NET issue a HTTP 401 Unauthorized, then the FormsAuthentication module intercepts this response before the request end, and change it for a HTTP 302 Found, setting a HTTP header "Location: /path/loginurl" in order to redirect the user agent to the login page, then the browser goes to that page and retrieves the login page, that is not protected, getting an HTTP 200 OK. That was a very good idea indeed, when AJAX was not being considered. Now I have a url in my application that returns JSON data and it needs the user to be authenticated. Everything works well, the problems is that if the auth cookie expires, when my client side code call the server it will get a HTTP 200 OK with the html of the login page, instead a HTTP 401 Unauthorized (because the explained previously). Then my client side is trying to parse the login page html as json, and failing. The question then is : How to cope with an expired authentication from client side? What is the most elegant solution to cope with this situation? I need to know when the call has been successful or not, and I would like to do it using the HTTP semantic. Is it possible to read custom HTTP Headers from client side in a safe cross browser way? Is there a way to tell the FormsAuthenticationModule to not perform redirections if the request is an AJAX request? Is there a way to override the HTTP status using a HTTP header in the same way you can override the HTTP request method? I need the Forms authentication, and I would like to avoid rewrite that module or write my own form authentication module. Regards. A: I had the same problem, and had to use custom attribute in MVC. You can easy adapt this to work in web forms, you could override authorization of your pages in base page if all your pages inherit from some base page (global attribute in MVC allows the same thing - to override OnAuthorization method for all controllers/actions in application) This is how attribute looks like: public class AjaxAuthorizationAttribute : FilterAttribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationContext filterContext) { if (filterContext.HttpContext.Request.IsAjaxRequest() && !filterContext.HttpContext.User.Identity.IsAuthenticated && (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true).Count() > 0 || filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true).Count() > 0)) { filterContext.HttpContext.SkipAuthorization = true; filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized; filterContext.Result = new HttpUnauthorizedResult("Unauthorized"); filterContext.Result.ExecuteResult(filterContext.Controller.ControllerContext); filterContext.HttpContext.Response.End(); } } } Note that you need to call HttpContext.Response.End(); or your request will be redirected to login (I lost some of my hair because of this). On client side, I used jQuery ajaxError method: var lastAjaxCall = { settings: null, jqXHR: null }; var loginUrl = "yourloginurl"; //... //... $(document).ready(function(){ $(document).ajaxError(function (event, jqxhr, settings) { if (jqxhr.status == 401) { if (loginUrl) { $("body").prepend("<div class='loginoverlay'><div class='full'></div><div class='iframe'><iframe id='login' src='" + loginUrl + "'></iframe></div></div>"); $("div.loginoverlay").show(); lastAjaxCall.jqXHR = jqxhr; lastAjaxCall.settings = settings; } } } } This showed login in iframe over current page (looking like user was redirected but you can make it different), and when login was success, this popup was closed, and original ajax request resent: if (lastAjaxCall.settings) { $.ajax(lastAjaxCall.settings); lastAjaxCall.settings = null; } This allows your users to login when session expires without losing any of their work or data typed in last shown form. A: I'm stealing this answer heavily from other posts, but an idea might be to implement an HttpModule to intercept the redirect to the login page (instructions at that link). You could also modify that example HttpModule to only intercept the redirect if the request was made via AJAX if the default behavior is correct when the request is not made via AJAX: Detect ajax call, ASP.net So something along the lines of: class AuthRedirectHandler : IHttpModule { #region IHttpModule Members public void Dispose() { } public void Init(HttpApplication context) { context.EndRequest+= new EventHandler(context_EndRequest); } void context_EndRequest(object sender, EventArgs e) { HttpApplication app = (HttpApplication)sender; if (app.Response.StatusCode == 302 && app.Request.Headers["X-Requested-With"] == "XMLHttpRequest" && context.Response.RedirectLocation.ToUpper().Contains("LOGIN.ASPX")) { app.Response.ClearHeaders(); app.Response.ClearContent(); app.Response.StatusCode = 401; } } #endregion } You could also ensure the redirect is to your actual login page if there are other legit 302 redirects in your app. Then you would just add to your web.config: <httpModules> <add name="AuthRedirectHandler" type="SomeNameSpace.AuthRedirectHandler, SomeNameSpace" /> </httpModules> Anyhow. Again, actual original thought went into this answer, I'm just pulling various bits together from SO and other parts of the web. A: I was having issues implementing the accepted answer. Chiefly, my error logs were getting filled with Server cannot set status after HTTP headers have been sent errors. I tried implementing the accepted answer to question Server cannot set status after HTTP headers have been sent IIS7.5, again no success. Googling a bit I stumbled upon the SuppressFormsAuthenticationRedirect property If your .Net version is >= 4.5, then you can add the following code to the HandleUnauthorizedRequest method of your custom AuthorizeAttribute class. public sealed class CustomAuthorizeAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true; filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; base.HandleUnauthorizedRequest(filterContext); return; } base.HandleUnauthorizedRequest(filterContext); return; } } The important part is the if block. This is the simplest thing to do if you are on .Net 4.5 & already have custom authorization in place.
[ "ru.stackoverflow", "0001055155.txt" ]
Q: Как отсортировать двумерный vector Есть условный, уже инициализированный 2х вектор: std::vector<std::vector<int>> vec = { {3,2,1,4,5},{3,2,4,1,5} }; Как его можно отсортировать? std::sort(vec.begin(), vec.end()); Отрабатывает, но не сортирует. Я так понимаю нужен итератор для работы с колонками вектора? Но как его инициализировать? Или какие еще есть варианты? A: Вы можете сортировать вектор векторов, например так: std::vector<std::vector<int>> vec = { {3,2,1,4,5},{3,2,4,1,5}, {5, 6,2} }; std::sort(vec.begin(), vec.end(), [](const auto& v1, const auto& v2) { return v1.size() < v2.size(); }); и можете сортировать вектора_элементы(думаю вам это нужно): for (auto& v : vec) { std::sort(v.begin(), v.end()); }
[ "stackoverflow", "0004575609.txt" ]
Q: Grabbing a string from a continously changing text file in PHP Well, I have a text file that constantly changes. The part of the text file is this important line: e=username The username part of it changes constantly, but I need to capture the username part of e=username string and put it into a variable every time it changes. Problem is I don't know how to. The file name is replace.txt A: filemtime() returns the time the file was last modified. Poll this timestamp every so often and read the file to check for a new e=username entry if the timestamp is later than the previous time you checked. The timestamp is given in seconds, so there's no point checking it more than once a second. If you need more frequent updates, you'll have to read the file continuously as the last modified time is stored with second accuracy. To extract username from e=username, you can use preg_match(): if (preg_match("/^e=(.+)$/", "e=username", $matches)) print $matches[1];
[ "stackoverflow", "0008056045.txt" ]
Q: jQuery loop, only last ajax success executes So this is the heart of my Chrome Extension [here], [jq is jQuery.noConflict()] the jq('.pam div .fbCurrentActionLink') returns each "Poke" link on Facebook. It uses .each() to loop through each person [aka, each person's "poke" link], and on success, it replaces the text "Poke" with a bold & green "Poked" text. function execute() { jq('.pam div .fbCurrentActionLink').each(function () { anc=jq(this) uid=anc.attr('ajaxify').match(/(\d+)/)[0] //ajax var post_form_id = jq('#post_form_id').val(); var fb_dtsg = jq('input[name=fb_dtsg]').val(); //use AJAX to submit poke, via their fb id jq.ajax({ type: 'POST', url: 'ajax/poke.php?__a=1', data: 'uid=' + uid + '&pokeback=1&post_form_id=' + post_form_id + '&fb_dtsg=' + fb_dtsg + '&post_form_id_source=AsyncRequest', beforeSend: function(xhr){ xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); }, success: function(data, textStatus){ anc.html('<b style="color:green !important">Poked</b>'); } }); //ajax }); } Now, the problem is, let's say there are 3 pokes to return. It will only execute the .html() on the last one. I can't figure out why. A: I think the problem you're running into is that by the time the first ajax call is done, the value of anc has been overridden. Once the success event is triggered, anc is equal to it's value at the last iteration. To solve this, you must stop the values from being overridden or, during the loop, you must tie each ajax calls to the element where the results will be placed. To tie an ajax call to a dom element, you need to supply define the context of the ajax call. Give this a try, I'm hopeful it should work... jq.ajax({ type: 'POST', context: this, //added line url: 'ajax/poke.php?__a=1', data: 'uid=' + uid + '&pokeback=1&post_form_id=' + post_form_id + '&fb_dtsg=' + fb_dtsg + '&post_form_id_source=AsyncRequest', beforeSend: function(xhr){ xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); }, success: function(data, textStatus){ $(this).html('<b style="color:green !important">Poked</b>'); //changed to $(this) instead of anc } }); A: You have to prefix your variables by var. Otherwise, they're not locally (ie, in each) declared. If this is the case, the variable is overwritten at each iteration. function execute() { jq('.pam div .fbCurrentActionLink').each(function () { var anc = jq(this); // Added `var` var uid = anc.attr('ajaxify').match(/(\d+)/)[0]; // Added `var` ....
[ "physics.stackexchange", "0000231666.txt" ]
Q: Why couldn't the decay $\pi^- \to e^- + \bar\nu_e$ occur if electrons were massless? If we assume that electrons (just like neutrinos) are massless, why can’t the decay $\pi^- \rightarrow e^- + \bar{\nu}_e$ occur under the weak interaction? A: Since the spin of the charged $\pi$ is $0$, the spins of the daughter particles need to add up to $0$ as well, i.e., their spins need to be anti-parallel. That's nothing else than the conservation of angular momentum. Assuming the anti-neutrino to be massless, it is always right-handed. Right-handed means that the momentum vector and the spin vector are parallel, while left-handed means that the momentum vector and the spin vector are anti-parallel. This is well defined for a massless particle, since it travels at the speed of light, and there is no inertial frame in which the momentum vector would switch direction. Since the anti-neutrino is right-handed, the electron would need to be right-handed as well to conserve linear momentum and angular momentum (spin). But the decay of the $\pi$ happens via the weak interaction, i.e. via the $W$ boson. Since the $W$ boson is known to couple only to left-handed particles, the decay would be forbidden. Since the electron is not massless, it has a small left-handed component. The decay is suppressed, but not forbidden. The heavier muon has a larger left-handed component, and its decay is less suppressed. Hence, pions usually decay into muons, although they have less phase space available.
[ "stackoverflow", "0023235668.txt" ]
Q: Zurb Foundation 5: Grid Column Stacking I'm new to foundation and I only have the basic idea on how to use grids. I have these 3 columns that need to be stacked (see "mobile" image) when viewed on mobile/small screens. It should look something like this when in larger screens: Here's my current code. It's not quite what I wanted, and I'm starting to get confused. <div class="row"> <div class="large-12" style="background-color:#bdc3c7;"> <div class="medium-4 medium-push-8 columns" style="background-color: #1abc9c; border: 1px solid #2c3e50;"> <p>TOP ROW</p> </div> <div class="medium-8 medium-pull-4 columns" style="background-color: #e74c3c; border: 1px solid #2c3e50; height: 250px;"> <p>MIDDLE ROW</p> </div> <div class="medium-4 columns" style="background-color: #9b59b6; border: 1px solid #2c3e50;"> <p>BOTTOM</p> </div> </div> </div> A: This grid system will work for large and small screens <div class="row"> <div class="small-12 large-8 columns"></div> <div class="small-12 large-4 columns"></div> <div class="small-12 large-4 columns"></div> </div>
[ "stackoverflow", "0020511516.txt" ]
Q: Android application signing: Proguard returned with error code 1. see console I have built an application that uses JacksonJson as a library. I am trying to export it as a signed application and getting the proguard error. I have tried various solutions posted on the internet, but none seems to work. Any help will be appreciated. Console: Proguard returned with error code 1. See console Warning: com.fasterxml.jackson.jaxrs.base.JsonMappingExceptionMapper: can't find superclass or interface javax.ws.rs.ext.ExceptionMapper Warning: com.fasterxml.jackson.jaxrs.base.JsonParseExceptionMapper: can't find superclass or interface javax.ws.rs.ext.ExceptionMapper Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find superclass or interface javax.ws.rs.ext.MessageBodyReader Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find superclass or interface javax.ws.rs.ext.MessageBodyWriter Warning: com.fasterxml.jackson.databind.ext.DOMSerializer: can't find referenced class org.w3c.dom.bootstrap.DOMImplementationRegistry Warning: com.fasterxml.jackson.databind.ext.DOMSerializer: can't find referenced class org.w3c.dom.bootstrap.DOMImplementationRegistry Warning: com.fasterxml.jackson.databind.ext.DOMSerializer: can't find referenced class org.w3c.dom.bootstrap.DOMImplementationRegistry Warning: com.fasterxml.jackson.databind.ext.DOMSerializer: can't find referenced class org.w3c.dom.bootstrap.DOMImplementationRegistry Warning: com.fasterxml.jackson.jaxrs.base.JsonMappingExceptionMapper: can't find referenced class javax.ws.rs.core.Response$Status Warning: com.fasterxml.jackson.jaxrs.base.JsonMappingExceptionMapper: can't find referenced class javax.ws.rs.core.Response Warning: com.fasterxml.jackson.jaxrs.base.JsonMappingExceptionMapper: can't find referenced class javax.ws.rs.core.Response$ResponseBuilder Warning: com.fasterxml.jackson.jaxrs.base.JsonMappingExceptionMapper: can't find referenced class javax.ws.rs.core.Response$ResponseBuilder Warning: com.fasterxml.jackson.jaxrs.base.JsonMappingExceptionMapper: can't find referenced class javax.ws.rs.core.Response$ResponseBuilder Warning: com.fasterxml.jackson.jaxrs.base.JsonMappingExceptionMapper: can't find referenced class javax.ws.rs.ext.ExceptionMapper Warning: com.fasterxml.jackson.jaxrs.base.JsonMappingExceptionMapper: can't find referenced class javax.ws.rs.core.Response$Status Warning: com.fasterxml.jackson.jaxrs.base.JsonMappingExceptionMapper: can't find referenced class javax.ws.rs.core.Response Warning: com.fasterxml.jackson.jaxrs.base.JsonMappingExceptionMapper: can't find referenced class javax.ws.rs.core.Response$ResponseBuilder Warning: com.fasterxml.jackson.jaxrs.base.JsonMappingExceptionMapper: can't find referenced class javax.ws.rs.core.Response Warning: com.fasterxml.jackson.jaxrs.base.JsonMappingExceptionMapper: can't find referenced class javax.ws.rs.core.Response Warning: com.fasterxml.jackson.jaxrs.base.JsonMappingExceptionMapper: can't find referenced class javax.ws.rs.ext.ExceptionMapper Warning: com.fasterxml.jackson.jaxrs.base.JsonMappingExceptionMapper: can't find referenced class javax.ws.rs.ext.Provider Warning: com.fasterxml.jackson.jaxrs.base.JsonParseExceptionMapper: can't find referenced class javax.ws.rs.core.Response$Status Warning: com.fasterxml.jackson.jaxrs.base.JsonParseExceptionMapper: can't find referenced class javax.ws.rs.core.Response Warning: com.fasterxml.jackson.jaxrs.base.JsonParseExceptionMapper: can't find referenced class javax.ws.rs.core.Response$ResponseBuilder Warning: com.fasterxml.jackson.jaxrs.base.JsonParseExceptionMapper: can't find referenced class javax.ws.rs.core.Response$ResponseBuilder Warning: com.fasterxml.jackson.jaxrs.base.JsonParseExceptionMapper: can't find referenced class javax.ws.rs.core.Response$ResponseBuilder Warning: com.fasterxml.jackson.jaxrs.base.JsonParseExceptionMapper: can't find referenced class javax.ws.rs.ext.ExceptionMapper Warning: com.fasterxml.jackson.jaxrs.base.JsonParseExceptionMapper: can't find referenced class javax.ws.rs.core.Response$Status Warning: com.fasterxml.jackson.jaxrs.base.JsonParseExceptionMapper: can't find referenced class javax.ws.rs.core.Response Warning: com.fasterxml.jackson.jaxrs.base.JsonParseExceptionMapper: can't find referenced class javax.ws.rs.core.Response$ResponseBuilder Warning: com.fasterxml.jackson.jaxrs.base.JsonParseExceptionMapper: can't find referenced class javax.ws.rs.core.Response Warning: com.fasterxml.jackson.jaxrs.base.JsonParseExceptionMapper: can't find referenced class javax.ws.rs.core.Response Warning: com.fasterxml.jackson.jaxrs.base.JsonParseExceptionMapper: can't find referenced class javax.ws.rs.ext.ExceptionMapper Warning: com.fasterxml.jackson.jaxrs.base.JsonParseExceptionMapper: can't find referenced class javax.ws.rs.ext.Provider Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.StreamingOutput Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.Response Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.ext.MessageBodyReader Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.ext.MessageBodyWriter Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MediaType Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MultivaluedMap Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MediaType Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MediaType Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MediaType Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MediaType Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MediaType Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MediaType Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MediaType Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MediaType Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MediaType Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MediaType Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MultivaluedMap Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MediaType Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MultivaluedMap Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MediaType Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MultivaluedMap Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MediaType Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MultivaluedMap Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MediaType Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MediaType Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MediaType Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MultivaluedMap Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MediaType Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MultivaluedMap Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MediaType Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.core.MediaType Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.ext.MessageBodyReader Warning: com.fasterxml.jackson.jaxrs.base.ProviderBase: can't find referenced class javax.ws.rs.ext.MessageBodyWriter You should check if you need to specify additional program jars. Warning: there were 67 unresolved references to classes or interfaces. You may need to specify additional library jars (using '-libraryjars'). java.io.IOException: Please correct the above warnings first. at proguard.Initializer.execute(Initializer.java:321) at proguard.ProGuard.initialize(ProGuard.java:211) at proguard.ProGuard.execute(ProGuard.java:86) at proguard.ProGuard.main(ProGuard.java:492) Here is my project.properties file: # This file is automatically generated by Android Tools. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! # # This file must be checked in Version Control Systems. # # To customize properties used by the Ant build system edit # "ant.properties", and override values to adapt the script to your # project structure. # # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # Project target. target=android-18 android.library.reference.3=../ABCSourceCode/Libraries/ABCLibrary android.library.reference.4=../ABCSourceCode/Libraries/AndroidHorizontalListView android.library.reference.1=../ABCSourceCode/Libraries/ABS_Library android.library.reference.2=../ABCSourceCode/Libraries/google-play-services_lib android.library.reference.6=../ABCSourceCode/Libraries/volleyLibrary android.library.reference.5=../ABCSourceCode/Libraries/SlidingMenuForklibrary A: IN proguard config file, just skip all the above libs which are thrown in error by below mentioned way.. -keep class yourclassname.** { *; } In your case it would be -keep class javax.ws.rs.** { *; } -dontwarn com.fasterxml.jackson.** Try doing this and run build again.
[ "stackoverflow", "0006254245.txt" ]
Q: How to add a path to LDFLAGS I'm trying to set up a library called PBC (Pairing-based cryptography). And this library requires another library called GMP -(GNU Multiple-Precision Library). My problem is after installing GMP correctly, PBC gives an error of: gmp library not found add its path to LDFLAGS I have no idea what LDFLAGS is and how to add it to the path. PS: I'm using MinGW. A: The question is not really descriptive enough for anyone to answer well, but.... On a Unix-based system you would likely do something like this: $ export LDFLAGS="-R/the/path/to/the/gmp/lib -L/the/path/to/the/gmp/lib" $ ./configure $ make $ make install Windows environments with GNU make tools, will need minor tweaks.
[ "stackoverflow", "0056050837.txt" ]
Q: DynamoDB deny access to everyone but administrators and Lambda functions I have several AWS Lambda functions, each one containing the following aliases (stages): dev, qa and prod. Each of these functions have some environment variables which should have different values for each alias, but as setting environment variables on an alias level is not supported by Lambda, I've decided to use a DynamoDB table to store the variable values. Now as these variables contains sensitive information, I would like to make sure that access to this table is as restricted as possible. So I would like to deny access to everyone and only allow administrators and Lambda functions to access it. I know that I may provide access to the table by using the appropriate roles/policies on IAM, but how may I make sure that access will only be provided to the users/functions for which I explicitly provided access? A: Take a look at Parameter Store which is hierarchical and will allow you to set permissions per stage (example here) or you can control based on tags (example here). Or you could package the parameters with the Lambda function upload. For more ideas, see this article.
[ "stackoverflow", "0035127870.txt" ]
Q: "conflicting implementations" error in complex generic code, how to fix it? I have Base trait, implement Foo<B> for all type that implemented Bar<B>, now I want to special implement Foo<B> for all Foobar<B> struct, where B: Base: trait Base {} trait Foo<B: Base> {} trait Bar<B: Base> {} struct Foobar<B: Base> { _b: B } // delete either, compile success impl<B: Base, T: Bar<B>> Foo<B> for T {} impl<B: Base> Foo<B> for Foobar<B> {} fn main() { } The compile error is: <anon>:14:1: 14:41 error: conflicting implementations for trait `Foo` [E0119] <anon>:14 impl<B: Base, T: Bar<B>> Foo<B> for T {} ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <anon>:14:1: 14:41 help: see the detailed explanation for E0119 <anon>:15:1: 15:38 note: note conflicting implementation here <anon>:15 impl<B: Base> Foo<B> for Foobar<B> {} ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This is playground A: Your impls are overlapping and there is no general fix to this (other than "avoid the blanket impl if you want to specialize it later"). Having the possibility to have a more specialized version of the impl is currently in a RFC. An attempt at implementation is in this pull request.
[ "stackoverflow", "0017420762.txt" ]
Q: OData String Maxvalue, how long can it be? I´m getting the following metadata from OData: <Property Name="CustomerDesc" Type="Edm.String" MaxLength="Max" FixedLength="false" Unicode="true"/> I could not find any specification about how long: MaxLength="Max" can be. Is there any limitation? Thank you. A: From the OData V4 spec(preview and not the current version), 6.2.2 Attribute MaxLength A binary, stream or string property MAY define a positive integer value for the MaxLength facet attribute. The value of this attribute specifies the maximum length of the value of the property on a type instance. Instead of an integer value the constant max MAY be specified as a shorthand for the maximum length supported by the server. If no value is specified, the property has unspecified length. So, it is up to the server implementation to assign a value for max.
[ "stackoverflow", "0029796704.txt" ]
Q: Python; Retreving dictonary values with more than one index I'm trying to retrieve a message from a dictionary based off a value (foo); the problem I'm facing is that I have more than one index for each message. It is proving to be difficult to retrieve the same message when the index changes value. I know this may not make all that much sense, but I hope by looking at the code it will help. foo=int(input('What is foo'))#foo is always 1 to 10 bar={10:'10/10', (8 or 9):'message1', (6 or 7):'message2', (4 or 5):'message3', (2 or 3):'message4', (0 or 1):'message5', print(bar[foo]) This code is part of a larger program it is just with this part that I can't solve. Foo is predetermined so the user doesn't input it in the overall program. I have tried multiple fixes for this problem and any help would be greatly appreciated. A: If you want to use a single integer as a key, you could use math to simplify each key to a single unique value, for example bar = {5:'10/10', # 10 4:'message1', # 9 or 8 3:'message2', # 7 or 6 2:'message3', # 5 or 4 1:'message4', # 3 or 2 0:'message5'} # 1 or 0 >>> foo = 7 >>> bar[foo // 2] 'message2'
[ "stackoverflow", "0054819775.txt" ]
Q: How to flatten a json with nested lists by Jayway JsonPath? Currently I need to process some json results based on configuration but not hard code. For example, with the json as follows { data: [{ orderNo: "CG8310150", details: [{ skuId: 4384, amount: 2 }, { skuId: 4632, amount: 5 }] }, { orderNo: "CG8310151", details: [{ skuId: 4384, amount: 3 }] }] } I want the result as follows [{ orderNo: "CG8310150", skuId: 4384, amount: 2 }, { orderNo: "CG8310150", skuId: 4632, amount: 5 }, { orderNo: "CG8310151", skuId: 4384, amount: 3 }] If anyone has the solution with Jayway JsonPath, or has any suggestion of other tools, please let me known. Thanks for your help! A: You can project results from that JSON using JsonPath. For example: $['data'][*]['orderNo'] returns: ["CG8310150","CG8310151"] $['data'][*]['details'][*]['skuId', 'amount'] returns: [{"skuId":4384,"amount":2},{"skuId":4632,"amount":5},{"skuId":4384,"amount":3}] But you cannot combine both of those expressions in one pass through JsonPath so you cannot use JsonPath to return your target output.
[ "stackoverflow", "0027634310.txt" ]
Q: How to add my application in jConsole local process? I developed a Java application with the project name DMS. Now I want to judge the performance of the application by using jConsole. When i open the jConsole.exe frm jdk_installation/bin package i am unable to see my application name in the local process list excepting showing only one process sun.tools.jconsole.JConsole . Please provide any sugession to resolve this. A: You will need to pass on the following system arguments when starting JVM: -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=10200
[ "stackoverflow", "0049019473.txt" ]
Q: How to add recurring events pragmatically in DHTMLX Scheduler? I'd like to add this event to my calendar let eventID = scheduler.addEvent({ start_date: "2018-03-03 10:00:00", end_date: "2018-03-10 11:00:00", text: "words", details: "", rec_type: "week_1___1,2", }); However, when I run through that part of my code I get an error in dhtmlxscheduler.js Cannot read property 'valueOf' of undefined. What's the proper way to add an event as recurring. I've added the dependency js file for recurring events and specified the following in my init scheduler.config.details_on_create=true; scheduler.config.details_on_dblclick=true; scheduler.config.include_end_by = true; scheduler.config.repeat_precise = true; var today = new Date(); scheduler.init('scheduler_here',today, "week"); A: If you use addEvent for recurring events, the value of the start/end_date properties must have the Date type: let eventID = scheduler.addEvent({ id: '1', start_date: new Date(2018, 2, 3, 10), end_date: new Date(2018, 2, 10, 11), text:"words", details: "", rec_type: "week_1___1,2", event_pid: "0", event_length: 60*60*4 })
[ "stackoverflow", "0005816661.txt" ]
Q: ASIHTTPRequest no error when lost connection I am downloading file (with apache tomcat 6.0.32). When I make disconnect (shutdown tomcat) some times ASHITTPRequest generate error, but sometimes (most of times exactly...ALL TIME EXACTLY! Only if there is no connection at the beginning occurs error) it ends work like all correct. So there is the question: why this happened and how can I watch if the connection lost properly. Thanks a lot! UPDATE: Try to send request through TCPMon and then stop it (TCPMon) and get the same: ASIHTTPRequest think that the downloading correctly done. UPDATE: responseHeaders: "Content-Disposition" = attachment; "Content-Length" = 2277888; "Content-Type" = "application/octet-stream"; Date = "Thu, 28 Apr 2011 12:35:32 GMT"; Server = "Apache-Coyote/1.1"; "Set-Cookie" = "JSESSIONID=98CAE6C0C4275B528D5E0F8651546AFE; Path=/ISED"; responseStatusMessage: HTTP/1.1 200 OK UPDATE: If disconnect computer by hand (disconnect the cable) and get this: Sometime ASIHTTPRequest waits till timeout, and next request get connecting error. Sometime error occurs just in time I disconnect. Sometime error does not occurs just in time I disconnect: download progress missing and (if make connection again) it file starts download from the beginning. And if close port ASIHTTPRequest thinks that is successful download done. I can't understand this logic... SOLUTION: I solve the problem by comparing Content-Length in header and total bytes read: NSString *contentLength = [[self.request responseHeaders] valueForKey:@"Content-Length"]; NSString *downloadedBytesCount = [NSString stringWithFormat:@"%llu",[self.request totalBytesRead]]; if ([contentLength isEqualToString:downloadedBytesCount] == NO) { // error maintain } So I can check if I got all data and if not: maintain error. In other cases (like manually disconnect) ASIHTTPRequest work appropriate way and generates errors by self. A: for checking connection status i am using Reachability library with ASI. i believe Reachability comes with ASI not sure. this is not mine code i took from somewhere but it is working flawless. #import "Reachability.h" -(void)viewDidAppear:(BOOL)animated { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil]; } - (void) checkNetworkStatus:(NSNotification *)notice { NetworkStatus internetStatus = [internetReachable currentReachabilityStatus]; switch (internetStatus) { case NotReachable: { NSLog(@"The internet is down."); //self.internetActive = NO; break; } case ReachableViaWiFi: { NSLog(@"The internet is working via WIFI."); //self.internetActive = YES; break; } case ReachableViaWWAN: { NSLog(@"The internet is working via WWAN."); //self.internetActive = YES; break; } } } i have altered the code little bit regarding my needs it returns YES/NO. and you should remove observer at some point. - (void)viewDidUnload { [[NSNotificationCenter defaultCenter] removeObserver:self]; } thanks.
[ "stackoverflow", "0026254341.txt" ]
Q: Update not working with Kendo datasource I have an issue with Kendo Datasource, the update is never fired while the change is well fired with modified Object. The datasource is very simple : collection: new kendo.data.DataSource({ autoSync: false, batch: true, transport: { read: { url: "http://localhost:81/GPL/Main/Sources/GPL.Web.MVC/Vignette/Vignettes_Read", dataType: "json" //"jsonp" is required for cross-domain requests; use "json" for same-domain requests }, update: { url: "http://localhost:81/GPL/Main/Sources/GPL.Web.MVC/Vignette/Vignette_Update", dataType: "json" //"jsonp" is required for cross-domain requests; use "json" for same-domain requests }, schema: { model: { id: "Id" } } }, change: function (e) { console.log(this); console.log(e); //Not working too //if (e.action == "itemchange") { // debugger; // vignettesViewModel.collection.pushUpdate(e.items[0]); //} $('.vignette').detach(); for (var i = 0; i < vignettesViewModel.collection.data().length; i++) { vignettesViewModel.createVignetteUI(vignettesViewModel.collection.data()[i]); } vignettesViewModel.init() } }) For the test, autosync is set at false and batch is set at true. Later in code, I update the datasource and I fired explicity the datasource by sync() methods //Some logic up var data_hospit = vignettesViewModel.getByUid($(ui.element).data('uid')); //Another logic data_hospit.set('date_debut', cellDepart.data('date')); data_hospit.set('date_fin', cellArrivee.data('date')); data_hospit.set('PrenomNomEtDateDeNaissance', 'toto'); vignettesViewModel.collection.sync(); update is not fired but I see well that object changed go through change function. So why update is never fired ? I have well define model with id : 'Id' and if I change update string to a dummy function alert(), this is not working too. I ve tried to "force" update with pushUpdate but I have got an error "undefined function" Thanks for your help A: schema is not part of transport, you wrote: transport: { read: { url: "http://localhost:81/GPL/Main/Sources/GPL.Web.MVC/Vignette/Vignettes_Read", dataType: "json" //"jsonp" is required for cross-domain requests; use "json" for same-domain requests }, update: { url: "http://localhost:81/GPL/Main/Sources/GPL.Web.MVC/Vignette/Vignette_Update", dataType: "json" //"jsonp" is required for cross-domain requests; use "json" for same-domain requests }, schema: { model: { id: "Id" } } }, and it should be: transport: { read: { url: "http://localhost:81/GPL/Main/Sources/GPL.Web.MVC/Vignette/Vignettes_Read", dataType: "json" //"jsonp" is required for cross-domain requests; use "json" for same-domain requests }, update: { url: "http://localhost:81/GPL/Main/Sources/GPL.Web.MVC/Vignette/Vignette_Update", dataType: "json" //"jsonp" is required for cross-domain requests; use "json" for same-domain requests } }, schema: { model: { id: "Id" } }
[ "stackoverflow", "0020460259.txt" ]
Q: Tee - mimicking program only writes the initial input to file, ignoring all sequential inputs So I have a mytee program (with much much less functionality). Trying to learn how to work with pipes / children / etc (1) I do pipe (2) Create the file(s) (3) fork (4) the parent does scanf to get the text (5) sends the text to the pipe (6) child receives it and writes it to files -> #4 should be a loop until the user writes '.' -> #6 should continue writing new lines, but somewhere there is a breakdown. Some of the things that I think it might be: 1. Something is wrong with my permissions (but O_APPEND is there, and not sure what else I would need) 2. there may be a problem in parent do while loop, where it should send the msg to the pipe (fd[1]) 3. #6 where I strongly think my problem lies. After the initial write it doesn, continue writing. I am not sure if I need to somehow keep track of the size of bytes already written, but if that was the case I would expect the last message to be there not the first. I'm pretty much at a loss right now I run it using ./mytee test1 Code: ret = pipe (fd); if (ret == -1) { perror ("pipe"); return 1; } for (i=0;i<argc-1;i++) { if ((filefd[i] = open(argv[i+1], O_CREAT|O_TRUNC|O_WRONLY|O_APPEND, 0644)) < 0) { perror(argv[i]); /* open failed */ return 1; } } pid = fork(); if (pid==0) /* child */ { int read_data; do { read_data = read(fd[0], buffer, sizeof(buffer)); for(i=0;i<argc;i++) { write(filefd[i], buffer, read_data); } } while (read_data > 1); for (i=0; i<argc; i++) close(filefd[i]); return 0; } else { /* parent */ char msg[20]; do{ scanf("%s",msg); write(fd[1],msg,sizeof(msg)); }while (strcmp(msg,".")!=0); while ((pid = wait(&status)) != -1) fprintf(stderr, "process %d exits with %d\n", pid, WEXITSTATUS(status)); return 0; } Adding Output: $ ./a.out test1 qwe asd zxc . ^C It doesn't exit properly. I think the child is stuck in the loop And the contents of test1: qwe A: Working through this with the OP, reportedly the problem was unconditionally writing all 20 bytes of msg instead of just the NUL-terminated string contained within it. Suggested minimal fix: change scanf("%s",msg); write(fd[1],msg,sizeof(msg)); to scanf("%19s",msg); write(fd[1],msg,strlen(msg));
[ "bicycles.stackexchange", "0000038467.txt" ]
Q: How can a recumbent tadpole trike brake three wheels with only two levers? So this is probably a terrible idea, but I was looking at recumbent tadpoles recently and it just clicked. I would have two brake levers but three wheels. I would need to have to... 1.) Calibrate the two front brakes off of a single lever which I suspect would be maddening 2.) Only brake using the back wheel and one front wheel (turning when braking sounds like a bad idea) 3.) Forgo braking on the rear wheel since on bikes the front wheel does most braking. I suspect this is similar for trikes. I would instead be able to actuate the brakes on the left wheel with the left lever, right wheel with the right lever etc... So, the question is, what is the general brake setup for tadpole trikes? A: Most are set up with one lever that works two brakes at the same time. There are lots of different styles, such as this one for example. You can see that it has 2 ferrules instead of 1, most commonly used on dual disc brakes. There are other models that differ somewhat visually but the idea is the same. Many Trike levers also have a push button locking mechanism that functions like a parking brake so that it cant roll while engaged. A: Typically, you do not brake all three wheels of a recumbent tadpole trike, but only the front wheels, at least when the trike is in motion. Most high end tadpole recumbents use two brake levers which independently control the brakes on the corresponding front wheel. They may optionally have a third brake on the rear wheel which is used as an emergency or parking brake. From the ICE owner's manual: The front brakes are controlled with brake levers on the handlebars of your trike. The left lever operates the brake on the left wheel, and the right lever operates the brake on the right wheel. To brake, squeeze both brake levers at the same time with even pressure. Some specially adapted trikes may have a different lever setup. Catrike brakes work the same way. The Catrike has front brakes only, since in a breaking situation 90% of the weight is transferred to the front of the trike. The front brakes are also independent, meaning that you can break the right wheel only, or the left wheel only. Therefore, especially in high speed or downhill situations, it is mandatory that you pull both brakes at the same time and with the same intensity. If you elect however, to brake only with one brake, this could cause the trike to steer out of your path and cause serious injury or death. The same for HP Velotechnik trikes: In the standard assembly, both front wheel brakes are operated separately: The left brake lever operates the left front brake, the right brake lever operates the right front brake. If your tricycle is equipped with a rear brake or a parking brake, use this brake only as an emergency brake in the unlikely event of a failure of the front brakes. As do Greenspeed trikes: Remember braking in a corner with only the inside brake will not slow you down as it is unweighted and will lock up. Try and use both brakes in an emergency situation. We have heard stories of people cornering at speed with their drink bottle in one hand, having to brake mid-corner, and finding they have very little brakes to slow them down. Even lower-end recumbent trikes use the same method. TerraTrike works this way: To stop, squeeze both brake levers smoothly and with equal pressure. Each brake lever activates the corresponding brake on the front wheels. You will experience brake steer if you brake with only one side or unevenly. It is possible to tip the trike forward by stopping too fast. I have actually seen a single lever which controls both brakes, only on one line of tadpole trikes: the Windcheetah line. These use a control yoke for steering, rather than handlebars, and as a consequence must have only one brake lever. And you'll see these on velomobiles which also use a steering yoke. A: I have a three wheel recumbent with a dual front brake lever which controls both brakes at the same time with equal force, then the left lever is for the rear brake that uses a cantilever brake system. Hard braking I use the all three. My trike is electric and I wasn't going to face down in the road in case I had to stop at 40 mph. This set-up works great for me and I have never in 9 years had a wreck or been sent over the front wheels during a power stop. Wouldn't mind putting on hydraulics in the front but haven't seen a dual system that can split the two line to the front disc brakes. G
[ "unix.stackexchange", "0000386411.txt" ]
Q: How can I lock down USB Stick access on Linux workstation? I have a set of Linux workstations that only approved users should be plugging in approved USB storage devices. How can I restrict mounting new USB devices to certain groups? And is there a way to reject unrecognised devices? A: You probably want to look into a piece of software called USBGuard. It's designed specifically for handling this. Unfortunately it's not pre-packaged for many distros, but it is pretty easy to build locally and you probably already have most if not all of the dependencies installed on the systems in question. A custom solution is also possible, but ironically your best reference on how to do that is probably also USBGuard.
[ "stackoverflow", "0013930742.txt" ]
Q: jQuery: I need to show consecutive fields in a form at each new click I have 5 upload fields but I need to hide them except the first. Then at each click to show them one by one. I created the following script but it seems like item.show() is not displaying the hidden fields.10x first = $('.webform-client-form').find('div[id$="-ajax-wrapper"]').first(); first.after('<a id="addmore" href=#>[+] Add more</a>'); $('.webform-client-form').find('div[id$="-ajax-wrapper"]').each(function(){ $(this).hide(); first.show(); }); var c = 1;//counter $('#addmore').bind('click', function(e) { item = $('edit-submitted-file'+c+'-ajax-wrapper'); item.show(); ++c; if (c == 5) { $('#addmore').hide(); return false; } }); A: shouldn't this: var item = $('edit-submitted-file'+c+'-ajax-wrapper'); be var item = $('#edit-submitted-file'+c+'-ajax-wrapper'); //if using id or var item = $('.edit-submitted-file'+c+'-ajax-wrapper'); //if using class
[ "stackoverflow", "0046963038.txt" ]
Q: Perform Segue to another storyboard swift Hey I am performing a basic segue from a ViewController in one storyboard to another ViewController second storyboard. 1st storyboard : Main 2nd Storyboard : Settings I have a reference to settings.storyboard in Main.storyboard. below are the screen shot of my setup Storyboard Ref to Settings in Main My segue(attributes) to storyboard ref. I am using a custom segue, that slides from right to left : Destination VC in settings storyboard. My source VC is a navigation embedded-TableViewController, I perform following operation to segue there: let storyboard = UIStoryboard(name: "Settings", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "editprofile") as? EditProfile performSegue(withIdentifier: "settings", sender: nil) With the above setting I am still unable to segue to my Destination VC. I have serach stackoverflow alot and even implemented exactly, but am out of Luck. I just dont know where exactly I am going wrong. Thanks! A: The (withIdentifier: "editprofile") portion of your code seems wrong. In the images you showed, nothing has the identifier of "editprofile". I would change that to "Settings", as it seems like that is your segue's identifier.
[ "stackoverflow", "0017450887.txt" ]
Q: Manipulating two different rows I have the following SQL statement: SELECT TRUNC(TIDSPUNKT) AS PERIOD, QUEUE, ROUND(SUM(CASE WHEN BESVARET_25_SEK > 0 THEN BESVARET_25_SEK END ) / SUM(CASE WHEN ANTAL_KALD > 0 THEN ANTAL_KALD END) * 100) AS SVAR_PROCENT FROM KS_DRIFT.PERO_NKM_KØ_OVERSIGT WHERE TIDSPUNKT >= '2013-06-17' AND TIDSPUNKT <= '2013-07-02' AND ANTAL_KALD > 0 AND QUEUE not in ('TekniskHotline') GROUP BY TRUNC(TIDSPUNKT), QUEUE ORDER BY PERIOD This gives me the following result: As you can see i have highlighed two rows. in the above SQL statement im calculating two rows to get a percentage now here is the tricky part and my question instead of having "Erhverv" and "ErhvervOverflow" on a row i want to count them as one! is there any way to achieve this? A: You can use a case statement to assign the values both in the select and the group by: SELECT TRUNC(TIDSPUNKT) AS PERIOD, (case when QUEUE in ('Erhverv', 'ErhvervOverflow') then 'Erhverv' else QUEUE end) as QUEUE, ROUND(SUM(CASE WHEN BESVARET_25_SEK > 0 THEN BESVARET_25_SEK END ) / SUM(CASE WHEN ANTAL_KALD > 0 THEN ANTAL_KALD END) * 100) AS SVAR_PROCENT FROM KS_DRIFT.PERO_NKM_KØ_OVERSIGT WHERE TIDSPUNKT >= '2013-06-17' AND TIDSPUNKT <= '2013-07-02' AND ANTAL_KALD > 0 AND QUEUE not in ('TekniskHotline') GROUP BY TRUNC(TIDSPUNKT), (case when QUEUE in ('Erhverv', 'ErhvervOverflow') then 'Erhverv' else QUEUE end) ORDER BY PERIOD; Note that I included both values in the when clause. You could do: when QUEUE = 'ErhvervOverflow' then 'Erhverv' else QUEUE end). I think including both values makes the intention more clear.
[ "askubuntu", "0000145965.txt" ]
Q: How do I target a specific driver for libata kernel parameter modding? I'm running a 22-disk setup, 19 of those in a ZFS array, 15 of those backed by three port multipliers attached to SATA controllers driven by the sata_sil24 module. When running full speed (SATA2, 3 Gbps), the operation is pretty quirky. Simple read errors will throw an entire port multiplier into spasms for a long time, sometimes with pretty awful results. Booting with kernel parameter libata.force=1.5G to force SATA controllers into "legacy" speeds completely fixes all issues with the port multipliers. Thing is, my ZFS pool is backed by a fast cache SSD on my ICH10R controller. Another SSD on this same controller holds the system. Doing libata.force=1.5G immediately shaves about 100 MB/s off the transfer rate of my SSDs. For the root drive, that's not such a big deal, but for the ZFS cache SSD, it is. It effectively makes the entire zpool slower for sustained transfers than it would've been without the cache drive. Random access and fs tree lookups, of course still benefit. Listing the module options for sata_sil24, no such option exists. How to pass the libata.force=1.5G parameter on to just the three SATA controllers being backed by the sata_sil24 module? A: Ah! I found out! At http://www.kernel.org/doc/Documentation/kernel-parameters.txt, it states, libata.force= [LIBATA] Force configurations. The format is comma separated list of "[ID:]VAL" where ID is PORT[.DEVICE]. PORT and DEVICE are decimal numbers matching port, link or device. Basically, it matches the ATA ID string printed on console by libata. If the whole ID part is omitted, the last PORT and DEVICE values are used. If ID hasn't been specified yet, the configuration applies to all ports, links and devices. If only DEVICE is omitted, the parameter applies to the port and all links and devices behind it. DEVICE number of 0 either selects the first device or the first fan-out link behind PMP device. It does not select the host link. DEVICE number of 15 selects the host link and device attached to it. The VAL specifies the configuration to force. As long as there's no ambiguity shortcut notation is allowed. For example, both 1.5 and 1.5G would work for 1.5Gbps. The following configurations can be forced. * Cable type: 40c, 80c, short40c, unk, ign or sata. Any ID with matching PORT is used. * SATA link speed limit: 1.5Gbps or 3.0Gbps. * Transfer mode: pio[0-7], mwdma[0-4] and udma[0-7]. udma[/][16,25,33,44,66,100,133] notation is also allowed. * [no]ncq: Turn on or off NCQ. * nohrst, nosrst, norst: suppress hard, soft and both resets. * dump_id: dump IDENTIFY data. If there are multiple matching configurations changing the same attribute, the last one is used. So, the tricky part is finding out which port X and device Y (dmesg ataX.YY) is which controller and drive. I think - that notation matches PORT[.DEVICE], but there's also the W:X:Y:Z notation. I'm guessing ataX.YY :) Luckily, I just did this mapping manually last week (trying to identify a drive that was throwing spasms and resetting a host controller), so I have an exhaustive list already :) I couldn't find anywhere that the mappings from sdX to ataX.Y or W:X:Y:Z where listed, so I ended up simply yanking out SATA cables and watching which ataX.YY messages appeared in /var/log/messages ;) So, in my setup, it seems I need to do libata.force=1:1.5G,2:1.5G,3:1.5G Gonna have to try that out as soon as my ZFS scrub finishes, and report back :) Awesome! Hope this helps someone else :)
[ "stackoverflow", "0022323327.txt" ]
Q: SQL using match on multiple tables (with join) mysql_query("SELECT a.about,b.title,b.article,b.description FROM about a JOIN articles b ON b.user_id=a.user_id WHERE MATCH(b.title,b.article) AGAINST ('$search') "); This produces the error "Can't find FULLTEXT index matching the column list" But either of these will work... mysql_query("SELECT a.about,b.title,b.article,b.description FROM about a JOIN articles b ON b.user_id=a.user_id WHERE MATCH(b.title) AGAINST ('$search') "); mysql_query("SELECT a.about,b.title,b.article,b.description FROM about a JOIN articles b ON b.user_id=a.user_id WHERE MATCH(b.article) AGAINST ('$search') "); Text indexing is activated on all the columns that have been stated. A: There is no FULLTEXT index on b.title,b.article. Use your query as mysql_query("SELECT a.about,b.title,b.article,b.description FROM about a JOIN articles b ON b.user_id=a.user_id WHERE MATCH(b.title) AGAINST ('$search') and MATCH(b.article) AGAINST ('$search') "); or build index on b.title,b.article columns CREATE FULLTEXT INDEX t_a_articles_index ON articles (title, article) ... How create index in MySQL
[ "ja.stackoverflow", "0000063295.txt" ]
Q: VS Codeのツールバー?の名称 Visual Studio Codeのテーマカラーを変更しています。 このツールバーの正式名称はなんでしょうか? こちらのドキュメント内にプロパティが定義されていますか? https://code.visualstudio.com/api/references/theme-color A: このツールバーの正式名称はなんでしょうか? 公式ドキュメントの User Interface などのページでは名称に関して言及されていませんが、開発者ツールを用いて当該箇所の HTML を読むと、 aria-label 属性に Editor actions と書かれています。 こちらのドキュメント内にプロパティが定義されていますか? 少し読んでみましたが、見当たりませんでした。そのため、ここでは Custom CSS and JS Loader を使用した装飾の変更方法を紹介します。 まず、開発者ツールで装飾を変更したい要素の選択子を決定します。そして、それに対して Custom CSS and JS Loader によって装飾を適用します。たとえば、 Split Editor Right のアイコンを変更し、アイコンの色を赤色にしたい場合には、以下のように CSS を記述します。この結果として、以下の画像のような動作が得られます。 .codicon-split-horizontal::before { color: #ff0000; content: "\eb78"; } ここで、 editor actions のアイコンや背景色は祖先要素から継承された値や初期値 (透明色) を使用しているため、 editorGroupHeader.tabsBackground のような一部のオプションであれば editor actions に対しても有効である可能性はあります。しかし、それらは editor actions のみに対して適用される装飾ではないため制御しづらく、複雑な装飾には不向きだと思います。
[ "stackoverflow", "0008429243.txt" ]
Q: How to make many comboboxes with same options I have a page with many comboboxes with same options. Diferences is selected value only. Now I render all of them, and it take much time and about 2Mb traffic. I would like to have "fake" comboboxes with only one option, that is selected. Other options must be in only one exemplar, and render itself when I click on some fake combobox to change it value. A: Try this approach. You can then get the data once, and bind to all the drop downs.
[ "stackoverflow", "0010562266.txt" ]
Q: Need to remove object from list before insert new object? I'm learning C# and I'm doing a task where I'm using a list of objects. I thought if I inserted a new object, with list.insert(index, object) at a position where it already is an object, the prevous object was replaced!? But it seems that I have to remove it first with list.removeAt(index) before I can insert the new one, otherwise it was just added and the old left in the list. Is this correct or am I doing something wrong? A: The Insert Method inserts a new item at the specified index, making space as needed: list.Insert(1, "foo"); // Before After // // list[0] == "a" list[0] == "a" // list[1] == "b" list[1] == "foo" // list[2] == "c" list[2] == "b" // list[3] == "c" If you want to replace an item at a specified index, you can use the list's indexer: list[1] = "foo"; // Before After // // list[0] == "a" list[0] == "a" // list[1] == "b" list[1] == "foo" // list[2] == "c" list[2] == "c" See also: Indexers (C# Programming Guide) A: This is correct. But if you wanted to replace an item in the list at a specified index, why not just list[index] = newitem;
[ "stackoverflow", "0001962685.txt" ]
Q: Xcode STL C++ Debug compile error I have some file writing code that works as expected, but prints an error on Debug mode, no output errors in Release. Code: #include <iostream> #include <string> #include <fstream> #include <sstream> using namespace std; int main (int argc, char * const argv[]) { string cppfilename; std::cout << "Please enter the filename to create: "; while ( cppfilename == "" ) { getline(cin, cppfilename); // error occurs here } cppfilename += ".txt"; ofstream fileout; fileout.open( cppfilename.c_str() ); fileout << "Writing this to a file.\n"; fileout.close(); return 0; } Debug Output: Please enter the filename to create: Running… myfile FileIO(5403) malloc: *** error for object 0xb3e8: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug Created: myfile.txt Release Output: FileIO implementation C++ Please enter the filename to create: Running… myfile Created: myfile.txt Aside from not checking for the file descriptor being open (for simplicity) what is wrong with this code? Update: I broke the code down to the following and it still errors: string cppfilename; getline(cin, cppfilename); // error here A: This looks to me like a bug in Apple's libstdc++, at least when compiled in debug mode. If I compile the two line reduction you gave above: #include <iostream> #include <string> using namespace std; int main() { string cppfilename; getline(cin, cppfilename); // error here return 0; } With the following command line (with defines taken from Xcode's default settings for a Debug build in a C++ project): g++ -D_GLIBCXX_DEBUG=1 -D_GLIBCXX_DEBUG_PEDANTIC=1 -g -o getline getline.cpp Then I get the same error that you saw: $ ./getline foo getline(74318) malloc: *** error for object 0x1000021e0: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug Abort trap This pops up a crash report, which gives us a stack trace (you can also get a stack trace from the debugger by running this under Xcode; I just wanted to reproduce it in as clean an environment as possible, to try and isolate the cause, without anything else strange Xcode might be doing): Thread 0 Crashed: Dispatch queue: com.apple.main-thread 0 libSystem.B.dylib 0x00007fff83c37fe6 __kill + 10 1 libSystem.B.dylib 0x00007fff83cd8e32 abort + 83 2 libSystem.B.dylib 0x00007fff83bf0155 free + 128 3 libstdc++.6.dylib 0x00007fff813e01e8 std::string::reserve(unsigned long) + 90 4 libstdc++.6.dylib 0x00007fff813e0243 std::string::push_back(char) + 63 5 libstdc++.6.dylib 0x00007fff813c92b5 std::basic_istream<char, std::char_traits<char> >& std::getline<char, std::char_traits<char>, std::allocator<char> >(std::basic_istream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&, char) + 277 6 getline 0x00000001000011f5 std::basic_istream<char, std::char_traits<char> >& std::getline<char, std::char_traits<char>, std::allocator<char> >(std::basic_istream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&) + 64 (basic_string.h:2451) 7 getline 0x0000000100000cbf main + 34 (getline.cpp:10) 8 getline 0x0000000100000c04 start + 52 This looks an awful lot like a bug to me. We're using some standard library functions in the most trivial possible way, and hitting an assertion failure. At this point, if we were using proprietary software (which much of Apple's software is, but luckily libstdc++ is free software), we would have to give up, file a bug report with our vendor, and try to find a workaround. Luckily, this is free software, so we can investigate the root cause. Unfortunately, I don't have the time at the moment to track this down to the root cause, but the source is available for perusal. You should probably file a bug about this. A workaround in this case would be to remove the _GLIBCXX_DEBUG=1 definition (and probably the _GLIBCXX_DEBUG_PEDANTIC=1 as well). You can do this in Xcode by finding your Target, double clicking on the executable it builds, going to the build tab, making sure the configuration is set to Debug, scrolling down to the GCC 4.2 - Preprocessing section, and deleting the two values from the Preprocessor Macros line. This way the code will build and run, and seems to work in this case, but you'll get fewer assertions that the debug build of the standard library might have been able to catch. A: This looks to be another case of _GLIBCXX_DEBUG being broken with gcc 4.2 on Mac OS X. Your best options look to be to drop _GLIBCXX_DEBUG or to switch to gcc 4.0.
[ "stackoverflow", "0002184372.txt" ]
Q: How do I save an NSString as a .txt file on my apps local documents directory? How do I save an NSString as a .txt file on my apps local documents directory (UTF-8)? A: NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory NSError *error; BOOL succeed = [myString writeToFile:[documentsDirectory stringByAppendingPathComponent:@"myfile.txt"] atomically:YES encoding:NSUTF8StringEncoding error:&error]; if (!succeed){ // Handle error here } A: Something like this: NSString *homeDirectory; homeDirectory = NSHomeDirectory(); // Get app's home directory - you could check for a folder here too. BOOL isWriteable = [[NSFileManager defaultManager] isWritableFileAtPath: homeDirectory]; //Check file path is writealbe // You can now add a file name to your path and the create the initial empty file [[NSFileManager defaultManager] createFileAtPath:newFilePath contents:nil attributes:nil]; // Then as a you have an NSString you could simple use the writeFile: method NSString *yourStringOfData; [yourStringOfData writeToFile: newFilePath atomically: YES];
[ "stackoverflow", "0043471724.txt" ]
Q: strcpy working no matter the malloc size? I'm currently learning C programming and since I'm a python programmer, I'm not entirely sure about the inner workings of C. I just stumbled upon a really weird thing. void test_realloc(){ // So this is the original place allocated for my string char * curr_token = malloc(2*sizeof(char)); // This is really weird because I only allocated 2x char size in bytes strcpy(curr_token, "Davi"); curr_token[4] = 'd'; // I guess is somehow overwrote data outside the allocated memory? // I was hoping this would result in an exception ( I guess not? ) printf("Current token > %s\n", curr_token); // Looks like it's still printable, wtf??? char *new_token = realloc(curr_token, 6); curr_token = new_token; printf("Current token > %s\n", curr_token); } int main(){ test_realloc(); return 0; } So the question is: how come I'm able to write more chars into a string than is its allocated size? I know I'm supposed to handle mallocated memory myself but does it mean there is no indication that something is wrong when I write outside the designated memory? What I was trying to accomplish Allocate a 4 char ( + null char ) string where I would write 4 chars of my name Reallocate memory to acomodate the last character of my name A: know I'm supposed to handle mallocated memory myself but does it mean there is no indication that something is wrong when I write outside the designated memory? Welcome to C programming :). In general, this is correct: you can do something wrong and receive no immediate feedback that was the case. In some cases, indeed, you can do something wrong and never see a problem at runtime. In other cases, however, you'll see crashes or other behaviour that doesn't make sense to you. The key term is undefined behavior. This is a concept that you should become familiar with if you continue programming in C. It means just like it sounds: if your program violates certain rules, the behaviour is undefined - it might do what you want, it might crash, it might do something different. Even worse, it might do what you want most of the time, but just occasionally do something different. It is this mechanism which allows C programs to be fast - since they don't at runtime do a lot of the checks that you may be used to from Python - but it also makes C dangerous. It's easy to write incorrect code and be unaware of it; then later make a subtle change elsewhere, or use a different compiler or operating system, and the code will no longer function as you wanted. In some cases this can lead to security vulnerabilities, since unwanted behavior may be exploitable.
[ "stackoverflow", "0040752239.txt" ]
Q: Local X from FOR to event i have problem here : w = st.getREFkartaFalse(x).getHodnotaKarty(); Error : local variables referenced from a lambda expression must be final or effectively final is there any way take value from local x into event ? else if (st.getHracTrueAleboHracFalse() == false) { for (int x = 0; x < st.getHracFalse().size(); x++) { getChildren().remove(st.getKartaHracFalse(x)); } st.zoberKartuFalse(); for (int x = 0; x < st.getHracFalse().size(); x++) { final int offsetx = 80; st.getREFkartaFalse(x).setTaleboF(false); st.getKartaHracFalse(x).setTranslateX((400 + (offsetx * x))); st.getKartaHracFalse(x).setTranslateY((780)); getChildren().addAll(st.getKartaHracFalse(x)); st.setPomPocitadloFalse(x); st.getKartaHracFalse(x).setOnMousePressed(eventUI -> { int q; int w; q = st.getArrayListkartyArrayList().size(); w = st.getREFkartaFalse(x).getHodnotaKarty(); if (w == q) { } }); } st.setHracTrueAleboHracFalse(true); } A: Yes. You have to capture the value of x in a local (implicitly) final variable: ... st.setPomPocitadloFalse(x); int y = x; // <=========================== Capture value of x st.getKartaHracFalse(x).setOnMousePressed(eventUI -> { int q; int w; q = st.getArrayListkartyArrayList().size(); w = st.getREFkartaFalse(y).getHodnotaKarty(); // <======== use here if (w == q) { } });
[ "drupal.stackexchange", "0000084920.txt" ]
Q: How can I sort a view based on a rewritten field? I have a view of a content type that contains two different date fields (one with date repeats and one multivalued single dates). Only one date field is filled out at any given time. In the view's display, I have combined the two fields by hiding the first date field and rewriting the second and including the replacement token of the first and second. Is there any way to now use the rewritten field to sort the view in ascending order based on this combined date field? It appears it sorts it based on the original value of the date field. I have done my research and have only found old, somewhat-related, threads with dead-ends. views sorting by rewritten field? Table does not sort on rewritten field, but on original field Views: custom field for sort criteria Sort by global:custom text. Is it possible? I was hoping there is a new or sneaky way of making this happen. A: If you don't want to go for the module route, this is one alternative: 1) install Computed Field module 2) add a computed field to your content type 3) in the field settings, in the Computed code (PHP) textarea, you can access the field data. Get your date fields in your current langugage to a variable. $repeating_dates = field_get_items($entity_type, $entity, 'field_repeating_date_example'); $multidates = field_get_items($entity_type, $entity, 'field_multidate_example'); Your date values can now be found in $repeating_dates[0]['value'], $repeating_dates[1]['value'], $repeating_dates[2]['value'], etc. $multidates[0]['value'], $multidates[1]['value'], $multidates[2]['value'], etc. Do whatever logic you need with your date fields and assign the result to $entity_field[0]['value'] Now you have a sortable field you can use in views, but first you have to update all the nodes as the computed field will only be computed and saved to the database at node save. There are many ways to do this, one is using Views Bulk Operations, it gives you an option to re-save nodes at admin/content.
[ "stackoverflow", "0007645714.txt" ]
Q: Using a checkbox to delete an object in rails? I've got the following form: <%= form_for(@subscription = @task.subscriptions.build(:user_id => subscribers.id)) do |f| %> <%= f.check_box :subscribed, :class => 'submittable' %> <%= f.label :subscribed, subscribers.full_name %> <%= f.hidden_field :user_id, :value => subscribers.id %> <%= f.hidden_field :task_id, :value => @task.id %> <% end %> The 'submittable' class on the checkbox causes the form to be submitted (via jQuery) on update. :susbcribed is returned via a method in model that returns whether a user is subscribed or not - it cannot be modified directly. The controller is available here: http://pastebin.com/zZy6KcXz - it is the standard scaffold. When I click the checkbox, the subcription is successfully created, but I cannot work out how to get it to delete the subscription when unticked. A: cjm, in follow up to jimworm's answer, the controller's destroy method is called when you DELETE (HTTP verb, it's actually a POST with a _method=DELETE field passed since some browsers don't support the DELETE verb. as he said: <%= link_to 'Delete', @model, :confirm=> 'Are you sure?', :method=> :delete %> The route is the same as your show or GET /models/1 but the verb DELETE is used instead, DELETE /models/1 which is actually POST /models/1 with a hidden field _method=DELETE passed in order to support all browsers. As he also mentioned, Rails automatically figures out which action to use when using form_for by checking to see if the @model is a new_record? (no id yet) or an existing one. It will then pick POST /models for create or PUT /models/1 for update
[ "stackoverflow", "0026899725.txt" ]
Q: Chromedriver extension id does not match key in manifest.json I am testing a chrome extension using selenium webdriver.js and chromedriver. I've been able to successfully launch chrome, with my extension installed, but the extension id is randomly generated instead of matching the key property of my manifest.json. This makes it impossible to test extension pages like the options page. manifest.json // ... "key": "pjnhffdkdckcagdmfmidafhppbomjdjg", // id from chrome web store // ... test.js var webdriver = require('selenium-webdriver'); var chrome = require('selenium-webdriver/chrome'); // load unpacked extension var chromeOptions = new chrome.Options(); chromeOptions.addArguments('load-extension=/path/to/my/extension'); var service = new chrome.ServiceBuilder().build(); var driver = chrome.createDriver(chromeOptions, service) // this page is not available T_T driver.get('chrome-extension://pjnhffdkdckcagdmfmidafhppbomjdjg/html/options.html'); My assumption is that the extension id would match the key (and it does when installing from the web store), but this does not seem to be true for loading the extension via chromedriver. Is there a way to get the loaded extension to have a consistent ID? Or should I take another approach? A: The manifest key value is not the extension ID. You have to install the extension from the web store and look in the manifest.json file on your desk. Use they key value inside that file. The documentation describes how to find the install directory.
[ "stackoverflow", "0034672868.txt" ]
Q: I want to pop up a confirmation message after all message after submitting This my jsp page and i'm doing Employee management work now and i want to popup a confirmation message after all my validations are successful or true and it should ask user yes or no. for the submission of the form. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <%@ page session="false" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Employee Management System</title> <link href="CSS/style.css" rel="stylesheet" type="text/css" /> <script src="http://code.jquery.com/jquery-1.10.2.js"></script> <script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script> <link rel="stylesheet" type="text/css" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/smoothness/jquery-ui.css" /> <script language="javascript" type="text/javascript"> function checkform(pform1){ var str=pform1.bloodGroup.value; var email = pform1.email.value; var phone = pform1.phoneNumber.value; var cleanstr = phone.replace(/[\(\)\.\-\ ]/g, ''); var err={}; var validemail =/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; var income = pform1.annualIncome.value; var Id = pform1.employeeId.value; var salary = income.replace(/[\(\)\.\-\ ]/g, ''); var Eid = Id.replace(/[\(\)\.\-\ ]/g, ''); //check required fields //password should be minimum 4 chars but not greater than 8 if (((str.length < 1) || (str.length > 3))&& (!(str.notequals("")))) { err.message="Invalid blood group"; err.field=pform1.bloodGroup; } //validate email else if( (email != "") && !(validemail.test(email))){ err.message="Invalid email"; err.field=pform1.email; } //check phone number else if (isNaN((cleanstr))) { err.message="Invalid phone number"; err.field=pform1.phoneNumber; } else if (isNaN((salary))) { err.message="Invalid Annual Income"; err.field=pform1.annualIncome; } else if (isNaN((Eid))) { err.message="Invalid EmployeeID"; err.field=pform1.annualIncome; } if(err.message) { document.getElementById('divError').innerHTML = err.message; err.field.focus(); alert(err.message); return false; } else { return true; } } </script> <script> $(function() { $( "#dateOfBirth" ).datepicker({ showOn: "button", buttonImage: "Pictures/calendicon.jpg" , buttonImageOnly: true, buttonText: "Select date", /* dateFormat: 'dd/mm/yy ' */ }); }); </script> </head> <body><center> <h2>Employee Management System</h2> <form:form method="POST" action="./add.html" modelAttribute ="employee" onsubmit="return checkform(this);" > <div id="errmsgbox"> <div id="divError"></div> </div> <table border="0" cellpadding="0" cellspacing="0"> <tr> <td width="14%">Employee ID<span class="mandatory" >*</span></td> <td width="35%"> <form:hidden path="ID" /> <form:input path="employeeId" required = "required"/></td> <td width="16%">Employee Name<span class="mandatory" >*</span></td> <td width="35%"><form:input path="employeeName" required = "required" /></td> </tr> <tr> <td>DOB<span class="mandatory" >*</span></td> <td><form:input path ="dateOfBirth" required = "required" id="dateOfBirth"></form:input></td> <style> img.ui-datepicker-trigger { width: 15px; height: 15px; } </style> <td>Blood group </td> <td><form:input path="bloodGroup" /></td> </tr> <tr> <td>Annual Income </td> <td><form:input path ="annualIncome" /></td> <td>Qualification</td> <td><form:input path ="qualification" /></td> </tr> <tr> <td>Pan No.</td> <td><form:input path="panNumber" /></td> <td>Phone No. </td> <td><form:input path="phoneNumber" /></td> </tr> <tr> <td>Sex</td> <td><form:radiobutton path="sex" value="m"/>Male <form:radiobutton path="sex" value="f"/>Female</td> <td>Email</td> <td><form:input path="email" /></td> </tr> <tr> <td>Address</td> <td colspan="3"><textarea name="" cols="" rows="2"></textarea></td> </tr> </table> <div> <input name="submit2" type="submit" title="Submit" value="Submit" /> <input type="button" name="reset_form" value="Reset" onclick="this.form.reset();"/> <a href="index.html"><input name="submit3" type="button" title="Reset" value="View All"/></a> </div> </form:form> </center> </body> </html> A: Replace you else block by following code in checkform(): if(confirm("Your question here?")) { return true; } else { return false; }
[ "stackoverflow", "0010119895.txt" ]
Q: Relations with TWIG Earlier i used Symfony 1.4. Now i learn Symfony 2. I do: http://symfony.com/doc/current/book/doctrine.html and i have: class Product { /** * @ORM\ManyToOne(targetEntity="Category", inversedBy="products") * @ORM\JoinColumn(name="category_id", referencedColumnName="id") */ protected $category; //... } and class Category { /** * @ORM\OneToMany(targetEntity="Product", mappedBy="category") */ protected $products; public function __construct() { $this->products = new ArrayCollection(); } //... } In Symfony 1.4 in foreach i can used: $result = findAll from Products. foreach ($results as $result){ echo $result->getCategory()->getName(); } How can i get relations (in this example Category) with TWIG system? {% for item in results %} <li><a href="{{ item.id }}">{{ item.name }} --- {{ item.category }} {{item.category.name}}</a></li> {% endfor %} item.category and item.category.name doesnt working. I can't find this in documentation. EDIT: OK, i know now. I dont have relation in one product. How can i protected before this? i have: id | name | category 1 | first | 1 2 | second | NULL 3 | third | 2 if in each row category is not null then this working OK, but if i have NULL in relations then i have error: Item "name" for "" does not exist in AcmeStoreBundle:Default:index.html.twig at line 3 What i can make with this? A: Add this to where you want to output the name. This will prevent twig from throwing that error. {% if item.category.name is defined %} {# print the name here #} {% endif %}
[ "stackoverflow", "0022015417.txt" ]
Q: OR Operator not working strictly in mysql php I want a strict condition with update, but it is not working here. I mean if level1 user log in and update a from and submit by this fields belongs to level2 get empty. My from user level from and entries them only. There are hidden fields also updating with null values. There is way to update only user level fields without effected hidden fields. if(!empty($_REQUEST['update'])){ $sql = "SELECT * FROM `tabl1` WHERE `ID` = ".$_REQUEST['update']; $query = mysql_query( $sql ); $res = mysql_fetch_array($query); $IndexNo= $_POST['IndexNo']; $ZoneID = $_POST['ZoneID']; $NameofCoordinator= $_POST['NameofCoordinator']; $GridNumber= $_POST['GridNumber']; $MobileNumber= $_POST['MobileNumber']; $StatusID= $_POST['StatusID']; $sql="UPDATE `tabl1` SET `IndexNo` = '$IndexNo',`ZoneID` = '$ZoneID'"; $sql .= if($userName =='admin' || 'level1'){ ",`NameofCoordinator` = '$NameofCoordinator'"; } $sql .= if($userName =='admin' || 'level2'){ ", `GridNumber` = '$GridNumber'"; } $sql .= if($userName =='admin' || 'level3'){ ",`MobileNumber` = '$MobileNumber'"; } $sql .= ",`Keyword` = '$Keyword', `StatusID` = '$StatusID' WHERE `ID` = ".$_REQUEST['update']; } A: See http://www.php.net/manual/en/language.operators.logical.php : $a || $b Or TRUE if either $a or $b is TRUE. So, $userName =='admin' || 'level3' evaluates to ($userName =='admin') || ('level3'), and since 'level3' is not falsy, this will always evaluate to true. What you probably want is $userName == 'admin' || $userName == 'level3'
[ "stackoverflow", "0005527651.txt" ]
Q: Need to add newline between include()ed css files I have a bunch of CSS files that get loaded on every page (header, global, main page, footer, etc.). I have written a simple PHP script that compiles them into a single string and then outputs that string. <?php set_include_path('../'); header('Content-Type: text/css'); $q = $_GET['q']; $patterns = array( '/.*[\.]{2,}.*/', '/,\//', '/^\//' ); $replacements = array( '', ',', '' ); $q = preg_replace($patterns, $replacements, $q); $css = explode(",", $q); $output = ''; foreach( $css as $link ) { $output .= include($link); } print $output; ?> it can be called (and the way I am calling it) like this: <?php $cssLinks = array( "/global/global.css", "/styles/local.css", $tmpl->headerContent['css']['link'], $tmpl->appContent['css']['link'], "/styles/css3buttons.css" ); $css = implode(",", $cssLinks); ?> <link rel="stylesheet" href="/components/CSS.php?q=<?= $css; ?>" type="text/css" /> Which results in a string like this: <link rel="stylesheet" href="/components/CSS.php?q=/global/global.css,/styles/local.css,/styles/header.css,/styles/index.css,/styles/css3buttons.css" type="text/css" /> This is fine, and - more importantly - it works. What is my question, then, you ask? It's a two-parter: What security vulnerabilities am I overlooking in the script? I've removed any directory traversal possibilities, but what else? I do need to be able to change what the links are, so I can't hard-code them into this script. For example, $tmpl->appContent['css']['link'] is a dynamic stylesheet for each page, of which there will be many. How can I add line breaks between the included files? I've added $output .= '\n\n'; in the foreach() loop, but it doesn't work. I'm still stuck with output like: #footer, #push { height: 3em; padding-top: 1em; }#header{ The CSS listed works but I would prefer to have the #header block two lines down, like: #footer, #push { height: 3em; padding-top: 1em; } #header{ (I apologize about the strange code block, Markdown broke horrendously on those hashes, and I couldn't figure out how to fix it). Note, this lack of line breaks only happens at the junction between two different files. The code inside each CSS file is formated just as it should be. A: You should prefer to pass only basenames to the CSS.php merge script: <link rel="stylesheet" href="CSS.php?q=global,local,header,index,css3buttons" type="text/css" > Then it becomes safer to implement in CSS.php with just: preg_match_all('#\w+#', $_GET["q"], $files); foreach ($files[0] as $fn) { foreach (array("global/$fn.css", "local/$fn.css") as $fn) if (file_exists($fn)) $content .= file_get_contents($fn); $content .= "\n\n"; } The only difference is that this script now has a little intelligence and knows where to look for the stylesheets. So you don't lose the flexibility of having variable stylesheet parts glued together.
[ "blender.stackexchange", "0000014202.txt" ]
Q: index out of range for UIList causes panel crash I am writing an addon that displays the mesh modifiers in a listbox, with the settings below the box. The issue I have is with the active index for the listbox - I'm using a custom property because there is no internal 'active' property for modifiers. The problem I have is that when the last modifier is removed, the index reaches true zero (index size zero), and I get a panel crash plus a console message: IndexError: bpy_prop_collection[index]:index 0 out of range, size 0 If I then re-add a modifier, the problem resolves and the panel(listbox) reappears. How can I structure this so the listbox doesn't crash when the index reaches size 0? Here's the backbone of the script: import bpy bpy.types.Object.modifier_active_index = bpy.props.IntProperty() def draw(self, context): layout = self.layout global num global atype global aname global amod num = bpy.context.object.modifier_active_index ob = context.object obname = context.object.name amod = bpy.data.objects[obname].modifiers[num] amods = bpy.data.objects[obname].modifiers atype = bpy.data.objects[obname].modifiers[num].type aname = bpy.data.objects[obname].modifiers[num].name rows = 2 row = layout.row() row.template_list("UI_UL_list", "", ob, "modifiers", ob, "modifier_active_index", rows=rows) Edit: class OBJECT_OT_modifier_move(bpy.types.Operator): #move active modifier down in stack bl_idname = "object.modifier_action" bl_label = "Modifier Action" action = bpy.props.EnumProperty( items=( ('UP', "Up", ""), ('DOWN', "Down", ""), ('REMOVE', "Remove", ""), ('ADD', "Add","") ) ) def invoke(self, context, event): ob = context.object idx = ob.modifier_active_index if self.action == 'ADD': if bpy.ops.object.modifier_add(type = '') == {'FINISHED'}: #how do I call the menu with modifier.type enums ob.modifier_active_index = len(ob.modifiers) - 1 try: mod = ob.modifiers[idx] except IndexError: pass else: if self.action == 'DOWN' and idx < len(ob.modifiers) - 1: if bpy.ops.object.modifier_move_down(modifier=mod.name) == {'FINISHED'}: ob.modifier_active_index += 1 elif self.action == 'UP' and idx >= 1: if bpy.ops.object.modifier_move_up(modifier=mod.name) == {'FINISHED'}: ob.modifier_active_index -= 1 elif self.action == 'REMOVE': bpy.ops.object.modifier_remove(modifier=mod.name) if idx >= 1: ob.modifier_active_index -= 1 return {"FINISHED"} A: You simply need to handle the case of an invalid index or an empty list of modifiers. You could for example test if len(ob.modifiers): ... if there are any, but I would rather catch all bad indices using try ... except IndexError: import bpy class OBJECT_PT_modifiers(bpy.types.Panel): bl_idname = "OBJECT_PT_modifiers" bl_label = "Modifiers" bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_context = "object" def draw(self, context): layout = self.layout rows = 2 ob = context.object idx = ob.modifier_active_index try: mod = ob.modifiers[idx] layout.label("%s (%s)" % (mod.name, mod.type), icon="MODIFIER") except IndexError: layout.label("no modifier selected") row = layout.row() row.template_list("UI_UL_list", "modifiers", ob, "modifiers", ob, "modifier_active_index", rows=rows) def register(): bpy.utils.register_module(__name__) bpy.types.Object.modifier_active_index = bpy.props.IntProperty() def unregister(): bpy.utils.unregister_module(__name__) del bpy.types.Object.modifier_active_index if __name__ == "__main__": register() Note that an index of -1 is not considered bad, because it refers to the last item in a list in Python. You shouldn't use global anywhere, it is certainly not needed. modifier_active_index is globally available for all objects, and you don't need globals inside the draw function to refer to the modifier. Also note that if you use UI_UL_list, the second argument should be some unique string to prevent collisions with other UI_UL_list that may exist in the panel. Edit: How to handle (re-)move actions while always showing the panel (even with no modifier) import bpy mod_icon_map = {m.identifier: m.icon for m in bpy.types.OBJECT_OT_modifier_add.bl_rna.properties['type'].enum_items} class OBJECT_OT_modifier_move(bpy.types.Operator): #move active modifier down in stack bl_idname = "object.modifier_action" bl_label = "Modifier Action" action = bpy.props.EnumProperty( items=( ('UP', "Up", ""), ('DOWN', "Down", ""), ('REMOVE', "Remove", ""), ) ) def invoke(self, context, event): ob = context.object idx = ob.modifier_active_index try: mod = ob.modifiers[idx] except IndexError: pass else: if self.action == 'DOWN' and idx < len(ob.modifiers) - 1: if bpy.ops.object.modifier_move_down(modifier=mod.name) == {'FINISHED'}: ob.modifier_active_index += 1 elif self.action == 'UP' and idx >= 1: if bpy.ops.object.modifier_move_up(modifier=mod.name) == {'FINISHED'}: ob.modifier_active_index -= 1 elif self.action == 'REMOVE': bpy.ops.object.modifier_remove(modifier=mod.name) if idx >= 1: ob.modifier_active_index -= 1 return {"FINISHED"} class MODIFIER_UL_listtype(bpy.types.UIList): #custom UIList type for modifiers def draw_item(self, context, layout, data, item, active_data, active_propname, index): modifier = item if self.layout_type in {'DEFAULT', 'COMPACT'}: layout.prop(modifier, "name", text="", emboss=False, icon=mod_icon_map[modifier.type]) icon = 'RESTRICT_RENDER_OFF' if item.show_render else 'RESTRICT_RENDER_ON' layout.prop(item, "show_render", text="", icon=icon, emboss=False) icon = 'RESTRICT_VIEW_OFF' if item.show_viewport else 'RESTRICT_VIEW_ON' layout.prop(item, "show_viewport", text="", icon=icon, emboss=False) icon = 'EDITMODE_HLT' if item.show_in_editmode else 'OBJECT_DATAMODE' layout.prop(item, "show_in_editmode", text="", icon=icon, emboss=False) elif self.layout_type in {'GRID'}: layout.alignment = 'CENTER' layout.label("", icon=mod_icon_map[modifier.type]) class OBJECT_PT_Modifiers(bpy.types.Panel): #panel draw class """Creates a Panel in the Object properties window""" bl_label = "Modifiers" bl_idname = "OBJECT_PT_Modifiers" bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_context = "object" def draw(self, context): layout = self.layout ob = bpy.context.object rows = 2 row = layout.row() row.template_list("MODIFIER_UL_listtype", "", ob, "modifiers", ob, "modifier_active_index", rows=rows) col = row.column(align=True) col.operator("object.modifier_add", icon='ZOOMIN', text="") col.operator("object.modifier_action", icon='ZOOMOUT', text="").action = 'REMOVE' col.separator() col.operator("object.modifier_action", icon='TRIA_UP', text="").action = 'UP' col.operator("object.modifier_action", icon='TRIA_DOWN', text="").action = 'DOWN' def register(): bpy.utils.register_module(__name__) bpy.types.Object.modifier_active_index = bpy.props.IntProperty() def unregister(): bpy.utils.unregister_module(__name__) del bpy.types.Object.modifier_active_index if __name__ == "__main__": register() Remarks: Creating a lookup dict is way better for icons Move up, move down and remove actions can be handled in a single operator Don't do ob.modifiers[ob.modifier_active_index] anywhere without range change or try/except construct Check the result of modifier_move_up() and modifier_move_down(), as it may fail (MultiRes can't be below a non-deforming modifier) All classes can be (un-)registered at once with (un-)register_module() Use consistent indentation (4 spaces for every level)
[ "stackoverflow", "0052439538.txt" ]
Q: Separate parts of string with explode I'm trying to get and display some data from the Wordpress database if the checkbox is checked using echo "<input type='checkbox' name='productinfo[]' value='" .$item->get_name() .$item->get_quantity() . $item->get_total() ."'>"; and printing it out using: $test = $_POST['productinfo']; for($i=0; $i < sizeof($test); $i++) { list($name, $quantity, $total) = explode(",", $test[$i]); echo "Name- ".$name; echo "<br>"; echo "Quantity ".$quantity; echo "<br>"; echo "Total ".$total; echo "<br>"; echo "<br/>"; } but the issue is that quantity and total are stuck together in a string at I cannot print the separate, is there a way to separate them from each other, it prints out like this currently, at the end 1 being the quantity and 279 being the total. A: You could try separating the strings with an unusual character, for example the '_' if it isn't contained in the name of the product (or the "|" for example) echo "<input type='checkbox' name='productinfo[]' value='" .$item->get_name() . "_" . $item->get_quantity() . "_" . $item->get_total() ."'>"; This way you can retrieve the different values using explode("_", $checkbox_value)(PHP) or checkbox_value.split("_") (JS)
[ "stackoverflow", "0031866390.txt" ]
Q: How do I get the right "this" in an Array.map? I assume there is some application of call or apply here but I'm not sure how to implement it. http://codepen.io/anon/pen/oXmmzo a = { foo: 'bar', things: [1, 2, 3], showFooForEach: function() { this.things.map(function(thing) { console.log(this.foo, thing); }); } } a.showFooForEach(); Say I want to map an array, but in the function, I need access to the this to which foo belongs. The function of map creates a new this context, so I obviously need to coerse that context back in somehow, but how do I do that while still having access to thing? A: Just realized I should have read the documentation for Array.map() more carefully. One simply needs to pass in the this value as the second parameter of map() http://codepen.io/anon/pen/VLggpX a = { foo: 'bar', things: [1, 2, 3], showFooForEach: function() { this.things.map(function(thing) { console.log(this.foo, thing); }, this); } } a.showFooForEach(); In addition, understanding how bind(), call() and apply() work are a must for serious JavaScript developers. These allow us to skip silly assignments like var self = this; myItems.map(function(item) { self.itemArray.push(item); }); with myItems.map(function(item) { this.itemArray.push(item); }.bind(this)); A: As of 2018, you could use an arrow function: a = { foo: 'bar', things: [1, 2, 3], showFooForEach: function() { this.things.map((thing) => { console.log(this.foo, thing); }); } } a.showFooForEach(); You could use bind() it to your context. a = { foo: 'bar', things: [1, 2, 3], showFooForEach: function() { this.things.map(function(thing) { console.log(this.foo, thing); }.bind(this)); } } a.showFooForEach(); That's because of JS lexical scope From MDN: The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind And here: http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/ Also, map() does accept a second parameter as "this" a = { foo: 'bar', things: [1, 2, 3], showFooForEach: function() { this.things.map(function(thing) { console.log(this.foo, thing); }, this); } } a.showFooForEach(); From MDN map() documentation: Parameters callback Function that produces an element of the new Array thisArg Optional. Value to use as this when executing callback. Further reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map Short advice PS.: Array.map is usually called when you want to do something with your array, for example adding 10 to each item, or something like that... Since the Array.map returns a new array. If you're only using console.log or something that wont affect the array itself you could just use a Array.forEach call instead A: Nothing complex needed! map takes a second param of thisArg, so you just pass it in with the function you want to invoke on each item: a = { foo: 'bar', things: [1, 2, 3], showFooForEach: function() { this.things.map(function(thing) { console.log(this.foo, thing); }, this); } } a.showFooForEach(); https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
[ "diy.stackexchange", "0000069881.txt" ]
Q: Framing a window directly through a post in post-and-beam construction? I have a single story home built on a concrete slab using post and beam construction. I have 4x4 posts spaced 5 feet apart along the exterior wall with 4x8 beams holding up a 4" tongue and groove roof with composite shingles. I am considering the removal of the post and replacing it with a sufficient header and jack studs so that the window isn't bisected by the post. I know having a professional engineer come and evaluate is my best option, but I am also considering over-speccing it if I can arrive at some kind of rough estimate for an appropriate header and supporting jack studs. Any advice is greatly appreciated! A: Removing the vertical post and finding some other way of supporting the roof beam will be complicated, specially since there is very little space between the window top and where the roof beam enters the wall. This is where you would need to insert a cross beam or similar to support the load from the roof. Needless to say, it will not be pretty and would probably still block a large part of your existing window. Alternatively, you could consider moving the window. There seems to be sufficient space to the left of the photo. Although it would be a bit more work, no structural elements will be compromized, and most of the covering materials taken off to make space for the window could be re-used to fill up the gap on the other side.
[ "aviation.stackexchange", "0000034873.txt" ]
Q: On average, how many landings does a student pilot need before their first solo? On average, how many landings does a student pilot need before their first solo? I know it depends on individual students, but roughly what is the number? Or you can just tell me your experience. A: My logbook shows 29 landings, with 11 hrs logged in an Aircraft Single Engine Land aircraft (ASEL) when my instructor stepped out and sent me off on my first solo flight. I think those figures were typical for students at my flight school. It is probably also fairly typical for students at most §141 flight schools, such as mine. Now, there can be a significant difference between the experience of training under §61 and training at a §141 flight school. The schedule at §141 schools tends to be more fast-paced than what many students might experience doing §61 flight training. Since students must systematically complete the curriculum at §141 schools, a certain minimum level of experience will be in place before a student solos. However, this curriculum also lends itself to a student being ready to solo after a fairly defined period of time. A student training under §61 might take longer to be ready to solo due to a number of factors, including a possibly more relaxed training pace. On the other hand, §61 training can also give an instructor the freedom to solo a student after less time than might be typical. I don't have any hard data outside of my own experience and what I have observed, but I would guess that a typical §141 student will solo after about 20-40 landings and 10-15 hours. I would guess that a typical §61 student will solo after about 20-60 landings and 10-25 hours. A: I was trained in the US Navy. My basic flight training was conducted at NAS Corpus Christi in the T-28 Trojan and consisted of 30 actual flights. This was average for a student Naval Aviator. Total actual flight time was 48.9 combined and 40.6 as first pilot. There were a total of 7.3 hours of instrument time, with 1.9 night time hours. Before my solo I had 148 landings. The average flight time was 1.6 hours with 1.4 as first pilot. Average landings per flight were 5. The T-28 Trojan was similar in looks to the A1 Skyraider. The Skyraider had a Wright R-3350-26WA radial engine with 2,700 HP. The Trojan had a Wright R-1820-86 Cyclone radial engine developing 1,425 HP. You could torque roll the Trojan! It was an airplane that, in a sense, was wasted on a new student like me. It was a lot to handle for a new aviator, and at the time I was flying, it was old and often a pilot was faced with emergencies. I remember being airborne listening to an emergency of a solo pilot with smoke in the cockpit. It had a lot of power with its 9 cylinder radial engine. At full throttle on engine checks at the end of the runway you had to press hard on the brakes, and could find yourself coming off the power as you skidded down the runway. When you released the brakes you had a lot of rudder in compensating for the prop wash hitting the vertical stabilizer. It was customary on your first takeoff not to put in nearly enough rudder. Whoa, that led to some interesting events. When I finished my indoctrination at Pensacola I was given the choice to fly the new T-34 Turboprop or go to Corpus Christi and fly the T-28. When I saw the engine on that beast I knew exactly which aircraft I wanted to fly. Wish I had enough money to own one.
[ "stackoverflow", "0011170248.txt" ]
Q: Android LinearLayout make button doesn't work I have many buttons in my layout and they work well. I want to put the two buttons on the same row, so I make a LinearLayout horizontal, but when I do that, the second button's click event doesn't work. It doesn't show me my textview <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <Button android:id="@+id/bAnswerQuestoinShowChoices" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Choices" android:visibility="invisible" /> <Button android:id="@+id/bAnswerQuestionShowHints" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Hint 1" android:visibility="invisible" /> </LinearLayout> If I remove the LinearLayout it works fine, but I want the linearlayout because I want the two buttons to be on the same row. A: android:layout_height="match_parent" //<----------------------this is the issue make it warp content <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" //<----------------------this is the issue make it warp content android:orientation="horizontal" >
[ "stackoverflow", "0016295436.txt" ]
Q: Log4j error during deploing web application I have a problem, I try to deploy my web project in glasfish 3.1.2, it is works fine but throws the following error, please help me to understand what is the problem SEVERE: log4j:ERROR log4j called after unloading, see http://logging.apache.org/log4j/1.2/faq.html#unload. SEVERE: java.lang.IllegalStateException: Class invariant violation at org.apache.log4j.LogManager.getLoggerRepository(LogManager.java:199) at org.apache.log4j.LogManager.getLogger(LogManager.java:228) at org.apache.log4j.Logger.getLogger(Logger.java:104) at org.apache.commons.logging.impl.Log4JLogger.getLogger(Log4JLogger.java:229) at org.apache.commons.logging.impl.Log4JLogger.<init>(Log4JLogger.java:65) at sun.reflect.GeneratedConstructorAccessor47.newInstance(Unknown Source) A: Set the org.apache.catalina.loader.WebappClassLoader.ENABLE_CLEAR_REFERENCES system property to false. <jvm-options> org.apache.catalina.loader.WebappClassLoader.ENABLE_CLEAR_REFEREN‌​CES=false </jvm-options> This can be found in the domain.xml file in Glassfish (glassfish/domains/domain1/config)
[ "stackoverflow", "0029934872.txt" ]
Q: How to update the markers postions on real time i am making a employee tracker in which i will fetch all employee current Lat long after every 30 sec and update on server and then Admin module will fetch the Lat-long of of each employee from server and update the eisting marker position. So please tell me how to update the 100 markers position without effecting the UI thread in android. please help its very important for me. A: You can update your UI after every 30sec using handler.Create a separate method that fetch and display marker on map. Use below code in your activity - Handler UI_HANDLER = new Handler(); UI_HANDLER.postDelayed(UI_UPDTAE_RUNNABLE, 30000); and Below is Runnable method put any where in your activity - Runnable UI_UPDTAE_RUNNABLE = new Runnable() { @Override public void run() { drawAllMarker();//Method that will get employee location and draw it on map UI_HANDLER.postDelayed(UI_UPDTAE_RUNNABLE, 30000); } }; Hope it will help you.
[ "scifi.stackexchange", "0000127907.txt" ]
Q: Star Wars: Flying a spaceship, or, when is a movie scene NOT canon? EDIT: Subsequent to a fascinating discussion with @Wad Cheber and @Mazura, I would have actually deleted the question, not because it's a dupe but because it moves into "unsolveable" issues regarding canonicity. As we all know, it's canon that the Star Wars movies constitute the highest level of canon in the saga. Using only the canonical movies, I wonder how to align one example, the issue of Spaceship controls with their contradictory portrayal. Taking only entering and leaving hyperspace, there must be a several methods the Millennium Falcon uses. Harrison Ford (a RL pilot, after all) himself one stated, when asked “I said, ‘Just make shit up!’” Ford remembered in an interview with Entertainment Weekly’s Anthony Breznican. “I mean, it’s a movie, man. It’s space. You don’t fly in space the way you do in an atmosphere.” I can recall at least 4 shown ways of how the Falcon gets into and out of hyperspace: A handful of closely spaced levels at the top of the instrument panel. Same levers also seems to control speed in atmospheric flight. Get up out of your seat and throw a bunch of switches in a panel above the pilot to leave hyperspace. Do nothing obvious and just wait for the computer to finish calculations Have your droid undo some Imperial sabotage and get thrown into hyperspace without so much as a safety pop-up asking "are you really sure?" If the movies are "infallible" and immovable canon, yet see a portrayal such as this, is there a canon explanation? One would be the official declaration that "we're retelling the history of The Star Wars, but we take artistic liberties and our goal isn't to provide flight lessons for YT class feighters"? Another would be quasi-technical canon explanation "controls have variable functions depending on flight situation and surrounds. Also there's more than one way to skin a cat." A: TL;DR Just because the canon conflicts with itself does not make it any less canon The movies are canon, and that is the end of the discussion. There are many places where it is severely inconsistent and or wrong, but it is still canon none the less. Eg We know that The Force is: The force is an energy field created by all living things, it surrounds us, it penetrates us, it binds the galaxy together But on the other hand we are somehow supposed to also believe that the Force is: Midi-chlorians What? You can see that sometimes the canon is clearly wrong. But it is still canon anyway.
[ "stackoverflow", "0033584671.txt" ]
Q: Does it make sense to create immutable objects that share structure by utilizing the javascript prototype system So far, there seem to be two opposing solutions to immutability in Javascript: immutable.js seamless-immutable immutable.js introduces their own (shallowly) immutable objects that are incompatible with the default javascript protocols for objects and arrays. seamless-immutable uses POJOs that are completely immutable without any magic, but do without structural sharing. It would be great to combine the best of both worlds. Could immutable prototype chains/trees be a proper solution? The underlying prototype mechanism gives hope: var a = [1, 2, 3]; var b = Object.create(a); b[0]; // 1 b.map(function (x) { return ++x; }); // 2, 3, 4 b.push(4, 5, 6); // initial assignment of b a; // 1, 2, 3 b; // 1, 2, 3, 4, 5, 6 for (var i = 0; i < b.length; i++) { console.log(b[i]); } // 1, 2, 3, 4, 5, 6 a[1] = null; // prototype mutation a; // 1, null, 3 b; // 1, null, 3, 4, 5, 6 b.unshift(0); // instance mutation a; // 1, null, 3 b; // 0, 1, null, 3, 4, 5, 6 !!! Whenever a mutation (unshift) of the current instance (b) makes it impossible for its prototypes to provide their values, the js engine seems to copy these values straight into the instance automatically. I didn't know that, but it makes total sense. However, working with immutable (keyed/indexed) objects one quickly encounters problems: var a = [1, 2, 3]; Object.freeze(a); var b = Object.create(a); b.push(4, 5, 6); // Error: Cannot assign to read only property "length" Object.freeze(b); This one is simple: The length property is inherited from the immutable prototype and hence not mutable. Fixing the problem isn't hard: var b = Object.create(a, {length: {value: a.length, writable: true}}); But there will probably be other issues, in particular in more complex, real world scenarios. Maybe someone have already dealt with this idea and can tell me, if it's worth reasoning about it. Aadit's answer to a related question and Bergi's comment on it touches my question without giving an answer. A: the js engine seems to copy these values straight into the instance automatically That's because all the array methods (shift, push etc) just use assignment to indices (and fortunately, to .length, which isn't automatically updated on non-arrays). As you know, assignment just creates a new property on the inheriting object, even if the prototype had that property (unless it has weird attributes, like in your frozen-length example). Regardless, your actual question was Could immutable prototype chains/trees be a proper solution? No. The problem is that a prototype chain is never garbage-collected. The engine doesn't know that you "don't need" the prototype any more once all the inherited properties are overwritten by your new "mutated" instance - and keeps it around forever. You'd need to manually garbage-collect (dereference) it, which is just what immutable.js with its structural sharing does. Only that mutating the [[prototype]] is a bad idea, so you better manage your structures in other ways and do property lookup manually.
[ "stackoverflow", "0025910699.txt" ]
Q: Qt programm can't open my MySql database When i push the Button, it views this error : QSqlQuery::exec: database not open void Tester::pushButtonClicked() { if (database.open() ) { model->setQuery("SELECT id, Nachname, Vorname, Ort FROM testtable"); model->setHeaderData(0, Qt::Horizontal, tr("ID")); model->setHeaderData(1, Qt::Horizontal, tr("Nachnamme")); model->setHeaderData(2, Qt::Horizontal, tr("Vorname")); model->setHeaderData(3, Qt::Horizontal, tr("Ort")); } else { qDebug("Nicht geöffnet"); } meineView->setModel(model); } whats wrong ? database is a QSqlDatabase . model is a QSqlQueryModel. I have connect it so : database = QSqlDatabase::addDatabase("QMYSQL", "conn1"); //database->addDatabase("QMYSQL", "conn1"); database.setHostName("127.0.0.1"); database.setPort(3306); database.setDatabaseName( "mydb" ); database.setUserName("root"); database.setPassword("XXXX"); if ( !database.open() ) { qDebug("Couldn't open DB"); } A: I have the answer ! I have forget to set the database fot the Query. It must look like : model->setQuery("SELECT id, Nachname, Vorname, Ort FROM testtable", database);
[ "unix.stackexchange", "0000092633.txt" ]
Q: Server down and require manual fsck. I saw this error in dmesg I saw this in dmesg. What does it mean? EXT4-fs error (device sdb1): htree_dirblock_to_tree: bad entry in directory #763 3575: rec_len is smaller than minimal - block=30429885offset=0(671744), inode=0, rec_len=0, name_len=0 How in the earth this happen? Is this because SDB is bad? This is what /var/messages say Sep 26 17:15:40 host pure-ftpd: ([email protected]) [INFO] New connection from 175.44.11.232 Sep 26 17:15:40 host pure-ftpd: ([email protected]) [INFO] Logout. Sep 26 17:15:41 host pure-ftpd: ([email protected]) [WARNING] Authentication failed for user [solarromancecom] Sep 26 17:15:41 host pure-ftpd: ([email protected]) [INFO] Logout. Sep 26 17:15:41 host pure-ftpd: ([email protected]) [INFO] New connection from 27.150.198.182 Sep 26 17:15:41 host pure-ftpd: ([email protected]) [INFO] New connection from 216.244.84.165 Sep 26 17:15:43 host pure-ftpd: ([email protected]) [WARNING] Authentication failed for user [admSep 27 04:17:49 host kernel: imklog 5.8.10, log source = /proc/kmsg started. Sep 27 04:17:49 host rsyslogd: [origin software="rsyslogd" swVersion="5.8.10" x-pid="1708" x-info="http://www.rsyslog.com"] start Sep 27 04:17:49 host kernel: Initializing cgroup subsys cpuset Sep 27 04:17:49 host kernel: Initializing cgroup subsys cpu Sep 27 04:17:49 host kernel: Linux version 2.6.32-358.18.1.el6.i686 ([email protected]) (gcc version 4.4.7 20120313 (Red Hat 4.4.7-3) (GCC) ) #1 SMP Wed Aug 28 14:27:42 UTC 2013 Sep 27 04:17:49 host kernel: KERNEL supported cpus: Sep 27 04:17:49 host kernel: Intel GenuineIntel Sep 27 04:17:49 host kernel: AMD AuthenticAMD Sep 27 04:17:49 host kernel: NSC Geode by NSC Sep 27 04:17:49 host kernel: Cyrix CyrixInstead Sep 27 04:17:49 host kernel: Centaur CentaurHauls Sep 27 04:17:49 host kernel: Transmeta GenuineTMx86 Sep 27 04:17:49 host kernel: Transmeta TransmetaCPU Sep 27 04:17:49 host kernel: UMC UMC UMC UMC Sep 27 04:17:49 host kernel: BIOS-provided physical RAM map: That's it. So the system reboot and before it reboot it doesn't tell why or anythign. A: According to this knowledgebase article on novell.com, titled: EXT3 file-system error "bad entry in directory", the resolution for this message: EXT3-fs error (device dm-0): ext3_readdir: bad entry in directory #5556142: rec_len is smaller than minimal - offset=0, inode=2553887680, rec_len=0, name_len=0 Is as follows: NOTE: This error is caused by a file that has been marked as a directory. This is a non-fatal error and can be fixed by removing the file in question. Mount the file-system in question Locate the file that has been corrupted. The file's inode is the number after "bad entry in directory" Using the example error code the file would be found by typing: $ find /MOUNT_POINT -inum 5556142 Delete the file identified in step two Umount the file-system Check the disk, and check for errors. $ fsck /dev/PHYSICAL_DEVICE Repeat step 5. If no errors, the file-system is clean. The resolution is the same, it doesn't matter if it's EXT4 or an EXT3 formatted drive.
[ "japanese.stackexchange", "0000075009.txt" ]
Q: Is the water radical sometimes three strokes and sometimes two strokes? 凍, does it have the water radical on the left? Why is this three strokes in some words and two strokes in others? A: While 「氵」 is indeed an abbreviation of 「水」 (water), it is rather unfortunate that the colloquial name of 「冫」 in both Chinese and Japanese implies that 「冫」 has something to do with water. To emphasise, 「冫」 does not have anything to do with water, unless the appearance of 「冫」 is due to graphical corruption from 「氵」. 西周金⿱一丞卣集成5318秦簡日乙227 冬睡虎地秦簡今楷  「冫」 was originally a picture of forged metal plates, now written as 「鉼」 (Zhengzhang OC: /*peŋʔ/). It was later borrowed to represent the morpheme now written as 「冰」 (/*pŋrɯŋ/, ice) via the rebus principle. As a stand-alone character, 「冫」 thus represents the two morphemes [鉼]{へい}, metal (plates) [冰]{ひょう} (Shinjitai: 氷), ice In accordance with how Chinese characters work, as a character component, 「冫」 may impart either a meaning hint, a sound hint, or both a meaning and sound hint to the character it is part of. These meaning and sound hints are taken from the morphemes that it represents; that is, if you see 「冫」 as part of a character 「X」, you should be thinking to yourself about one of the following: X sounds like へい X sounds like ひょう X has something to do with metal (plates) X has something to do with ice X both sounds like へい and has something to do with metal (plates) X both sounds like ひょう and has something to do with ice Examples: 冶 - to smelt metal 匀 - ancient weight measurement, now written as 「鈞」 金 - きん, metal, compound of 「冫」 (metal plates), semantic 「王」 (metal battle weapon > power/authority > king) and phonetic 「今」 (also きん). See What is the etymology of the kanji 金? 冷 - cold 冬 - winter 凍 - freeze 馮 - びょう, ひょう
[ "stackoverflow", "0057103796.txt" ]
Q: Trying to access psql after dropping a user but still got asked for entering password for the dropped user initially I have Role name | Attributes | Member of ------------+------------------------------------------------------------+----------- hezhenghao | Create DB | {} postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {} and I typed postgres=# REASSIGN OWNED BY hezhenghao to postgres postgres-# ; REASSIGN OWNED postgres=# REASSIGN OWNED BY hezhenghao to postgres; REASSIGN OWNED postgres=# DROP OWNED BY hezhenghao; DROP OWNED postgres=# DROP USER hezhenghao; DROP ROLE Now there is only one user postgres=# \du List of roles Role name | Attributes | Member of -----------+------------------------------------------------------------+----------- postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {} However when I type psql in terminal, I still got asked to Password for user hezhenghao: and then I would end up with psql: FATAL: password authentication failed for user "hezhenghao" I am new to postgres so I don't really understand what's going on here. Can someone help me with this? A: If you don't specify a user with -U then psql will default to the username of the user currently logged in. In this case, it sounds like that user is hezhenghao. Use -U postgres to log in as the postgres user.
[ "stackoverflow", "0026371415.txt" ]
Q: How to dynamically bind a WinJS list view within a repeater I have a WinJS Repeater which is using a template. That template contains a WinJS list view. I can't seem to figure out how to use data-win-bind to set the inner list views itemDataSource. My Repeater: <section id="genreView" aria-label="Main content" role="main"> <div id="genreWrapper"> <div id="genreRows" data-win-control="WinJS.UI.Repeater" data-win-options="{template: select('#genreRowTemplate')}"> </div> </div> </section> My Template which contains a List View: <div id="genreRowTemplate" data-win-control="WinJS.Binding.Template"> <div id="genreRow"> <h2 class="genreTitle" data-win-bind="innerText: genreTitle"></h2> <div class="genreMovieListView" data-win-control="WinJS.UI.ListView" data-win-bind="itemDataSource : data" data-win-options="{ layout: { type: WinJS.UI.GridLayout }, itemsDraggable: false, selectionMode: 'single', tapBehavior: 'none', swipeBehavior: 'none', itemsReorderable: false, itemTemplate: select('#genreMovieTemplate')}"> </div> </div> </div> My List View's template: <div id="genreMovieTemplate" data-win-control="WinJS.Binding.Template"> <div class="genreMovieItem"> <img style="width: 175px; height: 250px;" data-win-bind="alt: title; src: posterUrl" /> </div> </div> The data for the repeater is similar to this (only it's a binding list): var repeaterData = [{genreTitle: "titleA", data: new WinJS.Binding.List() }, {genreTitle: "titleB", data: new WinJS.Binding.List() } {genreTitle: "titleC", data: new WinJS.Binding.List() } {genreTitle: "titleD", data: new WinJS.Binding.List() }]; The data is created on the fly and each binding list is actually a lot more data so I can't get a good sample of real data. What I DO get is a repeated control, repeated exactly the number of times as the records in my bound list. What I DON'T get is the binding list displayed. My inner binding list is not getting databound via the data-win-bind. I've tried a few things and I either get nothing or an error. Any help is appreciated. Thanks. EDIT: I think the right way to bind would be data-win-bind="data-win-options.itemDataSource: data", but doing that throws the following confusing error: "JavaScript runtime error: WinJS.UI.Repeater.AsynchronousRender: Top level items must render synchronously". A: I was able to solve my problem, but I don't think I went about it in the right way. I went ahead and set the data source for the repeater, which gives me my genreRows from above. This was always working, it was just the child dataSource I couldn't figure out how to get to. My solution... set it in code after it loads. Nothing fancy, just a solution that feels a bit hacky to me. Here's my code in case it helps someone else get past this problem. var titleList = $(".genreRow > .genreTitle"); var genreLists = $(".genreRow > .genreMovieListView"); for (var i = 0; i < genreLists.length; i++) { var title = titleList[i].innerText; var listControl = genreLists[i].winControl; tempData.forEach(function (element, i) { if (element.genreTitle == title) listControl.itemDataSource = element.data.dataSource; }); }; Basically the above code assumes the title is unique (which it is). So it uses this as a key to traverse the data and set the itemDataSource that way. I won't mark this as the accepted answer just in case someone can point out how to do this "right".
[ "stackoverflow", "0052982009.txt" ]
Q: Is resultant java.time code has more code statements compared to equivalent Calendar code Recently, I try to port one of our old code base, from Calendar to java.time, as we need quite a number of arithmetic functionalities, which is only found in java.time. If we use Calendar in our current code base, we need to perform a lot of conversion back-and-forth (From Calendar to Instant, From Instant back to Calendar), in the middle of our code. To avoid such cumbersome conversion, we decide to eliminate usage of Calendar, and port them to equivalent java.time code. I'm a bit skeptical on my port. As compared with Calendar code, it seems to Create more temporary object instances within the while loop. Requires more code statements. Calendar code // reminderCal is Calendar object. long startTimestamp = getStartTimestamp(); reminderCal.setTimeInMillis(startTimestamp); while (startTimestamp <= maxTimestamp) { resultList.add(startTimestamp); reminderCal.add(Calendar.DAY_OF_MONTH, 1); startTimestamp = reminderCal.getTimeInMillis(); } return resultList; java.time code // Epoch timestamp loopTs as initial input. long startTimestamp = getStartTimestamp(); final ZoneId zoneId = ZoneId.systemDefault(); while (startTimestamp <= maxTimestamp) { resultList.add(startTimestamp); // More code, more temporary instances required compared // with Calendar's version. Not sure we're doing the right // way. Instant instant = Instant.ofEpochMilli(startTimestamp); LocalDateTime time = LocalDateTime.ofInstant(instant, zoneId); time = time.plus(1, ChronoUnit.DAYS); startTimestamp = time.atZone(zoneId).toInstant().toEpochMilli(); } return resultList; For the above code, I was wondering, are we doing the port correctly and optimized? Is there any room we can improve in our java.time's port? A: Since you want date manipulations between times in a given time zone, you shouldn't use milliseconds nor LocalDateTime, but ZonedDateTime. And I would argue that your List should contain Instants instead of longs, but let's keep it that way for now: long startTimestamp = getStartTimestamp(); ZoneId zoneId = ZoneId.systemDefault(); ZonedDateTime maxDateTime = Instant.ofEpochMilli(maxTimestamp).atZone(zoneId); ZonedDateTime loopDateTime = Instant.ofEpochMilli(loopTs).atZone(zoneId); while (!loopDateTime.isAfter(maxDateTime)) { tsList.add(loopDateTime.toInstant().toEpochMilli()); loopDateTime = loopDateTime.plusDays(1); } This is more concise, but also more readable. And all the Instant.ofEpochMilli() and toEpochMilli() calls wouldn't be needed if you wroked with Instants instead of longs.
[ "stackoverflow", "0062089378.txt" ]
Q: Swift - HTTP digest auth I am currently in the process of reverse engineering a home automation API. I want to manage all settings with my own app - because there is really no current home automation app of the company. Anyway - I already managed the authentication with my SmartHome device. To not make it too complicated: I need http digest authentication for final communication. I have already been able to connect to my device through the command line with curl - unfortunately this doesn't work in Swift as planned. curl -X POST -d '{"key": "value"}' https://192.168.0.0:1/action -k -s --digest --user username:password Translated to Swift: (1) Using Alamofire import Alamofire let data: [String: any] = ["key": "value"] let request = Alamofire.request("https://192.168.0.0:1/action", method: HTTPMethod.post, parameters: data); request.authenticate(user: "username", password: "password") request.responseJSON { response in // leads to error because of invalid self signed certificate of the smart home device ("https:") } Note to Alamofire: I guess using an external libary such as AF does not make much sense in this case - there are some unresolved issues that wont let such code as above work. (Self signed ceritficates makes problems, using custom manager instances overriding internal stuff leads also to problems) - I've already spent hours believe me. (2) Using not Alamofire :) extension ViewController: URLSessionDelegate { public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { let urlCredential = URLCredential(trust: challenge.protectionSpace.serverTrust!) completionHandler(.useCredential, urlCredential) } } let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil) var request = URLRequest(url: url) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") do { let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted) request.httpBody = jsonData; let task = session.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { return } let responseJSON = try? JSONSerialization.jsonObject(with: data, options: []) if let responseJSON = responseJSON as? [String: Any] { // success } } task.resume() } catch { } The code above seems to work fine - the problem is that I've not implemented the digest authentication yet - because I do not find any method how to do this. It would be super helpful if somebody to get some tips how generate the Auth header based on username and password Edit Curl uses this Authorization header: > Digest username="username", realm="XTV", nonce="MTU5MDcNc2UxNjQ3OTo1YzMwYjc3YjIxMzAAAGQ5Nzg2NzUzMmRkZGU1ZVVlYw==", uri="/action", cnonce="MTExOTZlZmI1MjBlYWU0MTIzMDBmNDE0YTkWzJl1MDk=", nc=00000001, qop=auth, response="2ba89269645e2aa24ac6f117d85e190c", algorithm="MD5" Is there the possibility to generate this header in Swift? A: Digest authentication is supported automatically by URLSession and Alamofire through URLCredential (which is what authenticate() uses in Alamofire) when the server properly returns the WWW-Authenticate header with the proper digest settings. You can generate the header manually, though I wouldn't recommend it due to the complexity of the digest process. I've found the wikipedia page to be thorough enough to implement the standard manually.
[ "stackoverflow", "0048398923.txt" ]
Q: How does plt.show() know what to show? My question is not about matplotlib in detail, but a general programming and question, and i'm looking for an answer on the mechanisms making this possible in python or matplotlib core. Let's say I have a scatter plot using the code: import matplotlib.pyplot as plt plt.scatter(a,b) plt.show() I'm wondering how is this statement handled? How does python (or matplotlib?) know what to plot and where to get the data? How are these statement handled by interpreter? A: Maybe I finally see the point of this question. Of course we cannot explain pyplot here, because that is much too complicated and would require a complete tutorial (which btw do exist). But we can have a look at how pyplot would work as a module in a very simplified manner. So let's create myplot, the ultimative console plotting library. ;-) The module myplot could look as follows. It has two functions, scatter and show and two variables, figures and plot. plot would store our coordinate system to plot to. figures would store the figures we create. plot = """ ^ | | | | | +----------->""" figures = [] def scatter(X,Y): thisplot = list(plot[:]) for x,y in zip(X,Y): thisplot[1+14*(6-y)+x] = "*" thisplot = "".join(thisplot) figures.append(thisplot) def show(): for fig in figures: print(fig) Calling scatter creates a new figure from plot and stores it in the figures list. Calling show takes all figures from that list, and shows them (prints them in the console). So using myplot would look exactly like the example above. import myplot as mlt mlt.scatter([2,3,4,5,6,8],[2,5,4,4,3,2]) mlt.show() Creating the output: ^ | * | ** | * | * * | +----------->
[ "stackoverflow", "0051135916.txt" ]
Q: what is the value of a multi-character character constant variable I know multi-character character constant stated as int. and I know that the value of it is compiler dependent. but my question is when I store a multi-character character constant in a char variable it will behave in a different way. #include <iostream> int main() { std::cout << 'asb'; return 0; } output: 6386530 #include <iostream> int main() { char a = 'asb'; std::cout << a; return 0; } output: b A: Case 1 : You are getting 'a'*256²+'s'*256+'b' = 6386530 because 'a' = 97, 's' = 115, 'b' = 98 cf. Ascii table 'asb' is interpreted as an integer. typeid('asb').name()[0] == 'i' && sizeof('asd') == 4; An integer is 32 bits, and you can store 'asb' (24bits) in an integer. That's why std::cout interprets it as an integer and display 6386530 Note that also: typeid('xxxxabcd').name()[0] == 'i' && sizeof('xxxxabcd') == 4; but 'xxxxabcd' is represented by 64-bits, so 32-bits are lost. std::cout << 'xxxxabcd'; std::cout << 'abcd'; would print the same thing. Case 2 : 'asb' is interpreted as an integer and you cast it into a char (8-bits). As @BenjaminJones pointed out, only the last 8-bits (98=='b') are saved. And std::cout interprets it as a char so it displays 'b'. Anyway, both case provokes compilation warning such as : warning: multi-character character constant [-Wmultichar] warning: multi-character character constant [-Wmultichar] In function 'int main()' warning: overflow in implicit constant conversion [-Woverflow] I guess the behavior depends on the compiler.
[ "stackoverflow", "0033657342.txt" ]
Q: How to perform a $and search with Python and MongoDB Let's say I have a list of keywords and I want to match against MongoDB documents in which they all appear in the keys field (that is, a AND clause). How can I do that in Python? I've tried: keywords = ['a', 'b', 'c'] keywords_dict = {'keys' : keywords} results = collection.find(keywords_dict) But it seems to return no result. I'm using Python3.5 with PyMongo. Any hints? A: You can use the $all operator which is also equivalent to an $and operation of the specified values; i.e. the following statement: { 'keys': { '$all': ['a', 'b', 'c'] } } is equivalent to: { '$and': [ { 'key': a }, { 'key': b }, { 'key': c} ] }
[ "gis.stackexchange", "0000173750.txt" ]
Q: Get a KML layer from Geoserver Is there a way to export into KMl a geoserver layer? I have used KML reflector but this doesnt return the whole content of the layer but a reference to it. Alternatively can I get a KML of a layer using OpenLayers? A: Reading the documentation a bit more carefully I found out there are different modes. In my case the "download" mode is what I am looking for. From the documentation: "Returns KML which contains the entire data set. In the case of a vector layer, this will include a series of KML placemarks. With raster layers, this will include a single KML ground overlay. This is the only mode that doesn’t dynamically request new data from the server, and thus is self-contained KML." So my request link looks like: http://host:port/geoserver/wms/kml?layers=layer_name&mode=download My problem is that some of the layers are not downloaded correctly and I get a KML file with: java.lang.NullPointerException null while some other work great. It seems like that the problem I mention was because of the styling of the layer. More specifically, the layers that would have problem to get downloaded as KMLs they had a style, which was assigned to a specific workspace (in geoserver). I have faced this problem in the past and the solution is to leave the choice: workspace (in style of layers) empty.
[ "stackoverflow", "0008375694.txt" ]
Q: How do I programmatically access reminders? I may be wrong, but it looks like there is no public API to create/access programmatically reminders in iOS 5. However, there is an app for iPhone that can access them: see this video. The question is: how they do this? Is there any undocumented way to access reminders ? I also looked at the relevant documentation for iCloud, but did not find anything related. A: For iOS 6.0 there is Event Kit framework grants access to users’ Reminders.app information. Refer ReadingAndWritingReminders link. Hope helpful A: Get reminder list EKEventStore *store = [[EKEventStore alloc] init]; [store requestAccessToEntityType:EKEntityTypeReminder completion:^(BOOL granted, NSError *error) { NSLog(@"acces to §Reminder granded %i ",granted); }]; NSPredicate *predicate = [store predicateForRemindersInCalendars:nil]; [store fetchRemindersMatchingPredicate:predicate completion:^(NSArray *reminders) { for (EKReminder *reminder in reminders) { NSLog(@"reminder %@",reminder); } }];
[ "stackoverflow", "0033998802.txt" ]
Q: Get list of pdf files in folder I want get a list of files name of all pdf files in folder I have my python script. Now I have this code: files = [f for f in os.listdir('.') if os.path.isfile(f)] for f in files: e = (len(files) - 1) The problem are this code found all files in folder(include .py) so I "fix" if my script is the last file on the folder (zzzz.py) and later I subtract the last file of the list that are my script.py. I try many codes for only find .pdf but this the more near I am. A: Use glob on the directory directly to find all your pdf files: from os import path from glob import glob def find_ext(dr, ext): return glob(path.join(dr,"*.{}".format(ext))) Demo: In [2]: find_ext(".","py") Out[2]: ['./server.py', './new.py', './ffmpeg_split.py', './clean_download.py', './bad_script.py', './test.py', './settings.py'] If you want the option of ignoring case: from os import path from glob import glob def find_ext(dr, ext, ig_case=False): if ig_case: ext = "".join(["[{}]".format( ch + ch.swapcase())) for ch in ext]) return glob(path.join(dr, "*." + ext)) Demo: In [4]: find_ext(".","py",True) Out[4]: ['./server.py', './new.py', './ffmpeg_split.py', './clean_download.py', './bad_script.py', './test.py', './settings.py', './test.PY'] A: Use the glob module: >>> import glob >>> glob.glob("*.pdf") >>> ['308301003.pdf', 'Databricks-how-to-data-import.pdf', 'emr-dg.pdf', 'gfs-sosp2003.pdf'] A: You simply need to filter the names of files, looking for the ones that end with ".pdf", right? files = [f for f in os.listdir('.') if os.path.isfile(f)] files = filter(lambda f: f.endswith(('.pdf','.PDF')), files) Now, your files contains only the names of files ending with .pdf or .PDF :)
[ "math.stackexchange", "0000599459.txt" ]
Q: $\mathrm{card} ( \mathbb{Q})=\mathrm{card}( \mathbb{Q^c})$: Overcoming Wrong Intuition This is a widespread intuitive argument, asserting that $\mathrm{card} ( \mathbb{Q})=\mathrm{card}( \mathbb{Q^c})$: Between any two rational numbers there's an irrational one and vice versa. So $\mathrm{card} ( \mathbb{Q})=\mathrm{card}( \mathbb{Q^c})$. How can one convince the learner that this argument is invalid? A: It is natural to have such misconceptions, and it is also hard for someone else to help you get rid of them. You use the right concepts instead repeatedly so that after sometime your wrong intuition seems absurd to you. As von Neumann says "In mathematics, you don't understand things. You just get used to them." That is very true. I have been there.
[ "stackoverflow", "0013264799.txt" ]
Q: Hibernate "No session or session was closed" when i trying to get data from database I am trying to write a stock management system. But now I have a few question. Please help me to sort out these problems. I have 2 entities. Item and ItemPrice. Item has one or more ItemPrice When I try to save Item object, it works fine; but when I try to retrieve details from database, it gives following Exception stack trace. org.hibernate.HibernateException: Found shared references to a collection: com.pos.entities.ItemGroup.items Hibernate: select itemmodel0_.id as id9_, itemmodel0_.item_model as item2_9_, itemmodel0_.status as status9_ from smartpos.item_model itemmodel0_ where (itemmodel0_.status=? ) Hibernate: select itemsize0_.id as id3_, itemsize0_.item_size as item2_3_, itemsize0_.status as status3_ from smartpos.item_size itemsize0_ where (itemsize0_.status=? ) at org.hibernate.engine.Collections.processReachableCollection(Collections.java:163) at org.hibernate.event.def.FlushVisitor.processCollection(FlushVisitor.java:37) at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:101) at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:61) at org.hibernate.event.def.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:55) at org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:138) at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:196) at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:76) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:26) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106) at com.pos.dao.ItemDaoImpl.getItem(ItemDaoImpl.java:761) at com.pos.manager.ItemManager.getItem(ItemManager.java:296) at com.pos.ui.ItemDefinitionForm$RefreshTask.doInBackground(ItemDefinitionForm.java:464) at com.pos.ui.ItemDefinitionForm$RefreshTask.doInBackground(ItemDefinitionForm.java:458) at javax.swing.SwingWorker$1.call(SwingWorker.java:277) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at javax.swing.SwingWorker.run(SwingWorker.java:316) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619) Nov 7, 2012 12:03:42 PM org.hibernate.LazyInitializationException SEVERE: failed to lazily initialize a collection of role: com.pos.entities.Item.itemPrices, no session or session was closed org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.pos.entities.Item.itemPrices, no session or session was closed at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358) at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350) at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:97) at org.hibernate.collection.PersistentSet.size(PersistentSet.java:139) at com.pos.ui.ItemDefinitionForm$RefreshTask.doInBackground(ItemDefinitionForm.java:520) at com.pos.ui.ItemDefinitionForm$RefreshTask.doInBackground(ItemDefinitionForm.java:458) at javax.swing.SwingWorker$1.call(SwingWorker.java:277) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at javax.swing.SwingWorker.run(SwingWorker.java:316) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619) org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.pos.entities.Item.itemPrices, no session or session was closed at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358) at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350) at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:97) at org.hibernate.collection.PersistentSet.size(PersistentSet.java:139) at com.pos.ui.ItemDefinitionForm$RefreshTask.doInBackground(ItemDefinitionForm.java:520) at com.pos.ui.ItemDefinitionForm$RefreshTask.doInBackground(ItemDefinitionForm.java:458) at javax.swing.SwingWorker$1.call(SwingWorker.java:277) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at javax.swing.SwingWorker.run(SwingWorker.java:316) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619) This is entity class files. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated Nov 3, 2012 10:36:51 PM by Hibernate Tools 3.2.1.GA --> <hibernate-mapping> <class catalog="smartpos" name="com.pos.entities.ItemPrice" table="item_price" lazy="false"> <id name="id" type="java.lang.Integer"> <column name="id"/> <generator class="identity"/> </id> <many-to-one class="com.pos.entities.Item" fetch="select" name="item"> <column name="item_id" not-null="true"/> </many-to-one> <many-to-one class="com.pos.entities.PriceList" fetch="select" name="priceList"> <column name="price_list_id" not-null="true"/> </many-to-one> <property name="price" type="float"> <column name="price" not-null="true" precision="12" scale="0"/> </property> Item Entity <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated Nov 3, 2012 10:36:51 PM by Hibernate Tools 3.2.1.GA --> <hibernate-mapping> <class catalog="smartpos" lazy="false" name="com.pos.entities.Item" table="item"> <id name="id" type="java.lang.Integer"> <column name="id"/> <generator class="identity"/> </id> <many-to-one class="com.pos.entities.ItemColor" fetch="select" name="itemColor"> <column name="item_color_id" not-null="true"/> </many-to-one> <many-to-one class="com.pos.entities.ItemModel" fetch="select" name="itemModel"> <column name="item_model_id" not-null="true"/> </many-to-one> <many-to-one class="com.pos.entities.ItemGrade" fetch="select" name="itemGrade"> <column name="item_grade_id" not-null="true"/> </many-to-one> <many-to-one class="com.pos.entities.BusinessPartner" fetch="select" name="businessPartner"> <column name="supplier_id" not-null="true"/> </many-to-one> <many-to-one class="com.pos.entities.ItemSize" fetch="select" name="itemSize"> <column name="item_size_id" not-null="true"/> </many-to-one> <many-to-one class="com.pos.entities.Login" fetch="select" name="login"> <column name="login_id" not-null="true"/> </many-to-one> <many-to-one class="com.pos.entities.ItemGroup" fetch="select" name="itemGroup"> <column name="item_group_id" not-null="true"/> </many-to-one> <many-to-one class="com.pos.entities.ItemBrand" fetch="select" name="itemBrand"> <column name="item_brand_id" not-null="true"/> </many-to-one> <property name="itemCode" type="string"> <column length="50" name="item_code" not-null="true" unique="true"/> </property> <property name="itemName" type="string"> <column length="200" name="item_name" not-null="true"/> </property> <property name="shortName" type="string"> <column length="100" name="short_name" not-null="true"/> </property> <property name="barcode" type="string"> <column length="50" name="barcode" not-null="true"/> </property> <property name="warrentyItem" type="byte"> <column name="warrenty_item" not-null="true"/> </property> <property name="taxableItem" type="byte"> <column name="taxable_item" not-null="true"/> </property> <property name="status" type="byte"> <column name="status" not-null="true"/> </property> <property name="createdDate" type="timestamp"> <column length="19" name="created_date" not-null="true"/> </property> <property name="batchSerial" type="byte"> <column name="batch_serial" not-null="true"/> </property> <property name="warrentyPeriod" type="int"> <column name="warrenty_period" not-null="true"/> </property> <set inverse="true" name="itemPrices" cascade="save-update"> <key> <column name="item_id" not-null="true"/> </key> <one-to-many class="com.pos.entities.ItemPrice"/> </set> GUI Coding headers = new SupportedMethod().getTableHeaderValues(tblItemPrice); System.out.println("sdff" + item.getItemPrices().size()); itemPriceSet = item.getItemPrices(); Iterator it = itemPriceSet.iterator(); while (it.hasNext()) { ItemPrice ip = (ItemPrice) it.next(); Vector<Object> oneRow = new Vector<Object>(); oneRow.add(ip.getId()); oneRow.add(ip.getPriceList().getPriceListName()); oneRow.add(Float.toString(ip.getPrice())); tableData.add(oneRow); } tblItemPrice.setModel(new DefaultTableModel(tableData, headers)); cascade is OK, and I already set lazy=false, but it throws Exception. Please anyone help me. A: These lines from stacktrace say that your Item.itemPrices set uses lazy initialization: collection of role: com.pos.entities.Item.itemPrices, no session or session was closed at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358) ... So please add lazy="false" to itemPrices collection: <set inverse="true" name="itemPrices" lazy="false" fetch="select" cascade="save-update"> <key> <column name="item_id" not-null="true"/> </key> <one-to-many class="com.pos.entities.ItemPrice"/> </set>
[ "math.stackexchange", "0002018680.txt" ]
Q: another trig limit without L'Hospital? $$\lim_{x\to \pi/3 }\dfrac{1-2\cos\left(x\right)}{{\pi}-3x}$$ Here's what I tried: ${\pi}-3x=y$, $\dfrac{{\pi}-y}{3}=x$ $$\lim_{y\to\ 0} \dfrac{1-2\cos\left(\frac{{\pi}-y}{3}\right)}{y}$$ ... A: Hint: The expression equals $$\frac{1}{3}\cdot\frac{f(x) - f(\pi/3)}{x-\pi/3},$$ where $f(x) = 2 \cos x.$
[ "civicrm.stackexchange", "0000007159.txt" ]
Q: Is there a way to display the latest mail in CiviMail? We use CiviMail for our organization's newsletter. In addition to a signup form, we would like to have a "click to view our latest newsletter" link which shows the most recent newsletter from CiviMail. Is there a way to automatically do this that doesn't involve changing the link manually every time a new newsletter is sent out? A: Option 1) There is CiviCRM extension which seems to do exactly what you need: Public Mailings Archive filterable by date, template, etc. It says is compatible up to Civi 4.5 so you might need to contact the developer or test first if you are using 4.6 Option 2) As you are on WordPress, check out Christian Wach's plugin, it creates a custom post for each public CiviMail mailing. You could link in your mailing to the custom archive page for that post, alternatively you could modify the archives-pages-template.php to output only the last post (ie last newsletter) if you don't want to expose previous newsletters. Option 3) Try out the Content Tokens extension and check if it fulfills your needs. Option 4) In conjunction with Christian Wach's plugin mentioned above, you could create your own token, as explain in this great post by Coleman.
[ "gardening.stackexchange", "0000020535.txt" ]
Q: Why are my tomatoes cracking and what can I do? (Memphis, TN. Zone 7) First garden. I'm growing tomatoes in two parts of the yard. One gets more sun than the other: the partially-shaded area is producing well, but in the the sun-baked area they're cracking before they can fully ripen. Cucumbers, okra and peppers grow fantastically in these same beds, but I suspect the tomatoes are just not getting enough water. I've tried watering the hell out of them, but still, no dice. Some have tiny spots, as well as cracks. There are also hundreds of little flying bugs, tiniest things I've ever seen. (Searching this site, they look like whiteflies.) I don't use anything artificial, pesticides, etc. It's possible birds are getting in there, too. Several tomatoes have actually rotted on the vine and fallen off as mush. :( The (single) plant is also enormous. Could I simply need to trim/prune it back? I've done zero maintenance and just let it grow wild. Maybe it's just trying to grow too much fruit at once? The tomatoes in the back yard, partially-shaded, have none of these problems. The plants are also smaller. Those are romas and grape tomatoes, though; I don't remember what kind the problem tomatoes are. The soil in both areas is a mixture of dirt and compost (chicken & rabbit manure mixed with dried leaves and pine shavings) that had "cooked down" over last fall and winter (with my chickens scratching at it.) It was black gold by the time it went into the beds, so I don't think it's a nutritional deficiency, but maybe? What can I do? Should I partially shade them? Is it just a bad spot? They're beautiful tomatoes until they crack, I'm so disappointed! A: Cracking tomatoes happens when the (almost) ripe fruit expands and the skin can't hold up any more. (A bit like stretch marks...) There are a few causes that typically lead to different crack patterns, but sometimes it's a bit non-conclusive, so I won't go into detail. Excess water, especially after a drought - water as consistantly as possible, protect plants from rain. Excess fertilizer late in the season - fertilize early, reduce or stop when fruits start to ripen. Temperature differences, especially in fall or when wet fruit are exposed to full sun - consider some kind of a cover, but remember that high humidity leads to fungal diseases, so ensure good ventilation. A cracked tomato is actually fine for the kitchen - if you pick and use it asap. The wound is an open door for mold spores, as you noticed. For next season, consider a bit of prior research: There are some breeds that are really prone to cracking, others are labeled "crack resistant" (or whatever the English term is). A: The cracks are a physical injury caused by the tomato plant going from too dry to wet too fast. When the plant goes through a sudden change like that the fruit goes from being short on water to suddenly having plenty of water, so it takes in a lot of water very fast and the skin doesn't stretch fast enough to keep up. The skin splits near the top and then the cracks seal up with brown scabs like you are seeing. If it happens on a tomato that is nearly ripe the fruit is perfectly healthy away from the cracks, but has a much shorter shelf life. The problem is probably more severe on your sun-baked tomato for two reasons. First, more sun means it probably gets drier faster, so it was easier to get dry enough for this to happen. Second, because beefsteak-type tomatoes (which is what the pictured plant is) are more prone to this kind of damage than grape and roma varieties are. The greener fruit seems to be in good shape. To prevent this from happening again, just keep your watering schedule fairly even from here on out, more if it's hot and dry, less or even none if it's raining a lot. A: Cracking in tomatoes is almost always caused by uneven watering. My guess is that the soil in the shady spot of your garden is able to retain water better, so the plants in the shade have more consistent access to water. The soil in the sun is probably drying out more in between watering, so those plants have less consistent access to water. Watering the sunny garden more consistently and possibly mulching the sunny garden will help.
[ "stackoverflow", "0048583639.txt" ]
Q: How to create DataFrame based on multiple JSON files I have many JSON files inside a folder. All of them have the same structure. Now I want to create the DataFrame, and each JSON file should be the row of this DataFrame. I know how to create DataFrame based on a single JSON string, but I don't know how to deal with multiple ones: import spark.implicits._ val jsonStr = """{ "key": 111, "value": 54, stamp: "aaa"}""" val df = spark.read.json(Seq(jsonStr).toDS) A: Assuming you have your JSONs in folder src/main/resources Following code will produce desired result: private val df: DataFrame = spark.read.json("src/main/resources") df.show() +---+-----+-----+ |key|stamp|value| +---+-----+-----+ |111| aaa| 54| |111| aaa| 54| +---+-----+-----+ Note that JSON should be machine-readable, not human readable (that means that JSONs shouldn't have new line characters.
[ "stackoverflow", "0005404755.txt" ]
Q: Coredata, EXC_BAD_ACCESS or weird behaviour on related objects I have a Journal NSManagedObject subclass which has many Pages. I have created this custom method (in a category) to get an array of the pages in their order. As you see it's quite straightforward. // // @returns an array of pages sorted by indexInJournal // - (NSArray*)sortedPages { NSLog(@"Are we in main thread? %i", [NSThread isMainThread]); NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"indexInJournal" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; NSArray *result = [[self.pages allObjects] sortedArrayUsingDescriptors:sortDescriptors]; return result; } For some reason the method fails sometimes, and I get EXC_BAD_ACCESS on the self object; which is strange, since I am executing the method on it. NSZombieEnabled hasn't helped. When called from other routines, the method works but just returns a single page (the first one); I am sure there are 3 pages. Is there something I am missing on the way coredata istantiates/releases objects? Cheers, Davide A: I found out what the problem was. Basically, when creating pages, I was adding them to the journal pages set and the releasing them; and thus I learned you don't release a NSManagedObject. This is what generated EXC_BAD_ACCESS. It was a bit tricky to detect because pages get created automatically when necessary, so I wasn't aware I was adding them.
[ "stackoverflow", "0025180645.txt" ]
Q: return statement in a Java for loop doesn't exit method Stepping through the following code in Android Studio takes me first to the return account.name line and then to the return "" line! And empty string is returned from the method. What am I missing? //return the username (email address) of the first Google account for the testmobile.co.uk domain on the device public static String getTestMobileAccountUserName(Context context) { final String TEST_MOBILE_ACCOUNT_TYPE = "com.google"; final String TEST_MOBILE_GOOGLE_APPS_DOMAIN = "testmobile.co.uk"; AccountManager accountManager = AccountManager.get(context); Account[] accounts = accountManager.getAccountsByType(TEST_MOBILE_ACCOUNT_TYPE); for (Account account: accounts) { if (account.name.endsWith("@" + TEST_MOBILE_GOOGLE_APPS_DOMAIN)) { return account.name; } } return ""; } When I step through in the debugger, account.name is set to [email protected] on the return account.name line. A: When a return statement is executed, the debug tool goes to the last statement of the method, but is not executed. If it returns "", is because account.name is "". Don't worry, both return are not executed.
[ "stackoverflow", "0035359529.txt" ]
Q: How to detect decryption failure using TurboPower Lockbox 3.5 How do you detect decryption failure? I have the following test code: procedure TForm1.Button1Click(Sender: TObject); var plainms, cipherms: TMemoryStream; tempstr: string; begin plainms := TMemoryStream.Create; cipherms := TMemoryStream.Create; try cipherms.LoadFromFile('rwcx.ini'); Codec1.Password := '122rkdkdk'; try Codec1.DecryptStream(plainms, cipherms); except on E: Exception do showmessage(e.Message); end; plainms.Position := 0; SetLength(tempstr, plainms.Size * 2); BinToHex(plainms.Memory, PChar(tempstr), plainms.Size); showmessage(tempstr); finally plainms.Free; cipherms.Free; end; end; The file "rwcx.ini" is just a plain text file that does not contain encrypted data. I am using AES 256 with CBC and version 3.5 of Lockbox installed with "GetIt." I expected the plainms memory stream to be empty or an exception to be raised as decryption is guaranteed to fail. Instead I get garbage in plainms and no exception. How do you detect decryption has failed? I must be able to detect bad passwords or corrupted input data. What am I missing? A: Encryption is just a transform, in itself it has no concept of correct decryption. One method is to create HMAC of the encrypted data and prepend that to the encrypted data and on decryption HMAC the encrypted data and compare the HMACs. Be careful to use a HMAC compare function that takes the same amount of time for matching and non-matching values.
[ "stackoverflow", "0037797071.txt" ]
Q: Unity onClick.addlistener not working I load a Canvas prefab at runtime when an event occurs. The canvas simply has a Panel inside it, which in turn has 2 buttons. I'm trying to add OnClick events to both these buttons in the script, but it only works for the first button somehow! I have the following two lines of code one after the other: GameObject.Find("RestartButton").GetComponent<Button>().onClick.AddListener(() => RestartClicked()); GameObject.Find("ViewButton").GetComponent<Button>().onClick.AddListener(() => ViewClicked()); The callback only works for the RestartButton, and not for the ViewButton. It may well be a very small thing, but I searched Google and Bing extensively and remain clueless, so any help would be appreciated. Thanks! Edit: The script instantiates the prefab and tries to reference the two buttons in the prefab through GameObject.Find(), given that once Instantiate is called the Canvas should be active in the heirarchy. I also opened up the part of the code that attaches buttons to the listener for debugging. I dont think it attaches the listener at all. void Start () { SetupScene(); var prefab = Resources.Load("RestartOrViewPrefab"); if (prefab == null) { Debug.LogAssertion("Prefab missing!"); return; } restartCanvas = (GameObject)Instantiate(prefab); Button btn = GameObject.Find("ViewButton").GetComponent<Button>(); btn.onClick.RemoveAllListeners(); btn.onClick.AddListener(() => ViewToggle()); Button btn2 = GameObject.Find("RestartButton").GetComponent<Button>(); btn2.onClick.AddListener(() => RestartClicked()); } private void RestartClicked() { Debug.Log("RESTARTING"); SetupScene(); } private void ViewToggle() { Debug.Log("TOGGLE"); if (freshStart) { //Something here freshStart = false; } else { //Something else here freshStart = true; } } A: So I took two days to solve my problem. Apparently, doing a GameObject.Find() for a GameObject within a prefab that you just instantiated doesn't work. We always need to use the GameObject that the Instantiate() method returns to find any component within the prefab. The code I used to make my scene work may not be the best solution if your prefab is very big/complex (say you have 15 buttons and need to do something with one), but it sure does work. :) I replaced the following lines of code: Button btn = GameObject.Find("ViewButton").GetComponent<Button>(); btn.onClick.RemoveAllListeners(); btn.onClick.AddListener(() => ViewToggle()); Button btn2 = GameObject.Find("RestartButton").GetComponent<Button>(); btn2.onClick.AddListener(() => RestartClicked()); With the following lines of code: Button[] buttons = restartCanvas.GetComponentsInChildren<Button>(); foreach(Button but in buttons) { if(but.gameObject.name == "RestartButton") but.onClick.AddListener(() => RestartClicked()); else if(but.gameObject.name == "ViewButton") but.onClick.AddListener(() => ViewToggle()); } So I just reused the restartCanvas that I got a reference to. restartCanvas = (GameObject)Instantiate(prefab); Hope this helps someone. :)
[ "stackoverflow", "0007554836.txt" ]
Q: Code::Blocks console app won't show output I've got an application in Code::Blocks, and it's the simple Hello, World traditional program. #include <iostream> int main() { std::cout << "Hello, World!" << std::endl; } The program builds and executes, but the output isn't shown. I checked the project properties in Code::Blocks and it is definitely set to console application. Any suggestions as to the problem? Edit: The output only fails in the IDE. When run separately the resulting executable functions exactly as expected. A: It's possible that you don't have xterm installed it. If you are on Linux (Debian flavor) you can install it with your package manager like so: sudo apt-get install xterm
[ "stackoverflow", "0046342904.txt" ]
Q: Print the pieces of 2 dimensional rod cutting that we get after the optimal cut #include <iostream> using namespace std; Declaring the variables and the arrays int cost[1000][1000]; int d[1000][1000]; int cutPrice; bool cut_is_vertical[1000][1000]; int max_index[1000][1000]; int n, m; This function print is for printing the pieces void print(int n, int m) { if (max_index[n][m] == 0) { cout << n << m <<" "; return; } print(max_index[n][m]); print(n - max_index[n][m]); } this is the main program to cut vertically and horizontally: int main() { cin >> n >> m >> cutPrice; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j){ cin >> cost[i][j]; } } for (int i = 1; i <= n; ++i) { d[i][0] = 0; } for (int j = 1; j <= m; ++j) { d[0][j] = 0; } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { // Do not cut. d[i][j] = cost[i][j]; max_index[i][j] = 0; This is for cutting horizontally for (int k = 1; k <= i / 2; ++k) { if (d[i][j] < d[k][j] + d[i - k][j] - cutPrice) { max_index[i][j] = k; cut_is_vertical[i][j] = false; d[i][j] = d[k][j] + d[i - k][j] - cutPrice; } } This is for cutting vertically. for (int k = 1; k <= j / 2; ++k) { if (d[i][j] < d[i][k] + d[i][j - k] - cutPrice) { max_index[i][j] = k; cut_is_vertical[i][j] = true; d[i][j] = d[i][k] + d[i][j - k] - cutPrice; } } } } cout << d[n][m] << endl; print(n, m); return 0; } the errors that gives me is at the print function which are: error: too few arguments to function 'void print(int, int)' print(max_index[n][m]); ^ note: declared here void print(int n, int m) { ^ error: too few arguments to function 'void print(int, int)' print(n - max_index[n][m]); ^ note: declared here void print(int n, int m) { ^ Can you please pin point me where is the mistake in my print function thanks A: You should call function that way: print(n, m); instead of: print(max_index[i][j]); Your function takes two arguments as error message is telling you.
[ "stackoverflow", "0019705979.txt" ]
Q: Storm-kafka spout consuming slowly I was just trying out kafka-storm spout mentioned here https://github.com/nathanmarz/storm-contrib/tree/master/storm-kafka and the configuration i used are mentioned as below. BrokerHosts brokerHosts = KafkaConfig.StaticHosts.fromHostString( ImmutableList.of("localhost"), 1); SpoutConfig spoutConfig = new SpoutConfig(brokerHosts, // list of Kafka "test", // topic to read from "/kafkastorm", // the root path in Zookeeper for the spout to "discovery"); // an id for this consumer for storing the // consumer offsets in Zookeeper spoutConfig.scheme = new StringScheme(); spoutConfig.stateUpdateIntervalMs = 1000; KafkaSpout kafkaSpout = new KafkaSpout(spoutConfig); TridentTopology topology = new TridentTopology(); InetSocketAddress inetSocketAddress = new InetSocketAddress( "localhost", 6379); TridentState wordsCount = topology .newStream(SPOUT_FIRST, kafkaSpout) .parallelismHint(1) .each(new Fields("str"), new TestSplit(), new Fields("words")) .groupBy(new Fields("words")) .persistentAggregate( RedisState.transactional(inetSocketAddress), new Count(), new Fields("counts")).parallelismHint(100); Config conf = new Config(); conf.setMaxTaskParallelism(200); // conf.setDebug( true ); // conf.setMaxSpoutPending(20); // This topology can only be run as local because it is a toy example LocalDRPC drpc = new LocalDRPC(); LocalCluster cluster = new LocalCluster(); cluster.submitTopology("symbolCounter", conf, topology.build()); But the speed at which the above spout fetched messages from the Kafka topic is around 7000/seconds but I am expected a load of around 50000 messages per seconds. I have tried various options of increasing the fetch buffer size in spoutConfig with no visible results. Has any faced with the similar type of issue where he is not able to fetch the kafka topic via storm with the speed at which the producer produces messages? A: I updated the "topology.spout.max.batch.size" value in config to about 64*1024 value and then storm processing became fast.