text
stringlengths
64
89.7k
meta
dict
Q: Ajax request not going through I m working on a project and this is my code according to my research this should go through but its not Can some please have a look at this function check_address1(){ var data = { 'full_name1' : jQuery('#full_name1').val(), 'street1' : jQuery('#street1').val(), 'street21' : jQuery('#street21').val(), 'city1' : jQuery('#city1').val(), 'county1' : jQuery('#county1').val(), 'postcode1' : jQuery('#postcode1').val(), 'country1' : jQuery('#country1').val(), }; jQuery,ajax({ url : '/project/admin/parsers/check_address1.php', method : 'post', data : data, success : function(data){ if(data != 'good'){ Query('#payment-errors').html(data); } if (data == 'good') { jQuery('#payment-errors').html(""); jQuery('#step1').css("display",'none'); jQuery('#step2').css("display",'none'); jQuery('#step3').css("display",'block'); jQuery('#next_button').css("display",'none'); jQuery('#take1').css("display",'none'); jQuery('#take2').css("display",'inline-block'); jQuery('#next_button').css("display",'none'); jQuery('#next_button1').css("display",'none'); jQuery('#checkout_button')css("display",'inline-block'); jQuery('#checkoutModalLabel').html("Enter your card details") } }, error : function(){alert("Something Went Wrong");}, }); } Thank you in advance A: You have a couple of errors in your code jQuery,ajax({ should be jQuery.ajax({ Query('#payment-errors').html(data); should be jQuery('#payment-errors').html(data); missing . in jQuery('#checkout_button')css("display",'inline-block'); Here is correct code function check_address1(){ var data = { 'full_name1' : jQuery('#full_name1').val(), 'street1' : jQuery('#street1').val(), 'street21' : jQuery('#street21').val(), 'city1' : jQuery('#city1').val(), 'county1' : jQuery('#county1').val(), 'postcode1' : jQuery('#postcode1').val(), 'country1' : jQuery('#country1').val(), }; jQuery.ajax({ url : '/project/admin/parsers/check_address1.php', method : 'post', data : data, success : function(data){ if(data != 'good'){ jQuery('#payment-errors').html(data); } if (data == 'good') { jQuery('#payment-errors').html(""); jQuery('#step1').css("display",'none'); jQuery('#step2').css("display",'none'); jQuery('#step3').css("display",'block'); jQuery('#next_button').css("display",'none'); jQuery('#take1').css("display",'none'); jQuery('#take2').css("display",'inline-block'); jQuery('#next_button').css("display",'none'); jQuery('#next_button1').css("display",'none'); jQuery('#checkout_button').css("display",'inline-block'); jQuery('#checkoutModalLabel').html("Enter your card details") } }, error : function(){alert("Something Went Wrong");}, }); }
{ "pile_set_name": "StackExchange" }
Q: Spring Security logout success url to another host is that possible to make Spring Security 3.2.7.RELEASE redirect user to another host after logout? I can't force it to use another host. I'm using some kind of SSO access system and that might be a problem. Example: My app is started on http://myAppUrl:8080/webapp1/ Users access it through http://ssoAccess:80/webapp1/ and that leads to real url, but in browser i still see ssoAccess url all the time (like some kind of proxy) I want to make logout button from http://myAppUrl:8080/webapp1/logout.xhtml to logout then redirect to http://ssoAccess:80/appList When logout-success-url is set to "http://ssoAccess:80/appList" it redirects to http://ssoAccess:80/webapp1/http://ssoAccess:80/appList which is obviously not correct url returning 404. I tried logout-success-handler as well, but still same problem. I also tried to make @Controller that has method returning "redirect:http://ssoAccess:80/appList" on endpoint that is pointed by logout-success-url. Still no luck. I'm also using JSF. Please help! A: A simple trick is that you create a logout.xhtml page in webapp1 that redirect's to appList. logout.xhtml: <script language="javascript"> window.location.href = "http://ssoAccess:80/appList" </script>
{ "pile_set_name": "StackExchange" }
Q: Call to undefined function apache_request_headers() I've just switched my scripts to a different server. On the previous server this worked flawlessly, and now that I've switched them to a different server, I can't understand the problem. I'm not sure it would help, but here's the relevant code. $headers = apache_request_headers(); PHP Version is: PHP 5.3.2 A: You can use the following replacement function: <?php if( !function_exists('apache_request_headers') ) { /// function apache_request_headers() { $arh = array(); $rx_http = '/\AHTTP_/'; foreach($_SERVER as $key => $val) { if( preg_match($rx_http, $key) ) { $arh_key = preg_replace($rx_http, '', $key); $rx_matches = array(); // do some nasty string manipulations to restore the original letter case // this should work in most cases $rx_matches = explode('_', $arh_key); if( count($rx_matches) > 0 and strlen($arh_key) > 2 ) { foreach($rx_matches as $ak_key => $ak_val) $rx_matches[$ak_key] = ucfirst($ak_val); $arh_key = implode('-', $rx_matches); } $arh[$arh_key] = $val; } } return( $arh ); } /// } /// ?> Source: PHP Manual A: From the docs, before the release of PHP 5.4.0: This function is only supported when PHP is installed as an Apache module. PHP 5.4.0 and later support this function unconditionally. Said docs also include replacement functions that mimic the functionality of apache_request_headers by stepping through $_SERVER. A: if php is installed as an Apache module: apache_request_headers()["Authorization"]; else, go to .htaccess file and add: SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1 You can then access request headers using any of these: $_SERVER["HTTP_AUTHORIZATION"]; // using super global OR $app->request->headers("Authorization"); // if using PHP Slim
{ "pile_set_name": "StackExchange" }
Q: Why does my game display the wrong "required Android version" on Google Play? I'm porting a Unity game to Android, and I've set up the "Minimum API Level" in the Player settings to "2.3.3 (API level 10)". However, on the store, it says "Requires Android: 1.6 and up". On the Google Developer Console I didn't find this setting, so I guess the store is just trying to "guess" it examining the application, and failing. Did I miss something? A: You have probably published your APK as Alpha or Beta. This is a known bug and Google Play store will incorrectly show "Requires Android: 1.6 and up". When you deploy your APK as production, it will show the correct number. You can check your apk's minSdkVersion by the command-line tool aapt (inside sdk/platform-tools) aapt d badging game.apk or aapt l -a game.apk But you should put the correct setting to your manifest in any case: <uses-sdk android:minSdkVersion="A" android:targetSdkVersion="B" />
{ "pile_set_name": "StackExchange" }
Q: Can't stop animation fro cycling I have three images in a row. I want to enlarge the one that the mouse is over until the mouse is moved off of it. This sort of works in my jsfiddle but, as you can see, the animation doesn't stop after enlarging. The other threads on this problem say to set the iteration count and forwards options, which I've done. The only other solution I could find was to use javascript to control it. Is there a way to do this with just css? Here's my code: <style> #set2 {margin-left:40px; display:inline-block} #set2:hover { -webkit-animation: enlarge 5s; animation: enlarge 5s; animation-fill-mode: forwards; animation-iteration-count: 1; } @-webkit-keyframes enlarge { 25% { -webkit-transform: scale(1.5); transform: scale(1.5); } } </style> <div class="banner_set"> <ul class="nav"> <li id="set2" class="nav-items"><a href="example.com"><img src="example1.jpg"></a></li> <li id="set2" class="nav-items"><a href="example.com"><img src="example2.jpg"></a></li> <li id="set2" class="nav-items"><a href="example.com"><img src="example3.jpg"></a></li> </ul> </div> A: Is there a specific reason you're using the animation approach rather than a transition? Since the desired behavior is to toggle between two animated states, perhaps the transition is an easier way to approach it. Using your example code: .nav {margin:0; padding-top:5px;overflow:hidden} .nav-items {border:1px solid black} .nav-items {margin-left:0px; display:inline-block; overflow: hidden;} .nav-items:hover img { box-shadow: 0px 0px 150px #000000; z-index: 2; -webkit-transition: all 500ms ease-in; -webkit-transform: scale(2.1); -ms-transition: all 500ms ease-in; -ms-transform: scale(2.1); -moz-transition: all 500ms ease-in; -moz-transform: scale(2.1); transition: all 500ms ease-in; transform: scale(2.1); } .nav-items img { -webkit-transition: all 200ms ease-in; -webkit-transform: scale(1); -ms-transition: all 200ms ease-in; -ms-transform: scale(1); -moz-transition: all 200ms ease-in; -moz-transform: scale(1); transition: all 200ms ease-in; transform: scale(1); } <div class="banner_set"> <ul class="nav"> <li id="0" class="nav-items small_0"><a href="example.com"><img src="http://placehold.it/200x200"></a></li> <li id="1" class="nav-items small_1"><a href="example.com"><img src="http://placehold.it/200x200"></a></li> <li id="2" class="nav-items small_2"><a href="example.com"><img src="http://placehold.it/200x200"></a></li> </ul> </div>
{ "pile_set_name": "StackExchange" }
Q: User Defined Functions in Excel and Speed Issues I have an Excel model that uses almost all UDFs. There are say, 120 columns and over 400 rows. The calculations are done vertically and then horizontally --- that is first all the calculations for column 1 are done, then the final output of column 1 is the input of column 2, etc. In each column I call about six or seven UDFs which call other UDFs. The UDFs often output an array. The inputs to each of the UDFs are a number of variables, some range variables, some doubles. The range variables are converted to arrays internally before their contents are accessed. My problem is the following, I can build the Excel model without UDFs and when I run simulations, I can finish all computations in X hours. When I use UDFs, the simulation time is 3X hours or longer. (To answer the obvious question, yes, I need to work with UDFs because if I want to make small changes to the model (like say add another asset type (it is a financial model)) it takes nearly a day of remaking the model without UDFs to fit the new legal/financial structure, with UDFs it takes about 20 minutes to accommodate a different financial structure.) In any case, I have turned off screen updating, there is no copying and pasting in the functions, the use of Variant types is minimal, all the data is contained in one sheet, i convert all range type variables to arrays before getting the contents. What else can I do other than getting a faster computer or the equivalent to make the VBA code/Excel file run faster? Please let me know if this needs more clarification. Thanks! A: Couple of general tips. Take your function and work out where the bottlenecks really are. See this question for the use of timer in excel. I'm sure there are VBA profilers out there... but you probably don't need to go that far. (NB: do this with one cell of data first...) Think about your design... 400x120 cells of data is not a lot. And for it to take hours that must be painful. (In the past i've cracked it after waiting a minute for 1,000s of VLOOKUPS() to return) anyway maybe instead of having having a stack of UDFs why not have a simple subroutine that for..each through the range and does what you need it to do. 48,000 cells could take seconds or maybe just minutes. You could then associate the subroutine with a button or menu item for the user. Out of interest i had a quick look at option 2 and created MyUDF(), using the sub DoMyUDF() to call it for the active selection worked 10x faster for me, than having the UDF in each and every cell. Option Explicit Function MyUDF(myVar As Variant) As Variant MyUDF = myVar * 10 End Function Sub DoMyUDF() Dim r As Range Dim c As Variant Dim t As Single t = Timer If TypeName(Selection) <> "Range" Then Exit Sub End If Set r = Selection.Cells Application.DisplayStatusBar = True For Each c In r c.Value = MyUDF(c.Value) Application.StatusBar = "DoMyUDF(): " & Format(Timer - t, "#0.0000ms") Next Debug.Print "DoMyUDF(): " & Format(Timer - t, "#0.0000ms") End Sub If you replace MyUDF() with your UDF this may only save you 4.5 minutes... but it's possible there are some other economies you can build in. Especially if you are repeating the same calcs over and over again. A: There is a slowdown bug in the way Excel handles UDFs. Each time a UDF gets calculated Excel refreshes the VBE title bar (you can see it flicker). For large numbers of UDFs this is very slow. The bypass is very simple in Manual Calculation mode: just initiate the calculation from VBA using something like Application.Calculate (you can trap F9 etc with OnKey). see http://www.decisionmodels.com/calcsecretsj.htm for some more details. A: Have you considered replacing the UDF (which gets called once per output cell) with a macro, which can operate on a range of cells in a loop? UDF setup/teardown is very slow, and anything each UDF call does in common with other UDFs (reading from overlapping inputs, for example) becomes extra effort. I've been able to improve performance 10-50x doing this--had a situation less than a month ago involving a spreadsheet with 4000-30000 UDF calls, replaced them with a single macro that operates on a few named ranges.
{ "pile_set_name": "StackExchange" }
Q: how to define a text field value in code <form id="form2" name="form2" action=""> <div class="form_colour" id="formcolour"><img src="../Images/red_car.jpg" alt="" width="370" height="124" />This car is <label for="textarea"></label> <input name="text_1" type="text" class="form_colour" id="text_1" /> </div> <p>&nbsp;</p> <p><img src="../Images/green_car.jpg" width="370" height="124" />This car is <input name="text_2" type="text" class="form_colour" id="text_2" /> </p> <p> <img src="../Images/Yellow_car.jpg" width="370" height="124" />This car is <input name="text_3" type="text" class="form_colour" id="text_3" maxlength="8" /> </p> <p> <input name="confirm" type="button" class="form_colour" id="confirm" value="Confirm" /> </p> </form> I currently have the following code for a form which has 3 text fields in them(Code for the form is above this and the Javascript code is below this text). My aim is based on the input of the text values the user will either get a message and stay on the page or if they are correct get a message and go to another page. I did this previously for drop down lists. and all i did was just change the variables from the drop down list names to the text field names. Now when i run this, nothing happens, do i need to do something more ??? </script> <script type="text/javascript"> function checkValues() { // this line must be within the script tags var a = document.form2.text_1.value; var b = document.form2.text_2.value; var c = document.form2.text_3.value; if (a == "red" && b == "green" && c == "yellow"){ alert ("Correct you have won press OK for your Reward!") window.location.href = "Reward.html"; // redirect to new page } else { alert ("Not right Please try again!"); window.location.href = "Money_Match.html"; } } </script> </script> A: you haven't called your script on button click, check working example here http://jsfiddle.net/3CgcH/7/ you need to specify onclick handler for button which will call checkValues function <input name="confirm" type="button" class="form_colour" id="confirm" value="Confirm" onclick="checkValues();" /> more proper way would be to use addEventListener and attachEvent to register events on html elements
{ "pile_set_name": "StackExchange" }
Q: Difference between use of while() and sleep() to put program into sleep mode I have created a shared object and access it from two different program and measuring the time. DATA array is the shared object between two processes. Case 1: Use of while inside program1 program1 : access shared DATA array ;// to load into memory and avoid page fault during access time calculation start=timer; access shared DATA array end=timer; Time_needed= end-start printf("Inside Program1, Time1=%d\n",Time_needed); start=timer; access shared DATA array end=timer; Time_needed= end-start printf("Inside Program1, Time2=%d\n",Time_needed); while(1){}; // I replace this by sleep(1000) in CASE-2 Program2 : access shared DATA array ;// to load into memory and avoid page fault during access time calculation start=timer; access shared DATA array end=timer; Time_needed= end-start printf("Inside Program2, Time1=%d\n",Time_needed); start=timer; access shared DATA array end=timer; Time_needed= end-start printf("Inside Program2, Time1=%d\n",Time_needed); OUTPUT : First I run program1, then Program2 Inside Program1, Time1 = 17620 Inside Program1, Time1 = 17680 Inside Program2, Time1 = 7620 Inside Program2, Time1 = 7600 Case 2: Use of sleep() inside program1 program1 : access shared DATA array ;// to load into memory and avoid page fault during access time calculation start=timer; access shared DATA array end=timer; Time_needed= end-start printf("Inside Program1, Time1=%d\n",Time_needed); start=timer; access shared DATA array end=timer; Time_needed= end-start printf("Inside Program1, Time2=%d\n",Time_needed); sleep(1000); Program2 : access shared DATA array ;// to load into memory and avoid page fault during access time calculation start=timer; access shared DATA array end=timer; Time_needed= end-start printf("Inside Program2, Time1=%d\n",Time_needed); start=timer; access shared DATA array end=timer; Time_needed= end-start printf("Inside Program2, Time1=%d\n",Time_needed); OUTPUT : First I run program1, then Program2 Inside Program1, Time1 = 17620 Inside Program1, Time1 = 17680 Inside Program2, Time1 = 17620 Inside Program2, Time1 = 17600 From the output in case -1, I can say shared data DATA array is loaded into memory/cache by 1st program and second program access it from cache. Whereas this also true for CASE-2, but the result looks like it is flushed out from cache while Program1 goes into sleep. I am using GCC under linux. Any clue ? Thanks in advance . A: You didn't describe exactly how you run the different versions (different processes?), but assuming they're sequential - It is possible that you're seeing the affect of sleep() It depends of course on the exact implementation and HW, but it's very likely to send your CPU into some power-saving/sleep state (that's what it's designed for). If that's the case, then the core caches will have to be flushed as part of the process, and you'll wake-up with cold caches. The whie loop on the other hand is intended to do a busy wait loop while grinding your CPU and keeping it alive (along with the caches), unless you happen to get a context switch along the way. The exact details would again depend on implementation, on x86 you can use inline assembly to invoke monitor+mwait instructions that allow you to specify the exact C-state depth you want to achieve. The deeper it is, the more caches will get closed (mostly relevant for the L3).
{ "pile_set_name": "StackExchange" }
Q: How to get system time? I want to get the current year, month, day, hour, minute second, and millisecond in javascript. I am also using p5.js, if that has any helper methods. This is what I want: Year=2018 Month=4 Day=20 Hour=10 Minute=15 Second=25 Millisecond=236 A: Questions like this are best answered by reading through the P5.js reference. Specifically, look at the Time and Date section, which lists exactly the functions you're looking for.
{ "pile_set_name": "StackExchange" }
Q: Python3 pandas: data frame grouped by a columns(such as name), then extract a number of rows for each group There is data frame called df as following: name id age text a 1 1 very good, and I like him b 2 2 I play basketball with his brother c 3 3 I hope to get a offer d 4 4 everything goes well, I think a 1 1 I will visit china b 2 2 no one can understand me, I will solve it c 3 3 I like followers d 4 4 maybe I will be good a 1 1 I should work hard to finish my research b 2 2 water is the source of earth, I agree it c 3 3 I hope you can keep in touch with me d 4 4 My baby is very cute, I like him The data frame is grouped by name, then I want to extract a number of rows by row index(for example: 2) for the new dataframe: df_new. name id age text a 1 1 very good, and I like him a 1 1 I will visit china b 2 2 I play basketball with his brother b 2 2 no one can understand me, I will solve it c 3 3 I hope to get a offer c 3 3 I like followers d 4 4 everything goes well, I think d 4 4 maybe I will be good df_new = (df.groupby('screen_name'))[0:2] But there is error: hash(key) TypeError: unhashable type: 'slice' A: Try using head() instead. import pandas as pd from io import StringIO buff = StringIO(''' name,id,age,text a,1,1,"very good, and I like him" b,2,2,I play basketball with his brother c,3,3,I hope to get a offer d,4,4,"everything goes well, I think" a,1,1,I will visit china b,2,2,"no one can understand me, I will solve it" c,3,3,I like followers d,4,4,maybe I will be good a,1,1,I should work hard to finish my research b,2,2,"water is the source of earth, I agree it" c,3,3,I hope you can keep in touch with me d,4,4,"My baby is very cute, I like him" ''') df = pd.read_csv(buff) using head() instead of [:2] then sorting by name df_new = df.groupby('name').head(2).sort_values('name') print(df_new) name id age text 0 a 1 1 very good, and I like him 4 a 1 1 I will visit china 1 b 2 2 I play basketball with his brother 5 b 2 2 no one can understand me, I will solve it 2 c 3 3 I hope to get a offer 6 c 3 3 I like followers 3 d 4 4 everything goes well, I think 7 d 4 4 maybe I will be good
{ "pile_set_name": "StackExchange" }
Q: Convert Node.js files to ES5 I have node.js script files which I am trying to re-use inside an ASP.NET application on IE 11. I follow below steps to use them on IE 11: Create a bundle file using browserify: browserify Module.js --standalone mymodule -o bundle.js Convert the ES6 version of bundle.js to ES5 by manually converting it using https://babeljs.io/repl. Save the converted ES5 script and include the saved .js file as in ASP.NET application. Is there anyway I can automate step 2? Is there any better way to convert Node.js files to ES5? A: Since you use Browserify, you can use Babelify which is a Browserify transform: npm install --save-dev babelify @babel/core @babel/preset-env browserify Module.js --standalone mymodule -o bundle.js -t [ babelify --presets [ @babel/preset-env ] ] See the babel-preset-env documentation to see how to define your target ("ie": 11), by default all ES2015+ syntax will be transformed.
{ "pile_set_name": "StackExchange" }
Q: How to get the release value from an RPM -qi command I'm on RedHat, I need to get the value in the Release field. Take "wget" for an example. Here's the output I'm expected to get WGET: 1.4.el6 Here's the output from rpm -qi wget [luke@machine ~]# rpm -qi wget Name : wget Relocations: (not relocatable) Version : 1.12 Vendor: Red Hat, Inc. Release : 1.4.el6 Build Date: Mon May 10 14:56:18 2010 Install Date: Wed Oct 3 16:48:58 2012 Build Host: x86-012.build.bos.redhat.com Group : Applications/Internet Source RPM: wget-1.12-1.4.el6.src.rpm Size : 1877597 License: GPLv3+ and GFDL Signature : RSA/8, Mon Aug 16 21:21:35 2010, Key ID 199e2f91fd431d51 Packager : Red Hat, Inc. <http://bugzilla.redhat.com/bugzilla> URL : http://wget.sunsite.dk/ Summary : A utility for retrieving files using the HTTP or FTP protocols How can I write a script to extract the "1.4.el6" from the Release field. I currently have #!/bin/bash RELwg= rpm -qi wget # Do string manipulation of $RELwg here wg="WGET: " echo $wg$RELwg But here's the output I get; Release : 1.4.el6 Build Date: Mon May 10 14:56:18 2010 WGET: I know I have to do some string extraction, to get the number. Get the index of the 1, seems to always be constant at 15 Get the index of the B in Build Date Get the sub string inbetween 15 and whatever B is Removing the space between "RELwg= rpm -qi wget" in my current script, I just get an error saying that ./GetRPMVersions.sh: line 12: -qi: command not found Mainly my current predicament is to addign the ouput of rpm -qi wget | grep Release to a variable. Any input on the string manipulation is welcome. A: something like RELwg=$(rpm -qi wget | awk -- '/^Release/ { print $3 }')
{ "pile_set_name": "StackExchange" }
Q: Any difference between importing whole file and importing only class with show in Dart? Instead of writing : import 'package:flutter_platform_widgets/flutter_platform_widgets.dart'; which exports a dozen of files, I would like to write : import 'package:flutter_platform_widgets/flutter_platform_widgets.dart' show PlatformAlertDialog, PlatformCircularProgressIndicator, PlatformDialogAction, PlatformText, showPlatformDialog; because I'm only using these components. However this is quite tidious (reminds me of Typescript's endless imports) and goes against Dart's principle of briefness. Imports snippets in VSCode uses the first solution, but is there any notable difference, for example in terms of performance? Is there some kind of good practice? I cannot find anything in official guidelines. A: There is no impact on performance. The reason of using show is to reduce chances of confusion when importing classes from different packages. For instance: Let's say abc.dart has 2 classes class One {} class Two {} And xyz.dart also has 2 classes: class One {} class Three {} And you are importing both package in your file import 'abc.dart'; import 'xyz.dart'; Say, you only want to use class One from abc.dart, so when you use One it could be from abc.dart or xyz.dart. So to prevent One coming from xyz.dart you'd use: import `xyz.dart` show Three // which means only `Three` class can be used in your current file from xyz.dart package
{ "pile_set_name": "StackExchange" }
Q: static unordered_map is erased when putting into different compilation unit in XCode I have a static unordered_map in my class C. I experience difference in behaviour if I put my class definition and declaration in different files from the file containing function main. The thing is that I observed that if the class C is in the same compilation unit as function main, all is well, I see only once the text "new string created: c". However if I split my code into three files (see the listing below), I see "new string created: c" twice which means that my static unordered_map is wiped right before entering main. My question would be: why does this happen? (The difference only happens when compiling with Apple LLVM compiler 4.1. I have tested it with g++4.7 -std=c++11 and the split code works out just fine.) Thanks in advance for any ideas! // would go to My_header.h #include <unordered_map> #include <string> #include <iostream> using namespace std; class C{ public: C(const string & s); private: static unordered_map<string, string*> m; string *name; }; // would go to My_code.cpp // (when separated, add #include "My_header.h") unordered_map<string, string*> C::m; C::C(const string & s): name(NULL) { string*& rs = m[s]; if(rs) { name = rs; } else { cout<<"new string created: "<<s<<endl; rs = name = new string(s); } } // would go to main.cpp // (when separated, add #include "My_header.h") C c("c"); int main(int argc, const char * argv[]) { cout << "main" << endl; C c1("c"); } A: The order of initialization of global objects is defined only within one translation unit. Between different translation the order isn't guaranteed. Thus, you probably see behavior resulting from the std::unordered_map being accessed before it is constructed. The way to avoid these problems is to not use global objects, of course. If you realky need to use a global object it is best to wrap the object by a function. This way it is guaranteed that the object is constructed the first time it is accessed. With C++ 2011 the construction is even thread-safe: T& global() { static T rc; return rc; }
{ "pile_set_name": "StackExchange" }
Q: Implementing Joomla update system for extension hosted on Github I have a number of Joomla extensions on the JED. I haven't set up a site for them; I'm just pointing JED at their location on Github. I've also never implemented auto-update for any of them. JED now has a new policy that extensions must implement auto-update, so I'm going to have to think about how to do this, and I'd like to ask here for some advice. I've avoided doing the updates before mainly because, having the extension served directly from a Github repo, I didn't know where I could put the update feed XML file. Is it acceptable for the update XML to be part of the main repository? If so, where in the repo should I put it? And also, what URL would I give for it to the JED? I assume I'd have to give a link directly to the master branch; is that right? Does anyone have any tips or other relevant info on managing this? Thank you! A: Yes, you can put the update.xml in the main repository. As for the link to provide JED, you'll need to open the file on Github, then click "Raw", so you URL will look something like this: https://raw.githubusercontent.com/USER/REPO-NAME/master/path-to-file/update.xml And also be sure to reference this URL in your extension's XML file too.
{ "pile_set_name": "StackExchange" }
Q: Regular expression to extract special number How can i write a regular expression to extract the "integer+W" value 100W abc 60W cde 40W G9 60W CA2 The out put will be 100W 60W 40W 60W A: [0-9]+W That should do it. Here's a breakdown, in case you want it: [0-9] (matches the range 0-9 [aka the digits]) + (asks for 1 or more of the previous match [one or more digits, aka an integer]) W (self-explanatory)
{ "pile_set_name": "StackExchange" }
Q: make webcam device invisible to a process Some context: I have an application that opens the first webcam device on Windows 10 64bit (whatever index 0 is during enumeration of devices) and does some processing on the frames. The application's source code is not accessible. Question: I need to make this application to work with two webcams at the same time. I thought maybe there is a way to do the following: hide webcam 2 run application (picks up webcam 1) hide webcam 1, unhide webcam 2 run application (picks up webcam 2) Is there a way to do this without interrupting camera's operation? Note that both applications are running at the same time so hard-disabling a camera is not an option. Calling either a Win32 api or doing this in PowerShell is acceptable. Thanks! A: Thanks to comments on my original question, I managed to solve my problem by hooking into CM_Get_Device_Interface_List_ExW Win32 API call. I had to verify what API is being called, so I used and API tracer tool (API monitor v2 64bit). Debugger should work too but for some reason my VS debugger did not show me any symbols (possibly missing pdbs). The original process I tried to hook into is written in C# so I hooked into the call via an injected C# DLL containing EasyHook. Here is my code snippet (actual injection code left out): using System; using System.Runtime.InteropServices; using EasyHook; public class HookDevices : IEntryPoint { LocalHook FunctionLocalHook; // construct this to hook into calls HookDevices() { try { FunctionLocalHook = LocalHook.Create( LocalHook.GetProcAddress("CfgMgr32.dll", "CM_Get_Device_Interface_List_ExW"), new FunctionHookDelegate(CM_Get_Device_Interface_List_Ex_Hooked), this); FunctionLocalHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 }); } catch (Exception ExtInfo) { Debug.LogException(ExtInfo); return; } } [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true)] delegate uint FunctionHookDelegate( ref Guid interfaceClassGuid, string deviceID, IntPtr buffer, uint bufferLength, uint flags, IntPtr hMachine); [DllImport("CfgMgr32.dll", CharSet = CharSet.Unicode, SetLastError = true, CallingConvention = CallingConvention.StdCall)] static extern uint CM_Get_Device_Interface_List_ExW( ref Guid interfaceClassGuid, string deviceID, IntPtr buffer, uint bufferLength, uint flags, IntPtr hMachine); // this is where we are intercepting all API accesses! static uint CM_Get_Device_Interface_List_Ex_Hooked( ref Guid interfaceClassGuid, string deviceID, IntPtr buffer, uint bufferLength, uint flags, IntPtr hMachine) { // pass-through original API uint ret = CM_Get_Device_Interface_List_ExW( ref interfaceClassGuid, deviceID, buffer, bufferLength, flags, hMachine); // do custom logic here and re-arrange "buffer" return ret; } }
{ "pile_set_name": "StackExchange" }
Q: Moving automatically spam messages to a folder in Postfix My problem is that I want to automatically to move spam messages to a folder and not sure how. I have a linux box giving email access. MTA is Postfix, IMAP is Courier. As webmail client I use Squirrelmail. To filter SPAM I use Spamassassin and is working ok. Spamassasin is overwriting subjects with [--- SPAM 14.3 ---] Viagra... Also is adding headers: X-Spam-Flag: YES X-Spam-Checker-Version: SpamAssassin 3.2.5 (2008-06-10) on xxxx X-Spam-Level: ************** X-Spam-Status: Yes, score=14.3 required=2.0 tests=BAYES_99, DATE_IN_FUTURE_24_48,HTML_MESSAGE,MIME_HTML_ONLY,RCVD_IN_PBL, RCVD_IN_SORBS_WEB,RCVD_IN_XBL,RDNS_NONE,URIBL_RED,URIBL_SBL autolearn=no version=3.2.5 X-Spam-Report: * 0.0 URIBL_RED Contains an URL listed in the URIBL redlist * [URIs: myimg.de] * 3.5 BAYES_99 BODY: Bayesian spam probability is 99 to 100% * [score: 1.0000] * 0.9 RCVD_IN_PBL RBL: Received via a relay in Spamhaus PBL * [113.170.131.234 listed in zen.spamhaus.org] * 3.0 RCVD_IN_XBL RBL: Received via a relay in Spamhaus XBL * 0.6 RCVD_IN_SORBS_WEB RBL: SORBS: sender is a abuseable web server * [113.170.131.234 listed in dnsbl.sorbs.net] * 3.2 DATE_IN_FUTURE_24_48 Date: is 24 to 48 hours after Received: date * 0.0 HTML_MESSAGE BODY: HTML included in message * 1.5 MIME_HTML_ONLY BODY: Message only has text/html MIME parts * 1.5 URIBL_SBL Contains an URL listed in the SBL blocklist * [URIs: myimg.de] * 0.1 RDNS_NONE Delivered to trusted network by a host with no rDNS I want to automatically to move spam messages to a folder. Ideally (not sure if possible) only to move messages with puntuation 5.0 or more to folder.. spam between 2.0 and 5.0 I want to be stored in Inbox. (I plan later to switch autolearn on) After reading a lot in procmail, postfix and spamassasin sites and googling a lot (lot of outdated howtos) I found two solutions but not sure which is the best or if there is another one: Put a rule in squirrelmail (dirty solution?) Use Procmail Which is the best option? Do you have any updated howto about it? Thanks A: I'm using a fairly similar setup (Postfix/SpamAssassin with amavisd-new/Dovecot) and I use maildrop as a delivery agent with filtering capabilities. Why not procmail? Simply because I find maildrop easier to live with. In the end it accomplishes the same or similar tasks. The first rule in pretty much any maildrop filter file I set up checks if X-Spam-Flag is set and if so, moves the email into the Spam folder. I would recommend against using a squirrelmail rule to move Spam; you don't know if you or your users also want to use another client besides squirrelmail. Given that one of IMAP's great advantages is that you can have multiple clients have the same view of the same Inbox, I'd go for a setup that preserves this advantage, which means using a separate delivery agent/filter.
{ "pile_set_name": "StackExchange" }
Q: Extract hash values (CRC) and path names from an archive I have successfully extracted data from a large .rar archive (1.9TB) using 7-zip and now I want to delete the archive. However, before I do so, I would like to save path names and, most importantly, the corresponding CRC values that are listed in the CRC column in the 7-zip file manager. The only way to do this that I know of is via cmd.exe with the following command 7z l -slt <archive.zip>. However, this method is not very efficient for my purposes. For one thing, command prompt's output window is limited in size. I know that I can adjust buffer size (perhaps even up to 32766), but the archive has over a million files... What is even more problematic, though, is the fact that the output of this method has a format that, as far as I know, cannot be altered and it is as follows: Path = - Folder = - Size = - Packed Size = - Modified = - Created = Accessed = Attributes = - Encrypted = - Solid = - Commented = - Split Before = - Split After = - CRC = - Host OS = - Method = - Version = - Volume Index = - Whereas what I'm looking for is an output per file that looks like this: <CRC> <pathname> For example: 60CD248A *Folder1\text1.txt 61CD248A *Folder1\Folder2\text1.txt 62CD248A *Folder1\Folder2\text2.txt Many thanks for your time and help. A: You can use one line command code to get only CRC lines from command line output. 7z l -slt archive.zip >>"%tmp%\output.txt && type "%tmp%\output.txt"|findstr /b CRC | clip && del /q /f "%tmp%\output.txt" This command will put in your clipboard/Crtl+C all lines contents CRC - ..... from 7z command. For save in a file: 7z l -slt archive.zip >>"%tmp%\output.txt && type "%tmp%\output.txt"|findstr /b CRC >>"c:\my_folder\my_save_output.txt" && del /q /f "%tmp%\output.txt" For loop direct save CRC - strings for /f tokens^=2*^delims^=^ ^-^ %i in ('7z l -slt archive.zip^|findstr /b CRC')do @echo/%i>>"c:\my_folder\my_save_output.txt" My 7Z version output look likes CRC = STRINGS, in my case, the delimiter changes to: for /f tokens^=^2*^delims^=^=^ %i in ('7za l -slt archive.zip ^| find /i "crc"')do @echo/%i>>"c:\my_folder\my_save_output.txt" Obs.: 1) There are 2 spaces in between ^=^= and %i: delims^=^= ←→ %i ---> delims^=^=^ %i Obs.: 2) The same apply to Path, just replace CRC to Path. Obs.: 3) The executable file in portable version used is 7za.exe, may your have another name.
{ "pile_set_name": "StackExchange" }
Q: What accessories do I have to add to my bike so that I may commute during rainy weather? I have a hybrid (Schwinn Sporterra) which I use for commuting except when it rains. The main problem of riding it during the rains is the dirt that gets spewn all over, esp over the drive-train. Cleaning it and re-oiling the whole thing is a painful hour long process. Due to this I tend to not take my bike out when there is a chance of rain. How do I get rid of this problem? I do have some plastic fenders, but they do not cover the wheels fully. If I get new metal fenders which cover most of the wheel will this problem be solved? Do I have to get any other accessories? A: Adding mud-flaps to both fenders will greatly reduce spraying water on to your bottom bracket, feet and bicyclists riding behind you. Mud-flaps can be made easily & cheaply by cutting a part of plastic bottles for milk /water/soda-pop and screwing them on to end of mud-guard/fenders (ensure there is enough clearance between screw and tire). Plastic fenders offering full coverage will avoid spraying water and dirt; besides the plastic one's usually are lighter and cheaper than their metal counter parts. These are also corrosion resistant. Using wet weather chain lubricant will help to some extent, however this doesn't replace the need for cleaning your drive train and re-lubing it. This type of lubricant will help you to space out cleaning a little further. A clean drive train will last longer. A: Don't forget lights. Many people who only ride during the day/nice weather don't bother to put lights on your bike. But in heavy rain, it's sometimes darker (especially closer to sunrise/sunset), and visibility is reduced. Having lights and also reflectors will help you to be seen and improve your safety. If you don't mind getting wet, and use a waterproof pannier to transport a change of clothes, you may not need any additional equipment. Just make sure to relube your chain frequently if it often gets wet. A: For riding in the rain, I would definitely recommend putting fenders on your bike that cover as much of the wheel as possible. This will help prevent "skunk stripes" on the back of your clothes due to dirt thrown up by the rear wheel. Fenders also generally help keep water from flying all around during riding, which keeps other things from getting as wet to begin with. I'd also recommend putting a plastic cover on your seat, as (a) wet seats tend to stay wet for a long time, and (b) keeping your seat dry will help extend its usable lifetime. For this, you can simply tie a plastic grocery bag over the seat -- it's not very elegant looking, but it works well as long as there aren't any holes in the bag. Make sure the bottom of the seat is covered as well as the top. For the drive train, it's difficult to keep this part of the bike dry during rainy weather. You could look into getting a chain guard, but these are typically designed to prevent dirt and grease from the chain rubbing onto your leg or pants, not to keep the chain dry in the rain. It might help keep rain off from above, but it won't help keep things dry from below. You might also prophylactically keep your drivetrain dry by using a wax-based chain lubricant before you go out in the rain. This will help repel water during the ride.
{ "pile_set_name": "StackExchange" }
Q: Canvas drawing doesn't work in external .js file My script works when it is included in the html file, but when I move it to an external .js file, canvas doesn't draw. this is my html file: <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <title>Reveal RGB Values</title> <form action='/' method='POST' enctype='multipart/form-data'> <h1>Select file to upload:</h1> <br> <input type='file' name='file'> <input type='submit' value='submit'> </form> {% if status == 'uploaded'%} <h1>There will be a photo here</h1> <canvas id="frame"></canvas> <canvas id= "solution_frame"></canvas> <div id="solution"></div> {% endif %} <script type = text/javascript src="{{ url_for('static', filename='script.js') }}"></script> </body> In the external .js file, I have two canvases that successfully get built (I can see empty blanks that match the sizes) var frame = document.getElementById('frame'); frame.width = 800; frame.height = 600; var context = frame.getContext('2d'); var solution_frame = document.getElementById('solution_frame'); var solution_context = solution_frame.getContext('2d'); solution_frame.width = 25; solution_frame.height = 25; but I cannot draw the image function draw_image(){ base_image = new Image(); // yay! jinja works here too. var image_url = '{{img_url}}'; base_image.src = image_url; base_image.onload = function(){ //context.drawImage(base_image, 0, 0); scale_to_fit(this); } } draw_image(); function scale_to_fit(img){ //get the scale var scale = Math.min(frame.width/img.width, frame.height/img.height); var x = (frame.width/2) - (img.width/2) * scale; var y = (frame.height/2) - (img.height/2) * scale; context.drawImage(base_image,x,y,img.width*scale, img.height*scale); I found a similar post that suggested me to add this document.addEventListener('DOMContentLoaded',draw_image,false); saying the script is acting before the canvas is fully loaded, but it doesn't seem to be the issue. Can anyone see where I'm possibly going wrong? Thanks ahead EDIT!: It just occurred to me that the issue might be related to retrieving the image source location with Jinja? A: It seems like my problem is not html/js related at all. I am using Jinja to retrieve the image location from the server, and Jinja doesn't serve to that external js file. It seems to me that function needs to be kept in the html file. That's correct. Jinja doesn't run any processing on statically included assets. I see two ways around your problem. Either hard code the URL in script.js: var image_url = '/path/to/image' Or remove that line from the draw_image function and set that JS variable in the template, prior to including script.js: <script type='text/javascript'> const image_url = {{img_url}}; </script> <script type='text/javascript' src="{{ url_for('static', filename='script.js') }}"></script>
{ "pile_set_name": "StackExchange" }
Q: Tikz coordinates relative to one node Using both calc and |- would be a convenient way to refer to "inner, relative coordinates" of a node, with (0, 0) meaning node.center, (0, 1) meaning node.east and (.3, -.5) meaning somewhere precise (but relative) in the south east quarter. However, as described here and there, the following coordinate is not parsed: ($(node.center)!.3!(node.east)$ |- $(node.center)!-.5!(node.north)$) So the following convenience macro does not work: \newcommand{\relativeToNode}[3]{($(#1.center)!#2!(#1.east)$ |- $(#1.center)!#3!(#1.north)$)} How nice would it be to write: \node (inner) at (\relativeToNode{outer}{.3}{-.5}) {hey!}; Is there any chance to get this working? Any workaround that would not involve defining intermediate macros or coordinates (whose names would have to be picked etc.)? A: For your use case you don't even need the calc library. You can define style relative to node=<node name> that shifts and scales the coordinate system accordingly: \tikzset{ relative to node/.style={ shift={(#1.center)}, x={(#1.east)}, y={(#1.north)}, } } Then you can place your node with \path[relative to node=outer] (-0.4,-0.5) node {Hello}; MWE: \documentclass[tikz,margin=2mm]{standalone} \tikzset{ relative to node/.style={ shift={(#1.center)}, x={(#1.east)}, y={(#1.north)}, } } \begin{document} \begin{tikzpicture} \node[minimum width=2cm,minimum height=3cm,draw=red] (outer) at (3,3) {}; % Only for the grid \begin{scope}[relative to node=outer] \foreach \ratio in {-1,-0.8,...,1}{ \draw[help lines] (-1,\ratio) -- (1,\ratio); \draw[help lines] (\ratio,-1) -- (\ratio,1); } \draw (-1,0) -- (1,0); \draw (0,-1) -- (0,1); \end{scope} \path[relative to node=outer] (-0.4,-0.5) node {Hello}; \end{tikzpicture} \end{document} Resulting in
{ "pile_set_name": "StackExchange" }
Q: Translating ~ほうがいい as 'should' -- why does this seem rare? In all of the resources I use (incl Genki, Dictionary of Basic Jap. Grammar, various websites), the ~ほうがいい construction is nearly universally translated "had better ~" and rarely includes the word "should ~". This is while noting that ~ほうがいい is a polite suggestion. Nearly all example sentences I find use the translation "had better ~". As a native speaker of English (Eastern Canada), the phrase "You'd better ~" rings quite assertive and somewhat condescending, and in polite speech I would rarely elect to use that phrase over "should". In fact, "You'd better ~" would be reserved for people I was familiar and casual with. Is it wrong to translate the phrase ~ほうがいい as "should" in the typical case, or to use it where I would use "should" in English? A: This is one of the Seven Wonders of English Education in Japan of which my poor English is a product. Long story short, I can guarantee as an average native Japanese-speaker that 「~~ほうがいい」 is closer in both meaning and nuance to "should" than to "had better". I was taught the complete opposite in junior high school in Japan (I was indeed taught "had better" sounded softer than "should") and it took me 7-8 years to realize that I was taught wrong. I had a chance to speak with a few Americans when I was around 21 about this matter and every one of them told me with confidence that what we had been taught was incorrect. Assuming that the authors of your textbooks have received the same type of English education in Japan, the topic that you have brought up this time would only be a natural result. They are simply teaching you what they have been taught. Once again, 「(Verb) + ほうがいい」 with no context (and said with no sarcasm), is closer to "should + (verb)". A phrase such as 「絶対{ぜったい} + (Verb) + べきだ」 is close to "had better (Verb)". I think that the word "better" innocently lead our nation into believing that 「ほうがいい」 was the appropriate translation, which would actually be "true" if it were just "better" instead of the more idiomatic "had better".
{ "pile_set_name": "StackExchange" }
Q: getElementsByClassName is not a function in Firefox My to-read shelf on GoodReads is a mix of published and unpublished books making it hard to find something published to read. I figured I could throw together a GreaseMonkey script that would change the background of the entry for the books that haven't yet been published. This is what I have put together so far: // ==UserScript== // @name Unpublished Lowlighter // @description Makes the background of books not yet published on the Goodreads to-read shelf grey. // @include http://www.goodreads.com/* // ==/UserScript== function dateColor() { var books = document.getElementsByClassName('bookalike review'); for (var book in books) { var dateString = book .getElementsByClassName('field date_pub') .getElementsByClassName('value') .textContent; var date = new Date(dateString); var today = new Date(); if (date > today) { book.style.backgroundColor('Lightgrey'); } } } dateColor(); The problem is that it doesn't work. When I tried running the script in scratchpad it gives me the error: Exception: book.getElementsByClassName is not a function I was under the impression that Firefox supports getElementsByClassName and that you can run it on the result of getElementsByClassName to get the child elements. Where am I going wrong? EDIT: Here is a snippet of the HTML for one <tr> in the table. The reason that I didn't post this to begin with is that it is really verbose: <tr id="review_265364012" class="bookalike review"> <td class="field checkbox" style="display: none"><label>checkbox</label><div class="value"> <input id="checkbox_review_265364012" name="reviews[265364012]" value="265364012" type="checkbox"> </div></td> <td class="field position"><label>position</label><div class="value"> <div class="reorderControls"> <a class="actionLink" href="#" id="loading_link_434018960" method="post" onclick="$(this).hide(); $('loading_anim_434018960').show(); $('hidden_link_434018960').simulate('click');; return false;"><img alt="up" src="http://www.goodreads.com/assets/up_arrow-7957f2bae9c3456ec7359ad79b000652.gif" title="move book up"></a><img alt="Loading-trans" class="loading" id="loading_anim_434018960" src="http://www.goodreads.com/assets/loading-trans-3e04cd6ed6ad31063972e688820d7866.gif" style="display:none"><a href="/shelf/move_up/174788201?redirect_url=%2Freview%2Flist%2F4111865%3Fformat%3Dhtml%26page%3D1%26shelf%3Dto-read" class="actionLink" data-method="post" id="hidden_link_434018960" rel="nofollow" style="display: none"><img alt="up" src="http://www.goodreads.com/assets/up_arrow-7957f2bae9c3456ec7359ad79b000652.gif" title="move book up"></a> <img src="/assets/loading.gif" class="position_loading" style="display: none"> <input id="positions_174788201" name="positions[174788201]" value="5" type="text"> <script type="text/javascript"> //<![CDATA[ var newTip = new Tip($('positions_174788201'), " <nobr>\n <a class=\"button\" href=\"#\" onclick=\"savePositionChanges(4111865); return false;\">Save position changes<\/a> &nbsp;\n <a href=\"#\" onclick=\"$(\'positions_174788201\').prototip.hide(); return false;\">close<\/a>\n <\/nobr>\n", { style: 'creamy', stem: 'leftMiddle', hook: { tip: 'leftMiddle', target: 'rightMiddle' }, offset: { x: 5, y: 5 }, hideOn: 'imaginaryelement', showOn: 'click', width: 'auto', hideOthers: true }); $('positions_174788201').observe('prototip:shown', function() { if (this.up('#box')) { $$('div.prototip')[0].setStyle({zIndex: $('box').getStyle('z-index')}); } else { $$('div.prototip')[0].setStyle({zIndex: 6000}); } }); //]]> </script> <a class="actionLink" href="#" id="loading_link_434206980" method="post" onclick="$(this).hide(); $('loading_anim_434206980').show(); $('hidden_link_434206980').simulate('click');; return false;"><img alt="down" src="http://www.goodreads.com/assets/down_arrow-61b0e7292c02b1dcfd3f75a7f9b6b7ad.gif" title="move book down"></a><img alt="Loading-trans" class="loading" id="loading_anim_434206980" src="http://www.goodreads.com/assets/loading-trans-3e04cd6ed6ad31063972e688820d7866.gif" style="display:none"><a href="/shelf/move_down/174788201?redirect_url=%2Freview%2Flist%2F4111865%3Fformat%3Dhtml%26page%3D1%26shelf%3Dto-read" class="actionLink" data-method="post" id="hidden_link_434206980" rel="nofollow" style="display: none"><img alt="down" src="http://www.goodreads.com/assets/down_arrow-61b0e7292c02b1dcfd3f75a7f9b6b7ad.gif" title="move book down"></a> </div> </div></td> <td class="field cover"><label>cover</label><div class="value"> <a href="/book/show/12074927-the-fractal-prince"><img alt="The Fractal Prince (The Quantum Thief Trilogy #2)" src="http://photo.goodreads.com/books/1311105989s/12074927.jpg" title="The Fractal Prince (The Quantum Thief Trilogy #2)"></a> </div></td> <td class="field title"><label>title</label><div class="value"> <a href="/book/show/12074927-the-fractal-prince" title="The Fractal Prince (The Quantum Thief Trilogy #2)"> The Fractal Prince <span class="darkGreyText">(The Quantum Thief Trilogy #2)</span> </a></div></td> <td class="field author"><label>author</label><div class="value"> <a href="/author/show/2768002.Hannu_Rajaniemi">Rajaniemi, Hannu</a> </div></td> <td class="field isbn" style="display: none"><label>isbn</label><div class="value"> </div></td> <td class="field isbn13" style="display: none"><label>isbn13</label><div class="value"> </div></td> <td class="field asin" style="display: none"><label>asin</label><div class="value"> </div></td> <td class="field num_pages" style="display: none"><label>num pages</label><div class="value"> <span class="greyText">unknown</span> </div></td> <td class="field avg_rating"><label>avg rating</label><div class="value"> 3.67 </div></td> <td class="field num_ratings" style="display: none"><label>num ratings</label><div class="value"> 9 </div></td> <td class="field date_pub"><label>date pub</label><div style="background: none repeat scroll 0% 0% Lightgrey;" class="value"> Sep 27, 2012 </div></td> <td class="field date_pub_edition" style="display: none"><label>date pub edition</label><div class="value"> <span class="greyText">unknown</span> </div></td> <td class="field rating"><label>my rating</label><div class="value"> <span class="stars" id="stars12074927_4111865" onmouseout="mouseOutStars('12074927')"><a rel="nofollow"><img alt="didn't like it " class="star" id="star12074927_0" onclick="submitStars('12074927', 0, '/review/rate/12074927?rating=1', 4111865); return false;" onmouseover="checkStars('12074927', 0)" src="/assets/layout/gr_orange_star_inactive.png" title="didn't like it" height="15" width="15"></a><a rel="nofollow"><img alt="it was ok " class="star" id="star12074927_1" onclick="submitStars('12074927', 1, '/review/rate/12074927?rating=2', 4111865); return false;" onmouseover="checkStars('12074927', 1)" src="/assets/layout/gr_orange_star_inactive.png" title="it was ok" height="15" width="15"></a><a rel="nofollow"><img alt="liked it " class="star" id="star12074927_2" onclick="submitStars('12074927', 2, '/review/rate/12074927?rating=3', 4111865); return false;" onmouseover="checkStars('12074927', 2)" src="/assets/layout/gr_orange_star_inactive.png" title="liked it" height="15" width="15"></a><a rel="nofollow"><img alt="really liked it " class="star" id="star12074927_3" onclick="submitStars('12074927', 3, '/review/rate/12074927?rating=4', 4111865); return false;" onmouseover="checkStars('12074927', 3)" src="/assets/layout/gr_orange_star_inactive.png" title="really liked it" height="15" width="15"></a><a rel="nofollow"><img alt="it was amazing " class="star" id="star12074927_4" onclick="submitStars('12074927', 4, '/review/rate/12074927?rating=5', 4111865); return false;" onmouseover="checkStars('12074927', 4)" src="/assets/layout/gr_orange_star_inactive.png" title="it was amazing" height="15" width="15"></a></span><script language="javascript" type="text/javascript">starRatings[ratingIndex++] = [ '12074927', -1]; checkStars('12074927', -1);</script> <span id="reviewMessage12074927_4111865"></span> <span id="successMessage12074927_4111865"></span> </div></td><td class="field shelves"><label>shelves</label><div class="value"> <span id="shelfList4111865_12074927"><span id="shelf_174788201"><a href="http://www.goodreads.com/review/list/4111865?shelf=to-read" class="shelfLink" title="View all books in Johan's to-read shelf.">to-read</a></span></span><br><a class="shelfChooserLink smallText" href="#" onclick="window.shelfChooser.summon(event, {bookId: 12074927, chosen: [&quot;to-read&quot;]}); return false;">[edit]</a> </div></td><td class="field review" style="display: none"><label>review</label><div class="value"> <span class="greyText">None</span> <a class="floatingBoxLink smallText" href="#" onclick="reviewEditor.summon(this, 12074927, 'review', {value: null}); return false;">[edit]</a> <div class="clear"></div> </div></td><td class="field notes" style="display: none"><label>notes</label><div class="value"> <span class="greyText">None</span> <a class="floatingBoxLink smallText" href="#" onclick="reviewEditor.summon(this, 12074927, 'notes', {value: null}); return false;">[edit]</a> </div></td><td class="field recommender" style="display: none"><label>recommender</label><div class="value"> <span class="greyText">none</span> </div></td><td class="field comments" style="display: none"><label>comments</label><div class="value"> <a href="/review/show/265364012">0</a> </div></td><td class="field votes" style="display: none"><label>votes</label><div class="value"> <a href="/rating/voters/265364012?resource_type=Review">0</a> </div></td><td class="field read_count" style="display: none"><label># times read</label><div class="value"> 0 </div></td><td class="field date_started" style="display: none"><label>date started</label><div class="value"> <span class="greyText">not set</span> <a class="floatingBoxLink smallText" href="#" onclick="reviewEditor.summon(this, 12074927, 'started_at', {value: null}); return false;">[edit]</a> </div></td><td class="field date_read"><label>date read</label><div class="value"> <span class="greyText">not set</span> <a class="floatingBoxLink smallText" href="#" onclick="reviewEditor.summon(this, 12074927, 'read_at', {value: null}); return false;">[edit]</a> </div></td><td class="field date_added" style="display: none"><label>date added</label><div class="value"> <span title="January 21, 2012"> Jan 21, 2012 </span> </div></td><td class="field date_purchased" style="display: none"><label>date purchased</label><div class="value"> <a class="smallText" href="#" id="add_for_date_purchased" onclick="new Ajax.Request('/review/update/12074927?format=json', {asynchronous:true, evalScripts:true, onFailure:function(request){Element.hide('loading_anim_206609');$('add_for_date_purchased').innerHTML = '<span class=&quot;error&quot;>ERROR</span>try again';$('add_for_date_purchased').show();}, onLoading:function(request){;Element.show('loading_anim_206609');Element.hide('add_for_date_purchased')}, onSuccess:function(request){Element.hide('loading_anim_206609');Element.show('add_for_date_purchased');var json = eval('(' + request.responseText + ')');$('review_265364012').replace(json.html);if (typeof(toggleFieldsToMatchHeader) == 'function') {toggleFieldsToMatchHeader();}}, parameters:'owned_book[book_id]=12074927&amp;partial=bookalike&amp;view=table' + '&amp;authenticity_token=' + encodeURIComponent('J5JjYi/D31hPm9w3u8hM35umQTh8bK3md4dVzpi4eKQ=')}); return false;">(add)</a><img alt="Loading-trans" class="loading" id="loading_anim_206609" src="http://www.goodreads.com/assets/loading-trans-3e04cd6ed6ad31063972e688820d7866.gif" style="display:none"> </div></td><td class="field owned" style="display: none"><label>owned</label><div class="value"></div></td><td class="field purchase_location" style="display: none"><label>purchase location</label><div class="value"> <a class="smallText" href="#" id="add_for_purchase_location" onclick="new Ajax.Request('/review/update/12074927?format=json', {asynchronous:true, evalScripts:true, onFailure:function(request){Element.hide('loading_anim_953979');$('add_for_purchase_location').innerHTML = '<span class=&quot;error&quot;>ERROR</span>try again';$('add_for_purchase_location').show();}, onLoading:function(request){;Element.show('loading_anim_953979');Element.hide('add_for_purchase_location')}, onSuccess:function(request){Element.hide('loading_anim_953979');Element.show('add_for_purchase_location');var json = eval('(' + request.responseText + ')');$('review_265364012').replace(json.html);if (typeof(toggleFieldsToMatchHeader) == 'function') {toggleFieldsToMatchHeader();}}, parameters:'owned_book[book_id]=12074927&amp;partial=bookalike&amp;view=table' + '&amp;authenticity_token=' + encodeURIComponent('J5JjYi/D31hPm9w3u8hM35umQTh8bK3md4dVzpi4eKQ=')}); return false;">(add)</a><img alt="Loading-trans" class="loading" id="loading_anim_953979" src="http://www.goodreads.com/assets/loading-trans-3e04cd6ed6ad31063972e688820d7866.gif" style="display:none"> </div></td><td class="field condition" style="display: none"><label>condition</label><div class="value"> <a class="smallText" href="#" id="add_for_condition" onclick="new Ajax.Request('/review/update/12074927?format=json', {asynchronous:true, evalScripts:true, onFailure:function(request){Element.hide('loading_anim_990684');$('add_for_condition').innerHTML = '<span class=&quot;error&quot;>ERROR</span>try again';$('add_for_condition').show();}, onLoading:function(request){;Element.show('loading_anim_990684');Element.hide('add_for_condition')}, onSuccess:function(request){Element.hide('loading_anim_990684');Element.show('add_for_condition');var json = eval('(' + request.responseText + ')');$('review_265364012').replace(json.html);if (typeof(toggleFieldsToMatchHeader) == 'function') {toggleFieldsToMatchHeader();}}, parameters:'owned_book[book_id]=12074927&amp;partial=bookalike&amp;view=table' + '&amp;authenticity_token=' + encodeURIComponent('J5JjYi/D31hPm9w3u8hM35umQTh8bK3md4dVzpi4eKQ=')}); return false;">(add)</a><img alt="Loading-trans" class="loading" id="loading_anim_990684" src="http://www.goodreads.com/assets/loading-trans-3e04cd6ed6ad31063972e688820d7866.gif" style="display:none"> </div></td><td class="field format"><label>format</label><div class="value"></div></td><td class="field actions"><label>actions</label><div class="value"> <div class="actionsWrapper greyText smallText"> <div class="editLinkWrapper"><a class="actionLinkLite editLink" href="#" id="loading_link_818479" onclick="new Ajax.Request('/review/edit/12074927', {asynchronous:true, evalScripts:true, onFailure:function(request){Element.hide('loading_anim_818479');$('loading_link_818479').innerHTML = '<span class=&quot;error&quot;>ERROR</span>try again';$('loading_link_818479').show();}, onLoading:function(request){;Element.show('loading_anim_818479');Element.hide('loading_link_818479')}, onSuccess:function(request){Element.hide('loading_anim_818479');Element.show('loading_link_818479');}, parameters:'authenticity_token=' + encodeURIComponent('J5JjYi/D31hPm9w3u8hM35umQTh8bK3md4dVzpi4eKQ=')}); return false;">edit</a><img alt="Loading-trans" class="loading" id="loading_anim_818479" src="http://www.goodreads.com/assets/loading-trans-3e04cd6ed6ad31063972e688820d7866.gif" style="display:none"></div> <div class="viewLinkWrapper"><a href="/review/show/265364012" class="actionLinkLite viewLink nobreak">view »</a></div> <a href="/review/destroy/12074927?return_url=http%3A%2F%2Fwww.goodreads.com%2Freview%2Flist%2F4111865%3Fshelf%3Dto-read" class="actionLinkLite smallText deleteLink" data-confirm="Are you sure you want to remove The Fractal Prince from your books? This will permanently remove this book from your shelves, including any review, rating, tags, or notes you have added. To change the shelf this book appears on please edit the shelves." data-method="post" rel="nofollow"> <img alt="Remove from my books" src="http://www.goodreads.com/assets/layout/delete.gif" title="Remove from my books"> <span class="label">remove book</span> </a> </div> </div></td> </tr> A: There are at least 3 problems in that code: You cannot chain getElementsByClassName like that. That function operates on a DOM element, but returns an object. for (var book in books) will loop on object properties that are not accounted for, and will crash this code. books is an object, not an array. book.style.backgroundColor is not a function and that is not how to set a style. Nowadays, getElementsByClassName is seldom the best approach for this kind of thing; use querySelectorAll for more: flexibility/power/precision. Fixing all the problems, here's code that should work -- assuming that the page structure really matches the code structure from the question. Post a relevant HTML snippet and/or link to the exact page, if it does not. // ==UserScript== // @name Unpublished Lowlighter // @description Makes the background of books not yet published on the Goodreads to-read shelf grey. // @include http://www.goodreads.com/* // ==/UserScript== function dateColor() { var books = document.querySelectorAll ( ".bookalike.review .field.date_pub .value" ); var today = new Date(); // More efficient, outside the loop. for (var J = books.length - 1; J >= 0; --J) { var book = books[J]; var dateString = book.textContent; var date = new Date(dateString); if (date > today) { book.parentNode.parentNode.style.setProperty ("background", "Lightgrey"); } } } dateColor(); A: There is a further problem (aside from trying to call getElementsByClassName on a NodeList) that for (var book in books) won't do what you want. in doesn't do a foreach as you would expect; it gets every property from the target object. Because of the way Javascript objects work, for an array, this would be the array indexes; for a NodeList, it is the properties of the NodeList (which will be the array indexes, plus the string "length" and the string "item"), which will not be useful for your loop. You need something like for (var i = 0; i < books.length; ++i) { var book = books[i]; ... } A: This won't work: book .getElementsByClassName('field date_pub') .getElementsByClassName('value') getElementsByClassName returns an array-like object of the appropriate elements (there can be more than one with a given class). You will have to loop over each one and execute getElementsByClassName on each. Nested getElementsByClassNames are not merged by default.
{ "pile_set_name": "StackExchange" }
Q: Is asp.net MVC2 included in .net 4.0 framework? I've installed .net 4 in the server. Now I don't know if I must install the MVC 2 for VS2008 or what because I got this error: Could not load file or assembly 'System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. A: VS 2010 comes with MVC 2, but it's not a part of the .NET Framework proper. This means that if you go download the .NET Framework 4 redistributable, it will not include the MVC 2 runtime. But since MVC is bin-deployable, this is fine. Your application - when deployed to a .NET 3.5 SP1 or .NET 4 server - will just copy System.Web.Mvc.dll to its /bin folder, and everything will run as expected. MVC runs just fine in Medium Trust. To do a server wide install you need to download AspNetMVC2_VS2008.exe from here, rename the .exe to .zip and inside the mvcruntime sub-folder you'll find the AspNetMVC2.msi file. Then you have to run: msiexec /i AspNetMVC2.msi /l*v .\mvc.log MVC_SERVER_INSTALL="YES" A: by default the System.Web.Mvc.dll is not included when you compile an MVC 2 project; you have to change the setting "Copy Local" to True on the Reference properties to get the file in your /bin
{ "pile_set_name": "StackExchange" }
Q: Cannot align fontawesome icons on sidebar I'm having some real trouble trying to align icons within their divs. Nothing I try works whether it be creating custom CSS or trying to use bootstrap's text-align-center. Here's a cut down example of the navbar: <div id="appSidenav" class="sidenav"> <button class="closebtn btn" id="navClose" onclick="closeNav()"><i class="fas fa-chevron-left"></i></button> <button class="openbtn btn" id="navOpen" onclick="openNav()"><i class="fas fa-bars"></i></button> <a href="#" class="pt-3"> <div class="row"> <div class="col-2"> <i class="fas fa-home"></i> </div> <div class="col"> <span>Home</span> </div> </div> </a> <a href="#"> <div class="row"> <div class="col-2"> <i class="fas fa-users"></i> </div> <div class="col"> <span>Contacts</span> </div> </div> </a> </div> I've tried to add text-center to the cols, I've also tried adding text-align: center; to the CSS but nothing seems to make any difference. I've also tried different sized cols and cols with no padding or margin. I've tried adding an alignment to pretty much every tag or class and nothing works. Any ideas? Thanks! UPDATE Nobody seems to quite understand what I'm getting at, so I'll post a picture. I've tried to align the icons using both CSS and bootstrap classes. I can live with it I guess but it's a bit annoying. Here's what's happening: A: I don't understand what you mean exactly, <!DOCTYPE html> <html> <head> <title>Font Awesome 5 Icons</title> <meta name='viewport' content='width=device-width, initial-scale=1'> <script src='https://kit.fontawesome.com/a076d05399.js'></script> <!--Get your own code at fontawesome.com--> </head> <body> <div id="appSidenav" class="sidenav"> <button class="closebtn btn" id="navClose" onclick="closeNav()"><i class="fas fa-chevron-left"></i></button> <button class="openbtn btn" id="navOpen" onclick="openNav()"><i class="fas fa-bars"></i></button> <a href="#" class="pt-3"> <div class="row"> <div class="col-2"> <i class="fas fa-home"></i> <span>Home</span> </div> </div> </a> <a href="#"> <div class="row"> <div class="col-2"> <i class="fas fa-users"></i> <span>Contacts</span> </div> </div> </a> </div> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: Pass an object to a class and call it in an static function in the same class I am using gdal to do some raster works, well it has a GDALWarpAppOptionsSetProgress function which gets an static function to show its progcess. here you can find its link :http://www.gdal.org/gdal__utils_8h.html#a6ed3c9681cabcfcbd6fc87d427762482 and this link http://gdal.sourcearchive.com/documentation/1.6.0/gdal_8h_5703b651695c0cbe6f3644a0a18dda8b.html well I know I must write an static function to use it, here is my function static int My_FN_GDALTermProgress( double dfComplete, const char *pszMessage, void *pData) { if(progressBar){ progressBar->setValue(FN_GDAL_PROGRESS_VALUE); } double FN_GDAL_PROGRESS_VALUE = dfComplete * 100; return TRUE; } well i have a class named gdal_dem which is like this #include "gdal_dem.h" #include "gdal_wrap.h" #include <qdebug.h> #include <iostream> #include "cpl_string.h" #include "gdal_priv.h" #include "ogr_spatialref.h" #include "gdal_utils_priv.h" #include "cpl_error.h" #include <QString> #include "commonutils.h" #include <QFile> gdal_dem::gdal_dem(QString SrcFilename): SrcFile(SrcFilename) { } float FN_GDAL_PROGRESS_VALUE = 0.0f; static int My_FN_GDALTermProgress(double dfComplete, CPL_UNUSED const char * pszMessage, CPL_UNUSED void * pProgressArg ) { FN_GDAL_PROGRESS_VALUE = dfComplete * 100; printf("Progress: %f\n",FN_GDAL_PROGRESS_VALUE); return true; } //// int gdal_dem::colorrelief(QString Dstanationfile,QString colorfile){ ..... if(!(psOptionsForBinary->bQuiet)) { prgFunc=My_FN_GDALTermProgress; GDALDEMProcessingOptionsSetProgress(psOptions, prgFunc,NULL); } ...... } In above code I can set the above mentioned function in processing option and it works fine. but my problem is when I want to update a progress bar. I have a QProgressBar and it is in my main class. How can I pass it into the static function? I tried these ways: 1- I tried to get progressbar in my gdal_dem and also defined a static variable in gdal_dem and tried to set its value and update it in My_FN_GDALTermProgress, the problem is because progressbar is also static I can see it in wrap.cpp's contractor, 2-I tried to define a new My_FN_GDALTermProgress function in my main apps class but it must be static and I faced this error cannot declare member function to have static linkage 3- I also tried this method but it does not work https://www.badprog.com/c-errors-warnings-cannot-declare-member-function-static-void-myclassmymethod-to-have-static-linkage Well, How can I pass a parameter to my gdal_dem class and update its value in an static class in it? A: Use the pData argument. You can pass anything you want to it when registering the static function. In this case, you can pass a pointer to your QProgressBar object: QProgressBar* qProgBarObj = // ... GDALDEMProcessingOptionsSetProgress(psOptions, prgFunc, qProgBarObj); The static function will then receive it as the third argument: static int My_FN_GDALTermProgress(double dfComplete, const char *pszMessage, void *pData) { auto progBar = reinterpret_cast<QProgressBar*>(pData); progBar->setValue(/* ... */); // ... }
{ "pile_set_name": "StackExchange" }
Q: Wordpress theme options variable scope I have my theme options saved and in my functions.php file, I have: $my_option = get_option('theme_options'); So, if in functions.php I insert: echo $my_option['name']; It will echo correctly. However, if I put the same echo line anywhere else in any other theme file, it will not work. The only way I have been able to get it to work is if I put: global $my_option; at the top of every single file. I have seen many other themes that didn't need to do this. Why can't I get the theme options variable to work throughout my theme? A: Simply Open your functions.php file and at the very top globalize the variable e.g: <?php global $my_option; and this should be available anywhere in your theme files as log as you are not inside a function, if that is the case then you will have to globalize it again inside the function.
{ "pile_set_name": "StackExchange" }
Q: Change color of a shape according color input type javesctipt I have used a colorPicker and want to take the value and set it. I have used this: <li id="color"><input type="color" name="color" onchange="changeColor()"></li> function changeColor(){ var selectedShapes = document.getElementsByClassName("selected"); var len = selectedShapes.length; for(var i=0; i<len; ++i) { selectedShapes[i].style.background = document.getElementsByName("color"); } } This is the file: http://jsbin.com/mebiriruzi/edit?css,js,output how do I use the color input of the user? A: document.getElementsByName("color") return a list of elements as suggested by the "s" in getElementsByName. You could use an id and then do document.getElementById("color").value or select the first occurance of "color" if you only have one with document.getElementsByName("color")[0].value So you can either do: function changeColor(){ var selectedShapes = document.getElementsByClassName("selected"); var len = selectedShapes.length; for(var i=0; i<len; ++i) { selectedShapes[i].style.background = document.getElementsByName("color")[0].value; } } or <li id="color"><input type="color" id="mySelectedColor" name="color" onchange="changeColor()"></li> And then in js: function changeColor(){ var selectedShapes = document.getElementsByClassName("selected"); var len = selectedShapes.length; for(var i=0; i<len; ++i) { selectedShapes[i].style.background = document.getElementById("mySelectedColor").value; } }
{ "pile_set_name": "StackExchange" }
Q: Referencing all table cells after a certain cell How would I go about changing the cells in a table which follow a certain cell? I cannot get this to work with .parent().nextAll(), or .index() My apologies, but I do not have any code to post. It is more of a general question I think. A: The cells aren't actually sequential in the HTML, so you can't just use everything at the same level (with nextAll or the like). Say you have this table: <table> <tbody> <tr> <td>one</td> <td id="two">two</td> <td>three</td> </tr> <tr> <td>four</td> <td>five</td> <td>six</td> </tr> </tbody> </table> ...and you want to highlight every cell "after" two, this would traverse and select those cells: $('table td:gt(' + $('#two').index() + ')').each(function() { console.log($(this).text()); // or whatever you want to do with the cell }); Demo Fiddle here.
{ "pile_set_name": "StackExchange" }
Q: Declare two variables split by comma equals to? long i, b = get(); equals to long i; long b = get(); or long b = get(); long i = b; ? I'm totally new to c A: It is first option long i; long b = get(); You would find it out faster by trying then asking on SO. It's called operator ,. In this case both expressions are evaluated, but only second's value is returned. int x = 5; while (--x, x > 0) { printf("%d,", x); } has output 4,3,2,1, This code is same as --x; while (x > 0) { printf("%d,", x); --x; }
{ "pile_set_name": "StackExchange" }
Q: NSTimers VS NSThreading I'm working on an iPhone Game where the player tilts the iPhone to make the character move, but unfortunately all of the timers I'm using to animate the scenario are slowing down my game. I've been told to use NSThreads, but I really don't know anything about them. My question is, What are the differences between using NSThreads and NSTimers? Or what are the advantages of using NSThreads? How are they useful? A: Timers are objects that simply call methods at a later time. Threads are additional "streams" of stuff to be processed, in psuedo-parallel. It's like comparing apples to oranges—they're not really related. The only relation I can see is if you want to do some processing in the background, but you shouldn't be doing UI calls in background threads, Why are you using timers to make your character move? Knowing that, we might be able to supply an alternate solution.
{ "pile_set_name": "StackExchange" }
Q: Html tag to obtain different forms I would like implement a sort of choice using only Html and Css. I need to obtain a field where my user makes a choise and the latter leads to different forms. Precisely if my user decides to change his password will appear two input fields, or if he decides to change his information about his place of residence will appear four input field. Is possible this by using only Html and Css? A: Sounds like you need to use a javascript library to do this bud. Don't think you can trigger this with just html and css. Though i may be wrong.
{ "pile_set_name": "StackExchange" }
Q: Term for a polygamist's wife Is there a term for a wife of a polygamist if she has only one spouse? A: In describing the relationship between the wives of a polygamist, the term co-wife is often used.
{ "pile_set_name": "StackExchange" }
Q: Programmatically access children builds in Jenkins build flow I have a build flow pipeline (https://wiki.jenkins-ci.org/display/JENKINS/Build+Flow+Plugin) setup in Jenkins that spawns two or more children jobs each of which runs Junit tests. def childjobs = [] // some logic to populate the children jobs array // Run the jobs in parallel parallel(childjobs) I am trying to write a Groovy script in the context of the parent job using the Jenkins API to send a summary email from the parent job by collecting the summaries from the children. How can I access the build information (success/failure, how many failures, duration, Junit results etc.) of the children jobs from the parent job? Conceptually something like this: for (AbstractBuild<?,?> childjob in childjobs) { // get build info from childjob // get Junit results from childjob } A: It took me a while to play with the Build Flow and Jenkins API, and finally I got this: import hudson.model.* import groovy.json.* // Assign a variable to the flow run def flow = parallel( {build("child-dummy", branch_name: "child1")}, {build("child-dummy", branch_name: "child2")} ) println 'Main flow ' + flow.getClass().toString() + ', size: ' + flow.size() flow.each { it -> // type = com.cloudbees.plugins.flow.FlowState def jobInvocation = it.getLastBuild() // type = com.cloudbees.plugins.flow.JobInvocation println 'Build number #' + jobInvocation.getNumber() println 'Build URL ' + jobInvocation.getBuildUrl() } To obtain details of the run, such as artifacts etc. from the child jobs, use jobInvocation.getBuild() method that returns a Run instance. Getting the Junit results should be easy by parsing the JSON result file as specified in How to get the number of tests run in Jenkins with JUnit XML format in the post job script?.
{ "pile_set_name": "StackExchange" }
Q: Add/remove Knockout observableArray nested elements I'm trying to add to/remove from a nested observableArray in KnockoutJS. I have an array several elements, each with an attribute object, type object and an attributeValue array which holds objects. So it's a nested array. The allAttributes array is observableArray. Then I tried making the attributeValue array observable by making a new ViewModel (attributeValueViewModel) with attributeValues as ko.observableArray([]). I made two Knockout functions (which don't work) and I'm trying to add/remove values to/from that array. The problem is that the array is nested so I have to access the attributeID through this.attribute.id. self.allAttributes[i].attributeValues[j] should be the object I'm adding/removing... where i=attributeID and j=index of the attribute's value object Why aren't those functions working? Here is my fiddle: http://jsfiddle.net/M6Hqj/2/ A: First off, you're overwriting the observable function in your inner view model, e.g. when you assign obj.attribute = item.attribute;, you're overwriting your initial assignment of self.attribute = ko.observable(data.attribute);. Instead assign the value through the observable, like so: obj.attribute(item.attribute); //instead of obj.attribute = item.attribute; This will also make your self.addAttributeValue() function call work since the array is now observable. Next, in your self.removeAttributeValue() function, the this call actually refers to the specific record inside your attributeValues array, therefore, when you do this.attributeValues.splice(), it can't find your attributeValues object property. So, shift the function into the attributeValueViewModel object and use self instead of this, like so: //This is inside function attributeValueViewModel(data) self.removeAttributeValue = function() { alert(JSON.stringify(this)); self.attributeValues.splice(this.id, 1); } To call it, just change your data-bind code to use $parent instead of $root, like so: <button data-bind="click: $parent.removeAttributeValue">REMOVE</button> Something like this fiddle here: http://jsfiddle.net/UMB79/ (Note that with these changes you still have to modify your logic to correctly add/remove elements, 'cause it's still buggy)
{ "pile_set_name": "StackExchange" }
Q: Resize Image From S3 with Javascript I am using the knox package to connect my S3 account and pull an image, like this: var picturestring; knoxclient.get(key).on('response', function(res){ console.log(res.statusCode); console.log(res.headers); res.setEncoding('base64'); res.on('data', function(chunk){ picturestring += chunk; }); res.on('end', function () { console.log(picturestring); resizeimage(picturestring, done); // use the resize library in this function }); }).end(); After that, I want to use a library that can take in that string (picturestring), resize the image, and return a new base64 string that represents the resized image. At this point, I plan on uploaded the resized image to S3. I wrote a similar script in Golang that let me resize images like this, but every JS resizing library I've reviewed only give examples on resizing images from the local file system. Is there any way that I can avoid reading the image from S3 into the file system, and focus on dealing with the returned string exclusively?? ***************UPDATE*********************** function pullFromS3 (key, done) { console.log("This is the key being pulled from Amazon: ", key); var originalstream = new MemoryStream(null, {readable: false}); var picturefile; client.get(key).on('response', function(res){ console.log("This is the res status code: ", res.statusCode); res.setEncoding('base64'); res.pipe(originalstream); res.on('end', function () { resizeImage(originalstream, key, done); }); }).end(); }; function resizeImage (originalstream, key, done) { console.log("This is the original stream: ", originalstream.toString()); var resizedstream = new MemoryStream(null, {readable: false}); var resize = im().resize('160x160').quality(90); // getting stuck here ****** originalstream.pipe(resize).pipe(resizedstream); done(); }; I can't seem to get a grip on how the piping from originalstream --> to the resize ImageMagick function ---> to the resizestream works. Ideally, the resizestream should hold the base64 string for the resized image, which I can then upload to S3. 1) How do I wait for the piping to finish, and THEN use the data in resizedstream? 2) Am I doing the piping correctly? I can't debug it because I am unsure how to wait for the piping to finish! A: I'm not using S3 but a local cloud provider in China to store images and their thumbnails. In my case I was using imagemagick library with imagemagick-stream and memorystream modules. imagemagick-stream provides a way to process image with imagemagick through Stream so that I don't need to save the image in local disk. memorystream provides a way to store the source image and thumbnail image binaries in memory, and with the ability to read/write to Stream. So the logic I have is 1, Retrieve the image binaries from the client POST request. 2, Save the image into memory using memorystream 3, Upload it to, in your case, S3 4, Define the image process action in imagemagick-stream, for example resize to 180x180 5, Create a read stream from the original image binaries in step 1 using memorystream, pipe into imagemagick-stream created in step 4, and then pipe into a new memory writable created by memorystream where stores the thumbnail. 6, Upload the thumbnail I got in step 5 to S3. The only problem in my solution is that, your virtual machine might run out of memory if many huge images came. But I know this should not be happened in my case so that's OK. But you'd better evaluate by yourself. Hope this helps a bit.
{ "pile_set_name": "StackExchange" }
Q: rooViewController leaving gap at the bottom of the screen Mt rootViewController (i.e the first viewcontroller) is not occupying full screen, while the other VCs do (see screenshot). In IB, they look identical. I am using iOS 6 / iOS 5.1 simulator. My AppDelegate method looks innocent. Any suggestions? - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // hide status bar [UIApplication sharedApplication].statusBarHidden = YES; _window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // allocate the root view controller _window.rootViewController = [[LMHomeViewController alloc] init]; // add a navigation controller [LMNavigationController initSharedInstanceWithRootViewController:self.window.rootViewController]; [_window addSubview:LMNavigationController.sharedInstance.view]; // show the window [_window makeKeyAndVisible]; return YES; } A: Hide the status bar in your LMHomeViewController xib file. In your info.plist set "Status bar is initially hidden" to YES. I think the problem is that your LMHomeViewController get "rendered with a status bar" and then you add this view to a view without a status bar, so there is a 20 px gap.
{ "pile_set_name": "StackExchange" }
Q: Uploading new android app with apk of unpublished app I lost my keystore, and hence couldn't update my app with the new keystore. I unpublished my old app (it's internal - not many users), and tried uploading the apk as a new app. Play store tells me that I need to use a different package name since it's being used by one of my other applications. Why is it considering the package name for an unpublished app and how do I prevent it from doing so? A: Why is it considering the package name for an unpublished app? Google Play looks at all apps ever uploaded to Google Play (whether published or just as a draft) when looking for a unique package name. How do I prevent it from doing so? You cannot. You'll have to change the package name for your new app. Save and backup your keystore!
{ "pile_set_name": "StackExchange" }
Q: How can I project my Android phone screen to my computer monitor? For the sake of a class, I want to give an Android app development demo which I hope I can project whatever displayed on the device to my computer (so that I can further project in front of the class). I was thinking whether ADB has already supported this feature, though I didn't find a desired command in Android Development website yet (link). But I'm aware the following two commands: screencap screenrecord (available on API 19 onward) For the first screencap command, I can write a bash script and put a while loop to loop over screencap and pull the image to my computer, this answer pretty much did what I just described (StackOverflow). However, since my target device is Nexus 5 whose screen resolution is 1920x1080, it takes almost 2 seconds to fetch a frame. Is there a way to specify the resolution size of output images? The second choice is screenrecord command. However, it has to be saved locally (i.e., on the phone) and then pull to the computer to play. Though I'm sure making a streaming record, pulling out to the computer, and playing clips can be pipelined, it has to be imposed a delay of several seconds. What is a good practice to streaming the device display on the computer? I'm okay with other solutions, in fact, I've also explored AndroidStudio, but it seems streaming is not supported. A: If you get the app called AirDroid then you can do remote viewing of your Android device if it's supported (Or definitely if it's rooted). I've found that it works pretty well, however when not rooted you are required to have a USB connection to your phone. https://play.google.com/store/apps/details?id=com.sand.airdroid&hl=en
{ "pile_set_name": "StackExchange" }
Q: What is the easiest way to have a better quality image from a given image I am a novice for graphic design. I have a low quality image which is given by my friend, its size is really small, but we want to make it bigger and clearer so that we can use it as a banner or logo or etc. So my question is what is the easiest way to get a better quality image from a given(smaller, low quality) image? Should I manually draw it, and how, what tools to use? Or is there a way which I can easily convert it to a vector and then increase the size and then save it back as a png? A: In order to turn your low-resolution graphic into a high-resolution (or vector) version, you'll need to trace over it in a program like Adobe Illustrator. Illustrator also has the "Live Trace" feature, which can quickly turn that sort of black-and-white icon into a vector instantly. Once the image is vector, you can stretch it infinitely large or small and not lose any quality. For your second item about the heart, I really don't have any idea. You should post your questions as separate anyways, it becomes really confusing trying to answer two different things at once.
{ "pile_set_name": "StackExchange" }
Q: Reference for passive scalar I would like to learn about turbulence of a scalar advected by a random velocity field. I know that this problem can be solved analytically and that the statistics of the scalar field are intermittent. I have read this which is a nice introduction but not detailed enough and am reading this which I am finding very hard. The passive scalar is an old problem. Do you know of any textbook where it's solution is explained? A: One of the first complete study was performed by Obukhov in 1949 with his famous paper The structure of the temperature field in a turbulent flow. You can find it here [link] (This is a PDF file, you can check by searching the report title on Google). It is a nice thing to know. A complete review was written by Warhaft in the Annual Review of Fluid Mechanics in 2000 [link]. The paper title is Passive Scalar in Turbulent Flows. It is a really complete review, and the best starting point I think. You can then follow some references he provides. If you want a textbook, I think that Tennekes & Lumley wrote something about passive scalar in the classic A First Course in Turbulence. And finally, you can find papers dealing with different aspects of passive scalar by looking at some common journals, Journal of Fluid Mechanics, Physics of Fluids, Journal of Turbulence or Journal of Fluids Engineering.
{ "pile_set_name": "StackExchange" }
Q: setTmpData() on dynamically added form DataSource I have added a datasource to a form using the standard pattern: Args args; FormRun formRun; Form form; FormBuildDataSource formBuildDataSource; ; form = new Form(formstr(ICS)); formBuildDataSource = form.addDataSource('dbm_ICStmp'); //formBuildDataSource.table(tablenum(dbm_ICStmp)); args = new Args(); args.object(form); formRun = classfactory.formRunClass(args); formRun.init(); formRun.run(); formRun.detach(); dbm_ICStmp is a temporary table. How do I call setTmpData? A: I can recommend you some things about this: Use the classFactory to create your form (The Args class - Classfactory) Instead of adding your datasource through code outside the form, try to put the temporary table as the datasource on your form. When you open the form the temporary table will be empty, but then you can add data by using the setTmpData(MyTemporaryRecordInstance) method. MyTemporaryRecordInstance is then a temporary table that you filled up prior to that. For more information, you can find all you need to know about temporary tables in form on the following link : Temporary tables in forms
{ "pile_set_name": "StackExchange" }
Q: ReactJS - Unknown prop `activeClassName` on tag. Remove this prop from the element I am using react 15.4.2 and react-router4.0.0 and This project was bootstrapped with Create React App. Here is my Code. import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import {BrowserRouter as Router,Route,Link} from 'react-router-dom' const AboutPage = () => { return( <section> <h2>This is About page</h2> <Link activeClassName="active" to="/about/nestedone">Nestedone</Link> {' '} <Link activeClassName="active" to="/about/nestedtwo">Nested two</Link> </section> ) } const HomePage = () => { return( <section> <h2>This is Home page</h2> <Link to="/about">About</Link> </section> ) } const NestedOne = () => { return ( <section> <h2>Nested page 1</h2> </section> ) } const NestedTwo = () => { return ( <section> <h2>Nested page 2</h2> </section> ) } ReactDOM.render( <Router> <section> <Route exact path="/" component={HomePage} /> <Route path="/about" component={AboutPage} /> <Route path="/about/nestedone" component={NestedOne} /> <Route path="/about/nestedtwo" component={NestedTwo} /> </section> </Router>, document.getElementById('root') ); When I browse /about, I am getting this error: "Warning: Unknown prop activeClassName on tag. Remove this prop from the element. What am I doing wrong here? Thanks! A: The activeClassName property is not a property of Link but of NavLink. So, just change your code to use NavLink instead of Link: const AboutPage = () => { return( <section> <h2>This is About page</h2> <NavLink activeClassName="active" to="/about/nestedone">Nestedone</NavLink> {' '} <NavLink activeClassName="active" to="/about/nestedtwo">Nested two</NavLink> </section> ) Remember to import the NavLink from the react-router-dom: import { NavLink } from 'react-router-dom' A: activeClassName is not a property of Link but of NavLink. Since react-router v4 beta8, the property is active by default. Verify which version is installed in your node modules folder
{ "pile_set_name": "StackExchange" }
Q: Add margin / padding to last line before page break I have a large HTML document with the background being converted to PDF (using wkhtmltopdf). Sometimes page break happens in middle of the text block, and last line before page break is too close to the bottom of page. (text blocks have already with page-break: avoid, and spacing between blocks is large enough to keep the block away from the bottom of page) Is there a possibility to add margin / padding to last line before page break? A: Seems like page-break-inside: avoid might be the source of the problem. According to MDN, https://developer.mozilla.org/en-US/docs/Web/CSS/page-break-inside, it probably causes the text blocks ignore page's margins. Maybe you could manually place page-break-after: always somewhere in your HTML code so as to achieve the needed formatting. Another thing to try is maybe display: inline-block with the container having white-space: nowrap and the text block having white-space: normal. (Just a hypothesis, though, seems like some experimentation is needed.)
{ "pile_set_name": "StackExchange" }
Q: Is it possible to process a task at django-background-tasks without entering the command 'python manage.py process_tasks'? Is it possible to process a task at django-background-tasks without the 'command python manage.py process_tasks'? my task needs start when the application starts but I don't want to enter a command to do it. Thanks in advance. A: Yes, since Django in version 1.7 you can add ready function to your app which will execute only once at startup. Let's say you have application named StackApp from django.apps import AppConfig class StackAppConfig(AppConfig): name = 'stackapp' verbose_name = "StackApp" def ready(self): process_tasks.delay() In your file app/__init__.py you have to include: default_app_config = 'stackapp.apps.StackAppConfig'
{ "pile_set_name": "StackExchange" }
Q: The complexity of comparing a power to some threshold Consider the following simple problem: Given fractions $a/b$, $c/d$ with $a/b<1$ and $c/d<1$, and natural number $e$, both encoded in binary (so the problem size is $\log(a)+\log(b)+\log(c)+\log(d)+\log(e)$, decide whether $$(\frac{a}{b})^e \geq \frac{c}{d}$$. What's the precise complexity of this problem? Note that one can simply compute $(\frac{a}{b})^e$, as it might require $e\cdot (\log(a)+\log(b))$ bits to store. Any upper/lower bound? Do I miss something here? A: The problem is decidable in polynomial time (in fact, in uniform $\mathrm{TC}_0$). We can recast the question as follows: given positive integers $a,b,c,d,e$, find the sign of $$\Lambda=e\log(a/b)-\log(c/d).$$ First, note that we can test whether $\Lambda=0$: if we assume w.l.o.g. that $\gcd(a,b)=\gcd(c,d)=1$, then $da^e=cb^e$ implies $a^e\mid c$ and $b^e\mid d$; in particular, apart from the trivial case $a=b=1$, equality can hold only if $e\le\max\{\log c,\log d\}$, in which case we can evaluate $a^e,b^e$ in polynomial time. Likewise, we can rule out the case when $(a/b)^{e_1}=(c/d)^{e_2}$ for some positive integers $e_1,e_2$. The argument above shows that if this is the case, then $e_1,e_2\le\max\{\log a,\log b,\log c,\log d\}$, hence we can find $e_1,e_2$ by brute force in polynomial time, and then it suffices to compare $e$ with $e_1/e_2$. Thus, suppose $a/b$ is not a rational power of $c/d$, which implies $\Lambda\ne0$. Write $\alpha_1=a/b$, $\alpha_2=c/d$, $\lambda_1=\log\alpha_1$, $\lambda_2=\log\alpha_2$, $\beta_1=e$, $\beta_2=-1$. Note that the logarithmic height $h(\alpha_1)=\max\{\log a,\log b\}$, $h(\alpha_2)=\max\{\log c,\log d\}$, and $\lambda_1,\lambda_2$ are linearly independent over $\mathbb Q$. By some version of Baker’s theorem (e.g., the “explicit result by Baker and Wüstholz” in http://en.wikipedia.org/wiki/Baker%27s_theorem#Statement), we have $$\log\lvert\Lambda\rvert>-Ch(\alpha_1)h(\alpha_2)\log\beta_1$$ for some constant $C$ (note that in the statement given in the link, we have $n=2$ and $d=1$, hence $C$ is really independent of the input data). The number on the right-hand side is polynomial in the length of the input, and it thus suffices to approximately evaluate $\Lambda$ with polynomially many bits of precision, which can be done by standard numerical algorithms in polynomial time. (If you want to look for more information, the keyword is “linear forms in logarithms”.)
{ "pile_set_name": "StackExchange" }
Q: Removing items from a list where the Id is in another list I see this questions is quite common yet none of the answers work as expected. I have a list of objects and I need to remove some of those objects when their Id is in a specified list. I tried List.RemoveAll but that just returns an integer, not the modified list. How do I get back my list, minus the removed items? List<Target> allServers = GetTargets(Group.Id); List<long> excludedServers = GetExcludedServers(); List<Target> patchServers = allServers .RemoveAll(x => !excludedServers.Any(y => y.Id == x.Id)); A: RemoveAll modifies your existing List, it returns the number of items it removed. To get a new list without the items you can use var newList = myList.Where(i => !excludedItems.Any(ei => ei.Id == i.Id)).ToList(); Although if your Server class has the right equality members to compare Ids, you could just write var newList = myList.Except(servers).ToList();
{ "pile_set_name": "StackExchange" }
Q: Ligatures in 'shelfful' I came across the following text while going through TeX documentation: textcompwordmark This command is used to separate letters which would normally ligature. For example fi is produced with f\textcompwordmark i. Note that the f and i have not ligatured to produce fi. This is rarely useful in English (shelfful is a rare example of where it might be used) but is used in languages such as German. Since ligature was a new word for me, I immediately referenced my dictionary and found that: Noun: ligature Character consisting of two or more letters combined into one Wikipedia entry shows an example as: So, it means that the horizontal cross line in f is merged with the next character. But, I do not see something similar happening in the text when shelfful is being written. I'd assume that the horizontal lines of both fs in ff would get merged when writing, but this should be happening to each and every word which has ff appearing in them. Why is such that all references (at least the ones I saw) only point out shelfful to be the rare example? Why not scaffold or afford or effort etc.? PS: For the scope of this question, I'm restricting to ligatures with the leading character f only. A: Shelfful is different from scaffold because it is a compound word (shelf + full), so the two f's are truly separate. Removing the ligature between the f's re-emphasizes this construction. Selffulfilling is another one that makes a little more sense without the ligature (selffulfilling). Not all fonts ligature anyways, so in my browser shelffull and "shelffull" have a ligature, but monospaced fonts (shelffull shelffull) do not. (see image below) EDIT: Ahhh....apparently some designers do offer monospaced fonts with ligatures - Nathan Tuggy gives Monoid as an example.
{ "pile_set_name": "StackExchange" }
Q: How to get total RAM size of a device? I want to get full RAM size of a device. memoryInfo.getTotalPss() returns 0. There is not function for get total RAM size in ActivityManager.MemoryInfo. How to do this? A: As of API level 16 you can now use the totalMem property of the MemoryInfo class. Like this: ActivityManager actManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo(); actManager.getMemoryInfo(memInfo); long totalMemory = memInfo.totalMem; Api level 15 and lower still requires to use the unix command as shown in cweiske's answer. A: Standard unix command: $ cat /proc/meminfo Note that /proc/meminfo is a file. You don't actually have to run cat, you can simply read the file. A: I can get the usable RAM memory in such a way public String getTotalRAM() { RandomAccessFile reader = null; String load = null; DecimalFormat twoDecimalForm = new DecimalFormat("#.##"); double totRam = 0; String lastValue = ""; try { reader = new RandomAccessFile("/proc/meminfo", "r"); load = reader.readLine(); // Get the Number value from the string Pattern p = Pattern.compile("(\\d+)"); Matcher m = p.matcher(load); String value = ""; while (m.find()) { value = m.group(1); // System.out.println("Ram : " + value); } reader.close(); totRam = Double.parseDouble(value); // totRam = totRam / 1024; double mb = totRam / 1024.0; double gb = totRam / 1048576.0; double tb = totRam / 1073741824.0; if (tb > 1) { lastValue = twoDecimalForm.format(tb).concat(" TB"); } else if (gb > 1) { lastValue = twoDecimalForm.format(gb).concat(" GB"); } else if (mb > 1) { lastValue = twoDecimalForm.format(mb).concat(" MB"); } else { lastValue = twoDecimalForm.format(totRam).concat(" KB"); } } catch (IOException ex) { ex.printStackTrace(); } finally { // Streams.close(reader); } return lastValue; } Tested Upto Android 4.3 : SAMSUNG S3
{ "pile_set_name": "StackExchange" }
Q: How to use Sed or Perl to sort given text file based on 2nd column number of string in a descending manner How to use Sed or Perl to sort given text file based on 2nd column number of string in a descending manner Input.txt 123|N1-G23-H40-K1-A11-C12-J12|banana|boy 123|Z12|Goal|test 123|F1-B23-G39-M22-Z12|some|girl 123|E1-T23-N12|car|girl 123|N1-G23-H40-K1-A11-C12|banana|boy 123|V1-M12|car|girl 123|P1-G23-H40-K1|school|boy Output.txt 123|N1-G23-H40-K1-A11-C12-J12|banana|boy 123|N1-G23-H40-K1-A11-C12|banana|boy 123|F1-B23-G39-M22-Z12|some|girl 123|P1-G23-H40-K1|school|boy 123|E1-T23-N12|car|girl 123|V1-M12|car|girl 123|Z12|Goal|test A: With the Schwartzian Transform in Perl, please try the following: perl -e ' print map { $_->[0] } sort { $b->[1] <=> $a->[1] } map { [$_, length((split(/\|/))[1])] } <>; ' input.txt Output: 123|N1-G23-H40-K1-A11-C12-J12|banana|boy 123|N1-G23-H40-K1-A11-C12|banana|boy 123|F1-B23-G39-M22-Z12|some|girl 123|P1-G23-H40-K1|school|boy 123|E1-T23-N12|car|girl 123|V1-M12|car|girl 123|Z12|Goal|test [How it works] To understand the algorithm, it will be convenient to read the script from the bottom to the top. The first function: map { [$_, length((split(/\|/))[1])] } <>; reads the input file, then generates a 2-D list which holds the input line itself in the 1st column and the length of the 2nd fileld in the 2nd column something like as: [["123|N1-G23-H40-K1-A11-C12-J12|banana|boy\n", 25], ["123|Z12|Goal|test\n", 3], ["123|F1-B23-G39-M22-Z12|some|girl\n", 13], ...]] The second function: sort { $b->[1] <=> $a->[1] } sorts the list by the values in the 2nd columns in descending order and the result will look like: [["123|N1-G23-H40-K1-A11-C12-J12|banana|boy\n", 25], ["123|N1-G23-H40-K1-A11-C12|banana|boy\n", 21], ["123|F1-B23-G39-M22-Z12|some|girl\n", 18], ...]] The final function: print map { $_->[0] } extracts the 1st columns and prints the result. The Schwartzian transform is a useful and efficient technique (or an idiom) to sort a list by a certain property of the elements of the list.
{ "pile_set_name": "StackExchange" }
Q: Image smoothBitmapContent doesn't work? recently I got a jagged image problem when scaling. I set my image components smoothBitmapContent true, and it works properly the first time, but if I reset the source, the images return jagged. It seems like the smoothBitmapContent property has been changed to false, but it doesn't work even if I set it to true in run time. Anyone knows how to fix this? Thanks. Here's is my code: <custom1:SmoothImage id="MJCard_3_36" x="286.5" y="56.65" scaleX="0.66" scaleY="0.83" smoothBitmapContent="true"/> MJCard_3_36.source = seabedPicArr[index1-1][index2-1][index3-1]; I simply use a custom Image-extended class and switch smoothBitmapContent on, and I set the image's source in run time. A: To enable smoothing with dynamically loaded images, you need to listen to Event.COMPLETE on Image. Then get content (it should be Bitmap) and set smoothing to true: var image:Image = new Image(); image.addEventListener(Event.COMPLETE, onLoaded); image.source = ... function onLoaded(event:Event):void { event.target.content.smoothing = true; }
{ "pile_set_name": "StackExchange" }
Q: How to edit individual fields in ASP.NET MVC? I want to be able to update fields of my models by showing the values and then having a little "edit" button next to it, which would turn the label into textbox/dropdownlist and the edit button should disappear and instead show a Save and Cancel buttons. The save and cancel buttons should disappear when you click on them or on any other thing in the page (and the edit button should come back) . I'm pretty sure that this will require some javascript (hopefully it could be done all in jQuery). Do you have any suggestions (links/tutorials) on how to achieve this? Thanks! A: This article might help you out http://www.appelsiini.net/projects/jeditable Also, just Google "jquery edit in place" and there should be a lot of articles to help you out.
{ "pile_set_name": "StackExchange" }
Q: Stuck completing my first rails app I was taking a tutorial online on rails but I got stuck. These are my controller and view files: /app/controllers/todos_controller.rb: class TodosController < ApplicationController def index @todo_array = [ "Buy Milk", "Buy Soap", "Pay bill", "Draw Money" ] end end /app/views/todos/index.html.erb: <title>Shared Todo App </title> <h1>Shared Todo App</h1> <p>All your todos here</p> <ul> <% @todo_array.each do |t| %> <li> #todo item here </li> <% end %> </ul> I need to change the code #todo item here to show the actual todo item from the array. So I get output as: Shared Todo App All your todos here - Buy Milk - Buy Soap - Pay bill - Draw Money A: <title>Shared Todo App </title> <h1>Shared Todo App</h1> <p>All your todos here</p> <ul> <% @todo_array.each do |t| %> <li> <% t %> </li> <% end %> </ul> But since you're getting stuck on that part, I suggest you start with a different tutorial or book, something that explains a bit more about what you're doing and why. http://ruby.railstutorial.org/ruby-on-rails-tutorial-book
{ "pile_set_name": "StackExchange" }
Q: Generics design pattern for holding a list of varying types I have a Column class: class Column<T> where T : IComparable, IConvertible { private List<T> _records; ... } and a table class that should hold many columns of varying datatypes. class Table { private List<Column> columns; ... } Obviously this wont compile but I am after a standard design pattern for handling this idea. Any ideas? A: You could use a common, non-generic base class or interface: // or maybe interface IColumn instead, depending on your needs class Column { // any non-generic stuff common to all columns } class Column<T> : Column where T : IComparable, IConvertible { // any generic stuff specific to Column<T> } class Table { private List<Column> _columns; }
{ "pile_set_name": "StackExchange" }
Q: Backbone.js async calls I've been searching about this and haven't found an answer yet. I found out that you can use async: true when calling fetch on Backbone, which isn't mentioned in its website. Can other methods, such as save, create, etc., be used with async too? A: Have a look at Backbone.sync documentation : Backbone.sync is the function that Backbone calls every time it attempts to read or save a model to the server. By default, it uses jQuery.ajax to make a RESTful JSON request and returns a jqXHR. It means you can use all jQuery.ajax options on you requests, and you can indeed set an async option (defaults to true) on save/create
{ "pile_set_name": "StackExchange" }
Q: How does RegExp.exec Populate Its Results Array I'm playing with a some regular expressions and, while looking at some of my matches, I became curious as to why a the exec function produced as many results as it did. I'm simply seeking a little clarification on the inner workings of the operation so that I can feel more comfortable with why a regular expression is returning n results, instead of just accepting that it does. Ex. var invalidValues = new RegExp( "\\bZIP or City & State$|" + "\\bCity & State or ZIP$|" + "\\bEm[ai][ia]l Address(\\s\\(Optional\\)|$)|" + "^$", "gi"); invalidValues.exec("Zip or City & State"); //returns ["Zip or City & State", undefined] In the example above, I get why it's matching "Zip or City & State", but I don't know why a second match is being produced with an undefined value. Thanks in advance. A: I'm not familiar with Proof General, but it looks as though exec returns only a single match at a time. The results that you're seeing are: "Zip or City & State" — the complete matched substring. undefined — the substring captured by the (\\s\\(Optional\\)|$) capture-group. Or not captured, in this case, because that capture-group is inside a non-matching alternand. To remove the latter, you can (presumably) change the ( to (?:, marking it as a non-capturing group. To retrieve subsequent matches, you likely need to call exec multiple times.
{ "pile_set_name": "StackExchange" }
Q: Which is better for building an API for my website: MVC or Ado.net data services? I have a website built with MVC, and now I want to build an API for this website, to let users to use this API to implement different website, web services, plugins and browser extensions. I went through this article but didn't get yet which to use. General info about the API I want to build: The user of the API will have a key user name and password to be able to use the API. API will let users add content to my DB after validating this data. API will let users upload images to my server. API need to have friendly URLs. Which technology will fit in my case? Also will help me decide is to know what is the technology behind stackoverflow API? A: Try WCF Web Api. It has got all the cool stuff to create good RESTFul api, and it satisfies all your requirements. You will use basic or some custom http authorization, simple as that. You will expose very basic urls for creating data, validate and return response, trivial. RESTFul means friendly url -s. The general idea is that this library gives you strong manipulation options from the very start of request till its response back. This is the main HTTP api for .NET Framework and WCF and it continues its evolution. A: Have you considered instead using OpenRasta? Its clean, ReSTful approach makes it ideally suited to developing web-based APIs in .NET.
{ "pile_set_name": "StackExchange" }
Q: What mechanism is used to measure ocean currents from cables? The volume transport of the Florida Current (one of the parts of the Gulf Stream) is measured using an underwater cable. What are the processes that allow for these measurements? How can we obtain measurements from a cable? Where else is this technique applied? Image from http://oceancurrents.rsmas.miami.edu/atlantic/florida.html A: The most likely explanation is that a device similar to a hot wire anemometer has been used; but one that has been designed to be used in oceans. A hot wire anemometer is basically an electric heater that has been calibrated. The heating element radiates heat into a surrounding medium, depending on the design and construction of the anemometer, either air or water. The greater the heat loss, the greater the flow of the cooling medium over the anemometer element. By calibrating the anemometer it is possible to determine the velocity of the medium, in this case ocean current, over the anemometer and from that it is possible to determine the volume flow rate. Solid state devices, using silicon transistor sensors have also been developed to measure ocean currents. A: From Prandle 19791: The flow of water across the vertical component of the Earth's magnetic field induces a potential gradient in the water; measurements of the difference in voltage between the opposite sides of a tidal channel provide an indication of the magnitude of the tidal flow I imagine that having a cable across the channel enables an accurate comparison of voltage on either side. I suspect that this is a large-scale example of the Hall Effect, but that part of my physics is too rusty to say for sure! 1 D. Prandle, "Anomalous results for tidal flow through the Pentland Firth", Nature vol 278, pp 541-542 http://www.homepages.ed.ac.uk/shs/Tidal%20Stream/Prandle%20phase%20anomaly.pdf Maxwell showed that the motion of electrically charged particles in any magnetic field creates an electric field. The two fields would be perpendicular to one another. As seawater containing a large amount of ions (it is salty after all) moves through Earth's magnetic field in ocean currents, it generates the an electric field that as the theory predict will be perpendicular to the water current. The electric field is the result of the vertically average effect of the ocean motion. When a submarine cable is available between two points, the change in electrical current at both ends of the cable can be measured. The change will be proportional to the "vertically integrated ocean current" or ocean current transport (the total flux of water through a given area). The first demonstrations were conducted by Henry Stommel in the 1950's. A full array of measurements are conducted in the Florida Straits taking advantage of submarine cables connecting Florida and Bahamas. The sources of errors and variability were discussed by Larsen, 1992. NOAA AOML provides a good description of the theory and applications. Stommel, H., 1957. Florida Straits Transports, 1952-1956. Bulletin of Marine Science, 7(3), pp.252-254.
{ "pile_set_name": "StackExchange" }
Q: How to implement a method to generate Poincaré sections for a non-linear system of ODEs? I have been trying to work out how to calculate Poincaré sections for a system of non-linear ODEs, using a paper on the exact system as reference, and have been wrestling with numpy to try and make it run better. This is intended to run within a bounded domain. Currently, I have the following code import numpy as np from scipy.integrate import odeint X = 0 Y = 1 Z = 2 def generate_poincare_map(function, initial, plane, iterations, delta): intersections = [] p_i = odeint(function, initial.flatten(), [0, delta])[-1] for i in range(1, iterations): p_f = odeint(function, p_i, [i * delta, (i+1) * delta])[-1] if (p_f[Z] > plane) and (p_i[Z] < plane): intersections.append(p_i[:2]) if (p_f[Z] > plane) and (p_i[Z] < plane): intersections.append(p_i[:2]) p_i = p_f return np.stack(intersections) This is pretty wasteful due to the integration solely between successive time steps, and seems to produce incorrect results. The original reference includes sections along the lines of whereas mine tend to result in something along the lines of Do you have any advice on how to proceed to make this more correct, and perhaps a little faster? A: To get a Pointcaré map of the ABC flow def ABC_ode(u,t): A, B, C = 0.75, 1, 1 # matlab parameters x, y, z = u return np.array([ A*np.sin(z)+C*np.cos(y), B*np.sin(x)+A*np.cos(z), C*np.sin(y)+B*np.cos(x) ]) def mysolver(u0, tspan): return odeint(ABC_ode, u0, tspan, atol=1e-10, rtol=1e-11) you have first to understand that the dynamical system is really about the points (cos(x),sin(x)) etc. on the unit circle. So values different by multiples of 2*pi represent the same point. In the computation of the section one has to reflect this, either by computing it on the Cartesian product of the 3 circles. Let's stay with the second variant, and chose [-pi,pi] as the fundamental period to have the zero location well in the center. Keep in mind that jumps larger pi are from the angle reduction, not from a real crossing of that interval. def find_crosssections(x0,y0): u0 = [x0,y0,0] px = [] py = [] u = mysolver(u0, np.arange(0, 4000, 0.5)); u0 = u[-1] u = np.mod(u+pi,2*pi)-pi x,y,z = u.T for k in range(len(z)-1): if z[k]<=0 and z[k+1]>=0 and z[k+1]-z[k]<pi: # find a more exact intersection location by linear interpolation s = -z[k]/(z[k+1]-z[k]) # 0 = z[k] + s*(z[k+1]-z[k]) rx, ry = (1-s)*x[k]+s*x[k+1], (1-s)*y[k]+s*y[k+1] px.append(rx); py.append(ry); return px,py To get a full picture of the Poincare cross-section and avoid duplicate work, use a grid of squares and mark if one of the intersections already fell in it. Only start new iterations from the centers of free squares. N=20 grid = np.zeros([N,N], dtype=int) for i in range(N): for j in range(N): if grid[i,j]>0: continue; x0, y0 = (2*i+1)*pi/N-pi, (2*j+1)*pi/N-pi px, py = find_crosssections(x0,y0) for rx,ry in zip(px,py): m, n = int((rx+pi)*N/(2*pi)), int((ry+pi)*N/(2*pi)) grid[m,n]=1 plt.plot(px, py, '.', ms=2) You can now play with the density of the grid and the length of the integration interval to get the plot a little more filled out, but all characteristic features are already here. But I'd recommend re-programming this in a compiled language, as the computation will take some time.
{ "pile_set_name": "StackExchange" }
Q: Devise's current_user only works for admins I've got a standard User model, it has in it an admin boolean. All's well and good for users that have that set to true, but for normal users I get this error: undefined local variable or method `current_user' app/models/doc.rb:18:in `mine' app/controllers/docs_controller.rb:9:in `index' The Doc model on line 18 reads like this: def self.mine where(:user_id => current_user.name, :retired => "active").order('created_at DESC') end My User model looks like this: class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable attr_accessor :current_password attr_accessible :name, :password, :password_confirmation, :current_password, :email, :remember_me, :admin end class Ability include CanCan::Ability def initialize(user) can :manage, :all if user.admin end end And in my application controller I have the following: class ApplicationController < ActionController::Base protect_from_forgery after_filter :user_activity rescue_from CanCan::AccessDenied do |exception| redirect_to root_path end def admin? self.admin == true end def authenticate_admin redirect_to :new_user_session_path unless current_user && current_user.admin? end private def user_activity current_user.try :touch end end I think that's everything relevant. I can't for the life of me figure this out. A: the current_user helper is a controller method that is not accessible from a model. You should pass current user in as a parameter from the controller to the model. def self.mine(current_user) where(:user_id => current_user.name, :retired => "active").order('created_at DESC') end EDIT: Side note It looks like user_id is a string in your logic. If this is what you are doing, you should reconsider. Setting up a belongs_to and a has_many with rails using identifiers in the database is far more maintainable. Using string ids is unconventional, and its a rabbit hole that ends in very bad places.
{ "pile_set_name": "StackExchange" }
Q: NullPointerException with Custom ArrayAdapter Sorry if I may sound stupid; I'm new to Android. I've checked other SO posts with similar problems, but nothing is helping me. I'm making a custom ArrayAdapter, but a NullPointerException is being thrown when the adapter is set to to the list. Here's the fragment XML layout (fragment_lines) with the list: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/lines_list_view" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> Here's the list item layout (lines_list_item): <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <View android:layout_width="40dp" android:layout_height="40dp" android:layout_margin="16dp" android:id="@+id/line_icon" android:background="@drawable/red_circle" /> <TextView android:layout_width="40dp" android:layout_height="40dp" android:id="@+id/line_letter" android:text = "R" android:textColor="#FFFFFF" android:gravity="center" android:textSize="25sp" android:layout_marginTop="16dp" android:layout_marginLeft="-56dp" /> <TextView android:layout_width="wrap_content" android:layout_height="40dp" android:id="@+id/line_name" android:text = "Red Line" android:textSize="16sp" android:textColor="#000000" android:gravity="center" android:layout_marginTop="13dp" android:layout_marginLeft="16dp" /> </LinearLayout> Here's the custom ArrayAdapter class (LineAdapter): package com.example.android.testapp; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.text.Layout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; /** * Created by Shubhang on 2/16/2015. */ public class LineAdapter extends ArrayAdapter<String> { Activity context; int[] icons; String[] letters; String[]lines; String[] letterColors; public LineAdapter(Activity context, int[] icons, String[] letters, String[] lines, String[] letterColors) { super(context, R.layout.lines_list_item, letters); this.context = context; this.icons = icons; this.letters = letters; this.lines = lines; this.letterColors = letterColors; } @Override public View getView(int position, View convertView, ViewGroup parent) { View rowView = convertView; if (rowView == null) { LayoutInflater inflater = context.getLayoutInflater(); rowView = inflater.inflate(R.layout.lines_list_item, null); } View icon = rowView.findViewById(R.id.line_icon); TextView letter = (TextView) rowView.findViewById(R.id.line_letter); TextView line = (TextView) rowView.findViewById(R.id.line_name); icon.setBackgroundResource(icons[position]); letter.setText(letters[position]); line.setText(lines[position]); letter.setTextColor(Color.parseColor(letterColors[position])); return rowView; } } Finally, here's the MainActivity: package com.example.android.testapp; import android.accounts.Account; import android.accounts.AccountManager; import android.content.ContentResolver; import android.os.AsyncTask; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.ListView; import com.example.android.testapp.data.SubwayContract; import com.example.android.testapp.data.SubwayProvider; import com.example.android.testapp.sync.CommuterSyncAdapter; import com.google.transit.realtime.GtfsRealtime; import java.io.IOException; import java.net.URL; public class MainActivity extends ActionBarActivity { SubwayProvider provider; Account mAccount; private static final String LOG_TAG = CommuterSyncAdapter.class.getSimpleName(); int[] icons = {R.drawable.red_circle, R.drawable.blue_circle, R.drawable.brown_circle, R.drawable.green_circle, R.drawable.orange_circle, R.drawable.purple_circle, R.drawable.pink_circle, R.drawable.yellow_circle}; String[] letters = {"R", "B", "B", "G", "O", "P", "P", "Y"}; String[] lines = {"Red Line", "Blue Line", "Brown Line", "Green Line", "Orange Line", "Purple Line", "Pink Line", "Yellow Line"}; String[] letterColors = {"#FFFFFF", "#FFFFFF", "#FFFFFF", "#FFFFFF", "#FFFFFF", "#FFFFFF", "#FFFFFF", "#000000"}; ListView list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new LinesFragment()) .commit(); } LineAdapter adapter = new LineAdapter(MainActivity.this, icons, letters, lines, letterColors); list = (ListView) findViewById(R.id.lines_list_view); list.setAdapter(adapter); ... } ... } The stack trace is telling me that there's a NullPointerException on line 51 of MainActivity (this line: list.setAdapter(adapter);). I've combed through LineAdapter and can't seem to find anything wrong. Can someone please help? Thanks in advance. A: I think you are confusing fragments and layouts. Your setContentView is loading this XML file activity_main And seems like the ListView lines_list_view is in fragment_lines So, fix that part, add that ListView to you activity_main or set fragment_lines as your ContentView and check again.
{ "pile_set_name": "StackExchange" }
Q: Why do we even use passwords / passphrases next to biometrics? In the last couple of days there were a lot of talking about passwords and passphrases, not only here, but on several blogs and forums I follow (especially after XKCD #936 saw the light of this world). I heard quite a few pros and cos of both of them and this got me thinking. Why do we use password and passphrase at all instead of biometrics? I know biometrics are not the holy grail of authentication and/or identification, but (And the most popular password is... from ZDNET) at least I can be pretty sure that majority of users won't have the very same and easy to guess biometrics. Also I can't forget my finger or iris (while I can forget password / passphrase). With the era of cloud coming, the major strength of passphrases (length) might easly be ephemeral. Like I said, I know biometrics are not perfect, but if we know that passwords / passphrases are the Achilles' heel of almost every system, why are biometrics underused? According to Tylerl (Biometric authentication in the real world from this site, second answer), biometrics is used even less than it used to be. I mean, even if fingerprints are easily forged, it's still better than having many users with password 123456 or qwertz, at least from my point of view (feel free to prove me wrong). So, in short, what are the biggest problems / obstacles which are stalling widespread adoption of biometrics? EDIT I won't comment each reply, but put my thoughts here. Also I would like to clarify some things. Problem of normalization I don't know how is it in USA, but in UK law states that you need at least 5 (or 7, I'm not sure) referent points used in matching. This means that even if you don't have perfect scan, system can still do matching against vector (which is representing fingerprint) stored in DB. System will just use different referent points. If you are using face as biometric characteristic EBGM can recognized person even if face is shifted by ~45°. Problem of not-changeable (characteristics) Well, you can actually change characteristics - it's called cancelable biometric. It's working similar as salting. The beauty of cancelable biometric is that you can apply transformation daily is needed (reseting password every day could result in a lot of complains). Anyway, I feel like the most of you are only thinking about fingerprint and face recognition, while in fact there are much more characteristics which system can use for authentication. In bracket I'll mark the chances of fraudery - H for high, M for medium and L for low. iris (L) termogram (L) DNA (L) smell (L - ask dogs if you don't believe me :] ) retina (L) veins [hand] (L) ear (M) walk (M) fingerprint (M) face (M) signature (H) palm (M) voice (H) typing (M) Ok, let say biometric hardware is expensive and for simple password you have everything you need - your keyboard. Well, why there aren't systems who are using dynamic of typing to harden the password. Unfortunately, I can't link any papers as they are written in Croatian (and to be honest, I'm not sure do I even have them on this disk), however few years ago two students tested authentication based on dynamic of typing. They made simple dummy application with logon screen. They uploaded application on one forum and post the master password. At the end of this test there were 2000 unique tries to log with correct password into the application. All failed. I know this scenario is almost impossible on the webpages, but locally, this biometric characteristic without need of any additional hardware could turn 123456 password into fairly strong one. P.S. Don't get me wrong, I'm not biometric fanboy, just would like to point out some things. There are pretty nice explanations like - cost, type 2 error, user experience,... A: Passwords and biometrics have distinct characteristics. Passwords are secret data. Data is abstract: it flows quite freely across networks. Cryptography defines many algorithms which can use secret data to realize various security properties such as confidentiality and authentication. The shortcomings of passwords are due to the fact that they are meant to be memorized by human beings (otherwise we would just call them "keys") and this severely limits their entropy. Biometrics are measures of the body (in a wide sense) of a human user. Being measures, they are a bit fuzzy: you cannot take a retinal scan and convert it into a sequence of bits, such that you would get the exact same sequence of bits every time. Also, biometrics are not necessarily confidential: e.g. you show your face to the wide World every time you step out of your home, and many face recognition systems can be fooled by holding a printed photo of the user's face. Biometrics are good at linking the physical body of a user to the computer world, and may be used for authentication on the basis that altering the physical body is hard (although many surgeons make a living out of it). However, this makes sense only locally. There is a good illustration in a James Bond movie (one with Pierce Brosnan; I don't remember which exactly): at some point, James is faced with a closed door with a fingerprint reader. James is also equipped with a nifty smartphone which includes a scanner; so he scans the reader, to get a copy of the fingerprint of the last person who used it, and then he just puts his phone screen in front of the reader; and lo! the door opens. This is a James Bond movie so it is not utterly realistic, but the main idea is right: a fingerprint reader is good only insofar as "something" makes sure that it really reads a genuine finger attached to its formal owner. Good fingerprint readers verify the authenticity of the finger through various means, such as measuring temperature and blood pressure (to make sure that the finger is attached to a mammal who is also alive and not too stressed out); another option being to equip the reader with an armed guard, who checks the whole is-a-human thing (the guard may even double as an extra face recognition device). All of this is necessarily local: there must be an inherently immune to attacks system on the premises. Now try to imagine how you could do fingerprint authentication remotely. The attacker has his own machine and the reader under his hand. The server must now believe that when it receives a pretty fingerprint scan, it really comes from a real reader, which has scanned the finger just now: the attacker could dispense with the reader altogether and just send a synthetic scan obtained from a fingerprint he collected on the target's dustbin the week before. To resist that, there must be a tamper-resistant reader, which also embeds a cryptographic key so that the reader can prove to the server that: it is a real reader; the scan it sent was performed at the current date; whatever data will come along with the scan is bound to it (e.g. the whole communication is through TLS and the reader has verified the server certificate). If you want to use the typing pattern, the problem is even more apparent: the measuring software must run on the attacker's machine and, as such, cannot be really trustworthy. It becomes a problem of defeating reverse engineering. It might deter some low-tech attackers, but it is hard to know how much security it would bring you. Security which cannot be quantified is almost as bad as no security at all (it can even be worse if it gives a false sense of security). Local contexts where there is an available honest systems are thus the contexts where biometrics work well as authentication devices. But local contexts are also those where passwords are fine: if there is an honest verifying system, then that system can enforce strict delays; smartcards with PINs are of that kind: the card locks out after three wrong PINs in a row. This allows the safe use of passwords with low entropy (a 4-digit PIN has about 13 bits of entropy...). Summary: biometrics can bring good user authentication only in situations where passwords already provide adequate security. So there is little economic incentive to deploy biometric devices, especially in a Web context, since this would require expensive devices (nothing purely software; it needs tamper-resistant hardware). Biometrics are still good at other things, e.g. making the users aware of some heavy security going on. People who have to get their retina scanned to enter a building are more likely to be a bit less careless with, e.g., leaving open windows. A: Abstracted across a network, most biometrics implementations can still be boiled down to the category of "something you know". For a discussion of how that happens with "something you have," take a look at How is "something you have" typically defined for "two-factor" authentication?. Biometrics suffers from a problem where once a credential is compromised, you can't change it. There are also some rather amusing compromises against fingerprint systems. Biometrics are great in certain areas, but logging into my bank account with a generic device and no password is not one of them. Finally, because there is no uniform standard, there's a cost issue that's hard to surmount. Not only are devices not already an integral part of the computer like a keyboard is, but they different models need different systems to interface with them. A: There are significant problems with all of these as a primary identifier. For example: Fingerprints/Palm - What happens if I fall off my bike and scuff my hand across the ground? My fingerprints are ruined for some time - possibly permanently. DNA - have you seen how easy it is to pick up blood or other material containing DNA? Typing - this has some success, but the responses depend on tiredness, emotional state, differing keyboards etc They are all susceptible to both false positives and negatives - you can get that crossover point down to a low level, but you can't eradicate it entirely. When compromised, you cannot change the identifier - this problem rules it out entirely! Another issue with some of the biometrics generally considered more resistant to attack (for example the retina pattern) is that users really dislike the invasive nature of the scan. While many end users now accept a fingerprint scanner (despite fingerprints being proven not to be unique) having a retina scanner is seen as intrusive and even scary. So the current process - use ID, password, token etc as initial identifiers (all replaceable if needed - things you know or have ) and a biometric as an additional preventative measure do mitigate the risk of the previous mechanisms being stolen and used by an attacker (something you probably are) seems to be the optimum in terms of: support resilience layered security
{ "pile_set_name": "StackExchange" }
Q: how do I change the button color in js? This is my code it is called when a button is clicked in html I dont know why the button is not going black/white Actually it worked just fine before I put my php code in my html file The alert with "asdf" is just to check if my code executing or not function checkp(event){ var x=event.currentTarget; var button_type=document.getElementsByTagName("button"); for(var i=0;i<button_type.length;i++) { if(button_type[i].id==x.id){ // alert(button_type[i].id); var index=i; } } var start=0; var end=button_type.length; for(var q=start;q<=end;q++) { if(q==index) { alert("asdf"); button_type[q].style.filter="grayscale(0)"; button_type[q].style.padding="3cm"; } else{ button_type[q].style.filter="grayscale(100%)"; button_type[q].style.padding=""; } } } This is how my buttons are declared in html <button id ="love" type="button" ><img src="love.png" alt="notfound" width="30" height="30"/></button> <button id ="haha" type="button" ><img src="haha.png" alt="notfound" width="30" height="30"/> </button> <button id ="wow" type="button" ><img src="wow.jpg" alt="notfound" width="30" height="30"/> </button> <button id ="Angry"type="button" ><img src="angry.png" alt="notfound" width="30" height="30"/> </button> <button id ="sad" type="button" ><img src="sad.png" alt="notfound" width="30" height="30"/> </button> and this is how I called the js function var x=document.getElementsByTagName("button"); for(var v=0;v<x.length;v++) { x[v].addEventListener("click",checkp,false); } A: Can you share the html? Does the ID of each of your buttons start from 0 and increment by 1? If not, then there is an error with this line as id = "" and not a number. LINE 6: if(button_type[i].id==x.id){ What are you trying to achieve with this code? If you tell us what you want it to do with some html then i can definitely help!
{ "pile_set_name": "StackExchange" }
Q: Query with date condition in where clause returns no rows but works in SQL Developer Thanks in advance if anyone can help... this is driving me crazy! I have a query like select * from tranHistory where itemid = 10 and created_dttm >= '21-Feb-2012'; Simple, right? Run from vb.net it returns no rows. Run from SQL Developer it returns 99 rows. I originally thought it was a parameter problem as the query used to look like select * from tranHistory where itemid = 10 and created_dttm >= :tranHistoryDate; In the original query there were two other parameters and I verified they were in the right order. I simplified it to this form to eliminate as many variables as possible. We're using Oracle 11g, Visual Studio 2010, and Oracle ODP.Net for the data provider. I cannot for the life of me figure out why this fails! A: To eliminate connection problems, if you remove the restriction on date from the WHERE clause, does it return any data in vb.net? If so, it's most likely a date string parsing issue. Check the NLS settings on the server, or try using a language agnostic date format like this: and created_dttm >= TO_DATE('20120221', 'YYYYMMDD'); If removing the date results in no data being returned, it is almost certainly not a problem with your query, but a problem with the connection to the database. Is it connecting to the same schema as from SQL Developer?
{ "pile_set_name": "StackExchange" }
Q: Can any one explain why StreamWriter is an Unmanaged Resource. Want to understand what part of StreamWriter source code is Unmanaged code. Have went through the code in http://referencesource.microsoft.com/ website. But it seems to be complex code to understand,there is good comments in the source code. But still had tough time to understand, may be my knowledge is not upto that mark. However , if anybody has any blog or article that can answer this question. it will be great !!! A: StreamWriter is not an unmanged resource, its a .NET class, and it is 100% managed. Another totally different thing is that StreamWriter might internally use unmanaged resources or own an IDisposable object that in turn might use an unmanaged resource, or simply extends a class that implements IDisposable. The latter two are the reasons why StreamWriter implements IDisposable, but beware, implementing IDisposable does not necessarily mean that the class uses directly or indirectly unmanaged resources. In the particular case of StreamWriter, it is obvious that it might indirectly consume unmanged resources; the underlying stream (the IDisposable instance field Stream stream) could be a FileStream which obviously consumes unmanaged resources (a file in your HD for instance). But its also very possible that the underlying stream doesn't use any unmanaged resources, but as Colin Mackay correctly points out in commentaries below, all streams must implement a consistent interface which the abstract class Stream provides.
{ "pile_set_name": "StackExchange" }
Q: InputStreamReader should end if there are no more lines I have an InputStreamReader (which is combined with a BufferedReader). I want to read the content of the Stream in a loop while((line = MyStream.readLine()) != null) { s.o.p(line); String lastline; } but this creates a loop without an end, so my whole program waits for the loop to end .. and waits ... and waits. At the moment, I've got a method where you can say how many lines should be read. This works fine, but is very inflexible. My method at the moment public void getStatus(int times) throws IOException { for (int i = 0; i < times; i++) { System.out.println(fromServer.readLine()); } I want this method to read all lines and save the last one in a string without the "times" parameter. A: The code you've got will work if it reaches the end of a stream. My guess is that this is a network stream, and the other end isn't closing the connection. That won't end up with you going into the loop ad infinitum though - it'll end up with you just hanging on the readLine call, waiting for either the other end to close the stream, or for more data to arrive. You need to either have some way of detecting you're finished (e.g. a terminating line / the connection closing) or know how many lines to read ahead of time.
{ "pile_set_name": "StackExchange" }
Q: Ajuda com o uso de delay ou setTimeout do JS Estou tentando criar uma função de loop que fica alternando entre 2 divs. Mas o resultado é que na hora de recomeçar a função, não consigo fazer ela esperar novamente os 5 segundos de intervalo da alternância, gerando um resultado visual errado. Segue a função: $(document).ready(function(){ ciclos(); function ciclos(){ $(".slide:first-child").fadeIn(1000).delay(5000).fadeOut(1000); $(".slide:nth-child(2)").delay(6000).fadeIn(1000).delay(5000).fadeOut(1000); setTimeout(ciclos, 5000); } }) A: Se quer que duas animações em elementos diferentes sejam feitas em sequência tem de chamar uma na função de completar da outra. Se tivermos a animação fadeIn de num <p> e queremos após essa fazer um fadeIn num <h1> teríamos que fazer o fadeIn do <h1> no callback(função que corre quando a animação completa) do fadeIn do <p>, assim: $("p").fadeIn(1000, function(){ //quando o fadeIn do p termina executa esta função $("h1").fadeIn(1000); }); Transpondo esta logica para o seu exemplo teria que o alterar para que ficasse assim: function ciclos(){ $(".slide:first-child").fadeIn(1000).delay(5000).fadeOut(1000, function(){ //esta segunda animação agora é apenas chamada quando a primeira termina $(".slide:nth-child(2)").delay(6000).fadeIn(1000).delay(5000).fadeOut(1000, function(){ //o timeout é agora só chamado quando a segunda animação termina setTimeout(ciclos, 5000); }); }); } Exemplo a funcionar (reduzi os tempos para ser mais fácil de ver que funciona): $(document).ready(function(){ ciclos(); function ciclos(){ $(".slide:first-child").fadeIn(1000).delay(2000).fadeOut(1000, function(){ $(".slide:nth-child(2)"). delay(1000).fadeIn(1000).delay(3000).fadeOut(1000, function(){ setTimeout(ciclos, 4000); }); }); } }) .slide { width:300px; height:200px; display:none; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div > <img class="slide" src="https://upload.wikimedia.org/wikipedia/commons/1/16/HDRI_Sample_Scene_Balls_%28JPEG-HDR%29.jpg"> <img class="slide" src="https://c2.staticflickr.com/4/3899/14383431886_8f0675cf95_b.jpg"> </div>
{ "pile_set_name": "StackExchange" }
Q: TypeScript React error: "Module not found: Can't resolve 'styled-components'" After installing @types/styled-components package and compiling my Typescript React app I keep getting error: Module not found: Can't resolve 'styled-components' I have dependancy in both package.json and package-lock.json and my import looks like this: import styled from 'styled-components'; I even have the auto-completion when importing and yet after compiling, aforementioned error keeps popping up. What may be causing the problem and how to fix it? A: You just installed the types for the library, not the library itself. That explains the autocompletion as that comes from the type declaration files (.d.ts). You should run npm i styled-components as well.
{ "pile_set_name": "StackExchange" }
Q: Login with angularjs and php Im going to try to build an login system with angularjs and php. However, I don't know how Im going to handle the sessions and the redirection when the user has successfully logged in? Should I start a session in the backend with PHP, and then return it to back to angular? Should I use window.location.href when Im going to redirect the user? A: You can use Php session and return it to Angular service. Then you can share your user information with service to other controllers. I recommend you to use ngRoute and shared service which contains user information. This method is very fast and secure. I just edit my answer and made a quick example for you. var doc = angular.module('doc', [ 'ngRoute' ]); doc.service('link', function () {//Creating my service this.user = false;//Here is my user object. I am changing these datas in the login section. }); doc.config(function($routeProvider, $locationProvider) { $routeProvider .when('/homepage', { templateUrl: 'view/homepage.html', controller: 'homePage', }) .when('/login', { templateUrl: 'view/login.html', controller: 'login', }) $locationProvider.html5Mode(true); }); doc.controller("login", function ($scope, $timeout, link, $location) { //As you see I sent 'link' as a parameter. So I can easily use my service and the user data. $scope.username = ""; $scope.password = ""; $scope.login = function () { $.get("/login.php", {username:$scope.username,password:$scope.password},function(data){ if(data){ link.user = JSON.parse(data); // I am parsing my json data and save to link.user $location.path("/homapage"); } }); } }); doc.controller("homePage", function ($scope, $timeout, link, $location) { //As you see I sent 'link' as a parameter. So I can easily use my service and the user data. if(link.user){ console.log(link.user); // I can access my user! }else{ $location.path("/login"); } }); As you see my service contains my user datas which I initialized at the login page. Now I am using them in my controllers easily.
{ "pile_set_name": "StackExchange" }
Q: form_open(); returns undefined function error when using in : CodeIgniter I am trying to create a master & view page layout, with Header, left menu, right content view & a footer. Each content page is written in <div>s in separate pages. With respect to my left menu link clicks, the corresponding page is loaded in content view. I used jQuery for this purpose, but when I use form_open() in content view <div>, it returns: undefined function form_open() I have tried both $autoload['helper'] = array('url','form'); and $this->load->helper('form'); But neither are working. When I use form_open() in a view page and load it via $this->load->view() in controller, I'm able to use the form_open method Here is controller class, template.php & content.php files class Home extends CI_Controller { public function index(){ $this->load->helper('form'); $this->load->library('form_validation'); $this->view(); } public function view() { $this->load->view('templates/template'); . . . } application/views/templates/template.php . . . <script type="text/javascript" charset="utf-8"> $(document).ready(function(){ $('#leftmenu_main ul li a').click(function(){ $('#content_main').load('<?=base_url()?>application/views/templates/content.php #' + $(this).attr('href')); return false; }); } <div id="leftmenu"> <div id="leftmenu_main"> <ul> <li><a href="createnewuser">Create New User</a></li> <li><a href="createnewtask">Create New Task</a></li> </ul> </div> </div> <div id="content_main"> . . . </div> application/views/templates/content.php <div id="createnewuser"> <?=form_open(controller/method);?> . . . <?=form_close();?> </div> <div id="createnewtask"> <?=form_open(controller/method);?> . . . <?=form_close();?> </div> When i use view() of Home Controller like the following, & place one of my div's "content" as a page in views/pages/ , it works & 'm able to use the form_open() tag ... public function view() { $page = 'createnewtask'; $this->load->view('templates/header'); $this->load->view('pages/'.$page); $this->load->view('templates/footer'); } I have searched a lot for this but unable to find a solution. Is there something which I need to load / configure for using form_open() in a separate page <div>? A: You are using AJAX to load the view file. $('#content_main').load('<?=base_url()?>application/views/templates/content.php #' + $(this).attr('href')); This is ajax. Problem is, you are loading the view file directly. Do not do this! That is why form_open isn't working. The view file doesn't know it's there. You need to make a controller function that calls $this->load->view('templates/content'); and set the AJAX call to that. class Home extends CI_Controller { public function index(){ $this->load->helper('form'); $this->load->library('form_validation'); $this->view(); } public function view() { $this->load->view('templates/template'); . . . } public function content(){ $this->load->view('templates/content'); } } Then change the AJAX call to: $('#content_main').load('<?=base_url()?>home/content #' + $(this).attr('href')); Now you are loading the view via the controller, which loaded the form helper, so form_open will work.
{ "pile_set_name": "StackExchange" }
Q: Measurability of a version of a random variable If $X$ is a ($\mathcal{F}$-measurable) random variable defined on a probability space $(\Omega, \mathcal{F}, \mathbf{P})$ and $Y$ is a version of $X$ in the sense that $\mathbf{P}(X \ne Y) = 0$ and $\{X \ne Y \} \in \mathcal{F}$, does it follow that $Y$ is also $\mathcal{F}$-measurable ? I am trying to prove that $\mathbf{L^2}(\Omega,\mathcal{G},\mathbf{P})$ is a closed subset of $\mathbf{L^2}(\Omega,\mathcal{F},\mathbf{P})$ for $\mathcal{G} \subseteq \mathcal{F}$ but the question of versions bothers me. If $X_n \to X$ in $\mathbf{L^2}$, then $X$ can be chosen to be $\mathcal{G}$-measurable, but $X$ might as well not be $\mathcal{G}$-measurable (unless the answer to my previous question is true). A: If the space is complete then $Y$ is measurable. Just having $\{ X \neq Y \} \in \mathcal{F}$ is not enough, because you need subsets of it to also be measurable in order to have preimages of intervals with $Y$ be measurable.
{ "pile_set_name": "StackExchange" }
Q: Why doesn't the following recursive call work? I had the following code: let rec nextUnusedInteger (r:Random) rangeMax used = let index = r.Next(0, rangeMax) match used |> List.tryFind (fun i -> i = index) with | None -> index | Some i -> nextUnusedInteger r rangeMax used let rec buildRandomIntegerList (rand:Random) rangeMax reserved count acc = match count with | 0 -> acc | _ -> let randomInteger = nextUnusedInteger rand rangeMax reserved let newCount = count - 1 buildRandomIntegerList rand rangemax randomInteger::reserved newCount randomInteger::acc I got the following compile error: Type mismatch. Expecting a 'a but given a int -> 'a list -> 'a list The resulting type would be infinite when unifying ''a' and 'int -> 'a list -> 'a list' This value is not a function and cannot be applied The problem was the inline Cons. The randomInteger::reserved and randomInteger::acc. If I explicitly make values for those, it works. Here is the revised code that works: let rec nextUnusedInteger rangeMax used = let rand = new Random() let index = rand.Next(0, rangeMax) match used |> List.tryFind (fun i -> i = index) with | None -> index | Some i -> nextUnusedInteger rangeMax used let rec buildRandomIntegerList rangeMax reserved count acc = match count with | 0 -> acc | _ -> let randomInteger = nextUnusedInteger rangeMax reserved let newCount = count - 1 let newReserved = randomInteger::reserved let newAcc= randomInteger::acc buildRandomIntegerList rangeMax newReserved newCount newAcc The question is why? I see examples all the time using the inline Cons. Why doesn't the original code work? A: You can use the inline cons but if the result is passed as function argument it needs parenthesis: buildRandomIntegerList rand rangemax (randomInteger::reserved) newCount (randomInteger::acc) Otherwise the compiler creates a partial applied function and tries to concatenate something to a function, which makes no sense and that's what the error message is telling you. The same applies to other operators, function application has priority over them.
{ "pile_set_name": "StackExchange" }
Q: Unable to add ngModel directive to angular material autocomplete I want to add an autocomplete field to a page in my angular app. I added below in my template. <mat-form-field class="example-full-width"> <input matInput placeholder="Pick one" [(ngModel)]="entity.type" [matAutocomplete]="auto"> <mat-autocomplete #auto="matAutocomplete"> <mat-option *ngFor="let option of options" [value]="option"> {{option}} </mat-option> </mat-autocomplete> </mat-form-field> But, I get following error when I navigate to the page. ERROR Error: More than one custom value accessor matches form control with unspecified name attribute Error goes away if I remove [(ngModel)]="entity.type" directive from the template. What is the reason for this error? Is there any way I can fix it? Here is a stackblitz for the issue. Error is shown in the console, which can be opened from the right bottom of the page. A: Found the issue. It was caused by the TrimValueAccessorModule which I had used in the app. When I remove the module, issue gets fixed. I could exclude the autocomplete from the TrimValueAccessorModule by using following class name in the input tag, so that I can fix the issue without removing TrimValueAccessorModule entirely. class="ng-trim-ignore"
{ "pile_set_name": "StackExchange" }
Q: UICollectionView autosize and dynamic number of rows I am trying to do something like this: Basically, I am using a UICollectionView and the cells (3 diferent .xib). So far, it works. The thing I want to do is: Set a autoheight If rotate, add 1 row to the UIColectionView 2.1 If tablet, on portrait will have 2 rows and landscape 3 rows. (which basically is the same of point 2, only adding 1 row. I have something like this: extension ViewController { override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator){ setSizeSize() } func setSizeSize(){ if(DeviceType.IS_IPAD || UIDevice.current.orientation == .landscapeLeft || UIDevice.current.orientation == .landscapeRight){ if let layout = myCollectionView.collectionViewLayout as? UICollectionViewFlowLayout { layout.estimatedItemSize = CGSize(width: 1, height: 1) layout.invalidateLayout() } }else{ if let layout = myCollectionView.collectionViewLayout as? UICollectionViewFlowLayout { layout.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize layout.invalidateLayout() } } myCollectionView.collectionViewLayout.invalidateLayout() } } Does not work. Also, it freezes device. On simulator works parcially. (I'm trusting more device) I also tried this, but it works sometimes... Please, let me know if you need more info. Thank you all in advance for the help. A: I can suggest you to create your own UICollectionViewFlowLayout subclass which would generate needed layout. Here is a simple flow layout that you can use. You can adjust it to your needs, if I missed something. public protocol CollectionViewFlowLayoutDelegate: class { func numberOfColumns() -> Int func height(at indexPath: IndexPath) -> CGFloat } public class CollectionViewFlowLayout: UICollectionViewFlowLayout { private var cache: [IndexPath : UICollectionViewLayoutAttributes] = [:] private var contentHeight: CGFloat = 0 private var contentWidth: CGFloat { guard let collectionView = collectionView else { return 0 } let insets = collectionView.contentInset return collectionView.bounds.width - (insets.left + insets.right) } public weak var flowDelegate: CollectionViewFlowLayoutDelegate? public override var collectionViewContentSize: CGSize { return CGSize(width: self.contentWidth, height: self.contentHeight) } public override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var layoutAttributesArray = [UICollectionViewLayoutAttributes]() if cache.isEmpty { self.prepare() } for (_, layoutAttributes) in self.cache { if rect.intersects(layoutAttributes.frame) { layoutAttributesArray.append(layoutAttributes) } } return layoutAttributesArray } public override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return self.cache[indexPath] } public override func prepare() { guard let collectionView = self.collectionView else { return } let numberOfColumns = self.flowDelegate?.numberOfColumns() ?? 1 let cellPadding: CGFloat = 8 self.contentHeight = 0 let columnWidth = UIScreen.main.bounds.width / CGFloat(numberOfColumns) var xOffset = [CGFloat]() for column in 0 ..< numberOfColumns { xOffset.append(CGFloat(column) * columnWidth) } var column = 0 var yOffset = [CGFloat](repeating: 0, count: numberOfColumns) for item in 0 ..< collectionView.numberOfItems(inSection: 0) { let indexPath = IndexPath(item: item, section: 0) let photoHeight = self.flowDelegate?.height(at: indexPath) ?? 1 let height = cellPadding * 2 + photoHeight let frame = CGRect(x: xOffset[column], y: yOffset[column], width: columnWidth, height: height) let insetFrame = frame.insetBy(dx: cellPadding, dy: cellPadding) let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) attributes.frame = insetFrame self.cache[indexPath] = attributes self.contentHeight = max(self.contentHeight, frame.maxY) yOffset[column] = yOffset[column] + height column = column < (numberOfColumns - 1) ? (column + 1) : 0 } } } Now in your UIViewController you can use it like this: override func viewDidLoad() { super.viewDidLoad() let flowLayout = CollectionViewFlowLayout() flowLayout.flowDelegate = self self.collectionView.collectionViewLayout = flowLayout } invalidate collectionView layout after orientation would be changed override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() guard let flowLayout = self.collectionView.collectionViewLayout as? CollectionViewFlowLayout else { return } flowLayout.invalidateLayout() } and now make your ViewController conform to CollectionViewFlowLayoutDelegate extension ViewController: CollectionViewFlowLayoutDelegate { func height(at indexPath: IndexPath) -> CGFloat { guard let cell = self.collectionView.cellForItem(at: indexPath) else { return 1 } cell.layoutIfNeeded() //get calculated cell height return cell.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height } func numberOfColumns() -> Int { //how much columns would be shown, depends on orientation return UIDevice.current.orientation == .portrait ? 2 : 3 } }
{ "pile_set_name": "StackExchange" }
Q: How to access private variable in aspectj So I have a scenario where I want to access context variable in a RESTful web service that is written using jersey. @Path("hello") public class Hello { @Context private UriInfo context; @GET @Produces("text/html") public String getHtml(@Context Request request, @Context HttpServletRequest requestss) { ... context.getBaseUri(); ... } In my aspect using @Around pointcut I can see that arguments are ARGS: [org.glassfish.jersey.internal.inject.RequestInjectee@7d9d679,org.apache.catalina.connector.RequestFacade@6e8fa5f5], so I can easily access Request object. My aspect is as follows: @Pointcut("execution(* *.getHtml(..))") public void methodCall() {} @Around("methodCall()") public Object aroundMethodCall(ProceedingJoinPoint pjp) throws Throwable { System.out.println("AROUND" + pjp.getSignature()); System.out.println("ARGS: "+ Arrays.toString(pjp.getArgs())); return pjp.proceed(); } I would like to access context variable in my aspect (to log it). In my aspect getThis() methods returns Hello class but the context field is private. Is it possible ? I am using load time weaving. A: You're going to need to do a few steps, assuming your Object reference is obj then you could try Class<?> clazz = obj.getClass(); Field field = clazz.getDeclaredField("context"); field.setAccessible(true); UriInfo context = (UriInfo) field.get(obj);
{ "pile_set_name": "StackExchange" }
Q: returning mySQL errors from php - nothing being returned on error I have a php file which performs a series of insert queries. If any of the queries generates an error, I would like to return the error message and query string and roll back all the queries So far I have this: mysql_query("SET autocommit=0;"); mysql_query("BEGIN;"); $sql ="SOME MALFORMED QUERY"; mysql_query($sql); if(mysql_error()){ mysql_query("rollback;"); $arr = array("returnCode" => 0, "returnMessage" => "Query failed: " .$sql. mysql_error()); echo json_encode($arr); die(); } However, In javascript all I'm seeing returned in the return message JSON field is 'Query failed: '. Any idea why this is? A: The problem is with your ROLLBACK query: as explained in the manual, mysql_error returns the error text from the last MySQL function. Since you used mysql_query again, the previous error is lost. I suggest this code: mysql_query("SET autocommit=0;"); mysql_query("BEGIN;"); $sql ="SOME MALFORMED QUERY"; mysql_query($sql); $error = mysql_error(); if($error){ mysql_query("rollback;"); $arr = array("returnCode" => 0, "returnMessage" => "Query failed: $sql, Error: $error"); echo json_encode($arr); die(); } Executing ROLLBACK in case an error occurs seems useless. The manual explains: Rolling back can be a slow operation that may occur implicitly without the user having explicitly asked for it (for example, when an error occurs) The following code should then be enough: mysql_query("SET autocommit=0;"); mysql_query("BEGIN;"); $sql ="SOME MALFORMED QUERY"; mysql_query($sql); if(mysql_error()){ $arr = array("returnCode" => 0, "returnMessage" => "Query failed: $sql, Error: ".mysql_error()); echo json_encode($arr); die(); }
{ "pile_set_name": "StackExchange" }
Q: multiple definition of namespace variable, C++ compilation I m writing a simple Makefile which looks like this CC=gcc CXX=g++ DEBUG=-g COMPILER=${CXX} a.out: main.cpp Mail.o trie.o Spambin.o ${COMPILER} ${DEBUG} main.cpp Mail.o trie.o Re2/obj/so/libre2.so trie.o: trie.cpp ${COMPILER} ${DEBUG} -c trie.cpp Mail.o: Mail.cpp ${COMPILER} ${DEBUG} -c Mail.cpp Spambin.o: Spambin.cpp ${COMPILER} ${DEBUG} -c Spambin.cpp clean: rm -f *.o I have a file name config.h which is required in Mail.cpp and Spambin.cpp, so I have #include "config.h" in both Mail.cpp and Spambin.cpp. config.h looks like this: #ifndef __DEFINE_H__ #define __DEFINE_H__ #include<iostream> namespace config{ int On = 1; int Off = 0; double S = 1.0; } #endif But when I try to compile the code it gives me Mail.o:(.data+0x8): multiple definition of `config::On' /tmp/ccgaS6Bh.o:(.data+0x8): first defined here Mail.o:(.data+0x10): multiple definition of `config::Off' /tmp/ccgaS6Bh.o:(.data+0x10): first defined here Can any one help me debug this? A: You can not assign to namespace variables in a header files. Doing that defines the variables instead of just declaring them. Put that in a separate source file and add that to the Makefile and it should work. Edit Also, you have to make the declarations in the header file extern. So in the header file the namespace should look like this: namespace config{ extern int On; extern int Off; extern double S; } And in the source file: namespace config{ int On = 1; int Off = 0; double S = 1.0; } A: Take a look at Variable definition in header files You have to put your variable definition, i.e. the value assignment in a source file or protect it with a #ifdef guard for not being defined twice when included in separate source files.
{ "pile_set_name": "StackExchange" }
Q: How to show subclass of UIControl in View Controller I would like to be able to interact with the UIControl I have made, and therefore want it in my ViewController. What I tried I subclassed UIControl (1). Then I added a UIView to my View Controller and assigned it the new class (2). But in Interface Builder I am not able to set my outlets to the buttons contained in the new class (1)?! 1: 2: UIControl's documentation confirms that it is a subclass of UIView, and I should therefore be able to connect the outlets, right? What am I missing here? :/ A: Off-course you can't add IBOutlet because buttons what you added to WeekdayControl are in UIViewController, you can't add Outlet to WeekdayControl, buttons only subviews of WeekdayControl, UIViewController is boss here, and you can add outlet only to UIViewController. (Sorry for my English) Better create you buttons programatically in WeekdayControl.
{ "pile_set_name": "StackExchange" }
Q: Disply zero value in cell in excel Is there any other way to display zero value in excel without using ' before zero. with zero before ' then it show zero in excel A: Check this setting in Excel (make sure it's on to display 0's) Also check the Cell's Number Format - its made up of up to 4 parts, the third is for Zero values. If the third field is blank 0's won't be displayed
{ "pile_set_name": "StackExchange" }
Q: What's the difference between [BITS 32] declaration and BITS 32, if there is any? I've seen assembly sources in the wild that uses [BITS 32] directive. I'm using compiler NASM and at its man pages, I've seen no reference to the need of the brackets, so I compiled my own source without them (just BITS 32), with no errors, and it works. Is there any difference from using or not the brackets wrapping compilers directives? A: NASM’s directives come in two types: user-level directives and primitive directives. Typically, each directive has a user-level form and a primitive form. In almost all cases, we recommend that users use the user-level forms of the directives, which are implemented as macros which call the primitive forms. Primitive directives are enclosed in square brackets; user-level directives are not. http://www.nasm.us/doc/nasmdoc6.html
{ "pile_set_name": "StackExchange" }
Q: `git mergetool`, A `fileName.~fileType` file was produced MAC produced an README.~md file When I have solved the git conflict use the command git mergetool with Beyond Compare. I think two ways to solve this, but I don't know which is the best practice. What can I do to avoid produce the .~ file? I add the *.~** into the .gitignore,and delete the *.~** file later. I found the README.~md show the detail of this conflict. It contains the unsolved conflict content. A: Beyond Compare set the Backups all backups to disable. By the way, Beyond Compare is a good tool.
{ "pile_set_name": "StackExchange" }
Q: I am trying to calculate the day of the century but I am getting this error in unix: I am starting to learn how to use C++ and currently trying to calculate what day of the century one is in with the date they submit when running my program. I am getting an error but when looking up the error it says that there is nothing to output. I am using unix on my terminal application in mac os, so I'm not sure if that affects anything. I have walked through my program with a white board many times and am still lost. Thank you so much for reviewing my question. Error: lab6.cpp: In function 'int day_of_century(int, int, int)': lab6.cpp:80:1: warning: control reaches end of non-void function [-Wreturn-type] } ^ Code: #include <library.h> //global variables: int month = 0; int year = 0; int day = 0; //this day variable is for getting the day for a date int days = 0;//this days variable is for counting an amount of days int count = 1; //functions: int length_of_month(int month, int year) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { cout << "31 Days" << endl; }//31 day if if (month == 4 || month == 6 || month == 9 || month == 11) { cout << "30 Days" << endl; }//30 day if if (month == 2) { if (year % 400 == 0 && year % 100 == 0) { cout << "29 Days" << endl; }//29 day if 1 else if (year % 4 == 0 && year % 100 == 0) { cout << "28 days" << endl; } // 28 days 1 else if (year % 4 == 0) { cout << "29 days" << endl; } // 29 days 2 else { cout << "28 Days" << endl; }//28 day else }//february return(0); } int length_of_month_value(int month, int year) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { days = 31; }//31 day if if (month == 4 || month == 6 || month == 9 || month == 11) { days = 30; }//30 day if if (month == 2) { if (year % 400 == 0 && year % 100 == 0) { days = 29; }//29 day if 1 else if (year % 4 == 0 && year % 100 == 0) { days = 28; } // 28 days 1 else if (year % 4 == 0) { days = 29; } // 29 days 2 else { days = 28; }//28 day else }//february return(days); } int day_of_year(int year, int month, int days) { if (month == 1) { days = day; }//if else { while (count < month) { days = days + length_of_month_value(count, year); count = count + 1; }//while // days = day + days; }//else return(days); } int day_of_century(int year, int month, int days) { if (year == 2000) { return(day_of_year(year, month, days)); } else if (year > 0) { return(day_of_year(year - 1, 12, 31) + day_of_century(year - 1, month, days)); } } int day_of_century(int year, int month, int days) { } //main function: int main() { //1: Length of Month: cout << "Please enter the month (numerically) with the year (numerically) and this program will tell you how many days are in that month" << endl; cout << "Month: "; cin >> month; cout << endl << "Year: "; cin >> year; cout << endl; length_of_month(month, year); cout << endl; //2: Day of the Year: year = 0; month = 0; days = 0; day = 0; cout << "Please enter the year, month, and day, and this program will tell you what day of the year that date is." << endl; cout << "Year: "; cin >> year; cout << endl << "Month: "; cin >> month; cout << endl << "Day: "; cin >> day; cout << "You are in day " << day_of_year(year, month, day) << " of the year." << endl; // day_of_year(year, month, day); // cout << days+day; cout << endl; //3: Day of the Century: year = 0; month = 0; days = 0; day = 0; count = 1; cout << "Please enter the year, month, and day, and this program will tell you what day of the century that date is in. This program only stays in this current century so please pick a year between 2000 and 2099." << endl; cout << "Year: "; cin >> year; cout << endl << "Month: "; cin >> month; cout << endl << "Day: "; cin >> day; cout << "You are in day " << day_of_century(year, month, day) << " of the century." << endl; return(0); } A: I think you might want to reorganize your day_of_century function. For example, if you have year != 2000 or year<=0 then you have a problem. To solve the problem you need a return of type int outside all of the if statements inside your function (considered to be the default return, similar to a switch case)
{ "pile_set_name": "StackExchange" }
Q: Fixing the IE 12030 repeatability bug for Ajax calls I just loop my Ajax call until the 12030 error goes away. The error is reported as a bug here Does anyone know if there is a better fix...as this takes up time to loop. I read this was a known issue with IE that it intermittently produces 12030 errors as that Ajax status. var Ajax = { createAjaxObject: function() { var request; try { request = new XMLHttpRequest(); } catch(error) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch(error) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch(error) { request = false; } } } return request; }, useAjaxObject: function( path, param, ajax_func, html_div ) { var object = new Ajax.createAjaxObject(); object.open( "POST", path, true ); object.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" ); object.setRequestHeader( "Content-length", param.length ); object.setRequestHeader( "Connection", "close" ); object.onreadystatechange = function() { if( this.readyState === 4 ) { if( this.status === 200 ) { ajax_func( this.responseText, html_div ); } else { Ajax.repeatUseAjaxObject( path, param, ajax_func, html_div ); return false; } } }; object.send( param ); return true; }, repeatUseAjaxObject: function( path, param, ajax_func, html_div ) { var state = false, count = 1; while(state === false && count <= 5) { state = Ajax.useAjaxObject( path, param, ajax_func, html_div ); if( count !== 1 ) { alert( 'Ajax Object Use Failed '); } count++; } return state; } A: I have this same problem, and I found a solution that works for me as long as the AJAX request is asynchronous. The solution is to wrap the AJAX call in a setTimeout call with a delay of 0. This seems to work 100% of the time for me. I also verified with one of my co-workers that the 12030 error still occurs in Internet Explorer 9, as well. <rant>So Billy G and company see fit to provide us with the new "Metro" interface, but they can't be bothered to fix their browser that all web programmers must support</rant>
{ "pile_set_name": "StackExchange" }
Q: Cobrança de Tráfego em Sistema SaaS Gostaria de saber se o tráfego consumido pelos Robôs de Busca, é contabilizado junto com os de usuários em um sistema SaaS. Ou a cobrança é feita somente pela navegação genuína via browser? Algumas plataformas SaaS cobram por pageviews, visitas ou tráfego, um exemplo são as plataformas de multi-lojas, limita o lojista em tráfego "Banda contabilizada nas visualizações de fotos, output do htmls, css, etc", pageviews, visitas únicas ou produtos. Minha dúvida consiste em saber, se a banda consumida por cada loja separadamente, envolve os robôs de busca ( bot, crawler, spider ), pois estes também consome banda do servidor. Desde já agradeço. ;) A: Bom vamos lá, é um pouco complexo de responder isso, tudo vai depender realmente o que o seu SaaS "olha", contabilizar tráfego é bem diferente de se contabilizar visualizações. Imagine que o seu SaaS olhe somente tráfego, esse tipo de controle é feito monitorando a porta do Switch Layer 3 na qual o serviço roda, se for algo virtualizado cada loja pode estar separada por Vlans, tudo que trafega na porta/vlan é somado (upload/download), no fim do mês o cara tem o seu tráfego de upload e download independente, eu duvido que eles tenham um sniffer por trás tirando da soma quais ips são robôs conhecidos, isso seria um trabalho brutal e inviável (e se o IP ou classe de um dos robôs mudar?), portanto eu duvido que alguém desconte do tráfego robôs colhendo informações. Pois bem imagine agora que o SaaS olhe a quantidade de visitas, a única maneira que eu conheço de se contabilizar isso é analisando os logs de acesso do servidor http, dependendo do verbose do log tem muita informação de quem se conectou (IP, Agent, Versao do SO, etc), mais uma vez o seu SaaS teria que saber quais destes visitantes são robôs, descontar agentes que não sejam considerados de usuários. É possível? sim é possível excluir os conhecidos! o google por exemplo disponibiliza informações de como os acessos de um bot deles apareceriam nos seus logs veja aqui. A questão é saber se estas empresas se preocupam em reunir informações e padrões de bots. na minha opinião isso não é feito. Imagine que o senhor José desenvolva na casa dele um robô que se conecte a sua loja virtual e compare o preço de um barbeador elétrico com outras lojas? e ai você acha o que o seu SaaS teria artifícios suficientes para identificar isso? tanto por tráfego quanto por acesso essa conexão passaria tranquilamente como um usuário, ainda mas se o robô do Senhor José enviar informações de agentes e SO exatamente como se fosse de um usuário verdadeiro (se passaria pelo que você chamou de navegação genuína por browser), e pior imagine que esse robô faça ao longo do dia 30 acessos, como saber se realmente não era um usuário clicando F5 a espera de uma promoção relâmpago em sua loja. O caminho correto é você questionar diretamente onde roda seus serviços, eles podem dizer que não contabilizam mas mesmo assim eu duvido rsrs.
{ "pile_set_name": "StackExchange" }
Q: Mountains and solids on other planets Are there planets that lack mountains or have constrained availablilty of solids. For example a planet that has clay but not more solid stones like normal stones. The direct reason why I wonder is because I started to wonder if there existed planets where one would have to build less solid houses then at the earth due to the solids available if a person would build a house on that planet hypothetically spoken. It would be really nice with a detailed answer of what solids another planet would lack and how it constraints the housings that could be built on that planet in terms of solidness. A: A planet has been theorized that forms in a primordial disk of high carbon content. See https://en.wikipedia.org/wiki/Carbon_planet. This planet's crust would have a high hydrocarbon content and thus not be very "solid". However, such a planet might theoretically have volcanoes that erupt diamonds, so an alien could build there home out of diamond! Another hypothetical planet is a waterworld or ocean planet. If there is indigenous life then the only "above water surface" would be composed of life (ie: mats of algae type material floating on the sea). As far as mountains go, this is not a question of solid or not solid. A large superearth would likely not have much in the way of mountains because of the high gravity at the surface. It might be noted that with out plate tectonics, we wouldn't have mountains and the Earth could arguably be covered in a global ocean.
{ "pile_set_name": "StackExchange" }
Q: Altering HTML through delimited PHP I have a simple HTML page as a wrapper, then a PHP function to read information from a file and separate it into div tags (think separating comments or forum posts). It reads from a .txt flat file that is delimited between each section. This delimiter is supposed to increment a variable, then create a new div tag based on the value i (). It works for number 1 (the initialiser) and then it increments once, but it fails to increment more than once. So my question is essentially what am I doing wrong? Am I modifying my variables incorrectly, or am I outputting HTML wrong? You can assume the file is being opened and closed properly. while (!feof($file)){ $currentPost = 1; # this is the counter (i) $charA = fgetc($file); # check for delimiterA $charB = fgetc($file); # check for delimiterB $line = fgets($file); # read THE REST OF THE LINE if ($charA == "$" && $charB == "!") { # this delimiter separates posts. $currentPost = $currentPost + 1; echo "</div> <div class=\"col$currentPost\">"; # close last div, make new div } else if ($charA == "%" && $charB == "&") { # content is finished, close div echo "</div>"; } else { echo "$charA$charB$line<br>"; } } A: Initialize $currentPost = 1; before the loop, not inside it. The way your doing it now resets the $currentPost to 1 every time the loop runs.
{ "pile_set_name": "StackExchange" }
Q: USB Type C 3.1 PD to get DC20V output I have a USB Type C notebook charger. I know it can supply 20V with 2.25A for my notebook. If I have a type-c breakout board, like this: https://www.ebay.com/itm/USB-3-1-Type-C-Female-to-Female-pass-through-adapter-breakout-USB3-1-CF-CF-V1A-/254173573546 And I know the pinout: What can I do to get DC20V between A1 and A4 (and of course between B12 and B9?) A: All answers are severely misleading. You can't get any other voltage than the default +5V without Power Delivery negotiations. Now, the Power Delivery specifications (614 pages) are as long as the entire USB 2.0 specifications (622 pages). The negotiating protocol involves hundreds of messages over 300 kbps link that is as complicated as USB, and the number of protocol states/stages are in order of 200. Starting from a background of bare Type-C pinout and even buying specialized IC is a far-far complex task. The mentioned specialized ICs are providing only the physical level interaction across CC links, and at most provide packet service. The entire negotiation protocol and "policies" are implemented over a general purpose MCU, and implementation of all these crazy polices takes thousands lines of code ("just as your laptop does"), so an advice to DIY the protocol interface at OP's level is misleading. However: What shall I do to get DC20V between A1 and A4 you shall buy a ready-to go board called "USB PD trigger", like this one: The board has at least 5 ICs including ARM 32-bit MCU chip, so it will be a challenge to make another one for this price tag.
{ "pile_set_name": "StackExchange" }
Q: Is it OK to mention dreams and future plans for a specific company in my SOP when applying for master's degree? I am about to apply for Master's degree at a University in US that specializes in game development. I have been playing and I am a huge fan of Blizzard games for almost 15 years and the reason I pursue a higher education is to broaden my knowledge and sharpen my skills so that I can land on my dream job. I wanted to mention this (in a politically correct manner) because I think it shows determination. Is this a good idea or would it hurt my statement? A: Unlike the other existing answer, I would advise you to tread carefully. Maybe this is different for a Master's in game development, but generally speaking, "I like to play computer games" qualifies as the #1 worst reason we get to hear about why students are interested in computer science. One of the reasons why this is such a bad motivation is because it shows a certain level of misunderstanding about what computer science is, and I would argue that this is even true for a master in game development. Even great computer game developers are, to the best of my knowledge, not only interested in gaming, but also in AI, computer graphics and animation, HCI, physical simulation, distributed systems, optimization, etc. Not all of them at the same time, but being "just" interested in building cool games seems rather weak, to be honest. I think it can be pretty much implied that you are interested in games if you apply for game development. Show and discuss your interests in other related areas that sets you apart from all the other applying gamers. Also, having working at Blizzard as your dream job does not show determination. Many people have this as their dream job, and still do not follow through. Determination is doing something to make your dream a reality despite problematic circumstances, not having a dream in the first place. You should explain what you did, not what you hope to achieve.
{ "pile_set_name": "StackExchange" }
Q: Input field is being treated as a password field when nothing indicates that it is one I am working on the front page of a website, in this context on the signup/login form combo. Those forms use the native forms from mobx-react, composed of a form.js observer, giving each element it's DOM structure, and a corresponding template.js file defining the role of each field. That means I can make nondescript fields in form.js and define them in template.js. Sadly, one of my fields is being converted into a password input when nothing should make it one. Here's a snip from form.js export default observer(({ form }) => { const isSuccess = state => (!state ? 'is-success' : 'is-danger'); return ( <article className='tiles is-ancestor is-inline-flex drc-column'> <div className='tile is-vertical is-size-4 has-text-centered has-text-grey'>Inscription</div> <form className='tile is-parent is-vertical'> // good field <div className='tile is-child'> <label className='has-text-centered is-block' htmlFor={form.$('surname').id}> {form.$('surname').label} <input className={`input is-medium has-background-white-ter ${form.$('surname').isEmpty ? '' : isSuccess(form.$('surname').error)}`} id='signup-surname' {...form.$('surname').bind()} /> </label> <p className='has-text-danger'>{form.$('surname').error}</p> </div> // multiple good fields <button className='tile is-child button is-large has-background-success is-fullwidth has-text-white' type='submit' onClick={form.onSubmit}><span className='is-size-6 is-uppercase'>Je m&apos;inscris</span></button> <p className={form.error ? 'has-text-danger' : 'has-text-success'}>{form.error}</p> </form> </article> ); }); and here's the other side of the coin, on template.js setup() { return { fields: [{ name: 'name', label: 'Prénom', rules: 'required|string' }, { name: 'surname', label: 'Nom', rules: 'required|string' }, { name: 'company', label: 'Entreprise', rules: 'required|string' }, { name: 'phone', label: 'Numéro de téléphone', rules: 'required|numeric' }, { name: 'email', label: 'E-mail', rules: 'required|email|string' }, { name: 'password', label: 'Mot de passe', rules: 'required|string', type: 'password' }] }; } Here are a screenshot of the form itself, and of the actual interpreted HTML. I want that surname field to be a regular text input, not a password input. I can't redo the tech stack at this point to exclude using the forms from mobx-react, and it used to work just fine. Nothing is overwriting those input fields, those two snips are the only ones in control, I'm not sure where to look next. Good day! A: Issue was resolved. When you were redirected (manually or otherwise) from the login form to the signup form, the fields were not reset. Since the second field on the login form was a password, it transitioned into the second field of the signup form, keeping the password type. Resetting said fields with the componentWillUnmount mobx hook effectively fixes this issue: componentWillUnmount() { const { profileStore } = this.props; profileStore.resetFields(); } And into profileStore itself: @observable fields = undefined; @action resetFields() { log.warn('resetFields'); this.fields = undefined; } Now forms are effectively recreated from the ground up every time, no more problem.
{ "pile_set_name": "StackExchange" }
Q: Why does Ruby's hash method vary across runs? # pry / irb example #1 "abc".hash => -1883761119486508070 "abc".hash => -1883761119486508070 # pry / irb example #2 "abc".hash => -4309321811150053495 "abc".hash => -4309321811150053495 The hash value is constant for a particular invocation, but varies across invocations. Why? Is this by design? Is this considered a "good thing"? I'm running ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin12.0.0]. A: According to page 23 of http://patshaughnessy.net/Ruby-Under-a-Microscope-Rough-Draft-May.pdf Here’s how Ruby’s hash function actually works ... [snip] ... For string and arrays it works differently. In this case, Ruby actually iterates through all of the characters in the string or elements in the array and calculates a cumulative hash value; this guarantees that the hash value will always be the same for any instance of a string or array, and will always change if any of the values in that string or array change. And: Also, Ruby 1.9 and Ruby 2.0 initialize MurmurHash using a random seed value which is reinitialized each time you restart Ruby. This means that if you stop and restart Ruby you’ll get different hash values for the same input data. It also means if you try this yourself you’ll get different values than I did above. However, the hash values will always be the same within the same Ruby process.
{ "pile_set_name": "StackExchange" }
Q: Testing vs Don't Repeat Yourself (DRY) Why is repeating yourself by writing tests so highly encouraged? It seems that tests basically express the same thing as the code, and hence is a duplicate (in concept, not implementation) of the code. Wouldn't the ultimate target of DRY include elimination of all test code? A: I believe this is a misconception any way I can think of. The test-code that tests production-code is not at all similar. I'll demonstrate in python: def multiply(a, b): """Multiply ``a`` by ``b``""" return a*b Then a simple test would be: def test_multiply(): assert multiply(4, 5) == 20 Both functions have a similar definition but both do very different things. No duplicate code here. ;-) It also occurs that people write duplicate tests essentially having one assertion per test function. This is madness and I have seen people doing this. This is bad practice. def test_multiply_1_and_3(): """Assert that a multiplication of 1 and 3 is 3.""" assert multiply(1, 3) == 3 def test_multiply_1_and_7(): """Assert that a multiplication of 1 and 7 is 7.""" assert multiply(1, 7) == 7 def test_multiply_3_and_4(): """Assert that a multiplication of 3 and 4 is 12.""" assert multiply(3, 4) == 12 Imagine doing this for 1000+ effective lines of code. Instead you test on a per 'feature' basis: def test_multiply_positive(): """Assert that positive numbers can be multiplied.""" assert multiply(1, 3) == 3 assert multiply(1, 7) == 7 assert multiply(3, 4) == 12 def test_multiply_negative(): """Assert that negative numbers can be multiplied.""" assert multiply(1, -3) == -3 assert multiply(-1, -7) == 7 assert multiply(-3, 4) == -12 Now when features are added/removed I only have to consider adding/removing one test function. You may have noticed I have not applied for loops. This is because repeating some things is good. When I would have applied loops the code would be a lot shorter. But when an assertion fails it could obfuscate the output displaying an ambiguous message. If this occurs then your tests will be less useful and you will need a debugger to inspect where things go wrong. A: It seems that tests basically express the same thing as the code, and hence is a duplicate No, this is not true. Tests have a different purpose than your implementation: Tests make sure that your implementation works. They serve as a documentation: By looking at the tests, you see the contracts which your code must fulfil, i.e. which input returns what output, what are the special cases etc. Also, your tests guarantee that as you add new features, your existing functionality does not break. A: No. DRY is about writing code just once to do a particular task, test are validation that the task is being done correctly. It's somewhat akin to a voting algorithm, where obviously using the same code would be useless.
{ "pile_set_name": "StackExchange" }
Q: c - dereferencing issue I have simplified an issue that I've been having trying to isolate the problem, but it is not helping. I have a 2 dimensional char array to represent memory. I want to pass a reference to that simulation of memory to a function. In the function to test the contents of the memory I just want to iterate through the memory and print out the contents on each row. The program prints out the first row and then I get seg fault. My program is as follows: #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> void test_memory(char*** memory_ref) { int i; for(i = 0; i < 3; i++) { printf("%s\n", *memory_ref[i]); } } int main() { char** memory; int i; memory = calloc(sizeof(char*), 20); for(i = 0; i < 20; i++) { memory[i] = calloc(sizeof(char), 33); } memory[0] = "Mem 0"; memory[1] = "Mem 1"; memory[2] = "Mem 2"; printf("memory[1] = %s\n", memory[1]); test_memory(&memory); return 0; } This gives me the output: memory[1] = Mem 1 Mem 0 Segmentation fault If I change the program and create a local version of the memory in the function by dereferencing the memory_ref, then I get the right output: So: #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> void test_memory(char*** memory_ref) { char** memory = *memory_ref; int i; for(i = 0; i < 3; i++) { printf("%s\n", memory[i]); } } int main() { char** memory; int i; memory = calloc(sizeof(char*), 20); for(i = 0; i < 20; i++) { memory[i] = calloc(sizeof(char), 33); } memory[0] = "Mem 0"; memory[1] = "Mem 1"; memory[2] = "Mem 2"; printf("memory[1] = %s\n", memory[1]); test_memory(&memory); return 0; } gives me the following output: memory[1] = Mem 1 Mem 0 Mem 1 Mem 2 which is what I want, but making a local version of the memory is useless because I need to be able to change the values of the original memory from the function which I can only do by dereferencing the pointer to the original 2d char array. I don't understand why I should get a seg fault on the second time round, and I'd be grateful for any advice. Many thanks Joe A: Try: printf("%s\n", (*memory_ref)[i]); The current version is equivalent to *(*(memory_ref + i)); This is because the [] operator has higher precedence than the dereference *. Which means that when i is larger than 0 you try to read memory after the char*** temporary memory_ref The second version is equal to (*memory_ref)[i] which means that you will be indexing the correct memory. EDIT: The reason it works on the first iteration is because: *(*(memory_ref + 0)) == *((*memory_ref) + 0)
{ "pile_set_name": "StackExchange" }
Q: Speech recognition: Hindi or Gujarti? I want to make the speech recognizer get the result hindi or gujarti. I try but I get the English. How to Install the Hindi language in voice recognizer setting in android phone? A: Quote from the Google Tutorial: Google's servers support many languages for voice input, with more arriving regularly. You can use the ACTION_GET_LANGUAGE_DETAILS broadcast intent to query for the list of supported languages. Also, I found this older post asking for basically the same (not sure if this is up-to-date anymore).
{ "pile_set_name": "StackExchange" }
Q: Textbox inputscope winrt - numbers only similar to 'enter your password' on windows phone 8 I would like to use the numbers only keypad on winrt like the one displayed on windows phone 'enter your password' screen? Even if this is one line of keys horizontally aligned. can it be done? It doesn't look like a standard offering in the enum... Is it possible to create custom input scopes for c#/xaml/winrt? thanks A: Unfortunately, the only InputScope that you can use is Number, you can't create your own. The only solution I can advise you here is handling TextChanged event, and using UInt32.TryParse() (as you don't need negative numbers, or you can just use NumberStyles.None).
{ "pile_set_name": "StackExchange" }
Q: Remove single quotes/quotation marks in Prolog I have an extern API sending info to my Prolog application and I found a problem creating my facts. When the information received is extensive, Prolog automatically adds ' (single quotes) to that info. Example: with the data received, the fact I create is: object(ObjectID,ObjectName,'[(1,09:00,12:00),(2,10:00,12:00)]',anotherID) The fact I would like to create is object(ObjectID,ObjectName,[(1,09:00,12:00),(2,10:00,12:00)] ,anotherID) without the ' before the list. Does anyone know how to solve this problem? With a predicate that receives '[(1,09:00,12:00),(2,10:00,12:00)]' and returns [(1,09:00,12:00),(2,10:00,12:00)]? A: What you see is an atom, and you want to convert it to a term I think. If you use swi-prolog, you can use the builtin term_to_atom/2: True if Atom describes a term that unifies with Term. When Atom is instantiated, Atom is parsed and the result unified with Term. Example: ?- term_to_atom(X,'[(1,09:00,12:00),(2,10:00,12:00)]'). X = [ (1, 9:0, 12:0), (2, 10:0, 12:0)]. So at the right hand side, you enter the atom, at the left side the "equivalent" term. Mind however that for instance 00 is interpreted as a number and thus is equal to 0, this can be unintended behavior. You can thus translate the predicate as: translate(object(A,B,C,D),object(A,B,CT,D)) :- term_to_atom(CT,C). Since you do not fully specify how you get this data, it is unknown to me how you will convert it. But the above way will probably be of some help.
{ "pile_set_name": "StackExchange" }
Q: Right triangle circumscribed by a horocycle Is it possible that a right triangle is circumscribed by a horocycle? Or, is this statement a theorem in the hyperbolic gemetry? For any horocycle $\gamma$, there are no three distinct ordinary points A,B,C on $\gamma$ forming a right triangle $\Delta$ABC I'm pretty sure that this is a true statement but I do not know how to prove it.(or my guess might be wrong) A: There are lots of right-angled triangles with vertices on a horocycle. A right-angled triangle has one right angle, the others are smaller. There are no hyperbolic triangles with three right angles. Claim: Let $\gamma$ be a horocycle and $A,B$ two distinct points on it. Then there exists a point $C$ on the horocycle such that $\Delta ABC$ is a hyperbolic triangle with a right angle at $A$. Proof: Let us work in the Poincaré disk model. A horocycle is a circle that touches the boundary of the disk. Let $A,B$ be two points on a horocycle $\gamma$. We note that the geodesic $\overline{AB}$ does not intersect $\gamma$ at a right angle at $A$ and is not parallel to $\gamma$ at $A$. Since the geodesic $\overline{AB}$ is not parallel to the horocycle, we can look at the interior of the horocycle. Since $\overline{AB}$ does not intersect $\gamma$ in a right angle, there is one side, where you can add a new geodesic $\overline{AC}$ that also points inside the horocycle. At some point this geodesic will leave the horocycle (it will not go to the boundary point where $\gamma$ touches the disk, since it does not intersect $\gamma$ at a right angle at $A$.) Let us call that point $C$. There is a geodesic connecting $C$ and $B$, completing the triangle. By construction the triangle $\Delta ABC$ has a right angle at $A$.
{ "pile_set_name": "StackExchange" }
Q: NGINX access.log not updating I've created a simple HTML website with 4 html pages (4 links). The access.log doesn't update for accessing a html page more than once. E.g. user clicks on link #1 -> link #2 -> link #1 The access.log will only show: GET /page#1.html GET /page#2.html I want it show all requests, i.e.: GET /page#1.html GET /page#2.html GET /page#1.html I've looked into tailoring my .config file but to no success. Any help will be appreciated. Thank you. Here is my nginx.config file: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 2048; multi_accept on; } http { ## # Basic Settings ## server_name_in_redirect off; server_tokens off; port_in_redirect off; sendfile on; tcp_nopush on; tcp_nodelay off; send_timeout 30; keepalive_timeout 60; keepalive_requests 200; reset_timedout_connection on; types_hash_max_size 2048; server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; #default_type application/octet-stream; default_type text/html; charset UTF-8; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log warn; ## # Gzip Settings ## gzip on; gzip_min_length 256; gzip_disable "msie6"; # gzip_vary on; gzip_proxied any; gzip_comp_level 5; # gzip_buffers 16 8k; # gzip_http_version 1.1; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } A: As @emix already pointed out, is the browser simply not making a request to your server. Instead the page is most likely going to be served from your browsers cache. The (too) short answer to why browsers do this is, is to reduce unnecessary network requests and to save resources. To get a better understanding of what a (browser) cache is, I'd recommend you to read the following resources: Stackoverflow Q/A: What Is A Browser Cache? What does it store from a webpage data? What is caching? External sites: HTTP Caching How Browser Caching Works
{ "pile_set_name": "StackExchange" }
Q: sympy : expression simplification I begin with sympy python lib. If, I have this expression from sympy.abc import a,b,c,p,q e = p * ( a + b ) + q * ( a + c ) how I can use a,b,c as factor ? like a(p+q) + b*p + c*q A: from sympy.abc import a,b,c,p,q from sympy import collect, expand e = p * ( a + b ) + q * ( a + c ) print e print expand(e) print collect(expand(e),a)
{ "pile_set_name": "StackExchange" }
Q: Window is shown but cannot interact with the simulator I am reading Programming iOS4 by O'Rielly and I am using a slightly newer version of XCode than the one that the book is using. However, this slight change has led to a little bit of confusion because I cannot create window-based app using the XCode 4.2. Anyhow, I started an empty project which gave me the barebone structure for an iPhone app without the MainWindow.xib. I was already given the project's delegate .h and .m. I proceeded to create my own MainWindow.xib. I figured out that I had to set 'Main nib file base name' to 'MainWindow' for my nib to show up at all and so I did that. Inside my MainWindow.xib, I added a button under the window object just to make sure that I have what I want when I run the project. This is the state of my nib right now Without making any changes to the AppDelegate.h and AppDelegate.m, I built and ran my project. I was able to see the button! HOWEVER, I could not click on the button and when I pressed the home button and resumed my empty app, I could not see the button anymore! Here are some files that I did not make any changes to: main.m #import <UIKit/UIKit.h> #import "EmptyWindowAppDelegate.h" int main(int argc, char *argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([EmptyWindowAppDelegate class])); } } EmptyWindowAppDelegate.m #import "EmptyWindowAppDelegate.h" @implementation EmptyWindowAppDelegate @synthesize window = _window; @synthesize managedObjectContext = __managedObjectContext; @synthesize managedObjectModel = __managedObjectModel; @synthesize persistentStoreCoordinator = __persistentStoreCoordinator; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; } //...Omitted A: You can specify the name of the main nib file in your application plist (by default it is MainWindow.xib). To investigate your problem further you could just create a default view based app and see what the differences are. It seems to me that you have made no connection in interface builder between your App Delegate's window property and your IB window object. Which means that window, in didFinishLaunchingWithOptions would probably be nil and that the messages you send it will therefore have no effect.
{ "pile_set_name": "StackExchange" }