text
stringlengths
64
89.7k
meta
dict
Q: How to upload a file and JSON data in Postman? I am using Spring MVC and this is my method: /** * Upload single file using Spring Controller. */ @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) public @ResponseBody ResponseEntity<GenericResponseVO<? extends IServiceVO>> uploadFileHandler( @RequestParam("name") String name, @RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) { if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); // Creating the directory to store file String rootPath = System.getProperty("catalina.home"); File dir = new File(rootPath + File.separator + "tmpFiles"); if (!dir.exists()) { dir.mkdirs(); } // Create the file on server File serverFile = new File(dir.getAbsolutePath() + File.separator + name); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile)); stream.write(bytes); stream.close(); System.out.println("Server File Location=" + serverFile.getAbsolutePath()); return null; } catch (Exception e) { return null; } } } I need to pass the session id in postman and also the file. How can I do that? A: In postman, set method type to POST. Then select Body -> form-data -> Enter your parameter name (file according to your code) and on right side next to value column, there will be dropdown "text, file", select File. choose your image file and post it. For rest of "text" based parameters, you can post it like normally you do with postman. Just enter parameter name and select "text" from that right side dropdown menu and enter any value for it, hit send button. Your controller method should get called. A: The Missing Visual Guide You must first find the nearly-invisible pale-grey-on-white dropdown for File which is the magic key that unlocks the Choose Files button. After you choose POST, then choose Body->form-data, then find the File dropdown, and then choose 'File', only then will the 'Choose Files' button magically appear: A: Maybe you could do it this way:
{ "pile_set_name": "StackExchange" }
Q: What database table structure should I use for versions, codebases, deployables? I'm having doubts about my table structure, and I wonder if there is a better approach. I've got a little database for version control repositories (e.g. SVN), the packages (e.g. Linux RPMs) built therefrom, and the versions (e.g. 1.2.3-4) thereof. A given repository might produce no packages, or several, but if there are more than one for a given repository then a particular version for that repository will indicate a single "tag" of the codebase. A particular version "string" might be used to tag a version of the source code in more than one repository, but there may be no relationship between "1.0" for two different repos. So if packages P and Q both come from repo R, then P 1.0 and Q 1.0 are both built from the 1.0 tag of repo R. But if package X comes from repo Y, then X 1.0 has no relationship to P 1.0. In my (simplified) model, I have the following tables (the x_id columns are auto-incrementing surrogate keys; you can pretend I'm using a different primary key if you wish, it's not really important): repository - repository_id - repository_name (unique) ... version - version_id - version_string (unique for a particular repository) - repository_id ... package - package_id - package_name (unique) - repository_id ... This makes it easy for me to see, for example, what are valid versions of a given package: I can join with the version table using the repository_id. However, suppose I would like to add some information to this database, e.g., to indicate which package versions have been approved for release. I certainly need a new table: package_version - version_id - package_id - package_version_released ... Again, the nature of the keys that I use are not really important to my problem, and you can imagine that the data column is "promotion_level" or something if that helps. My doubts arise when I realize that there's really a very close relationship between the version_id and the package_id in my new table ... they must share the same repository_id. Only a small subset of package/version combinations are valid. So I should have some kind of constraint on those columns, enforcing that ... ... I don't know, it just feels off, somehow. Like I'm including somehow more information than I really need? I don't know how to explain my hesitance here. I can't figure out which (if any) normal form I'm violating, but I also can't find an example of a schema with this sort of structure ... not being a DBA by profession I'm not sure where to look. So I'm asking: am I just being overly sensitive? A: Yes, I'm being overly sensitive. Especially when I realize that a package could conceivably move to a different repository over time (changing the contents of the package table), so the package_version table doesn't really have extra information. In fact it's essential.
{ "pile_set_name": "StackExchange" }
Q: Can the open unit disk be expressed as the union of a countable collection of closed squares? My question is simple, but I believe it is challenging think of an example. Forget the fact that I couldn't think about an example, I couldn't understand the solution to this. Need some explanation on it. Answer : The closed this $D_n$ of radius $1-\frac{1}{n}$ can be covered by a finite number of squares contained in $D$ and union of all $D_n$ would give us $D$ Q1) How come union of all $D_n$ give us $D$ Q2) Aren't we trying to express the unit circle, instead of covering it? A: The open unit disk is $B_E(0,1)$, a subset of $\mathbb R^2$, where $E$ is the Euclidean metric. We are looking to prove or disprove, that $B_E(0,1)$ can be described with countable unions of $\bar B_M(x_i,r)$, where $M$ is the Manhattan metric, and that the $\bar B$ denotes closed ball. Immediately notice that if the unit disk was closed, there would exist an uncountable union of closed squares: let $T_\theta$ be a transformation that rotates the cordinate system (for example a rotation matrix), and then $M_\theta = M(T_\theta(x),T_\theta(y))$ is a well defined metric. It follows that $$\bar B_E(0,1) = \bigcup_{\theta \in \Theta} \bar B_{M_\theta}(0,1)$$ The following is also true for open unit disk and open squares. Now for the proof itself: say there does exist $B_E(0,1) = \bigcup_{n \in \mathbb N} \bar S_n$, where $\bar S_n$ is an arbitrary, closed square. Now, $B$ is open and is a union of sets. Therefore the members in the union need to be open - with respect to $E$ - as well. $\bar S_n$ is homeomorphic to $[a,b] \times [c,d]$. Set $U$ is open if for any $x \in U$, there exists $\epsilon >0$ such that, any point $y \in \mathbb R^2$ satisfying $E(x,y)<\epsilon$ means that $y \in U$. Equivalently for every point in $U$, $U$ contains that point's neighbourhood. Take any corner point of $\bar S_n$, in this case $a$: $E(a,y) < 2$ implies we can take $y = a-1$, but $y$ is not in $\bar S_n$, so $\bar S_n$ is not open, and there does not exist a countable collection of closed squares that express the open unit disk. Even more strongly, there does not exists an uncountable collection, as our proof did not rely on the index family $n \in \mathbb N$.
{ "pile_set_name": "StackExchange" }
Q: Alert Box that displays written text in html5 I have a dropdown list. When someone clicks the option "Other" in the dropdown list, a blank line appears to allow someone to write his or her own request. I want to create an alert box which displays what someone wrote in the blank line in big, bold letter. How do I do this? Here's my code: <form action=""> <select name="requests" onchange ="checkIfOther();" id="dropDown1"> <option value="blank"></option> <option value="good morning sir">Good Morning Sir</option> <option value="temperature">The current temperature is _____ centigrade.</option> <option value="other">Other</option> </select> </form> </p> <button onclick="myFunction()" value>Submit</button> <div id="other" style="display:none"> <br><br><label>Optional Request: </label><input type="text" id="otherText"/> </div> </body> </html> <script> function checkIfOther(){ a = document.getElementById("dropDown1"); if(a.value == "other") document.getElementById("other").setAttribute("style","display:inline"); else document.getElementById("other").setAttribute("style","display:none"); } </script> <script> function myFunction(){ var x=document.getElementById("dropDown1"); alert("You have chosen: " + x.options[x.selectedIndex].text); if(x.value == "other"){ b=document.getElementById("other"); alert("You have chosen: " + b.text); //what do I do? } } </script> A: Try using Jquery, Here is code: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> function myFunction(){ alert('You have chosen: '+$("#otherText").val()); } function checkIfOther() { $("#otherText").val(''); ($("#dropDown1").val() == 'other') ? $("#other").show() : $("#other").hide(); } </script> let me know is this helpful?.
{ "pile_set_name": "StackExchange" }
Q: ajax file post: Unable to send base64 data via FileReader automatically If I do this manually, I get picture updated Reader.readAsDataURL($('#foto')[0].files[0]) $.post('update.php', { foto: Reader.result }, function(resp) { console.log(resp) }); But the code won't work! $('#fotoOk').click(function() { var ok = true; var s = $('#foto').val().split('.'); var ext = s[s.length-1]; if (!ext.match(/(jpg|jpeg|png|gif)/i)) { ok = false; console.log('bad ext'); $('#errFoto').html('bad avatar!'); } else if ($('#foto')[0].files.item(0).size > (1024 * 1024 * 5)) { console.log('too big'); ok = false; $('#errFoto').html('Avatar file is too big!'); } if (ok) { if (!Reader) Reader = new FileReader(); Reader.readAsDataURL($('#foto')[0].files[0]); console.log(Reader.result); $.post("update.php", { foto: Reader.result }); $('#errFoto').html(''); $('#avt').attr('src', Reader.result); $('#edfoto').hide(); } else { console.log("foto upload failed!"); } }); It passes all the validations, (file extension/size checkup) and yet wont, post base64 data In console i see, empty Reader.result [:rage:]! A: you have to use the reader's onload event. result doesnt get filled immediately if (!Reader) Reader = new FileReader(); Reader.onload = function(e) { console.log(e.result); $.post("update.php", { foto: e.result }); $('#errFoto').html(''); $('#avt').attr('src', e.result); $('#edfoto').hide(); }; Reader.readAsDataURL($('#foto')[0].files[0]);
{ "pile_set_name": "StackExchange" }
Q: API responsibilities vs Client responsibilities (Characteristics of returned data) I have a hard time trying to find a 'rule of thumb' to follow when dictating certain responsibilities to either the API, or the client-side code base. For instance, if I know a dataset should be returned in alphabetic order, should I as a front-end developer expect the data to be properly ordered alphabetically by the API designers/developers, or should I expect to be the one to order the data. Extending this thought, what are ways I can determine if data-related operations are the front-end developer's responsibility or the api designer/developer's responsibility? I want to know when to draw the line and expect things to be done before it reaches my jurisdiction. A: All interfaces should have clear "contracts" that specify what each side can expect from the other side. If it's stated in the contract that data is sorted, you should rely on that. If it turns out that the service delivers unsorted data, you can blame it :-) If you're unsure about some part, that's normally a sign that the contract isn't written properly. Depending on how much influence you have on the API's author, you should ask them to clarify, or if that is not possible, assume the worst and program defensively. In this case it would mean that even if your tests indicate that the service returns sorted data, assume that it's just lucky chance and sort anyway.
{ "pile_set_name": "StackExchange" }
Q: Showing Dialog in SurfaceView My game is drawn onto a SurfaceView. I am using a Dialog as a level completion screen, but cannot get it to show (Dialog.show()). I keep getting the following error: 01-30 16:45:34.425: E/AndroidRuntime(3415): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() I have a Game class which extends Activity and holds the SurfaceView. I think runOnUiThread() may be the solution, but after tireless searching have no idea how to implement it inside my SurfaceView. Any help is appreciated and I will post my code if requested (just not sure which bits are actually relevant at the moment) A: You're attempting to modify the UI thread from a worker thread which will give these errors. To prevent this try making a call to the runOnUiThread() method... Game.this.runOnUiThread(new Runnable() { public void run() { customDialogObject.show(); } });
{ "pile_set_name": "StackExchange" }
Q: Run script on boot. I want to know my Public IP address of PI using script and script should be start running automatically when my raspberry pi boot and Store output in some file, so that i can use later on. Actually, I am Controlling my PI Remotely from Cloud and for that whenever Public IP of PI change then PI should be able to inform new IP to cloud. For that i need script that start automatically after boot and run every 5-10 second and check Public IP and overwrite output file. I use sudo curl icanhazip.com for check public IP but that give me actually i need only public IP without extra information, is there any command that give me only public IP and for looping a script i use While loop. Is it a right way or is there another better way to run screen in a loop. A: It seems your question for getting your ip address has been solved, but that there's still a question re "looping" this command. Here's a suggestion for that bit: Add the command to your crontab, and let cron run it for you at any interval you specify. Here are the steps from your RPi terminal: crontab -e This will display your current (likely default in your case) crontab file. Note that each line is "commented out" with # in column 1. In pico (or whatever your default editor is), add a line to tell cron your schedule. In your case, adding the following crontab entry will run your command every minute. * * * * * sudo curl -s icanhazip.com And no, you can't do it every 5 seconds! You'll need another solution if that's an actual requirement, but I can't even imagine why you'd even need updates every minute since DHCP leases usually last far longer. And finally, if you want to run this on reboot, put this line in your crontab: @reboot curl -s icanhazip.com A: Use the documented -s or --silent option sudo curl -s icanhazip.com or sudo curl --silent icanhazip.com
{ "pile_set_name": "StackExchange" }
Q: how to use match() in node.js MySQL Using numtel:mysql for meteor which is node-mysql for meteor. How should a SQL match against query look. A: It looks to me like this should work. return liveDb.select( `SELECT * FROM articles WHERE MATCH (title,body) AGAINST ('+MySQL -YourSQL' IN BOOLEAN MODE);`, [ { table: articles} ] );
{ "pile_set_name": "StackExchange" }
Q: How can I sort Go slices whose element type is an alias of string, but not string itself? type MyObject string var objects []MyObject I want to sort these objects. The standard library has sort.Strings, but that requires an instance of []string instead of []MyObject. My current solution is to implement sort.Interface (as shown below) and use sort.Sort, but I'd like to get rid of that boilerplate code. Is there a nicer way? type MyObjects []MyObject func (objs MyObjects) Len() int { return len(objs) } func (objs MyObjects) Less(i, j int) bool { return strings.Compare(string(objs[i]), string(objs[j])) < 0 } func (objs MyObjects) Swap(i, j int) { o := objs[i] objs[i] = objs[j] objs[j] = o } A: No. Since Go doesn't allow the implicit conversion of types within slices (there is also no covariance with interfaces), you need to supply the appropriate methods for your type. type MyObjects []MyObject func (p MyObjects) Len() int { return len(p) } func (p MyObjects) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (p MyObjects) Less(i, j int) bool { return p[i] < p[j] } If you really want to do this, you could use unsafe (but please don't). I doubt those 3 extra lines of safe code are going to make that big a difference for you. http://play.golang.org/p/d6ciFjjr2c objects := []MyObject{"one", "two", "three", "four"} sort.Strings(*(*[]string)(unsafe.Pointer(&objects)))
{ "pile_set_name": "StackExchange" }
Q: How to get YUV from Android GLSurfaceView? Is there any way to get YUV buffer from Android Camera with GLSurfaceView ? (Not from onPreviewFrame) A: You get a YUV buffer from the Android Camera by using the Android Camera API. There's no reason to get OpenGL ES involved if you just want a single frame. Use ImageReader to avoid data copies. OpenGL ES works with RGB, not YUV, so anything rendered by GLES has been color-space converted. You can do the conversion back to YUV in a fragment shader if you like. In any event, the SurfaceView classes are not intended as intermediates in a processing pipeline; they are display endpoints. You can't get anything from them. See the arch doc for details.
{ "pile_set_name": "StackExchange" }
Q: Relative variable importance for Boosting I'm looking for an explanation of how relative variable importance is computed in Gradient Boosted Trees that is not overly general/simplistic like: The measures are based on the number of times a variable is selected for splitting, weighted by the squared improvement to the model as a result of each split, and averaged over all trees. [Elith et al. 2008, A working guide to boosted regression trees] And that is less abstract than: $\hat{I_{j}^2}(T)=\sum\limits_{t=1}^{J-1} \hat{i_{t}^2} 1(v_{t}=j)$ Where the summation is over the nonterminal nodes $t$ of the $J$-terminal node tree $T$, $v_{t}$ is the splitting variable associated with node $t$, and $\hat{i_{t}^2}$ is the corresponding empirical improvement in squared error as a result of the split, defined as $i^2(R_{l},R_{r})=\frac{w_{l}w_{r}}{w_{l}+w_{r}}(\bar{y_{l}}-\bar{y_{r}})^2$, where $\bar{y_{l}}, \bar{y_{r}}$ are the left and right daughter response means respectively, and $w_{l}, w_{r}$ are the corresponding sums of the weights. [Friedman 2001, Greedy function approximation: a gradient boosting machine] Finally, I did not find the Elements of Statistical Learning (Hastie et al. 2008) to be a very helpful read here, as the relevant section (10.13.1 page 367) tastes very similar to the second reference above (which might be explained by the fact that Friedman is a co-author of the book). PS: I know relative variable importance measures are given by the summary.gbm in the gbm R package. I tried to explore the source code, but I can't seem to find where the actual computation takes place. Brownie points: I'm wondering how to get these plots in R. A: I'll use the sklearn code, as it is generally much cleaner than the R code. Here's the implementation of the feature_importances property of the GradientBoostingClassifier (I removed some lines of code that get in the way of the conceptual stuff) def feature_importances_(self): total_sum = np.zeros((self.n_features, ), dtype=np.float64) for stage in self.estimators_: stage_sum = sum(tree.feature_importances_ for tree in stage) / len(stage) total_sum += stage_sum importances = total_sum / len(self.estimators_) return importances This is pretty easy to understand. self.estimators_ is an array containing the individual trees in the booster, so the for loop is iterating over the individual trees. There's one hickup with the stage_sum = sum(tree.feature_importances_ for tree in stage) / len(stage) this is taking care of the non-binary response case. Here we fit multiple trees in each stage in a one-vs-all way. Its simplest conceptually to focus on the binary case, where the sum has one summand, and this is just tree.feature_importances_. So in the binary case, we can rewrite this all as def feature_importances_(self): total_sum = np.zeros((self.n_features, ), dtype=np.float64) for tree in self.estimators_: total_sum += tree.feature_importances_ importances = total_sum / len(self.estimators_) return importances So, in words, sum up the feature importances of the individual trees, then divide by the total number of trees. It remains to see how to calculate the feature importances for a single tree. The importance calculation of a tree is implemented at the cython level, but it's still followable. Here's a cleaned up version of the code cpdef compute_feature_importances(self, normalize=True): """Computes the importance of each feature (aka variable).""" while node != end_node: if node.left_child != _TREE_LEAF: # ... and node.right_child != _TREE_LEAF: left = &nodes[node.left_child] right = &nodes[node.right_child] importance_data[node.feature] += ( node.weighted_n_node_samples * node.impurity - left.weighted_n_node_samples * left.impurity - right.weighted_n_node_samples * right.impurity) node += 1 importances /= nodes[0].weighted_n_node_samples return importances This is pretty simple. Iterate through the nodes of the tree. As long as you are not at a leaf node, calculate the weighted reduction in node purity from the split at this node, and attribute it to the feature that was split on importance_data[node.feature] += ( node.weighted_n_node_samples * node.impurity - left.weighted_n_node_samples * left.impurity - right.weighted_n_node_samples * right.impurity) Then, when done, divide it all by the total weight of the data (in most cases, the number of observations) importances /= nodes[0].weighted_n_node_samples It's worth recalling that the impurity is a common name for the metric to use when determining what split to make when growing a tree. In that light, we are simply summing up how much splitting on each feature allowed us to reduce the impurity across all the splits in the tree. In the context of gradient boosting, these trees are always regression trees (minimize squared error greedily) fit to the gradient of the loss function.
{ "pile_set_name": "StackExchange" }
Q: Set value in a loop to a value which is set in the first loop execution What I want to do is to set a variable to a value which is set by the first loop execution. As background information: I'm using CollectionFS to upload multiple files in my meteor app. Now I want to set to all files (beside the first one) the custom field value parent to the id of the first inserted file. I get the id by data._id. My attempt: As I'm using a loop for each uploaded file, I thought data is undefined for the first file, so I check if it has a value. In this case also parent would be undefined. For the second file, data is already set, so parent should get data._id as its value. But this doesn't work properly, as parent is always undefined: FS.Utility.eachFile(event, function (file) { var newFile = new FS.File(file), parent = (data) ? data._id : undefined; newFile.metadata = { parent: parent }; var data = Images.insert(newFile); console.log(data._id); // id of the inserted file }); A: data is being redefined on every iteration. Declare it outside of the loop. var data; FS.Utility.eachFile(event, function(file) { ... });
{ "pile_set_name": "StackExchange" }
Q: add GWT-Highchart to Tab in TabSet This is my code : HighChart chart = new HighChart(title, PIE, data); VLayout vlayout = new VLayout(title); vlayout.setHeight100(); vlayout.setWidth100(); vlayout.addMember(chart); Tab tab = new Tab(); tab.setTitle(title); tab.setPane(vlayout); tab.setCanClose(true); tabset.addTab(tab); The HighChart class contain the showcase example code. The result is an empty tab, any solutions? A: I solved the problem, the ​​RootLayoutPanel who did not accept the chart display, a simple replacement by a layout.draw(); did the trick
{ "pile_set_name": "StackExchange" }
Q: Is it possible send data in realtime in iPhone app to an php aplication? I want to make an iPhone app that sends some data to a PHP web site, I know it can be done with a web service, but how? Can be done in realtime? If I got several iPhones how can I make my app? A: NSString *content = @"message=Message&user=21"; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.example.com/form.php"]];//The address of the website page [urlRequest setHTTPMethod:@"POST"]; //Method GET/POST. POST is recommended [urlRequest setHTTPBody:[content dataUsingEncoding:NSISOLatin1StringEncoding]]; // generates an autoreleased NSURLConnection [NSURLConnection connectionWithRequest:request delegate:self]; From : How to write data to the web server from iphone application?
{ "pile_set_name": "StackExchange" }
Q: Sub Query Problems Im having issues getting my head around how i go about coding the following. I have one table with a list of lat/longitudes and another table with a list of place names with latitudes and longitudes. What i need to do is this : 1) Loop through each item in table 1, grab the lat and long, do a radius search on table 2 and grab the place name, update table 1 with the new place name. This code gets me the place name i require : $sql="SELECT *, (3959 * acos(cos(radians('".$lat."')) * cos(radians(lat)) * cos( radians(lon) - radians('".$lng."')) + sin(radians('".$lat."')) * sin(radians(lat)))) AS distance FROM cats HAVING distance < 5 ORDER BY distance LIMIT 1"; I need help figuring out how i join the 2 queries together, or the best way for me to loop through lat/longs from table 1. I tried doing this with a php loop but i dont think thats the best way and i couldn't get it to work Thanks for any help or suggestions! A: Base on your description I think that you need something like this: UPDATE table1 SET place_name = (SELECT place_name FROM table2 WHERE (3959 * acos(cos(radians('".$lat."')) * cos(radians(lat)) * cos( radians(lon) - radians('".$lng."')) + sin(radians('".$lat."')) * sin(radians(lat)))) < 5 ORDER BY (3959 * acos(cos(radians('".$lat."')) * cos(radians(lat)) * cos( radians(lon) - radians('".$lng."')) + sin(radians('".$lat."')) * sin(radians(lat)))) DESC LIMIT 1)
{ "pile_set_name": "StackExchange" }
Q: Experiences with Nokia's Technical Support for Qt? Does anybody have experiences (good or bad) with Nokia's LGPL technical support (or even their commercial license support)? Is it worth the cost? How helpful are they/quality of responses? How responsive is Nokia? http://shop.qt.nokia.com/us/support.html A: I have a commercial license and have contacted them about 10 different times and usually have a response within a day. Often times the e-mail indicates a workaround, alternative solution, or the correct way to handle what I was attempting. When the issues have involved actual bugs, they've been prioritized and then become trackable on the public bug tracker. I've never needed to pursue a workaround for a bug that I've been aware of.
{ "pile_set_name": "StackExchange" }
Q: Need a RegExp to find character not surrounded by plus signs Can somebody please help? I need to sort through a string to check for any single character from a-z that is NOT surrounded by plus signs on both sides specifically Please help? So for example then, I will get strings that are at least 1 char long which will be like: Input = "+d+=3=+s+" (returns "true"--all chars are wrapped in pluses), or Input = "f++d+ (returns "false"--the 'f' is not bordered.) From the above I want to return a true or false value myself, so I'll be using the regex.test(str) function to do so. re: examples of what I've tried so far-> /\b*\w\b*/g;, /[^+]|\=\w[^+]|\=\/g; A: Since JavaScript doesn't have look-behind, rather than just a straight regex.text(str), I think you may need something very slightly more complicated. If you remove all of the characters surrounded by +, then if there are any left in the result, you want a false result and if there are not you want true. So: if (!/[a-z]/.test(str.replace(/\+[a-z](?:\+[a-z])*\+/g, ""))) { // All characters surrounded by `+` (or there were none to start with) } else { // Some unbounded } That expression is a bit complicated, so: \+ - A literal + (the first one of a series) [a-z] - Followed by a character a-z (?:\+[a-z])* - Followed by zero or more occurrences of a literal + and a character a-z \+ - A literal + (the final ending one of a series) That's to handle +b+ as well as +b+b+b+b+. That'll give a false positive for a string that doesn't have any a-z characters in it to start with, so if that's a possibility, check for that in advance, e.g.: if (!/[a-z]/.test(str)) { // String has no a-z characters at all } else if (!/[a-z]/.test(str.replace(/\+[a-z](?:\+[a-z])*\+/g, ""))) { // Has a-z characters, all of them surrounded by `+` } else { // Has a-z characters, at least one not surrounded by `+` }
{ "pile_set_name": "StackExchange" }
Q: Effect of aliasing when sampling at higher rate Considering a signal $f(t)=\sin(2\pi t)$ with frequency $10\textrm{ Hz}$: Middle and bottom plots show the results of sampling at different rates. I'm trying to understand the case shown at the bottom. Is the sampling rate too high that it's capturing noise? What's the name of this effect? May I call it a kind of aliasing caused by high sampling rate? A: The name of this effect is Spectral Leakage. Remember the relation $$\frac{k}{N} = \frac{F}{F_S}$$ where $k$ is the bin number, $N$ is the FFT size, $F$ is the continuous frequency in Hz and $F_S$ is the sample rate in Hz. It can be seen that $k$ varies from $-N/2$ to $N/2-1$ (or from $0$ to $N-1$). So there are only $N$ continuous frequencies $F$ for which you will get a single impulse in discrete frequency domain. So in the first figure, the frequency of the signal contains an exact integer number of periods within the FFT duration and hence the correlation of other DFT sinusoids with the signal is zero. In the second figure, the signal span is not equal to the integer number of periods that violates the orthogonality requirement. Hence, the correlation of different DFT sinusoids appears as leakage around the true frequency. A: When discussing DFT, you have to remember two things: you're windowing your true signal $x[n]$ (which is periodic, and then infinitely long) with a window $w[n]$ (here a rectangular window) to obtain a truncated version $x'[n]$ of it $$x'[n] = x[n]w[n].$$ you're sampling the Fourier Transform $X'(e^{j\Omega})$ of your signal at normalized pulsation $\Omega_k = \frac{2\pi k}{N}$ where $N$ is the number of points of your signal (and thus the number of points of your DFT) $$X'[k] = X'(e^{j\Omega_k}).$$ So now, let's discuss your specific example. The real Fourier transform $X(e^{j\Omega})$ of your signal $x[n]$ is composed of two delta's at $\pm 1$Hz or $\Omega = \pm \frac{2\pi}{10}$ in normalized pulsation (i.e. $\Omega = 2\pi f/f_s$ where $f_s$ is your sampling frequency). This is illustrated in the figure below. Then, in the time domain, you're applying a rectangular window $w[n]$ of length $N$ to $x[n]$, this is equivalent to convolving the real spectrum $X(e^{j\Omega})$ with the Fourier transform $W(e^{j\Omega})$ of your rectangular window, which is a sinc function $$X'(e^{j\Omega}) = X(e^{j\Omega}) \circledast W(e^{j\Omega})$$ where $\circledast$ represents the convolution. Those sinc functions are null at multiples of $\Omega = \frac{2\pi}{N}$. Convolving with a delta is equivalent to moving the signal centered on this delta and so you end up with two sinc functions centered around $\Omega = \pm \frac{2\pi}{10}$. The Fourier Transform of $x'[n]$ is illustrated in the figure below (for the case of $N = 100$). To obtain such a plot showing what is "hidden" in $X'(e^{j\Omega})$, you can use zero-padding on $x'[n]$. Finally, you're sampling the spectrum $X'(e^{j\Omega})$ of your truncated version of $x[n]$ at $\Omega _k = \frac{2\pi k}{N}$ to obtain the DFT $X[k]$. For $N = 100$ (i.e. an integer multiple of the period of $x[n]$), you will thus exactly sample at the places where the sinc functions are centered (for $k = \pm 10$, $\Omega_k$ coincides with the center of the two sinc functions $\Omega = \pm \frac{2\pi}{10}$), and the sinc functions are null. And so you go back to the two delta's at $k = \pm 10$ you observed in the first figure. For $N = 128$ however, the sinc functions are no longer well positionned (the places where the sinc are null do no longer coincides with the pulsation $\Omega_k$ where you will sample). This leads to the second figure you have. A: Think of it this way: You have a 10Hz signal. You try to make a 10Hz signals with some building blocks. 1) Your building blocks are this signals: 1Hz, 2Hz,.. 10Hz, .. 20Hz. Quite easy right? You just make your 10Hz signals using the 10Hz "building block". 2) Your building blocks are: 0.6Hz, 1.2Hz, .. 9.6Hz, 10.2Hz, ... Now what can we do? Well.. the signal looks almost like a 10.2Hz so we use a big block of 10.2. But it's not exactly that so we add a little bit of 9.6 and some others. That's exactly spectral leakage. You're trying to describe a signal with elements you don't have so you project them and use a component of each.
{ "pile_set_name": "StackExchange" }
Q: javascript: Unexpected Evaluation Behavior with Ternary Operator Problem: The function is not returning the value that is expected (3). The following code does not evaluate as expected returning 1. I've found that this is due to the usage of the ternary operator. What about the ternary causes the return value to be unexpected? Is it precedence? The ternary operator is right associative according to the mdn specifications. function foo() { var x = 1; var flag = true; function bar(a,b) { return a + b; } var y = bar(2,2) - (flag) ? x : 0; return y; } alert(foo()); Note that if I modify the line: var y = bar(2,2) - (flag) ? x : 0; to var y = bar(2,2) - ((flag) ? x : 0); The above code will act as expected returning 3. Also note that if I replace the function with any type of float var y = 3 - (flag) ? x : 0; The same unexpected return value is evaluated to 1. A: You guessed correctly: It is precendence. The operator - is evaluated before the ternary operator. var y = bar(2,2) - (flag) ? x : 0; is evaluated as var y = (bar(2,2) - (flag)) ? x : 0; You can see the operator precedence here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence Note that the "conditional" (ternary) operator is way down on the list.
{ "pile_set_name": "StackExchange" }
Q: Asp.Net Core 2 bound object is null When I submit my form, ModelValidation.IsValid is true, but the object I have used [BindProperty] on is null. PageModel I have the [BindProperty] tag on the public Group Group {get; private set} property. In the OnGetAsync(int? Id) method I look up the Group with .FindAsync(Id) and populate the form. That works fine :) My understanding is that the OnPostAsync() should populate the Group object automatically as a result of the BindProperty annotation. However, once I post the ModelState is Valid, but the Group object is null. How do I fix this? using xxx.ReportGroups.Data; using xxx.ReportGroups.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace xxx.ReportGroups.Pages { public class GroupEditModel : PageModel { private readonly ApplicationDbContext _db; public GroupEditModel(ApplicationDbContext db) { _db = db; } [BindProperty] public string ErrorMessage { get; private set; } [BindProperty] public Group Group { get; private set; } public IList<Group> ParentGroups { get; private set; } public IList<Tier> Tiers { get; private set; } public IList<GroupType> GroupTypes { get; private set; } //public async Task<IActionResult> OnGetAsync(int? id) // Snip. It works fine public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { StringBuilder sb = new StringBuilder(); sb.Append("<dl>"); foreach (var modelStateKey in ViewData.ModelState.Keys) { var modelStateVal = ViewData.ModelState[modelStateKey]; foreach (var error in modelStateVal.Errors) { var key = modelStateKey; var errorMessage = error.ErrorMessage; var exception = error.Exception; // You may log the errors if you want sb.Append($"<dt>Key <span class=\"error-hilight\">{key}</span></dt><dd>{errorMessage}<br>{exception}</dd>{Environment.NewLine}"); } } sb.Append("</dl>"); ErrorMessage = sb.ToString(); return Page(); } _db.Attach(Group).State = EntityState.Modified; try { await _db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { ErrorMessage = $"Group {Group.Id} not found!"; } return RedirectToPage(); } public async Task<IActionResult> OnPostDeleteAsync(int id) { var contact = await _db.Groups.FindAsync(id); if (contact != null) { _db.Groups.Remove(contact); await _db.SaveChangesAsync(); } return RedirectToPage(); } } } Listed below is the .cshtml page. It's an edit page, for updating details of an existing object. It display the current values, and then has a form below to modify values. The hidden values were added to ensure I was setting the [Required] properties of the object, but that didn't fix the issue. @page "{id:int?}" @model GroupEditModel @{ ViewData["Title"] = "Edit Group"; } <h2><i class="fas fa-users"></i> @ViewData["Title"] - @Model.Group.Id @Model.Group.Name</h2> @if(Model.ErrorMessage != null) { <div class="error"> @(new HtmlString(Model.ErrorMessage)) </div> } <form method="post"> <div asp-validation-summary="All"></div> <input asp-for="Group.Id" type="hidden" /> <input asp-for="Group.OrgCode" type="hidden" /> <input asp-for="Group.GroupTypeId" type="hidden" /> <input asp-for="Group.ExcludeFromAlertStats" type="hidden" /> <div class="form-static"> <h3>Current Values</h3> <fieldset> <label>Name</label> <span class="readonly">@Model.Group.Name</span> </fieldset> <fieldset> <label>Parent</label> <span class="readonly">@Model.Group.Parent.Name</span> </fieldset> <fieldset> <label>Tier</label> <span class="readonly">@Model.Group.Tier.Id</span> <span class="readonly">@Model.Group.Tier.Name</span> </fieldset> <fieldset> <label>Group Type</label> <span class="readonly">@Model.Group.GroupType.Name</span> <i class="fas fa-lock" title="This property requires admin rights to change"></i> </fieldset> <fieldset> <label asp-for="Group.OrgCode">Org Code</label> <span class="readonly">@Model.Group.OrgCode</span> <i class="fas fa-lock" title="This property requires admin rights to change"></i> </fieldset> </div> <div class="form-edit"> <h3>Edit Values</h3> <fieldset> <label for="Group.Name">Name</label> <input asp-for="Group.Name" /> <span asp-validation-for="Group.Name"></span> </fieldset> <fieldset> <label for="Group.ParentGroupId">Parent</label> <select asp-for="Group.ParentGroupId"> @foreach (Group parent in Model.ParentGroups) { <option value="@parent.Id">@parent.Name</option> } </select> </fieldset> <fieldset> <label for="Group.TierId">Tier</label> <select asp-for="Group.TierId"> @foreach (Tier tier in Model.Tiers) { <option value="@tier.Id">@tier.Name</option> } </select> </fieldset> <fieldset> <input type="submit" /> </fieldset> </div> </form> <h2><i class="fas fa-trash-alt"></i> Delete Group</h2> <form method="post"> <div class="form-delete"> <fieldset> <i class="fas fa-trash-alt" style="color:red"></i> <button type="submit" asp-page="/App/GroupEdit" asp-page-handler="delete" asp-route-id="@Model.Group.Id"> Delete </button> </fieldset> </div> </form> A: You have to make the property setter public.
{ "pile_set_name": "StackExchange" }
Q: c++ error converting *char to int I have a char array that I need converted to int so that I can do math against the values. Right now the closest I can get is -> error: request for member 'str' in 'myData', which is of non-class type 'char*' code: char *getmyData() { static char buff[BUFSIZ]; FILE *fp = popen("php script.php 155", "r"); std::fgets(buff,sizeof(buff),fp); return buff; } void mathFunc(){ char *myData = getmyData(); for (int i = 0; myData[i]; ++i) { int x; const char * cstr2 = myData.str().c_str(); cstr2 >> x; for (int i = 0; i < size; ++i) cout << x[i] + 10; } } error: # g++ -g myDataunfuck.cpp -o myDataunfuck.o -std=gnu++11 -lcurl myDataunfuck.cpp: In function 'void mathFunc()': myDataunfuck.cpp:30:31: error: request for member 'str' in 'myData', which is of non-class type 'char*' myDataunfuck.cpp:31:12: error: invalid operands of types 'const char*' and 'int' to binary 'operator>>' myDataunfuck.cpp:32:23: error: 'size' was not declared in this scope myDataunfuck.cpp:33:15: error: invalid types 'int[int]' for array subscript myDataunfuck.cpp:44:1: error: a function-definition is not allowed here before '{' token myDataunfuck.cpp:47:1: error: expected '}' at end of input complete code A: You can simply do the following:- const char * cstr2 = myData;
{ "pile_set_name": "StackExchange" }
Q: Why do I not get experience for quests? Yesterday, the Warlords of Draenor Patch 6.0.2 released, and once you logged in the first time (with a level 90 character), a quest starts automatically and leads you to the blasted lands. All the quests from there do get you armor, but I don't get experience, theres not even an amount of experience displayed on the quest itself, is this a bug or am I doing something wrong? A: No, this is not a bug. You are actually not playing the expansion itself yet, but its prepatch. Yes, general changes like the item squish, draenor itself and talent changes etc. are already patched in, but the level cap stays 90 until WoD releases (13th of November I think). You currently do the pre-quests for Draenor, these probably intend to gear you up, make you ready for Draenor itself.
{ "pile_set_name": "StackExchange" }
Q: What is the meaning of $1_{x}$ and $1_{y}$? In a book that I read about mapping, it said: Any mapping $f:X\rightarrow Y$ satisfies: $f1_{x}=1_{y}f=f$ $g:Y\rightarrow X$ is a reverse mapping with $f:X\rightarrow Y$ only when $gf=1_{x}$ and $fg=1_{y}$ I do not understand what $1_{x}$ and $1_{y}$ mean. Can anyone explain them to me? A: $1_x:X \to X$ is the identity function that maps each element of $X$ to itself. Likewise $1_y:Y \to Y$ is the identity function that maps each element of $Y$ to itself. Thus $g$ is defined to be a reverse mapping of $f$ if composing it with $f$ on either side yields the identity. (Note that $gf$ is a function from $X$ to itself obtained by first applying $f: X \to Y$ and then $g: Y \to X$. Whereas $fg$ is a function from $Y$ to itself obtained by first applying $g:Y \to X$ and then $f:X \to Y$).
{ "pile_set_name": "StackExchange" }
Q: Wavy underlines as a TextDecoration: what I am doing wrong? I want to create wavy underlines using TextDecoration (in a control similar to RichTextBox). I did the following thing: private static Pen CreateErrorPen() { var geometry = new StreamGeometry(); using (var context = geometry.Open()) { context.BeginFigure(new Point(0.0, 0.0), false, false); context.PolyLineTo(new[] { new Point(0.75, 0.75), new Point(1.5, 0.0), new Point(2.25, 0.75), new Point(3.0, 0.0) }, true, true); } var brushPattern = new GeometryDrawing { Pen = new Pen(Brushes.Red, 0.2), Geometry = geometry }; var brush = new DrawingBrush(brushPattern) { TileMode = TileMode.Tile, Viewport = new Rect(0.0, 1.5, 9.0, 3.0), ViewportUnits = BrushMappingMode.Absolute }; var pen = new Pen(brush, 3.0); pen.Freeze(); return pen; } This almost works, but depending on the underlined word position in text, underlines often show up as a pattern of several superimposed waves. Also the underlines are a bit blurry even when they are correct (wpf problem with drawing between pixels, I suppose). My solution was kind of a trial-and-error, so I might have gone a wrong way, especially with Viewport/ViewportUnits. What am I doing wrong and is there a way to get crisp underlines? Thanks in advance. A: bstoney had a solution to this problem here. The key seems to be setting the Viewbox as well as the Viewport such that the waves are seperated vertically, so you only get 1 in the underline. There are some breaks in the wave that can be eliminated by extending it to the right and changing the Viewbox from so it starts from X=1 instead of 0: <VisualBrush x:Key="WavyBrush" TileMode="Tile" Viewbox="1,0,3,3" ViewboxUnits="Absolute" Viewport="0,-1,6,4" ViewportUnits="Absolute"> <VisualBrush.Visual> <Path Data="M 0,1 C 1,0 2,2 3,1 4,0 5,2 6,1" Stroke="Red" StrokeThickness="0.2"/> </VisualBrush.Visual> </VisualBrush>
{ "pile_set_name": "StackExchange" }
Q: what is the difference between these two lines getting 2 different outputs while using the same currency 'egp' $currency = ($q->currency == 'egp')? '£' : (($q->currency == 'usd') ? '$' : '€'); this line outputs $ $currency = ($q->currency == 'egp')? '£' : ($q->currency == 'usd') ? '$' : '€'; this one outputs £ and I can't find why? note: the only difference is the () around the second ternary operator statement A: Consider this code: echo (true?"Left is first":(true?"Right is first":"")); Left is first Versus echo (true?"Left is first":true?"Right is first":""); Right is first The exaplanation can be found at http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary. In short, in the second case PHP will evaluate true?"Left is first":true as the condition for the ternary expression. This will evaluate to Left is first which evaluates to true and therefore Right is first will be echoed
{ "pile_set_name": "StackExchange" }
Q: Swift 2 upgrade (SpriteKit) I upgrade my spritekit game to swift 2. It went pretty smooth, the converter did most of the work. The rest was about 10 min work. However I now noticing some issues. I get these in my console now 1) 2015-09-10 13:43:07.376 My Game[1392:157762] -canOpenURL: failed for URL: "kindle://home" - error: "This app is not allowed to query for scheme kindle". Once on launch this happens 2) 2015-09-10 13:43:08.541 My Game[1392:157762] <CAMetalLayer: 0x15cd94140>: calling -display has no effect. These are coming up randomly and multiple times. 3) 2015-09-10 13:47:55.889 My Game[3108:182039] Error loading /System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib: dlopen(/System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib, 262): no suitable image found. Did find: /System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib: mach-o, but not built for iOS simulator 2015-09-10 13:47:55.889 My Game[3108:182039] Cannot find function pointer IOHIDLibFactory for factory 13AA9C44-6F1B-11D4-907C-0005028F18D5 in CFBundle/CFPlugIn 0x7fdced037370 </System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin> (bundle, not loaded) 2015-09-10 13:47:55.890 My Game[3108:182039] Error loading /System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib: dlopen(/System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib, 262): no suitable image found. Did find: /System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib: mach-o, but not built for iOS simulator 2015-09-10 13:47:55.890 My Game[3108:182039] Cannot find function pointer IOHIDLibFactory for factory 13AA9C44-6F1B-11D4-907C-0005028F18D5 in CFBundle/CFPlugIn 0x7fdced037370 </System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin> (bundle, not loaded) 2015-09-10 13:47:55.890 My Game[3108:182039] Error loading /System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib: dlopen(/System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib, 262): no suitable image found. Did find: /System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib: mach-o, but not built for iOS simulator 2015-09-10 13:47:55.890 My Game[3108:182039] Cannot find function pointer IOHIDLibFactory for factory 13AA9C44-6F1B-11D4-907C-0005028F18D5 in CFBundle/CFPlugIn 0x7fdced037370 </System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin> (bundle, not loaded) 2015-09-10 13:47:55.891 My Game[3108:182039] Error loading /System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib: dlopen(/System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib, 262): no suitable image found. Did find: /System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib: mach-o, but not built for iOS simulator 2015-09-10 13:47:55.891 My Game[3108:182039] Cannot find function pointer IOHIDLibFactory for factory 13AA9C44-6F1B-11D4-907C-0005028F18D5 in CFBundle/CFPlugIn 0x7fdced037370 </System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin> (bundle, not loaded) 2015-09-10 13:47:55.891 My Game[3108:182039] Error loading /System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib: dlopen(/System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib, 262): no suitable image found. Did find: /System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin/Contents/MacOS/IOHIDLib: mach-o, but not built for iOS simulator 2015-09-10 13:47:55.891 My Game[3108:182039] Cannot find function pointer IOHIDLibFactory for factory 13AA9C44-6F1B-11D4-907C-0005028F18D5 in CFBundle/CFPlugIn 0x7fdced037370 </System/Library/Extensions/IOHIDFamily.kext/Contents/PlugIns/IOHIDLib.plugin> (bundle, not loaded) This happens only when I run on the simulator, on my device they are not showing. Anyone having the same issues since upgrading. A: Incase people are still reading this. Most of these errors went away with Xcode updates since release. Most of these actually only show up when running in the simulator and not on real device.
{ "pile_set_name": "StackExchange" }
Q: Remove attribute of parent only? I'm looking to remove the href attribute of the first link, at the moment it removes the attribute of ALL the links. $("#menu-item-2003 a").removeAttr('href'); This is my html setup: <li id="menu-item-2003"> <a href="#"> <span class="menu-image-title">Products</span> </a> <ul> <li id="menu-item-2005"> <a href="#"> <img src="icon.svg"> <span class="menu-image-title">Title</span> </a> </li> <li id="menu-item-2006"> <a href="#"> <img src="icon.svg"> <span class="menu-image-title">Title</span> </a> </li> </ul> </li> A: If you just want to remove the href of the first a, use direct descendent selector: $("#menu-item-2003 > a").removeAttr('href'); The one which you use currently allows selection of the children at any level, which was causes the issue. Working demo: $("#menu-item-2003 > a").removeAttr('href'); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <li id="menu-item-2003"> <a href="#"> <span class="menu-image-title">Products</span> </a> <ul> <li id="menu-item-2005"> <a href="#"> <img src="icon.svg"> <span class="menu-image-title">Title</span> </a> </li> <li id="menu-item-2006"> <a href="#"> <img src="icon.svg"> <span class="menu-image-title">Title</span> </a> </li> </ul> </li> Alternatively, if a is not a direct descendent, you can use the :first pseudo class to select the very first tag: $("#menu-item-2003 a:first").removeAttr('href');
{ "pile_set_name": "StackExchange" }
Q: CSS override with second stylesheet I'm working on a pretty large website that has a big stylesheet already on the website. We're working with this large corporation with limited ability to make changes (no full access). We'll be applying some new styles for a specific section on the website and we've been given the green light to include a second override stylesheet (in addition to the global one) if needed. My question is this. Are there any browser incompatibility issues we need to be aware of if using this method? Due to the popularity of this website and how many views they receive daily, we'll need to be as compatible as possible and I'm just wanting to make sure that our CSS overrides for the sections we're working with go off without a hitch. I've heard of some rumors that IE may not handle the overrides correctly. Here's an example of the nature of the types of style overrides we'll be doing... if i have body { color:blue; } and body { font-weight:bold; } in the second CSS file, we'll get blue and bold right? A: What you are describing with your CSS is inheritance, and essentially it will 'stack' your css definitions, so as you made the example of body { color: blue } , body { font-weight: bold; } you will end up with both values for body via inheritance (not overriding!) To counter the inheritance, you would need to zero out, or elminate the primary css sheets defnition. so if you had the example: body { padding: 5px; color: red } and you wanted to have a 3px margin with font color blue in your 2ndary sheet you would do the following to counter the inheritance body {padding: 0px; margin: 3px; color: blue } That way you would zero out the padding (to 0, if you so wished, effectively canceling it out). Color would be overwritten, and margin would be the new value added. I would suggest (if you already don't) to use Firefox with firebug enabled (dual screens help here greatly, but not needed). Firebug will show you which lines are canceled out due to inheritance and in essence are overwritten. You could also utilize your own classes, and double (or more) up on the class definition like so: .red { color: red; } .center { text-align: center; } .w500px { width: 500px; } <div class="red center w500px">This text is red and centered</div> This way you just combine the values into one. Might give you another idea on how to go about something differently. Hope that helps.
{ "pile_set_name": "StackExchange" }
Q: ¿Por qué razón mi diccionario es unhasheable? Python Tengo una lista que contiene los elementos (diccionarios) que el usuario decide ingresar del catálogo. El catálogo es el siguiente: self.catalogo = [{"isbn": 0,"titulo": "Lluvia fina","precio": 33000}, {"isbn": 1,"titulo": "Amsterdam","precio": 40000}, {"isbn": 2,"titulo": "Seducción","precio": 80000}, {"isbn": 3,"titulo": "Obsesión","precio": 60000}, {"isbn": 4,"titulo": "Devoción","precio": 100000}, {"isbn": 5,"titulo": "Los renglones torcidos de Dios","precio": 50000}, {"isbn": 6,"titulo": "Plata quemada","precio": 20000}, {"isbn": 7,"titulo": "Intimidad","precio": 40000}, {"isbn": 8,"titulo": "Leonora","precio": 56000}, {"isbn": 9,"titulo": "Éramos unos niños","precio": 17000}] Mi objetivo es obtener solo los elementos cuando no se repitan y dar una salida por pantalla de este tipo: En caso de que se haya seleccionado "Lluvia fina" dos veces: ISBN: 0 / Título: Lluvia fina / Precio: 33000 x2 Intente iterar sobre el set que genero con la función set(), ya que solo va a contener los diccionarios una vez (no-repetidos), e imprimir por pantalla ese "xN" con el método count() (obteniendo el número de veces que se repite un diccionario en la lista). Algo así: for j in range(len(set(self.carrito))): print(f"ISBN: {set(self.carrito)[j]['isbn']} / Título: {set(self.carrito)[j]['titulo']} / Precio: {set(self.carrito)[j]['precio']} x{self.carrito.count(set(self.carrito)[j])}") Nota: self.carrito está definido en el __init__ de la clase (como lista vacía []), obtengo las elecciones del usuario así: confirmacion = input("¿Desea añadir al carrito este libro? [Si o No]") if confirmacion == "Si": cantidad = int(input("¿Cuantos desea añadir al carrito?")) for j in range(cantidad): self.carrito.append(libro) Cuando ejecuto la iteración for j in range(len(set(self.carrito))):, obtengo este error: File "C:\Users\gabriel\Desktop\parteuno.py", line 78, in checkout for j in range(len(set(self.carrito))): TypeError: unhashable type: 'dict Nota: self.carrito es una lista que contiene diccionarios, estoy iterando en el rango de la longitud del set de este. Ahí es donde surge mi pregunta: ¿Por qué se da este error, como pude solucionarlo o hay otra manera e conseguir lo que quiero? Investigando, me dí cuenta que un elemento unhasheable es uno inmutable. No tiene sentido que esté consiguiendo ese error , por que lo diccionarios se pueden modificar y las listas también. Además en ningún momento modifico en el set (ni siquiera itero directamente sobre el, si ¿no sobre el rango de su longitud) **PD:**No adjunto todo el código, son 84 lineas, pero lo haré si es necesario. Muchas gracias de antemano, un saludo! A: Se puede hacer en un solo bucle (mas o menos): catalogo = [{"isbn": 0,"titulo": "Lluvia fina","precio": 33000}, {"isbn": 1,"titulo": "Amsterdam","precio": 40000}, {"isbn": 2,"titulo": "Seducción","precio": 80000}, {"isbn": 3,"titulo": "Obsesión","precio": 60000}, {"isbn": 4,"titulo": "Devoción","precio": 100000}, {"isbn": 5,"titulo": "Los renglones torcidos de Dios","precio": 50000}, {"isbn": 6,"titulo": "Plata quemada","precio": 20000}, {"isbn": 7,"titulo": "Intimidad","precio": 40000}, {"isbn": 8,"titulo": "Leonora","precio": 56000}, {"isbn": 9,"titulo": "Éramos unos niños","precio": 17000}] carrito = [catalogo[1], catalogo[2], catalogo[0], catalogo[2]] print(carrito) carritofinal = [] for item in carrito: if item in carritofinal: # reviso si el diccionario esta en el carrito original item["cantidad"] += 1 # agrego 1 a la cantidad en el nuevo diccionario else: carritofinal.append(item) # Nuevo elemento lo agrego al nuevo diccionario item["cantidad"] = 1 # cantidad = 1 al ser un nuevo elemento print(carritofinal) Resultado: [{'isbn': 1, 'titulo': 'Amsterdam', 'precio': 40000}, {'isbn': 2, 'titulo': 'Seducción', 'precio': 80000}, {'isbn': 0, 'titulo': 'Lluvia fina', 'precio': 33000}, {'isbn': 2, 'titulo': 'Seducción', 'precio': 80000}] [{'isbn': 1, 'titulo': 'Amsterdam', 'precio': 40000, 'cantidad': 1}, {'isbn': 2, 'titulo': 'Seducción', 'precio': 80000, 'cantidad': 2}, {'isbn': 0, 'titulo': 'Lluvia fina', 'precio': 33000, 'cantidad': 1}] Agrego la cantidad a los diccionarios
{ "pile_set_name": "StackExchange" }
Q: Strange c pointer issue I had this kind of question in a job interview. This code seems to be very easy: long a = 1234; long &b = a; For me, a and b are the same thing. But i was asked which expression of the 4 following is the same thing const *long c = &a; const long *d = &a; const * long e = &a; long *const f = &a; Honestly, i do not understand which of the 4 is the equivalent. A: The thing here is that reference can not be assigned to point to another object once initialized. So the closest analogy to pointers would be a constant pointer to non-constant object. Thus you just need to find an expression which matches: const *long c = &a; // invalid const long *d = &a; // non-const pointer to const long const * long e = &a; // invalid long *const f = &a; // const pointer to non-const long
{ "pile_set_name": "StackExchange" }
Q: jQuery: if checkboxes and dropdown option is equal, then I have 3 checkboxes with the following jQuery and it works great. $(document).ready(function() { var $finishBoxes = $('#co1,#co2,#co3'); $finishBoxes.change(function(){ // check if all are checked based on if the number of checkboxes total // is equal to the number of checkboxes checked if ($finishBoxes.length == $finishBoxes.filter(':checked').length) { $('#submit2pd').attr("disabled", false); } else{ $('#submit2pd').attr("disabled", true); } }); $finishBoxes.ready(function(){ // check if all are checked based on if the number of checkboxes total // is equal to the number of checkboxes checked if ($finishBoxes.length == $finishBoxes.filter(':checked').length) { $('#submit2pd').attr("disabled", false); } else{ $('#submit2pd').attr("disabled", true); } }); }); I want to add the following select option to the if statement so if all 3 are checked and the checkbox value=1 (yes) then the $('#submit2pd').attr("disabled", true); <select name="tcaccept" id="tcaccept"> <option value="0"<?php if($mychecklist->tcaccept==0) echo 'selected' ?>>No</option> <option value="1"<?php if($mychecklist->tcaccept==1) echo 'selected' ?>>Yes</option> </select> Any help would be greatly appreciated. A: Here some proper code: if ( ( $finishBoxes.length == $finishBoxes.filter(':checked').length ) && ( $('#tcaccept').val() == '1' )) { $('#submit2pd').prop("disabled", false); // $('#submit2pd').attr("disabled", ""); }else{ $('#submit2pd').prop("disabled", true); //$('#submit2pd').attr("disabled", "disabled"); } If you are using jquery 1.6+, it's better to use .prop() for special attributes like disabled (or checked ...). Edit according to the comments: <form> <input type="checkbox" id="col1" /><label for="col1">Checkbox 1</label> <input type="checkbox" id="col2" /><label for="col2">Checkbox 2</label> <input type="checkbox" id="col3" /><label for="col3">Checkbox 3</label> <select id="tcaccept"> <option value="0">No</option> <option value="1">Yes</option> </select> <input type="submit" text="Submit" id="SubmitButton" /> </form> To cancel the form submition, simply return false;: $('#SubmitButton').click(function(event) { var $finishBoxes = $('#co1,#co2,#co3'); if (!($finishBoxes.length == $finishBoxes.filter(':checked').length && $('#tcaccept').val() == '1' )) { alert('Check all the boxes and select "Yes"'); return false; } // otherwise the form is submitted alert('Form will be submitted'); }); I've created a jsfiddle for you to play with.
{ "pile_set_name": "StackExchange" }
Q: Is this an issue with my PHP Session? I am using sessions to log users into my site. The login form sends the input to a login-exec file which then queries the db and validates the login info. I have placed session_start(); at the beginning of the login-exec file and then used the below snippet to write data to the session: session_regenerate_id(); $member = mysql_fetch_assoc($result); $_SESSION['SESS_MEMBER_ID'] = $member['id']; $_SESSION['Username'] = $member['username']; $_SESSION['key'] = $member['Serial']; session_write_close(); header('Location: account.php'); at the beginning of the account.php file i have required the auth.php to validate the session. account.php: require_once('auth.php'); auth.php: <?php //Start session session_start(); //Check whether the session variable SESS_MEMBER_ID is present or not if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) { header("Refresh: 5; url=login.php"); //echo $_SESSION['SESS_MEMBER_ID']; die("Access Denied!"); exit(); } ?> Always the first time logging in it returns access denied. When the script redirects back to the login page and I try again it always works... I have saved my php files in UTF-8 Without BOM as I originally thought there was leading white space before the session was started. That did not fix the issue and I really can't figure this out. Any ideas as to why this is happening? A: I believe the issue was the redirection url in my login-exec.php script. For example: If I loaded the login.php script by going to http://www.mydomain.com/mysubdirectory/login.php and the header redirect in login-exec.php was pointing to http://subdomain.mydomain.com/account.php the PHPSESSID was being regenerated because the domain changed. So I changed the header redirects to account.php instead of the full url and this resolved the issue. I could have used a full URL either subdomain.mydomain.com or mydomain.com/subdirectory/ but in doing so would of restricted the user and the scripts portability. So simple answer..ensure the domain is staying the same. If it isn't you can set the session name which I am pretty sure would resolve this aswell. However in my case header('Location: script.php'); did the trick.
{ "pile_set_name": "StackExchange" }
Q: Problem with ENGINE_load_private_key and PKCS#11 Being stuck with signing (Authenticode) using PKCS#11 tokens, and given the amazingly poor driver support from the vendor (SafeNet), we're signing Windows code on Linux. All of this is working fine using all of our tokens on several build servers. However, I have one token that fails, depending on the mechanism being used. From Java, using Jsign and the SunPKCS11 provider, everything works fine with this token. However, from osslsigncode, signing fails with this token: Unable to enumerate certificates PKCS11_get_private_key returned NULL Failed to load private key 9df65894eb084ba3140555614123992:error:26096080:engine routines:ENGINE_load_private_key:failed loading private key:eng_pkey.c:124: Failed The difference between the working token and the non-working token is that the non-working token includes not just the certificate, but also its trust chain: # pkcs11-tool --module libeToken.so --list-objects Using slot 0 with a present token (0x0) Certificate Object, type = X.509 cert label: te-69f298db-2f32-4a94-82ea-3e11829b26cd ID: 9df65894eb084ba3 Certificate Object, type = X.509 cert label: Certificate Object, type = X.509 cert label: Using p11tool, the two empty-looking certs above show as: Type: X.509 Certificate Label: Flags: CKA_CERTIFICATE_CATEGORY=CA; ID: My other tokens, all of which work fine, do not include these CA certs. This token was created recently, so it may be that either the token firmware is different from my others, or the token installation process has changed since I created the other, working tokens. The certificate is the same on all of them, working and non-working. I've confirmed (via gdb) that the correct key ID is being passed into ENGINE_load_private_key. I'm not sure who owns the ENGINE API in this case - is it a token driver issue? (SafeNet) Is it a problem with OpenSC? etc. It would be helpful to find some other tool that uses the API in the same way so I could confirm whether the problem somehow lies with osslsigncode (which isn't actively supported) or one of the lower layers in this tower of cards. P.S. I used PKCS#11 Spy, and it shows enumeration of all of the certs in the chain, so it's finding the key pair (by ID), but then fails - no errors in PKCS#11 Spy - all CKR_OK. P.P.S. To address the question of whether this token also has a private key... Using slot 0 with a present token (0x0) Logging in to "Code Signing Token 11". Please enter User PIN: Private Key Object; RSA label: ID: 9df65894eb084ba3 Usage: decrypt, sign, unwrap Certificate Object, type = X.509 cert label: te-69f298db-2f32-4a94-82ea-3e11829b26cd ID: 9df65894eb084ba3 Certificate Object, type = X.509 cert label: Certificate Object, type = X.509 cert label: A: The solution, at least for now, seems to be just deleting the CA certs from the token (via SAC Tools on Windows). Once done, osslsigncode (via the PKCS#11 stack) has no problem finding the token. The CA certs aren't needed for signing, so deleting them presents no problem.
{ "pile_set_name": "StackExchange" }
Q: SQLAlchemy default DateTime This is my declarative model: import datetime from sqlalchemy import Column, Integer, DateTime from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Test(Base): __tablename__ = 'test' id = Column(Integer, primary_key=True) created_date = DateTime(default=datetime.datetime.utcnow) However, when I try to import this module, I get this error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "orm/models2.py", line 37, in <module> class Test(Base): File "orm/models2.py", line 41, in Test created_date = sqlalchemy.DateTime(default=datetime.datetime.utcnow) TypeError: __init__() got an unexpected keyword argument 'default' If I use an Integer type, I can set a default value. What's going on? A: Calculate timestamps within your DB, not your client For sanity, you probably want to have all datetimes calculated by your DB server, rather than the application server. Calculating the timestamp in the application can lead to problems because network latency is variable, clients experience slightly different clock drift, and different programming languages occasionally calculate time slightly differently. SQLAlchemy allows you to do this by passing func.now() or func.current_timestamp() (they are aliases of each other) which tells the DB to calculate the timestamp itself. Use SQLALchemy's server_default Additionally, for a default where you're already telling the DB to calculate the value, it's generally better to use server_default instead of default. This tells SQLAlchemy to pass the default value as part of the CREATE TABLE statement. For example, if you write an ad hoc script against this table, using server_default means you won't need to worry about manually adding a timestamp call to your script--the database will set it automatically. Understanding SQLAlchemy's onupdate/server_onupdate SQLAlchemy also supports onupdate so that anytime the row is updated it inserts a new timestamp. Again, best to tell the DB to calculate the timestamp itself: from sqlalchemy.sql import func time_created = Column(DateTime(timezone=True), server_default=func.now()) time_updated = Column(DateTime(timezone=True), onupdate=func.now()) There is a server_onupdate parameter, but unlike server_default, it doesn't actually set anything serverside. It just tells SQLalchemy that your database will change the column when an update happens (perhaps you created a trigger on the column ), so SQLAlchemy will ask for the return value so it can update the corresponding object. One other potential gotcha: You might be surprised to notice that if you make a bunch of changes within a single transaction, they all have the same timestamp. That's because the SQL standard specifies that CURRENT_TIMESTAMP returns values based on the start of the transaction. PostgreSQL provides the non-SQL-standard statement_timestamp() and clock_timestamp() which do change within a transaction. Docs here: https://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT UTC timestamp If you want to use UTC timestamps, a stub of implementation for func.utcnow() is provided in SQLAlchemy documentation. You need to provide appropriate driver-specific functions on your own though. A: DateTime doesn't have a default key as an input. The default key should be an input to the Column function. Try this: import datetime from sqlalchemy import Column, Integer, DateTime from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Test(Base): __tablename__ = 'test' id = Column(Integer, primary_key=True) created_date = Column(DateTime, default=datetime.datetime.utcnow) A: You can also use sqlalchemy builtin function for default DateTime from sqlalchemy.sql import func DT = Column(DateTime(timezone=True), default=func.now())
{ "pile_set_name": "StackExchange" }
Q: Delete first child node using BeautifulSoup import os from bs4 import BeautifulSoup do = dir_with_original_files = 'C:\FOLDER' dm = dir_with_modified_files = 'C:\FOLDER' for root, dirs, files in os.walk(do): for f in files: print f.title() if f.endswith('~'): #you don't want to process backups continue original_file = os.path.join(root, f) mf = f.split('.') mf = ''.join(mf[:-1])+'_mod.'+mf[-1] # you can keep the same name # if you omit the last two lines. # They are in separate directories # anyway. In that case, mf = f modified_file = os.path.join(dm, mf) with open(original_file, 'r') as orig_f, \ open(modified_file, 'w') as modi_f: soup = BeautifulSoup(orig_f.read()) for t in soup.find_all('table'): for child in t.find_all("table"):#*****this is fine for now, but how would I restrict it to find only the first element? child.REMOVE() #******PROBLEM HERE******** # This is where you create your new modified file. modi_f.write(soup.prettify().encode(soup.original_encoding)) Hi all, I am trying to do some parsing of files using BeautifulSoup to clean them up slightly. The functionality I want is that I want to delete the first table which is anywhere within a table, eg : <table> <tr> <td></td </tr> <tr> <td><table></table><-----This will be deleted</td </tr> <tr> <td><table></table> --- this will remain here.</td </tr> </table> At the moment, my code is set to find all tables within a table and I have a made up a .REMOVE() method to show what I wish to accomplish. How can I actually remove this element? Tl;dr - How can I adapt my code to find only the first nested table in a file. How can I remove this table? A: Find the first table inside the table and call extract() on it: inner_table = soup.find('table').find('table') # or just soup.table.table inner_table.extract()
{ "pile_set_name": "StackExchange" }
Q: View all fields / properties of bean in JSP / JSTL I have a bean, ${product}. I would like to view all of the available fields / properties of this bean. So for instance, ${product.price}, ${product.name}, ${product.attributes.colour} etc. Is it possible to dynamically print out all names and values of these properties in JSP, using JSTL/EL? Something like: <c:forEach items="${product}" var="p"> ${p.key} - ${p.value} </c:forEach> A: Replace object with the bean to determine. <c:set var="object" value="${product}" /> Display all declared fields and their values. <c:if test="${not empty object['class'].declaredFields}"> <h2>Declared fields <em>&dollar;{object.name}</em></h2> <ul> <c:forEach var="field" items="${object['class'].declaredFields}"> <c:catch><li><span style="font-weight: bold"> ${field.name}: </span>${object[field.name]}</li> </c:catch> </c:forEach> </ul> </c:if> Display all declared methods. <c:if test="${not empty object['class'].declaredMethods}"> <h2>Declared methods<em>&lt;% object.getName() %&gt;</em></h2> <ul> <c:forEach var="method" items="${object['class'].declaredMethods}"> <c:catch><li>${method.name}</li></c:catch> </c:forEach> </ul> </c:if> A: Ready to use version of @Toby's answer <p class="TODO <your name> PRINT OBJECT PROPERTIES"> <c:set var="object" value="${<your object here>}" /> <h2><b>Object:&nbsp; ${object.class} </b></h2> <h3><b>Declared fields</b></h3> <c:if test="${!empty object.class.declaredFields}"> <ul> <c:forEach var="attr" items="${object.class.declaredFields}"> <c:catch><li><b>${attr.name}</b>:&nbsp; ${object[attr.name]}</li></c:catch> </c:forEach> </ul> </c:if> <c:if test="${empty object.class.declaredFields}">No declared fields</c:if> <h3><b>Declared methods</b></h3> <c:if test="${!empty object.class.declaredMethods}"> <ul> <c:forEach var="attr" items="${object.class.declaredMethods}"> <c:catch><li><b>${attr.name}</b>(...)</li></c:catch> </c:forEach> </ul> </c:if> <c:if test="${empty object.class.declaredMethods}">No declared methods</c:if> </p>
{ "pile_set_name": "StackExchange" }
Q: FliteController within a loop So I have this loop: for (int i =0; i< ([rounds_words count]-1); i++){ [self.fliteController say:[rounds_words objectAtIndex:(i)] withVoice:self.slt]; } Where array_o_words is an array of strings that I would like to use OpenEars' TtS engine flite to say. I have followed the instructions on http://www.politepix.com/openears/#FliteController_Class_Reference but of course this just states that there can only be one instance. I have tried reseting fliteController = nil but this just prevents it from working at all. Any advice to make the loop work? A: OpenEars developer here. For the current implementation of FliteController you will get the desired results by speaking the NSString at the first index, waiting for the OpenEarsEventsObserver delegate method fliteDidFinishSpeaking to fire, speaking the NSString at the next index, etc.
{ "pile_set_name": "StackExchange" }
Q: What are these numbers after "MM, Bowing and Rhythm"? This Scales practice schedule from violin masterclass has numbers after MM, Bowing and Rhythm means. What do they mean? A: The picture shows the MM indication several times, first time MM=52 then a series of MM= without a number later on MM=40 and finalley MM= without a number MM indicates the metronome speed. So for the options without a number you probably decide the speed yourself. I can't think of any other meaning of MM in this context. As far as I know MM is an abreviation of Maelzel's Metronome, since Maelzel is the inventor. There have been other attempts in the past, trying to make a device that would indicate the time, like using a pendul. Reference: Metronome ELABORATION: @CarlWitthoft wrote this comment: The MM is straightforward. IT's the others that require checking the Introduction to the studies. Oh I see I have misunderstood the question. Well, after that misunderstanding I decided to go the violinmasterclass website to see what it is all about. After looking around on the site I will say this to @Mony who asked the question: If you go to the website and click on "Video Tutorials" and then click on "Scales, Arpeggios, and Double Stops" you end up at this place: Scales, Arpeggios, and Double Stops Here I suggest you watch the videos under the section "Scales". Maybe those videos will give an idea on what the numbers mean. If not you could click on "Contact Us" under "About Us" and simply ask.
{ "pile_set_name": "StackExchange" }
Q: have you got a py-poppler-qt example? I'm developing an application in PyQt4 that eventually has to open and show PDF files. For this task there is a python library: python-poppler (in various spelling flavours). The problem is that it is terribly under documented and the only simple working example I found so far uses Python+Gtk+Cairo, while the example with Python+Qt I found uses an older version of the library, and many major changes have occurred ever since, hence it doesn't work anymore. It's a week I'm trying to use the code in the PyGtk example to hack the code of the PyQt one, but no success so far. Has anybody got a simple example of a Python-Qt program that opens and shows a PDF file, which might be useful to the community to see how to work with that library? Thanks a lot. Archive with broken pyqt example Archive with working PyGtk example A: There is an example buried deep within an experimental (unused) branch of an app, here is a link to the specific file containing the code. Don't know if it'll help? All the relevant poppler code is self contained within the PdfViewer class at the bottom of that file. http://bazaar.launchpad.net/~j-corwin/openlp/pdf/annotate/head:/openlp/plugins/presentations/lib/pdfcontroller.py
{ "pile_set_name": "StackExchange" }
Q: How can I extract an embedded archive to disk during the installation process I have an embedded 7Zip archive in my setup script. Is there a "native" way of extracting the contents to a target folder? If not any hints on how this could be achieved? Updated with my implementation. Thanks for the hint TLama [Files] Source: "Documentation.7zip"; DestDir: "{tmp}" Source: "7za.exe"; DestDir: "{tmp}" [Run] Filename: "{tmp}\7za.exe"; Parameters: "x -o""{app}"" ""{tmp}\Documentation.7zip"""; Flags: runhidden; Description: "{cm:InstallingDocumentation}"; StatusMsg: "{cm:InstallingDocumentationStatus}" [CustomMessages] en.InstallingDocumentation=Documentation Files en.InstallingDocumentationStatus=Installing Documentation Files. This may take several minutes... A: No, there is no native way to extract 7zip files from InnoSetup installer. However, you can get a copy of 7zip library, which is redistributable and call it from InnoSetup script's code section. A: Inno doesn't have any native method of extracting files from anything other than it's own archives (which normally compress better than 7Zip). Inno Setup can however use wildcards for including files to install: [Files] Source: "Documentation\*.*"; DestDir: "{app}/Documentation/"; If you have many small files, using the solidcompression flag will improve compression performance and size.
{ "pile_set_name": "StackExchange" }
Q: How to find and clean up bad questions We've got lots of existing meta posts about how many bad questions there are and how much of a problem they are (or aren't) - that's not what this question is about. I wanted to collect in one post some techniques for finding bad questions and dealing with them and it should come as no surprise that by "dealing with them" I mean to downvote the bad ones. The automatic delete rules are our friend here: questions with no answers and negative scores (or 0, or even +1 in some situations) will be automatically deleted if they meet certain criteria. I'll be posting some of the searches I do to find bad questions and anyone else who has ideas can do the same. Here are the automatic deletion rules: 9 Days If a question was closed more than 9 days ago, and ... was not closed as a duplicate has a score of 0 or less is not locked has no answers with a score > 0 has no accepted answer has no pending reopen votes has not been edited in the past 9 days ... it will be automatically deleted. This check is run every day. (at 0300 UTC) 30 Days If a question (open or closed) is more than 30 days old, and ... has −1 or lower score has no answers* is not locked ...or if it was closed and migrated to a different site... ... it will be automatically deleted. This check is run every week. (0300 UTC on Saturday, to be precise.) *NOTE: In most SE contexts, "no answers" means "no answers with a score > 0" i.e. no upvoted answers. But there are comments on Reference #2 that imply this auto-delete scenario only applies to question with no answers whatsoever. 1 Year If a question (open or closed) is more than 365 days old, and ... has a score of 0 or a score of 1 with a deleted owner has no answers is not locked has a viewcount <= the age of the question in days times 1.5 has 1 or 0 comments ... it will be automatically deleted. This check is also run once a week. References: The official FAQ post on meta.SE about how deleting works. The first answers includes the rules for automatic deletion, and links to more detailed explanations given in the next reference. The post on meta.SE that most clearly states when "bad" posts are automatically deleted. This includes a new rule for automatic deletion that was added in June 2013. Since the automatic delete rules mention locked questions, here's the official FAQ post on those. Duplicates My post on meta.SE asking if the auto-delete rules apply to questions closed as duplicates is the closest thing there is to an official answer. And the answer is: Duplicates do vanish, so the auto-delete rules apparently apply. This isn't official since there's nothing posted by SE employees, but it explains what the observed behaviour is: the same autodelete rules apply to questions closed as duplicates. There's a link to Shog9's answer to another question that implies that crappy duplicates deserve to be deleted. A: The fastest way to get rid of bad questions is to close them and make sure they have a downvote. Here are some ideas for searching for bad questions... #1 - Closed questions with no answers and no upvotes In this previous post, I suggested searching for: closed:1 migrated:0 answers:0 score:0 (Note that score:0 matches only posts with score=0, whereas score:anything_else matches score>=anything_else) On 3 August 2013, there were ~1300 results from this search, but apparently multiple people got in on the cleanup and there are now (18 Aug) only 77 results, most of them merged duplicates which will never be deleted (merged questions are another type of "locked," so they'll always fail that test.) And if you look at the results of: closed:1 migrated:0 answers:0 score:-1...-1 (If you just use score:-1, you get all the questions with score >= -1. The syntax shown limits it to only -1) You'll see that once you go 30 days back, there are very, very few -1 questions left. Yay! All sorts of bad questions gone. #2 - Closed questions with no answers and one upvote This next one isn't as dramatic, search for closed but upvoted questions: closed:1 migrated:0 answers:0 score:1 Since score:1 means score>=1 this matches a few questions with multiple upvotes, but most of them are only +1.  (As of 19 Aug 2013, this search gives ~370 results, and ~300 of them are at +1.) The questions that this search turns up that are +1 are a mixed bag - when I go through the list, I see some that are ok, but many others I think are bad. If they get downvoted to 0 and they're a year old, they'll get auto-deleted. If they get downvoted to -1, they'll get deleted once they're a month old. #3 - Questions (open or closed) with no answers and no upvotes (This is newly added in Sep 2014... I'm not sure how I missed it when I first posted.) answers:0 score:0 locked:0 There are tons of these and many of them are crappy. If so, give them a downvote so they're at -1 and they'll get taken care of on the next Saturday cleanup. I usually sort the search results by date and look through the oldest ones first. I find it's easier to spot old crappy questions. When I added this idea on 9 Sep 2014, this search gave ~8800 results, now on 12 Sep it's down to 8400, so yay! Today, I thought of a complementary search: answers:0 score:1 locked:0 Lots of the questions with just 1 vote are also crappy, so if one person votes those down to 0, they'll show up when someone else does the earlier search for votes:0
{ "pile_set_name": "StackExchange" }
Q: List all valid kbd layouts, variants and toggle options (to use with setxkbmap) Is there a way from command line to retrieve the list of all available keyboard layouts and relative variants? I need to list all the valid layout/variants choices to be used then from setxkbmap. Also about the layout toggle options, is there a way to retrieve a list of all available choices (e.g. grp:shift_caps_toggle , ...) I know that with setxkbmap -query I retrieve the list of my current ones, but I need the whole list of options. UPDATE: I've been told about the command man xkeyboard-config which provides all the info to the command line. Furthermore, using man -P cat xkeyboard-config the output goes to stdout and can be parsed with scripts or c code A: Take a look at localectl, especially following options: localectl list-x11-keymap-layouts - gives you layouts localectl list-x11-keymap-variants de gives you variants for this layout (or all variants if no layout specified) localectl list-x11-keymap-options | grep grp: - gives you all layout switching options A: Try looking in /usr/share/X11/xkb/symbols as described on the setxkbmap man page. The options can be found in various files, try doing a grep -rinH alts_toggle /usr/share/X11/xkb. /usr/share/X11/xkb/rules/xorg.xml looks like a good choice. A: You could retrieve the list in that file /usr/share/X11/xkb/rules/evdev.lst Example to retrieve variants with sed to find only Danish variant sed '/! variant/,/^$/!d;/Danish/!d' < /usr/share/X11/xkb/rules/evdev.lst nodeadkeys dk: Danish (eliminate dead keys) winkeys dk: Danish (Winkeys) mac dk: Danish (Macintosh) mac_nodeadkeys dk: Danish (Macintosh, eliminate dead keys) dvorak dk: Danish (Dvorak) Edit: I add the full list ! layout us USA ad Andorra af Afghanistan ara Arabic al Albania am Armenia az Azerbaijan by Belarus be Belgium bd Bangladesh in India ba Bosnia and Herzegovina br Brazil bg Bulgaria ma Morocco mm Myanmar ca Canada cd Congo, Democratic Republic of the cn China hr Croatia cz Czechia dk Denmark nl Netherlands bt Bhutan ee Estonia ir Iran iq Iraq fo Faroe Islands fi Finland fr France gh Ghana gn Guinea ge Georgia de Germany gr Greece hu Hungary is Iceland il Israel it Italy jp Japan kg Kyrgyzstan kh Cambodia kz Kazakhstan la Laos latam Latin American lt Lithuania lv Latvia mao Maori me Montenegro mk Macedonia mt Malta mn Mongolia no Norway pl Poland pt Portugal ro Romania ru Russia rs Serbia si Slovenia sk Slovakia es Spain se Sweden ch Switzerland sy Syria tj Tajikistan lk Sri Lanka th Thailand tr Turkey tw Taiwan ua Ukraine gb United Kingdom uz Uzbekistan vn Vietnam kr Korea, Republic of nec_vndr/jp Japan (PC-98xx Series) ie Ireland pk Pakistan mv Maldives za South Africa epo Esperanto np Nepal ng Nigeria et Ethiopia sn Senegal brai Braille tm Turkmenistan ml Mali tz Tanzania ! variant chr us: Cherokee euro us: With EuroSign on 5 intl us: International (with dead keys) alt-intl us: Alternative international (former us_intl) colemak us: Colemak dvorak us: Dvorak dvorak-intl us: Dvorak international dvorak-l us: Left handed Dvorak dvorak-r us: Right handed Dvorak dvorak-classic us: Classic Dvorak dvp us: Programmer Dvorak rus us: Russian phonetic mac us: Macintosh altgr-intl us: International (AltGr dead keys) olpc2 us: Group toggle on multiply/divide key srp us: Serbian ps af: Pashto uz af: Southern Uzbek olpc-ps af: OLPC Pashto olpc-fa af: OLPC Dari olpc-uz af: OLPC Southern Uzbek azerty ara: azerty azerty_digits ara: azerty/digits digits ara: digits qwerty ara: qwerty qwerty_digits ara: qwerty/digits buckwalter ara: Buckwalter phonetic am: Phonetic phonetic-alt am: Alternative Phonetic eastern am: Eastern western am: Western eastern-alt am: Alternative Eastern cyrillic az: Cyrillic legacy by: Legacy latin by: Latin oss be: Alternative oss_latin9 be: Alternative, latin-9 only oss_sundeadkeys be: Alternative, Sun dead keys iso-alternate be: ISO Alternate nodeadkeys be: Eliminate dead keys sundeadkeys be: Sun dead keys wang be: Wang model 724 azerty probhat bd: Probhat ben in: Bengali ben_probhat in: Bengali Probhat guj in: Gujarati guru in: Gurmukhi jhelum in: Gurmukhi Jhelum kan in: Kannada mal in: Malayalam mal_lalitha in: Malayalam Lalitha ori in: Oriya tam_unicode in: Tamil Unicode tam_keyboard_with_numerals in: Tamil Keyboard with Numerals tam_TAB in: Tamil TAB Typewriter tam_TSCII in: Tamil TSCII Typewriter tam in: Tamil tel in: Telugu urd-phonetic in: Urdu, Phonetic urd-phonetic3 in: Urdu, Alternative phonetic urd-winkeys in: Urdu, Winkeys bolnagri in: Hindi Bolnagri hin-wx in: Hindi Wx alternatequotes ba: Use guillemets for quotes unicode ba: Use Bosnian digraphs unicodeus ba: US keyboard with Bosnian digraphs us ba: US keyboard with Bosnian letters nodeadkeys br: Eliminate dead keys dvorak br: Dvorak nativo br: Nativo nativo-us br: Nativo for USA keyboards nativo-epo br: Nativo for Esperanto phonetic bg: Traditional phonetic bas_phonetic bg: New phonetic french ma: French tifinagh ma: Tifinagh tifinagh-alt ma: Tifinagh Alternative tifinagh-alt-phonetic ma: Tifinagh Alternative Phonetic tifinagh-extended ma: Tifinagh Extended tifinagh-phonetic ma: Tifinagh Phonetic tifinagh-extended-phonetic ma: Tifinagh Extended Phonetic fr-dvorak ca: French Dvorak fr-legacy ca: French (legacy) multix ca: Multilingual multi ca: Multilingual, first part multi-2gr ca: Multilingual, second part ike ca: Inuktitut shs ca: Secwepemctsin kut ca: Ktunaxa eng ca: English tib cn: Tibetan tib_asciinum cn: Tibetan (with ASCII numerals) alternatequotes hr: Use guillemets for quotes unicode hr: Use Croatian digraphs unicodeus hr: US keyboard with Croatian digraphs us hr: US keyboard with Croatian letters bksl cz: With &lt;\|&gt; key qwerty cz: qwerty qwerty_bksl cz: qwerty, extended Backslash ucw cz: UCW layout (accented letters only) dvorak-ucw cz: US Dvorak with CZ UCW support nodeadkeys dk: Eliminate dead keys mac dk: Macintosh mac_nodeadkeys dk: Macintosh, eliminate dead keys dvorak dk: Dvorak sundeadkeys nl: Sun dead keys mac nl: Macintosh std nl: Standard nodeadkeys ee: Eliminate dead keys dvorak ee: Dvorak us ee: US keyboard with Estonian letters pes_keypad ir: Persian, with Persian Keypad ku ir: Kurdish, Latin Q ku_f ir: Kurdish, (F) ku_alt ir: Kurdish, Latin Alt-Q ku_ara ir: Kurdish, Arabic-Latin ku iq: Kurdish, Latin Q ku_f iq: Kurdish, (F) ku_alt iq: Kurdish, Latin Alt-Q ku_ara iq: Kurdish, Arabic-Latin nodeadkeys fo: Eliminate dead keys nodeadkeys fi: Eliminate dead keys smi fi: Northern Saami classic fi: Classic mac fi: Macintosh nodeadkeys fr: Eliminate dead keys sundeadkeys fr: Sun dead keys oss fr: Alternative oss_latin9 fr: Alternative, latin-9 only oss_nodeadkeys fr: Alternative, eliminate dead keys oss_sundeadkeys fr: Alternative, Sun dead keys latin9 fr: (Legacy) Alternative latin9_nodeadkeys fr: (Legacy) Alternative, eliminate dead keys latin9_sundeadkeys fr: (Legacy) Alternative, Sun dead keys bepo fr: Bepo, ergonomic, Dvorak way bepo_latin9 fr: Bepo, ergonomic, Dvorak way, latin-9 only dvorak fr: Dvorak mac fr: Macintosh bre fr: Breton oci fr: Occitan geo fr: Georgian AZERTY Tskapo generic gh: Multilingual akan gh: Akan ewe gh: Ewe fula gh: Fula ga gh: Ga hausa gh: Hausa ergonomic ge: Ergonomic mess ge: MESS ru ge: Russian os ge: Ossetian deadacute de: Dead acute deadgraveacute de: Dead grave acute nodeadkeys de: Eliminate dead keys ro de: Romanian keyboard with German letters ro_nodeadkeys de: Romanian keyboard with German letters, eliminate dead keys dvorak de: Dvorak sundeadkeys de: Sun dead keys neo de: Neo 2 mac de: Macintosh mac_nodeadkeys de: Macintosh, eliminate dead keys dsb de: Lower Sorbian dsb_qwertz de: Lower Sorbian (qwertz) qwerty de: qwerty simple gr: Simple extended gr: Extended nodeadkeys gr: Eliminate dead keys polytonic gr: Polytonic standard hu: Standard nodeadkeys hu: Eliminate dead keys qwerty hu: qwerty 101_qwertz_comma_dead hu: 101/qwertz/comma/Dead keys 101_qwertz_comma_nodead hu: 101/qwertz/comma/Eliminate dead keys 101_qwertz_dot_dead hu: 101/qwertz/dot/Dead keys 101_qwertz_dot_nodead hu: 101/qwertz/dot/Eliminate dead keys 101_qwerty_comma_dead hu: 101/qwerty/comma/Dead keys 101_qwerty_comma_nodead hu: 101/qwerty/comma/Eliminate dead keys 101_qwerty_dot_dead hu: 101/qwerty/dot/Dead keys 101_qwerty_dot_nodead hu: 101/qwerty/dot/Eliminate dead keys 102_qwertz_comma_dead hu: 102/qwertz/comma/Dead keys 102_qwertz_comma_nodead hu: 102/qwertz/comma/Eliminate dead keys 102_qwertz_dot_dead hu: 102/qwertz/dot/Dead keys 102_qwertz_dot_nodead hu: 102/qwertz/dot/Eliminate dead keys 102_qwerty_comma_dead hu: 102/qwerty/comma/Dead keys 102_qwerty_comma_nodead hu: 102/qwerty/comma/Eliminate dead keys 102_qwerty_dot_dead hu: 102/qwerty/dot/Dead keys 102_qwerty_dot_nodead hu: 102/qwerty/dot/Eliminate dead keys Sundeadkeys is: Sun dead keys nodeadkeys is: Eliminate dead keys mac is: Macintosh dvorak is: Dvorak lyx il: lyx phonetic il: Phonetic biblical il: Biblical Hebrew (Tiro) nodeadkeys it: Eliminate dead keys mac it: Macintosh us it: US keyboard with Italian letters geo it: Georgian kana jp: Kana OADG109A jp: OADG 109A mac jp: Macintosh phonetic kg: Phonetic ruskaz kz: Russian with Kazakh kazrus kz: Kazakh with Russian basic la: Laos stea la: Laos - STEA (proposed standard layout) nodeadkeys latam: Eliminate dead keys deadtilde latam: Include dead tilde sundeadkeys latam: Sun dead keys std lt: Standard us lt: US keyboard with Lithuanian letters ibm lt: IBM (LST 1205-92) lekp lt: LEKP lekpa lt: LEKPa apostrophe lv: Apostrophe (') variant tilde lv: Tilde (~) variant fkey lv: F-letter (F) variant cyrillic me: Cyrillic cyrillicyz me: Cyrillic, Z and ZHE swapped latinunicode me: Latin unicode latinyz me: Latin qwerty latinunicodeyz me: Latin unicode qwerty cyrillicalternatequotes me: Cyrillic with guillemets latinalternatequotes me: Latin with guillemets nodeadkeys mk: Eliminate dead keys us mt: Maltese keyboard with US layout nodeadkeys no: Eliminate dead keys dvorak no: Dvorak smi no: Northern Saami smi_nodeadkeys no: Northern Saami, eliminate dead keys mac no: Macintosh mac_nodeadkeys no: Macintosh, eliminate dead keys qwertz pl: qwertz dvorak pl: Dvorak dvorak_quotes pl: Dvorak, Polish quotes on quotemark key dvorak_altquotes pl: Dvorak, Polish quotes on key 1 csb pl: Kashubian ru_phonetic_dvorak pl: Russian phonetic Dvorak dvp pl: Programmer Dvorak nodeadkeys pt: Eliminate dead keys sundeadkeys pt: Sun dead keys mac pt: Macintosh mac_nodeadkeys pt: Macintosh, eliminate dead keys mac_sundeadkeys pt: Macintosh, Sun dead keys nativo pt: Nativo nativo-us pt: Nativo for USA keyboards nativo-epo pt: Nativo for Esperanto cedilla ro: Cedilla std ro: Standard std_cedilla ro: Standard (Cedilla) winkeys ro: Winkeys crh_f ro: Crimean Tatar (Turkish F) crh_alt ro: Crimean Tatar (Turkish Alt-Q) crh_dobruca1 ro: Crimean Tatar (Dobruca-1 Q) crh_dobruca2 ro: Crimean Tatar (Dobruca-2 Q) phonetic ru: Phonetic phonetic_winkeys ru: Phonetic Winkeys typewriter ru: Typewriter legacy ru: Legacy typewriter-legacy ru: Typewriter, legacy tt ru: Tatar os_legacy ru: Ossetian, legacy os_winkeys ru: Ossetian, Winkeys cv ru: Chuvash cv_latin ru: Chuvash Latin udm ru: Udmurt kom ru: Komi sah ru: Yakut xal ru: Kalmyk dos ru: DOS srp ru: Serbian bak ru: Bashkirian yz rs: Z and ZHE swapped latin rs: Latin latinunicode rs: Latin Unicode latinyz rs: Latin qwerty latinunicodeyz rs: Latin Unicode qwerty alternatequotes rs: With guillemets latinalternatequotes rs: Latin with guillemets alternatequotes si: Use guillemets for quotes us si: US keyboard with Slovenian letters bksl sk: Extended Backslash qwerty sk: qwerty qwerty_bksl sk: qwerty, extended Backslash nodeadkeys es: Eliminate dead keys deadtilde es: Include dead tilde sundeadkeys es: Sun dead keys dvorak es: Dvorak ast es: Asturian variant with bottom-dot H and bottom-dot L cat es: Catalan variant with middle-dot L mac es: Macintosh nodeadkeys se: Eliminate dead keys dvorak se: Dvorak rus se: Russian phonetic rus_nodeadkeys se: Russian phonetic, eliminate dead keys smi se: Northern Saami mac se: Macintosh svdvorak se: Svdvorak legacy ch: Legacy de_nodeadkeys ch: German, eliminate dead keys de_sundeadkeys ch: German, Sun dead keys fr ch: French fr_nodeadkeys ch: French, eliminate dead keys fr_sundeadkeys ch: French, Sun dead keys fr_mac ch: French (Macintosh) de_mac ch: German (Macintosh) syc sy: Syriac syc_phonetic sy: Syriac phonetic ku sy: Kurdish, Latin Q ku_f sy: Kurdish, (F) ku_alt sy: Kurdish, Latin Alt-Q legacy tj: Legacy tam_unicode lk: Tamil Unicode tam_TAB lk: Tamil TAB Typewriter tis th: TIS-820.2538 pat th: Pattachote f tr: (F) alt tr: Alt-Q sundeadkeys tr: Sun dead keys ku tr: Kurdish, Latin Q ku_f tr: Kurdish, (F) ku_alt tr: Kurdish, Latin Alt-Q intl tr: International (with dead keys) crh tr: Crimean Tatar (Turkish Q) crh_f tr: Crimean Tatar (Turkish F) crh_alt tr: Crimean Tatar (Turkish Alt-Q) indigenous tw: Indigenous saisiyat tw: Saisiyat phonetic ua: Phonetic typewriter ua: Typewriter winkeys ua: Winkeys legacy ua: Legacy rstu ua: Standard RSTU rstu_ru ua: Standard RSTU on Russian layout homophonic ua: Homophonic crh ua: Crimean Tatar (Turkish Q) crh_f ua: Crimean Tatar (Turkish F) crh_alt ua: Crimean Tatar (Turkish Alt-Q) extd gb: Extended - Winkeys intl gb: International (with dead keys) dvorak gb: Dvorak dvorakukp gb: Dvorak (UK Punctuation) mac gb: Macintosh colemak gb: Colemak latin uz: Latin crh uz: Crimean Tatar (Turkish Q) crh_f uz: Crimean Tatar (Turkish F) crh_alt uz: Crimean Tatar (Turkish Alt-Q) kr104 kr: 101/104 key Compatible CloGaelach ie: CloGaelach UnicodeExpert ie: UnicodeExpert ogam ie: Ogham ogam_is434 ie: Ogham IS434 urd-crulp pk: CRULP urd-nla pk: NLA ara pk: Arabic legacy epo: displaced semicolon and quote (obsolete) igbo ng: Igbo yoruba ng: Yoruba hausa ng: Hausa left_hand brai: Left hand right_hand brai: Right hand alt tm: Alt-Q fr-oss ml: Français (France Alternative) us-mac ml: English (USA Macintosh) us-intl ml: English (USA International)
{ "pile_set_name": "StackExchange" }
Q: How to Reduce the font size of Morris Donut graph? Here is my js fiddle link JSFiddle I have tried out using css..but its not happening svg text{ font-size:10px!important /*but its not reducing the font size */ } A: Include the style svg text{ font-size:10px!important; } In the end of your HTML (after the js includes). This will solve your problem. P.S:This is not the best way to solve this as morris.js by default resizes your text to fit the graph.
{ "pile_set_name": "StackExchange" }
Q: Enable Checkbox based on Radio Button Selection I have Group of Checkbox , inside Treeview (bootstrap) I'm Trying to create from each in the top Radio Button , Show and Hide function for specif Checkbox Everything I've tried so far has failed. I have 5 Radio button : - Radio button 1 show all checkbox with id matching FCB & FCTK - HIDE THE REST Radio button 2 show only all check boxes with id matching FCB - HIDE THE REST Radio Button 3 show only all check boxes with id matching FCTK- HIDE THE REST Radio button 4 show All Check boxes Radio button 5 i will add new checkbox that he can show ALL options and the new added check boxes any idea how to correctly do this? I have an a idea but i failed when i tried to do it: I thought of doing an array with each Checkbox ID, and then search document elements and create foreach loop, Is that possible? <!DOCTYPE HTML> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> --> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link type="text/css" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <!-- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> --> <title>" TZ Generator</title> </head> <body> <form class="form-horizontal" action="ConstructorMain.php" method="post"> <fieldset> <!-- Form Name --> <!-- <legend>Documents Generator</legend>--> <nav class="navbar navbar-default no-margin"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header fixed-brand"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" id="menu-toggle"> <span class="glyphicon glyphicon-th-large" aria-hidden="true"></span> </button> <a class="navbar-brand" href="#"><i class="fa fa-rocket fa-4"></i> " OTSP Team</a> </div><!-- navbar-header--> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li class="active" ><button class="navbar-toggle collapse in" data-toggle="collapse" id="menu-toggle-2"> <span class="glyphicon glyphicon-th-large" aria-hidden="true"></span></button></li> </ul> </div><!-- bs-example-navbar-collapse-1 --> </nav> <!-- Text input--> <div class="form-group"> <label class="col-md-4 control-label" for="filename">Company Name</label> <div class="col-md-4"> <input id="filename" name="filename" type="text" placeholder="" class="form-control input-md" required=""> <span class="help-block">File name for the generated file</span> </div> </div> <!-- Certified Or Non --> <div class="form-group"> <label class="col-md-4 control-label" for="type">Product Type</label> <div class="col-md-4"> <div class="radio"> <label for="type-0"> <input type="radio" name="type" id="type-0" onchange="checkcert();" value="cert"> Certified " Products </label> </div> <div class="radio"> <label for="type-3"> <input type="radio" name="type" id="type-3" onchange="checkcertFCB();" value="certFCB"> Certified " Products By FCB </label> </div> <div class="radio"> <label for="type-4"> <input type="radio" name="type" id="type-4" onchange="checkcertFCTK();" value="certFCTK"> Certified " Products By FCTK </label> </div> <div class="radio"> <label for="type-1"> <input type="radio" name="type" id="type-1" onchange="checkcertNON();" value="non"> Non-Certified " Product </label> </div> <div class="radio"> <label for="type-2"> <input type="radio" name="type" id="type-2" onchange="checkcertUNI();" value="full"> Universal </label> </div> </div> </div> <!-- AV & CC --> <div class="form-group"> <label class="col-md-4 control-label" for="avcc[]">Protection Type</label> <div class="col-md-4"> <div class="checkbox"> <label for="avcc-0"> <input type="checkbox" name="avcc-0" id="avcc-0[]" value="AV.docx"> Anti-virus </label> </div> <div class="checkbox"> <label for="avcc-1"> <input type="checkbox" name="avcc-1" id="avcc-1[]" value="CC.docx"> Control Center </label> </div> </div> </div> <!-- Product Line Tree New --> <br></br> <div class="form-group"> <label class="col-md-4 control-label" for="ostype">Operating System Platform</label> <div class="col-md-4"> <div id="selection"> <ul> <!-- DSS --> <li> <input type="checkbox" name="DSS" id="DSS-0[]" value="DSS-TXT.docx"> <label for="DSS">DSS :</label> <ul> <li id="DSS-1-tree"> <input type="checkbox" name="DSS-1" id="DSS-1[]" value="DSS-WIN.docx"> <label for="DSS-1">Windows</label> </li> <li id="DSS-3-tree"> <input type="checkbox" name="DSS-3" id="DSS-3[]" value="DSS-WIN-CERT-FCB.docx"> <label for="DSS-3">Windows CERT-FCB</label> </li> <li id="DSS-4-tree"> <input type="checkbox" name="DSS-4" id="DSS-4[]" value="DSS-WIN-CERT-FCTK.docx"> <label for="DSS-4">Windows CERT-FCTK</label> </li> <li id="DSS-2-tree"> <input type="checkbox" name="DSS-2" id="DSS-2[]" value="DSS-LINUX.docx"> <label for="DSS-2">Linux</label> </li> <li id="DSS-5-tree"> <input type="checkbox" name="DSS-5" id="DSS-5[]" value="DSS-LINUX-CERT-FCB.docx"> <label for="DSS-5">Linux CERT-FCB</label> </li> <li id="DSS-6-tree"> <input type="checkbox" name="DSS-6" id="DSS-6[]" value="DSS-LINUX-CERT-FCTK.docx"> <label for="DSS-6">Linux CERT-FCTK</label> </li> </ul> </li> <br></br> <li> <!-- SSS --> <input type="checkbox" name="SSS" id="SSS-0[]" value="SSS-TEXT.docx"> <label for="SSS">SSS :</label> <ul> <li id="SSS-1-tree"> <input type="checkbox" name="SSS-1" id="SSS-1[]" value="SSS-WIN.docx"> <label for="SSS-1">Windows</label> </li> <li id="SSS-3-tree"> <input type="checkbox" name="SSS-3" id="SSS-3[]" value="SSS-WIN-CERT-FCB.docx"> <label for="SSS-3">Windows CERT-FCB</label> </li> <li id="SSS-5-tree"> <input type="checkbox" name="SSS-5" id="SSS-5[]" value="SSS-WIN-CERT-FCTK.docx"> <label for="SSS-5">Windows CERT-FCTK</label> </li> <li id="SSS-2-tree"> <input type="checkbox" name="SSS-2" id="SSS-2[]" value="SSS-LINUX.docx"> <label for="SSS-2">Linux</label> </li> <li id="SSS-4-tree"> <input type="checkbox" name="SSS-4" id="SSS-4[]" value="SSS-LINUX-CERT-FCB.docx"> <label for="SSS-4">Linux CERT-FCB</label> </li> <li id="SSS-6-tree"> <input type="checkbox" name="SSS-6" id="SSS-6[]" value="SSS-LINUX-CERT-FCTK.docx"> <label for="SSS-6">Linux CERT-FCTK</label> </li> </ul> </li> <br></br> <li> <!-- MSS --> <input type="checkbox" name="MSS" id="MSS-0[]" value="MSS-TXT.docx"> <label for="MSS">MSS :</label> <ul> <li id="MSS-1-tree"> <input type="checkbox" name="MSS-1" id="MSS-1[]" value="MSS-LINUX.docx"> <label for="MSS-1">Unix Mail Server </label> </li> <li id="MSS-5-tree"> <input type="checkbox" name="MSS-5" id="MSS-5[]" value="MSS-LINUX-CERT-FCB.docx"> <label for="MSS-5">Unix Mail Server CERT-FCB</label> </li> <li id="MSS-6-tree"> <input type="checkbox" name="MSS-6" id="MSS-6[]" value="MSS-LINUX-CERT-FCTK.docx"> <label for="MSS-6">Unix Mail Server CERT-FCTK</label> </li> <li id="MSS-2-tree"> <input type="checkbox" name="MSS-2" id="MSS-2[]" value="MSS-EXCH.docx"> <label for="MSS-2">MS Exchange</label> </li> <li id="MSS-7-tree"> <input type="checkbox" name="MSS-7" id="MSS-7[]" value="MSS-EXCH-CERT-FCB.docx"> <label for="MSS-7">MS Exchange CERT-FCB</label> </li> <li id="MSS-8-tree"> <input type="checkbox" name="MSS-8" id="MSS-8[]" value="MSS-EXCH-CERT-FCTK.docx"> <label for="MSS-8">MS Exchange CERT-FCTK</label> </li> <li id="MSS-3-tree"> <input type="checkbox" name="MSS-3" id="MSS-3[]" value="MSS-LOUTS.docx"> <label for="MSS-3">Lotus</label> <ul> <li id="MSS-3-1-tree"> <input type="checkbox" name="MSS-3-1" id="MSS-3-1[]" value="MSS-LOUTS-WIN.docx"> <label for="MSS-3-1">Lotus For Windows</label> </li> </ul> <ul> <li id="MSS-3-2-tree"> <input type="checkbox" name="MSS-3-2" id="MSS-3-2[]" value="MSS-LOUTS-LINUX.docx"> <label for="MSS-3-2">Lotus For Linux</label> </li> </ul> </li> <li id="MSS-4-tree"> <input type="checkbox" name="MSS-4" id="MSS-4[]" value="MSS-KERIO-TEXT.docx"> <label for="MSS-4">Kerio</label> <ul> <li id="MSS-4-1-tree"> <input type="checkbox" name="MSS-4-1" id="MSS-4-1[]" value="MSS-KERIO-WIN.docx"> <label for="MSS-4-1">Kerio For Windows</label> </li> </ul> <ul> <li id="MSS-4-2-tree"> <input type="checkbox" name="MSS-4-2" id="MSS-4-2[]" value="MSS-KERIO-LINUX.docx"> <label for="MSS-4-2">Kerio For Linux</label> </li> </ul> </li> </ul> </li> <br></br> <li> <!-- GSS --> <input type="checkbox" name="GSS" id="GSS-0[]" value="GSS-TEXT.docx"> <label for="GSS">GSS :</label> <ul> <li id="GSS-1-tree"> <input type="checkbox" name="GSS-1" id="GSS-1[]" value="GSS-Kerio-Winroute.docx"> <label for="GSS-1">Kerio Winroute</label> </li> <li id="GSS-2-tree"> <input type="checkbox" name="GSS-2" id="GSS-2[]" value="GSS-UNIX.docx"> <label for="GSS-2">Unix gateways</label> </li> <li id="GSS-6-tree"> <input type="checkbox" name="GSS-6" id="GSS-6[]" value="GSS-UNIX-CERT-FCB.docx"> <label for="GSS-6">Unix gateways CERT-FCB</label> </li> <li id="GSS-7-tree"> <input type="checkbox" name="GSS-7" id="GSS-7[]" value="GSS-UNIX-CERT-FCTK.docx"> <label for="GSS-7">Unix gateways CERT-FCTK</label> </li> <li id="GSS-3-tree"> <input type="checkbox" name="GSS-3" id="GSS-3[]" value="GSS-Qbik.docx"> <label for="GSS-3">Qbik</label> </li> <li id="GSS-4-tree"> <input type="checkbox" name="GSS-4" id="GSS-4[]" value="GSS-MIME.docx"> <label for="GSS-4">MIMEsweeper</label> </li> <li id="GSS-5-tree"> <input type="checkbox" name="GSS-5" id="GSS-5[]" value="GSS-ISATMG.docx"> <label for="GSS-5">MS ISA Server & Forefront TMG</label> </li> <li id="GSS-8-tree"> <input type="checkbox" name="GSS-8" id="GSS-8[]" value="GSS-ISATMG-CERT-FCB.docx"> <label for="GSS-8">MS ISA Server & Forefront TMG CERT-FCB</label> </li> <li id="GSS-9-tree"> <input type="checkbox" name="GSS-9" id="GSS-9[]" value="GSS-ISATMG-CERT-FCTK..docx"> <label for="GSS-5">MS ISA Server & Forefront TMG CERT-FCTK</label> </li> </ul> </li> </ul> </div> </div> </div> <!-- Button (Double) --> <div class="form-group"> <label class="col-md-4 control-label" for="generate">Confirm Slection</label> <div class="col-md-8"> <button id="generate" name="generate" class="btn btn-primary">Generate File</button> <button id="clearselection" name="clearselection" class="btn btn-inverse" type="reset">Reset Selection</button> </div> </div> </fieldset> </form> <!-- Tree Code --> <script> $('input[type="checkbox"]').change(function(e) { var checked = $(this).prop("checked"), container = $(this).parent(), siblings = container.siblings(); container.find('input[type="checkbox"]').prop({ indeterminate: false, checked: checked }); function checkSiblings(el) { var parent = el.parent().parent(), all = true; el.siblings().each(function() { return all = ($(this).children('input[type="checkbox"]').prop("checked") === checked); }); if (all && checked) { parent.children('input[type="checkbox"]').prop({ indeterminate: false, checked: checked }); checkSiblings(parent); } else if (all && !checked) { parent.children('input[type="checkbox"]').prop("checked", checked); parent.children('input[type="checkbox"]').prop("indeterminate", (parent.find('input[type="checkbox"]:checked').length > 0)); checkSiblings(parent); } else { el.parents("li").children('input[type="checkbox"]').prop({ indeterminate: true, checked: true }); } } checkSiblings(container); }); </script> <!-- Certified Button FULL CERT --> <script> function checkcert() { var el = document.getElementById("type-0"); if (el.checked) { $('#DSS-4-tree').show(); $("#DSS-3-tree").show(); $("#DSS-5-tree").show(); $("#DSS-6-tree").show(); $("#SSS-3-tree").show(); $("#SSS-5-tree").show(); $("#SSS-4-tree").show(); $("#SSS-6-tree").show(); $("#MSS-5-tree").show(); $("#MSS-6-tree").show(); $("#SSS-7-tree").show(); $("#MSS-8-tree").show(); $("#GSS-6-tree").show(); $("#GSS-7-tree").show(); $("#GSS-8-tree").show(); $("#GSS-9-tree").show(); } else { $("#DSS-4-tree").hide(); $("#DSS-3-tree").hide(); $("#DSS-5-tree").hide(); $("#DSS-6-tree").hide(); $("#SSS-3-tree").hide(); $("#SSS-5-tree").hide(); $("#SSS-4-tree").hide(); $("#SSS-6-tree").hide(); $("#MSS-5-tree").hide(); $("#MSS-6-tree").hide(); $("#SSS-7-tree").hide(); $("#MSS-8-tree").hide(); $("#GSS-6-tree").hide(); $("#GSS-7-tree").hide(); $("#GSS-8-tree").hide(); $("#GSS-9-tree").hide(); } } </script> <!-- Certified Button CERT FCB --> <script> function checkcertFCB() { var el = document.getElementById("type-3"); if (el.checked) { $('#DSS-3-tree').show(); } } </script> <!-- Certified Button CERT FCTK --> <script> function checkcertFCTK() { var el = document.getElementById("type-4"); if (el.checked) { $('#DSS-4-tree').show(); } } </script> <!-- Non Certified Button --> <script> function checkcertNON() { var el = document.getElementById("type-1"); if (el.checked) { $('#MSS-3-tree').show(); } } </script> <!-- Universal Radio Button Selection --> <script> function checkcertUNI() { var el = document.getElementById("type-2"); if (el.checked) $('#').show(); else $('#').hide(); } </script> <!-- No Space Allowed in Input Text --> <script> $("input#filename").on({ keydown: function(e) { if (e.which === 32) return false; }, change: function() { this.value = this.value.replace(/\s/g, ""); } }); </script> </body> A: this was a very big code to look at. it will take a long time if i go through what you have done. so i am gonna give you a idea how you can achieve what you want. for the following form <form > <label><input type="radio" name="aa" value="cert" />fcb FCTK</label> <label><input type="radio" name="aa" value="certFCB" />fcb</label> <label><input type="radio" name="aa" value="certFCTK" />FCTK</label> <label><input type="radio" name="aa" value="non" />none</label> <br /> <br /> <label class="all fcb"><input type="checkbox" name="chk[]" class="all fcb" />fcb 1</label><br /> <label class="all FCTK"><input type="checkbox" name="chk[]" />FCTK 1</label><br /> <label class="all fcb"><input type="checkbox" name="chk[]" />fcb 2</label><br /> <label class="all FCTK"><input type="checkbox" name="chk[]" />FCTK 2</label><br /> <label class="all fcb"><input type="checkbox" name="chk[]" />fcb 3</label><br /> <label class="all FCTK"><input type="checkbox" name="chk[]" />FCTK 3</label><br /> <label class="all fcb"><input type="checkbox" name="chk[]" />fcb 4</label><br /> </form> JS $('input[type="radio"]').change(function(e) { $(".all").hide(); var a = $(this).val(); switch(a) { case 'cert': $(".fcb").show(); $(".FCTK").show(); break; case 'certFCB': $(".fcb").show(); break; case 'certFCTK': $(".FCTK").show(); break; case 'non': default: $(".all").hide(); } }) CSS .all{ display:none; } this kind of solution you are looking for. working jsfiddle link https://jsfiddle.net/vL423ncp/
{ "pile_set_name": "StackExchange" }
Q: read and display text file in the console with time delay? I am trying to print the content of my text file into the console but with time delay, for example 2 seconds for each line. This is my text file content: David 1 1 Chris 1 2 David 2 1 Chris 1 3 David 3 1 and this is my code so far: File f = new File("actions.txt"); try{ Scanner scanner = new Scanner(f); while (scanner.hasNextLine()) { String line = scanner.nextLine(); System.out.println(line); } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } System.exit(0); // terminate the program } any help would be great(im a beginner) A: you can try this. File f = new File("actions.txt"); try{ Scanner scanner = new Scanner(f); while (scanner.hasNextLine()) { String line = scanner.nextLine(); System.out.println(line); Thread.sleep(2000); } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); }catch (InterruptedException e) { e.printStackTrace(); } System.exit(0); // terminate the program }
{ "pile_set_name": "StackExchange" }
Q: SO renderer breaks Makefile syntax The following answer contains an GNU Makefile: https://stackoverflow.com/a/27190627/402322 I tried to use the Makefile on my system, but it does not work, because the syntax is broken. I edited the answer and corrected the syntax. Indented lines need to be indented with exactly one tabulator and no spaces. But after saving the change I realized, that the answer gets rendered in a way, which breaks the syntax of the file. The SO rendering replaces the tabulator with 4 spaces. A: There's a workaround, as per mbomb007's answer to the Meta Stack Exchange feature request. Writing this: <pre><code>Hello! This is a tab:&#9;:bat a si sihT</code></pre> makes: Hello! This is a tab: :bat a si sihT This, however, is by no means perfect, since you have to manually escape &, < and >. It is simply a hack.
{ "pile_set_name": "StackExchange" }
Q: Replace the page from a url using php I have this type of urls stored in a php variable: $url1 = 'https://localhost/mywebsite/help&action=something'; $url2 = 'https://localhost/mywebsite/jobs&action=one#profil'; $url3 = 'https://localhost/mywebsite/info&action=two&action2=something2'; $url4 = 'https://localhost/mywebsite/contact&action=one&action2=two#profil'; I want to replace the page help, jobs, info, contact with home in a very simple way, something like this: echo replaceUrl($url1); https://localhost/mywebsite/home&action=something echo replaceUrl($url2); https://localhost/mywebsite/home&action=one#profil echo replaceUrl($url3); https://localhost/mywebsite/home&action=two&action2=something2 echo replaceUrl($url4); https://localhost/mywebsite/home&action=one&action2=two#profil A: So here is the solution i found: function replaceUrl($page){ $pieces = explode("/", $page); $base = ''; for ($i=0; $i<count($pieces)-1; $i++) $base .= $pieces[$i].'/'; $hash = strpbrk($pieces[count($pieces)-1], '&#'); return $base.'home'.$hash; }
{ "pile_set_name": "StackExchange" }
Q: Tomcat sets cookie JSESSIONID spontaneously I have a spring webapp running on tomcat. I never set any sessions in my code. There is only this line : HttpSession session = httpServletRequest.getSession(false); if( session != null ) { log.debug("session is not null"); } These lines logs, session is not null, which makes no sense. I also checked, a cookie named JSESSIONID is being set. But as you can see above I give false enter code hereargument to getSession. How is this possible ? A: I missed the fact that unless you enter <% session=false %> jsp pages creates a session.
{ "pile_set_name": "StackExchange" }
Q: Homogenizing whole milk, butter, and vodka I have a recipe that calls for mixing half a stick of butter into 1.5 liters of milk and 4 shots of vodka. Unfortunately, these three things don't mix very well and as soon as I pour it out into a serving glass the solution separates. I have read that soy lecithin can be used to homogenize milk and butter, but will it work with the vodka as well? If so, how much soy lecithin needs to be used. If the vodka cannot be incorporated, how much lecithin would I need to homogenize just the butter and the milk? Thanks A: Homogenization has a fairly specific meaning in dairy. To keep the relatively large milk fat globules in cow's milk from coalescing, the milk is forced under some pressure through a very small aperture that atomizes the fat and keeps it in solution. Although it seems like this might work with butter I doubt very much that this is a worthwhile solution (pun intended). What you want, therefore, is to create an emulsion. Butter has some emulsifiers in it but I don't think it will be up to this task on its own. The idea with any emulsion is to blend emulsifiers into the liquid and then slowly add the fat. The emulsifier will grab the particles of fat and keep them from coalescing and so keep them in solution. Look at mayonnaise recipes for examples of this technique though, of course, you don't want as much air worked into your dish. I would mix a small amount of lecithin into the milk and whisk it quickly as you drizzle in the butter. As for the vodka- I don't use alcohol and can't predict how it will behave. If your milk is cold then you shouldn't have a problem with curdling and should be able to mix the vodka directly in with the milk. I fear that if it went directly into the butter that there would be enough liquid to make the emulsification difficult.
{ "pile_set_name": "StackExchange" }
Q: How to pass values across the pages in ASP.net without using Session I am trying to improve performance of my web portal. I'm using Session to store state information. But I heard that using session will decrease the speed of the application. Is there any other way to pass values across the page in asp.net. A: You can pass values from one page to another by followings.. Response.Redirect Cookies Application Variables HttpContext Response.Redirect SET : Response.Redirect("Defaultaspx?Name=Pandian"); GET : string Name = Request.QueryString["Name"]; Cookies SET : HttpCookie cookName = new HttpCookie("Name"); cookName.Value = "Pandian"; GET : string name = Request.Cookies["Name"].Value; Application Variables SET : Application["Name"] = "pandian"; GET : string Name = Application["Name"].ToString(); Refer the full content here : Pass values from one to another A: There are multiple ways to achieve this. I can explain you in brief about the 4 types which we use in our daily programming life cycle. Please go through the below points. 1 Query String. FirstForm.aspx.cs Response.Redirect("SecondForm.aspx?Parameter=" + TextBox1.Text); SecondForm.aspx.cs TextBox1.Text = Request.QueryString["Parameter"].ToString(); This is the most reliable way when you are passing integer kind of value or other short parameters. More advance in this method if you are using any special characters in the value while passing it through query string, you must encode the value before passing it to next page. So our code snippet of will be something like this: FirstForm.aspx.cs Response.Redirect("SecondForm.aspx?Parameter=" + Server.UrlEncode(TextBox1.Text)); SecondForm.aspx.cs TextBox1.Text = Server.UrlDecode(Request.QueryString["Parameter"].ToString()); URL Encoding Server.URLEncode HttpServerUtility.UrlDecode 2. Passing value through context object Passing value through context object is another widely used method. FirstForm.aspx.cs TextBox1.Text = this.Context.Items["Parameter"].ToString(); SecondForm.aspx.cs this.Context.Items["Parameter"] = TextBox1.Text; Server.Transfer("SecondForm.aspx", true); Note that we are navigating to another page using Server.Transfer instead of Response.Redirect.Some of us also use Session object to pass values. In that method, value is store in Session object and then later pulled out from Session object in Second page. 3. Posting form to another page instead of PostBack Third method of passing value by posting page to another form. Here is the example of that: FirstForm.aspx.cs private void Page_Load(object sender, System.EventArgs e) { buttonSubmit.Attributes.Add("onclick", "return PostPage();"); } And we create a javascript function to post the form. SecondForm.aspx.cs function PostPage() { document.Form1.action = "SecondForm.aspx"; document.Form1.method = "POST"; document.Form1.submit(); } TextBox1.Text = Request.Form["TextBox1"].ToString(); Here we are posting the form to another page instead of itself. You might get viewstate invalid or error in second page using this method. To handle this error is to put EnableViewStateMac=false 4. Another method is by adding PostBackURL property of control for cross page post back In ASP.NET 2.0, Microsoft has solved this problem by adding PostBackURL property of control for cross page post back. Implementation is a matter of setting one property of control and you are done. FirstForm.aspx.cs <asp:Button id=buttonPassValue style=”Z-INDEX: 102″ runat=”server” Text=”Button” PostBackUrl=”~/SecondForm.aspx”></asp:Button> SecondForm.aspx.cs TextBox1.Text = Request.Form["TextBox1"].ToString(); In above example, we are assigning PostBackUrl property of the button we can determine the page to which it will post instead of itself. In next page, we can access all controls of the previous page using Request object. You can also use PreviousPage class to access controls of previous page instead of using classic Request object. SecondForm.aspx TextBox textBoxTemp = (TextBox) PreviousPage.FindControl(“TextBox1″); TextBox1.Text = textBoxTemp.Text; As you have noticed, this is also a simple and clean implementation of passing value between pages. Reference: MICROSOFT MSDN WEBSITE HAPPY CODING! A: If it's just for passing values between pages and you only require it for the one request. Use Context. Context The Context object holds data for a single user, for a single request, and it is only persisted for the duration of the request. The Context container can hold large amounts of data, but typically it is used to hold small pieces of data because it is often implemented for every request through a handler in the global.asax. The Context container (accessible from the Page object or using System.Web.HttpContext.Current) is provided to hold values that need to be passed between different HttpModules and HttpHandlers. It can also be used to hold information that is relevant for an entire request. For example, the IBuySpy portal stuffs some configuration information into this container during the Application_BeginRequest event handler in the global.asax. Note that this only applies during the current request; if you need something that will still be around for the next request, consider using ViewState. Setting and getting data from the Context collection uses syntax identical to what you have already seen with other collection objects, like the Application, Session, and Cache. Two simple examples are shown here: // Add item to Context Context.Items["myKey"] = myValue; // Read an item from the Context Response.Write(Context["myKey"]); http://msdn.microsoft.com/en-us/magazine/cc300437.aspx#S6 Using the above. If you then do a Server.Transfer the data you've saved in the context will now be available to the next page. You don't have to concern yourself with removing/tidying up this data as it is only scoped to the current request.
{ "pile_set_name": "StackExchange" }
Q: Aligning text in the centre of the screen between 2 buttons, one of which might not be visible This is difficult to explain, please bear with me. I have a top menu bar in a design which has been given to me (it's a port). The menu bar has two buttons, one on the left of the menu, one on the right, and a text title between the two buttons. The text view is single line so that if the text is longer than the view, it shortens with an ellipsis at the end. The text should be centred within the display width between the buttons. The text is a title for the current content and it's OK that it might be shortened. In practice, on most devices, only the odd letter or two gets chopped off. If both buttons are visible, then it's very straightforward however, depending on where I am in the app, the right button might not be visible. When it's not visible, I use View.GONE. The problem is that the text now fills the remaining space, which is desired, but centres in that remaining space, not within the display width so that a short piece of text is offset to the right by the width of the first button. Using View.INVISIBLE rather than View.GONE is not the answer as the text then centres correctly but doesn't use the available space to minimise the shortening of the text. Here's the effect I'm trying to achieve: Both buttons visible: --------------------------------------------------------------- | Left button | Title text centred in display | Right button | --------------------------------------------------------------- Right button hidden --------------------------------------------------------------- | Left button | Title text centred in display | --------------------------------------------------------------- Right button hidden with long text showing elipsis. This is what I'm looking for. --------------------------------------------------------------- | Left button | A really long piece of title text centred ...| --------------------------------------------------------------- Here's what I'm getting when i hide the right button, note that the text is not centred. --------------------------------------------------------------- | Left button | Title text centred in this space | --------------------------------------------------------------- Here's the layout I'm using currently. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:background="@drawable/activitytitlegradient" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center_vertical"> <ImageView android:id="@+id/mainMenuLeftButton" android:background="#00ffffff" android:layout_gravity="center_vertical" android:src="@drawable/rr_boat_bow" android:scaleType="fitStart" android:layout_weight="1" android:layout_height="34dip" android:layout_width="wrap_content"/> <TextView android:id="@+id/mainMenuTitle" android:layout_weight="10" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="2dp" android:background="#00ffffff" android:text="Reference" android:singleLine="true" android:textSize="19sp" android:textStyle="bold" android:textColor="#ffffff" android:gravity="center_horizontal|center_vertical" /> <Button android:id="@+id/mainMenuRightButton" android:background="@drawable/buttonborder" android:text="Edit" android:textSize="13sp" android:textColor="#ffffff" android:textStyle="bold" android:layout_margin="3dip" android:padding="3dip" android:layout_weight="1" android:layout_height="35dip" android:layout_width="wrap_content" android:visibility="gone"/> </LinearLayout> The first button is implemented as an ImageView to enable some other (non relevant) effects I'm doing elsewhere. The text is hard coded only to help with laying out. My code changes the text as needed. I can do this with a custom view but I am sure there must be a way to do this with the standard framework. Thank you for any clues... A: I've been dreaming about this problem - really! I've woken in the middle of the night thinking about how to fix this thing. The code I posted below is fugly and it offends my eye every time I look at it. The thought of writing a custom widget just to centre some text feels like taking a shotgun to a pimple on my nose. So, I got stuck in again and I'm embarrased at how easy the solution turned out to be. The trick is to use a relative layout, align the second button on the right and anchor the text centring to the parent. The key tag is: android:layout_centerInParent="true" Here are the relevant snippets from the layout XML (I've removed the non-relevant tags to save space): <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/mainMenuLayout" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <ImageView android:id="@+id/mainMenuLeftButton" android:layout_width="wrap_content" android:layout_height="34dip" android:scaleType="fitStart" android:src="@drawable/rr_boat_bow" /> <Button android:id="@+id/mainMenuRightButton" android:layout_width="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:text="Edit" android:visibility="gone" /> <TextView android:id="@+id/mainMenuTitle" android:layout_toRightOf="@+id/mainMenuLeftButton" android:layout_toLeftOf="@+id/mainMenuRightButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_vertical" android:layout_centerInParent="true" android:singleLine="true"/> </RelativeLayout> I'll sleep well tonight. No fugly code, no custom class. UI in XML only - sweet! Hope it helps..
{ "pile_set_name": "StackExchange" }
Q: Extra Cross Join with Spring Data JPA & Querydsl I am using Querydsl 2.9, Spring Data JPA 1.3.0 and Hibernate JPA 2 API version 1.0. I'm attempting to do a simple join between two tables, Parent and Child, joining on a parentId column. For some reason the query that is executed by Hibernate always has an extra cross join in it. The tables look like this: CREATE TABLE PARENT ( PARENTID INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, NAME VARCHAR(255) ); CREATE TABLE CHILD ( CHILDID INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, PARENTID INT(11), NAME VARCHAR(255) ); The domain classes look like this: @Entity @Table(name="PARENT") public class Parent { @Id @GeneratedValue private Integer parentId; private String name; @OneToMany @JoinColumn(name="parentId") private List<Child> children; // ... getters/setters omitted for brevity } @Entity @Table(name="CHILD") public class Child { @Id @GeneratedValue private Integer childId; private Integer parentId; private String name; // ... getters/setters omitted for brevity } My query code looks like this: private List<Parent> test(List<Integer> parentIds) { JPAQuery query = new JPAQuery(entityManagerFactory.createEntityManager()); QParent qParent = QParent.parent; QChild qChild = QChild.child; List<Parent> parents = query.from(qParent, qChild) .innerJoin(qParent.children, qChild) .where(qParent.parentId.in(parentIds)) .list(qParent); return parents; } I would expect the generated query to look something like this: select p.parentId, p.name from parent p inner join child c on c.parentid = p.parentid where p.parentid in(1, 2); However, the query that is actually run is this: select parent0_.parentId as parentId1_3_, parent0_.name as name2_3_ from PARENT parent0_ inner join CHILD children2_ ON parent0_.parentId = children2_.parentId cross join CHILD child1_ where parent0_.parentId in (1 , 2); Notice the extra cross join at the end. I realize I can get correct results if I do a group by on childId, but I don't want the extra overhead of the cross join when it's not necessary. I've tried using both innerJoin and join to no avail. I have scoured the Querydsl docs and I can see that the default join type is cross join, so perhaps I'm not specifying my join correctly? How do I get rid of the extra cross join? A: The second from argument is probably responsible for the cross join. Try this instead List<Parent> parents = query.from(qParent) .innerJoin(qParent.children, qChild) .where(qParent.parentId.in(parentIds)) .list(qParent);
{ "pile_set_name": "StackExchange" }
Q: Parsing ES6 Class Objects From localStorage Doesn't Include Class Functions I want to persist a class object in HTML5 localStorage. The class contains methods which I also need to persist, but parsing the localStorage object reveals that the object isn't the same. class ExcitingMath { constructor(firstNumber, secondNumber) { this._firstNumber = firstNumber; this._secondNumber = secondNumber; } add() { return this._firstNumber + this._secondNumber; } subtract() { return this._firstNumber - this._secondNumber; } } const eMath = new ExcitingMath(2, 4); Logging eMath in the console displays the class object with it's properties and methods: However, when I localStorage.setItem("math", JSON.stringify(eMath)); and JSON.parse(localStorage.getItem("math")); the object to and from localStorage, it no longer includes the constructor or methods. How can I persist the original class instance with localStorage? A: That is not possible since JSON.toString just saves the STATE of the object, but not the object's functions as you have already found out. I faced the same "problem" and wrote a function "fromJSON" in my classes which takes the JSON from localstorage and transforms that into an object as follows: class ExcitingMath { constructor(firstNumber, secondNumber) { this._firstNumber = firstNumber; this._secondNumber = secondNumber; } add() { return this._firstNumber + this._secondNumber; } subtract() { return this._firstNumber - this._secondNumber; } static fromJSON(serializedJson) { return Object.assign(new ExcitingMath(), JSON.parse(serializedJson)) } } You then may use it as follows: const eMath = ExcitingMath.fromJSON(JSON.parse(localStorage.getItem("math")))
{ "pile_set_name": "StackExchange" }
Q: Continuity of a function at $0$ A similar has been asked before, but it was confusing. Please help me with it. I need a general method of dealing with such problems I need to show that the following function is continuous at $0$. $f(0,0)=0$ $$f(x,y)= \frac {x^2y^2}{x^2y^2+(y-x)^2}$$ A: Hints: Let $y=x$. So $\lim_{x,y\to 0}f(x,y)=1\not=0$
{ "pile_set_name": "StackExchange" }
Q: Best way to render a voxel animation using WebGL? I would like to render an animated voxel scene using WebGL and Three.js, for a hobby project (to visualize live point cloud data from a server-side stream). the scene is not very huge - it should be around 128*128*128 voxels (2 millions points). So I suppose I could just load a big static file containing all voxels data, then incrementally add or delete individual voxels, depending on events in a stream from a server. However after seeing this demo (which is not based on a volume (with "inner" details) but a simpler "XY coordinates + elevation + time" model) : webgl kinect demo I am wondering: Could I use the same things (video, textures, shaders..) to render my voxel animations? How would you implement this? I don't have that much "hobby time" so I prefer to ask out before :) For the moment I am thinking about loading many videos, for each layer of the voxel model. But I'm not sure that three.js will like it. On the other hand, voxels are always big memory consumers so maybe I don't have a lot of choices.. Thank you Update 1: I do not need, indeed, real-time visualization of the data. I could just poll the server once in a while (downloading a new snapshot as soon as the previous has been loaded on the GPU)! Update 2: Each voxel has a material attached to it (the "color") A: There're so many ways to go about this, but I'll suggest the following... As it's pretty much down to writing one single shader, I'd choose [GLOW][1] in favor of Three.js but that's entirely up to you - both will work, I think, but I think GLOW will turn out cleaner. (Actually, not sure Three.js supports drawArrays, which is more or less necessary in my suggestion. Read on.) For data I'd use 4 images (PNG as it's lossless) that is... 128x128 pixels Each pixel has (RGBA) 4x8=32 bits Each bit represents a voxel You need 128/32=4 128x128 images to represent 128x128x128 You simply make one shader which you, between draw calls, switch texture and move a position (which is added to the vertex) up/down. There are a couple of ways to go about creating the vertices for the voxel boxes. There's one straight forward method: you create vertex/normal attributes for each voxel box, and a parallell attribute with UVs+bit (basically a 3D UV-coordinate, if you like) to sample the right bit. This will be huge, memory wise, but probably quite fast. On less straight forward method: Possibly you could survive with just the 3D UV-coordinate attribute plus some kind of vertex index (stored in .w in a vec4 attribute), and in the vertex shader calculate a vertex/normals on the fly. I leave it there, cause it's so much explaining and you can probably figure it out yourself ;) The shader will require vertex textures, as you need to sample the textures described above in the vertex shader. Most computers support this, but not all, unfortunately. If the bit is set, you simply project the vertex as you normally do. If it's not set, you place it behind the near clipping plane and WebGL pipeline will remove it for you. Note that bit operations in WebGL is more or less a pain (shift/and/or aren't available) and you should avoid using ints as these aren't supported on some Mac drivers. I've successfully done it before, so it's very doable. ...something like that might work ;D
{ "pile_set_name": "StackExchange" }
Q: jQuery selector output differs between browser console and PhantomJS Why am I getting different results for the same jQuery selector? Website: http://www.cleartrip.com/flights/results?from=BOM&to=DEL&depart_date=03/12/2014&return_date=12/12/2014&adults=1&childs=0&infants=0&class=Economy&airline=&carrier=&intl=n&page=loaded node.js / phantomjs-node(bridge) code: phantom.create(function(ph){ ph.createPage(function(page){ page.open("http://www.cleartrip.com/flights/results?from=BOM&to=DEL&depart_date=03/12/2014&return_date=12/12/2014&adults=1&childs=0&infants=0&class=Economy&airline=&carrier=&intl=n&page=loaded",function(){ setTimeout(function(){ page.evaluate(function(){ var flight= []; $('table.resultUnitMini tbody tr:nth-child(2) td span span').each(function(){ flight.push($(this).html()); }); return { x: flight }; },function(result){ console.log(result.x); }); },15000); }); }); }); This is the output in the browser console: var flight = []; undefined $('table.resultUnitMini tbody tr:nth-child(2) td span span').each(function(){ flight.push($(this).html()); }); flight ["G8-345", "9W-305", "AI-677", "AI-666", "AI-605", "AI-101", "G8-337", "6E-168", "6E-176", "6E-172", "6E-174", "6E-186", "6E-182", "G8-343", "6E-198", "G8-319", "G8-339", "G8-341", "6E-194", "6E-196", "6E-192", "AI-633", "AI-633", "AI-864", "AI-660", "AI-658", "G8-329", "9W-390", "9W-351", "G8-327", "6E-188", "G8-334", "6E-183", "6E-179", "AI-349", "AI-634", "AI-634", "AI-636", "AI-636", "6E-171", "SG-131", "G8-330", "6E-167", "SG-109", "G8-332", "G8-336", "6E-189", "6E-169", "G8-340", "SG-458", "G8-342", "SG-125", "G8-344", "6E-181", "6E-175", "6E-191", "6E-187", "AI-657", "AI-665", "AI-887", "AI-865", "6E-905", "AI-102"] The output in terminal is : [ 'G8-345', '9W-305', 'AI-633', 'AI-633', 'G8-334', '6E-183', 'AI-634', 'AI-634', '6E-171' ] A: The :nth-child CSS selector seems broken in PhantomJS (1.x). For your page, you don't need it. Simply remove it. $('table.resultUnitMini tbody tr td span span').each(function(){ flight.push($(this).html()); }); When you have a problem like this and you need :nth-child and similar, then either use some tricks like table tr + tr td span span for the second tr or use XPath, because it doesn't seem to be broken: var iterator = document.evaluate("//table[contains(@class,'resultUnitMini')]//tr[2]//td//span//span", document, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null), element = iterator.iterateNext(); while(element){ // do something with element here element = iterator.iterateNext(); }
{ "pile_set_name": "StackExchange" }
Q: 1 Watt Audio Amplifier Using BJT I am trying to design a audio amplifier circuit but I do now know where to start. The only requirement given to us is for it to be a 1 watt amplifier. We have decided to use a 9v DC battery as source. I searched in google about the designs but I do not know how it becomes a 1 watt amplifier. I do have a background about the Voltage/Current gain and DC biasing I just need a hint what to do first. EDIT: my load will be an 8 ohm speaker. EDIT: I know the question is too broad. That's why I am also getting a hard time dealing with this thing. My professor only taught us how to solve BJT and FET circuits and gave us project like this. A: I'll try and consider your thoughts about a \$1W\$ design. But quite frankly, the \$9V\$ source just isn't going to cut it. The reason is that assuming perfect efficiency and no headroom required for the circuit itself, the speaker requires \$V_{peak} = \sqrt{2\cdot P\cdot R}\$. In your case, this works out to \$V_{peak} = 4V\$. This is above and below the ground reference your speaker requires. So you need \$\pm 4V\$. Of course, you say you want to use \$9V\$. But this leaves only \$500mV\$ from each rail and I just don't believe you can readily consider that. So a traditional design would require you to give up on the \$9V\$ battery. (And in any case, you will want some kind of ground reference -- there are nice ICs for this, but you'll need something.) You do have an alternative if you are absolutely stuck on the idea of using a \$9V\$ source. You can go to a bridge-tied load configuration. In effect, this is two amplifiers sourcing from the same battery but with one of them \$180^{\circ}\$ out of phase with the other one. The speaker is then tied between the two amplifier outputs. This would get you there. But it greatly complicates your design. If you want to see one of these, take a look at the TDA8551 that I mentioned in an earlier comment to you. That is a BTL amplifier. But I don't think you want to go there. Looks like you are trying to get through a design of some kind (with only a tiny subset of the necessary specifications to do it.) So this means you have to give up on the \$9V\$ power supply and accept something different. For now, let's assume you can accept \$\pm 6V\$ rails, with ground, and go from there. (Otherwise, I can't offer you much. No time to go around trying to explain a full BTL here.) Let's assume you don't want horrible cross-over complications, but that you want a simple output stage, too. That means two BJTs with a pair of diodes to help spread apart the base voltages. That block looks like: simulate this circuit – Schematic created using CircuitLab Through those diodes, you will need a waterfall of current (shown as the drive current), which the output transistors can tap into. This current magnitude needs to be enough to drive the transistor bases. Since the peak \$I_c = \frac{4V}{8\Omega} = 500mA\$, and if we assume we can keep the BJTs out of saturation, then we can reasonably plan a gain of \$\beta=50\$ and estimate a maximum \$I_b = \frac{500mA}{50} = 10mA\$. We'll need a little extra available, though. Just in case. So let's set this up for \$15mA\$. A current mirror is handy. So let's add one: simulate this circuit (I'm ignoring temperature issues everywhere. And other effects. Just keeping this very, very simple.) This current mirror allows me to set up a current flow from the \$+6V\$ rail down to the \$-6V\$ rail. Roughly speaking, I set up a current of about \$I_{drive} = \frac{+6V - 800mV - \left(-6V\right)}{680\Omega} \approx 16.5mA\$. Which is fine. Now, we have to drive the thing. And now I have a serious issue. You didn't say what your source looked like, at all. I have no idea what you need for gain, no idea what loading is allowed on the input, and frankly nothing else about it. I'm clueless. So I'm going to borrow a page from the other answer you got and just cheat. I'm going to use an opamp. Normally, though, that is not what you do. You will have a pre-amplifier that is designed for your input source, then you will have some perhaps variable gain, then you will drive the CTRL line I have above with a specialized circuit for that. (Possible Miller compensation for BJTs, too.) Then the above output stage. Then negative feedback of some kind is necessary. (None of this takes into account that your speaker is a complex impedance and not a resistor, that some operator might short out the wires leading to the speaker, and ... well... oh, who cares? You didn't care about any of that, so neither do I.) So let's just paste on an opamp to give you a fixed gain of 10 and to drive that CTRL line. I won't even bother with a separate current sink BJT. Instead, the opamp will need to be able to sink up to the full \$16.5mA\$ supplied by the current source as well as any PNP BJT base current that may also be required. So let's say at least able to sink \$30mA\$. If you don't like that, you can add a BJT to further lighten the load. I won't specify the opamp. But it will need to be able to get within about \$1V\$ of the bottom rail and perhaps within \$2.4V\$ of the top rail (because of those two diodes adding another \$1.4V\$.) So here is the new circuit: simulate this circuit That should be able to reach about \$\pm 4V\$ on the output. There is still a lot to improve. But it gets the basic idea across. The opamp adjusts its output, sinking current while doing that. The current source sources current for \$Q_1\$ for the positive half of the cycle, leaving the opamp to sink the rest. Then \$Q_1\$ shuts off and \$Q_2\$ takes over for the negative half of the cycle and the opamp now has to sink not only the current source current but also any base current required for \$Q_2\$. That's why I said you need one that can sink up to the over-estimated \$10mA\$ base current of \$Q_2\$ plus the \$16.5mA\$ of the current source, or \$30mA\$ or better. (The opamp won't need to source, as that is what the current mirror is doing.) Also, keep in mind the output requirements for the opamp (within \$1V\$ of the negative rail and within \$2.4V\$ of the positive rail.) Lots more needs to be discussed if you intend to actually make one of these and have it work reasonably well. I didn't care in the least about the wasted current during cross-over, where in this design it's very likely that both BJTs will be conducting a fair amount of current when the speaker drive voltage is near ground. And, I suspect, using the opamp is cheating. If so, there is lots more design work ahead for a discrete amplifier capable of \$1W\$ output and doing that safely into a speaker or some oaf shorting the speaker output leads, while allowing a nice volume control, plus supporting some one or two different specified kinds of input sources.
{ "pile_set_name": "StackExchange" }
Q: Can JAXB unmarshal a string into a date attribute I have a xml tag in this format: <DOB>19801213</DOB> How can I unmarshal this xml tag into a Date variable? @XmlElement (name = "DOB") private Date dob When I try to get dob it return me null. A: You must use an XmlAdapter import java.util.Date; import javax.xml.bind.annotation.adapters.XmlAdapter; public class DateAdapter extends XmlAdapter<String, Date> { @Override public String marshal(Date v) throws Exception { return .. ; } @Override public Date unmarshal(String v) throws Exception { return .. ; } } and on your attribute you must add @XmlJavaTypeAdapter @XmlJavaTypeAdapter(DateAdapter.class) @XmlElement (name = "DOB") private Date dob;
{ "pile_set_name": "StackExchange" }
Q: PHP merging arrays uniquely So i'm working on a small php applications that combines four arrays. Now there is a possibility that some of the possible arrays will be null. I tried the following solution to merge the four arrays uniquely. <?php $a = [1,2,3,4,5]; $b = null; $c = [5,4,3,2,1]; $d = [1,2]; $new_array; if(is_array($a) && is_array($b) && is_array($c) && is_array($d)) { $new_array = array_unique(array_merge($a,$b,$c,$d)); }else if(is_array($a) && is_array($b) && is_array($c)) { $new_array = array_unique(array_merge($a,$b,$c)); }else if(is_array($a) && is_array($b)) { $new_array = array_unique(array_merge($a,$b)); }else{ $new_array = $a; } print_r($new_array); ?> I soon realized my code was highly dysfunctional in that it does not cater for all possible combinations of arrays while excluding the null variables. How do I solve this. Ensuring that all the variables that are arrays are merged a nd those that are not are discarded. Thanks A: how about this? putting all the array's in an array, so you can loop through them all easily, and use a custom in_array() function to check if they are already existing? The good thing about this way is that it doesn't limit the script to just four array's, as it will loop through all the array's you get together. $a = [1,2,3,4,5]; $b = null; $c = [5,4,3,2,1]; $d = [1,2]; $array_stack = array($a, $b, $c, $d); $new_array = array(); foreach($array_stack as $stack){ if(!is_array($stack)) continue; foreach($stack as $value){ if(!in_array($value, $new_array)) $new_array[] = $value; } } print_r($new_array); A: maybe something like this : <?php $a = [1,2,3,4,5]; $b = null; $c = [5,4,3,2,1]; $d = [1,2]; $new_array; if(is_array($a)) $new_array = $a; if(is_array($b)) $new_array = array_unique(array_merge($new_array,$b)); if(is_array($c)) $new_array = array_unique(array_merge($new_array,$c)); if(is_array($d)) $new_array = array_unique(array_merge($new_array,$d)); ?>
{ "pile_set_name": "StackExchange" }
Q: Extraction of value from Chrome local storage not assigning the value to local variable I am creating a Chrome extension using React. During login I store the username and for some other operation I need to extract it inside the background.js file whose contents are below: /* globals chrome */ chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { let username; if (request.data.type == "SENDTRANSACTION") { chrome.storage.sync.get(['username'], (response) => { console.log(response.username) username = response.username // This is not being set on first invocation }); console.log(username); sendResponse({message: "Sent values to Server"}); } }); The value of username is undefined. Am I missing something? A: Try this: chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { let username; if (request.data.type == "SENDTRANSACTION") { chrome.storage.sync.get(['username'], (response)=>{ username = response.username // This is not being set on first invocation console.log(username); sendResponse({ message: "Sent values to Server" }); }); return true; } }); chrome.storage.sync.get need time to load data from storage, so your sendResponse before callback run (set username = response.username) Check runtime#event-onMessage This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously
{ "pile_set_name": "StackExchange" }
Q: Flash message in AJAX rendering I have a Products and product Reviews controller. Im trying to display a Flash message ("Your review is under review for approval") in my AJAX rendering when a review is created. Not sure how do i go about doing so. Review Controller def create @product = Product.find(params[:product_id]) @review = Review.new(review_params) @review.user = current_user @review.product = @product respond_to do |format| if @review.save format.html { redirect_to product_path(@product), flash[:notice]="Your review is under review for approval" } format.js {render :create_success} else format.html { render "products/show" } format.js {render :create_failure} end end end create_success.js.erb $("#reviews").prepend("<%= j render '/reviews/review', review: @review %>"); <% @review = Review.new %> $("#new_review").replaceWith("<%= j render 'review_form' %>") index.html.erb <div class="reviews" id="<%= dom_id(review)%>"> </div> <%= simple_form_for [@product, @review], remote: true do |f| %> <div class="form-group"> <%= f.input :review_comment, placeholder: "Let us know what you think here..."%> </div> <div> <%= f.submit "Submit", class: "btn review-form-btn" %> </div> <% end %> A: Step-1: Add an element to DOM as follows: <div id="flash_notice"></div> Step-2: Render flash message to DOM in create.js.erb : $("#flash_notice").html("Your review is under review for approval");
{ "pile_set_name": "StackExchange" }
Q: Is there any program designed for writing a book? Is there any program for writing a book? I tried to find it on some forums and sites, but I really couldn't find any. A: For smaller projects, you should be fine with Libreoffice Writer. If you are looking for a professional typesetting tool, the most well known and most widely used open source program is called LaTeX. On Ubuntu, the texlive LaTeX distribution is available in the software repository. Beware, that LaTeX is not a WYSIWYG (What You See Is What You Get) editor, but a WYGIWYW (What You Get Is What You Want) typesetting language, and can in some respects be compared to HTML. LaTeX files are plain text, which are compiled by the LaTeX program into DVI or PDF files. There exist numerous style templates, and with some knowledge of the LaTeX language one can write them oneself. Using a style template and only writing plain text spares the user the tedious work with layout, and lets the writer concentrate on what is being written instead on how it might look in the end. A: Try Scribus. Scribus is an Open Source program that brings professional page layout to Linux, it supports professional publishing features, such as color separations, CMYK and spot colors, ICC color management, and versatile PDF creation. For other ways to install, and Instructions for Debian/Ubuntu Or Click to install Scribus Source:Scribus A: Since no one else has mentioned it: If you want something as predictable as LaTeX, but don't need all of the power (and the complexity that comes with that power), Markdown is a great language. It's what's this website uses for markup. You write plain text and it gets converted to formatted text: Input: # Title This is a paragraph with *italics* and **bold**. Output: Title This is a paragraph with italics and bold. Ubuntu has a program called Pandoc, which can convert Markdown to basically any format you could want (including LaTeX, if you decide you want fancier formatting than Markdown can do).
{ "pile_set_name": "StackExchange" }
Q: Authenticating proxy like CNTLM but without the NTLM On one of the corporate networks I log into, I use CNTLM to centralise my proxy settings. It's great, because when I have to change my password every so often, I only need to change it in one spot, and everything else works. On another network I log into, they have a proxy server that isn't using NTLM. I tried to configure CNTLM to use it, but it doesn't seem to work. Does anyone know of any software like CNTLM that uses non-NTLM auth (basic/digest/etc.) in Linux? A: Polipo was proposed for non-NTLM auth in this article: http://www.techbite.in/2011/10/setup-transparent-net-access-over-insti.html
{ "pile_set_name": "StackExchange" }
Q: Parsing an URL in JavaScript I need to parse url in JavaScript. Here is my code: var myRe = /\?*([^=]*)=([^&]*)/; var myArray = myRe.exec("?page=3&Name=Alex"); for(var i=1;i<myArray.length;i++) { alert(myArray[i]); } Unfortunately it only works for first name=value pair. How I can correct my code? A: exec returns a match, or null if no match found. So you need to keep execing until it returns null. var myRe = /\?*([^=]*)=([^&]*)/; var myArray; while((myArray = myRe.exec("?page=3&Name=Alex")) !== null) { for(var i=1;i<myArray.length;i++) { alert(myArray[i]); } } Also, you're regex is wrong, it definately needs th g switch, but I got it working using this regex: var regex = /([^=&?]+)=([^&]+)/g; See Live example: http://jsfiddle.net/GyXHA/
{ "pile_set_name": "StackExchange" }
Q: Support both armv6 and iOS 6 in an App Store app? Since Xcode 4.5, we are unable to build for armv6 and thus unable to support devices like iPhone 3G anymore. Would it be possible to use, say, Xcode 4.3 to generate a properly signed armv6 binary and then use lipo to combine that binary and the Xcode-4.5-generated armv7 binary into a fat one? How would I go about this? Does anyone know a good tutorial? Would the resulting fat binary be allowed for submission to the App Store? A: The code signature would no longer match after modifying a binary using lipo. So the bundle would need to be re-codesigned afterwards. Apps built with Xcode 4.4 and even earlier will still run just fine on iOS 6 devices; and there are reports that Apple is still accepting apps built with the iOS 5.1 SDK. Objective C will allow you to use some of the newer APIs not in the older linked frameworks via calling them thru the Objective C runtime by name. (Of course, the app should check for their availability on the current device first!) You can even support the new iPhone 5 display from an earlier Xcode and pre-iOS-6 SDK by simply including a 568@2x tall Default image in the app bundle, and setting all your app's window and view sizes and resizing properties properly. UPDATE: Apple is no longer accepting apps built this way when submitted to the iTunes App store. ADDED: Another potential solution is to split your development into two similar apps. One for iOS 4.3 and up. And one for iOS 4.2.x and lower with not iOS 6 and iPhone 5 support. Two different apps in the app store. However it is unknown whether Apple will allow this. A: It appears that someone else figured out how to do it, see this SO question. I haven't tested it yet myself, though.
{ "pile_set_name": "StackExchange" }
Q: CSS: Empty inputs have a different line height to inputs with content? This is not so much a specific problem for a certain site, just something that I seem to nortice in every project. If you take a look here. Click inside the input, the caret stretches to the height of the input. Now press a key, the caret shrinks to the text height. Does anyone: a) Know why this happens b) Know how to fix it? A: I don't know if it's worth it, but if you insist on fixing this issue in Firefox, you could do this: On the focus event, if the value of the text-box is an empty string, then: set the value to " " (a space character) move the caret to the beginning of the text-box Working demo: http://jsfiddle.net/U2TPK/11/ I am using a custom script to set the selection. It is located here: http://vidasp.net/js/selection.js selec.set(this, 0, 0) will set the caret to the beginning of the text-box. $("input:text").focus(function() { if ( this.value.length === 0 ) { this.value = " "; selec.set(this, 0, 0); } }); Update: http://jsfiddle.net/U2TPK/12/ (this also handles the situation when the user repeatedly focuses the empty text-box)
{ "pile_set_name": "StackExchange" }
Q: Simple Odata With Ms Dynamic 2016 Web API insert return null I am using simple Simple.Odata API to insert new entity data into Ms Dynamic CRM Web api and use the following code snip var newContactData = await _oDataClient .For<Contacts>() .Set(new { firstname = contactData.ContatDetails.firstname, lastname = contactData.ContatDetails.lastname, emailaddress1 = contactData.ContatDetails.emailaddress1 }) .InsertEntryAsync(true); This code snip created new entity data but the Problem is newcontactData is always null. According to documentation newcontactData object should have newly created object data. see the link for documenation https://github.com/object/Simple.OData.Client/wiki/Adding-entries A: By default when creating a record no data is returned, the new record id is returned in the header (OData-EntityId). This differs from the older 2011 endpoint where the record is returned by default. https://msdn.microsoft.com/en-us/library/gg328090.aspx#bkmk_basicCreate In the latest version of CRM 8.2/Dynamics 365 you have the option to return all the attributes by passing the Prefer: return=representation header. https://msdn.microsoft.com/en-us/library/gg328090.aspx#bkmk_createWithDataReturned
{ "pile_set_name": "StackExchange" }
Q: monkeyrunner script - starting an activity that requires a permission in a monkeyrunner script while launching an activity, is there a way to mimic yourself having a certain permission that the starting activity requires? I am using "device.startActivity(component='com.package/.MyActivity)" but the activity MyActivity requires a permission, and hence device.startActivity fails. Is there a way to give this permission to the script? A: When I had this problem, I solved it by creating a very small application(with the correct permissions in the manifest) that I pushed to the phone. All the application did was re-send intents sent to it, but to a different destination. My application also had a gui for triggering events manually, but that's optional.
{ "pile_set_name": "StackExchange" }
Q: How to get specific part of url string? This is the result of the console.log below: console.log('subscribe:', event.url); "https://hooks.stripe.com/adapter/ideal/redirect/complete/src_1E2lmZHazFCzVZTmhYOsoZbg/src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ?success=true" Where I want to strip src_1E2lmZHazFCzVZTmhYOsoZbg and src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ How to achieve this? A: Convert the string to a url, read the pathname and than split on / and take the last two parts. var str = "https://hooks.stripe.com/adapter/ideal/redirect/complete/src_1E2lmZHazFCzVZTmhYOsoZbg/src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ?success=true" const parts = new URL(str).pathname.split('/').slice(-2) console.log(parts)
{ "pile_set_name": "StackExchange" }
Q: Do pointers always lead to memory leak or they are deleted when they go out of scope? I'm studying c++ and I'm reading about pointers. I'm curious about the following scenarios: Scenario 1: If I'm not mistaken, if the user types -1, there will be a memory leak: #include <iostream> using namespace std; int main(){ int *p = new int; cout << "Please enter a number: "; cin >> *p; if (*p == -1){ cout << "Exiting..."; return 0; } cout << "You entered: " << *p << endl; delete p; return 0; } Scenario 2: But what happens in the following code? From what I've read and correct me if I'm wrong, when declaring a pointer like in the second scenario the pointer gets cleared out once you are out of scope. So if the user doesn't enter -1, the *p will be auto-cleared? #include <iostream> using namespace std; int main(){ int x; int *p = &x; cout << "Please enter a number: "; cin >> *p; if (*p == -1){ cout << "Exiting..."; return 0; } cout << "You entered: " << *p << endl; return 0; } What happens if I enter -1 in the second scenario? A: Do not focus on the fact that you are using pointers that much. Memory leaks are usually about memory that the pointer points to, not about the pointer itself. In this code: int x; int *p = &x; there is no memory leak since there is no memory that would require explicit deallocation (no memory that has been allocated dynamically). int x is a variable with automatic storage duration that will be cleaned up automatically when the execution goes out of scope and int *p = &x; is just a pointer that holds the address of the memory where x resides. But you are right that in code like: Resource* r = new Resource(); if (something) { return -1; } delete r; there is a memory leak since there is a return path (exit path) that doesn't free the allocated memory. Note that the same would happen if the exception would be thrown instead of return being called... ensuring that all resources are freed properly is one of the main reasons why you should learn more about smart pointers, the RAII idiom and try to prefer objects with automatic storage duration over dynamically allocated ones. A: In the second scenario, everything's fine. Indeed, you haven't allocated memory (while you did in the first scenario). In the first case, the pointer "holds" the memory you allocated through new. In the second case, it points to a local variable with automatic-storage duration (i.e. it will be removed when going out of scope). Simple rule: If you used new you must use delete (unless you're using a smart pointer). In the first scenario, if you type -1, you end up with one new and zero delete, which yields a memory leak. In the second case, you haven't allocated anything, the pointer points to memory that is already managed.
{ "pile_set_name": "StackExchange" }
Q: Swift 4: type(of:self).description() differs from String(describing: type(of:self)) I need to determine the dynamic type of my object in a method that is implemented in a super class. The super class is called BaseClient and DisplayClient inherits from it. I only need the class name, not the package name. This is what I tried: print("1", String(describing: type(of: self))) // DisplayClient print("2", type(of: self)) // DisplayClient print("3", type(of: self).description()) // package.DisplayClient print("4", "\(type(of: self))") // DisplayClient Why does type(of: self).description() return package.DisplayClient while the others only return the class name? I wonder what is called internally when I use String(describing: type(of: self)). I would assume this does exactly what I do (call describing()). Where can I find more info on how the strings get generated internally? The docs say: Use this initializer to convert an instance of any type to its preferred representation as a String instance. The initializer creates the string representation of instance in one of the following ways, depending on its protocol conformance: If instance conforms to the TextOutputStreamable protocol, the result is obtained by calling instance.write(to: s) on an empty string s. If instance conforms to the CustomStringConvertible protocol, the result is instance.description. If instance conforms to the CustomDebugStringConvertible protocol, the result is instance.debugDescription. An unspecified result is supplied automatically by the Swift standard library. But type(of: self) does not even have a description attribute. It only has a description() method. Is this some special case that is handled differently by the compiler? A: If your class inherits from NSObject then type(of: self).description() invokes the NSObject.description() class method: class func description() -> String NSObject's implementation of this method simply prints the name of the class. and it is not documented whether that includes the module name or not. If your class does not inherit from NSObject then there is no default description() method. On the other hand, print(String(describing: type(of: self))) // DisplayClient print(type(of: self)) // DisplayClient both print the unqualified type name, and print(String(reflecting: type(of: self))) // package.DisplayClient debugPrint(type(of: self) ) // package.DisplayClient both print the fully qualified type name, compare How to get a Swift type name as a string with its namespace (or framework name) and the Xcode 7 Release Notes: Type names and enum cases now print and convert to String without qualification by default. debugPrint or String(reflecting:) can still be used to get fully qualified names.
{ "pile_set_name": "StackExchange" }
Q: Firestore Reading Old Data I've deleted all documents from my collection "Cards". But my old data keeps showing up! I've recently updated my Firebase pods. Here is my reading data code: CARDS_REF.addSnapshotListener({ (snapshot, error) in if let error = error { debugPrint("ERROR WHILE FETCHING CARDS: \(error.localizedDescription)") return } var newCards = [Card]() guard let snaps = snapshot else { return } for snap in snaps.documents { let newCard = Card(key: snap.documentID, dictionary: snap.data() as [String: AnyObject]) let timeStamp = newCard.expirationDate let expirationDate: Date = timeStamp!.dateValue() let currentDate = Date() if currentDate < expirationDate { newCards.append(newCard) } } self.cards = newCards self.mainVC?.cardsLoaded() }) Here is CARDS_REF: let firestoreRef = Firestore.firestore() // <-- Declared outside of class fileprivate var _CARDS_REF = firestoreRef.collection("cards") // <-- Declared inside DataService class var CARDS_REF: CollectionReference { // <-- Declared inside DataService class return _CARDS_REF } Any ideas? Thanks! A: Yea Firebase is caching data for you. To disable this, do the following: let settings = FirestoreSettings() settings.isPersistenceEnabled = false db.settings = settings // db is your firebase database reference.
{ "pile_set_name": "StackExchange" }
Q: Javascript merge two objects I am looking for a javascript function like PHP array_merge_recursive(). From what I've read, there is no such thing in javascript, and I want to know how I can implement something similar. The problem: I have two objects: var obj1 = { "AUDCAD": { "t": [1439238600, 1439238600], "o": [0.9646, 0.9646], "h": [0.9646, 0.9646], "l": [0.9645, 0.9645], "c": [0.9645, 0.9645], "v": [15, 15] }, "AUDCHF": { "t": [1439238600, 1439238600], "o": [0.7291, 0.7291], "h": [0.7292, 0.7292], "l": [0.729, 0.729], "c": [0.7291, 0.7291], "v": [6, 6] } }; var obj2 = { "AUDCAD": { "t": [111], "o": [111], "h": [111], "l": [111], "c": [111], "v": [111] }, "AUDCHF": { "t": [111], "o": [111], "h": [111], "l": [111], "c": [111], "v": [111] } }; Of those objects I need to create a new one like this: var obj3 = { "AUDCAD": { "t": [1439238600, 1439238600, 111], //Note that the value "111" is added from obj2 to the end of obj1. "o": [0.9646, 0.9646, 111], "h": [0.9646, 0.9646, 111], "l": [0.9645, 0.9645, 111], "c": [0.9645, 0.9645, 111], "v": [15, 15, 111] }, "AUDCHF": { "t": [1439238600, 1439238600, 111], "o": [0.7291, 0.7291, 111], "h": [0.7292, 0.7292, 111], "l": [0.729, 0.729, 111], "c": [0.7291, 0.7291, 111], "v": [6, 6, 111] } } What im doing: /* Code seen here: http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically Author: Scdev */ function extendObjects() { var newObject = {}; var overwriteValues = false; var overwriteObjects = false; for (var indexArgument = 0; indexArgument < arguments.length; indexArgument++) { if (typeof arguments[indexArgument] !== 'object') { if (arguments[indexArgument] == 'overwriteValues_True') { overwriteValues = true; } else if (arguments[indexArgument] == 'overwriteValues_False') { overwriteValues = false; } else if (arguments[indexArgument] == 'overwriteObjects_True') { overwriteObjects = true; } else if (arguments[indexArgument] == 'overwriteObjects_False') { overwriteObjects = false; } } else { extendObject(arguments[indexArgument], newObject, overwriteValues, overwriteObjects); } } function extendObject(object, extendedObject, overwriteValues, overwriteObjects) { for (var indexObject in object) { if (typeof object[indexObject] === 'object') { if (typeof extendedObject[indexObject] === "undefined" || overwriteObjects) { extendedObject[indexObject] = object[indexObject]; } extendObject(object[indexObject], extendedObject[indexObject], overwriteValues, overwriteObjects); } else { if (typeof extendedObject[indexObject] === "undefined" || overwriteValues) { extendedObject[indexObject] = object[indexObject]; } } } return extendedObject; } return newObject; } var newExtendedObject = extendObjects('overwriteValues_False', 'overwriteObjects_False', obj1, obj2); I am using nodejs and I have tried without success with some libraries, I've also read some similar questions here but not found a solution to my problem. Any suggestions on how I can solve? Thanks everyone for your time. Temporal solution Temporarily solved my problem with array.push() //Pseudo-code obj1[0]["AUDCAD"]["t"].push(obj2[0]["AUDCAD"]["t"]); A: This function assumes that all the keys and sub-keys in object x are in object y and vice versa. function merge(x, y) { var result = {}; Object.keys(x).forEach( function (k) { result[k] = {}; Object.keys(x[k]).forEach( function (j) { if (j in y[k]) { result[k][j] = x[k][j].concat(y[k][j]); } }); }); return result; } Test run: merge(obj1, obj2); => { AUDCAD: { t: [ 1439238600, 1439238600, 111 ], o: [ 0.9646, 0.9646, 111 ], h: [ 0.9646, 0.9646, 111 ], l: [ 0.9645, 0.9645, 111 ], c: [ 0.9645, 0.9645, 111 ], v: [ 15, 15, 111 ] }, AUDCHF: { t: [ 1439238600, 1439238600, 111 ], o: [ 0.7291, 0.7291, 111 ], h: [ 0.7292, 0.7292, 111 ], l: [ 0.729, 0.729, 111 ], c: [ 0.7291, 0.7291, 111 ], v: [ 6, 6, 111 ] } }
{ "pile_set_name": "StackExchange" }
Q: No static method intoSet in Firebase |error while i try to implement firebase database and push notification I use firebase database and firebase push notification while I run my app it crashes with firebase error This is the error: java.lang.NoSuchMethodError: No static method intoSet(Ljava/lang/Object;Ljava/lang/Class;)Lcom/google/firebase/components/Component;in class Lcom/google/firebase/components/Component;or its super classes (declaration of 'com.google.firebase.components.Component' appears in /data/app/com.shadow.recipeworld-1/base.apk) at com.google.firebase.platforminfo.LibraryVersionComponent.create(com.google.firebase:firebase-common@@19.3.0:25) at com.google.firebase.analytics.connector.internal.AnalyticsConnectorRegistrar.getComponents(com.google.android.gms:play-services-measurement-api@@17.2.2:10) at com.google.firebase.components.zzf.<init>(com.google.firebase:firebase-common@@16.0.2:52) at com.google.firebase.FirebaseApp.<init>(com.google.firebase:firebase-common@@16.0.2:539) at com.google.firebase.FirebaseApp.initializeApp(com.google.firebase:firebase-common@@16.0.2:355) at com.google.firebase.FirebaseApp.initializeApp(com.google.firebase:firebase-common@@16.0.2:324) at com.google.firebase.FirebaseApp.initializeApp(com.google.firebase:firebase-common@@16.0.2:310) at com.google.firebase.provider.FirebaseInitProvider.onCreate(com.google.firebase:firebase-common@@16.0.2:53) at android.content.ContentProvider.attachInfo(ContentProvider.java:1748) at android.content.ContentProvider.attachInfo(ContentProvider.java:1723) at com.google.firebase.provider.FirebaseInitProvider.attachInfo(com.google.firebase:firebase-common@@16.0.2:47) at android.app.ActivityThread.installProvider(ActivityThread.java:5173) at android.app.ActivityThread.installContentProviders(ActivityThread.java:4768) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4708) at android.app.ActivityThread.-wrap1(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1406) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5438) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:762) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652) Following is content in gradle: implementation 'com.google.firebase:firebase-messaging:20.1.0' implementation 'com.google.firebase:firebase-database:19.2.0' implementation 'com.google.firebase:firebase-core:17.2.2' implementation 'com.firebase:firebase-client-android:2.5.2' My notification service : public class GeneralNotificationService extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); Global.showNotification(getBaseContext(),remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody()); } } My notification function : public static void showNotification( Context c,String title,String message) { if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) { NotificationChannel channel =new NotificationChannel("GeneralNotification","GeneralNotification", NotificationManager.IMPORTANCE_DEFAULT); NotificationManager manager=c.getSystemService(NotificationManager.class); manager.createNotificationChannel(channel); Notification.Builder builder=new Notification.Builder(c,"GeneralNotification") .setContentTitle(title) .setSmallIcon(R.drawable.ic_launcher_background) .setAutoCancel(true) .setContentText(message); manager.notify(1,builder.build()); } else { NotificationCompat.Builder builder=new NotificationCompat.Builder(c,"GeneralNotification") .setContentTitle(title) .setSmallIcon(R.drawable.ic_launcher_background) .setAutoCancel(true) .setContentText(message); NotificationManagerCompat manager=NotificationManagerCompat.from(c); manager.notify(1,builder.build()); } } Any help will be appreciated! A: Remove the following dependency: implementation 'com.firebase:firebase-client-android:2.5.2' This is the old firebase library which is not supported anymore.
{ "pile_set_name": "StackExchange" }
Q: TreeMap foreach doesn't change value object So I have a TreeMap<Integer, Transmitter> and through a foreach I am trying to modify an inner attribute of the transmitter, but it feels like it is making a copy of the object in the TreeMap, since it does not change the value in the TreeMap. My foreach code: for (TreeMap<Integer, Transmitter> current : transmitterDiagnosticMap.values()) { for (Transmitter t : current.values()) { String transmitterError = t.printErrorReport(date, appContext); if (transmitterError != null) stringsErrorsAndWarnings.add(transmitterError); } } My printErrorReport code: public String printErrorReport(String data, Context context) { String output = null; if (this.writeOnReport()) { // This is the function that will modify the object output = data + " - " + this.getTension(); } return output; } // This is the method that tells whether or not the report will be written, and changes the variable lastStatus if necessary private boolean writeOnReport() { if (this.status > 0) { if (this.lastStatus == 0 || this.lastStatus != this.status) { this.lastStatus = this.status; return true; } return false; } else { this.lastStatus = 0; return false; } } What I could notice is that the Transmitter t actually changes the value from lastStatus = 0 to lastStatus = 1, but nothing is changed in the TreeMap. A: You have to use the iterator to mutate the values in the TreeMap. Using current.values() will create a copy instead of mutating the object. You need to iterate over the keys of the TreeMap and update the values. for (TreeMap<Integer, Transmitter> current : transmitterDiagnosticMap.values()) { for (Map.Entry<Integer, Transmitter> entry : current.entrySet()) { Transmitter t = entry.getValue(); String transmitterError = t.printErrorReport(date, appContext); if (transmitterError != null) stringsErrorsAndWarnings.add(transmitterError); entry.setValue(t); } }
{ "pile_set_name": "StackExchange" }
Q: Background switcher, when a div hits top of the page I've been trying for a while to get this completely working now and perfecting the code, but I am still a rooky javascript programmer so I decided to ask for help. What I want the script to do is, when a div hits to top(or bottom) of the page the body background changes. My current script to make this happen is. function bg_switch() { var window_top = $(window).scrollTop(); var div_top = $('#post12').offset().top; var div_top_1 = $('#post10').offset().top; var div_top_2 = $('#post8').offset().top; var div_top_3 = $('#post1').offset().top; if (window_top > (div_top) ) { $("body").css({"backgroundImage":"url(<?php bloginfo( 'template_url' );?>/img/bg/bg-join-us.jpg)"}); } if (window_top > (div_top_1) ) { $("body").css({"backgroundImage":"url(<?php bloginfo( 'template_url' );?>/img/bg/bg-about-us.jpg)"}); } if (window_top > (div_top_2)) { $("body").css({"backgroundImage":"url(<?php bloginfo( 'template_url' );?>/img/bg/bg-contact.jpg)"}); } if (window_top > (div_top_3)) { $("body").css({"backgroundImage":"url(<?php bloginfo( 'template_url' );?>/img/bg/bg-bf4-join-us.jpg)"}); } } $(function () { $(window).scroll(bg_switch); bg_switch(); }); As you can see this isn't really good code, it also doesn't change the background back for the first post. Here is a website where I am working on and trying to get this principle work, so you guys see for yourself. http://neutralgaming.nl/NeutralGaming/ (sorry for the slow loading page, bad host) Thanks for your time A: The jQuery plugin Waypoints might help you out a lot here. You can basically set your own offsets and then return something when the browser is at that position from the top, for example: $('#div_top').waypoint(function() { $(this).css({ 'background' : 'url(../path/to/img.jpg) no-repeat;' }, { offset: 0 }); So, this will change the background image of #div_top when its offset is 0 from the top.
{ "pile_set_name": "StackExchange" }
Q: Почему переполнение стека в дочернем потоке убивает весь процесс? Отвечая на этот вопрос был удивлен, что переполнение стека в дочернем потоке убивает процесс целиком. Собственно, вопрос: А почему так происходит? Ведь каждый поток имеет собственный стек, даже, на сколько я помню, Рихтер писал об этом. Даже StackTrace().FrameCount показывает различное кол-во фреймов в основном потоке и дочернем. В С++- это обрабатываемое исключение, если верить комментариям из предыдущего вопроса, а в .NET нет, так как возможно, как я понимаю, что СLR, которой нужно что-то сделать, может повредится из-за не хватки стека. CLR, по идее, одна на все приложение и она точно не крутится в дочернем потоке. Получается, что запуская чужой код, к исходникам которого мы не имеем доступа, хоть в отдельном потоке, хоть в отдельном домене, то мы все равно падаем и в .NET никак нельзя предотвратить это при таком типе исключения? UPD Есть какие-то "Области с ограничением выполнения" CER, где можно указать, что метод может поверить процесс. Это никак не оказывает влияния на CLR, что бы она подготовилась и не умерла? A: По-моему тут накладываются друг на друга две особенности работы CLR. Необработанные исключения в дочерних потоках убивают процесс Не только переполнение стека, а вообще любое необработанное исключение в дочернем потоке убивает весь процесс: static void Main() { var thread = new Thread(Recursive); thread.Start(); while (true) { Console.WriteLine("I will live forever!"); Thread.Sleep(1000); } } static void Recursive() { throw new Exception("RIP Unnamed Process (2018-2018"); } Об это говорится в MSDN: Starting with the .NET Framework version 2.0, the common language runtime allows most unhandled exceptions in threads to proceed naturally. In most cases this means that the unhandled exception causes the application to terminate. [Спорную] мотивацию такого поведения дает Эрик Липперт: We cannot easily tell the difference between bugs which are missing handlers for vexing/exogenous exceptions, and which are bugs that have caused a program crash because something is broken in the implementation. The safest thing to do is to assume that every unhandled exception is either a fatal exception or an unhandled boneheaded exception. In both cases, the right thing to do is to take down the process immediately. This philosophy underlies the implementation of unhandled exceptions in the CLR. Way back in the CLR v1.0 days the policy was that an unhandled exception on the "main" thread took down the process aggressively, but an unhandled exception on a "worker" thread simply killed the thread and left the main thread running. (And an exception on the finalizer thread was ignored and finalizers kept running.) This turned out to be a poor choice; the scenario it leads to is that a server assigns a buggy subsystem to do some work on a bunch of worker threads; all the worker threads go down silently, and the user is stuck with a server that is sitting there waiting patiently for results that will never come because all the threads that produce results have disappeared. It is very difficult for the user to diagnose such a problem; a server that is working furiously on a hard problem and a server that is doing nothing because all its workers are dead look pretty much the same from the outside. The policy was therefore changed in CLR v2.0 such that an unhandled exception on a worker thread also takes down the process by default. You want to be noisy about your failures, not silent. Это означает что исключения в потоках нужно обрабатывать намертво, например так: static void SafeRecursive() { try { Recursive(); } catch (Exception e) { //должная обработка, запись в логи и уведомление администраторам //ха-ха, так никто не делает, просто глотаем и забываем о потоке } } StackOverflowException нельзя поймать Но особенность StackOverflowException в том, что его нельзя поймать, ни в дочернем потоке, ни где-либо еще: static void Main() { try { Recursive(); } catch (Exception) { //не получится Console.WriteLine("Catch!"); } } О чем сказано в документации исключения: Starting with the .NET Framework 2.0, you can’t catch a StackOverflowException object with a try/catch block, and the corresponding process is terminated by default. Consequently, you should write your code to detect and prevent a stack overflow. Документация ясно дает понять, что нигде в процессе переполнение стека возникать не должно, вообще нигде. Есть вырожденные случаи, в которых StackOverflowException все же можно обработать: если Вы сами загружаете CLR, то может получится ее восстановить; если StackOverflowException выбрасывается кодом. В .Net 1.0 переполнение стека можно было отловить, с версии 2.0 разработчики заняли жесткую позицию: «Переполнение стека — проблема программиста и его кода, а не CLR». Я не смог найти прямых указаний на то, по какой причине потребовалось внести изменения. Предполагаю, что восстановление после SOE было небеспроблемно и разработчики решили не тратить на эту задачу ресурсы. Вообще, обе эти особенности CLR вполне укладываются в пуританскую философскую позицию «мертвые программы не врут», которую также освещает Эрик Липперт: I am of the philosophical school that says that sudden, catastrophic failure of a software device is, of course, unfortunate, but in many cases it is preferable that the software call attention to the problem so that it can be fixed, rather than trying to muddle along in a bad state, possibly introducing a security hole or corrupting user data along the way. Обновление: Constrained Execution Regions Вопрос в комментариях: А "Области с ограничением выполнения" CER - это что такое? Вот там можно повесить атрибут, что есть возможность того, что будет поврежден процесс. Это на что-то влияет? Влияет. CER позволяет защититься от части ошибок, которые могли бы возникнуть при исполнении кода (ошибки загрузки классов, нехватки памяти) и корректно освободить ресурсы. Тем не менее, переполнение стека с помощью CER обработать не получится. Об этом пишет Рихтер (CLR via C#, Constrained Execution Regions): Note Even if all the methods are eagerly prepared, a method call could still result in a StackOverflowException. When the CLR is not being hosted, a StackOverflowException causes the process to terminate immediately by the CLR internally calling Environment.FailFast. When hosted, the PreparedConstrainedRegions method checks the stack to see if there is approximately 48 KB of stack space remaining. If there is limited stack space, the StackOverflowException occurs before entering the try block. Внимание: Даже если все методы были явно подготовлены, вызов метода все еще может привести к StackOverflowException. Если CLR не загружена извне, то StackOverflowException завершает процесс немедленно, вызывая Environment.FailFast. Если CLR загружена извне, то метод PreparedConstrainedRegions проверяет, осталось ли в стеке примерно 48КБ свободного пространства. Если пространство стека ограничено, то StackOverflowException вызывается перед входом в блок try. Т.о. отловить переполнение стека с помощью одного CER не получится. StackOverflowException также отдельно упоминается в документации: CERs that are marked using the PrepareConstrainedRegions method do not work perfectly when a StackOverflowException is generated from the try block. For more information, see the ExecuteCodeWithGuaranteedCleanup method. Мне никак не удалось заставить метод ExecuteCodeWithGuaranteedCleanup обработать переполнение стека. Судя по обсуждению в вопросе по данному методу он также сработает только если Вы сами захостите CLR. Ссылки Catching unhandled exception on separate threads — вопрос об обработке исключений в отдельном потоке catch exception that is thrown in different thread — еще один. How do I prevent and/or handle a StackOverflowException? — вопрос о предупреждении SOE, рассматриваются разного рода костыли. When can you catch a StackOverflowException? — статья о вырожденных случаях, которая только подчеркивает, что SOE поймать нельзя. Asynchrony in C# 5, Part Eight: More Exceptions — статья Эрика Липперта об исключениях в асинхронных функциях, в которой, между делом, рассказывается об истории обработки исключений в дочерних потоках в .Net 1.0 и, в целом, об отношении авторов C# к обработке исключений. A: В С++- это обрабатываемое исключение, если верить комментариям из предыдущего вопроса На самом деле все немного не так. Стандартными средствами С++, разумеется, нельзя обработать переполнение стека. Однако, в Windows его можно обработать с помощью механизма SEH. И, что бы ни говорил Эрик Липперт, восстановление после переполнения стека - вполне поддерживаемый сценарий, иначе зачем бы существовали функции _resetstkoflw и SetThreadStackGuarantee? а в .NET нет, так как возможно, как я понимаю, что СLR, которой нужно что-то сделать, может повредится из-за не хватки стека В .NET StackOverflowException не обрабатывается не потому, что это технически невозможно, а потому, что так решили разработчики. В Windows переполнение стека порождает исключение SEH с кодом STATUS_STACK_OVERFLOW (0xC00000FD). CLR перехватывает SEH-исключения и, если видит этот код, принудительно убивает процесс (будучи загруженной с параметрами по умолчанию). При этом куда более опасное Access Violation .NET почему-то разрешает обрабатывать. Получается, что запуская чужой код, к исходникам которого мы не имеем доступа, хоть в отдельном потоке, хоть в отдельном домене, то мы все равно падаем и в .NET никак нельзя предотвратить это при таком типе исключения? Только средствами .NET нельзя. Однако в неуправляемом коде нужно написать, по сути, очень немного. Один из способов обойти это поведение, это создать специальную неуправляемую DLL, единственной целью которой будет обработать SEH-исключение и поменять его код на тот, который CLR "не напугает" (SEH-исключения с неизвестным кодом CLR преобразует в SEHException, которое можно обработать). В приложении на C# загрузить DLL, установить векторный обработчик исключений и увеличить размер зарезервированной области стека с помощью функции SetThreadStackGuarantee. Конечно, это не обеспечит полное восстановление стека, т.е., чтобы можно было далее в том же потоке снова словить переполнение стека и обработать его. Но если просто позволить потоку завершиться и забыть про него, это не имеет значения: вновь созданные потоки уже будут иметь корректный стек. Например, создадим DLL на С++ с таким кодом: #include <malloc.h> #include <windows.h> #ifdef __cplusplus extern "C"{ #endif __declspec(dllexport) LONG WINAPI fnCrashHandler(LPEXCEPTION_POINTERS pExceptionInfo) { if(pExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_STACK_OVERFLOW){ pExceptionInfo->ExceptionRecord->ExceptionCode = 0x1234; } return EXCEPTION_CONTINUE_SEARCH; } #ifdef __cplusplus } #endif Назовем ее, допустим, CrashHandler.dll, и поместим в каталог с программой. Тогда в C# можно обработать переполнение стека таким образом: using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Runtime.InteropServices; namespace ConsoleTest { class Program { [DllImport("kernel32.dll")] public static extern IntPtr AddVectoredExceptionHandler( uint FirstHandler, IntPtr VectoredHandler ); [DllImport("kernel32.dll")] public static extern int SetThreadStackGuarantee( ref uint StackSizeInBytes); [DllImport("kernel32.dll")] public static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]string lpFileName); [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); static void Recursive() { Recursive(); } static void Test() { //увеличим размер зарезервированной области стека (30 KB должно быть достаточно) uint size = 30000; SetThreadStackGuarantee(ref size); try { Recursive(); } catch (SEHException) { Console.WriteLine("SEHException. Code: 0x" + Marshal.GetExceptionCode().ToString("X")); } } static void Main(string[] args) { //добавим обработчик исключений IntPtr h = LoadLibrary("CrashHandler.dll"); IntPtr fnAddress = GetProcAddress(h, "_fnCrashHandler@4"); //декорированное имя функции по правилам stdcall AddVectoredExceptionHandler(1, fnAddress); //запустим поток Thread thread = new Thread(Test); thread.Start(); thread.Join(); Console.WriteLine("Press any key..."); Console.ReadKey(); } } } Примечание. Целевая архитектура неуправляемой DLL и приложения должны совпадать. Для AnyCPU-приложений понадобится иметь несколько неуправляемых DLL под каждую архитектуру и загружать нужную в зависимости от текущей архитектуры приложения.
{ "pile_set_name": "StackExchange" }
Q: How do I describe a polynomial time algorithm for computing a formula? I need some help with describing a polynomial time algorithm for computing: (a^(b^c)) mod p where a,b,and c are ints and p is a prime. My first thought is to do two loops, multiplying (bb).. c times, followed by multiplying (aa) that many times. Then taking that mod p. The terms are confusing me though. Polynomial-time algorithms end after a certain number of iterations, right? Idk how to answer this correctly. Any tips and suggestions are much appreciated. Thanks! A: Exponentiation by squaring is indeed part of the optimal solution. As others already pointed out, you can compute b^c (mod x) in O(log c) for a given x. Second, we would need to take advantage of p being a prime. Enter Fermat's little theorem: a^p=a (mod p) if p is prime. In other words: a^(b^c) = a ^ ((b^c) mod (p-1)) (mod p) Complexity: O(log c) to compute the second part, the result being a number between [0, p-1]; since the second exponentiation is independent, the overall complexity would be O(log c) + O(log (p-1))
{ "pile_set_name": "StackExchange" }
Q: Google App Script: Getting NULL values from getAttributes I want to get all the attributes like(BOLD,UNDERLINE,FOREGROUND_COLOR,FONT_SIZE etc) from google doc. But I am getting NULL values while using getAttributes. Following is my code. var fields = doc.getNamedRanges("myFields"); var lastFontColor; for(var i = 0; i < fields.length; i++) { var rangeElement = fields[i].getRange().getRangeElements()[0]; var obj= rangeElement.getElement().asText().editAsText(); var element= rangeElement.getElement().asText(); var atts = obj.getAttributes(); for (var att in atts) { Logger.log("value of " + att + ":" + atts[att]); } } the ouput I am getting:- FONT_SIZE: null ITALIC: null STRIKETHROUGH: null FOREGROUND_COLOR: #0000ff \ fore colors comes for some of elements. BOLD: null Please let me know if there is any other method to do this. A: Unfortunately, this has been a recurring issue in Google Docs. Some of the style attributes return 'null' unless set explicitly in code. For example, after executing the following document-bound script, I get 'null' values for FONT_SIZE, FONT_FAMILY, and some other attributes while PAGE_MARGIN and PAGE_WIDTH display correct values: var doc = DocumentApp.getActiveDocument(); var body = doc.getBody(); var styles = body.getAttributes(); Logger.log(styles); However, if you explicitly set these attributes in your script, logging the output of body.getAttributes() will return these new values var styles = {}; styles[DocumentApp.Attribute.FONT_FAMILY] = "Times New Roman"; styles[DocumentApp.Attribute.FONT_SIZE] = 16; body.setAttributes(styles);
{ "pile_set_name": "StackExchange" }
Q: Why there are messed up teens in a world where everyone can be designed to be perfect I have a book where in the future a sterility disease spreads across the world making people unable to have children. Then, a company rises to power and using CRISPR are able to make babies again. Later parents are able to design their children completely; eye color, hair color, body type all that. Well also in this world is what are called "Freaks" teens who have had the wrong Gene's activated and so they grow up deformed. (My main character is super fat instead of muscular). Because the sterility disease that the world is still recovering from, it is illegal to kill The Freaks. Then someone, for nefarious purposes, starts killing The Freaks. The company also is the only establishment to work for. so they hold like a lottery see who gets the good jobs out of the "poor". The winners of the lottery are then stuck in a competition to see who can make it and be employed. Those who lose are kicked out and left to die on the streets. My dilemma Why are freaks being made? I had the idea originally that genetics Is a finite science and human error causes mess ups. But a company of this size would only employ the BEST, and would catch on to the ones messing up. I could chalk it up to beginners mistakes but again that seems unlikely... I had another idea that maybe the poorer people are having their kids make from a cheaper virus with CRISPR or a more diluted version of the virus that is more prone to mistake. But then again why would the company sell it in the first place if they now have to pay to kill off the people they made... A: CRISPR isn't perfect Alright, let's get into the science behind CRISPR gene altering and why it can fail horribly. CRISPR is pretty awesome, it's a fairly accurate gene splicing technique which we borrowed from bacteria which lets us cuts out the parts of DNA we don't want. It's pretty accurate, given that we can give it direct parts of the DNA to cut. Unfortunately, that's the only thing it does. It's like when you want to assemble a ransom note so you use a pair of scissors to cut out sections of a newspaper. Except all CRISPR can do it cut out sections. If you want to take those snips, or more accurately what we're trying to do here, take the newspaper and replace the words you've cut out with other words that make sense, you need other mechanisms to do that. And we don't have those kinds of mechanism, we just kind of just release the DNA into the target zone. (Okay, it's a little more directed than that. But not like a lot more complicated. The method is nowhere near as good as CRISPR, which itself isn't perfect.) Basically, CRISPR isn't 100% successful - which makes sense. This isn't a computer program that's being edited bit by bit - you're dealing with biological life which always has a chance of failure, and is subject to weird phenomena like Browning Motion. Even in the future, it's highly unlikely you'd be able to have a 100% success rate and what will most likely happen is that you'll make these 'designer babies' in large batches (maybe like 100 at a time, especially if you're doing multiple gene edits). Also, since we're in the future, we'll have mastered the whole 'artificial womb' thing, so everything which seems viable can just be tried, especially if children are needed. So, recap: CRISPR isn't perfect, a lot of designers babies get made, artificial wombs for all, and the Freaks are a result of that. A: Different offers Making a perfect human is quite difficult, needs lots of quality control, paperwork, etc. and therefore it's expensive. However, you can avail of the cheaper option. But this has none of the quality assurance that the "Platinum package" has, and therefore carries a much greater risk of deformities. This way you don't have to worry about "The BEST" employees screwing up, it's just that the customer didn't pay enough for them to put in the meticulous attention to detail that's required. A: There is more to the sterility disease than just sterility. Where does this disease come from? How does it work? Maybe people in your world still do not really understand (a la Children of Men). The CRISPR thing was a workaround. The sterility disease does not roll over that easy. Sterility is the main thing and if a fetus dies in utero that is the only manifestation. But there are other aspects to this disease, and in some persons this disease can affect more than one system. Bypassing the most lethal part with CRISPR allows babies to be born despite being infected, but secondary and tertiary effects of the disease can affect a subset of persons. It is hard to anticipate all the possible effects of this disease and sometimes it can still affect an individual. Thus the freaks.
{ "pile_set_name": "StackExchange" }
Q: PayPal handling with Simple Payments? I'm using Simple Payments to handle PayPal processing in a module I'm building (See previous question). The first part is fine -- it sends data to PayPal okay, but now that users can pay, I need to write the post-transaction handling code (which will ultimately store that the transaction succeeded in the database.). I'm supposed to use hook_simple_payment_process, but there's very little documentation. In its entirety: /** * Passes a completed payment to the module that created it for processing. * * @param $payment * A payment to be processed. * * @return * TRUE if the payment was successfully processed. */ function hook_simple_payment_process($payment) { } What am I supposed to do with this...? Thanks! A: You need to process the payment. In your case you could mark that the invoice has been paid, maybe in storm or a custom table. $payment should hold all the info about the payment that you need. I guess some of the info depends on your module as well. Anyways when you have processed the payment you should return TRUE which will make the simple payment module mark that payment as being processed. I imagine that there is an interface that will allow you to see if a payment hasn't been processed, which would happen if an error occurred while processing.
{ "pile_set_name": "StackExchange" }
Q: Homsets of group actions related to fixed points MacLane and Moerdijk's Sheaves in Geometry and Logic has a section on Continuous Group Actions (Sec. III.9). On page 152, there is an isomorphism displayed: $$Hom_G(G/U, X) \cong X^U$$ In their set-up, $G$ is a topological group, $U$ is an open subgroup, $X$ is a set (space with discrete topology) with an action of $G$. The Hom-set is that of right G-actions. $X^U$ is the set of $U$-fixed points in $X$. (This result probably holds for ordinary groups instead of topological groups. I can't say.) The commentary following the display says "as usual" by which, they presumably mean it is widely known. But I can't find anything like it in the standard text books. Can somebody figure out what this isomorphism is? Or, tell me where to look to find out? A: $G/U$ has a distinguished element, namely the coset of the identity. A $G$-morphism $G/U \to X$ is completely determined by where it sends this coset, and the possible points in $X$ it can be sent to are precisely points fixed by the action of $U$. (This should make sense on the point-set level, and then one only has to check that the topological details work out.) One way of describing this result is that $G$ is the free $G$-set on a point and $G/U$ is the free $G$-set on a $U$-fixed point.
{ "pile_set_name": "StackExchange" }
Q: clear output in telnet Is there any way to make a telnet app to clear the output client-side (using Java Socket connection + Buffers)? For example, the program queries the connected user for login and password and when they've succeeded logging in, I do cls for Windows or clear for Linux. A: The telnet application is a terminal emulator. In really old times the only way to communicate with a computer was by using a terminal with a pure text based screen and a keyboard. The terminal sent everything you typed to the computer. The computer sent characters back that was printed on the screen. Just like telnet. DEC created a series of terminals called VT52, VT100 etc. They was able to interpret special control sequences so that the computer could give more fancy instructions to the terminal. These control sequences was standardized by ANSI and is now called ANSI escape codes. Terminal emulators that understand the VT100 escape codes are called VT100 terminal emulators. You may look up the ansi escape codes on wikipedia and other places. They all start with the character codes for escape and [ followd by the control characters. The control characters for clearing the screen is "2J". So, what you need to do is sending this string from your server to the telnet client: myOutputStream.print("\u001B[2J"); myOutputStream.flush(); You may send other control characters as well. Try "\u001B[7m" to reverse the screen.
{ "pile_set_name": "StackExchange" }
Q: $f(x)$ non-decreasing then pseudoinverse of $x + f(x)$ is Lipschitz. while studying some proof, I came across the following statement: Let $f$ be a non-decreasing function defined on closed interval $[a, b]$. Let $\alpha = a + f(a)$ and $\beta=b+f(b)$. We can define $g$ (the "pseudoinverse" of $f$) on $[\alpha, \beta]$ as $g(y)=\sup\left\{x\in[a,b]; x+f(x)\leq y\right\}.$ Then g is non-decreasing and Lipschitz. The statement is made without any hints. I've tried hard but I can't prove that $g$ is indeed Lipschitz. Honestly, I haven't come up with anything useful... I'd be really grateful if you could help me. Thanks a lot! P.S. I don't know why but I can't write "Hi" at the beggining of my post, so I'm saying hello here.:) A: If we let $A_y=\left\{x\in[a,b]:x+f(x)\leq y\right\}$ and $B_y=\left\{x\in[a,b]:y<x+f(x)\right\}$ (notice that $g(y)=\sup A_y$), then $A_y$ and $B_y$ are complementary intervals of $[a,b]$, and $B_y$ is to the right of $A_y$, so $\sup A_y=\inf B_y$, that is, \begin{align*} g(y)&=\sup A_y=\inf B_y\tag{$*$}\\ &=\sup\left\{x\in[a,b]:x+f(x)\leq y\right\}=\inf\left\{x\in[a,b]:y<x+f(x)\right\}. \end{align*} Now, suppose $y_1\leq y_2$. Then $A_{y_1}\subseteq A_{y_2}$, thus $g(y_1)\leq g(y_2)$, so $g$ is non-decreasing. Now, let $y_1, y_2$ in $[\alpha,\beta]$. WLOG, we may assume that $y_1\leq y_2$ (otherwise, just reverse the roles) and, since we're analyzing a Lipschitz condition, that $g(y_1)\neq g(y_2)$, that is $g(y_1)<g(y_2)$. Let $\varepsilon>0$. By $(*)$, we can find $x_1\in B_{y_1}$ and $x_2\in A_{y_2}$ with \begin{align*} x_1-g(y_1)<\varepsilon\qquad\text{ and }\qquad g(y_2)-x_2<\varepsilon.\tag{1} \end{align*} Also, since $g(y_1)<g(y_2)$, we can take $x_i$ sufficiently close to $g(y_i)$ so that $x_1<x_2$ and thus $f(x_1)\leq f(x_2)$. Then, since $g$ is non-decreasing and $y_1\leq y_2$, \begin{align*} |g(y_2)-g(y_1)|&=g(y_2)-g(y_1)\overset{(1)}{<}2\varepsilon+x_2-x_1=2\varepsilon+x_2+f(x_2)-f(x_2)-x_1\\ &\leq 2\varepsilon+x_2+f(x_2)-f(x_1)-x_1=2\varepsilon+(x_2+f(x_2))-(x_1+f(x_1))\\ &\leq 2\varepsilon +y_2-y_1=|y_2-y_1|+2\varepsilon, \end{align*} where the last inequality follows from $x_1\in B_{y_1}$ and $x_2\in A_{y_2}$. Letting $\varepsilon\to 0$, we obtain $|g(y_2)-g(y_1)|\leq |y_2-y_1|$ for every $y_1,y_2\in[\alpha,\beta]$, so $g$ is Lipschitz. If we think about smooth, invertible functions, then $\dfrac{df(x)}{dx}\geq 0$, so $\dfrac{d(f(x)+x)}{dx}\geq 1$. Thus, $g$ is the inverse of $f(x)+x$, and it's derivative must satisfy $g'\leq 1$, so that is the reason why we add $x$ to $f(x)$. A very similar argument would work if we changed $f(x)+x$ by some function $F:[a,b]\to\mathbb{R}$ which is non-decreasing and satisfying $|F(x)-F(y)|\geq c\cdot |x-y|\quad \forall x,y$ for some number $c>0$.
{ "pile_set_name": "StackExchange" }
Q: How fast is the interconversion triplet → singlet in organic molecules? When computational studies are performed on transition state geometries, the "thermodynamic" (that is, with no kinetic considerations) energy of the analyzed state is obtained. I was wondering: if a (multistep) reaction begins in a biradical state, the kinetics of the interconversion from triplet to singlet is so slow that the reaction is likely to proceed in a radical fashion, or if a lower transition state exists for the ionic (singlet) counterpart, then it is likely to proceed in a ionic way, because the rate of interconversion is extremely fast? I am sorry if the question is dumb, but all I could find was about transition metals, and I don't know if the same applies. A: It depends on the organic molecule. When spin-orbit coupling facilitates intersystem crossing, it can be fast: 100 femtoseconds for nitronapthalene (viz. Chem. Eur. J. 2018, 24, 5379 – 5387). The Wikipedia article on intersystem crossing cites a timescale for radiative decay (phosphorescence) of triplet to singlet of 10−8 to 10−3 s. A: Spin-orbit coupling will cause the spin flip needed. This is always present but becomes larger the heavier the atom are, iodine, xenon for example present either in solvent (such as iodobenzene) or as part of the molecule. Paramagnetic species also work in the same way, e.g. O2, NO as does an external magnetic field because, as the molecule tumbles, the apparent changing magnetic field the molecule experiences causes T-S crossing. How fast intersystem crossing is will depend largely on the energy gap between singlet and triplet; the larger the gap the slower the process, and as the strength of spin-orbit coupling increases so does the rate constant. This 'energy gap law' has been confirmed by many experiments on excited states and of aromatic molecules and metal complexes and has the form $k=Ae^{-\beta\Delta E}$ where $A$ depends on the strength of the interaction and $\beta$ on the properties of the molecule, this varies as $\ln(\Delta E)$ so is almost constant as $\Delta E$ changes, typical values are 3 to 5.
{ "pile_set_name": "StackExchange" }
Q: What is the easiest way for me to download all my comments across all Stack Exchange sites? The FAQ says: Comments are temporary "Post-It" notes left on a question or answer, meaning that we should not expect them to be around forever. So I would like to backup all my comments on a regular basis: what is the easiest way for me to download all my comments across all Stack Exchange sites? A: "Back them up" by editing them into a question or answer. They'll quickly be mirrored across The Internet. A: You can use the Data Explorer and run this query (thanks bluefeet and ʞunɥdɐpɐɥd for the suggestion). -- Display all comments of a given user DECLARE @UserId int = ##UserId## SELECT Comments.Text FROM Comments WHERE Comments.UserId = @UserId The main issue is that it needs to be run for each Stack Exchange website you want to retrieve your comments from, which can be pretty tedious to do. A: You can download a Stack Exchange GDPR data dump of your own content, and extract your comments from the respective PostComments.json file. It looks like even the comment revision history is included, which is normally inaccessible to users who are not moderators. I wrote an answer to Dump of my own Stack Exchange content which discusses the process in more detail.
{ "pile_set_name": "StackExchange" }
Q: Programmatically sending mule message (formerly: Accessing mule http endpoint from java) Scroll towards the end for the solution to the topic's problem. The original question was asking for a somewhat different thing. As a part of a larger process, I need to fetch and link two related sets of data together. The way that the data is retrieved(dynamics crm, n:n relationships..) forces us retrieve the second set of the data again so that it will have all the necessary information. During a part of larger transformation of this data, I would like to access the http endpoint that is used to fetch the data from the crm, retrieve the second set of data and process it. I can get the endpoint through DefaultEndPointFactory like so: DefaultEndpointFactory def = new DefaultEndpointFactory(); def.getInboundEndpoint("uri").getConnector; But there is no method to actually send the mulemessage. Solved: The problem is that you can not set inbound properties on the MuleMessage, and the flow is depending on some of those to function(path, query params etc). It seems you are able to inbound scoped properties with this: m.setProperty("test", (Object)"test", PropertyScope.INBOUND); Is there a way to make this approach work, or an alternative way to access the flow? I tried using mulecontext to get the flow: muleContext.getRegistry().lookupFlowConstruct("myflow"); But it did not contain anything that looked useful. Solution: As David Dossot suggested in a comment of his answer, I was able to solve this with muleClients request method. muleContext.getClient().request(url, timeout); Then constructing the url as usual with GET parameters etc. A: I'm not 100% sure about what you're trying to achieve but anyway, the correct way of using Mule transports from Java code is to use the MuleClient, which you can access with muleContext.getClient(). For example, the send method allow you to pass a properties map that are automatically added to the inbound scope. Behind the scene, Mule takes care of creating the endpoint needed for the operation. Regarding the flow: what are you trying to do with it? Invoke it?
{ "pile_set_name": "StackExchange" }
Q: Open layers supercluster integration - is it possible to fetch underlying features for each cluster? I am using the open layers 3 with supercluster at the moment, extending the example provided here : https://jsfiddle.net/d5gwvz2y/2/ My question is: How does one fetch all the underlying features behind a cluster if clicked? In open layers cluster implementation you could use cluster forEachFeature, or just getFeatures. Here is a sample of the clusters working using default cluster implementation http://www.wwarn.org/surveyor/NMFI/ when a cluster is clicked, an array of features are returned, which can then be iterated through. A: I had to make some changes to the fiddle to get it running. What I changed: Use latest version of Supercluster (2.3.0) because it has a new function called getLeaves that you need (see 3.). Create a FeatureCollection (to have the advantage of identifying features by properties - e.g. name) and load it with supercluster: var count = 200000; // create featurecollection var featureCollection = { "type": "FeatureCollection", "features": [] }; // add features to featurecollection for (var i = 0; i < count; ++i) { var feature = { "type": "Feature", "properties": { "name": "point_"+i }, "geometry": { "type": "Point", "coordinates": [(Math.random() * (-78.31801021112759 + 74.65681636347132) - 74.65681636347132).toFixed(10), (Math.random() * (37.92771687103033 - 39.366988155008926) + 39.366988155008926).toFixed(10)] } }; featureCollection.features.push(feature); } // create supercluster var index = supercluster({ radius: 100, maxZoom: 16 }); index.load(featureCollection.features); Use getLeaves(clusterId, clusterZoom, limit = 10, offset = 0) in your select event (as described in the supercluster project): selectSingleClick.on('select', function (selectEvent) { // get selected feature var feature = selectEvent.selected[0]; // get parameter to call getLeaves var zoom = map.getView().getZoom(); var clusterId = feature.get("cluster_id"); // get features in cluster var featuresInCluster = index.getLeaves(clusterId, zoom, Infinity, 0); // iterate over features (NO ol.Feature objects!) for(let clusterObj of featuresInCluster){ // do stuff with your feature! } }); Have a look at this working JSFiddle. EDIT: I updated the JSFiddle to fit the question requirements of looping through the resulting child elements... Note that you do not access features in the cluster as ol.Feature objects because the access is realized with supercluster not openlayers! If necessary you could access the features in openlayers by searching for certain properties to identify the feature (e.g. name property in the provided JSFiddle). A: It depends on what supercluster you are using. I assume it's the Mapbox supercluster, which lucky for you has implemented the method getLeaves() on 2017 Jan 18. The method was implemented in particular for the purpose you are looking for ( you were not the first ask :-) ), and it was implemented with flexibility in mind as well (pagination). The pull request also shows an in-detail explanation of the parameters of this function, I just copy them here for reference: index.getLeaves( clusterId, // cluster_id property of the clicked cluster zoom, // zoom of the clicked cluster limit, // how many points to return; 10 by default offset); // how many points to skip for pagination; 0 by default If you want to get all points in a cluster, either set limit to Infinity(yes, that's a valid value!), or use a negative value such as -1. If you try to retrieve large amount of point data (e.g. all 200k points in the example), you probably will have severe performance issues, plus you cannot sensibly display that information at once, either. Given your other example (showing details about a study represented by a point), you could use the additional parameters (limit, offset) to only request data as needed: Click on the cluster to open the popup/information, but only request a chunk of the data (e.g. the first ten studies), with the first being shown right away. Then, only when the user selects one of the other studies, do another request for the next chunk of studies. Not necessarily relevant to this question, but a quick introduction to pagination never hurts for stackexchange readers ;) : It's a great way to boost UX, with better performance allowing for sleeker ways to present data. The relevant&merged pull request (My reputation limits me to only two links, so I had to "break" the link. Just add https:// in front): github.com/mapbox/supercluster/pull/32 And if you want the background story of the pull request as well: github.com/mapbox/mapbox-gl-js/issues/3318
{ "pile_set_name": "StackExchange" }
Q: Is a 3 Hz beat frequency from my neighbor's HVAC a sign of a malfunction? I'm being annoyed by a pulsating hum which comes from my neighbor's HVAC system. I read up a little on the design of HVAC systems and I came to a tentative conclusion that what I'm hearing is a compressor being driven by an AC induction motor. A frequency spectrum shows a spike at 120 Hz and another at 117 Hz; which of course produces a 3 Hz beat. The 117 Hz spike actually moves around between say 117 and 118 Hz. I guess what I'm hearing is called a "slip frequency beat"? I'm in the US, where the mains frequency is 60 Hz; so 120 Hz is the audible hum produced from magnetic fields in motors, transformers, and so on. According to this document (p. 3), the "slip frequency", defined as "per-unit slip times line frequency" is the "actual frequency of current in the rotor conductors". Per-unit slip is proportional to torque and is commonly 0.03 - 0.05. This means 3 Hz could be a typical slip frequency, and I guess 117 Hz could be a slip-frequency sideband of 120 Hz. But there is no 123 Hz spike, and in fact the rest of the spectrum is pretty quiet except for spikes at 59 Hz and 29 Hz. There are harmonics at 234 Hz and 240 Hz, but the harmonic at 352 Hz is stronger than that at 234 Hz. All the harmonics have much less energy than the 117 Hz and 120 Hz fundamentals (say >20 times less). The 29 Hz and 59 Hz spikes don't seem to vary much when the compressor turns on and off, and neither does the 120 Hz spike. Only the 117 Hz spike and its harmonics show an "on-off" square wave in a time-series plot, corresponding to compressor activation at 10-minute intervals. I can't provide decibel-calibrated sound pressure levels (and since I don't have access to the equipment, I can't measure the actual vibration intensity). I would say the sound is not loud enough to be annoying unless you have to live next to it. I have calculated that the sound amplitude in the 117 Hz "spike" is 3 times higher than that in the 120 Hz spike. I don't know if this reveals anything significant. I've read that the speed of an AC motor is 120 Hz / (number of poles), and that the minimum number of poles is 2, so I'm concluding that the motor cannot be turning at just under 120 Hz (7200 RPM) but rather must be going at some slower speed like 60 Hz (3600 RPM). This seems to imply that the 117 Hz vibration is not mechanical vibration from the rotor - but I'm not sure what else it could be. The linked document mentions certain faults producing vibrations at 2 x RPM, but it seems these should be concurrent with vibrations at 1 x RPM. But, as I said, the 59 Hz spike doesn't vary with compressor activation. Here's a time-series plot of various spectral amplitudes, taken over 6 hours at night. The spectral bands shown here are 58-59 Hz, 116-118 Hz, 174-177 Hz, etc. You can see that compressor activation doesn't seem to affect the 59 Hz spike, but there is a clear signal at 117 Hz and 3x117 = 351 Hz. (I also appended a spectrum plot) According to the linked document, some amount of vibration is normal and the surest way to diagnose a developing fault is to take spectral readings over time and see if anything is getting worse. The neighbor's HVAC system is 20 years old, but I only have readings for the past six months, and there seems to be a lot of fluctuation just from weather conditions and diurnal temperature variations influencing the propagation of sound across the property line. Because of this I can't say that there has been an obvious trend upwards in sound amplitude over this time period. A: A 3Hz pulsating hum-- noise that is getting louder and softer at 3Hz. Yes, I agree that would be quite annoying. Since this is a residential unit in the US, both the compressor and the fan are run with single phase asynchronous motors. Almost certainly, they are four pole with an 1800 RPM synchronous speed, running about 1750 RPM or so, depending upon load. The peak you are seeing at 116.8 Hz is consistent with this since that corresponds to the second harmonic of a 1752 RPM rotation rate. The big peak you see at 120Hz is interesting. I wonder if this is due to a loose winding in one of the motors. The compressor is inside the A/C unit, in this case, on top of the house. The fan has to be exposed to the outside. My experience is the fan is what you hear most of the time. From the graphs, it looks like everything is working correctly. The compressor or fan is cycling in and out every 20 minutes which is to be expected. The duty cycle is less than 50% which means it is properly cooling so I guess the coolant levels are adequate. The sounds are probably caused by a combination of loose sheet metal and maybe a loose winding. If it were my unit, I would put my hand here and there to try to guess where the noises are coming from and make sure everything I can get to was bolted down securely. Recognizing that it is not your unit and you don’t have access to it, much less permission to go monkeying around, this won’t do you much good. If it is not running in heat pump mode and it is running at close to 50% duty cycle in February, (when this question was originally posted), it won’t be able to keep the house cool when it starts to get hot and your neighbor will get it fixed, hopefully with a replacement unit. After reading the linked document, I think you should go over there in the dark of night and do a “power trip test” if for no other reason than to get some peace and quiet.
{ "pile_set_name": "StackExchange" }
Q: Android List View , how to give a border and a background color to individual items in android list I have created an android list and I want to give a border color to individual list items by checking a variable value and color the background according to the value. This is my work so far . The layout <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <ListView android:id="@+id/android:myalertlist" android:layout_width="250dp" android:layout_height="wrap_content" android:choiceMode="singleChoice" android:clickable="true" android:background="@drawable/border_ui" android:drawSelectorOnTop="false" > </ListView> </RelativeLayout> My list view <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/txtOne" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textIsSelectable="false" /> <TextView android:id="@+id/txtTwo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textIsSelectable="false" /> </LinearLayout> @drawable/border_ui declaration <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > --> Activity Java Code package test.application; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); HashMap<String, String> hashMapOne = new HashMap<String, String>(); hashMapOne.put("KEYONE", "EXPORT"); hashMapOne.put("KEY_TWO", "A"); HashMap<String, String> hashMapTwo = new HashMap<String, String>(); hashMapTwo.put("KEYONE", "IMPORT"); hashMapTwo.put("KEY_TWO", "B"); HashMap<String, String> hashMapThree = new HashMap<String, String>(); hashMapThree.put("KEYONE", "IMPORT"); hashMapThree.put("KEY_TWO", "C"); HashMap<String, String> hashMapFour = new HashMap<String, String>(); hashMapFour.put("KEYONE", "EXPORT"); hashMapFour.put("KEY_TWO", "C"); ArrayList<HashMap<String, String>> hashList = new ArrayList<HashMap<String, String>>(); hashList.add(hashMapOne); hashList.add(hashMapTwo); hashList.add(hashMapThree); hashList.add(hashMapFour); setContentView(R.layout.activity_main); SimpleAdapter simpleAdapter = new SimpleAdapter(MainActivity.this, hashList, R.layout.list_test, new String[] { "KEYONE", "KEY_TWO" }, new int[] { R.id.txtOne, R.id.txtTwo }); final ListView lv = (ListView) findViewById(R.id.android_myalertlist); lv.setAdapter(simpleAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } I still have a no clue to highlight and color the individual items. If anyone can guide me I would be thankful. A: You should create your own adepter class and a row layout. please look at this exaple. and in the getViev event you should change your background public class MyCustomAdapter extends SimpleAdapter { public MyCustomAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) { super(context, data, resource, from, to); } static class ViewHolder { protected TextView label; protected Linearlayout layout; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = null; LayoutInflater inflator = context.getLayoutInflater(); view = inflator.inflate(R.layout.row_task_layout, null); final ViewHolder viewHolder = new ViewHolder(); viewHolder.label = (TextView) view.findViewById(R.id.label); viewHolder.layout= (LineerLayout) view.findViewById(R.id.layout); view.setTag(viewHolder); ViewHolder holder = (ViewHolder) view.getTag(); holder.label.setText(data.get(position).title); if(statement) { holder.layout.setBackground(background); } return view; } } rowlayout <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#F3F3F3" android:gravity="center" android:padding="5dip" > <LinearLayout android:id="@+id/layout" android:layout_width="fill_parent" android:layout_height="wrap_parent" android:background="@drawable/button_style_main_single" android:paddingLeft="5dip" android:paddingRight="10dip" > <TextView android:id="@+id/label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceSmall" /> </LinearLayout> </LinearLayout>
{ "pile_set_name": "StackExchange" }
Q: Display specific data based on a click on specific item in a list I'm running into a problem, where I want to display information about a specific item when it is clicked? The code I'm working with is JSP/servlet with jQuery. The part I'm having problem is retrieving that information based on click. function data(response) { var records = response.split('||'); var write = ""; for (var i = 0; i < records.length; i++) { var productdata = records[i].split('|'); write += "<div class='listproducts'><input type='image' src='/image_upload/" + productdata[4] + "' width=" + "'100%' name='item' value='" + productdata[4] + "'/><br/>" + productdata[1] + "<br/> $" + productdata[3] + "</div>"; } $("#pcontentcontainer").html(write); $("[name='item']").on('click', function () { $("#pcontentcontainer").html($("[name='item']").val()); }); } Better example: List of products, and you click on a product and it displays all information about that product only. A: Try: $("[name='item']").on('click', function () { $("#pcontentcontainer").html($(this).val()); });
{ "pile_set_name": "StackExchange" }
Q: how to create a function that tokenizes and stems the words My code def tokenize_and_stem(text): tokens = [sent for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(text)] filtered_tokens = [token for token in tokens if re.search('[a-zA-Z]', token)] stems = stemmer.stem(filtered_tokens) words_stemmed = tokenize_and_stem("Today (May 19, 2016) is his only daughter's wedding.") print(words_stemmed) and I'm getting this error AttributeError Traceback (most recent call last) in 13 return stems 14 ---> 15 words_stemmed = tokenize_and_stem("Today (May 19, 2016) is his only daughter's wedding.") 16 print(words_stemmed) in tokenize_and_stem(text) 9 10 # Stem the filtered_tokens ---> 11 stems = stemmer.stem(filtered_tokens) 12 13 return stems /usr/local/lib/python3.6/dist-packages/nltk/stem/snowball.py in stem(self, word) 1415 1416 """ -> 1417 word = word.lower() 1418 1419 if word in self.stopwords or len(word) <= 2: AttributeError: 'list' object has no attribute 'lower' A: YOUR CODE def tokenize_and_stem(text): tokens = [sent for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(text)] filtered_tokens = [token for token in tokens if re.search('[a-zA-Z]', token)] stems = stemmer.stem(filtered_tokens) words_stemmed = tokenize_and_stem("Today (May 19, 2016) is his only daughter's wedding.") print(words_stemmed) The error says """word = word.lower()... if word in self.stopwords or len(word) <= 2: list object has no attribute 'lower'""" The error is not only because of .lower() but because of the length If you try to run it with out changing the filtered_tokens on the 5th line, without changing means using yours. you will get no error but the output will be like this: ["today (may 19, 2016) is his only daughter's wedding.", "today (may 19, 2016) is his only daughter's wedding.", "today (may 19, 2016) is his only daughter's wedding.", "today (may 19, 2016) is his only daughter's wedding.", "today (may 19, 2016) is his only daughter's wedding.", "today (may 19, 2016) is his only daughter's wedding.", "today (may 19, 2016) is his only daughter's wedding.", "today (may 19, 2016) is his only daughter's wedding.", "today (may 19, 2016) is his only daughter's wedding.", "today (may 19, 2016) is his only daughter's wedding.", "today (may 19, 2016) is his only daughter's wedding.", "today (may 19, 2016) is his only daughter's wedding.", "today (may 19, 2016) is his only daughter's wedding.", "today (may 19, 2016) is his only daughter's wedding."] Here is your fixed code. def tokenize_and_stem(text): tokens = [word for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)] filtered_tokens = [token for token in tokens if re.search('[a-zA-Z]', token)] stems = [stemmer.stem(t) for t in filtered_tokens if len(t) > 0] return stems words_stemmed = tokenize_and_stem("Today (May 19, 2016) is his only daughter's wedding.") print(words_stemmed) So, i have only changed line 3 and line 7
{ "pile_set_name": "StackExchange" }
Q: Derived to base implicit pointer type conversion For a generic tree structure, I'm using some code that looks like this (The following code is a MCVE): template <typename T> class Base { protected: Base() {} public: T *ptr; void setRelated() { ptr = this; } }; class Derived : public Base<Derived> {}; int main() { Derived d; d.setRelated(); return 0; } Rationale: The reason for doing this is to save the developer using this class the effort of having to cast everything around from base to derived and back for every call and algorithm used in this class, especially that the base is abstract and can't be instantiated by itself. This code doesn't compile. It says: main.cpp:7: error: invalid conversion from ‘Base<Derived>*’ to ‘Derived*’ [-fpermissive] void setRelated() { ptr = this; } ~~~~^~~~~~ The question: Is there a way to make all conversions from Base<Derived>* to Derived* implicit (assuming we shouldn't overload every method)? A: ... especially that the base is abstract and can't be instantiated by itself. You cannot make Base abstract directly. That needs to derive it from another class (interface) that specifies the pure virtual functions1. Is there a way to make all conversions from Base* to Derived* implicit (assuming we shouldn't overload every method)? No, there isn't. The typical idiom for the CRTP is to use a static_cast: void setRelated() { ptr = static_cast<T*>(this); } 1 Take a look at STTCL where I was using that technique extensively.
{ "pile_set_name": "StackExchange" }
Q: Экранирование в POST запросе У меня есть REST-сервис: @Path(value = "post") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String post(String post) { System.out.println(post); return post; } На вход подается массив символов в таком виде - \u0413\u043e\u0440\u0448 Проблема в том, что он не преобразуется в корректную строку и в таком же виде и остается (а должно быть слово Горш). Есть предположение что они, автоматом падая в String post, тут же экранируются. В итоге ни replace, никакие указания кодировок не помогают. Как преобразовать все это в корректную строку? A: В Apache Commons Text есть удобный метод для этого String s = StringEscapeUtils.unescapeJson(post)
{ "pile_set_name": "StackExchange" }
Q: How to read state property accessors outside the dialog in V4 Bot Framework I'm using bot framework version 4. I would like to access user state properties in the validator method but I didn't find any solution to it. GitHub In the GitHub sample above, we have a validator AgePromptValidatorAsync which validates age. But I would want to access Name which I have stored in State property. How could that be achieved. And is it possible to access state/use GetAsync in a method outside dialog which doesn't contain context. @mdrichardson could you please help me in this.Thank you in advance. A: 1. Ensure that UserProfile.Name is saved before hitting validation. That sample doesn't do this on it's own, so you would: private async Task<DialogTurnResult> NameConfirmStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { stepContext.Values["name"] = (string)stepContext.Result; // ADDED: This code block saves the Name if (!string.IsNullOrEmpty((string)stepContext.Result)) { var userProfile = await _userProfileAccessor.GetAsync(stepContext.Context, () => new UserProfile(), cancellationToken); userProfile.Name = (string)stepContext.Result; await _userProfileAccessor.SetAsync(stepContext.Context, userProfile); } // We can send messages to the user at any point in the WaterfallStep. await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Thanks {stepContext.Result}."), cancellationToken); // WaterfallStep always finishes with the end of the Waterfall or with another dialog; here it is a Prompt Dialog. return await stepContext.PromptAsync(nameof(ConfirmPrompt), new PromptOptions { Prompt = MessageFactory.Text("Would you like to give your age?") }, cancellationToken); } 2. Access the User Profile // CHANGED: Since this accesses the userProfile, the method is no longer static. Also must be async private async Task<bool> AgePromptValidatorAsync(PromptValidatorContext<int> promptContext, CancellationToken cancellationToken) { // ADDED: Here is how you can access the Name // Note: You can use promptContext.Context instead of stepContext.Context since they're both ITurnContext var userProfile = await _userProfileAccessor.GetAsync(promptContext.Context, () => new UserProfile(), cancellationToken); var name = userProfile.Name; // Do whatever you want with the Name // CHANGED: Since this is now async, we don't return Task.FromResult(). We just return the result return promptContext.Recognized.Succeeded && promptContext.Recognized.Value > 0 && promptContext.Recognized.Value < 150; } Accessing the UserProfile Without Context This is kind of possible, but you can't do this easily or out-of-the-box. There are some options that you can use, however (mostly in order from least difficult to most): Pass the context to whatever method/function you need to use it in. Just about every bot method you'd use has some kind of context that you can pass into another method. This is definitely your best option. Create a separate class that you use to store variables in bot memory Either Write Directly to Storage or Implement Custom Storage that you use to track the UserProfile. Note, you'd have to pass around your Storage object, so you may as well just pass around the context, instead. Use the new Adaptive Dialogs, since they do state management differently. I highly recommend against this, though, as these are "experimental", meaning that there's still bugs and we barely use this internally. I'm adding this as an option more for posterity and users that want to play with new stuff.
{ "pile_set_name": "StackExchange" }
Q: Will publishing a package with a git submodule using apm include the submodule? I have a git repository and I want to leave a separate git repo with fonts as a submodule. Can I leave it as a submodule for apm to pick it up correctly with the included submodule or do I need to add the files separately from git repository? Will apm publish the package with with the repository on github added in to the main repository? A: As far as I know, this is not possible. See this issue for reference and keep in mind that apm is a fork of npm. In my opinion, the Node-way is to install a repository as a standard dependency (see npm documentation). However, this requires the extra step of copying the files to the desired target location. This can be done in the postinstall script.
{ "pile_set_name": "StackExchange" }
Q: If i am sending two request on single button click using Volley Library Then result is not getting as per expectation If i am requesting two different request(two different type Endpoint) on single button click using volley Library not getting as per expected result . If i am calling two request on two different button click then result is proper . I think volley is unable to handle multiple requests. How can i get solve this situation ? A: you can do this as a send first request if this is success then send second request under first request response first request... respose{ second request } for more please follow this link Need to send multiple Volley Requests - in a sequence
{ "pile_set_name": "StackExchange" }
Q: What's the difference setting background image in layout xml and setting it from the code? What's the difference between setting background image in layout xml and setting it from the code? Does setting image from code use more memory? For example: In XML: <ImageView android:id="@+id/background" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/background_img" /> From the code: ((ImageView)findViewById(R.id.background)).setBackgroundResource(R.drawable.background_img); Thanks. A: Off the top of my head, I can only think of it in terms of optimization. Setting in the layout means that the background is already there during the setContentView, you don't need the extra steps to set it in your code. If you don't have to customize it, it would be faster to leave in the XML.
{ "pile_set_name": "StackExchange" }
Q: Assign Multiple EC2 instances to one Elastic IP I have 2 EC2 instances and they send requests to an external server. That server requires a static IP, so I used Elastic IP to connect one of the EC2s to it. The problem is that I'm only allowed to have one static IP associated with my account on that server. Is there a way to put the 2 EC2s behind the same EIP using network interface or ELB? I tried to read about it, but AWS documentation is a bit overwhelming. A: The simplest method is to: Create a NAT Gateway in a public subnet Put your EC2 instances in a private subnet Configure the routing for the private subnet to send internet-bound traffic to the NAT Gateway This way, all traffic will appear to be coming from the NAT Gateway, which can have a single Elastic IP address. An alternate method would be to use one of the instances (Instance-A) as a NAT Instance, which uses a masquerade setting in iptables to forward traffic. Then, configure the second instance (Instance-B) to send internet-bound traffic to Instance-A. Instance-A will forward the traffic to the external server and pass the response back to Instance-B. This is the normal script to configure an EC2 instance as a NAT Instance: #!/bin/sh echo 1 > /proc/sys/net/ipv4/ip_forward echo 0 > /proc/sys/net/ipv4/conf/eth0/send_redirects /sbin/iptables -t nat -A POSTROUTING -o eth0 -s 0.0.0.0/0 -j MASQUERADE /sbin/iptables-save > /etc/sysconfig/iptables mkdir -p /etc/sysctl.d/ cat <<EOF > /etc/sysctl.d/nat.conf net.ipv4.ip_forward = 1 net.ipv4.conf.eth0.send_redirects = 0 EOF
{ "pile_set_name": "StackExchange" }