text
stringlengths
64
81.1k
meta
dict
Q: Uikit switcher component & current window hash Uikit have Switcher component - https://getuikit.com/docs/switcher. I need the selected tab added to the address bar and not reset when the page reloads. for example <ul class="uk-subnav uk-subnav-pill" uk-switcher> <li><a href="#tab1">Item</a></li> <li><a href="#tab2">Item</a></li> <li><a href="#tab3">Item</a></li> <ul class="uk-switcher uk-margin"> <li>Hello!</li> <li>Hello again!</li> <li>Bazinga!</li> Please help with the solution of this problem. Thanks! A: Add this piece of code before closing body tag. This is one idea, you may develop on this // Replace .uk-subnav with your switcher element const switcherEl = document.querySelector('.uk-subnav'); const anchors = switcherEl.querySelectorAll('li > a'); const switcher = UIkit.switcher(switcherEl); // Show content corresponds to location hash let active = 0; while(anchors[active]) { if(anchors[active].hash === window.location.hash) { switcher.show(active); break; } active++; } // Update location hash in address bar. switcherEl.addEventListener('click', (event) => window.location.hash = event.target.hash.substr(1));
{ "pile_set_name": "StackExchange" }
Q: Make image positioned on other element I need to make image positioned like on below picture: I have code: <footer> <div class="stopka1"> <div class="container"> .................... </p> <a href="#top"></a> </div> </div> </footer> <div class="container"> <div class="row" style="padding-right:0; padding-left:0;padding-top:30px;padding-bottom:20px;"> <div class="col-md-6"> <div class="row"> <div class="col-xs-6"><img src="phone.png" style="vertical-align:middle !important;"> <span style="font-weight:lighter;color:rgb(10, 55, 110);font-size: 28px; vertical-align:middle !important;">22 213 18 31</span></div> <div class="col-xs-6"><a href="" style="width:100%;"><button class="col-cs-12 przycisk-pytanie" style="font-weight: bold;margin-top:0;">Zadaj pytanie</button></a></div> </div> </div> <div class="col-md-6"> <div class="row"> <div class="col-xs-2"><img src="women.png" style=""></div> <div class="col-xs-5">.. price ..</div> <div class="col-xs-5"><a href="" style="width:100%;"><button class="przycisk-rezerwuj-big" style="font-weight: bold;height:35px;">Rezerwuj teraz</button></a></div> </div> </div> </div> </div> Have someone any idea how to get this effect? I have no idea how to force it to cover higher div. A: You can do one of two options: OPTION 1 img {margin-top:-20px;} OPTION 2 img {position:relative; top:-20px;}
{ "pile_set_name": "StackExchange" }
Q: adding custom drop down list in tinymce I have to display a drop down list in tinymce. I googled to find any tutorial or any good example but I just found that code: // Adds a menu to the currently active editor instance var dm = tinyMCE.activeEditor.controlManager.createDropMenu('somemenu'); // Add some menu items dm.add({title : 'Menu 1', onclick : function() { alert('Item 1 was clicked.'); }}); dm.add({title : 'Menu 2', onclick : function() { alert('Item 2 was clicked.'); }}); // Adds a submenu var sub1 = dm.addMenu({title : 'Menu 3'}); sub1.add({title : 'Menu 1.1', onclick : function() { alert('Item 1.1 was clicked.'); }}); // Adds a horizontal separator sub1.addSeparator(); sub1.add({title : 'Menu 1.2', onclick : function() { alert('Item 1.2 was clicked.'); }}); // Adds a submenu to the submenu var sub2 = sub1.addMenu({title : 'Menu 1.3'}); // Adds items to the sub sub menu sub2.add({title : 'Menu 1.3.1', onclick : function() { alert('Item 1.3.1 was clicked.'); }}); sub2.add({title : 'Menu 1.3.2', onclick : function() { alert('Item 1.3.2 was clicked.'); }}); dm.add({title : 'Menu 4', onclick : function() { alert('Item 3 was clicked.'); }}); // Display the menu at position 100, 100 dm.showMenu(100, 100); This code seems to create a drop down list but I don't know where to put this code or how to use it to display custom drop down list. Kindly somebody help me in adding custom drop down list in tinyMCE. A: var myListItems = ['Item1', 'Item2', 'Item3', 'Item4', 'Item5', 'Item6', 'Item7', 'Item8', 'Item9', 'Item10', 'Item11']; tinymce.PluginManager.add('mypluginname', function (editor) { var menuItems = []; tinymce.each(myListItems, function (myListItemName) { menuItems.push({ text: myListItemName, onclick: function () { editor.insertContent(myListItemName); } }); }); editor.addButton('mypluginname', { type: 'menubutton', text: 'My Plugin Name', icon: 'code', menu: menuItems }); editor.addMenuItem('mypluginnameDropDownMenu', { icon: 'code', text: 'My Plugin Name', menu: menuItems, context: 'insert', prependToContext: true }); }); Then add to your list of plugin when you initialize your editor: $('#myTesxtArea').tinymce({ theme: "modern", convert_urls: false, height: 100, plugins: [ "advlist autolink lists link image charmap print preview hr anchor pagebreak", "searchreplace wordcount visualblocks visualchars code fullscreen", "insertdatetime nonbreaking save table contextmenu directionality", "paste textcolor","mypluginname" ], toolbar1: "undo redo | forecolor backcolor | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image", image_advtab: true }); Here's how panel button with dropdown looks like: A: First, register the plugin: var myListItems = ['Item1','Item2']; tinymce.PluginManager.add('myNewPluginName', function(editor) { var menuItems = []; tinymce.each(myListItems, function(myListItemName) { menuItems.push({ text: myListItemName, onclick: function() { editor.insertContent(myListItemName); } }); }); editor.addMenuItem('insertValueOfMyNewDropdown', { icon: 'date', text: 'Do something with this new dropdown', menu: menuItems, context: 'insert' }); }); Then add to your list of plugin when you initialize your editor: $('#myTesxtArea').tinymce({ theme: "modern", convert_urls: false, height: 100, plugins: [ "advlist autolink lists link image charmap print preview hr anchor pagebreak", "searchreplace wordcount visualblocks visualchars code fullscreen", "insertdatetime nonbreaking save table contextmenu directionality", "myNewPluginName paste textcolor" ], toolbar1: "undo redo | forecolor backcolor | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image", image_advtab: true });
{ "pile_set_name": "StackExchange" }
Q: How do I make iframe get src from js variable? I was wondering if anyone could help me with making a program in HTML that looks like this: <html> <body> <script> var iframesite = prompt ('Enter in a site'); </script> <iframe src="?"></iframe> </body> </html> So what would I put in the place of the "?" ? I want it to be javascript inside of the src attribute so that I can put 'https:// ' + iframesite for a src. Thanks A: I think adding a Iframe would work. Here is some example code: var iframesite = prompt ('Enter in a site'); var iframe = document.createElement('iframe'); iframe.src = iframesite; document.body.appendChild(iframe);
{ "pile_set_name": "StackExchange" }
Q: mdadm --create: RUN_ARRAY failed: Invalid argument I'm trying to set up a RAID1 array, like this: djc@miles dev $ sudo mdadm -v --create /dev/md0 --level=1 --raid-devices=2 /dev/sdb1 /dev/sdc1 mdadm: Defaulting to version 1.2 metadata mdadm: RUN_ARRAY failed: Invalid argument This is with two brand new hard disks and brand new (type 83) partitions (both have a single partition). What could be going wrong here? Google is not offering much help, and I don't really understand the error message here. A: I figured it out: my kernel doesn't contain support for RAID1. Should have enabled the CONFIG_MD_RAID1 option.
{ "pile_set_name": "StackExchange" }
Q: Git add a worktree from existing remote branch In my remote repository there are 3 branches (master and 2 long running branches): master #the common features are here like Core, DAL,... north #customized for A company (long-running) razavi #customized for B company (long-running) At my office PC, I add 2 worktree for those north and razavi branches: $ git worktree list C:/Source/nis a6fb6e1 [master] C:/Source/north ebc7670 [north] C:/Source/razavi eed08a2 [razavi] Everything is OK so far, I decide to work on this project from my home as well, but in my home PC, when I try to add worktree for those two branches, it gives me an error: $git worktree add -b north ../north north fatal: A branch named 'north' already exists. I remove the -b switch to not add a new branch, but it doesn't work too. How can I add a worktree from existing branch that is not local but remote? A: TL;DR: you probably wanted git worktree add ../north north First, a reminder (or information for others coming across this question): git worktree add wants to create a new work-tree and, at the same time, make sure that this new work-tree is using a different branch name from every other work-tree. This is because, while each added work-tree has its own index and HEAD, the HEAD files wind up sharing the underlying branch pointers in the shared repository. Having two different work-trees with independent index objects but the same underlying branch leads to some tricky problems for users to deal with. Rather than trying to figure out how to deal with these—by either educating programmers or providing tools to deal with the problems—git worktree simply forbids the situation entirely. Hence, it's pretty typical to want to create a new branch name when creating a new work-tree. By definition, a new branch name is automatically different from every existing branch name: $ git checkout -b newbranch Switched to a new branch 'newbranch' $ git checkout -b newbranch fatal: A branch named 'newbranch' already exists. This seems pretty natural: no one is ever surprised by this. You're running git worktree add in a way that is just like git checkout -b, except that the checkout occurs in the new added work-tree. But you already have a branch named north. If this existing north branch is not useful, you can delete it. Now you don't have a local branch named north and you can create a new one. If this existing north branch is useful, don't delete it! If it's already checked out in some existing work-tree, move to that work-tree and work on it there. If it's not checked out in some existing work-tree, you can make a new work-tree that does have it checked out; you just need to avoid using the -b flag (and the corresponding branch name): git worktree add ../north north Note that when you're creating a new branch, you do not have to repeat yourself: git worktree add -b newbranch ../path will create a new work-tree in ../path, and use git checkout -b newbranch to populate it. You only need the branch name when: you're not using -b, and the path argument does not end in the name of the branch. For instance, if you want to check out the existing branch zorg in a new work-tree in path ../zorg, you can just run: git worktree add ../zorg Here, since there is neither a -b zorg nor a final argument, Git figures out the branch name by using the last part of ../zorg, which is of course just zorg, so this tries to check out the existing branch zorg into the new work-tree. A: For this problem, worktree add does need a --checkout switch to do so: $ git worktree add --checkout ../north north $ git worktree add --checkout ../razavi razavi A: In addition of git worktree add --checkout, Git 2.16 (Q1 2018) will propose another alternative: The way "git worktree add" determines what branch to create from where and checkout in the new worktree has been updated a bit. See commit e92445a, commit 71d6682 (29 Nov 2017), and commit 4e85333, commit e284e89, commit c4738ae, commit 7c85a87 (26 Nov 2017) by Thomas Gummerer (tgummerer). (Merged by Junio C Hamano -- gitster -- in commit 66d3f19, 19 Dec 2017) add worktree.guessRemote config option Some users might want to have the --guess-remote option introduced in the previous commit on by default, so they don't have to type it out every time they create a new worktree. Add a config option worktree.guessRemote that allows users to configure the default behaviour for themselves. The documentation for git config now reads: worktree.guessRemote:: With add, if no branch argument, and neither of -b nor -B nor --detach are given, the command defaults to creating a new branch from HEAD. If worktree.guessRemote is set to true, worktree add tries to find a remote-tracking branch whose name uniquely matches the new branch name. If such a branch exists, it is checked out and set as "upstream" for the new branch. If no such match can be found, it falls back to creating a new branch from the current HEAD. Actually, Git 2.21 (Q1 2019) clarifies the documentation for this option, which jumped right in with "With add", without explaining that add is a sub-command of "git worktree". See commit b4583d5 (23 Dec 2018) by Eric Sunshine (sunshineco). (Merged by Eric Sunshine -- sunshineco -- in commit b4583d5, 28 Dec 2018) The documentation now reads: worktree.guessRemote: If no branch is specified and neither -b nor -B nor --detach is used, then git worktree add defaults to creating a new branch from HEAD.
{ "pile_set_name": "StackExchange" }
Q: C execution stack - local variable allocation I have a very basic question. Lets take this snippet: #include <stdio.h> void foo(void) { char *s = "StackOverflow"; printf("%s\n", s); } int main(void) { foo(); } In the process execution stack, main gets loaded on to the stack, then foo() gets called. Now, where is the memory for "StackOverflow" allocated? Similarly where is the memroy for "%s\n" allocated when printf is called? Consider the following code: Now the other question I have is, considering the below code: #include <stdio.h> int x; int abc = 100; void foo(void) { char *s = "stackoverflow"; printf("%s\n", s); } int main(void) { foo(); } So, if I do objdump -s -j .bss a.out , I should see uninitialized segment and if I do objdump -s -j .data a.out , I should see initialized segment (abc=100) rt? Is there anything wrong with this assumption? I get the following outputs though: test > objdump -s -j .bss a.out a.out: file format elf32-i386 test > objdump -s -j .data a.out a.out: file format elf32-i386 Contents of section .data: 804954c 00000000 3c960408 00000000 64000000 ....<.......d... What am I missing here? thanks everyone again A: "StackOverflow" and "%s\n" string literals are put in .rodata (read only data ) section in most systems. On UNIX, you can dump .rodata section using the objdump command: $ gcc tst.c $ objdump -s -j .rodata a.out As added by @FatalError in the comments, "%s\n" is not visible with objdump in the example as gcc optimizes a call to printf("%s\n",str) by replacing it by a call to puts(str). To see the "%s\n" string literal in the objdump output, you can compile your program with gcc -fno-builtin. A: The standard doesn't define where the storage for "StackOverflow" is located. Often, it will be stored in the read-only text portion of your program; sometimes, it will be stored in the initialized data portion of your program. Neither of these is the stack; neither of these is the 'heap' (in the sense of dynamically allocated memory managed by malloc() et al). The same comments and issues arise for the format string.
{ "pile_set_name": "StackExchange" }
Q: How can I add min and max Threshold line in Google Line Charts I have added line chart on my web-app and I need to add or highlight a constant line showing up in red for min-threshold value for this parameter and max-threshold for this parameter. I have gone the Google Line Charts Configuration Options but couldn't find any such options available in it. I wonder how anyone other also haven't ask this question on community so far. While searching a lot for solution to this problem I found one Fiddle related to this but it is adding an another line parameter and it showing tool-tip as that value, which I don't want to show on line chart. Also, adding it as another line in chart I find inefficient. Thanks for help in advance. A: there aren't any standard options for adding threshold lines or markers adding another series is the only way you can use the following option to disable tooltips... enableInteractivity: false see following working snippet... google.charts.load('current', { callback: drawChart, packages:['corechart'] }); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Month', 'Bolivia', 'Ecuador', 'Madagascar', 'Papua New Guinea', 'Rwanda', ''], ['2004/05', 165, 938, 522, 998, 450, 250], ['2005/06', 135, 1120, 599, 1268, 288, 250], ['2006/07', 157, 1167, 587, 807, 397, 250], ['2007/08', 139, 1110, 615, 968, 215, 250], ['2008/09', 136, 691, 629, 1026, 366, 250] ]); var options = { seriesType: "line", series: { 5: { type: "steppedArea", color: '#FF0000', visibleInLegend: false, areaOpacity: 0, enableInteractivity: false } } }; var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data, options); } <script src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div"></div> note: recommend loading the newer library loader.js instead of jsapi, according to the release notes... The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader.js from now on. this will only change the load statement, see above snippet...
{ "pile_set_name": "StackExchange" }
Q: Definition of Strongly Parsimonious Reduction There is a well known definition of parsimonious reduction. The standard definition of parsimonious reduction is very intuitive. It simply means that the two problem have the same number of solutions, when on input of one of them we applied function $f$. We say there is a parsimonious reduction from #A to #B if there is a polynomial time transformation $f$ such that for all $x$, $|\{y,(x, y) \in A\}| = |\{z : (f(x), z) \in B\}|$. I am interested in definition of strongly parsimonious reduction. The only definition I found: "Strongly parsimonious reduction of $R'$ to $R$ is a parsimonious reduction $g$ that is coupled with an efficiently computable 1-1 mapping of pairs $(g(x), y) \in R$ to pairs $(x, h(x, y)) \in R'$ (i.e., $h$ is efficiently computable and $h(x, ·)$ is a 1-1 mapping of $R(g(x))$ to $R'(x)$). For technical reasons, we also assume that $|g(x)| ≥ |x|$ for every $x$." The problem is I simply don't understand what this definition means. I tried to separate it to smaller block, but so far with no success. According to the definition there are two function $g(x)$ and $h(x,y)$ are they are applied simultaneously to two different problem $R$ and $R'$. How the usages of two function can be explained. What is the difference between two reduction, parsimonious reduction and strongly parsimonious reduction. I would appreciate any help in understanding the definition of strongly parsimonious reduction. A: A search problem is defined by a relation like $R$. The task is given an input $x$ find a solution $y$ s.t. $R(x,y)$ is true. A counting problem is defined as counting the number of solutions of a search problem, i.e. given an input $x$ we want to compute the number of $y$s s.t. $R(x,y)$ holds. The counting problem associated with search problem $R$ is denoted by $\#R: \Sigma^* \to \mathbb{N}$, $x \mapsto \#y: R(x,y)$. A parsimonious reduction $f$ between counting problems only needs to preserve the number of $y$s, i.e. for all $x$, $$\#y:R(x,y) = \#z:S(f(x),z)$$ A strongly parsimonious reduction has an the extra property that you mentioned. The meaning of the property should become clear if you look at it in the following way: Assume that we want to use the search problem $S$ to solve the search problem $R$. On an input $x$ for $R$, we first compute $g(x)$ which is an input for $S$. Then we use $S$ to find an $S$-solution $y$ for $g(x)$, i.e. $(g(x),y)\in S$. Finally we compute $h(x,y)$ to obtain an $R$-solution for $x$. Now if we want to preserve the number of solutions between these two search problems, we can make sure that for every $x$, the function $h(x,\cdot)$ that computes an $R$-solution for $x$ from an $S$-solution $y$ for $g(x)$ is a bijection. The difference should be clear now: not only the number of $R$-solutions for $x$ and $S$-solutions for $g(x)$ are equal, there is an efficient bijection between those solutions.
{ "pile_set_name": "StackExchange" }
Q: Creating a live database (or leader board) for a website I have created a small javascript game for my website. I want to include a leaderboard but don't know what type of database to use - MongoDB, SQLite, ect. I know SQLite is server-less, but does this mean it wouldn't work for my website? Furthermore, how would these databases be updated? If I'm hosting my website through github, wouldn't a git push be required every time an update was needed? A: Github is static. That means you need to use something like Firebase to have updating content.
{ "pile_set_name": "StackExchange" }
Q: Stripping all '\n' from HTMLCalendar() import calendar def websiteCalendar(month, year): return calendar.HTMLCalendar().formatmonth(year, month).rstrip("\n") returns: "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"month\">\n<tr><th colspan=\"7\" class=\"month\">November 2016</th></tr>\n<tr><th class=\"mon\">Mon</th><th class=\"tue\">Tue</th><th class=\"wed\">Wed</th><th class=\"thu\">Thu</th><th class=\"fri\">Fri</th><th class=\"sat\">Sat</th><th class=\"sun\">Sun</th></tr>\n<tr><td class=\"noday\">&nbsp;</td><td class=\"tue\">1</td><td class=\"wed\">2</td><td class=\"thu\">3</td><td class=\"fri\">4</td><td class=\"sat\">5</td><td class=\"sun\">6</td></tr>\n<tr><td class=\"mon\">7</td><td class=\"tue\">8</td><td class=\"wed\">9</td><td class=\"thu\">10</td><td class=\"fri\">11</td><td class=\"sat\">12</td><td class=\"sun\">13</td></tr>\n<tr><td class=\"mon\">14</td><td class=\"tue\">15</td><td class=\"wed\">16</td><td class=\"thu\">17</td><td class=\"fri\">18</td><td class=\"sat\">19</td><td class=\"sun\">20</td></tr>\n<tr><td class=\"mon\">21</td><td class=\"tue\">22</td><td class=\"wed\">23</td><td class=\"thu\">24</td><td class=\"fri\">25</td><td class=\"sat\">26</td><td class=\"sun\">27</td></tr>\n<tr><td class=\"mon\">28</td><td class=\"tue\">29</td><td class=\"wed\">30</td><td class=\"noday\">&nbsp;</td><td class=\"noday\">&nbsp;</td><td class=\"noday\">&nbsp;</td><td class=\"noday\">&nbsp;</td></tr>\n</table>" For some reason it keeps '\n', is there an easy way to strip out all the '\n' from the returned text? I successfully stripped the '\n' element at the end, but there is still the one before the tag that I can't seem to get rid of. A: If you want just to remove all '\n' occurrences from string you should try calendar.HTMLCalendar().formatmonth(year, month).replace("\n", "")
{ "pile_set_name": "StackExchange" }
Q: Unicast Communication in Veins Does Veins support 802.11p unicast communication? I checked the source code of the class "Mac1609_4" in Veins framework. Referring to the following snippet of the code: WaveShortMessage* wsm = dynamic_cast<WaveShortMessage*>(macPkt-> decapsulate()); long dest = macPkt->getDestAddr(); DBG_MAC << "Received frame name= " << macPkt->getName() << ", myState=" << " src=" << macPkt->getSrcAddr() << " dst=" << macPkt->getDestAddr() << " myAddr=" << myMacAddress << std::endl; if (macPkt->getDestAddr() == myMacAddress) { DBG_MAC << "Received a data packet addressed to me." << std::endl; statsReceivedPackets++; sendUp(wsm); } It seems that the implemented MAC layer can receive unicast packet but I couldn't find any method for sending MAC layer acknowledgements that are required in unicast communication. Any suggestions please? There is also a publication by Christoph Sommer et al. that unicast communication is considered harmful in 802.11p. Is it true that because of the reasons mentioned in the paper, Veins framework doesn't support unicast communication? A: Veins framework does not support unicast transmissions. In Section IIIC of the publication here it has been reported that MAC layer of Veins was extended to support unicast transmissions, this means the official release does not include this functionality. The paper was published in 2015 while the latest release of Veins 4.3 came last month. Since there is nothing mentioned about unicast transmissions in the "Changelog" of the latest release, it implies that unicast transmissions are still not supported.
{ "pile_set_name": "StackExchange" }
Q: Custom Object Page Layout (changes) not recognised in Scratch Org when name matches standard We ran into an interesting problem that I can't find mentioned anywhere (or maybe I'm just not able to find it). We have created 2 custom objects that have the "same" name as a standard object: Campaign Member, Opportunity Line Item. (whether that is a good idea shall be a topic for another day :-)). When pulling source from the Scratch Org the Page Layouts for these objects were not included. Whatever change we applied to them, it would just not get picked up. A: Since the Labels of the Custom Objects are the same as their standard equivalents, their default Page Layouts were also named the same: Campaign Member Layout and Opportunity Line Item Layout. It seems that this caused these to be completely overlooked and not synced at all with the local project (the standard Layouts were not changed in any way). My guess is that the changes tracked are somehow stored indexed by the API names and since Layout names can sometimes be the same this somehow clashed and caused the changes in Custom Object layouts not being tracked, i.e. the Standard objects won. Once we updated the name of the layouts to be different from the Standard objects' layouts, there were pulled from the Scratch org without issues.
{ "pile_set_name": "StackExchange" }
Q: MySQL - Select row values from url ID I created a table which is updated through a form and each row gets assigned a specific number. When viewing this table, I want to click on that assigned number and get a page where all the details of that row are displayed. If I do $sql = "SELECT * FROM clients WHERE nif_id='114522';"; - where the nif_id is the assigned number - I get the values for that number, but I need it to change with every number in the table. Any ideas? UPDATE This is the table code: <div class="card card-body"> <table class="table"> <thead> <tr> <th>NIF</th> <th>Nome</th> <th>Apelido</th> <th>Telemóvel</th> <th>E-mail</th> </tr> </thead> <tbody> <?php include_once '../includes/db.inc.php'; $sql = "SELECT * FROM clients ORDER BY nif_id ASC;"; $result = mysqli_query($conn, $sql); $resultCheck = mysqli_num_rows($result); if ($resultCheck > 0) { while ($row = mysqli_fetch_assoc($result)) { $first = $row["prm_nome"]; $last = $row["apelido"]; $phone = $row['nmr_tlm']; $email = $row['mail']; $nif = $row['nif_id']; echo '<tr>'; echo '<td>'.$nif.'</td>'; echo '<td>'.$first.'</td>'; echo '<td>'.$last.'</td>'; echo '<td>'.$phone.'</td>'; echo '<td>'.$email.'</td>'; echo '</tr>'; } } ?> </tbody> </table> </div> A: This is quite a common scenario for web-based systems. <div class="card card-body"> <table class="table"> <thead> <tr> <th>NIF</th> <th>Nome</th> <th>Apelido</th> <th>Telemóvel</th> <th>E-mail</th> </tr> </thead> <tbody> <?php include_once '../includes/db.inc.php'; $sql = "SELECT * FROM clients ORDER BY nif_id ASC;"; $result = mysqli_query($conn, $sql); $resultCheck = mysqli_num_rows($result); if ($resultCheck > 0) { while ($row = mysqli_fetch_assoc($result)) { $first = $row["prm_nome"]; $last = $row["apelido"]; $phone = $row['nmr_tlm']; $email = $row['mail']; $nif = $row['nif_id']; echo '<tr>'; echo '<td><a href="detail.php?nifid=' . $nif . '">'.$nif.'</a></td>'; echo '<td>'.$first.'</td>'; echo '<td>'.$last.'</td>'; echo '<td>'.$phone.'</td>'; echo '<td>'.$email.'</td>'; echo '</tr>'; } } ?> </tbody> </table> </div> where the detail.php is another page to query specific details regarding the query nifid. As a reminder, if the data type of the column is INT, there is no need to use single quotes to surround the value in the SQL statement. Sample detail.php: <?php if(!isset($_GET['nifid']) || (int)$_GET['nifid'] <= 0) { // Invalid or missing NIFID header('Location: table.php'); } include_once '../includes/db.inc.php'; $id = (int)$_GET['nifid']; $sql = "SELECT * FROM clients WHERE nif_id=$id"; $result = mysqli_query($conn, $sql); $row = mysqli_fetch_assoc($result); // TODO: display the result in whatever way you like ?>
{ "pile_set_name": "StackExchange" }
Q: .net core + MongoDB how to create database dynamically I have a .net core project with MongoDB. Before starting to work with this I need to create DB for this manually. I mean I need to go mongo shell and use next commands like this: use admin db.createUser( { user: "admin", pwd: "abc123!", roles: [ { role: "root", db: "admin" } ] } ); exit; But I don't like do this every time when I need to deploy my project. How can I automate this process and creating DB dynamically from C# code or use some other solution if it's possible? P.S. I use this article for building work with MongoDB + .net core. A: The solution is to use a mongoDb driver. U can get it via nuget. In general u just instantiate a server object and call GetDatabase to create a Database. server.GetDatabase("myDB"); This way you can also create users using the mongoDb driver as mentioned here : How to create a user in MongoDB Further reading: https://www.nuget.org/packages/MongoDB.Driver/2.3.0 http://mongodb.github.io/mongo-csharp-driver/2.2/getting_started/installation/ The following Video provides a short tutorial how to do it: https://www.youtube.com/watch?v=6x0-vHHHpv8 Thanks to that answer : https://stackoverflow.com/a/30629593/4992212
{ "pile_set_name": "StackExchange" }
Q: target="new" is not opening new tab or window of my browser in OpenSocial app target="new" is not opening new tab or window of my browser in OpenSocial app! A: target="_blank"
{ "pile_set_name": "StackExchange" }
Q: Adding alias to end of alias list in .bashrc file using sed I'm writing a shell script that I want to add an alias to the end of the alias list in the .bashrc file. I'm thinking something with sed would work, just not sure how to find the last line that begins with alias, then add on the next line another alias. A: Why do you need to add it to an "alias list"? If you don't have additional requirements that you did not specify in the question, just append your alias to .bashrc: echo "alias youralias='yourcmd'" >> /home/user/.bashrc A: When I hear "do something after the last whatever", I think of reversing the file and do something when I see the first whatever: tac .bashrc | awk -v newalias="alias new=foo" '$1 == "alias" {print newalias} 1' | tac > .bashrc.new mv .bashrc .bashrc.$(date +%Y%m%d%H%M%S) && mv .bashrc.new .bashrc
{ "pile_set_name": "StackExchange" }
Q: ComboBox is Overriding Another ComboBox using Excel 2013 VBA I am trying to use comboboxes to hide/unhide specific sections of my excel sheet. I have one combobox that hides/unhides a specific block (ComboBox1) of cells and another that hides/unhides sections of cells within that block(ComboBox2). Everything works accept when I go to unhide the whole block, it overrides the sections that Ive selected hidden within that block. Is there a way to execute ComboBox2 after clicking ComboBox1 to update the worksheet. Private Sub ComboBox3_Click() ComboBox3.TextAlign = fmTextAlignCenter ComboBox3.List = Array("1", "2", "3", "4") If ComboBox3.Value = "1" Then 'ranges to be hidden = True/False End If End Sub Private Sub ComboBox4_Click() ComboBox4.TextAlign = fmTextAlignCenter ComboBox4.List = Array("0", "5", "6", "7", "8", "9", "10") If ComboBox4.Value = "0" Then 'Ranges to be hidden in ComboBox3 block of cells' End if End Sub A: If you just want to call the Event, just call ComboBox4_Click Private Sub ComboBox3_Click() ComboBox3.TextAlign = fmTextAlignCenter ComboBox3.List = Array("1", "2", "3", "4") If ComboBox3.Value = "1" Then 'ranges to be hidden = True/False End If Combo4Handler End Sub Private Sub ComboBox4_Click() Combo4Handler End Sub Private Sub Combo4Handler() ComboBox4.TextAlign = fmTextAlignCenter ComboBox4.List = Array("0", "5", "6", "7", "8", "9", "10") If ComboBox4.Value = "0" Then 'Ranges to be hidden in ComboBox3 block of cells' End if End Sub
{ "pile_set_name": "StackExchange" }
Q: Haproxy - HTTP/2 - TLS ALPN - Don't work correctly I have a centos 7 server with OpenSSl 1.0.2j fully working. With Nginx working correcly with HTTP/2 but haproxy fail. When I try to run a curl ( is already version 7.51 ) once is enabled alpn h2 I have the following error : curl --http2 -I https://domain:port/file.htm curl: (16) Error in the HTTP2 framing layer If I disabled h2, curl work correctly but of course only connect http 1.1 : curl --http2 -I https://domain.com:port/file.htm HTTP/1.1 200 OK Server: nginx/1.11.6 Date: Fri, 18 Nov 2016 12:22:47 GMT Content-Type: text/html; charset=utf-8 Last-Modified: Wed, 10 Aug 2016 10:27:58 GMT Connection: keep-alive Vary: Accept-Encoding ETag: "57ab01ae-59" Expires: Tue, 13 Dec 2016 12:22:47 GMT Cache-Control: max-age=2160000 X-Page-Speed: Powered By ngx_pagespeed Here I put haproxy setting ( it suppose only is setup https mode ) global # Default SSL material locations ca-base /etc/ssl/certs crt-base /etc/ssl/private # Default ciphers to use on SSL-enabled listening sockets. ssl-default-bind-options no-sslv3 no-tls-tickets force-tlsv12 ssl-default-bind-ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS spread-checks 4 tune.maxrewrite 1024 tune.ssl.default-dh-param 2048 ... frontend mode tcp bind 0.0.0.0:60641 ssl crt /etc/haproxy/certs/domain.pem alpn h2,http/1.1 http-response set-header Strict-Transport-Security "max-age=16000000; includeSubDomains; preload;" ... backend stick-table type ip size 200k expire 30m stick on src server server_51_a4.domain.com IP:PORT check ssl verify none I have read a lot of sites and information related OpenSSL Information : https://www.nginx.com/blog/supporting-http2-google-chrome-users/ Setup curl haproxy and others : https://blog.cloudflare.com/tools-for-debugging-testing-and-using-http-2/ Best site to setup Nginx and Haproxy : http://m12.io/blog/http-2-with-haproxy-and-nginx-guide Here Haproxy vv information HA-Proxy version 1.7-dev3 2016/05/10 Copyright 2000-2016 Willy Tarreau <[email protected]> Build options : TARGET = linux2628 CPU = generic CC = gcc CFLAGS = -O2 -g -fno-strict-aliasing -DTCP_USER_TIMEOUT=18 OPTIONS = USE_LINUX_TPROXY=1 USE_ZLIB=1 USE_REGPARM=1 USE_OPENSSL=1 USE_LUA=1 USE_PCRE=1 USE_PCRE_JIT=1 Default settings : maxconn = 2000, bufsize = 16384, maxrewrite = 1024, maxpollevents = 200 Encrypted password support via crypt(3): yes Built with zlib version : 1.2.7 Compression algorithms supported : identity("identity"), deflate("deflate"), raw-deflate("deflate"), gzip("gzip") Built with OpenSSL version : OpenSSL 1.0.2j 26 Sep 2016 Running on OpenSSL version : OpenSSL 1.0.2j 26 Sep 2016 OpenSSL library supports TLS extensions : yes OpenSSL library supports SNI : yes OpenSSL library supports prefer-server-ciphers : yes Built with PCRE version : 8.32 2012-11-30 PCRE library supports JIT : yes Built with Lua version : Lua 5.3.0 Built with transparent proxy support using: IP_TRANSPARENT IPV6_TRANSPARENT IP_FREEBIND Available polling systems : epoll : pref=300, test result OK poll : pref=200, test result OK select : pref=150, test result OK Total: 3 (3 usable), will use epoll. Available filters : [COMP] compression [TRACE] trace Also I have seen another site where told haproxy don't support Http/2. https://istlsfastyet.com/#server-performance What is the problem ? Haproxy ? Centos 7 openssl support ? Thank you for read. Help world to have haproxy ready for http/2. I want to add another question related. "When setting up haproxy in front on a web server, haproxy will do the ALPN negotiation". And what happen if we can use haproxy with two levels and in different servers. Server 01 - Level 01 - Haproxy ( listen ssl) Server 02 - Level 02 - Haproxy ( listen ssl) Server 03 - Level 03 - Nginx ( listen no ssl ) In this model, who did Alpn negotiation ? In my test I have trying to make a proxy from SSL to another SSL server. Thanks for all. Brqx / Ricardo. A: When setting up haproxy in front on a web server, haproxy will do the ALPN negotiation. That means that only haproxy knows which protocol was negotiated (http/1.1 or h2). I believe you're seeing an error because haproxy is negotiating h2, and then sending clear text HTTP/2 traffic to a server that's not expecting it. As pointed out by the 'The complete guide to HTTP/2 with HAProxy and Nginx' site you liked to, the way you address that is that you make Nginx listed for two ports: one for HTTP/1.1 and another for HTTP/2: listen 80 default_server; listen 81 default_server http2 proxy_protocol; ## Needed when behind HAProxy with SSL termination + HTTP/2 support Then, in haproxy, you declare two backends: backend nodes-http server node1 web.server:80 check backend nodes-http2 mode tcp server node1 web.server:81 check send-proxy and direct traffic depending on the negotiated ALPN protocol: use_backend nodes-http2 if { ssl_fc_alpn -i h2 }
{ "pile_set_name": "StackExchange" }
Q: What determines Catchability of Pokémon? I've noticed that after beating a stage, the initial Catchability percentage will be very low, despite being what I would consider a good game. It then adds on additional percentage for moves that were unused. What I don't understand is how the initial percent is calculated. I can do really well on one stage and get a low percentage, but do pretty badly on another and get a high percentage. How is the Catachability determined? A: According to Bulbapedia: Pokémon have a set capture rate that is added to depending on how many moves a player has left at the end of a battle (Example: 50% plus 5% per move remaining.) Timed levels have a per-3-seconds-group bonus that is added for each time 3 seconds can be subtracted from the time remaining before it becomes zero or negative. If capture fails and the player has at least 2500 coins, they are offered the choice of buying a Great Ball that has twice the probability of capture of the Poké Ball used for free. So it's not calculated, it's a fixed value. The only thing you can do to increase the Catchability is end a challenge with a good amount of left moves or time. And eventually use a Great Ball. Note that Moves+5 and Time+10 do not increase capture rate for those bonus moves, so you can't use these items to make it easier to catch a Pokémon. If you end the stage with 5 or fewer moves, the Pokémon will have the same capture rate as if you beat it with 0 moves remaining. EDIT: The latest update introduced a new feature called Super Catch Power: After successfully completing a stage, if the player fails to catch a Pokémon with their first Poké Ball (before using a Great Ball), they have a chance of being offered a "Super Catch Power". This Super Catch Power provides a somewhat random boost on top of the Great Ball's boost (the player still uses a Great Ball, and can use the same number of Great Balls as they could without the "Super Catch Power")
{ "pile_set_name": "StackExchange" }
Q: How do I display Numbers and Text in C# with XNA? I am working on a pong clone, and i want to display the player scores onscreen. I don't know how to display it. A: The SpriteBatch object has a DrawString method that takes: a SpriteFont which can be created in your content project and loaded via content.Load the string you wish to write to the screen a Vector2 of the position that you want to draw the text at the Color you wish the text to be. So for example your draw method might look like this: public void Draw() { spriteBatch.Begin(); DrawPaddles(spriteBatch); DrawBall(spriteBatch); // this being the line that answers your question spriteBatch.DrawString(scoreFont, playerScore.ToString(), new Vector2(10, 10), Color.White); spriteBatch.End(); } See http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.drawstring.aspx A: You should start your XNA journey at the XNA Creators Club. Even the most basic tutorials output text. The XNA Forums are a better resource for XNA-related questions.
{ "pile_set_name": "StackExchange" }
Q: Why textbox is still disabled after removing value from other text box in angular I have a angular page with two textboxes. Once user enter value in any of the text box then other text box should get disabled. Below is my code: <div class="col-md-4"> <input type="text" class="form-control" [(ngModel)]="firstName" [disabled]="lastName"/> </div> <div class="col-md-4"> <input type="text" class="form-control" [(ngModel)]="lastName" [disabled]="firstName"/> </div> This works fine but if I remove value from textbox then other textbox is not getting enabled. A: The ngModel directive appears to alter the behavior of the disabled property binding. The input element is disabled when ngModel is applied and disabled is bound to an empty string: <input type="text" [disabled]="''" /> // Enabled <input type="text" ngModel [disabled]="''" /> // Disabled <== unexpected!!! <input type="text" ngModel [disabled]="" /> // Enabled <input type="text" ngModel [disabled]="undefined" /> // Enabled <input type="text" ngModel disabled /> // Disabled Therefore, if emptyString is an empty string, the following control will be disabled: <input type="text" [(ngModel)]="value" [disabled]="emptyString" /> // Disabled You can get the expected behavior by converting the string to a boolean with !!: <input type="text" [(ngModel)]="value" [disabled]="!!emptyString" /> // Enabled These behaviors can be observed in this stackblitz:
{ "pile_set_name": "StackExchange" }
Q: drawInRect not preserving transform UIGraphicsBeginImageContext(backgroundImageView.frame.size); UIImageView *image1 = backgroundImageView; UIImageView *image2 = boat; // Draw image1 [image1.image drawInRect:CGRectMake(0, 0, image1.image.size.width, image1.image.size.height)]; // Draw image2 [image2.image drawInRect:CGRectMake(boat.center.x, boat.center.y, boat.image.size.width, boat.image.size.height)]; UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext(); When resultingImage is displayed the transform angle value for image2 is not preserved after I set it equal to the boat UIImageView. I thought that when I set image2 = boat that the transform value of boat would carry over to image2. I suspect it relates to the fact that I am I am working with UIImageView instead of UIVIew. I have tried many different things but have been unable to resolve this issue. Any help would be appreciated. Thanks. A: When you draw an image into a graphics context, it uses the context's transformation matrix, which is distinct from any transformation applied to a view. So the transformation on image2 (a UIImageView presumably) is completely irrelevant to direct image drawing. You can either specify a new transformation with the various CGContext and CGAffineTransform functions in Quartz, or you can directly apply a copy of the UIImageView 's transformation like so: CGContextConcatCTM(UIGraphicsGetCurrentContext(), someView.transform); [someView.image drawInRect: CGRectMake(...)];
{ "pile_set_name": "StackExchange" }
Q: How to concatenate DateParts in Sql Server I really need a help from Database ninjas. I have the following piece of code: SELECT DATEPART(hh, BeginMinute) AS Intervalo, SUM(Qtde) AS Total FROM tr_CustomerCount WHERE BeginMinute > '5/22/2013 00:00:00 AM' AND BeginMinute < '6/22/2013 12:00:00 AM' GROUP BY DATEPART(hh, BeginMinute) Actually it just returns the Hour (HH) but I wanna show the HOUR and MINUTE together separated by " : " such '12:00' its can be a String, no worries. How can I do this? Thanks in advance! A: You could use CONVERT with style 114 (section Date and Time Styles): SELECT CONVERT(VARCHAR(5), GETDATE(), 114); or, starting from SQL Server 2012 you can use FORMAT (demo): SELECT FORMAT(GETDATE() , 'hh:mm');
{ "pile_set_name": "StackExchange" }
Q: Filter rows based on condition sql server 2008 The below is the sample data. Op_ID manual TT ------------------ 1 0 32 1 1 38.4 2 0 4.56 2 1 7.5 55 1 50 55 1 30 case 1: i need to check Op_id and manual column, if the manual column is having 0 then i need to take tt value= 32 and ignore the below record. similarly needs to check the other records.i.e. op_id=2 and manual=0 then need to take tt=4.56. case 2: if both records having manual =1 then i need to take max of tt, i.e tt=50.(for the op_id=55). So i need the output like below. Op_ID manual TT ------------------ 1 0 32 2 0 4.56 55 1 50 A: select opid, manual, tt from ( select *, row_number() over (partition by opid order by manual, tt desc) rn from yourtable ) v where rn = 1
{ "pile_set_name": "StackExchange" }
Q: What would it be like to participate in a (coronavirus) challenge trial, in the US? I am strongly considering volunteering for any COVID human challenge trial that becomes available near me (midwestern United States). I am willing to undergo long-term isolation. However, I am not willing to significantly disrupt my work life. That means I want free time with my computer, significant private time, and the opportunity to be physically active. Can anyone give me an educated guess about whether, as a participant in such a trial, I would have access to things like free time, space to exercise, and a personal computer? I presume that the answer is "the range of situations is extremely wide, and the answer depends on a bunch of factors." However, I would appreciate any suggestive information. I would also appreciate advice in how best to phrase these questions to get good answers from prospective trial administrators. Thanks! A: You would want to talk to the staff who are recruiting patients; I'm not aware of any such trials that have started anywhere yet. I would expect you would have access to most of those things depending on what your definitions are of private time and physical activity. As far as asking questions, just be direct and define your terms. "Can I bring my computer and have internet access" might not be specific enough if your question is really "Can I work an uninterrupted full-time schedule from 8 am to 5 pm using my computer?" - the answer to that is likely no, but you might get an idea of what interruptions you can expect, how often, etc, and also how flexible those interruptions can be. An example facility that is capable of appropriate isolation and has been used in influenza challenge trials is at NIH; their tour video at the page linked below might be a good place to start for some of your questions. https://www.niaid.nih.gov/news-events/scsu-video-tour I think the whole video is probably useful to someone considering participating in a trial, but I'd note that around 12 minutes they are touring a patient room and shortly after there is some discussion of what the patients participating in clinical trials there can bring in, which includes bringing in computers for entertainment and work. Again, I wouldn't use this video as a guarantee of anything for a specific trial you might be involved in, so ask your specific questions to those trial staff. If you do participate, you of course may develop symptoms that interfere with all the things you mentioned.
{ "pile_set_name": "StackExchange" }
Q: how to check multiple values of a result from ajax request in jquery's if statement hi i have an ajax request where i am sending some request to an php file through ajax and the request is generating a result so far everything is working good but now i want to keep some validations for my results. i am doing this on dynamically added table rows so if the validations is are not met it wont allow to add a new row but still after validating it is adding rows can anybody help in fixing my issue thanks here is my code $("#savetodb").removeAttr("disabled"); var vendor = $("#sub_vendor_id"+rowcount+">option:selected").val(); var product = $("#prodid_"+rowcount).val(); var productname = $("#prod_"+rowcount).val(); var vouchdt = $("#dateinfo").val(); var qty = $("#quantity_"+rowcount).val(); var amt = $("#amount_"+rowcount).val(); $.get("../model/check_product_with_invoice_number.php", { invno : invoice, product : product, vendor : vendor, date : vouchdt, quantity : qty, amount : amt }, function (result) { if(result == "") { alert(productname+" Does not exist for invoice number "+id); $("#savetodb").attr("disabled", "disabled"); } if(result == 2) { alert("Quantity "+ qty +" for "+productname+" does not exist for invoice number "+id); $("#savetodb").attr("disabled", "disabled"); } if(result == 3) { alert("Amount "+amt +" For "+productname+" does not exist for invoice number "+id); $("#savetodb").attr("disabled", "disabled"); } if(result !=='' && result !==3 && result !==2){ $("#savetodb").removeAttr("disabled"); append_row('enable remove','',prods,unitid,unitcode); } }); here is my php $code = mysql_real_escape_string($_GET["invno"]); $vendor = mysql_real_escape_string($_GET["vendor"]); $product = mysql_real_escape_string($_GET["product"]); $vouchdt = mysql_real_escape_string($_GET["date"]); $amt = mysql_real_escape_string($_GET["amount"]); $qty = mysql_real_escape_string($_GET["quantity"]); $chkquantity = mysql_query("SELECT * FROM `gc_procurement_daily_detail` WHERE quantity_procured='".$qty."' AND product_id='".$product."' AND sub_vendor_id='".$vendor."'")or die(mysql_error()); if(mysql_num_rows($chkquantity)> 0){ $chkamt = mysql_query("SELECT * FROM `gc_procurement_daily_detail` WHERE procured_detail_amount='".$amt."' AND product_id='".$product."' AND sub_vendor_id='".$vendor."' AND quantity_procured='".$qty."'")or die(mysql_error()); if(mysql_num_rows($chkamt)>0){ $chkinvoice = mysql_query("SELECT a.*, b.* FROM `gc_procurement_daily_detail` a, `gc_procurement_daily_summary` b WHERE a.sub_vendor_id='".$vendor."' AND a.product_id='".$product."' AND a.quantity_procured='".$qty."' AND a.procured_detail_amount='".$amt."' AND b.`date_of_invoice`='".$vouchdt."' AND b.invoice_number='".$code."' AND a.`procurement_daily_summary_id`= b.procurement_daily_summary_id")or die(mysql_query()); $minv = mysql_fetch_object($chkinvoice); $fininv = $minv->invoice_number; if($code == $fininv){ echo 1; exit; }else{ echo ''; exit; } }else{ echo 3; exit; } }else{ echo 2; exit; } A: Ok just warp the ajax conditions inside double quote if(result !=='' && result !=="3" && result !=="2") And this for all of them. as this answer has been chosen as best answer i would suggest to combine other ideas also that you should chain your conditions in if(){ }else if(){ } an so on or use Switch (result){ case 1: //Do logic of this case here break; case 2: //Do logic of this case here break; } so you will have benefit of exiting execution whenever your condition achieved That's all.
{ "pile_set_name": "StackExchange" }
Q: Skipping arguments/parameters without using empty strings Theoretically speaking, let's say I have a function that takes 100 parameters and I only want to use 1 of these, and it's the 100th one. Instead of writing 99 empty strings before I can pass the 100th one, is there an easier way of doing this? I know you should never have 100 parameters but I got curious if this is even possible. A: Use parameter objects - you can easily set defaults and override what you want with the parameter var foo = myFunction({foo:'bar', bar:25}) Google parameter objects, eg Passing Default Parameter Objects in JavaScript (but if you've got more than 3 or 4 parameters you might have a more serious problem)
{ "pile_set_name": "StackExchange" }
Q: Can a 485 network work if the DE (driver enable) pin of the transceiver is always on? We are using a Beaglebone Black with the Osso Cape (https://github.com/nexlab/Osso) for comunicating with other equipment using a 485 connection and Modbus RTU. The driver enable (DE) pin of the cape's DS485 chip is tied to the GPIO 2_24, while the RO and DI pins were tied to the UART1 RX and TX respectively. We haven't write any code to act on the GPIO2_24 at all, other than a cape overlay that sets it as output and pin Mode GPIO. We were troubleshooting some communication problems when we noticed something strange: Using an oscilloscope, we saw that the driver enable (DE) pin was always high, but somehow the Beaglebone was able to normally send requests and receive correctly responses from the other equipement. Normally I would expect that the 485 comms only worked with the DE pin HIGH when transmitting and LOW when finished, to avoid driving the bus when other equipment respond. In other capes we used, this was controlled using UART4 RTS, but I could not explain why it seems to work in this case. Is there any explanation on why it works with the DE always on? EDIT: The datasheet (http://www.ti.com/lit/ds/symlink/ds485.pdf) says: Due to the multipoint nature of the bus, contention between drivers may occur. This will not cause damage to the drivers since they feature short-circuit protection and also thermal shutdown protection. Thermal shutdown senses die temperature and puts the driver outputs into TRI-STATE if a fault condition occurs that causes excessive power dissipation which can elevate the junction temperature to +150°C. Maybe the chip senses contention and goes to high-impedance state, then being able to receive the response from the other equipment? A: It is quite possible that the state with the driver always on would allow communications to work in both directions due to the overall current limit and effective output impedance of the driver. You do want to correct this however because the driver in this condition will be under unnecessary stress and drawing way more current from your power sources than necessary. A stressed driver chip may very well have a shortened life. The correction of course is to devise the programming necessary to drive the GPIO to turn off the driver once transmission is complete. Turning off the driver at the correct time can, in some cases, require some careful work. Due to the fact that the sending UART port will spend time sending the last loaded data bytes after the final data is loaded there is a need to comprehend when sending is complete. Some considerations... Some UARTs are capable of generating an interrupt when the actual serial data pipe plus any FIFO buffered data has been sent. This can be leveraged as the time to turn off the UART. If there is no actual UART EMPTY indicator then you may need to use a time delay in the software to get to the time when to turn off the driver. This could be a timer interrupt delay or an inline software delay. In practical applications of RS485 interfaces it is often the best practice to assign one device as the master initiator of transaction packets on the interface. All other devices are then slave responder devices. It is a good idea for a slave responder device to delay a bit from receiving a transaction packet till sending the start of its response packet. This delay allows time for the master initiator to get off the bus before the slave tries to send. Likewise the master should delay between receipt of a response packet and start of sending the next initiator packet to allow the slave device to get back off the bus.
{ "pile_set_name": "StackExchange" }
Q: Cannot insert into mysql database I'm trying to insert data to database. There is no error, but the database is still not being updated. In the database, the product table contains: productid, categoryid, productname, productimage, stock, price and the detailsales table contains: transactionid, productid, and quantity The update one is working, but the insert one is not working at all. Here is my code: <form action="doShop.php" method="post"> <table border="1"> <tr> <td>Product ID</td> <td>Product Name</td> <td>Product Image</td> <td>Price</td> <td>Product Stock</td> <td> Quantity</td> </tr> <?php $query = mysql_query("SELECT * FROM Product"); while($row = mysql_fetch_array($query)){ ?> <tr> <td><input type="text" value="<?=$row['ProductID']?>" name="productid"></td> <td><?=$row['ProductName']?></td> <td><img src="image/<?=$row['ProductImage']?>"></td> <td><?=$row['Price']?></td> <td><input type="text" value="<?=$row['Stock']?>" name="stock"></td> <td><input type="text" name="quantity"></td> </tr> <?php } print mysql_error(); ?> </table> <table> <tr><input type="submit" value="Submit"></tr> </table> </form> Here is the doShop code: <?php include("connect.php"); $id=$_REQUEST['productid']; $quantity=$_REQUEST['quantity']; $stock = $_REQUEST['stock']; mysql_query("insert into DetailSales(ProductID, Quantity)values('".$id."','".$quantity."')"); mysql_query("update product set stock = $stock - $quantity where detailsales.productid = product.productid"); header("location:shopcart.php"); ?> Can anyone help me? A: You were trying to carry out calculations inside your query, instead I created a separate variable called $total to handle that for, you. Like this: $total = $stock - $quantity; Instead of this: SET stock = $stock - $quantity So, change the doshop code to this: <?php include("connect.php"); $id = $_REQUEST['productid']; $quantity = $_REQUEST['quantity']; $stock = $_REQUEST['stock']; $total = $stock - $quantity; mysql_query("INSERT INTO DetailSales(ProductID, Quantity) VALUES ('".$id."','".$quantity."')") or die(mysql_error()); mysql_query("UPDATE product SET stock = '$total' WHERE detailsales.productid = product.productid") or die(mysql_error()); header("Location: shopcart.php");
{ "pile_set_name": "StackExchange" }
Q: Pan the map depending on the zoom (how to do the math) http://jsfiddle.net/bor9zuhr/2/ On this Fiddle is an illustration of my problem. I have the navigation over the top of the map element. Now, when you click a marker, the map is being panned to the marker's coordinates, and the top of the info window most probably will not be readable when it is large enough. What I want is to pan the map to a position above the marker, so that the info window falls lower, and will not be obscured by the navigation. Ideally, it would fall right in the middle of the visible area. The problem is that when the map is zoomed in far, I need to pan it for a much smaller amount than if it were zoomed out far. And I can't seem to get the math right. This is the part of the code that deals with the panning: infowindow.open(map, marker); var K = 0; // this should be something depending on the zoom level var lat = marker.getPosition().lat() + K; var lng = marker.getPosition().lng(); var newCenter = new google.maps.LatLng(lat, lng); map.panTo(newCenter); A: You could call map.panBy at the end of your function. From the docs: Changes the center of the map by the given distance in pixels. If the distance is less than both the width and height of the map, the transition will be smoothly animated. Note that the map coordinate system increases from west to east (for x values) and north to south (for y values). With panBy you don't have to think about zoom levels, you just pan by pixels.
{ "pile_set_name": "StackExchange" }
Q: What does process.env.wifi_interface do? While reading someone's code on Github's electron, I came across the line var wifi_interface = process.env.wifi_interface What does it do? A: It is copying an environment variable to a local variable. Any software can set environment variables but going by the name I'd suggest it is a variable that the user should set in their shell prior to running the software to define the device node of the wifi hardware (ie: /dev/eth0 or equivalent) that the software should communicate with. export WIFI_INTERFACE=/dev/eth0 Windows also supports environment variables usually set via the "System" control panel. If you want a more specific answer you'll really need to look at the source code and/or documentation.
{ "pile_set_name": "StackExchange" }
Q: Firefox doesn't do "asynchronous" load on dynamic script injection? I've 2 js functions, request() and response(). Request injects a dynamic script tag to DOM, loading some "script" from server. The script that comes from server is set to call response(). Now if I make 5 calls one after the other immediately, and if first one is still waiting, the next 4 calls are still made, the response comes back (I saw that from Firebug), but response() is not called until the first one returns. This is happening only in Firefox. :( Why is this not making the function call ? PS : if first request is being delayed, I don't care about its results, I want the last one to be loaded and calling response without delays.. I tried $.ajax with dataType set to 'jsonp', pure javascript style insertion of script tags and $.getScript. Nothing seems to be working well with FF :( Edit : For those who requested code samples : function request(){ var URL = 'http://xxx.xxx.xxx.xxx/cgi-bin/response.php?callback=?'; callHandle = $.getScript(URL); } function response(data){ alert(data); } the request function calls the server's php script, which has following code : $data = $_GET['callback']; //using just to identify request uniquely. sleep(rand(1,10)); echo "response(".$data.")"; Now if first request takes 10 seconds, and second request takes 2 seconds, the response should be called back for the second request. But it is getting the response, but instead of alerting, it is waiting for first request to complete in firefox. Why is this so ? A: I've seen the same thing: Firefox handling the return responses (javascript inclusions done with document.createElement('script') and append them to the Head-Node) in the order in which script elements were appended to the document. From a programmer viewpoint this simplifies programming. However, I think you should treat this as an implementation detail from this browser (version), not a guarantee. Google chrome executes the included scripts in any (unexpected) order. This behavior is already called "Old firefox behavior" when looking to Firefox 4 and HTML5 compliance ( http://hsivonen.iki.fi/script-execution/ ) The Old firefox behavior Script-inserted external non-async, non-defer scripts executed in the order they were inserted into the document. Have you tried inserting your scripts with document.write?
{ "pile_set_name": "StackExchange" }
Q: Help on installing a tar.gz on Ubuntu Okay, I am trying to install, Icecast http://www.icecast.org/ guggy@guggy-pc:~/Downloads/icecast$ ./configure checking for a BSD-compatible install... /usr/bin/install -c checking whether build environment is sane... yes checking for a thread-safe mkdir -p... /bin/mkdir -p checking for gawk... no checking for mawk... mawk checking whether make sets $(MAKE)... yes checking whether to enable maintainer-specific portions of Makefiles... no checking for gcc... gcc checking whether the C compiler works... yes checking for C compiler default output file name... a.out checking for suffix of executables... checking whether we are cross compiling... no checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether gcc accepts -g... yes checking for gcc option to accept ISO C89... none needed checking for style of include used by make... GNU checking dependency style of gcc... gcc3 checking build system type... i686-pc-linux-gnu checking host system type... i686-pc-linux-gnu checking how to print strings... printf checking for a sed that does not truncate output... /bin/sed checking for grep that handles long lines and -e... /bin/grep checking for egrep... /bin/grep -E checking for fgrep... /bin/grep -F checking for ld used by gcc... /usr/bin/ld checking if the linker (/usr/bin/ld) is GNU ld... yes checking for BSD- or MS-compatible name lister (nm)... /usr/bin/nm -B checking the name lister (/usr/bin/nm -B) interface... BSD nm checking whether ln -s works... yes checking the maximum length of command line arguments... 1572864 checking whether the shell understands some XSI constructs... yes checking whether the shell understands "+="... yes checking how to convert i686-pc-linux-gnu file names to i686-pc-linux-gnu format... func_convert_file_noop checking how to convert i686-pc-linux-gnu file names to toolchain format... func_convert_file_noop checking for /usr/bin/ld option to reload object files... -r checking for objdump... objdump checking how to recognize dependent libraries... pass_all checking for dlltool... no checking how to associate runtime and link libraries... printf %s\n checking for ar... ar checking for archiver @FILE support... @ checking for strip... strip checking for ranlib... ranlib checking command to parse /usr/bin/nm -B output from gcc object... ok checking for sysroot... no checking for mt... mt checking if mt is a manifest tool... no checking how to run the C preprocessor... gcc -E checking for ANSI C header files... yes checking for sys/types.h... yes checking for sys/stat.h... yes checking for stdlib.h... yes checking for string.h... yes checking for memory.h... yes checking for strings.h... yes checking for inttypes.h... yes checking for stdint.h... yes checking for unistd.h... yes checking for dlfcn.h... yes checking for objdir... .libs checking if gcc supports -fno-rtti -fno-exceptions... no checking for gcc option to produce PIC... -fPIC -DPIC checking if gcc PIC flag -fPIC -DPIC works... yes checking if gcc static flag -static works... yes checking if gcc supports -c -o file.o... yes checking if gcc supports -c -o file.o... (cached) yes checking whether the gcc linker (/usr/bin/ld) supports shared libraries... yes checking whether -lc should be explicitly linked in... no checking dynamic linker characteristics... GNU/Linux ld.so checking how to hardcode library paths into programs... immediate checking whether stripping libraries is possible... yes checking if libtool supports shared libraries... yes checking whether to build shared libraries... yes checking whether to build static libraries... yes checking for special C compiler options needed for large files... no checking for _FILE_OFFSET_BITS value needed for large files... 64 checking for ANSI C header files... (cached) yes checking whether time.h and sys/time.h may both be included... yes checking alloca.h usability... yes checking alloca.h presence... yes checking for alloca.h... yes checking sys/timeb.h usability... yes checking sys/timeb.h presence... yes checking for sys/timeb.h... yes checking for pwd.h... yes checking for unistd.h... (cached) yes checking for grp.h... yes checking for sys/types.h... (cached) yes checking for setuid... yes checking for chroot... yes checking for chown... yes checking for __func__... yes checking for localtime_r... yes checking for poll... yes checking for gettimeofday... yes checking for ftime... yes checking for library containing nanosleep... none required checking sys/socket.h usability... yes checking sys/socket.h presence... yes checking for sys/socket.h... yes checking for socklen_t... yes checking for va_copy... va_copy checking sys/select.h usability... yes checking sys/select.h presence... yes checking for sys/select.h... yes checking sys/uio.h usability... yes checking sys/uio.h presence... yes checking for sys/uio.h... yes checking winsock2.h usability... no checking winsock2.h presence... no checking for winsock2.h... no checking for library containing sethostent... none required checking for library containing getnameinfo... none required checking for endhostent... yes checking for getaddrinfo... yes checking for inet_aton... yes checking for writev... yes checking for struct sockaddr_storage.ss_family... yes checking for inet_pton... yes checking for xslt-config... no configure: error: XSLT configuration could not be found Readme tells me this To build icecast on a Unix platform, perform the following : Run ./configure make make install This is the typical procedure if you download the tar file. If you retrieve the code from subversion or want to rebuild the configure then run autogen.sh instead of the configure above. Most people do not need to run autogen.sh A sample config file will be placed in /usr/local/etc (on UNIX) or in the current working directory (on Win32) and is called icecast.xml Documentation for icecast is available in the doc directory, by viewing doc/index.html in a browser. A: You will find the answer here: http://www.linuxquestions.org/questions/linux-newbie-8/icecast-and-xslt-config-problem-205105/ Basically sudo apt-get install libxslt-dev. As a tip, when you install things like this, always read the README. It is usually in the source directory of the tarball once uncompressed. Still in building source yourself, when it fails it is usually because it is missing a dependency. Spot the dependency needed, install it with sudo apt-get install *dependency* and try build again. Also, please use some formatting so people can read your post.
{ "pile_set_name": "StackExchange" }
Q: Why is the Foursquare API only generating results for certain coordinates? I am using the Foursquare API to read JSON pages filled with the trending venues in areas. I tried generating a link as they explain to, but venues are only returned for the coordinates, 40.7, -74 – the ones they give as an example on their site. This can be seen using their API Explorer: The trending restaurants are returned for the coordinates they give as an example, as can be seen at this link: https://developer.foursquare.com/docs/explore#req=venues/trending%3Fll%3D40.7,-74 But trying coordinates for San Francisco, for instance – 37.755516, -122.44812 – doesn't return anything, although it also doesn't show an error: https://developer.foursquare.com/docs/explore#req=venues/trending%3Fll%3D37.755516,-122.44812 I tried both links with my own Client ID and Client Secret outside of the explorer, but again I only got results for 40.7, -74. This leads me to believe that it must be the coordinates I'm giving it, although I cannot figure out why. Many thanks in advance. A: Not all points have trending venues nearby. If the check-in volume in the area is low, or no venues are especially busy at the moment, there will be no trending venues. Here is a spot in San Francisco that, at the time of this writing, has trending venues: https://developer.foursquare.com/docs/explore#req=venues/trending%3Fll%3D37.786793,-122.405211 You can try increasing the "radius" parameter to capture more trending venues nearby. Here is an example of your query with a higher radius, so it captures more venues: https://developer.foursquare.com/docs/explore#req=venues/trending%3Fll%3D37.755516,-122.44812%26radius%3D20000
{ "pile_set_name": "StackExchange" }
Q: Percorrer pagina HTML e procurar por links Não sei se o titulo ficou esclarecido mas gostaria de saber como percorrer o corpo de uma pagina html e identificar links por exceções...Digamos que quero apenas links que tenham https://site.com/imagens/ em sua url. A: Veja se este exemplo utilizando jQuery lhe atende. Obtém todos os links que tenham no endereço (href) a string "https://site.com/imagens/". Com o objeto dos links você pode fazer o que você precisar. No exemplo abaixo, coloquei para exibir em uma div. function ObterLinks() { var links = $('a[href*="https://site.com/imagens/"]'); //obtém todos os links que contenham o endereço. var divResultado = $('#divResultado'); for(var i = 0; i < links.length; i++) { divResultado.append('<p>' + links[i].href + '</p>'); } } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="links"> <a href="https://site.com/imagens/1.jpg"> Link 1 </a> <br> <a href="https://site.com/imagens/2.jpg"> Link 2 </a> <br> <a href="https://site.com/imagens/3.jpg"> Link 3 </a> <br> <a href="https://site.com/imagens/4.jpg"> Link 4 </a> </div> <br> <button onclick="ObterLinks()">Obter Links </button> <div id="divResultado"> </div>
{ "pile_set_name": "StackExchange" }
Q: How to delete only directories and leave files untouched I have hundreds of directories and files in one directory. What is the best way deleting only directories (no matter if the directories have anything in it or not, just delete them all) Currently I use ls -1 -d */, and record them in a file, and do sed, and then run it. It rather long way. I'm looking for better way deleting only directories A: To delete all directories and subdirectories and leave only files in the working directory, I have found this concise command works for me: rm -r */ It makes use of bash wildcard */ where star followed by slash will match only directories and subdirectories. A: find . -maxdepth 1 -mindepth 1 -type d then find . -maxdepth 1 -mindepth 1 -type d -exec rm -rf '{}' \; To add an explanation: find starts in the current directory due to . and stays within the current directory only with -maxdepth and -mindepth both set to 1. -type d tells find to only match on things that are directories. find also has an -exec flag that can pass its results to another function, in this case rm. the '{}' \; is the way these results are passed. See this answer for a more complete explanation of what {} and \; do A: First, run: find /path -d -type d to make sure the output looks sane, then: find /path -d -type d -exec rm -rf '{}' \; -type d looks only for directories, then -d makes sure to put child directories before the parent.
{ "pile_set_name": "StackExchange" }
Q: ive been getting stuck on getting this table to work can someone help me? I am a noob programmer, and have been getting stuck a lot lately. On this example i have the basics of the table, but dont know how to proceed. public void paintComponent (Graphics g) { super.paintComponent(g); double row; double add = 0.25; int y = 15; for(int i = 1; i <= 8; i++) { row = 10 + add; g.drawString( i + " " + row, 10, y +=15); } } I know its just gonna be a small add to the code, but i really dont know what. I have tried alot of things like using multiple for statements but that didnt work as well. This is what it looks like: This is what i want it to look like: A: This line, in for loop makes problem row = 10 + add;. In each loop iteration row will have value 10 + 0.25 = 10.25. Perhaps, this is how your method should look. public void paintComponent (Graphics g) { super.paintComponent(g); double row = 10; double add = 0.25; int y = 15; for(int i = 1; i <= 8; i++) { row = row + add; g.drawString( i + " " + row, 10, y +=15); } }
{ "pile_set_name": "StackExchange" }
Q: Exception when reading file image on server - ASP.NET i hope anyone help me in this problem .. i have simple aspx code to get image file from directory and make some proccesses on it as drawing somthing on it after that i save it on the same directory. really the code has worked well on local machine, but on server side the code fails and the exception appears. ( ArgumentException: Parameter is not valid ) please look at the code : DirectoryInfo[] dir = new DirectoryInfo[2]; dir[0] = new DirectoryInfo(Server.MapPath("Image/DB/Large/")); dir[1] = new DirectoryInfo(Server.MapPath("Image/DB/Thumb/")); System.Drawing.Image signature = System.Drawing.Image.FromFile(Server.MapPath("Image/Design/signature.png")); for (int i = 0; i < dir.Length; i++) { FileInfo[] fs = dir[i].GetFiles("*.jpg"); foreach (FileInfo s in fs) { FileStream strm = s.OpenRead(); String name = s.Name; System.Drawing.Image img = System.Drawing.Image.FromStream(strm); Graphics g = Graphics.FromImage(img); g.SmoothingMode = SmoothingMode.HighQuality; g.DrawImage(signature, new Point(0, 0)); strm.Close(); if (i == 0) { String v = Server.MapPath("Image/DB/Large/" + name); img.Save(v); } else if (i == 1) { String v = Server.MapPath("Image/DB/Slide/" + name); img.Save(v); } g.Dispose(); } } Exception Details : Parameter is not valid. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentException: Parameter is not valid. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [ArgumentException: Parameter is not valid.] System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData) +1062843 System.Drawing.Image.FromStream(Stream stream) +8 Developer.Button1_Click(Object sender, EventArgs e) +279 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565 A: You must convert your FileStream to Stream System.Drawing.Image.FromStream(..);// This method take Stream as argument and nor FileStream You can try with CopyTo, in order to convert. Link : http://msdn.microsoft.com/en-us/library/dd782932.aspx FileStream strm = s.OpenRead(); Stream stream = new Stream(); strm.CopyTo(stream); System.Drawing.Image.FromStream(stream); Before .Net 4, you can use this extension method public static class Ext { public static void CopyTo(this FileStream in, Stream out) { byte[] temp= new byte[16*1024]; //You can adjust this value int bytesRead; while ((bytesRead = in.Read(temp,0, temp.Length)) > 0) { out.Write(temp, 0, bytesRead); } } }
{ "pile_set_name": "StackExchange" }
Q: Update multiple rows in a table from another table when column values match I would like to update the columns of Table1 with the values from Table2 where postcode value from table1 matches table2. It must work with multiple rows as some rows have same postcode, latitude and longitute data but different door number. I am using the statement shown below. I am trying to update table1 with latitude and longitue data from table2 for matching postcode. update table1 set latitude = (select latitude from table2 where table1.postcode = table2.postcode); I am getting error message : Subquery returned more than 1 value. Table1 id Postcode Street City Latitude Longitude 1 N76PP 44 Camden Road London NULL NULL 2 N76PP 45 Camden Road London NULL NULL 3 N76PP 46 Camden Road London NULL NULL Table2 id Postcode Street City Latitude Longitude 1 N76PP 44 Camden Road London 51.5166 -0.052787 2 N76PP 45 Camden Road London 51.5166 -0.052787 3 N76PP 46 Camden Road London 51.5166 -0.052787 A: The subquery will return multiple records as per your query, you are trying to update one column with multiple records that cannot be done. In this case you can use JOIN. update t1 set t1.latitude = t2.latitude from table1 as t1 inner join table2 as t2 on t1.postcode = t2.postcode and t1.street = t2.street
{ "pile_set_name": "StackExchange" }
Q: Does a drainage pipe need to be continuously sloped? I need to move water from the back yard to the front yard, to combat the monsoon season, in which a 50 gallon container in the backyard can fill up in 1-2 minutes. I bought some 4" piping, and will have it collect water in a drain in the higher back yard, and divert it in a half-circle around the house to the lower front yard. I'm finding that due to the length of the pipes, about 150 feet, it is difficult to make it continuously downhill. There already is a slight slope of 1" per 10 feet horizontally. Is there any issue if the pipe is not perfectly sloped, and in places goes slightly higher than before, so long as all of the pipe is lower than the entry drain? A: It's true that, so long as the exit is lower than the entrance, water will find its way through the pipe even if there are low points in the path. However, as others have noted, debris could accumulate in those low points. So the answer to your specific questions "does it need to be continuously sloped" is a squishy "yes.. unless you're willing to install mitigations." One mitigation you could consider is one or more sump pits/traps/catch basins along the path. Here's a sketch from Dejana Industries: This construction is specifically designed to catch debris in storm water systems. That's not what you're after, so we can modify the design a bit. Run pipe with a continuous slope at a sufficiently steep grade so that debris will carry along well. When you reach a point that the pipe is getting too deep in the ground, install a catch basin there. Take an exit pipe out of the pit at a level higher than the inlet and proceed to the destination. During a storm water will fill the catch basin. Eventually the water level will rise high enough to flow out the exit pipe. Some debris will settle in the basin; other debris will float up and flow out the exit. Construct the basin to be leaky so that after the storm the water remaining in the basin slowly drains away. That'll minimize the chance of breeding mosquitos or odors. From time to time you'll have to clean out the debris from the bottom of the basin, but it's better to have it there than in some unknown and inaccessible section of pipe buried in the yard! A: If you are in a climate where the water can freeze it is a definite problem. If not, there is still the potential for debris and sediment to settle in the low sections and eventually clog the pipe. A: Your fix is to make like a Roman Aqueduct and support the lower "dips" so that the pipe runs at a more-consistent downward angle. This will also make the water flow faster, flushing possible sediments without a chance to block up. Aim for a straight run of pipe with the same drop over distance, rather than a specific angle. Start by supporting the pipe with wood or stone and once its well-aligned, consider more permanent solutions like concrete.
{ "pile_set_name": "StackExchange" }
Q: why doesn't this ERB standalone rendering work for the instance variable why doesn't this ERB standalone rendering work for the instance variable? That is the output is blank for the "<%= @test_var %>" line? @test_var = "test variable" template = Tilt.new('./app/scripts/email.erb') st = template.render puts st and email.erb <html> <body> <h1>This is it!</h1> <p> Phone Number: <%= @test_var %> </p> </body> </html> gives <html> <body> <h1>This is it!</h1> <p> Phone Number: </p> </body> </html> A: found the answer...need to have (a) the following in my class where the instance variables are: # Support templating of member data. def get_binding binding end (b) also when calling "run" on the ERB object have to pass the result from this method, e.g. rhtml = ERB.new(erb_str) html = rhtml.run(get_binding)
{ "pile_set_name": "StackExchange" }
Q: Converting binary string to text in R (salesforce ID conversion 15 to 18) Looking to create a conversion of a 15 digit salesforce ID to 18 digit in R. The formula is written out here: https://salesforce.stackexchange.com/questions/27686/how-can-i-convert-a-15-char-id-value-into-an-18-char-id-value but that is in C#, and I'd like to do this in R. I've made a clunky formula with as much as I know in R which does work for a 15 digit input and returns the 18 digit one successfully. I would like to know how to then apply this to a column in a data.frame via dplyr. reproducible code: SFID_Convert <- function(fifteen_digit) { if (length(fifteen_digit == 15)) { # binary map ---- binary <- c( "00000", "00001", "00010", "00011", "00100", "00101", "00110", "00111", "01000", "01001", "01010", "01011", "01100", "01101", "01110", "01111", "10000", "10001", "10010", "10011", "10100", "10101", "10110", "10111", "11000", "11001", "11010", "11011", "11100", "11101", "11110", "11111" ) letter <- c(LETTERS, 0:5) binarymap <- data_frame(binary, letter) # sfid ---- sfid <- substr(fifteen_digit, 1, 15) s1 <- substr(sfid, 1, 5) s2 <- substr(sfid, 6, 10) s3 <- substr(sfid, 11, 15) convertID <- function(str_frag) { str_frag <- paste(rev(strsplit(str_frag, NULL)[[1]]), collapse = '') str_frag <- strsplit(str_frag, NULL)[[1]] str_frag[which(unlist(gregexpr("[0-9]", str_frag)) == 1)] <- 0 str_frag[which(unlist(gregexpr("[a-z]", str_frag)) == 1)] <- 0 str_frag[which(unlist(gregexpr("[A-Z]", str_frag)) == 1)] <- 1 str_frag <<- paste(str_frag, collapse = '') } convertID(s1) n1 <- str_frag convertID(s2) n2 <- str_frag convertID(s3) n3 <- str_frag binary <- data_frame(c(n1, n2, n3)) %>% select(binary = 1) %>% left_join(binarymap) return(paste(sfid, paste(binary$letter[1:3], collapse = ''), sep = ''))} } example: sfid <- "001a003920aSDuh" SFID_Convert(sfid) [1] "001a003920aSDuhAAG" which is what I want, but when you apply it to a df... col <- c("001a003920aSDuh", "001a08h010JNkJd") name <- c("compA", "compB") df <- data_frame(name, col) It takes the "AAG" that it correctly computed for the first one, and applies it to every row. I could lapply it across, but if I have a df of 100,000 rows, it would be the wrong way to do it I think. Any help is appreciated! still learning here. :) A: There are various issues with your code. I've included a possible solution below, which should be more efficient: 1: Defining the map between binary string & letters. You can do this outside your function. Just define it once, with all the transformations necessary, & use it in the function. binary <- c("00000","00001","00010","00011","00100","00101","00110","00111", "01000","01001","01010","01011","01100","01101","01110","01111", "10000","10001","10010","10011","10100","10101","10110","10111", "11000","11001","11010","11011","11100","11101","11110","11111") binary.reverse <- lapply(binary, function(x){paste0(rev(strsplit(x, split = "")[[1]]), collapse = "")}) binary2letter <- c(LETTERS, 0:5) names(binary2letter) <- unlist(binary.reverse) rm(binary, binary.reverse) I reversed the binary strings in this step as well, so that I don't have to do it repeatedly for all the IDs. The results are saved in a named vector rather than a data frame. 2: Creating the function in a way that accepts vectors as input. Note that to check whether a string has X characters, you should use nchar() rather than length(). The latter returns the number of strings, not the number of characters in a string. SFID_Convert <- function(sfid) { sfid <- as.character(sfid) # in case the input column are factors str_num <- gsub("[A-Z]", "1", gsub("[a-z0-9]", "0", sfid)) s1 <- substring(str_num, 1, 5) s2 <- substring(str_num, 6, 10) s3 <- substring(str_num, 11, 15) sfid.addon <- paste0(sfid, binary2letter[s1], binary2letter[s2], binary2letter[s3]) sfid[nchar(sfid)==15] <- sfid.addon[nchar(sfid)==15] return(sfid) } Check the solution: sfid <- "001a003920aSDuh" col <- c("001a003920aSDuh", "001a08h010JNkJd") name <- c("compA", "compB") df <- data_frame(name, col) > SFID_Convert(sfid) [1] "001a003920aSDuhAAG" > df %>% mutate(new.col = SFID_Convert(col)) # A tibble: 2 x 3 name col new.col <chr> <chr> <chr> 1 compA 001a003920aSDuh 001a003920aSDuhAAG 2 compB 001a08h010JNkJd 001a08h010JNkJdAAL
{ "pile_set_name": "StackExchange" }
Q: How to find and replace image inside using jquery? I am trying to check the image and replace the image for my expand and collapse <div> but i cant able to find the solution. html code: <h4 id="expanderHead">Virtual Room <span id="expanderSign">+</span></h4> <div id="expanderContent" style="display:none"> content ... content... </div> jquery: $(document).ready(function(){ $("#expanderHead").click(function(){ $("#expanderContent").slideToggle(); if ($("#expanderSign").text() == "+"){ $("#expanderSign").html("-") } else { $("#expanderSign").text("+") } }); }); Here, instead of + and - i have to place <img src="" alt=""/> . Thank you. A: HTML <h4 id="expanderHead">Virtual Room <span id="expanderSign"><img src="plus-sign.png" /></span></h4> <div id="expanderContent" style="display:none"> content ... content... </div>​ EDITED (Added better jQuery Version) jQuery New Version $(document).ready(function(){ $("#expanderHead").click(function(){ $("#expanderContent").slideToggle(); var plusImg = "http://cdn2.iconfinder.com/data/icons/diagona/icon/16/129.png"; var minusImg = "http://cdn2.iconfinder.com/data/icons/diagona/icon/16/130.png"; $this = $("#expanderSign img"); if( $this.attr('src') == plusImg ) { $this.attr('src', minusImg);} else { $this.attr('src', plusImg); } }); }); SEE LIVE DEMO
{ "pile_set_name": "StackExchange" }
Q: Cleanup of the "version" tags Currently there are a multitude of tags for questions about alternative movie versions. First of all, the tags versions and alternate-version, which have largely the same tag descriptions and usages (some questions even use both tags). Then there are the less frequently used movie-edition and directors-cut (which is more specialized, but could easily be covered by a broader tag). Since the current situation is overly confusing, how to proceed with those tags? EDIT: Since the appraoch proposed in NapoleonWilson's answer has been unanimously accepted by the community, I'd hereby ask the moderators to make directors-cut, versions and movie-edition synonyms of alternate-version and tag this question as status-completed when done. A: Since versions, alternate-version and movie-edition seem to cover the same topics, I'd propose to merge them into a single tag. Though I'm yet unsure what to call that tag. versions seems a bit too generic (yet, it's Movies & TV, so what else could it mean than a movie or TV show version?), so maybe alternate-version might be a better choice. Likewise I'm not sure if to make the other two synonyms of the new tag or delete them completely. The latter would be cleaner but would result in mass edits (though, there aren't too many questions yet anyway). Then the question remains what to do with directors-cut. It covers a more specific case of alternate version. But then again it's covered equally well by the broader tag and it being too specific isn't a good idea either, since this opens the question if there should also be tags for "Special Editions", "Remastered Versions" or "Special Fan-Approved De-Remastered Non-Director's Cuts". I would thus propose directors-cut to be a synonym of the new single version tag (here a synonym is more appropriate than deleting, since Director's Cut is a common term likely to come up again as a tag).
{ "pile_set_name": "StackExchange" }
Q: Higher dimensional large sieve inequality One of the most important achievements in analytic number theory is the establishment of the so-called large sieve inequality, which is formulated as follows. Let $\{a_n\}$ denote a finite sequence of complex numbers, say supported on the segment $M \leq n < M + N$. For a real number $\alpha$ put $$\displaystyle S(\alpha) = \sum_n a_n e(\alpha n),$$ where $e(x) = \exp(2\pi i x)$. Let $\alpha_1, \cdots, \alpha_r$ be real numbers such that $\lVert \alpha_i - \alpha_j \rVert \geq \delta > 0$ for $i \ne j$. Here $\lVert x \rVert$ of a real number $x$ denotes the distance of $x$ to the nearest integer. The large sieve inequality (of Selberg and Montgomery-Vaughan, independently) then asserts that for any finite sequence of complex numbers $\{a_n\}$ supported on $N$ integers we have $$\displaystyle \sum_j |S(\alpha_j)|^2 \leq (\delta^{-1} + N - 1) \sum_n |a_n|^2$$ and that this inequality is best possible in general. One can formulate a higher dimensional analogue of this. Let $\mathbf{a} = (a_1, \cdots, a_n)$ be a vector of real numbers, and let $G_{\mathbf{v}}$ be complex numbers supported on the box $B = \{\mathbf{v} \in \mathbb{Z}^n : M \leq v_i < M + N\}$. Put $$\displaystyle S(\mathbf{a}) = \sum_{\mathbf{v} \in B} G_{\mathbf{v}} \exp(2 \pi i \mathbf{a} \cdot \mathbf{v}).$$ Suppose that $\mathbf{a}_1, \cdots, \mathbf{a}_r$ are vectors which are pairwise separated by $\delta$ modulo 1. Is there a general formula for good functions $F_n(\delta, N)$ for which the inequality $$\displaystyle \sum_j |S(\mathbf{a}_j)|^2 \leq F_n(\delta, N) \sum_{\mathbf{v} \in B} |G_{\mathbf{v}}|^2?$$ For instance, we can take $F_1(\delta, N) = \delta^{-1} + N - 1$. A: There is a paper of Huxley from 1968 (http://www.ams.org/mathscinet-getitem?mr=237455) that answers this. If I am translating the notation correctly, Huxley shows that $$F_n(\delta, N) = (N^{1/2} + \delta^{-1/2})^{2n}$$ is allowable. More generally, if one restricts to $M_i \leq v_i < M_i + N_i$ and assumes that the $i$-th component of ${\bf a}_k - {\bf a}_{\ell}$ is spaced by at least $\delta_i$ (modulo $1$, $k \neq \ell$), then one can replace $F_n(\delta, N)$ by $$\prod_{i=1}^{n} (N_i^{1/2} + \delta_i^{-1/2})^2.$$
{ "pile_set_name": "StackExchange" }
Q: The Commutator Subgroup is Normal. This is part of Exercise 2.7.9 of F. M. Goodman's "Algebra: Abstract and Concrete". Definition 1: The commutator subgroup $C$ of a group $G$ is the subgroup generated by all elements of the form $xyx^{-1}y^{-1}$ for $x, y\in G$. The Question: Show that the commutator subgroup $C$ of a group $G$ is normal and that $G/C$ is abelian. My Attempt: Let $g\in G$. Then $g(xyx^{-1}y^{-1})g^{-1}=gxy(gyx)^{-1}$, but I don't know where to go from here. What I'm trying to do is write $g(xyx^{-1}y^{-1})g^{-1}$ as an element of $C$. Please help :) A: We have $(gxg^{-1})^{-1}=gx^{-1}g^{-1}$ and similarly for $gyg^{-1}$, so that $$\begin{align} g(x yx^{-1}y^{-1})g^{-1}&=gx\cdot (g^{-1}g)\cdot y\cdot (g^{-1}g)\cdot x^{-1}\cdot (g^{-1}g)\cdot y^{-1}g^{-1} \\ &=\underbrace{gxg^{-1}} \underbrace{gyg^{-1}}\underbrace{gx^{-1}g^{-1}}\underbrace{gy^{-1}g^{-1}} \\ &=(gxg^{-1})(gyg^{-1})(gxg^{-1})^{-1}(gyg^{-1})^{-1} \end{align}$$ is an element of $C$, so $C$ is normal.
{ "pile_set_name": "StackExchange" }
Q: How to get String.Format not to parse {0} I am writing a code generation tool that frequently will have lines like StringBuilder sp = new Stringbuilder(); sp.AppendFormat(" public {0}TextColumn()\n", className); sp.AppendLine(" {" sp.AppendLine(" Column = new DataGridViewTextBoxColumn();"); sp.AppendFormat(" Column.DataPropertyName = \"{0}\";\n", columnName); However the issue I am having is when I run in to a line like this. sp.AppendFormat("return String.Format(\"{0} = '{0}'\", cmbList.SelectedValue);", columnName); I want the first {0} to turn in to whatever the value of columnName is but I want the seccond {0} to be left alone so the internal String.Format will process it correctly. How do I do this? A: Use double curly braces: string result = string.Format("{{Ignored}} {{123}} {0}", 543); A: Curly braces can be escaped by using two curly brace characters. The documentation of string.Format states: To specify a single literal brace character in format, specify two leading or trailing brace characters; that is, "{{" or "}}". In your example that would be sp.AppendFormat("return String.Format(\"{0} = '{{0}}'\",cmbList.SelectedValue);", columnName); A: sp.AppendFormat("return String.Format(\"{0} = '{{0}}'\", cmbList.SelectedValue);", columnName);
{ "pile_set_name": "StackExchange" }
Q: Can you create a Python list from a string, while keeping characters in specific keywords together? I want to create a list from the characters in a string, but keep specific keywords together. For example: keywords: car, bus INPUT: "xyzcarbusabccar" OUTPUT: ["x", "y", "z", "car", "bus", "a", "b", "c", "car"] A: With re.findall. Alternate between your keywords first. >>> import re >>> s = "xyzcarbusabccar" >>> re.findall('car|bus|[a-z]', s) ['x', 'y', 'z', 'car', 'bus', 'a', 'b', 'c', 'car'] In case you have overlapping keywords, note that this solution will find the first one you encounter: >>> s = 'abcaratab' >>> re.findall('car|rat|[a-z]', s) ['a', 'b', 'car', 'a', 't', 'a', 'b'] You can make the solution more general by substituting the [a-z] part with whatever you like, \w for example, or a simple . to match any character. Short explanation why this works and why the regex '[a-z]|car|bus' would not work: The regular expression engine tries the alternating options from left to right and is "eager" to return a match. That means it considers the whole alternation to match as soon as one of the options has been fully matched. At this point, it will not try any of the remaining options but stop processing and report a match immediately. With '[a-z]|car|bus', the engine will report a match when it sees any character in the character class [a-z] and never go on to check if 'car' or 'bus' could also be matched. A: s = "xyzcarbusabccar" import re print re.findall("bus|car|\w", s) ['x', 'y', 'z', 'car', 'bus', 'a', 'b', 'c', 'car'] Or maybe \S for any non whitespace chars: s = "xyzcarbusabccar!" import re print re.findall("bus|car|\S", s) ['x', 'y', 'z', 'car', 'bus', 'a', 'b', 'c', 'car', '!'] Just make sure you get the order correct putting longer words first if you want the longest matches. In [7]: s = "xyzcarsbusabccar!" In [8]: re.findall("bus|car|cars|\S", s) Out[8]: ['x', 'y', 'z', 'car', 's', 'bus', 'a', 'b', 'c', 'car', '!'] In [9]: re.findall("bus|cars|car|\S", s) Out[9]: ['x', 'y', 'z', 'cars', 'bus', 'a', 'b', 'c', 'car', '!']
{ "pile_set_name": "StackExchange" }
Q: Texture coordinates for a 3D box I have a box model in my DirectX application, stored as 8 vertices: MyVertex vertices[] = { { DirectX::XMFLOAT3( - 1.0f, + 1.0f, - 1.0f ), /*,tex coord...*/}, //0 { DirectX::XMFLOAT3( + 1.0f, + 1.0f, - 1.0f ), /*,tex coord...*/}, //1 { DirectX::XMFLOAT3( + 1.0f, + 1.0f, + 1.0f ), /*,tex coord...*/}, //2 { DirectX::XMFLOAT3( - 1.0f, + 1.0f, + 1.0f ), /*,tex coord...*/}, //3 { DirectX::XMFLOAT3( - 1.0f, - 1.0f, - 1.0f ), /*,tex coord...*/}, //4 { DirectX::XMFLOAT3( + 1.0f, - 1.0f, - 1.0f ), /*,tex coord...*/}, //5 { DirectX::XMFLOAT3( + 1.0f, - 1.0f, + 1.0f ), /*,tex coord...*/}, //6 { DirectX::XMFLOAT3( - 1.0f, - 1.0f, + 1.0f ), /*,tex coord...*/}, //7 }; And for the index buffer I use: WORD indices[] = { 3,1,0,2,1,3, //top 0,5,4,1,5,0, 3,4,7,0,4,3, 1,6,5,2,6,1, 2,7,6,3,7,2, 6,4,5,7,4,6, }; It works just fine, but now I want to add a texture to the faces of my box. Which would be the best approach? The options I see: Use 24 instead of 8 vertices -- four for each of the box's six faces. Some of these will have the same position/normals, but different texture coordinates. Use 8 vertices and texture coordinates like here: MAYBE there is a way to provide different sets of texture coordinates for a single vertex, so I can provide different texture coordinates on different faces of the box? If so, how can I do that? The disadvantages (for the options with the same numbers): 16 additional vertices (3 as many), all the benefits of using a index buffer to have less vertices are wasted - maybe this means I shouldn't use an index buffer at all, under this approach? Texture with odd proportion (2:3), texture must be six times the size for the same resolution. None? In option 2. I can use one texture to create different images on each box's face, but I'm not interested in that benefit. Additional question (!!!): How is this done in 3d software and mesh formats? When I create a box in 3ds Max, create a material with a texture and apply it to the box, each side of box has the same texture (like option #1), with good texture coordinates (impossible to achieve with 8 vertices and a single square texture?), and the statistics says "8 VERTEXES". How is it possible? Did they achieve option #3? A: A vertex is not just a spatial position, but a whole bag of attributes. A position p is a point in some spatial space or a homogeneous coordinate. A texcoord tc is a point in texture space. A normal n is a bivector, and so on. If you represented a vertex with multiple indices, a vertex V_k could be represented by a tuple of indices {p_a, tc_b, n_c}. In a single-indexed environment like Direct3D or OpenGL, you can only have one index. This means that your index values will be {p_i, tc_i, n_i}, or in short, i. If you've got multi-indexed geometry like in the former case, the way you can make it single-indexed is to for each unique tuple of indices, generate a new set of vertex attribute data with the same single-indexed index. If you've seen the tuple before, reuse the index; otherwise generate a new vertex. If you have ever loaded the Wavefront OBJ file format, this will be painfully familiar to you as OBJ stores separate streams for each attribute and uses multi-indexed tuples like outlined above. Other file formats use other approaches like pre-baked deduplicated single-indexed attribute streams, or completely non-indexed attribute streams, which is equivalent to deduplication without actual deduplication, just repeating the data for each vertex in each face.
{ "pile_set_name": "StackExchange" }
Q: Excel Formula to Match Items Within a Date Range I'm trying to match a product sale date with the range date of sales. I have the following so far: =INDEX(A3,MATCH(1,((H:H=A3)*(B:B>=I3)*(B:B<=J3)),0)) I'm trying to have the formula produce a result if column A matches column H and if column B is between column I & J, where J may not have occurred yet. EDIT: column E15 isn't returning any results See Here A: Use this array formula: =IF(SUM(($H$3:$H$12=$A3)*($I$3:$I$12<=B3)*(IF($J$3:$J$12<>"",$J$3:$J$12,TODAY()+1)>$B3)),$A$3,"") Being an array formula it must be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.
{ "pile_set_name": "StackExchange" }
Q: What is lim sup (x/n)? can you please tell me what $$\lim_{n \to \infty} \sup_{x \in D} \frac{x}{n},$$ with $D = (0, \infty)$ is? I'm pretty sure the supremum doesn't exist, but I'm not sure. Thanks in advance! :) A: For each $n$, we have $\sup_{x\in(0,D)}\frac xn = +\infty$, hence $\lim_{n\to\infty}\sup_{x\in(0,D)}\frac xn = +\infty$ (if one calls a supremum/limit with infinite value existent).
{ "pile_set_name": "StackExchange" }
Q: Member not declared in scope? So I'm trying my hand at some C++ after finishing up an introductory book, and I've become stuck. I've made a vector of objects that each have an SFML circle object as a member, and I want main() to go and draw these circles. The vector is called theBoard, but when I try to access it, I get the following error messages: error: request for member 'theBoard' in 'GameBoard', which is of non-class type 'Board*' error: 'theBoard' was not declared in this scope I'm new to this (came from two years of Python), so I'm sure I made a mistake somewhere. Here is the relevant code for the board creation: class Board { public: //These are the member functions. Board(); ~Board(); vector<Space*> CreateBoard(); //This will be the game board. vector<Space*> theBoard; //These clusters represent the waiting areas for pieces not yet in the game. vector<Space*> Cluster1; vector<Space*> Cluster2; vector<Space*> Cluster3; private: //These integers represent the number of spaces on each row, starting at the top (which is row [0]) vector<int> RowNums; }; Board::Board() { //Fill in RowNums with the right values. RowNums.push_back(1); RowNums.push_back(17); RowNums.push_back(2); RowNums.push_back(17); RowNums.push_back(1); RowNums.push_back(1); RowNums.push_back(5); RowNums.push_back(2); RowNums.push_back(7); RowNums.push_back(2); RowNums.push_back(11); RowNums.push_back(3); RowNums.push_back(17); RowNums.push_back(4); RowNums.push_back(17); //Then, create the board. theBoard = CreateBoard(); } CreateBoard() is a very, very long function that returns a vector of pointers to Space objects. I doubt there's a problem here, as the only error message I get crops up when I try to access the circle members of Space objects in main(). It seems to me as though I have declared theBoard in the relevant scope, that is, as a data member of the Board class. My main() function, in case it's important: int main() { //This sets up the display window. sf::RenderWindow App(sf::VideoMode(1200, 900, 32), "Malefiz"); //This creates the board on the heap, and a pointer to it. Board* GameBoard = new Board(); cout << "Board made."; //This is the game loop. while(App.IsOpened()) { //This is used to poll events. sf::Event Event; while(App.GetEvent(Event)) { //This closes the window. if(Event.Type == sf::Event::Closed) { App.Close(); } } //This gets the time since the last frame. //float ElapsedTime = App.GetFrameTime(); //This fills the window with black. App.Clear(sf::Color(200, 200, 125)); //This draws the places into the window. for(int i = 0; i < GameBoard.theBoard.size(); ++i) { App.Draw(GameBoard.*theBoard[i].m_Circle); } //This displays the window. App.Display(); } return EXIT_SUCCESS; } A: In your main() function, GameBoard is a Board *, not a Board. So to access members, you need to use -> instead of .. e.g.: GameBoard->theBoard.size() [Some people (I am one of them) like to name their pointer variables with a leading p or ptr prefix, in order to make this kind of irritation explicitly clear.] A: GameBoard is a pointer to a Board object, and thus you need to use the "->" operator instead of the "." operator to access any of its member variables or methods. A: GameBoard is a pointer, so the syntax should be this: for(int i = 0; i < GameBoard->theBoard.size(); ++i) { App.Draw((GameBoard->theBoard[i])->m_Circle); } Since elements of theBoard also are pointer, so I used the pointer notation when accessing m_Circle.
{ "pile_set_name": "StackExchange" }
Q: Purpose of FXSAPIDebugLogFile.txt in Windows 7 temp folder? Many Windows 7 systems have the file FXSAPIDebugLogFile.txt in a temp folder. The file cannot easily be deleted while Windows is running. When trying to delete the file using standard procedures, Windows claims the file is "open in Windows Explorer". This is interesting because when trying to delete FXSTIFFDebugLogFile.txt in the same temp folders, Windows indicates that file is open by a different process: "print driver host". Researching the purpose of FXSAPIDebugLogFile.txt yields conflicting and incomplete information. What process is actually creating this file, and what are the consequences of disabling that process? Every time I have seen a system with that file, it is zero bytes. Does it ever contain data? If so, what data? This question involves better understanding the system; leaving the file alone is typical. A: It would appear to be a debug log file for Windows Fax Print services. If you do not fax or print the file will stay empty other than that it does absolutely nothing. Network administrators usually get rid of the file. Or atleast I do. You can remove it however by just disabling the Print and Document Services in the windows feature panel.
{ "pile_set_name": "StackExchange" }
Q: Regex, add an attribute to a tag in html (php) I can't quite figure it out, I'm looking for some regex that will add an atttribute to a html tag. For example lets say I have a string with an <a> in it, and that <a> needs an attribute added to it, so <a> get's added style="xxxx:yyyy;" . How would you go about doing this? Ideally it would add any attribute to any tag. Am I asking to much of php + regex, should I be building a class to do this sort of thing instead? Cheers! A: It's been said a million times. Don't use regex's for HTML parsing. $dom = new DOMDocument(); @$dom->loadHTML($html); $x = new DOMXPath($dom); foreach($x->query("//a") as $node) { $node->setAttribute("style","xxxx"); } $newHtml = $dom->saveHtml() A: Here is using regex: $result = preg_replace('/(<a\b[^><]*)>/i', '$1 style="xxxx:yyyy;">', $str); but Regex cannot parse malformed HTML documents.
{ "pile_set_name": "StackExchange" }
Q: How to bring focused field into the view using iscroll and Android WebView When I focus into a form field at the bottom of iScroll view, it does not scroll up/bring the focused field above the softkeyboad. Any idea? Thank you! This is the Android project. https://dl.dropboxusercontent.com/u/75818136/webkitdemo.zip <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0"> <title>iScroll demo: simple</title> <style type="text/css" media="all"> body,ul,li { padding:0; margin:0; border:0; } body { font-size:12px; -webkit-user-select:none; -webkit-text-size-adjust:none; font-family:helvetica; } #header { position:absolute; z-index:2; top:0; left:0; width:100%; height:45px; line-height:45px; background-color:#d51875; background-image:-webkit-gradient(linear, 0 0, 0 100%, color-stop(0, #fe96c9), color-stop(0.05, #d51875), color-stop(1, #7b0a2e)); background-image:-moz-linear-gradient(top, #fe96c9, #d51875 5%, #7b0a2e); background-image:-o-linear-gradient(top, #fe96c9, #d51875 5%, #7b0a2e); padding:0; color:#eee; font-size:20px; text-align:center; } #header a { color:#f3f3f3; text-decoration:none; font-weight:bold; text-shadow:0 -1px 0 rgba(0,0,0,0.5); } #footer { position:absolute; z-index:2; bottom:0; left:0; width:100%; height:48px; background-color:#222; background-image:-webkit-gradient(linear, 0 0, 0 100%, color-stop(0, #999), color-stop(0.02, #666), color-stop(1, #222)); background-image:-moz-linear-gradient(top, #999, #666 2%, #222); background-image:-o-linear-gradient(top, #999, #666 2%, #222); padding:0; border-top:1px solid #444; } #wrapper { position:absolute; z-index:1; top:45px; bottom:48px; left:0; width:100%; background:#aaa; overflow:auto; } #scroller { position:absolute; z-index:1; /* -webkit-touch-callout:none;*/ -webkit-tap-highlight-color:rgba(0,0,0,0); width:100%; padding:0; } #scroller ul { list-style:none; padding:0; margin:0; width:100%; text-align:left; } #scroller li { padding:0 10px; height:40px; line-height:40px; border-bottom:1px solid #ccc; border-top:1px solid #fff; background-color:#fafafa; font-size:14px; } </style> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="iscroll.js"></script> </head> <body> <div id="header"><a href="http://cubiq.org/iscroll">iScroll</a></div> <div id="wrapper"> <div id="scroller"> <ul id="thelist"> <li>Pretty row 1</li> <li>Pretty row 2</li> <li>Pretty row 3</li> <li>Pretty row 4</li> <li>Pretty row 5</li> <li>Pretty row 6</li> <li>Pretty row 7</li> <li>Pretty row 8</li> <li>Pretty row 9</li> <li>Pretty row 10</li> <li>Pretty row 11</li> <li>Pretty row 12</li> <li>Pretty row 13</li> <li>Pretty row 14</li> <li>Pretty row 15</li> <li>Pretty row 16</li> <li>Pretty row 17</li> <li>Pretty row 18</li> <li>Pretty row 19</li> <li>Pretty row 20</li> <li>Pretty row 21</li> <li>Pretty row 22</li> <li>Pretty row 23</li> <li>Pretty row 24</li> <li>Pretty row 25</li> <li>Pretty row 26</li> <li>Pretty row 27</li> <li>Pretty row 28</li> <li>Pretty row 29</li> <li>Pretty row 30</li> <li>Pretty row 31</li> <li>Pretty row 32</li> <li>Pretty row 33</li> <li>Pretty row 34</li> <li>Pretty row 35</li> <li>Pretty row 36</li> <li>Pretty row 37</li> <li>Pretty row 38</li> <li>Pretty row 39</li> <li><form><input type="text" value="hey" spellcheck="false"></form></li> </ul> </div> </div> <div id="footer"></div> <script> var myScroll; function loaded() { myScroll = new iScroll('wrapper'); } document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false); document.addEventListener('DOMContentLoaded', function () { setTimeout(loaded, 200); }, false); window.addEventListener("resize", function() { console.error("=------======-=-=-=="); }, false); </script> </body> </html> A: I finally found the solution to my question. BTW, this solution will be in my book which will be published soon. I just wanted to share this with the developer community. First of all, iscroll should handle this matter for us, but somehow it does not. Also, I think there is a bug in Android API. When I use full-screen mode (in manifest or programmatically), the "resize" event does not get fired in the WebView. No idea why. I already reported this bug to Android team. If you know why this happens, please let us know here. Thanks. android:theme="@android:style/Theme.NoTitleBar.Fullscreen" // or getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); Here is the solution: I removed the full-screen mode. Instead, I used res/values/style.xml, requestWindowFeature(android.view.Window.FEATURE_NO_TITLE); and android:theme="@style/Theme" in the application in order to remove the application native title. This solution also works when orientation occurs. Then, using "focus" event, I captured which element has a focus. var $elm; $('input, textarea').bind('focus', function(e) { console.error("onFocus"); $elm = $(this); }); Then, using "resize" event, I refreshed the iscroll object and then scroll to the $elm. $(window).bind('resize', function() { console.error("onResize"); if (myScroll !== undefined) { setTimeout(function() { myScroll.refresh(); myScroll.scrollToElement($elm[0], 200); }, 100); } }); This is the answer to my question, WebKitDemo2.zip
{ "pile_set_name": "StackExchange" }
Q: toggleClass is not working as expected : function is calling twice ToggleClass is not giving expected result because the function is executing twice. HTML: <form method="get" class="custom-controls"> <label><input name="Gorilla" type="checkbox"/>Gorilla</label><br/> <label><input name="Lamb" type="checkbox"/>Lamb</label><br/> <label><input name="Tiger" type="checkbox"/>Tiger</label><br/> <input type="submit"> </form> jQuery: $(document).ready(function(){ $('.custom-controls').find('input').each(function(){ ($(this).is(':radio')?$input_class_name="custom-radio-wrap":$input_class_name="custom-check-wrap"); $(this).parents('label').wrapInner(('<span class="' + $input_class_name + '"></span>')); }); $('.custom-controls').delegate("span", "click", function () { $(this).toggleClass('checked'); }); }); FIDDLE REFERENCE A: This is caused by event bubbling, just add a return false after it. $('.custom-controls').delegate("span", "click", function () { $(this).toggleClass('checked'); return false; }); OR $('.custom-controls').delegate("span", "click", function (e) { $(this).toggleClass('checked'); e.preventDefault(); });
{ "pile_set_name": "StackExchange" }
Q: Sur meRah Mission What does Sur meRah mean (sources please) in the context of Al Berko's answer to Why did Ya'akov enslave himself for so long?? I think it might mean to turn away from evil, but then there would be no "h" at the end. Also, then why would Yaakov need to go looking for the Lavan in "Chutz Laaretz, the land of idolatry"? Shouldn't he be avoiding him? A: The Shem MiShmuel (Parashat Vayetse) writes that Yaakov was originally meant to serve God through the mode of assei tov, and Esav was supposed to serve God through the mode of sur mera: עקב ועשו ועל דעת כך נבראו. יעקב יזכה לשלימותו ע"י עשה טוב, וכך הי' ממלא תעודתו איש תם יושב אוהלים. ועשו נברא עם תכונות רעות שהי' מושכין אותו לכל רע, והכוונה היתה שיתאמץ בכח על טבעו ויברח מן הרע ועי"ז יבוא לעומתו למדריגות גדולות מאד Rivka realised that Esav wasn't fulfilling this mission, so she arranged for Yaakov to receive his blessing which transferred the mission serving God through sur mera. Accordingly, after the blessings, Ya'akov faced many hardships which challenged his behaviour, rather than his easier earlier life which allowed hom to more easily pursue good: ועשו הי' נמשך אחר תכונותיו הרעות עד שנעשה רשע גמור אדם בליעל. ורבקה הרגישה זה והשתדלה שגם בחי' סור מרע תמסר ליעקב ויזכה יעקב בשתיהן. וע"כ עד אז הי' יעקב יושב בשלוה ולא היו לו שום מניעות ורדיפות שיצטרך להתאמץ עליהן ולברוח מהן, ומן אז והלאה התחיל אצלו פרק חדש שהיו לו כל ימיו מניעות ורדיפות רעות רבות וצרו (ibid).
{ "pile_set_name": "StackExchange" }
Q: What are the most commonly understood signs/icons for chat interactions? I'm designing an in-app chat feature where users get can live support from chat agents. What are the most commonly understood signs/icons for chat receipts like sending sent not sent delivered not delivered read I see WhatsApp uses ticks and double ticks changing the colour when read, while facebook messenger users something slightly different. What would be more common practices to follow when designing for this without overcomplicating things, and are all these receipts even needed? A: As you pointed out there are different icons used in different apps. This makes is difficult to pinpoint a universally understood standard. I remember Jakob Nielsen saying "Users spent most of their time on other websites". With this in mind, here is what I would do: Identify the target user group for the app you are designing for and Understand which messenger/chat tool they are most likely accustomed to, then Design icons very similar to the ones of the most popular messenger for the target group Example: By number of users, WhatsApp appears to be the most used messenger globally [data]. But if your target group would be primarily based in China, then they most likely use WeChat a lot. In this case you could use WeChat to inspire your icon designs. Those designs could be tested with real users to check if they understand the interactions, supported by the icons. You could also consider text only as an alternative to icons, or icons in conjunction with a text label.
{ "pile_set_name": "StackExchange" }
Q: Add buttons to push notification alert Is there a way to set up how users see the push notifications alert box? My notifications are appearing without the view / cancel buttons, but i'm receiving others from different apps with those buttons. Is that a setting i should set before sending the push notification? Thanks! A: There are two things going on in your question. First, you will see no buttons at all when you receive Apple Push Notification alerts and your screen is locked. All Apps will have just the Title and the Message of the Alert, without the buttons. If your phone is unlocked, you will see the buttons. Second, altering the Payload, you can customize the "View" button text (or remove it) Apple Push Documentation with the "action-loc-key" key. If you set it to null, only "OK" will be presented. If you specify a value, it must be a localized string in your Application and the "View" will be replaced with that value.
{ "pile_set_name": "StackExchange" }
Q: 'active' is not a member of 'UnityEngine.Transform' Anyone know why i am getting that error, i got this error when i upgrade my project to newest version of unity3d. #pragma strict @script ExecuteInEditMode function Start () { } var bool : boolean = false; var ts1 : Transform[]; function Update () { if(bool){ bool = false; var ts = new Array(); for(var trans : Transform in transform){ if(!trans.active){ ts.Add(trans); } } ts1 = new Array(ts.Count); for(var i=0; i<ts.length; i++){ ts1[i] = ts[i]; } } } Tell me which part of the code is wrong? A: Currently this property not exist. Instead of transform.active you need to use gameobject.activeself to check the active status. #pragma strict @script ExecuteInEditMode function Start () { } var bool : boolean = false; var ts1 : Transform[]; function Update () { if(bool){ bool = false; var ts = new Array(); for(var trans : Transform in transform){ if(!trans.gameObject.activeSelf){ ts.Add(trans); } } ts1 = new Array(ts.Count); for(var i=0; i<ts.length; i++){ ts1[i] = ts[i]; } } }
{ "pile_set_name": "StackExchange" }
Q: Site layout with dynamic sticky footer that works back to IE6 with no JS: Is it possible? The requirement is simple: Create a site layout that has a dynamic sticky footer (i.e., a footer of dynamic height that sticks to the bottom of the viewport when the content doesn't fill up the entirety of the viewport, but that is under the content and not immediately visible when the content extends beyond the height of the viewport) that works in browsers back to IE6 and doesn't require JS hacks to work. Is this possible? I honestly don't mind if I have to use a table for layout purposes, but what I am looking for is the layout below that works back to IE6, but also of course works in all modern browsers. In the pictures below, orange is the header, green, the content and purple the footer. I've tried any number of layouts with divs and tables, but I can't think of any that get this to work in old IE, Firefox, etc. Any help would be greatly appreciated. Thank you. A: A dynamically-sized sticky footer is tough, because you also then need to dynamically size the main content view so that scrolling works correctly, but CSS is not a dynamic programming language. The closest I think you're going to be able to get even with current CSS ("current" of course completely rules out IE6) is to use percentages. The problem with percentages is that the footer won't be dynamically sized to the content of the footer, it'll be sized to your best guess as to the percentage value to use. It won't be satisfactory. You said you want to avoid JavaScript "hacks," but nevertheless you could almost certainly pull this off with JavaScript, setting the footer to be absolutely positioned, with the bottom position nailed to 0 (zero), and write an event handler which detects changes in the height of the footer and resizes the main content window appropriately. I don't know that I'd call that a "hack" in a pejorative sense. It's just code, doing what you tell it to do. Of course, if corporate (or other) policy where you're trying to implement this won't permit the use of JavaScript, that's another matter. And given what a security travesty 14 year old IE6 is at this stage of the game, I'd actually be one of the ones in favor of disabling JavaScript. But that, of course, rules out being able to deploy any remotely modern facsimile of an "app." By modern, of course, I simply mean the types of user-friendly feedback that I was designing into thick client apps over 20 years ago, and which have only become truly possible in web browsers since the "Web 2.0" web-standards days. IE6, of course, predates even that. Providing full support for IE6 can be a tall order. Are you sure you can't specify that your app needs to run on a modern browser? The very latest versions of Chrome and Firefox can still be installed on Windows XP, and anybody who doesn't believe new versions of Chrome or Firefox are vastly more secure than ancient, bug-riddled IE6 is fooling themselves. Having said that; if you're still running Windows XP, you have very serious security problems just waiting to bite you.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to use group_concat with coredata? I am really trying hard to use coredata with a new IOS application. A real challenge is that since my background is SQL, I keep thinking in terms of SQLite rather than coredata. I've solved most hurdles, but this one stumps me -- I really want to create a SQLite view that returns a group_concat. Do I need to recreate this by coding on the results in objective-c, or is there a way to create a view or issue direct SQL using coredata objects? EDIT: Added data model and desired results Table_A; columns -- key, name (note -- key is not unique) Sample data: K1, N1 K1, N2 K1, N3 K2, N1 K2, N2 Desired results: K1, N1;N2;N3 K2, N1;N2 In SQLite this would be SELECT key, GROUP_CONCAT(name) from Table_A GROUP BY key A: If you set your fetch request to return results as dictionaries, you have a lot of control over grouping. http://mattconnolly.wordpress.com/2012/06/21/ios-core-data-group-by-and-count-results/ and Core Data Fetching Properties with Group By Count both contain good examples. The second link shows how to walk down a relationship's keypath for grouping. EDIT: After seeing revised question, I tinkered with this a bit. Source code is on Github: https://github.com/halmueller/CoreDataGroupFetch I couldn't get a solution that would work in one single query. This is the best I could come up with. It fetches all of the unique values for the "key" field, then iterates over those keys and fetches all objects matching that "key". In the second fetch, you might want to fetch NSManagedObjects instead of dictionaries, depending on what you're going to do. NSFetchRequest* uniqueKeysFetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"KeyedName"]; uniqueKeysFetchRequest.propertiesToFetch = @[@"key"]; uniqueKeysFetchRequest.resultType = NSDictionaryResultType; uniqueKeysFetchRequest.returnsDistinctResults = YES; NSError* error = nil; NSArray *results = [self.managedObjectContext executeFetchRequest:uniqueKeysFetchRequest error:&error]; NSLog(@"uniqueKeysFetchRequest: %@", results); NSLog(@"distinct values for \"key\": %@", [results valueForKeyPath:@"@distinctUnionOfObjects.key"]); for (NSString *thisKey in [results valueForKey:@"key"]) { NSFetchRequest *oneKeyFetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"KeyedName"]; NSString *predicateString = [NSString stringWithFormat:@"key LIKE '%@'", thisKey]; oneKeyFetchRequest.predicate = [NSPredicate predicateWithFormat:predicateString]; oneKeyFetchRequest.resultType = NSDictionaryResultType; oneKeyFetchRequest.propertiesToFetch = @[@"name"]; NSLog(@"%@: %@", thisKey, [self.managedObjectContext executeFetchRequest:oneKeyFetchRequest error:&error]); } This yields results from uniqueKeysFetchRequest: ( { key = K1; }, { key = K2; } ) distinct values for "key": ( K1, K2 ) K1: ( { name = N2; }, { name = N1; }, { name = N3; } ) K2: ( { name = N2; }, { name = N1; } ) I also tried NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"KeyedName"]; fetchRequest.propertiesToFetch = @[@"key", @"name"]; fetchRequest.propertiesToGroupBy = @[@"key", @"name"]; fetchRequest.resultType = NSDictionaryResultType; fetchRequest.returnsDistinctResults = YES; NSError* error = nil; NSArray *results = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error]; NSLog(@"withKeypathStrings: %@", results); NSLog(@"distinct values for \"key\": %@", [results valueForKeyPath:@"@distinctUnionOfObjects.key"]); which might be closer to what you want: withKeypathStrings: ( { key = K1; name = N1; }, { key = K1; name = N2; }, { key = K1; name = N3; }, { key = K2; name = N1; }, { key = K2; name = N2; } ) distinct values for "key": ( K2, K1 )
{ "pile_set_name": "StackExchange" }
Q: Alfresco+DotCMIS: Folder.GetChildren returns some duplicate items When I run DotCMIS' Folder.GetChildren on an Alfresco server, I sometimes receive a few duplicate items, for instance: dir1 dir2 dir3 file1 dir4 dir5 file1 dir4 dir5 You can see that the last 3 items should not be present. Here is my code, and debug showing one of the duplicated items: Here is the detail of the lower part of the screenshot, showing two items that represent the same folder. You can see that both items have the same name ("cmissync") and same id ("workspace://SpacesStore/385da00c-8b3a-4736-b3e5-1ca1c2ff1cac"). Is it a problem with my code? (line shown in screenshot above, full method here) Or is it a known problem with either DotCMIS or Alfresco? I have tried to analyze the CMIS network traffic, but unfortunately the packets content is not readable, and I could not reproduce the problem when I tried on a freshly installed non-HTTPS Alfresco. A: Upgrading to DotCMIS from 0.4 to 0.5 fixed the problem.
{ "pile_set_name": "StackExchange" }
Q: man xargs says standard input is delimited by blanks; but is it? I'm puzzled by what actually defines an arg in xargs. The man page seems to suggest that args are delimited by blanks (I assume that means whitespace). However, the following script doesn't behave as I would expect. Here is an excerpt from man's DESCRIPTION section: xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or new‐lines, and executes the command ... It seems that perhaps xargs works in blocks of what the man-page calls items. Does this mean a null-delimited item, or a newline delimited item? Basically, I don't understand why, in the following script, xargs treats the input as a single arg, even though the spaces (in stdin) are not protected. I expected xargs to treat stdin as 3 args, or at least reduce multiple spaces to a single space, but it does neither of these! #!/bin/bash if [[ $1 == "." ]] ;then # act on a recursive call to self shift # scrap the 'recursive' arg printf '|%s|\n' "$@" # print all 'xargs' args printf '|%s|\n' "$1" # print only the first 'xargs' arg exit fi printf 'a b c\n' |xargs -I {} "$0" "." {} Here is the output; showing only a single arg was passed to the script. |a b c| |a b c| But I would have expected 3 separate args, like this: |a| |b| |c| A: Read what the manual page says about option -I, which you are using: -I replace-str Replace occurrences of replace-str in the initial-arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. A: No, this isn't about “blocks” vs “items”, that's just shifting terminology. xargs takes input quoted with ' or " and delimited by blanks, except when certain options are passed. Some options change to line-by-line processing with no quoting: -I, -L, -i (GNU), -l (GNU). The option -0 (where available) changes to null-delimited input with no quoting. The option -d (GNU) changes to a custom delimiter with no quoting.
{ "pile_set_name": "StackExchange" }
Q: Assign click-event on a new element in the event itself I want to create a new element and assign this element the same event for onclick, which it has created it. DEMO $(function(){ var counter = 0; $('.sub').click(function(event){ event.stopPropagation(); counter++; $div = $(this); // makes more sense in the original code $div.append('<div class="sub" title="subsub">subsub' + counter + '</div>'); //$div.find('.sub').click // <-- ????? }); }); In my demo I want to create a new subsub for every sub, which was clicked. Than I want to add the same click event to the new subsub element. Could anyone help me with this? I've found nothing for this problem. Maybe I don't have the correct keywords for google or SO :/ A: Just use event Delegation $(document).on('click', '.sub', function(event){ Your click events seem to be working correctly at this point,because you are using append which actually nests the new div inside the div that is clicked. Try using after and the functionality breaks. $(function(){ var counter = 0; $(document).on('click', '.sub', function(event){ event.stopPropagation(); counter++; $div = $(this); // makes more sense in the original code $div.after('<div class="sub" title="subsub">subsub' + counter + '</div>'); }); }); Check Fiddle
{ "pile_set_name": "StackExchange" }
Q: How to change certain pages into landscape/portrait mode How can I change some pages into document into landscape mode, while leaving the others in portrait mode (or vice versa)? A: Try the lscape package: % lscape.sty Produce landscape pages in a (mainly) portrait document. \usepackage{lscape} ... \begin{landscape} ... \end{landscape} This modifies the margins and rotates the page contents but not the page number. Useful, for example, with large multipage tables, and is compatible with the packages longtable and supertabular. If you are using pdfLaTeX, you should use pdflscape instead. The pdflscape package adds PDF support to the landscape environment of package lscape, by setting the PDF/Rotate page attribute. Pages with this attribute will be displayed in landscape orientation by conforming PDF viewers: \usepackage{pdflscape} ... \begin{landscape} ... \end{landscape} A: The lscape package has problems with doublesided documents! The landscape pages of even pagenumbers (on the left side of the document) should be upside down from the ones of the odd pagenumbers (on the right side of the document). To solve this problem in doublesided documents use package rotating: \usepackage{rotating} ... \begin{sidewaysfigure} ... \end{sidewaysfigure} It rotates the figures with respect to the page numbering. It also supports manual rotation with \begin{sideways} (90 degree counter-clockwise) and \begin{turn}{30} (30 degree rotation). I found the solution here. A: Found a much better solution that works with PDF files only. Use the pdflscape package instead of the lscape package. This will rotate the page inside the PDF too so it looks good. However, it still does not change \textwidth and other things. Interferes with other packages, so for example instead of \SetWatermarkAngle{19} you will have to manually set \SetWatermarkAngle{109} on landscape (in reality: rotated) pages.
{ "pile_set_name": "StackExchange" }
Q: Finding image in image position, with Keypoint Matching technique Hi I looking for solution which find real time positions of template in source image. I find many theoretical discussions, and in this article Image comparison - fast algorithm i found Keypoint Matching technique. Have any one any experiences with this in c# ? Some tests ? Or better some code samples ? A: Have a look at EmguCV it is a C# wrapper that will allow you to use the OpenCV library. In particular, the features2d library. Finally, here is an example to get you started.
{ "pile_set_name": "StackExchange" }
Q: which is better a sram 11 speed or shimano 10 speed FD with shimano 105 11speed groupset I have bought an 11 speed shimano 105 groupset, unfortunately the 11 speed FD does not fit my bike (It is an Airnimal Chamelion). Therefore I have a choice of Sram 11 speed FD or Shimano 105 10speed ? please advise which is best? A: Unfortunately, you should be using a 11 speed Shimano road FD with a 11 speed road Shimano shifter. SRAM will have cable pull issues. According to Zinn, "a Shimano 11-speed shifter will not work well with a 10-speed front derailleur because the 11-speed shifter is designed to actuate the longer lever arm of Shimano 11-speed front derailleurs." so that cuts out the old days where you didn't have to match the front shifter speeds with the front derailleur. So, you need to find the right Shimano 11 speed front derailleur for your frame (you're looking for "Shimano 105 5800 Braze-On Front Derailleur" (Shimano FD-5800-L) since the Airnimal Chameleon seems to have a Braze On FD).
{ "pile_set_name": "StackExchange" }
Q: Select Data from Database with Id From URL I've a database it is look like this |ID | Name | |081| John Davidson| and i have "index.php" in my website, i've learnt about php form, using method get, and the url is change to index.php?id=081 <form action="index.php" method="get"> <input name="id" value="081"/> <input type="submit" value="Submit"/></form> and when the page is loaded i want to show the name of id 081 from my database, how to do that? A: Try this, //Your index.php file if($_GET['id']){ $id = $_GET['id']; $sql="SELECT * FROM tableName where id='$id'"; $data = mysql_query($sql); $row = mysql_fetch_array($data); echo $row['name']; } <form action="index.php" method="get"> <input name="id" value="081"/> <input type="submit" value="Submit"/></form>
{ "pile_set_name": "StackExchange" }
Q: IntelliJ IDEA: Custom regions folding in xml I found out it is possible to create custom regions folding in java files with nice line comments as descibed here: http://www.jetbrains.com/idea/webhelp/folding-custom-regions-with-line-comments.html but I can see this only works for java files. Is it somehow possible to make it work in xml files like in pom.xml. What I would like to achieve is to introduce custom regions in dependencies to make it easier to navigate between them. A: XML and HTML custom folding regions will be a new feature introduced in upcoming IDEA 2016.3 release (see IDEA-93649). If you want to use these features now, you can download the IDEA 2016.3 EAP release now.
{ "pile_set_name": "StackExchange" }
Q: If you submit one runnable to an executor service with multiple threads, will multiple threads execute that runnable? I'm having a hard time understanding how ExecutorService works in Java 8. I was trying to understand some of the code on this website: https://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-hashmap-can-be-synchronized-in-java/ Particularly at the end where he tests the runtimes of the different maps. This is the code: public class CrunchifyConcurrentHashMapVsSynchronizedMap { public final static int THREAD_POOL_SIZE = 5; public static Map<String, Integer> crunchifyHashTableObject = null; public static Map<String, Integer> crunchifySynchronizedMapObject = null; public static Map<String, Integer> crunchifyConcurrentHashMapObject = null; public static void main(String[] args) throws InterruptedException { // Test with Hashtable Object crunchifyHashTableObject = new Hashtable<String, Integer>(); crunchifyPerformTest(crunchifyHashTableObject); // Test with synchronizedMap Object crunchifySynchronizedMapObject = Collections.synchronizedMap(new HashMap<String, Integer>()); crunchifyPerformTest(crunchifySynchronizedMapObject); // Test with ConcurrentHashMap Object crunchifyConcurrentHashMapObject = new ConcurrentHashMap<String, Integer>(); crunchifyPerformTest(crunchifyConcurrentHashMapObject); } public static void crunchifyPerformTest(final Map<String, Integer> crunchifyThreads) throws InterruptedException { System.out.println("Test started for: " + crunchifyThreads.getClass()); long averageTime = 0; for (int i = 0; i < 5; i++) { long startTime = System.nanoTime(); ExecutorService crunchifyExServer = Executors.newFixedThreadPool(THREAD_POOL_SIZE); for (int j = 0; j < THREAD_POOL_SIZE; j++) { crunchifyExServer.execute(new Runnable() { @SuppressWarnings("unused") @Override public void run() { for (int i = 0; i < 500000; i++) { Integer crunchifyRandomNumber = (int) Math.ceil(Math.random() * 550000); // Retrieve value. We are not using it anywhere Integer crunchifyValue = crunchifyThreads.get(String.valueOf(crunchifyRandomNumber)); // Put value crunchifyThreads.put(String.valueOf(crunchifyRandomNumber), crunchifyRandomNumber); } } }); } // Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation // has no additional effect if already shut down. // This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that. crunchifyExServer.shutdown(); // Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is // interrupted, whichever happens first. crunchifyExServer.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); long entTime = System.nanoTime(); long totalTime = (entTime - startTime) / 1000000L; averageTime += totalTime; System.out.println("500K entried added/retrieved in " + totalTime + " ms"); } System.out.println("For " + crunchifyThreads.getClass() + " the average time is " + averageTime / 5 + " ms\n"); } } So in the crunchifyPerformTest class, he's starting an ExecutorService with 5 threads and then submitting 5 different runnables with 500k reads and writes to the hashmap each time? Will the executor service automatically have 5 threads executing each runnable? A: No. Each Runnable is executed on exactly one thread. This means that all Runnables will be executed in parallel, because the number of Runnables matches the number of available threads. You could also submit 6 Runnables. In this case 5 of them would be executed in parallel and as soon as one Runnable has finished execution, the sixth one will be executed. By the way, I think the docs are quite clear about the behaviour of this ExecutorService.
{ "pile_set_name": "StackExchange" }
Q: NLP for java, which toolkit should I use? I'm working on a project that needs to count the occurrence of every word of a txt file. For example, I have a text file like this: What Silver Lake Looks For in IPO Candidates 3 Companies Crushed by Earnings: Apple, Cirrus Logic, IBM IBM's Palmisano: How You Get To Be A 100-Year Old Company If there are 3 sentences shown above in the file and I want to calculate every word's occurrence. Here, Companies and company should be considered as the same word "company"(lowercase), so the total occurrence for the word "company" is 2. Is there any NLP toolkit for java that can tell two words like "families" and "family" are actually from the same word "family"? I'll count the occurrence of every word to further do the Naive Bayes training, so it's very important to get the accurate numbers of occurrences of each word. A: Apache Lucene and OpenNLP provide good stemming algorithm implementations. You can review and use the best one that suites you. I've been using Lucene for my projects.
{ "pile_set_name": "StackExchange" }
Q: NavBar logo does not appear on Foundation 6 dist Foundation 6: NavBar logo works locally on my machine but when I upload to server it does not appear. Site: www.adolfobarreto.atwebpages.com I've searched through the code and can find no errors. Any Ideas? Thanks Adolfo Html: <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Foundation for Sites</title> <link rel="stylesheet" href="assets/css/app.css"> </head> <body> <!-- Small Navigation --> <div class="title-bar" data-responsive-toggle="nav-menu" data-hide-for="medium"> <a class="logo-small show-for-small-only" href="#"><img src="\assets\img\fingerLogoXS.gif" /></a> <button class="menu-icon" type="button" data-toggle></button> <div class="title-bar-title">Menu</div> </div> <!-- Medium-Up Navigation --> <nav class="top-bar" id="nav-menu"> <div class="logo-wrapper hide-for-small-only"> <div class="logo"> <img src="\assets\img\fingerLogosm.gif"> </div> </div> <!-- Left Nav Section --> <div class="top-bar-left"> <ul class="vertical medium-horizontal menu"> <li><a href="#">Menu 1</a></li> <li><a href="#">Menu 2</a></li> <li><a href="#">Menu 3</a></li> </ul> </div> <!-- Right Nav Section --> <div class="top-bar-right"> <ul class="vertical medium-horizontal dropdown menu" data-dropdown-menu> <li class="has-submenu"> <a href="#">Menu 4</a> <ul class="submenu menu vertical medium-horizontal" data-submenu> <li><a href="#">First link in dropdown</a></li> </ul> </li> <li class="has-submenu"> <a href="#">Menu 5</a> <ul class="submenu menu vertical" data-submenu> <li><a href="#">First link in dropdown</a></li> </ul> </li> </ul> </div> </nav> <!--End Main Navigation--> <br /> <br /> <div class="row"> <div class="medium-4 columns"> <img src="http://placehold.it/450x183&text=LOGO" alt="company logo"> </div> <div class="medium-8 columns"> <img src="http://placehold.it/900x175&text=Responsive Ads - ZURB Playground/333" alt="advertisement for deep fried Twinkies"> </div> </div> </header> <br> <div class="row"> <div class="medium-8 columns"> <p><img src="\assets\img\finger.jpg" alt="main article image"></p> </div> <div class="medium-4 columns"> <p><img src="\assets\img\seo2.gif" alt="article promo image" alt="advertisement for deep fried Twinkies"></p> <p><img src="\assets\img\responsive.jpg" alt="article promo image"></p> </div> </div> <hr> <footer> <div class="row expanded callout secondary"> <div class="large-4 columns"> <h4>Portfolio Images</h4> <div class="row small-up-4"> <div class="column"><img class="thumbnail" src="http://placehold.it/75" alt="image of space dog"></div> <div class="column"><img class="thumbnail" src="http://placehold.it/75" alt="image of space dog"></div> <div class="column"><img class="thumbnail" src="http://placehold.it/75" alt="image of space dog"></div> <div class="column"><img class="thumbnail" src="http://placehold.it/75" alt="image of space dog"></div> <div class="column"><img class="thumbnail" src="http://placehold.it/75" alt="image of space dog"></div> <div class="column"><img class="thumbnail" src="http://placehold.it/75" alt="image of space dog"></div> <div class="column"><img class="thumbnail" src="http://placehold.it/75" alt="image of space dog"></div> <div class="column"><img class="thumbnail" src="http://placehold.it/75" alt="image of space dog"></div> </div> </div> <div class="large-4 columns"> <h4>Mission</h4> <P>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iste magnam a quam voluptates aliquam cum, quisquam tempora sapiente minus, eos modi. Quia enim, doloremque deleniti. Voluptate nemo facilis, dignissimos temporibus. </P> </div> <div class="large-4 columns"> <h4>Technologies</h4> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deleniti quam voluptatum vel repellat ab similique molestias molestiae ea omnis eos, id asperiores est praesentium, voluptate officia nulla aspernatur sequi aliquam. </p> </div> </div> </div> <div class="row"> <div class="medium-6 large-6 columns"> <ul class="menu align-left"> <li><a href="#">Legal</a></li> <li><a href="#">Partner</a></li> <li><a href="#">Explore</a></li> </ul> </div> <div class="medium-6 large-6 columns"> <ul class="menu align-right"> <li class="menu-text">Copyright © 2016 Adolfo Barreto</li> </ul> </div> </div> </footer> <script src="assets/js/app.js"></script> </body> </html> SCSS: //Navigation //__________ /* Small Navigation */ .logo-small { float: right; } .title-bar { padding: 0 .5rem; } .menu-icon, .title-bar-title { position: relative; top: 10px; } /* Medium-Up Navigation */ @media only screen and (min-width: 40rem) { .logo-wrapper { position: relative; } .logo-wrapper .logo { width: 92px; height: 92px; position: absolute; left: 50%; right: 50%; top: -6px; margin-left: -46px; } // Right part .top-bar-right { width: 50%; padding-left: 60px; } .top-bar-right ul { float: left; } // Left part .top-bar-left { width: 50%; padding-right: 60px; } .top-bar-left ul { float: right; } } .menu-text { color: deepskyblue; } #footer-sep { padding: 1em; } A: All your image paths use backslashes instead of forward slashes. Never use backslashes in paths, no matter if they are absolute, relative, or root relative paths. BTW the link to your website does not work.
{ "pile_set_name": "StackExchange" }
Q: How can I find out why a website looks different when I upload it to IIS? Good day... I've been working on a website project, that requires to be on a Microsoft IIS Web Server. It is HTML, pure HTML, with really nice CSS, web-standards, etc. I open this website using in my computer, using Firefox, IE 8.0, Safari, Google Chrome and it looks fine everywhere. But as I upload it to the Microsoft IIS server, it changes a few things. for example: the main menu, which is a navigation bar that has dropdowns, seems to change it's line-height for some reason, and it is bigger. Some <h3> or <h2> Alignment seems wrong as well... And the lines that are supposed to surround the photographs in the website (like a frame - dotted line) won't appear. But all the rest of the CSS is loading perfectly fine. I don't think it's a path problem as everything is loading fine. But this is making me look bad and it is very important to have this done as soon as possible. Can someone give me good suggestions on what to look at ? The IIS permissions seem fine. I'm not a big Microsoft fan...but I have to develop the website there. Also, I uploaded the site to my apache server and it worked wonders. I wish I could change the policies in this corporation, but I can't. Thank you so much for your kind help. Update: To answer the request of some of the code, especially the heading until the body tag... here it is (without page title and content of the meta tags) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <!-- TemplateBeginEditable name="doctitle" --> <title></title> <!-- TemplateEndEditable --> <!-- TemplateParam name="categoria" type="text" value="home" --> <!-- Meta Tags --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="title" content="" /> <meta name="creator" content="" /> <meta name="author" content="" /> <meta name="publisher" content="" /> <meta name="Description" content="" /> <meta name="Keywords" content="" /> <meta name="subject" content="" /> <!-- list of CSS to import --> <link href="../css/main-client.css" rel="stylesheet" type="text/css" media="all" /> <!-- Load Drop down menu CSS files --> <link href="../css/dropdown.css" media="screen" rel="stylesheet" type="text/css" /> <link href="../css/default.advanced.css" media="screen" rel="stylesheet" type="text/css" /> <!-- Load Drop down menus CSS files - END --> <!-- Change of H2 or H3 font using CUFON --> <script src="../cufon-yui.js" type="text/javascript"></script> <script src="../AFB_400.font.js" type="text/javascript"></script> <script type="text/javascript"> Cufon.replace('h2'); </script> <script type="text/javascript"> Cufon.replace('h3'); </script> <!-- End of CUFON Load--> <!-- TemplateBeginEditable name="head" --> <!-- TemplateEndEditable --> </head> Update #2: I just noticed that this site is breaking in IE8.0 on IIS, but not in Firefox on IIS. But it still looks good on my IE8.0 when i open the file from my computer. Update #3: I deactivated with the Cufon lines, and the problem did persist. So I don't think it is a problem. Maybe I'm doing something wrong. But that's what I found out. Update #4: Playing with Compatibility Mode lead me to see my website running well on IE8.0 but the computer next door, still looks bad. And I shouldn't be using that option to make it look good, or else all the users would have to do the same, and that's not the idea. I'm a little confused with QuirksMode, I just changed the doctype of the site, to HTML 4.01 Transitional, but things are pretty much the same. All the CSS files are loading...but is not being interpreted well. and per your request...the Cufon-yui code, it's horrible to look at this: /* * Copyright (c) 2009 Simo Kinnunen. * Licensed under the MIT license. * * @version 1.09 */ var Cufon=(function(){var m=function(){return m.replace.apply(null,arguments)};var x=m.DOM={ready:(function(){var C=false,E={loaded:1,complete:1};var B=[],D=function(){if(C){return}C=true;for(var F;F=B.shift();F()){}};if(document.addEventListener){document.addEventListener("DOMContentLoaded",D,false);window.addEventListener("pageshow",D,false)}if(!window.opera&&document.readyState){(function(){E[document.readyState]?D():setTimeout(arguments.callee,10)})()}if(document.readyState&&document.createStyleSheet){(function(){try{document.body.doScroll("left");D()}catch(F){setTimeout(arguments.callee,1)}})()}q(window,"load",D);return function(F){if(!arguments.length){D()}else{C?F():B.push(F)}}})(),root:function(){return document.documentElement||document.body}};var n=m.CSS={Size:function(C,B){this.value=parseFloat(C);this.unit=String(C).match(/[a-z%]*$/)[0]||"px";this.convert=function(D){return D/B*this.value};this.convertFrom=function(D){return D/this.value*B};this.toString=function(){return this.value+this.unit}},addClass:function(C,B){var D=C.className;C.className=D+(D&&" ")+B;return C},color:j(function(C){var B={};B.color=C.replace(/^rgba\((.*?),\s*([\d.]+)\)/,function(E,D,F){B.opacity=parseFloat(F);return"rgb("+D+")"});return B}),fontStretch:j(function(B){if(typeof B=="number"){return B}if(/%$/.test(B)){return parseFloat(B)/100}return{"ultra-condensed":0.5,"extra-condensed":0.625,condensed:0.75,"semi-condensed":0.875,"semi-expanded":1.125,expanded:1.25,"extra-expanded":1.5,"ultra-expanded":2}[B]||1}),getStyle:function(C){var B=document.defaultView;if(B&&B.getComputedStyle){return new a(B.getComputedStyle(C,null))}if(C.currentStyle){return new a(C.currentStyle)}return new a(C.style)},gradient:j(function(F){var G={id:F,type:F.match(/^-([a-z]+)-gradient\(/)[1],stops:[]},C=F.substr(F.indexOf("(")).match(/([\d.]+=)?(#[a-f0-9]+|[a-z]+\(.*?\)|[a-z]+)/ig);for(var E=0,B=C.length,D;E<B;++E){D=C[E].split("=",2).reverse();G.stops.push([D[1]||E/(B-1),D[0]])}return G}),quotedList:j(function(E){var D=[],C=/\s*((["'])([\s\S]*?[^\\])\2|[^,]+)\s*/g,B;while(B=C.exec(E)){D.push(B[3]||B[1])}return D}),recognizesMedia:j(function(G){var E=document.createElement("style"),D,C,B;E.type="text/css";E.media=G;try{E.appendChild(document.createTextNode("/**/"))}catch(F){}C=g("head")[0];C.insertBefore(E,C.firstChild);D=(E.sheet||E.styleSheet);B=D&&!D.disabled;C.removeChild(E);return B}),removeClass:function(D,C){var B=RegExp("(?:^|\\s+)"+C+"(?=\\s|$)","g");D.className=D.className.replace(B,"");return D},supports:function(D,C){var B=document.createElement("span").style;if(B[D]===undefined){return false}B[D]=C;return B[D]===C},textAlign:function(E,D,B,C){if(D.get("textAlign")=="right"){if(B>0){E=" "+E}}else{if(B<C-1){E+=" "}}return E},textShadow:j(function(F){if(F=="none"){return null}var E=[],G={},B,C=0;var D=/(#[a-f0-9]+|[a-z]+\(.*?\)|[a-z]+)|(-?[\d.]+[a-z%]*)|,/ig;while(B=D.exec(F)){if(B[0]==","){E.push(G);G={};C=0}else{if(B[1]){G.color=B[1]}else{G[["offX","offY","blur"][C++]]=B[2]}}}E.push(G);return E}),textTransform:(function(){var B={uppercase:function(C){return C.toUpperCase()},lowercase:function(C){return C.toLowerCase()},capitalize:function(C){return C.replace(/\b./g,function(D){return D.toUpperCase()})}};return function(E,D){var C=B[D.get("textTransform")];return C?C(E):E}})(),whiteSpace:(function(){var D={inline:1,"inline-block":1,"run-in":1};var C=/^\s+/,B=/\s+$/;return function(H,F,G,E){if(E){if(E.nodeName.toLowerCase()=="br"){H=H.replace(C,"")}}if(D[F.get("display")]){return H}if(!G.previousSibling){H=H.replace(C,"")}if(!G.nextSibling){H=H.replace(B,"")}return H}})()};n.ready=(function(){var B=!n.recognizesMedia("all"),E=false;var D=[],H=function(){B=true;for(var K;K=D.shift();K()){}};var I=g("link"),J=g("style");function C(K){return K.disabled||G(K.sheet,K.media||"screen")}function G(M,P){if(!n.recognizesMedia(P||"all")){return true}if(!M||M.disabled){return false}try{var Q=M.cssRules,O;if(Q){search:for(var L=0,K=Q.length;O=Q[L],L<K;++L){switch(O.type){case 2:break;case 3:if(!G(O.styleSheet,O.media.mediaText)){return false}break;default:break search}}}}catch(N){}return true}function F(){if(document.createStyleSheet){return true}var L,K;for(K=0;L=I[K];++K){if(L.rel.toLowerCase()=="stylesheet"&&!C(L)){return false}}for(K=0;L=J[K];++K){if(!C(L)){return false}}return true}x.ready(function(){if(!E){E=n.getStyle(document.body).isUsable()}if(B||(E&&F())){H()}else{setTimeout(arguments.callee,10)}});return function(K){if(B){K()}else{D.push(K)}}})();function s(D){var C=this.face=D.face,B={"\u0020":1,"\u00a0":1,"\u3000":1};this.glyphs=D.glyphs;this.w=D.w;this.baseSize=parseInt(C["units-per-em"],10);this.family=C["font-family"].toLowerCase();this.weight=C["font-weight"];this.style=C["font-style"]||"normal";this.viewBox=(function(){var F=C.bbox.split(/\s+/);var E={minX:parseInt(F[0],10),minY:parseInt(F[1],10),maxX:parseInt(F[2],10),maxY:parseInt(F[3],10)};E.width=E.maxX-E.minX;E.height=E.maxY-E.minY;E.toString=function(){return[this.minX,this.minY,this.width,this.height].join(" ")};return E})();this.ascent=-parseInt(C.ascent,10);this.descent=-parseInt(C.descent,10);this.height=-this.ascent+this.descent;this.spacing=function(L,N,E){var O=this.glyphs,M,K,G,P=[],F=0,J=-1,I=-1,H;while(H=L[++J]){M=O[H]||this.missingGlyph;if(!M){continue}if(K){F-=G=K[H]||0;P[I]-=G}F+=P[++I]=~~(M.w||this.w)+N+(B[H]?E:0);K=M.k}P.total=F;return P}}function f(){var C={},B={oblique:"italic",italic:"oblique"};this.add=function(D){(C[D.style]||(C[D.style]={}))[D.weight]=D};this.get=function(H,I){var G=C[H]||C[B[H]]||C.normal||C.italic||C.oblique;if(!G){return null}I={normal:400,bold:700}[I]||parseInt(I,10);if(G[I]){return G[I]}var E={1:1,99:0}[I%100],K=[],F,D;if(E===undefined){E=I>400}if(I==500){I=400}for(var J in G){if(!k(G,J)){continue}J=parseInt(J,10);if(!F||J<F){F=J}if(!D||J>D){D=J}K.push(J)}if(I<F){I=F}if(I>D){I=D}K.sort(function(M,L){return(E?(M>=I&&L>=I)?M<L:M>L:(M<=I&&L<=I)?M>L:M<L)?-1:1});return G[K[0]]}}function r(){function D(F,G){if(F.contains){return F.contains(G)}return F.compareDocumentPosition(G)&16}function B(G){var F=G.relatedTarget;if(!F||D(this,F)){return}C(this,G.type=="mouseover")}function E(F){C(this,F.type=="mouseenter")}function C(F,G){setTimeout(function(){var H=d.get(F).options;m.replace(F,G?h(H,H.hover):H,true)},10)}this.attach=function(F){if(F.onmouseenter===undefined){q(F,"mouseover",B);q(F,"mouseout",B)}else{q(F,"mouseenter",E);q(F,"mouseleave",E)}}}function u(){var C=[],D={};function B(H){var E=[],G;for(var F=0;G=H[F];++F){E[F]=C[D[G]]}return E}this.add=function(F,E){D[F]=C.push(E)-1};this.repeat=function(){var E=arguments.length?B(arguments):C,F;for(var G=0;F=E[G++];){m.replace(F[0],F[1],true)}}}function A(){var D={},B=0;function C(E){return E.cufid||(E.cufid=++B)}this.get=function(E){var F=C(E);return D[F]||(D[F]={})}}function a(B){var D={},C={};this.extend=function(E){for(var F in E){if(k(E,F)){D[F]=E[F]}}return this};this.get=function(E){return D[E]!=undefined?D[E]:B[E]};this.getSize=function(F,E){return C[F]||(C[F]=new n.Size(this.get(F),E))};this.isUsable=function(){return !!B}}function q(C,B,D){if(C.addEventListener){C.addEventListener(B,D,false)}else{if(C.attachEvent){C.attachEvent("on"+B,function(){return D.call(C,window.event)})}}}function v(C,B){var D=d.get(C);if(D.options){return C}if(B.hover&&B.hoverables[C.nodeName.toLowerCase()]){b.attach(C)}D.options=B;return C}function j(B){var C={};return function(D){if(!k(C,D)){C[D]=B.apply(null,arguments)}return C[D]}}function c(F,E){var B=n.quotedList(E.get("fontFamily").toLowerCase()),D;for(var C=0;D=B[C];++C){if(i[D]){return i[D].get(E.get("fontStyle"),E.get("fontWeight"))}}return null}function g(B){return document.getElementsByTagName(B)}function k(C,B){return C.hasOwnProperty(B)}function h(){var C={},B,F;for(var E=0,D=arguments.length;B=arguments[E],E<D;++E){for(F in B){if(k(B,F)){C[F]=B[F]}}}return C}function o(E,M,C,N,F,D){var K=document.createDocumentFragment(),H;if(M===""){return K}var L=N.separate;var I=M.split(p[L]),B=(L=="words");if(B&&t){if(/^\s/.test(M)){I.unshift("")}if(/\s$/.test(M)){I.push("")}}for(var J=0,G=I.length;J<G;++J){H=z[N.engine](E,B?n.textAlign(I[J],C,J,G):I[J],C,N,F,D,J<G-1);if(H){K.appendChild(H)}}return K}function l(D,M){var C=D.nodeName.toLowerCase();if(M.ignore[C]){return}var E=!M.textless[C];var B=n.getStyle(v(D,M)).extend(M);var F=c(D,B),G,K,I,H,L,J;if(!F){return}for(G=D.firstChild;G;G=I){K=G.nodeType;I=G.nextSibling;if(E&&K==3){if(H){H.appendData(G.data);D.removeChild(G)}else{H=G}if(I){continue}}if(H){D.replaceChild(o(F,n.whiteSpace(H.data,B,H,J),B,M,G,D),H);H=null}if(K==1){if(G.firstChild){if(G.nodeName.toLowerCase()=="cufon"){z[M.engine](F,null,B,M,G,D)}else{arguments.callee(G,M)}}J=G}}}var t=" ".split(/\s+/).length==0;var d=new A();var b=new r();var y=new u();var e=false;var z={},i={},w={autoDetect:false,engine:null,forceHitArea:false,hover:false,hoverables:{a:true},ignore:{applet:1,canvas:1,col:1,colgroup:1,head:1,iframe:1,map:1,optgroup:1,option:1,script:1,select:1,style:1,textarea:1,title:1,pre:1},printable:true,selector:(window.Sizzle||(window.jQuery&&function(B){return jQuery(B)})||(window.dojo&&dojo.query)||(window.Ext&&Ext.query)||(window.YAHOO&&YAHOO.util&&YAHOO.util.Selector&&YAHOO.util.Selector.query)||(window.$$&&function(B){return $$(B)})||(window.$&&function(B){return $(B)})||(document.querySelectorAll&&function(B){return document.querySelectorAll(B)})||g),separate:"words",textless:{dl:1,html:1,ol:1,table:1,tbody:1,thead:1,tfoot:1,tr:1,ul:1},textShadow:"none"};var p={words:/\s/.test("\u00a0")?/[^\S\u00a0]+/:/\s+/,characters:"",none:/^/};m.now=function(){x.ready();return m};m.refresh=function(){y.repeat.apply(y,arguments);return m};m.registerEngine=function(C,B){if(!B){return m}z[C]=B;return m.set("engine",C)};m.registerFont=function(D){if(!D){return m}var B=new s(D),C=B.family;if(!i[C]){i[C]=new f()}i[C].add(B);return m.set("fontFamily",'"'+C+'"')};m.replace=function(D,C,B){C=h(w,C);if(!C.engine){return m}if(!e){n.addClass(x.root(),"cufon-active cufon-loading");n.ready(function(){n.addClass(n.removeClass(x.root(),"cufon-loading"),"cufon-ready")});e=true}if(C.hover){C.forceHitArea=true}if(C.autoDetect){delete C.fontFamily}if(typeof C.textShadow=="string"){C.textShadow=n.textShadow(C.textShadow)}if(typeof C.color=="string"&&/^-/.test(C.color)){C.textGradient=n.gradient(C.color)}else{delete C.textGradient}if(!B){y.add(D,arguments)}if(D.nodeType||typeof D=="string"){D=[D]}n.ready(function(){for(var F=0,E=D.length;F<E;++F){var G=D[F];if(typeof G=="string"){m.replace(C.selector(G),C,true)}else{l(G,C)}}});return m};m.set=function(B,C){w[B]=C;return m};return m})();Cufon.registerEngine("canvas",(function(){var b=document.createElement("canvas");if(!b||!b.getContext||!b.getContext.apply){return}b=null;var a=Cufon.CSS.supports("display","inline-block");var e=!a&&(document.compatMode=="BackCompat"||/frameset|transitional/i.test(document.doctype.publicId));var f=document.createElement("style");f.type="text/css";f.appendChild(document.createTextNode(("cufon{text-indent:0;}@media screen,projection{cufon{display:inline;display:inline-block;position:relative;vertical-align:middle;"+(e?"":"font-size:1px;line-height:1px;")+"}cufon cufontext{display:-moz-inline-box;display:inline-block;width:0;height:0;overflow:hidden;text-indent:-10000in;}"+(a?"cufon canvas{position:relative;}":"cufon canvas{position:absolute;}")+"}@media print{cufon{padding:0;}cufon canvas{display:none;}}").replace(/;/g,"!important;")));document.getElementsByTagName("head")[0].appendChild(f);function d(p,h){var n=0,m=0;var g=[],o=/([mrvxe])([^a-z]*)/g,k;generate:for(var j=0;k=o.exec(p);++j){var l=k[2].split(",");switch(k[1]){case"v":g[j]={m:"bezierCurveTo",a:[n+~~l[0],m+~~l[1],n+~~l[2],m+~~l[3],n+=~~l[4],m+=~~l[5]]};break;case"r":g[j]={m:"lineTo",a:[n+=~~l[0],m+=~~l[1]]};break;case"m":g[j]={m:"moveTo",a:[n=~~l[0],m=~~l[1]]};break;case"x":g[j]={m:"closePath"};break;case"e":break generate}h[g[j].m].apply(h,g[j].a)}return g}function c(m,k){for(var j=0,h=m.length;j<h;++j){var g=m[j];k[g.m].apply(k,g.a)}}return function(V,w,P,t,C,W){var k=(w===null);if(k){w=C.getAttribute("alt")}var A=V.viewBox;var m=P.getSize("fontSize",V.baseSize);var B=0,O=0,N=0,u=0;var z=t.textShadow,L=[];if(z){for(var U=z.length;U--;){var F=z[U];var K=m.convertFrom(parseFloat(F.offX));var I=m.convertFrom(parseFloat(F.offY));L[U]=[K,I];if(I<B){B=I}if(K>O){O=K}if(I>N){N=I}if(K<u){u=K}}}var Z=Cufon.CSS.textTransform(w,P).split("");var E=V.spacing(Z,~~m.convertFrom(parseFloat(P.get("letterSpacing"))||0),~~m.convertFrom(parseFloat(P.get("wordSpacing"))||0));if(!E.length){return null}var h=E.total;O+=A.width-E[E.length-1];u+=A.minX;var s,n;if(k){s=C;n=C.firstChild}else{s=document.createElement("cufon");s.className="cufon cufon-canvas";s.setAttribute("alt",w);n=document.createElement("canvas");s.appendChild(n);if(t.printable){var S=document.createElement("cufontext");S.appendChild(document.createTextNode(w));s.appendChild(S)}}var aa=s.style;var H=n.style;var j=m.convert(A.height);var Y=Math.ceil(j);var M=Y/j;var G=M*Cufon.CSS.fontStretch(P.get("fontStretch"));var J=h*G;var Q=Math.ceil(m.convert(J+O-u));var o=Math.ceil(m.convert(A.height-B+N));n.width=Q;n.height=o;H.width=Q+"px";H.height=o+"px";B+=A.minY;H.top=Math.round(m.convert(B-V.ascent))+"px";H.left=Math.round(m.convert(u))+"px";var r=Math.max(Math.ceil(m.convert(J)),0)+"px";if(a){aa.width=r;aa.height=m.convert(V.height)+"px"}else{aa.paddingLeft=r;aa.paddingBottom=(m.convert(V.height)-1)+"px"}var X=n.getContext("2d"),D=j/A.height;X.scale(D,D*M);X.translate(-u,-B);X.save();function T(){var x=V.glyphs,ab,l=-1,g=-1,y;X.scale(G,1);while(y=Z[++l]){var ab=x[Z[l]]||V.missingGlyph;if(!ab){continue}if(ab.d){X.beginPath();if(ab.code){c(ab.code,X)}else{ab.code=d("m"+ab.d,X)}X.fill()}X.translate(E[++g],0)}X.restore()}if(z){for(var U=z.length;U--;){var F=z[U];X.save();X.fillStyle=F.color;X.translate.apply(X,L[U]);T()}}var q=t.textGradient;if(q){var v=q.stops,p=X.createLinearGradient(0,A.minY,0,A.maxY);for(var U=0,R=v.length;U<R;++U){p.addColorStop.apply(p,v[U])}X.fillStyle=p}else{X.fillStyle=P.get("color")}T();return s}})());Cufon.registerEngine("vml",(function(){var e=document.namespaces;if(!e){return}e.add("cvml","urn:schemas-microsoft-com:vml");e=null;var b=document.createElement("cvml:shape");b.style.behavior="url(#default#VML)";if(!b.coordsize){return}b=null;var h=(document.documentMode||0)<8;document.write(('<style type="text/css">cufoncanvas{text-indent:0;}@media screen{cvml\\:shape,cvml\\:rect,cvml\\:fill,cvml\\:shadow{behavior:url(#default#VML);display:block;antialias:true;position:absolute;}cufoncanvas{position:absolute;text-align:left;}cufon{display:inline-block;position:relative;vertical-align:'+(h?"middle":"text-bottom")+";}cufon cufontext{position:absolute;left:-10000in;font-size:1px;}a cufon{cursor:pointer}}@media print{cufon cufoncanvas{display:none;}}</style>").replace(/;/g,"!important;"));function c(i,j){return a(i,/(?:em|ex|%)$|^[a-z-]+$/i.test(j)?"1em":j)}function a(l,m){if(m==="0"){return 0}if(/px$/i.test(m)){return parseFloat(m)}var k=l.style.left,j=l.runtimeStyle.left;l.runtimeStyle.left=l.currentStyle.left;l.style.left=m.replace("%","em");var i=l.style.pixelLeft;l.style.left=k;l.runtimeStyle.left=j;return i}function f(l,k,j,n){var i="computed"+n,m=k[i];if(isNaN(m)){m=k.get(n);k[i]=m=(m=="normal")?0:~~j.convertFrom(a(l,m))}return m}var g={};function d(p){var q=p.id;if(!g[q]){var n=p.stops,o=document.createElement("cvml:fill"),i=[];o.type="gradient";o.angle=180;o.focus="0";o.method="sigma";o.color=n[0][1];for(var m=1,l=n.length-1;m<l;++m){i.push(n[m][0]*100+"% "+n[m][1])}o.colors=i.join(",");o.color2=n[l][1];g[q]=o}return g[q]}return function(ac,G,Y,C,K,ad,W){var n=(G===null);if(n){G=K.alt}var I=ac.viewBox;var p=Y.computedFontSize||(Y.computedFontSize=new Cufon.CSS.Size(c(ad,Y.get("fontSize"))+"px",ac.baseSize));var y,q;if(n){y=K;q=K.firstChild}else{y=document.createElement("cufon");y.className="cufon cufon-vml";y.alt=G;q=document.createElement("cufoncanvas");y.appendChild(q);if(C.printable){var Z=document.createElement("cufontext");Z.appendChild(document.createTextNode(G));y.appendChild(Z)}if(!W){y.appendChild(document.createElement("cvml:shape"))}}var ai=y.style;var R=q.style;var l=p.convert(I.height),af=Math.ceil(l);var V=af/l;var P=V*Cufon.CSS.fontStretch(Y.get("fontStretch"));var U=I.minX,T=I.minY;R.height=af;R.top=Math.round(p.convert(T-ac.ascent));R.left=Math.round(p.convert(U));ai.height=p.convert(ac.height)+"px";var F=Y.get("color");var ag=Cufon.CSS.textTransform(G,Y).split("");var L=ac.spacing(ag,f(ad,Y,p,"letterSpacing"),f(ad,Y,p,"wordSpacing"));if(!L.length){return null}var k=L.total;var x=-U+k+(I.width-L[L.length-1]);var ah=p.convert(x*P),X=Math.round(ah);var O=x+","+I.height,m;var J="r"+O+"ns";var u=C.textGradient&&d(C.textGradient);var o=ac.glyphs,S=0;var H=C.textShadow;var ab=-1,aa=0,w;while(w=ag[++ab]){var D=o[ag[ab]]||ac.missingGlyph,v;if(!D){continue}if(n){v=q.childNodes[aa];while(v.firstChild){v.removeChild(v.firstChild)}}else{v=document.createElement("cvml:shape");q.appendChild(v)}v.stroked="f";v.coordsize=O;v.coordorigin=m=(U-S)+","+T;v.path=(D.d?"m"+D.d+"xe":"")+"m"+m+J;v.fillcolor=F;if(u){v.appendChild(u.cloneNode(false))}var ae=v.style;ae.width=X;ae.height=af;if(H){var s=H[0],r=H[1];var B=Cufon.CSS.color(s.color),z;var N=document.createElement("cvml:shadow");N.on="t";N.color=B.color;N.offset=s.offX+","+s.offY;if(r){z=Cufon.CSS.color(r.color);N.type="double";N.color2=z.color;N.offset2=r.offX+","+r.offY}N.opacity=B.opacity||(z&&z.opacity)||1;v.appendChild(N)}S+=L[aa++]}var M=v.nextSibling,t,A;if(C.forceHitArea){if(!M){M=document.createElement("cvml:rect");M.stroked="f";M.className="cufon-vml-cover";t=document.createElement("cvml:fill");t.opacity=0;M.appendChild(t);q.appendChild(M)}A=M.style;A.width=X;A.height=af}else{if(M){q.removeChild(M)}}ai.width=Math.max(Math.ceil(p.convert(k*P)),0);if(h){var Q=Y.computedYAdjust;if(Q===undefined){var E=Y.get("lineHeight");if(E=="normal"){E="1em"}else{if(!isNaN(E)){E+="em"}}Y.computedYAdjust=Q=0.5*(a(ad,E)-parseFloat(ai.height))}if(Q){ai.marginTop=Math.ceil(Q)+"px";ai.marginBottom=Q+"px"}}return y}})()); Update #5 I removed the URLs of the website, so the company's privacy remains. This is the index.html response header...using Firefox, but remember in Firefox it looks fine. I dont know how to find it via IE. GET /test-1/index.html HTTP/1.1 Host: * User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 (.NET CLR 3.5.30729) Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 115 Connection: keep-alive Referer: http://test-1/contact-us.html If-Modified-Since: Thu, 08 Apr 2010 16:32:15 GMT If-None-Match: "cc980c39d7ca1:15ce" HTTP/1.1 304 Not Modified Last-Modified: Thu, 08 Apr 2010 16:32:15 GMT Accept-Ranges: bytes Etag: "cc980c39d7ca1:15ce" Server: Microsoft-IIS/6.0 X-Powered-By: ASP.NET Date: Thu, 08 Apr 2010 18:59:45 GMT A: Update #2: I just noticed that this site is breaking in IE8.0 on IIS, but not in Firefox on IIS. But it still looks good on my IE8.0 when i open the file from my computer. Thus, it is running in quirks mode. Check the page source (rightclick, View Source) and the response headers. Does the page source look fine? No whitespace before <!doctype>? It would trigger IE in quirks mode. No odd response headers which forces IE to render/emulate in quirks mode? Does it have correct Content-Type header? IE namely doesn't support application/xhtml+xml, the server has to send it as text/html. Update #4: Playing with Compatibility Mode lead me to see my website running well on IE8.0 but the computer next door, still looks bad. This confirms that IE was running in quirks mode. And I shouldn't be using that option to make it look good, or else all the users would have to do the same, and that's not the idea. I'm a little confused with QuirksMode, I just changed the doctype of the site, to HTML 4.01 Transitional, but things are pretty much the same. All the CSS files are loading...but is not being interpreted well. You shouldn't change the doctype. You're using XHTML strict which is okay (it will render IE in (almost) standards mode), even though I would prefer HTML strict since this doesn't seem to be autogenerated code which uses a XML tool to parse components. Once again, did you check the page source? There should be no whitespace before the <!doctype> line. No linefeed/newline, no spaces/tabs, no BOM characters, etcetera. The < must be the firstmost character. Use a hex editor if necessary. Did you check the real response headers? I don't mean the HTML <meta> tags, they are part of the response body. You can use under each Fiddler or a webbrowser-specific "http header" plugin for this, Google can find them.
{ "pile_set_name": "StackExchange" }
Q: Are Debug Routines MSVC++ specific? Are the Debug Routines found here: http://msdn.microsoft.com/de-de/library/1666sb98(v=VS.100).aspx specific to MSVC++ or are they C++ Standard? What do other compilers provide? A: They are not specified by the C++ standard. They are MSVC specific. For GCC debug related options see this.
{ "pile_set_name": "StackExchange" }
Q: MYSQL: Can you pull results that match like 3 out of 4 expressions? Say I have a query like this: SELECT * FROM my_table WHERE name = "john doe" AND phone = "8183321234" AND email = "[email protected]" AND address = "330 some lane"; But say I only need 3 out of the 4 to match, I know I can write a very long query with several ORs but I was wondering if there was a feature for this? Thanks. A: SELECT * FROM my_table WHERE CASE WHEN name = "john doe" THEN 1 ELSE 0 END + CASE WHEN phone = "8183321234" THEN 1 ELSE 0 END + CASE WHEN email = "[email protected]" THEN 1 ELSE 0 END + CASE WHEN address = "330 some lane" THEN 1 ELSE 0 END >= 3; Side note: this will very likely not be using indexes efficiently. On the other hand, there will very likely be no indexes on these kinds of columns anyway. A: Holy overcomplexity, Batman. SELECT * FROM my_table WHERE ( (name = "john doe") + (phone = "8183321234") + (email = "[email protected]") + (address = "330 some lane") ) >= 3; A: Same thing using indexes: SELECT * FROM ( SELECT id FROM ( SELECT id FROM mytable _name WHERE name = 'john doe' UNION ALL SELECT id FROM mytable _name WHERE phone = '8183321234' UNION ALL SELECT id FROM mytable _name WHERE email = "[email protected]" UNION ALL SELECT id FROM mytable _name WHERE address = '330 some lane' ) q GROUP BY id HAVING COUNT(*) >= 3 ) di, mytable t WHERE t.id = di.id See the entry in my blog for performance details.
{ "pile_set_name": "StackExchange" }
Q: Silverstripe relation is not visible on details page Am looping teachers relation on template CoursePage.ss but when i try to loop that relation teachers inside CouresePage_details.ss does not work. Am doing somthing wrong. I have two models Courses and Teachers Course can have many teachhers Teacher can have one course Courses.php class Courses extends DataObject { private static $many_many = array( 'Teachers' => 'Teachers', ); } Teachers.php class Courses extends DataObject { private static $belongs_many_many = array( 'Courses ' => 'Courses ', ); } CoursesPage.php class CoursesPage extends Page { } class CoursesPage_Controller extends Page_Controller { public static $allowed_actions = array( 'details' ); // Show specific course public function details(SS_HTTPRequest $request) { $c= Courses::get()->byID($request->param('ID')); if(!$c) { return $this->httpError(404, "Courses not found"); } return array( 'Courses' => $c, ); } // Courses list public function CoursesList () { $c = Courses::get()->sort('Featured', 'DESC'); return $c; } } CoursesPage.ss In this file i just loop courses, nothing important. Here i loop list of courses and teachers. Here teachers looping working perfect just not work on details template. CoursesPage_details.ss Here is problem. When i show details about specific course i want to loop teachers which is related with this course but i all time get NULL return Teachers does not exist . Looks like it is not in scope. <section class="course-details"> <h2>$Courses.Name</h2> <!-- Work --> <p>$Courses.Descr</p> <ul class="teachers-list"> <% if $Teachers %> <!-- Not work here, but on CoursePage.ss work --> <% loop $Teachers %> $FirstName <% end_loop %> <% else > Teachers does not exist <% end_if %> </ul> </section> A: You need to use $Courses.Teachers instead… or you could just change the scope to Courses, by using <% with $Courses %>. So your template would look like this: <section class="course-details"> <% with $Courses %> <h2>$Name</h2> <p>$Descr</p> <ul class="teachers-list"> <% if $Teachers %> <% loop $Teachers %> $FirstName <% end_loop %> <% else > Teachers does not exist <% end_if %> </ul> <% end_with %> </section> The reason for this is: You're passing your Course DataObject to the template as a parameter named Courses. It's this DataObject that has a relation to Teachers, therefore you need to use $Courses.Teachers or change the scope as outlined above. By default, you're still in the scope of CoursesPage.
{ "pile_set_name": "StackExchange" }
Q: What are the XP rewards for public events in Destiny? Do public events give XP? If so, how does it scale based on location or type of event (Kill target vs Defend the thingy)? A: The first public event you complete each day rewards you with a package at the postmaster. Opening this package grants 5,000 experience. For completing the event itself, I do not think there is any known experience gain, besides whatever you get for kill enemies. If you get some at the end of the event itself, I do not think it is a significant amount, otherwise people would probably have figured out a way to exploit this and power level.
{ "pile_set_name": "StackExchange" }
Q: When did Harry find out about Sirius almost killing Snape? I'm trying to find, when Harry found out that Sirius nearly killed Snape by making him go down the Whomping Willow to where Remus was in werewolf form? A: It's at the very end of Chapter 18, Moony, Wormtail, Padfoot, and Prongs, of the third book, HP and the Prisoner of Azkaban: "Severus was very interested in where I went every month." Lupin told Harry, Ron, and Hermione. "We were in the same year, you know, and we— er—didn't like each other very much. He especially disliked James. Jealous, I think, of James's talent on the Quidditch field... anyway Snape had seen me crossing the grounds with Madam Pomfrey one evening as she led me toward the Whomping Willow to transform. Sirius thought it would be— er—amusing, to tell Snape all he had to do was prod the knot on the tree trunk with a long stick, and he'd be able to get in after me. Well, of course, Snape tried it—if he'd got as far as this house, he'd have met a fully grown werewolf—but your father, who'd heard what Sirius had done, went after Snape and pulled him back, at great risk to his life... Snape glimpsed me, though, at the end of the tunnel. He was forbidden by Dumbledore to tell anybody, but from that time on he knew what I was..." "So that's why Snape doesn't like you," said Harry slowly, "because he thought you were in on the joke?" "That's right," sneered a cold voice from the wall behind Lupin. Severus Snape was pulling off the Invisibility Cloak, his wand pointing directly at Lupin. (@Slytherincess This time I did copy-paste, from here, rather than transcribing by hand.)
{ "pile_set_name": "StackExchange" }
Q: A maximal subspace of the vector space of real valued function I am trying to find a maximal subspace of the vector space of real valued functions. I've proved that the subspace $N_X=\{f:\mathbb{R\rightarrow\mathbb{R}}: f(r)=0\space\forall r\in X\}$ is maximal subspace of $\mathbb{R}^{\mathbb{R}}$ when $X={\{r\}},$ without consider the whole space, but I am searching another maximal subspace $W,$ $W\neq N_{\{r\}}.$ I was thinking that subspace of odd or even function could work but I do not get anything useful. Any kind of help is thanked in advanced. A: All we need is a nonzero linear function $h:\Bbb R^{\Bbb R}\to \Bbb R$ that has more complicated behavior than evaluation at $x_0\in\mathbb R$. Then, the kernel of $h$ will be a maximal subspace that does not belong to the list you have provided. Here's an example. Let $h(f) = f(1)-f(0)$. One easily verifies $h$ is linear. We can also read off the maximal subspace: $\{f\in\mathbb R^{\mathbb R} | f(1)=f(0)\}$.
{ "pile_set_name": "StackExchange" }
Q: Node JS - get FQDN How can I get the FQDN (Fully Qualified Domain Name) of the machine on which node is running? os.gethostname() is not sufficient, since it usually returns the unqualified DN, only. Same thing for dns.reverse(ip, callback) - assuming the ip is the one associated with the hostname, e.g. obtained using dns.lookup(os.gethostname()[, options], callback). Also doing a shell.exec("hostname -f", { silent: true }, cb) is not an option, since it is not POSIX compliant and thus will fail e.g. on Solaris et. al., and it is a really bad hack, since exec() is a very, very expensive call wrt. resources like RAM and CPU (causes context switching). A: The trick is to utilize the getnameinfo(...) function provided by the OS usually via libc.so or libsocket.so, since it does a FQDN lookup by default! Because dns.lookupService(address, port, callback) seems to be the only documented nodeJS core function, which "wraps" it, we need to use this one. E.g.: var os = require('os'); var dns = require('dns'); var h = os.hostname(); console.log('UQDN: ' + h); dns.lookup(h, { hints: dns.ADDRCONFIG }, function(err, ip) { console.log('IP: ' + ip); dns.lookupService(ip, 0, function (err, hostname, service) { if (err) { console.log(err); return; } console.log('FQDN: ' + hostname); console.log('Service: ' + service); }); }); Port 0 is used in the example to show that this has no influence on the result (by default there is no service defined for this port).
{ "pile_set_name": "StackExchange" }
Q: Appending timestamp in business objects scheduled reports Can we append timestamp in the format 'mmddyyyy' to business objects reports name generated by scheduler. I know we can append file extension using '%EXT%'. I am looking for something similar. Thanks for any help A: I figured out this one: I have to pass : RPT_NAME_%SI_STARTTIME%.%EXT% This will generate only in yyyy-MM-dd-hh-mm-ss.fileextension format though
{ "pile_set_name": "StackExchange" }
Q: Core Data Multithreading Import (Duplicate Objects) I have an NSOperationQueue that imports objects into Core Data that I get from a web api. Each operation has a private child managedObjectContext of my app's main managedObjectContext. Each operation takes the object to be imported and checks whether the object already exists in which case it updates the existing object. If the object doesn't exist it creates this new object. These changes on the private child contexts are then propagated up to the main managed object context. This setup has worked very well for me, but there is a duplicates issue. When I've got the same object being imported in two different concurrent operations I get duplicate objects that have the exact same data. (They both check to see if the object exists, and it doesn't appear to them to already exist). The reason i'll have 2 of the same objects importing at around the same time is that I'll often be processing a "new" api call as well as a "get" api call. Due to the concurrently asynchronous nature of my setup, it's hard to ensure that I won't ever have duplicate objects attempting to import. So my question is what is the best way to solve this particular issue? I thought about limiting imports to max concurrent operations to 1 (I don't like this because of performance). Similarly I've considering requiring a save after every import operation and trying to handle merging of contexts. Also, i've considered grooming the data afterwards to occasionally clean up duplicates. And finally, i've considered just handling the duplicates on all fetch requests. But none of these solutions seem great to me, and perhaps there is an easy solution I've over looked. A: So the problem is: contexts are a scratchpad — unless and until you save, changes you make in them are not pushed to the persistent store; you want one context to be aware of changes made on another that hasn't yet been pushed. To me it doesn't sound like merging between contexts is going to work — contexts are not thread safe. Therefore for a merge to occur nothing else can be ongoing on the thread/queue of the other context. You're therefore never going to be able to eliminate the risk that a new object is inserted while another context is partway through its insertion process. Additional observations: SQLite is not thread safe in any practical sense; hence all trips to the persistent store are serialised regardless of how you issue them. Bearing in mind the problem and the SQLite limitations, in my app we've adopted a framework whereby the web calls are naturally concurrent as per NSURLConnection, subsequent parsing of the results (JSON parsing plus some fishing into the result) occurs concurrently and then the find-or-create step is channeled into a serial queue. Very little processing time is lost by the serialisation because the SQLite trips would be serialised anyway, and they're the overwhelming majority of the serialised stuff. A: Start by creating dependences between your operations. Make sure one can't complete until its dependency does. Check out http://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html#//apple_ref/occ/instm/NSOperation/addDependency: Each operation should call save when it finished. Next, I would try the Find-Or-Create methodology suggested here: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreData/Articles/cdImporting.html It'll solve your duplicates problem, and can probably result in you doing less fetches (which are expensive and slow, thus drain battery quickly). You could also create a global child context to handle all of your imports, then merge the whole huge thing at the end, but it really comes down to how big the data set is and your memory considerations.
{ "pile_set_name": "StackExchange" }
Q: Parsing in Javascript Here I am getting the data using the java.stringify. But to use the data which I get in the graph framework, that should not be withinquoted. I need to parse all the data which has quote in it. (eg [{data:[{x:87.6,y:85}..) What should I do here? Please help me!! Here`s the data which I need to parse.. [{"data":[{"x":87.6,"y":85},{"x":116.08,"y":61},{"x":113.11,"y":49},{"x":181.37,"y":65},{"x":138.14,"y":74},{"x":66.03,"y":89}]}] A: Use regular expression to remove quotes. For example if it is a json string you can do this: var json = '{ "name": "John Smith" }'; //Let's say you got this json = json.replace(/\"([^(\")"]+)\":/g,"$1:"); //This will remove all the quotes json; //'{ name:"John Smith" }' In case of your input: var a ='[{"data":[{"x":87.6,"y":85},{"x":116.08,"y":61},{"x":113.11,"y":49},{"x":181.37,"y":65},{"x":138.14,"y":74},{"x":66.03,"y":89}]}]'; a = a.replace(/\"([^(\")"]+)\":/g,"$1:"); a; //"[{data:[{x:87.6,y:85},{x:116.08,y:61},{x:113.11,y:49},{x:181.37,y:65},{x:138.14,y:74},{x:66.03,y:89}]}]"
{ "pile_set_name": "StackExchange" }
Q: nested for loops with String I am having problems with this method. It is a constructor with 2 parameters: a name and a String with 100 char called in. in must be turned in to a array[10][10] with vak(an object) in it. I always get the same exception: StringIndexOutOfBoundsException: String index out of range: 100 This is the method: public SpelBord(String naam, String in) { int muur=1; this.naam = naam; System.out.println(in.length()); for(int i=0;i<in.length();i++) { for (int j = 0; j < vakken.length; j++) { for (int k = 0; k < vakken[j].length; k++) { if (in.charAt(i) == '.') { this.vakken[j][k] = new Vak(); } if (in.charAt(i) == 'K') { this.vakken[j][k] = new Vak(false, false, new Kist()); } if (in.charAt(i) == 'D') { this.vakken[j][k] = new Vak(true, false); } if (in.charAt(i) == 'M') { this.vakken[j][k] = new Vak(false, false, new Man()); } if (in.charAt(i) == '#') { this.vakken[j][k] = new Vak(false, true); } } } } I think it is something with the for loops. thank you in advance! A: You got this error StringIndexOutOfBoundsException: String index out of range: 100 Because: Suppose you enter a String of 100 character suppose the string is "ABCDEFGHIJK . . . . . . LMNOPQRSTUVWXYZ" in that case in.length=100 Now see what happens to your code: (Read the comments) for(int i=0;i<in.length();i++) {// i=0 for (int j = 0; j < vakken.length; j++) { for (int k = 0; k < vakken[j].length; k++) { if (in.charAt(i) == '.') {//looking for charAt(0) this.vakken[j][k] = new Vak(); i++;//if this condition satisfies i=1 } if (in.charAt(i) == 'K') {//if last if condition satisfies looking for charAt(1) this.vakken[j][k] = new Vak(false, false, new Kist()); i++;//if this condition satisfies i=2 } if (in.charAt(i) == 'D') {//if last if condition satisfies looking for charAt(2) this.vakken[j][k] = new Vak(true, false); i++;//if this condition satisfies i=3 } if (in.charAt(i) == 'M') {//if last if condition satisfies looking for charAt(3) this.vakken[j][k] = new Vak(false, false, new Man()); muur++; i++;//if this condition satisfies i=4 } if (in.charAt(i) == '#') {//if last if condition satisfies looking for charAt(4) this.vakken[j][k] = new Vak(false, true); i++;//if this condition satisfies i=5 } } } Here, in the code the value of your variable i increasing unnecessarily. Now think that i=99 in the loop. Now see what happens in your code:(Read the comments carefully): for(int i=0;i<in.length();i++) {// i=99 for (int j = 0; j < vakken.length; j++) { for (int k = 0; k < vakken[j].length; k++) { if (in.charAt(i) == '.') {//looking for charAt(99) this.vakken[j][k] = new Vak(); i++;//if this condition satisfies i=100 } if (in.charAt(i) == 'K') { //if last if condition satisfies //looking for charAt(100) //now charAt(100) dose not exists //and an error occurs that String out of range this.vakken[j][k] = new Vak(false, false, new Kist()); i++; } if (in.charAt(i) == 'D') { this.vakken[j][k] = new Vak(true, false); i++; } if (in.charAt(i) == 'M') { this.vakken[j][k] = new Vak(false, false, new Man()); muur++; i++; } if (in.charAt(i) == '#') { this.vakken[j][k] = new Vak(false, true); i++; } } } I think you understand why the error StringIndexOutOfBoundsException: String index out of range: 100 occurs. To improve your code you can use else if ladder and do not increment i unnecessarily because i is increment in your for loop - for(int i=0;i<in.length();i++ . And try to setup/clear the logic before starting coding.
{ "pile_set_name": "StackExchange" }
Q: Cast as decimal in mysql I have below table structure and data : create table sample ( id INT(10) ); INSERT INTO sample values (23398), (98743), (54734); Now I want to understand CAST function in mysql. Consider following query : select cast((id/3) as decimal(2,2)) as cast1, cast((id/3) as decimal(3,2)) as cast2, cast((id/3) as decimal(4,2)) as cast3, cast((id/3) as decimal(5,2)) as cast4, cast((id/3) as decimal(6,2)) as cast5, cast((id/3) as decimal(7,2)) as cast6, id/3 as actualId from sample; Please see output of this query at SQL Fiddle. I am wondering why this query gives 0.99, 9.99 and vice versa. Can anyone explain it ? Thanks in advance. A: decimal is a type that takes 2 arguments decimal(size, places) : size determines how many digits are in the number. places determines how many of those digits are to the right of the decimal. decimal(2,2) - .00 - 2 digits both of which are to the right of the decimal when casting (23398 / 3) = 7799.33333333 to declimal(2, 2) it yields a decimal in the specified amount of space closest to the desired number which is 0.99 decimal(3,2) - 0.00 - 3 digits 2 of which are to the right of the decimal when casting (23398 / 3) = 7799.33333333 to declimal(3, 2) it yields a decimal in the specified amount of space closest to the desired number which is 9.99 if all of the original numbers were negative you would yield -0.99 and -9.99 because they are the closest numbers to the desired number within the allocated space As a matter of fact java does something similar if you take the max double and try to convert it to an int you will give the max int which is no where near the max double
{ "pile_set_name": "StackExchange" }
Q: creating files in c getting abort : 6 error the loop only goes through 0-9 the out put is this. the error im getting is abort 6 , im not sure what it means 1.txt 38 2.txt 5 3.txt 6 4.txt 24 5.txt 17 6.txt 12 7.txt 34 8.txt 30 9.txt 6 Abort trap: 6 also the code below creates the same random numbers every run how can i make it more random void save(char *, int ); void create(char *, int ); void close(); FILE * list; FILE * file; int main(void) { char ext[4] = ".txt"; static const int MIN = 1 ; static const int MAX = 40 ; int rdm , fsize; list = fopen("filelist.txt","w"); char str[2]; //char str3[6]; list = fopen("filelist.txt", "a+"); for(int i = 0 ; i < 10 ; i ++ ) { sprintf(str,"%d",i+1); char * str3 = (char *) calloc(1,1 + strlen(str)+ strlen(ext) ); //file = fopen(str3,"r"); strcat(str3,str); strcat(str3, ext); // printf("%s \n",ext); //strcat(str3, ext); rdm = (rand()%(MAX-MIN)+MIN); printf("%s %i \n",str3, rdm); save(str3 , rdm); create(str3 , rdm); // printf("%s \n",ext); } close(); } void save(char * fname , int sz) { fprintf(list , "%s %d %d \n" , fname , sz , sz*512 ); } void create(char * fname , int sz) { file = fopen(fname, "w"); fseek(file, sz*512, SEEK_SET); fputc('\n', file); fclose(file); } void close() { fclose(list); } A: There are at least three things here: Firstly, your main function is returning int: int main() So, in the success case for running your code, you should return 0 at the very last line: ...//all other lines return 0; //no error Secondly, rand() is pseudo random random. It generates pre-determined random number everytime according to the random number seed used. to make your rand() value change everytime, consider of having time as random seed in srand(). Then your random values will change according to the time. #include <time.h> ... srand(time(NULL)); // randomize seed //do it once before you use rand() Thirdly, as commented, your char arrays size seem to be to small: char ext[5] = ".txt"; //should be 5, the last one will be \0 ... char str[15]; //should be large enough for your text
{ "pile_set_name": "StackExchange" }
Q: Swift 4: Array index out of Range i am new to swift, i got a simple question, looked over the related questions on stackoverflow, none of them were in swift 4, so i had to ask here i have an array which looks something like this on the log ["72 Wilson St, Manchester M11 2AZ, UK"] // 0 ["Goldbergweg 117, 60599 Frankfurt am Main, Germany"] // 1 ["Rondweg Zuid, 3817 Amersfoort, Netherlands"] // 2 am i right? and i used this code to get the elements in it: var stringArray = [String]() stringArray.append(forss as! String) print(stringArray self.predit1.text = stringArray[2] self.predit2.text = stringArray[0] self.predit3.text = stringArray[1] but getting: Thread 1: Fatal error: Index out of range A: You declared an array of String var stringArray = [String]() Then you appended one element stringArray.append(forss as! String) That means only index 0 is valid stringArray[0] and you get an out-of-range error for stringArray[1] stringArray[2] etc. Note: The question is not particularly related to Swift 4. All versions of Swift exhibit this behavior.
{ "pile_set_name": "StackExchange" }
Q: Книги по Flash Помогите, дорогие ХэшКод'овцы. Есть великолепная идея хорошего приложения, но идеи мало для реализации. Хотелось бы научиться создавать приложения, но нормальных книжек не нашел, а возможно плохо искал. Прошу Вас помочь мне с литературой по этому поводу, а ниже я опишу чему же я хочу научиться. Руководство по AS3 (основы я знаю, создавать простенькие Flash приложения с небольшим функционал умею, но хочется именно уметь создавать большие приложения, а вот именно с этим у меня проблемы) Изометрические движки (посоветуйте какие-нибудь проверенные движки, возможно те, с которыми Вы работали) А вообще все книги, по которым можно научиться создавать приложения по типу Клондайк'а ВКонтакте. Интересует больше не как создавать такие приложения, а как делать такую механику, движения, анимацию и прочее. Буду премного благодарен всем, кто поможет. A: https://ru.stackoverflow.com/questions/234334#291713
{ "pile_set_name": "StackExchange" }
Q: What can we say about two topological spaces with the same fundamental group? Let's consider two topological spaces. If they are homeomorphic, or homotopic equivalent, they have isomorphic fundamental groups, but the converse is not true. My question is: is there a (non trivial) equivalence relation between topological spaces that holds if and only they have isomorphic fundamental groups? Or weaker: what common properties have two spaces if they have isomorphic fundamental groups? A: There is not really anything interesting that can be said. The property of two spaces having isomorphic fundamental groups is pretty much never singled out in the literature, because it doesn't have any interesting nontrivial consequences and doesn't arise naturally very often. In some very special cases, there are stronger consequences. For instance, if $X$ and $Y$ are connected CW-complexes such that $\pi_n(X)$ and $\pi_n(Y)$ are trivial for all $n>1$, then $\pi_1(X)\cong \pi_1(Y)$ implies $X$ and $Y$ are homotopy equivalent. Or, if $X$ and $Y$ are both connected closed surfaces, then $\pi_1(X)\cong \pi_1(Y)$ implies $X$ and $Y$ are homeomorphic (this follows from the classification of surfaces).
{ "pile_set_name": "StackExchange" }
Q: Why shouldn't I buy an ultra light tent? I have a workhorse of a tent, an Alpine Meadows, (described in this answer) that I really like. We bought it 30 years ago, and at first we just had way more stuff than we should, and eventually we had two small children (and their stuff) in the tent with us. There were times when I read stories to five children at a time in that tent. But now, it has more space than we need. And it's 30 years old, and tent technology has really changed. So we're thinking of replacing it with a tent that weighs less and takes up less room in the pack. (We canoe camp primarily, and create extra bedrooms at a cottage every few years.) I understand I will have to give up something I really like about the Alpine Meadows: I can stand up in it, which makes dressing much easier. I accept that modern 2 and 3 person tents are all generally shorter inside, and I'll take that in exchange for the weight and the pack room. Step 1: go to a 2 or 3 person tent instead of a 4. No problem. Step 2: enjoy the lighter materials even ordinary tents come in (example). No problem. Step 3: what about an ultralight (example)? Wow, one-third the weight of a regular tent! That's amazing. I'm ready to buy one but hang on, why do they still make regular tents? What's the downside here? I'm comparing floor area, peak height, and so on and don't see significant differences. I have several hypotheses: a tiny difference is huge. You can endure 1.2m peak height but not 1.12. fabric thickness and material affects durability and I need to pay attention to the numbers and whatnot in that area ultralights can't be 4 season (don't care: I never winter camp.) there is some other important difference that isn't included in specs that keeps many people away from ultralights the only difference is the price I'm really hoping it's that last one. At 30 years per tent, $600 doesn't seem like a big deal. But I worry that it's actually something else and I just don't know about it. Here is what a tent is for on my trips: keep the rain off us while we sleep and provide a rain free refuge where it's possible to move around a little while reading, or to play cards etc if it is cold (for a summer definition of cold) keep us warm. We have sleeping bags and clothes of course, and the very coldest we've ever camped was a morning we woke up to -1C. That is nowhere near the norm. The norm is 18C nights. keep the bugs off us while we sleep, and provide a bug free refuge once in a while guaranteed shade when I want it (I sunburn incredibly easily) keep our stuff from blowing away when we are away from camp provide a little privacy when traveling with others, whether to change clothes, or just to be alone for a while I would never consider a tarp-only or tarp-and-hammock setup. A tent to me is a place to put stuff and a place to hang out if the weather is bad, not just a place to sleep or a way to keep rain off me. There will be two adults in this tent. Also, we camp during high bug season - blackflies, mosquitos, horseflies, you name it. We never cook in the vestibule - we set up a kitchen tarp across the campsite. We keep lifejackets, empty packs, shoes, and coats in there. It's also a place to put your shoes on while you're exiting the tent, and to take them off while you're entering. We're quite capable of carrying our current tent, but I won't deny looking forward to carrying 8 pounds less on every portage. A: I wouldn't buy an ultralight tent if you're going to put the tent through severe trauma or require significant space (e.g. to use chairs inside). I do think the main difference in buying is cultural; unless you are poking it with sticks tents shouldn't experience that much damage. The modern ultralights should be good for most any weather outside of snowstorms and severe windstorms. One trend is to cut tent weight by replacing the inner tent with ever increasing amounts of mesh (compare the BA Seedhouse to the BA Copper Spur linked in your example). The REI (a US equivalent to MEC) Half Dome sold today is almost entirely mesh compared to the one I purchased almost a decade ago. I don't mind this, as it gives you the option to sleep under the stars in good weather, and if you're using the rainfly there's really no need for a waterproof inner wall. The second, somewhat more recent trend, is to experiment with pole geometry. Instead of a traditional dome design or simple crossed poles, many manufacturers are incorporating Y-joints and shorter segments to increase living space while cutting weight. The BA Copper Spur is a good example of this, as it does both. Be aware that many tents have only a small area with the stated headroom, which is not so good once you have two people. The more vertical the sidewalls are, the better the livability. The inner tent fabrics are somewhat delicate but not unreasonably so. A separate footprint will extend the life of the tent floor, and I'm not sure what would be damaging the walls of the tent. (Perhaps children falling through a partially-zipped door, but usually the tent just flexes.) The main difference between many 3 and 4 season tents I've seen is the use of a traditional dome structure with the poles (better wind and snow resistance) as well as the ability to fully cover the mesh panels of the inner tent. (I've used the 3-season REI Half Dome mentioned earlier in winter snow during a severe windstorm; ridge gusts were over 90mph, fortunately we were down in a valley. A small problem was spindrift forced through the small air vents in the rainfly and past the mesh panels of the inner. The other issue was the two-crossed-poles design being vulnerable to snow piling up on the long sides.) The MEC Nunatak appears aimed at mountaineering and has additional features to beef it up; it is probably overkill outside of that environment. Ultralight hikers consider even the lightweight tents from large manufacturers too heavy, although some offerings from makers like Big Agnes are now considered reasonably decent for someone getting into lightweight hiking. A multi-person shelter also helps bring down the weight-per-person. Smaller "cottage" gear makers build shelters out of materials like silnylon (most common) or cuben fiber (expensive). These can be smaller and more delicate and range from simple tarps to fully-enclosed shelters. (Keep in mind that single-wall tents have condensation issues that double-wall tents help shield you from.) Two example makers are Tarptent and Six Moon Designs. I find the Tarptent Stratospire 2 good for two people; the offset trekking pole design adds space for two people to easily sit facing each other. (Some designs, most commonly the floorless pyramids, are quite usable in winter.) Finally, $600 is approaching Hilleberg territory. Those tents are bomber; the fabric is an incredibly strong silicone-coated nylon. I have a Jannu for winter mountaineering, but would suggest taking a look at the Kaitum 2 (or 3). At 3.1 kg it isn't that light, but it's a good trade for something more than capable of handling exposed tundra and arctic winds. Also, the tunnel tent design makes for good roominess inside; do a Google image search for examples. They turn up used on gear forums every so often; I recommend keeping an eye out. Otherwise, something like the BA Copper Spur you found should work quite well. Edit: I glossed over the materials a bit, and it's one area where technology has improved. Modern tent poles like DAC's lightweight aluminum offerings are made via seamless extrusion rather than sheet welding. This allows for poles that are strong, thing, and lightweight, but do cost more due to the manufacturing process. (Newer alloys also help.) Excluding canvas, tents will come in nylon or polyester of varying weights. For car-camping family tents where weight is not an issue, a heavier-weight fabric may be used. Nylon is somewhat lighter and tougher, and comes in various weights. 70D nylon, common for floors, weighs about 1.9oz per square yard while a much lighter 30D weighs in at 1.1oz per square yard. This is an area where there's a direct tradeoff between weight and durability. The other advance is the use of silicone to make the fabric waterproof, which results in a stronger and lighter material than traditional polyurethane coatings. (E.g. a 30D silnylon may have twice the tear resistance of a 70D nylon coated with polyurethane.) A: I have bought the Copper Spur 3 and slept in it now on a cottage lawn and on a backcountry campsite. The advantages (lightweight, easy to set up) are real. There are some disadvantages that I have not seen mentioned in the other answers, so I've decided to add an answer providing them. None of these are enough to make me regret buying the tent or tell someone else not to buy it, but I feel they're worth mentioning. the tent floor is extremely slippery. (As are new mats, bags etc, see my answer to Are self-inflatable sleeping pads more slippery than other mats?) I think this is a natural side effect of the thin and flexible material. I really noticed this camped on a slight slope - I had to crawl back up hill several times in the night. the zippers are very thin and buckle easily. If whatever you're trying to unzip isn't tight, you'll need another hand to hold it tight while you unzip. Think about the difference between unzipping a big suitcase zipper and a delicate dress zipper. This was more of an issue on the vestibule than the doors, but on a different ultralight it might vary. it's cooler in the same weather than my old Alpine Meadows. We slept one cottage night in the old tent before letting someone else have it the next night, and I felt the breeze around my ears the second night for sure everything is smaller and lighter and thinner. Everything. I took far too long trying to hook a mini carabiner (with a lantern on it) through the gear loop at the peak, but it was just so damn small! we had a very rainy trip in, and were looking at setting up under the tarp if it didn't stop, but eventually it did. The other couple, using our AM, could have set it up out in the rain if need be. The mesh roof on the ultralight makes that a very wet strategy. I was able to change clothes in it although I couldn't stand up, but I'm not sure I could have done so had anyone else been in there. Luckily we tend to get up and go have coffee in what we slept in, then pop into the tent to change for the day, so this isn't an issue for us. I was also pleasantly surprised at the effect of the two-doors-two-vestibules setup. Most of our stuff was in the vestibules - stuff sack of clothes as pillows were inside, along with water bottles, flashlights, and cameras - but sitting up, unzipping the door, and poking around in a pack in the vestibule was astonishingly easy. In the AM, the vestibule was for stuff you didn't need in the tent at all ever, and I accessed it from the rest of the site if I needed something. The experience in the CS blurred the lines between inside and outside more, and overall I think I like that. A: I see an ultralight tent as an expensive piece of backpacking equipment, with the alternative being a tarp. Compared to the tarp, the tent is slightly heaver, much more expensive, easier to set up, and keeps out bugs. I'm ready to buy one but hang on, why do they still make regular tents? What's the downside here? I would assume that the vast majority of the market for tents consists of people who car-camp. They want something large, comfortable, and cheap, and they don't care about weight or bulk. Then there would be a much smaller fraction of the market that is cheap, relatively heavy backpacking tents, and an even tinier fraction of the market that is expensive ultralight tents. For the style of canoe camping you do, is the main function of the tent to keep out bugs? Do you want a big vestibule to cook in? Do you sometimes spend long periods of time confined to the tent, e.g., if it rains all day? [EDIT] Based on the further information in the revised question, I'm surprised that an ultralight is an option for you, since I would think you'd want a lot of room. But if it's roomy enough, and you think it's likely to be durable enough for your conditions, then it probably comes down to a trade-off of expense versus weight while portaging.
{ "pile_set_name": "StackExchange" }
Q: How to filter a RecyclerView with a SearchView I am trying to implement the SearchView from the support library. I want the user to be to use the SearchView to filter a List of movies in a RecyclerView. I have followed a few tutorials so far and I have added the SearchView to the ActionBar, but I am not really sure where to go from here. I have seen a few examples but none of them show results as you start typing. This is my MainActivity: public class MainActivity extends ActionBarActivity { RecyclerView mRecyclerView; RecyclerView.LayoutManager mLayoutManager; RecyclerView.Adapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recycler_view); mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view); mRecyclerView.setHasFixedSize(true); mLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mLayoutManager); mAdapter = new CardAdapter() { @Override public Filter getFilter() { return null; } }; mRecyclerView.setAdapter(mAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } And this is my Adapter: public abstract class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> implements Filterable { List<Movie> mItems; public CardAdapter() { super(); mItems = new ArrayList<Movie>(); Movie movie = new Movie(); movie.setName("Spiderman"); movie.setRating("92"); mItems.add(movie); movie = new Movie(); movie.setName("Doom 3"); movie.setRating("91"); mItems.add(movie); movie = new Movie(); movie.setName("Transformers"); movie.setRating("88"); mItems.add(movie); movie = new Movie(); movie.setName("Transformers 2"); movie.setRating("87"); mItems.add(movie); movie = new Movie(); movie.setName("Transformers 3"); movie.setRating("86"); mItems.add(movie); movie = new Movie(); movie.setName("Noah"); movie.setRating("86"); mItems.add(movie); movie = new Movie(); movie.setName("Ironman"); movie.setRating("86"); mItems.add(movie); movie = new Movie(); movie.setName("Ironman 2"); movie.setRating("86"); mItems.add(movie); movie = new Movie(); movie.setName("Ironman 3"); movie.setRating("86"); mItems.add(movie); } @Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_view_card_item, viewGroup, false); return new ViewHolder(v); } @Override public void onBindViewHolder(ViewHolder viewHolder, int i) { Movie movie = mItems.get(i); viewHolder.tvMovie.setText(movie.getName()); viewHolder.tvMovieRating.setText(movie.getRating()); } @Override public int getItemCount() { return mItems.size(); } class ViewHolder extends RecyclerView.ViewHolder{ public TextView tvMovie; public TextView tvMovieRating; public ViewHolder(View itemView) { super(itemView); tvMovie = (TextView)itemView.findViewById(R.id.movieName); tvMovieRating = (TextView)itemView.findViewById(R.id.movieRating); } } } A: Introduction Since it is not really clear from your question what exactly you are having trouble with, I wrote up this quick walkthrough about how to implement this feature; if you still have questions feel free to ask. I have a working example of everything I am talking about here in this GitHub Repository. If you want to know more about the example project visit the project homepage. In any case the result should looks something like this: If you first want to play around with the demo app you can install it from the Play Store: Anyway lets get started. Setting up the SearchView In the folder res/menu create a new file called main_menu.xml. In it add an item and set the actionViewClass to android.support.v7.widget.SearchView. Since you are using the support library you have to use the namespace of the support library to set the actionViewClass attribute. Your xml file should look something like this: <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/action_search" android:title="@string/action_search" app:actionViewClass="android.support.v7.widget.SearchView" app:showAsAction="always"/> </menu> In your Fragment or Activity you have to inflate this menu xml like usual, then you can look for the MenuItem which contains the SearchView and implement the OnQueryTextListener which we are going to use to listen for changes to the text entered into the SearchView: @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); final MenuItem searchItem = menu.findItem(R.id.action_search); final SearchView searchView = (SearchView) searchItem.getActionView(); searchView.setOnQueryTextListener(this); return true; } @Override public boolean onQueryTextChange(String query) { // Here is where we are going to implement the filter logic return false; } @Override public boolean onQueryTextSubmit(String query) { return false; } And now the SearchView is ready to be used. We will implement the filter logic later on in onQueryTextChange() once we are finished implementing the Adapter. Setting up the Adapter First and foremost this is the model class I am going to use for this example: public class ExampleModel { private final long mId; private final String mText; public ExampleModel(long id, String text) { mId = id; mText = text; } public long getId() { return mId; } public String getText() { return mText; } } It's just your basic model which will display a text in the RecyclerView. This is the layout I am going to use to display the text: <?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <variable name="model" type="com.github.wrdlbrnft.searchablerecyclerviewdemo.ui.models.ExampleModel"/> </data> <FrameLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/selectableItemBackground" android:clickable="true"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="8dp" android:text="@{model.text}"/> </FrameLayout> </layout> As you can see I use Data Binding. If you have never worked with data binding before don't be discouraged! It's very simple and powerful, however I can't explain how it works in the scope of this answer. This is the ViewHolder for the ExampleModel class: public class ExampleViewHolder extends RecyclerView.ViewHolder { private final ItemExampleBinding mBinding; public ExampleViewHolder(ItemExampleBinding binding) { super(binding.getRoot()); mBinding = binding; } public void bind(ExampleModel item) { mBinding.setModel(item); } } Again nothing special. It just uses data binding to bind the model class to this layout as we have defined in the layout xml above. Now we can finally come to the really interesting part: Writing the Adapter. I am going to skip over the basic implementation of the Adapter and am instead going to concentrate on the parts which are relevant for this answer. But first there is one thing we have to talk about: The SortedList class. SortedList The SortedList is a completely amazing tool which is part of the RecyclerView library. It takes care of notifying the Adapter about changes to the data set and does so it a very efficient way. The only thing it requires you to do is specify an order of the elements. You need to do that by implementing a compare() method which compares two elements in the SortedList just like a Comparator. But instead of sorting a List it is used to sort the items in the RecyclerView! The SortedList interacts with the Adapter through a Callback class which you have to implement: private final SortedList.Callback<ExampleModel> mCallback = new SortedList.Callback<ExampleModel>() { @Override public void onInserted(int position, int count) { mAdapter.notifyItemRangeInserted(position, count); } @Override public void onRemoved(int position, int count) { mAdapter.notifyItemRangeRemoved(position, count); } @Override public void onMoved(int fromPosition, int toPosition) { mAdapter.notifyItemMoved(fromPosition, toPosition); } @Override public void onChanged(int position, int count) { mAdapter.notifyItemRangeChanged(position, count); } @Override public int compare(ExampleModel a, ExampleModel b) { return mComparator.compare(a, b); } @Override public boolean areContentsTheSame(ExampleModel oldItem, ExampleModel newItem) { return oldItem.equals(newItem); } @Override public boolean areItemsTheSame(ExampleModel item1, ExampleModel item2) { return item1.getId() == item2.getId(); } } In the methods at the top of the callback like onMoved, onInserted, etc. you have to call the equivalent notify method of your Adapter. The three methods at the bottom compare, areContentsTheSame and areItemsTheSame you have to implement according to what kind of objects you want to display and in what order these objects should appear on the screen. Let's go through these methods one by one: @Override public int compare(ExampleModel a, ExampleModel b) { return mComparator.compare(a, b); } This is the compare() method I talked about earlier. In this example I am just passing the call to a Comparator which compares the two models. If you want the items to appear in alphabetical order on the screen. This comparator might look like this: private static final Comparator<ExampleModel> ALPHABETICAL_COMPARATOR = new Comparator<ExampleModel>() { @Override public int compare(ExampleModel a, ExampleModel b) { return a.getText().compareTo(b.getText()); } }; Now let's take a look at the next method: @Override public boolean areContentsTheSame(ExampleModel oldItem, ExampleModel newItem) { return oldItem.equals(newItem); } The purpose of this method is to determine if the content of a model has changed. The SortedList uses this to determine if a change event needs to be invoked - in other words if the RecyclerView should crossfade the old and new version. If you model classes have a correct equals() and hashCode() implementation you can usually just implement it like above. If we add an equals() and hashCode() implementation to the ExampleModel class it should look something like this: public class ExampleModel implements SortedListAdapter.ViewModel { private final long mId; private final String mText; public ExampleModel(long id, String text) { mId = id; mText = text; } public long getId() { return mId; } public String getText() { return mText; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ExampleModel model = (ExampleModel) o; if (mId != model.mId) return false; return mText != null ? mText.equals(model.mText) : model.mText == null; } @Override public int hashCode() { int result = (int) (mId ^ (mId >>> 32)); result = 31 * result + (mText != null ? mText.hashCode() : 0); return result; } } Quick side note: Most IDE's like Android Studio, IntelliJ and Eclipse have functionality to generate equals() and hashCode() implementations for you at the press of a button! So you don't have to implement them yourself. Look up on the internet how it works in your IDE! Now let's take a look at the last method: @Override public boolean areItemsTheSame(ExampleModel item1, ExampleModel item2) { return item1.getId() == item2.getId(); } The SortedList uses this method to check if two items refer to the same thing. In simplest terms (without explaining how the SortedList works) this is used to determine if an object is already contained in the List and if either an add, move or change animation needs to be played. If your models have an id you would usually compare just the id in this method. If they don't you need to figure out some other way to check this, but however you end up implementing this depends on your specific app. Usually it is the simplest option to give all models an id - that could for example be the primary key field if you are querying the data from a database. With the SortedList.Callback correctly implemented we can create an instance of the SortedList: final SortedList<ExampleModel> list = new SortedList<>(ExampleModel.class, mCallback); As the first parameter in the constructor of the SortedList you need to pass the class of your models. The other parameter is just the SortedList.Callback we defined above. Now let's get down to business: If we implement the Adapter with a SortedList it should look something like this: public class ExampleAdapter extends RecyclerView.Adapter<ExampleViewHolder> { private final SortedList<ExampleModel> mSortedList = new SortedList<>(ExampleModel.class, new SortedList.Callback<ExampleModel>() { @Override public int compare(ExampleModel a, ExampleModel b) { return mComparator.compare(a, b); } @Override public void onInserted(int position, int count) { notifyItemRangeInserted(position, count); } @Override public void onRemoved(int position, int count) { notifyItemRangeRemoved(position, count); } @Override public void onMoved(int fromPosition, int toPosition) { notifyItemMoved(fromPosition, toPosition); } @Override public void onChanged(int position, int count) { notifyItemRangeChanged(position, count); } @Override public boolean areContentsTheSame(ExampleModel oldItem, ExampleModel newItem) { return oldItem.equals(newItem); } @Override public boolean areItemsTheSame(ExampleModel item1, ExampleModel item2) { return item1.getId() == item2.getId(); } }); private final LayoutInflater mInflater; private final Comparator<ExampleModel> mComparator; public ExampleAdapter(Context context, Comparator<ExampleModel> comparator) { mInflater = LayoutInflater.from(context); mComparator = comparator; } @Override public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final ItemExampleBinding binding = ItemExampleBinding.inflate(inflater, parent, false); return new ExampleViewHolder(binding); } @Override public void onBindViewHolder(ExampleViewHolder holder, int position) { final ExampleModel model = mSortedList.get(position); holder.bind(model); } @Override public int getItemCount() { return mSortedList.size(); } } The Comparator used to sort the item is passed in through the constructor so we can use the same Adapter even if the items are supposed to be displayed in a different order. Now we are almost done! But we first need a way to add or remove items to the Adapter. For this purpose we can add methods to the Adapter which allow us to add and remove items to the SortedList: public void add(ExampleModel model) { mSortedList.add(model); } public void remove(ExampleModel model) { mSortedList.remove(model); } public void add(List<ExampleModel> models) { mSortedList.addAll(models); } public void remove(List<ExampleModel> models) { mSortedList.beginBatchedUpdates(); for (ExampleModel model : models) { mSortedList.remove(model); } mSortedList.endBatchedUpdates(); } We don't need to call any notify methods here because the SortedList already does this for through the SortedList.Callback! Aside from that the implementation of these methods is pretty straight forward with one exception: the remove method which removes a List of models. Since the SortedList has only one remove method which can remove a single object we need to loop over the list and remove the models one by one. Calling beginBatchedUpdates() at the beginning batches all the changes we are going to make to the SortedList together and improves performance. When we call endBatchedUpdates() the RecyclerView is notified about all the changes at once. Additionally what you have to understand is that if you add an object to the SortedList and it is already in the SortedList it won't be added again. Instead the SortedList uses the areContentsTheSame() method to figure out if the object has changed - and if it has the item in the RecyclerView will be updated. Anyway, what I usually prefer is one method which allows me to replace all items in the RecyclerView at once. Remove everything which is not in the List and add all items which are missing from the SortedList: public void replaceAll(List<ExampleModel> models) { mSortedList.beginBatchedUpdates(); for (int i = mSortedList.size() - 1; i >= 0; i--) { final ExampleModel model = mSortedList.get(i); if (!models.contains(model)) { mSortedList.remove(model); } } mSortedList.addAll(models); mSortedList.endBatchedUpdates(); } This method again batches all updates together to increase performance. The first loop is in reverse since removing an item at the start would mess up the indexes of all items that come up after it and this can lead in some instances to problems like data inconsistencies. After that we just add the List to the SortedList using addAll() to add all items which are not already in the SortedList and - just like I described above - update all items that are already in the SortedList but have changed. And with that the Adapter is complete. The whole thing should look something like this: public class ExampleAdapter extends RecyclerView.Adapter<ExampleViewHolder> { private final SortedList<ExampleModel> mSortedList = new SortedList<>(ExampleModel.class, new SortedList.Callback<ExampleModel>() { @Override public int compare(ExampleModel a, ExampleModel b) { return mComparator.compare(a, b); } @Override public void onInserted(int position, int count) { notifyItemRangeInserted(position, count); } @Override public void onRemoved(int position, int count) { notifyItemRangeRemoved(position, count); } @Override public void onMoved(int fromPosition, int toPosition) { notifyItemMoved(fromPosition, toPosition); } @Override public void onChanged(int position, int count) { notifyItemRangeChanged(position, count); } @Override public boolean areContentsTheSame(ExampleModel oldItem, ExampleModel newItem) { return oldItem.equals(newItem); } @Override public boolean areItemsTheSame(ExampleModel item1, ExampleModel item2) { return item1 == item2; } }); private final Comparator<ExampleModel> mComparator; private final LayoutInflater mInflater; public ExampleAdapter(Context context, Comparator<ExampleModel> comparator) { mInflater = LayoutInflater.from(context); mComparator = comparator; } @Override public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final ItemExampleBinding binding = ItemExampleBinding.inflate(mInflater, parent, false); return new ExampleViewHolder(binding); } @Override public void onBindViewHolder(ExampleViewHolder holder, int position) { final ExampleModel model = mSortedList.get(position); holder.bind(model); } public void add(ExampleModel model) { mSortedList.add(model); } public void remove(ExampleModel model) { mSortedList.remove(model); } public void add(List<ExampleModel> models) { mSortedList.addAll(models); } public void remove(List<ExampleModel> models) { mSortedList.beginBatchedUpdates(); for (ExampleModel model : models) { mSortedList.remove(model); } mSortedList.endBatchedUpdates(); } public void replaceAll(List<ExampleModel> models) { mSortedList.beginBatchedUpdates(); for (int i = mSortedList.size() - 1; i >= 0; i--) { final ExampleModel model = mSortedList.get(i); if (!models.contains(model)) { mSortedList.remove(model); } } mSortedList.addAll(models); mSortedList.endBatchedUpdates(); } @Override public int getItemCount() { return mSortedList.size(); } } The only thing missing now is to implement the filtering! Implementing the filter logic To implement the filter logic we first have to define a List of all possible models. For this example I create a List of ExampleModel instances from an array of movies: private static final String[] MOVIES = new String[]{ ... }; private static final Comparator<ExampleModel> ALPHABETICAL_COMPARATOR = new Comparator<ExampleModel>() { @Override public int compare(ExampleModel a, ExampleModel b) { return a.getText().compareTo(b.getText()); } }; private ExampleAdapter mAdapter; private List<ExampleModel> mModels; private RecyclerView mRecyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main); mAdapter = new ExampleAdapter(this, ALPHABETICAL_COMPARATOR); mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this)); mBinding.recyclerView.setAdapter(mAdapter); mModels = new ArrayList<>(); for (String movie : MOVIES) { mModels.add(new ExampleModel(movie)); } mAdapter.add(mModels); } Nothing special going on here, we just instantiate the Adapter and set it to the RecyclerView. After that we create a List of models from the movie names in the MOVIES array. Then we add all the models to the SortedList. Now we can go back to onQueryTextChange() which we defined earlier and start implementing the filter logic: @Override public boolean onQueryTextChange(String query) { final List<ExampleModel> filteredModelList = filter(mModels, query); mAdapter.replaceAll(filteredModelList); mBinding.recyclerView.scrollToPosition(0); return true; } This is again pretty straight forward. We call the method filter() and pass in the List of ExampleModels as well as the query string. We then call replaceAll() on the Adapter and pass in the filtered List returned by filter(). We also have to call scrollToPosition(0) on the RecyclerView to ensure that the user can always see all items when searching for something. Otherwise the RecyclerView might stay in a scrolled down position while filtering and subsequently hide a few items. Scrolling to the top ensures a better user experience while searching. The only thing left to do now is to implement filter() itself: private static List<ExampleModel> filter(List<ExampleModel> models, String query) { final String lowerCaseQuery = query.toLowerCase(); final List<ExampleModel> filteredModelList = new ArrayList<>(); for (ExampleModel model : models) { final String text = model.getText().toLowerCase(); if (text.contains(lowerCaseQuery)) { filteredModelList.add(model); } } return filteredModelList; } The first thing we do here is call toLowerCase() on the query string. We don't want our search function to be case sensitive and by calling toLowerCase() on all strings we compare we can ensure that we return the same results regardless of case. It then just iterates through all the models in the List we passed into it and checks if the query string is contained in the text of the model. If it is then the model is added to the filtered List. And that's it! The above code will run on API level 7 and above and starting with API level 11 you get item animations for free! I realize that this is a very detailed description which probably makes this whole thing seem more complicated than it really is, but there is a way we can generalize this whole problem and make implementing an Adapter based on a SortedList much simpler. Generalizing the problem and simplifying the Adapter In this section I am not going to go into much detail - partly because I am running up against the character limit for answers on Stack Overflow but also because most of it already explained above - but to summarize the changes: We can implemented a base Adapter class which already takes care of dealing with the SortedList as well as binding models to ViewHolder instances and provides a convenient way to implement an Adapter based on a SortedList. For that we have to do two things: We need to create a ViewModel interface which all model classes have to implement We need to create a ViewHolder subclass which defines a bind() method the Adapter can use to bind models automatically. This allows us to just focus on the content which is supposed to be displayed in the RecyclerView by just implementing the models and there corresponding ViewHolder implementations. Using this base class we don't have to worry about the intricate details of the Adapter and its SortedList. SortedListAdapter Because of the character limit for answers on StackOverflow I can't go through each step of implementing this base class or even add the full source code here, but you can find the full source code of this base class - I called it SortedListAdapter - in this GitHub Gist. To make your life simple I have published a library on jCenter which contains the SortedListAdapter! If you want to use it then all you need to do is add this dependency to your app's build.gradle file: compile 'com.github.wrdlbrnft:sorted-list-adapter:0.2.0.1' You can find more information about this library on the library homepage. Using the SortedListAdapter To use the SortedListAdapter we have to make two changes: Change the ViewHolder so that it extends SortedListAdapter.ViewHolder. The type parameter should be the model which should be bound to this ViewHolder - in this case ExampleModel. You have to bind data to your models in performBind() instead of bind(). public class ExampleViewHolder extends SortedListAdapter.ViewHolder<ExampleModel> { private final ItemExampleBinding mBinding; public ExampleViewHolder(ItemExampleBinding binding) { super(binding.getRoot()); mBinding = binding; } @Override protected void performBind(ExampleModel item) { mBinding.setModel(item); } } Make sure that all your models implement the ViewModel interface: public class ExampleModel implements SortedListAdapter.ViewModel { ... } After that we just have to update the ExampleAdapter to extend SortedListAdapter and remove everything we don't need anymore. The type parameter should be the type of model you are working with - in this case ExampleModel. But if you are working with different types of models then set the type parameter to ViewModel. public class ExampleAdapter extends SortedListAdapter<ExampleModel> { public ExampleAdapter(Context context, Comparator<ExampleModel> comparator) { super(context, ExampleModel.class, comparator); } @Override protected ViewHolder<? extends ExampleModel> onCreateViewHolder(LayoutInflater inflater, ViewGroup parent, int viewType) { final ItemExampleBinding binding = ItemExampleBinding.inflate(inflater, parent, false); return new ExampleViewHolder(binding); } @Override protected boolean areItemsTheSame(ExampleModel item1, ExampleModel item2) { return item1.getId() == item2.getId(); } @Override protected boolean areItemContentsTheSame(ExampleModel oldItem, ExampleModel newItem) { return oldItem.equals(newItem); } } After that we are done! However one last thing to mention: The SortedListAdapter does not have the same add(), remove() or replaceAll() methods our original ExampleAdapter had. It uses a separate Editor object to modify the items in the list which can be accessed through the edit() method. So if you want to remove or add items you have to call edit() then add and remove the items on this Editor instance and once you are done, call commit() on it to apply the changes to the SortedList: mAdapter.edit() .remove(modelToRemove) .add(listOfModelsToAdd) .commit(); All changes you make this way are batched together to increase performance. The replaceAll() method we implemented in the chapters above is also present on this Editor object: mAdapter.edit() .replaceAll(mModels) .commit(); If you forget to call commit() then none of your changes will be applied! A: All you need to do is to add filter method in RecyclerView.Adapter: public void filter(String text) { items.clear(); if(text.isEmpty()){ items.addAll(itemsCopy); } else{ text = text.toLowerCase(); for(PhoneBookItem item: itemsCopy){ if(item.name.toLowerCase().contains(text) || item.phone.toLowerCase().contains(text)){ items.add(item); } } } notifyDataSetChanged(); } itemsCopy is initialized in adapter's constructor like itemsCopy.addAll(items). If you do so, just call filter from OnQueryTextListener: searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { adapter.filter(query); return true; } @Override public boolean onQueryTextChange(String newText) { adapter.filter(newText); return true; } }); It's an example from filtering my phonebook by name and phone number. A: Following @Shruthi Kamoji in a cleaner way, we can just use a filterable, its meant for that: public abstract class GenericRecycleAdapter<E> extends RecyclerView.Adapter implements Filterable { protected List<E> list; protected List<E> originalList; protected Context context; public GenericRecycleAdapter(Context context, List<E> list) { this.originalList = list; this.list = list; this.context = context; } ... @Override public Filter getFilter() { return new Filter() { @SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence constraint, FilterResults results) { list = (List<E>) results.values; notifyDataSetChanged(); } @Override protected FilterResults performFiltering(CharSequence constraint) { List<E> filteredResults = null; if (constraint.length() == 0) { filteredResults = originalList; } else { filteredResults = getFilteredResults(constraint.toString().toLowerCase()); } FilterResults results = new FilterResults(); results.values = filteredResults; return results; } }; } protected List<E> getFilteredResults(String constraint) { List<E> results = new ArrayList<>(); for (E item : originalList) { if (item.getName().toLowerCase().contains(constraint)) { results.add(item); } } return results; } } The E here is a Generic Type, you can extend it using your class: public class customerAdapter extends GenericRecycleAdapter<CustomerModel> Or just change the E to the type you want (<CustomerModel> for example) Then from searchView (the widget you can put on menu.xml): searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String text) { return false; } @Override public boolean onQueryTextChange(String text) { yourAdapter.getFilter().filter(text); return true; } });
{ "pile_set_name": "StackExchange" }
Q: url from another domain in my access log Most of the time when I am looking for 404 errors in my access.log, I see attempts to access something like /phpMyAdmin/scripts/setup.php. This does not bother me so much, but few days ago I was surprised because I saw this in my access.log 95.47.119.124 - - [19/Aug/2013:11:30:31 +0000] "GET http://server7.cyberpods.net/azenv.php HTTP/1.1" 404 3080 "-" "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.28) Gecko/20120306 Firefox/3.6.28 (.NET CLR 3.5.30729)" 223.220.68.129 - - [21/Aug/2013:00:55:46 +0000] "GET http://www.baidu.com/ HTTP/1.1" 404 3080 "http://www.baidu.com/" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)" What surprises me is that someone is trying to access not some relevant URL on my domain, but something absolutely different. I have two questions: How are they doing it? What is the reason behind it? A: welcome to the intertubes!!! What is the reason behind it? what you see are scans for open proxies, e.g. someone is looking if he/she/it can misuse your server to browse other sites. the first one looks very interesting, because it looks like a scanner; when checking the link (please DONT click on that with a browser), it will give back: <!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" xml:lang="en" lang="en"><head><title>AZ Environment variables 1.04</title> </head><body><pre> HTTP_USER_AGENT = Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0) HTTP_HOST = server7.cyberpods.net HTTP_CACHE_CONTROL = max-age=43200 HTTP_CONNECTION = keep-alive REMOTE_ADDR = 80.226.24.11 REMOTE_PORT = 45993 REQUEST_METHOD = GET REQUEST_URI = /azenv.php REQUEST_TIME = 1377237144 How are they doing it? by using tools and issuing the GET-request directly no magique at all :) btw, get used to it, install stuff like ossec and you'll see a lot more scanners brute-forcing your website for wp/phpmyadmin/joomla - whatever-eyploits all day long
{ "pile_set_name": "StackExchange" }
Q: reverse geocoding is not working I am writting an application which needs to find the current location. The code is returning lattitude and longitude correctly but doesnt return the real address(reverse geocoding) what could be problem. Someone please help, i am new to android. I am testing on emulator with android 4.0 updateWithNewLocation() is called from onLocationChanged(Location loc) method void updateWithNewLocation(Location location) { if (location != null) { double lat = 29.00;//location.getLatitude(); double lng = 77.0;//location.getLongitude(); longitudeLattitudeString="Lattitude :"+lat+" Longitude :"+lng; Geocoder gc = new Geocoder(this, Locale.getDefault()); try { List<Address> addresses = gc.getFromLocation(lat, lng, 1); StringBuilder sb = new StringBuilder(); //Toast.makeText(this, "Problem1", 2000).show(); if (addresses.size() > 0) { Address address = addresses.get(0); for (int i = 0; i < address.getMaxAddressLineIndex(); i++) sb.append(address.getAddressLine(i)).append("\n"); sb.append(address.getLocality()).append("\n"); Toast.makeText(this, "Problem2", 2000).show(); sb.append(address.getPostalCode()).append("\n"); sb.append(address.getCountryName()); } else { addressString=" No Location"; //Toast.makeText(this, "Problem3", 2000).show(); } addressString = sb.toString(); } catch (IOException e) { //Toast.makeText(thisContext, "Problem : InCatch", 2000).show(); } } else { longitudeLattitudeString = "No location found"; } } A: Reverse Geocoding does not work with Emulator, test on device.
{ "pile_set_name": "StackExchange" }
Q: The least populated class in y has only 1 member, which is too few. The minimum number of groups for any class cannot be less than 2 I am getting following error when I am trying to split data into train and test. I know that error is occurring because for stratify parameter I should pass categorical data only, not numeric but here OFFENSE_CODE is like a category except the categories in it are represented by number. So how can I do stratify sampling by OFFENSE_CODE. x = df.loc[:,['YEAR','MONTH','DAY_OF_WEEK']] X_train, x_test, Y_train, y_test = model_selection.train_test_split(x,df['OFFENSE_CODE'],stratify=df['OFFENSE_CODE'],random_state=2,test_size=0.3) this is sample of dataset INCIDENT_NUMBER OFFENSE_CODE OFFENSE_CODE_GROUP \ I192067438 613 Larceny I192067437 3831 Motor Vehicle Accident Response I192067435 3115 Investigate Person I192067434 3301 Verbal Disputes I192067433 3301 Verbal Disputes OFFENSE_DESCRIPTION DISTRICT REPORTING_AREA SHOOTING \ LARCENY SHOPLIFTING A1 112 NaN PROPERTY DAMAGE A1 NaN INVESTIGATE PERSON C11 336 NaN VERBAL DISPUTE E18 492 NaN VERBAL DISPUTE D14 769 NaN OCCURRED_ON_DATE YEAR MONTH DAY_OF_WEEK HOUR UCR_PART \ 2019-08-25 19:55:02 2019 8 Sunday 19 Part One 2019-08-25 18:20:00 2019 8 Sunday 18 Part Three 2019-08-25 20:45:00 2019 8 Sunday 20 Part Three 2019-08-25 20:32:00 2019 8 Sunday 20 Part Three 2019-08-25 20:30:00 2019 8 Sunday 20 Part Three STREET Lat Long Location CODES WASHINGTON ST 42.355123 -71.060880 (42.35512339, -71.06087980) tyer613a NaN 42.352389 -71.062603 (42.35238871, -71.06260312) tyer3831a NORTON ST 42.306265 -71.068646 (42.30626521, -71.06864556) tyer3115a DERRY RD 42.265933 -71.113774 (42.26593347, -71.11377415) tyer3301a PARSONS ST NaN NaN (0.00000000, 0.00000000) tyer3301a i also tried y = df.loc['OFFENSE_CODE'].apply(str) X_train, x_test, Y_train, y_test = model_selection.train_test_split(x,y,stratify=y,random_state=2,test_size=0.3) it is giving same error ValueError:The least populated class in y has only 1 member, which is too few. The minimum number of groups for any class cannot be less than 2. A: convert the column to string and then do the sampling df['OFFENSE_CODE'].apply(str) Dont foget to assign the result back df['OFFENSE_CODE'] = df['OFFENSE_CODE'].apply(str)
{ "pile_set_name": "StackExchange" }
Q: Is it possible to change button postbackurl via javascript? I have a sever control button. Is it possible to set postbackurl of the button via javascript? <asp:Button name="Button1" ID="Button1" runat="server" Text="Search" OnClick="Button1_Click" OnClientClick="return searchSubmit();" PostBackUrl="" > A: By default, any asp.net page will automatically have it's own form tag that posts to its self. In javascript, you can change the action of the form to post to any other page you want. So you could update the form's action when you click the button, and it will then post to the updated action. e.g. with some jquery $(function(){ $('#btnsubmit').click(function(){ $('#myform').attr("action", "updatedurl.aspx"); }); });
{ "pile_set_name": "StackExchange" }
Q: Как добиться однородного фона (TextView внутри CardView)? В моей программе мне нужно использовать TextView внутри Cardview из библиотеки поддержки. Нужны скругленные углы. Нужно иметь возможность изменять цвет элемента программно. Следующий код: <android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="2" android:layout_margin="2dp" card_view:cardElevation="5dp" card_view:cardCornerRadius="15dp" card_view:cardBackgroundColor="@color/colorPrimary" > <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="31" android:textColor="#0f0" android:textSize="150sp" android:gravity="center_vertical|center_horizontal" /> </android.support.v7.widget.CardView> приводит к такому результату: Эти странные полосы и черточки меня совершенно не устраивают. Следующий же код: <android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="2" card_view:cardElevation="5dp" card_view:cardCornerRadius="15dp" > <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="31" android:textColor="#0f0" android:textSize="150sp" android:gravity="center_vertical|center_horizontal" android:background="@color/colorPrimary" /> </android.support.v7.widget.CardView> приводит к другому результату: Второй результат мне не подходит из-за белых краев. Третья моя попытка: Создала файл rownded_corners.xml в папке drawable: <?xml version="1.0" encoding="utf-8"?> <shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="@color/colorPrimary" /> <corners android:radius="15dp" /> </shape> и в разметке второй попытки задала его в качестве фона TextView: android:background="@drawable/rounded_corner" Вот что получилось: Здесь меня не устраивает белая рамка. В общем, вопрос: Как мне добиться однородного цвета, заполняющего весь CardView, и сохранить возможность программно установить другой цвет. UPDATE. Описанное в вопросе недоразумение уже разрешилось. См. мой ответ. A: Представляете, описанное в вопросе недоразумение было вызвано тем, что используемый мною цвет (colorPrimary) был полупрозрачным (что-то вроде #a03F51B5) и через него была видна "кухня" построения CardView. Я изменила его на #3F51B5 и первый вариант дал желаемый результат даже без атрибута, предложенного @ЮрийСПб.
{ "pile_set_name": "StackExchange" }
Q: Error message when using find -exec to copy files I use the find command to copy some files from one destination to another. If I do $ mkdir dir1 temp $ touch dir1/dir1-file1 $ find . -iname "*file*" -exec cp {} temp/ \; everything works fine as expected, but if I do $ mkdir SR0a temp $ touch SR0a/SR0a-file1 $ find . -iname "*file*" -exec cp {} temp/ \; > cp: `./temp/SR0a-file1' and `temp/SR0a-file1' are the same file I get an error message. I do not understand this behavior. Why do I get an error by simply changing names? A: That is because find searchs in SR0a/ folder at first, and then in temp/, and since you have copied into it the file, find founds it again in temp/ folder. It seems that find uses crafty sorting so it just should be take into account on use of find: $ mkdir temp dir1 SR0a DIR TEMP $ find . . ./TEMP ./SR0a ./temp ./dir1 ./DIR So in case the dir1/ find founds the it at first, and this don't make such problems, let see the search sequence: temp/ dir1/ When you search with SR0a the sequence is: SR0a/ temp/ so found file is being copied into temp before searching it. To fix it, either move temp/ folder outside the current one: $ mkdir SR0a ../temp $ touch SR0a/SR0a-file1 $ find . -iname "*file*" -exec cp {} ../temp/ \; or use pipe to separate find and copy procedures: $ find . -iname "*file*" | while read -r i; do cp "$i" temp/; done
{ "pile_set_name": "StackExchange" }
Q: ndk-build doesn't find hidraw.h for 32bit ABIs I am trying to build a native app to communicate with a device over hidraw. While trying to build app through ndk-build, I get following error: jni/daemon.c:15:26: fatal error: linux/hidraw.h: No such file or directory #include <linux/hidraw.h> ^ compilation terminated. make: *** [obj/local/armeabi-v7a/objs/hidrawdaemon/daemon.o] Error 1 Now, I checked with other ABIs, and I found that build fails for all 32 bit ABIs (armeabi-v7a armeabi x86 mips) but succeeds for all 64 bit ABIs (arm64-v8a x86_64 mips64) I also checked that my ndk (r10e) contains hidraw.h for all available platforms: gps@gps-HP-ProBook-4540s:~/Android/android-ndk-r10e/platforms/android-21$ ls arch-arm arch-arm64 arch-mips arch-mips64 arch-x86 arch-x86_64 gps@gps-HP-ProBook-4540s:~/Android/android-ndk-r10e/platforms/android-21$ find . -name hidraw* ./arch-x86_64/usr/include/linux/hidraw.h ./arch-arm/usr/include/linux/hidraw.h ./arch-mips/usr/include/linux/hidraw.h ./arch-mips64/usr/include/linux/hidraw.h ./arch-arm64/usr/include/linux/hidraw.h ./arch-x86/usr/include/linux/hidraw.h gps@gps-HP-ProBook-4540s:~/Android/android-ndk-r10e/platforms/android-21$ Can anyone point me to reason for build failure, and how to go about fixing this. A: This seems like you're targeting an older version of android than 21 - check what you've set as APP_PLATFORM in jni/Application.mk, or what is set in AndroidManifest.xml. The reason why it's failing only on 32 bit platforms, is that for the 64 bit platforms, android-21 is the first version where they're supported at all, so if you target an older version, the 64 bit parts will still be built against android-21 headers and libs. (Similarly, x86 and mips were added in android-9.) So in this case, since linux/hidraw.h is available only since android-21, make sure you set this as your minimum platform version.
{ "pile_set_name": "StackExchange" }