text
stringlengths
64
81.1k
meta
dict
Q: Cleaning fridge and freezer - do you need to turn it off? I'm doing a bit of a clean of my fridge and freezer (dual unit) and I have heard you should turn your fridge/freezer off when cleaning - since I am not doing a complete/deep clean of it and I don't have many items in there I was wanting to keep it running. Is there any particular reason you should turn it off when cleaning? ...or is that just a "save power" kind of thing? ...or does it let off particles of gas or something when running that you shouldn't be breathing in that long? A: There's no reason to turn it off. You'd save a few cents in power by doing so, but it's not worth the hassle for a short period. It's not going to cause damage.
{ "pile_set_name": "StackExchange" }
Q: std::bind and std::function term does not evalue as taking 0 arguments? I'm working on generic class that will be used to run functions of different prototype for performance testing of algorithms. I stuck because std::function can't execute what it was bound with, here is sample code, with comment where the error happens: #include <utility> #include <functional> template<typename ReturnType> class Performance { public: template<typename... Args> using Algorithm = std::function<ReturnType(Args...)>; template<typename... Params> void run(const Algorithm<Params...>& ref, const Algorithm<Params...>& target) { // ERROR: term does not evaluate as taking 0 args ref(); target(); } }; void bar1(int, int) { // algorithm 1 } void bar2(int, int) { // algorithm 2 } int main() { using test = Performance<void>; using Algorithm = test::Algorithm<int, int>; int x = 0; int y = 1; Algorithm ref = std::bind(bar1, std::ref(x), std::ref(y)); Algorithm target = std::bind(bar2, std::ref(x), std::ref(y)); test foobar; foobar.run(ref, target); } A: The problem is, the std::function type, i.e. Algorithm is declared to take two parameters (with type int); when calling on them two arguments are required. After std::bind applied, the returned functors take no parameters; arguments (std::ref(x) and std::ref(y)) have been bound. Algorithm should be declared as using Algorithm = test::Algorithm<>; LIVE
{ "pile_set_name": "StackExchange" }
Q: Prove that $b^2-4ac$ can not be a perfect square Given $a$,$b$,$c$ are odd integers Prove that $b^2-4ac$ can not be a perfect square. My try:Let $a=2k_1+1,b=2n+1,c=2k_2+1;n,k_1,k_2 \in I$ $b^2-4ac=(2n+1)^2-4(2k_1+1)(2k_2+1)$ $\implies b^2-4ac=4n^2+4n+1-16k_1k_2-8k_2-8k_1-4 $ A: Assume $b^2-4ac=d^2$. Then $d$ is odd and $(b-d)(b+d)=4ac$. Consequently, there exists odd $u,v$ such that $b-d=2u$ and $b+d=2v$. This leads to the contradiction $b=u+v$ since $u+v$ is even.
{ "pile_set_name": "StackExchange" }
Q: What are some of the "true" swing states in the U.S 2016 election cycle? I'm talking about ones where the margin is less then 7 points, or has swinged by more then 5 in polls within the 2012 results and polls currently in that state or is trending way too much to one party and can flip from GOP to dem or vice-versa. A: It differs, there's no true swing states, but depends on predictions. In different elections, the states can vary. Swing state is defined as: a US state where the two major political parties have similar levels of support among voters, viewed as important in determining the overall result of a presidential election. So, in this unconventional election, the states that have exceptionally close polling numbers are Arizona, Iowa and Ohio where both candidates have changed leads throughout the election. Though Hillary Clinton has hinted that she would compete in Texas, I do doubt that it's a swing state, it's still considered Republican-leaning and Trump is still a favourite to win. Traditionally, swing states will include Colorado, North Carolina, Pennsylvania, Florida, New Hampshire and Nevada. However, the polling in these states doesn't seem to be close so far and there's a clear lead in each of these state. You can check out a feature by The New York Times regarding this.
{ "pile_set_name": "StackExchange" }
Q: spring quartz schedular properties autocomit exception I am using maven-java-spring with quartz schedular and spring-jdbc template. <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>1.7.3</version> </dependency> We have process which makes large amount of inserts using quartz scheduler job. When i execute job after inserting x number of records it throws exception as follows exception caught: org.springframework.transaction.TransactionSystemException: Could not commit JDBC transaction; nested exception is java.sql.SQLException: commit() should not be called while in auto-commit mode. at org.springframework.jdbc.datasource.DataSourceTransactionManager.doCommit(DataSourceTransactionManager.java:270) at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754) at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723) at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:147) Following is my sechdular code <!-- Spring jobs --> <bean id="wireJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="search"/> <property name="targetMethod" value="executeWireSearch"/> </bean> <bean id="nonWireJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="search"/> <property name="targetMethod" value="executeNonWireSearch"/> </bean> <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="wireQuartzTrigger"/> <ref bean="nonWireQuartzTrigger"/> </list> </property> </bean> does it something to do with quartz properties related to autocomit ?? A: Give a look to the quartz FAQ: http://quartz-scheduler.org/documentation/faq#FAQ-springCommit BTW, you should upgrade if possible because 1.7 is quite old and not supported anymore HIH
{ "pile_set_name": "StackExchange" }
Q: Following the tensorflow document (version r0.11), I got a double print instead of single print Following the tensorflow document (version r0.11, Python 3.4.3), I got a wrong print with twice 1 instead of once 1. The code is following here: import tensorflow as tf state = tf.Variable(0, name="counter") one = tf.constant(1) new_value = tf.add(state, one) update = tf.assign(state, new_value) init_op = tf.initialize_all_variables() with tf.Session() as sess: sess.run(init_op) print(sess.run(state)) for _ in range(3): sess.run(update) print(sess.run(state)) then the print result is like this 0 1 1 2 2 3 3 A: sess.run(update) update the variable and return its value. So when you run this code in a python shell, it print the value of state (see here why). So if you want to see only one time each new value of state, remove print(sess.run(state)) or write your code in a python script.
{ "pile_set_name": "StackExchange" }
Q: ios view transitions animations, page curl i'm new to the ios sdk and i'm developing my first app. i need to implement a curl transition between multiple views; giving the user the impression they are reading a book. the documentation only talks about doing it between two views in a single view controller. like i said i need to implement this with a stack of several views. do i need to use more than 1 view controller? if so how? or do i have to use 1 view controller but use say 10 views in a stack? again how would i go about doing this. would greatly appreciate your help. A: Ideally, you would use only two views for this: one for the view being animated (to an offscreen position), and one for the view underneath. To handle multiple flips, you would animate the top view to its offscreen position, then fill it with the data for the page underneath the current page and then insert it underneath the current page. For the subsequent flip, you would animate the current off the screen, etc. You could alternatively use a number of views that matches the total number of pages you want to display. This might make your coding simpler, but it would eat up a lot more memory.
{ "pile_set_name": "StackExchange" }
Q: Performance of Java enums I was thinking about using enum type to manage i18n in a Java game I'm developing but I was curious about performance issues that can occur when working with enums that have lots of elements (thousands I think). Actually I'm trying something like: public enum Text { STRING1, STRING2, STRING3; public String text() { return text; } public String setText() { this.text = text; } } Then to load them I can just fill the fields: static { Text.STRING1.setText("My localized string1"); Text.STRING2.setText("My localized string2"); Text.STRING3.setText("My localized string3"); } Of course when I'll have to manage many languages I'll load them from a file. What I'm asking is is an obect allocated (in addition to the string) for every element? (I guess yes, since enums are implemented with objects) how is the right element retrieved from the enum? is it static at compile time? (I mean when somewhere I use Text.STRING1.text()). So it should be constant complexity or maybe they are just replaced during the compiling phase.. in general, is it a good approach or should I look forward something else? Thanks A: Found and adapted a nice mix of enums and ResourceBundle: public enum Text { YELL, SWEAR, BEG, GREET /* and more */ ; /** Resources for the default locale */ private static final ResourceBundle res = ResourceBundle.getBundle("com.example.Messages"); /** @return the locale-dependent message */ public String toString() { return res.getString(name() + ".string"); } } # File com/example/Messages.properties # default language (english) resources YELL.string=HEY! SWEAR.string=§$%& BEG.string=Pleeeeeease! GREET.string=Hello player! # File com/example/Messages_de.properties # german language resources YELL.string=HEY! SWEAR.string=%&$§ BEG.string=Biiiiiitte! GREET.string=Hallo Spieler! A: You're probably better off using the java.util.ResourceBundle class. It is designed to solve exactly this problem. To answer your questions: Yes, there is exactly one instance of each enum value. Yes, constant complexity for looking up an Enum value. Not really. Changing the content/behaviour of the enum kinda defeats the purpose of having enums in the first place. They're supposed to represent fixed-range constants with type safety. You can do this kind of thing but that's not what they were designed for. A: I hate to hijack to topic, but relying on enums for i18n is going to eventually paint you into a corner. Java has proper i18n support, even going so far as to have a tutorial for it.
{ "pile_set_name": "StackExchange" }
Q: dataframe.idxmax() - first N occurences Pandas dataframe.idxmax() function returns the index of first occurrence of maximum over requested axis. Is there a way to instead return the index of top N number of occurrences? The line in question: df2 = df.loc[df.groupby(['columnA', 'columnB'], sort=False)['columnC'].idxmax()] I want this to return the top N number of indices based on the Nth largest values in df['columnC']. So if df['columnC'] contains values 5, 10, 20, 50, 75, 90, 100 and N=3, I want the indices of rows with values of 75, 90, and 100. Edit: DataFrame looks something like this: raw_data = {'cities': ['LA', 'LA', 'LA', 'Chicago', 'Chicago', 'Chicago', 'Chicago', 'Boston', 'Boston', 'Boston', 'Boston', 'Boston'], 'location': ['pub', 'dive', 'club', 'disco', 'cinema', 'cafe', 'diner', 'bowling','supermarket', 'pizza', 'icecream', 'music'], 'distance': ['0', '50', '100', '5', '75', '300', '20', '40', '70', '400', '2000', '2'], 'score': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]} df = pd.DataFrame(raw_data, columns = ['cities', 'location', 'distance', 'score']) df A: You want to use nlargest. Here is an exemple In [1]: import pandas as pd df = pd.DataFrame({'t' : [0, 8,32, 56, 96, 128], 'T2' : [333, 500, 333, 500, 333, 460], }) df['t'].nlargest(3).index.tolist() Out [1]: [5, 4, 3] So this is what you are looking for : N = 3 df2 = df.loc[df.groupby(['columnA', 'columnB'], sort=False)['columnC'].nlargest(N).index.tolist()] A: Solution N = 2 df['distance'] = pd.to_numeric(df['distance']) df['bin100'] = pd.cut(df['distance'], np.arange(0, 2001, 100), include_lowest=True, labels=False) test = df.groupby(['cities', 'bin100'], sort=False)['score'].nlargest(N).index.tolist() test = np.array(test) test = test[:,2] df = df.iloc[test] df All in one line: df.iloc[np.array(df.groupby(['cities', 'bin100'], sort=False)['score'].nlargest(N).index.tolist())[:,2]]
{ "pile_set_name": "StackExchange" }
Q: Responsibility when processing results of ethically questionable survey I am a software engineer in an USA local government setting. Recently they sent out a survey asking about how people where feeling about an upcoming reorganization/job reclassification. Now, an important note, nothing says that the survey is anonymous and It never explicitly asks for your name. It's using system data to figure out who submitted the survey but nothing says that it isn't either. Now,I have been given the task of not only moving all the survey results to a database, but also ranking the comments on how positive/negative they are. Now, I know from the specs that upper management will be able to see who wrote what comments. Which I consider to be alarming because I was trained in TCPS 2 core(Human experimentation ethics) during college, and I know this would be wrong to allow such identifying information at least for TCPS.They have already indicated they want to use the information for good, but they could also use it for negative reasons. No one is saying that upper management will retaliate. But several comments I have read fear retribution, and say they don't trust upper management. And there is the issue that I was told this is a secret project and I shouldn't tell anyone about it. Bottom line: What is my responsibility? Is this ethical? Should I bring this to anyone's attention? I want to help protect my coworkers, even though I am leaving the company Post: Thank you all for the wonderful answers, I have since brought up the idea of blocking, obfuscating or otherwise hiding the names of people id'ed in the survey, my request has been ignored and I have been asked to ID their union as well..... A: What is my responsibility? Do your job. Move the results into a database as instructed, do not put your job at risk. Your situation is uncomfortable no doubt, but not beyond reason. Is this ethical? I have to admit, this situation sure seems like its dancing on the ethics line a bit. Your only real recourse would be to anonymously blow the whistle on the survey, but I still think you would be at risk potentially for retaliation. Should I bring this to anyone's attention? Another tricky question...whose attention could you bring it to without putting yourself at risk? If you have a safe path, take it. If you do not, be careful not to put yourself in the line of fire. A: If it didn't say it was anonymous, you should assume it wasn't. IANAL, but I think a survey is only anonymous if it actually says so. You can't assume anonymity just because you think it should be. Collating the results of a non-anonymous survey is not an ethical problem. I'm not sure how secret the project can really be, since these people filled out a survey and should expect that someone is actually going to look at the results. It would probably be better if the management made their rules and expectations clear, but they haven't broken any laws based on the info provided. If they actually take improper action against an employee because of the survey responses, then that would be unethical and/or illegal, but until that happens, they haven't crossed the line.
{ "pile_set_name": "StackExchange" }
Q: Docker and Kubernetes integrations compatibility matrix? Two example integrations of Docker and Kubernetes are OpenShift and Rancher Labs AFAIK. Sadly but in fact we have not completely escaped us from the dependency hell. Question: is there an established source of information which distributions here package which versions (like Ubutu/Debian version chronicles on Wikipedia)? Background. Not-so-obvious facts for newbies (judged by my learnings so far) are (defining acceptable technical usability to a level that you do no need hours to debug even 101 tutorials): Kubernetes is very dynamic project and it is not so easy to deploy it as-is (but seem to get better with each version, also thanks to kubeadm I would say) Kubernetes does not support any Docker versions coming after the community fork to moby and Docker CE. See also: https://stackoverflow.com/questions/44657320/which-docker-versions-will-k8s-1-7-support A: Every Kubernetes release has an External Dependencies section in the respective Changelog. E.g.: CHANGELOG-1.14: The list of validated docker versions has changed. 1.11.1 and 1.12.1 have been removed. The current list is 1.13.1, 17.03, 17.06, 17.09, 18.06, 18.09. CHANGELOG-1.13: The list of validated docker versions remain unchanged at 1.11.1, 1.12.1, 1.13.1, 17.03, 17.06, 17.09, 18.06 since Kubernetes 1.12. CHANGELOG-1.12: The list of validated docker versions was updated to 1.11.1, 1.12.1, 1.13.1, 17.03, 17.06, 17.09, 18.06. and so on...
{ "pile_set_name": "StackExchange" }
Q: Google Maps Issue Cannot call method 'apply' of undefined? I have searched all over google for a solution however this seems a new one? I am trying to implement google maps API on a site however I keep getting the following error: Uncaught TypeError: Cannot call method 'apply' of undefined My JS is as follows: var map; function initialize(location) { var mapDiv = document.getElementById('map-canvas'); var latLng; if (location == 0) { latLng = new google.maps.LatLng(52.066356, 1.102388); } else if (location == 1) { latLng = new google.maps.LatLng(52.672492, 1.232196); } else if (location == 2) { latLng = new google.maps.LatLng(52.207607, 0.123017); } map = new google.maps.Map(mapDiv, { center: latLng, zoom: 14, mapTypeId: google.maps.MapTypeId.ROADMAP }); google.maps.event.addDomListener(map, 'tilesloaded', addMarker(location)); } function addMarker(location) { var latLng; if (location == 0) { latLng = new google.maps.LatLng(52.066703, 1.113573); } else if (location == 1) { latLng = new google.maps.LatLng(52.672492, 1.232196); } else if (location == 2) { latLng = new google.maps.LatLng(52.207607, 0.123017); } var marker = new google.maps.Marker({ position: latLng, map: map }); } $(document).ready(function () { initialize(0); }); A: In this line google.maps.event.addDomListener(map, 'tilesloaded', addMarker(location)); You're calling the function addMarker instead of passing it as a function reference. Therefore, addMarker is getting executed before map is defined. Try changing that line to: google.maps.event.addDomListener(map, 'tilesloaded', function() {addMarker(location)}); A: The problem is you're invoking the function addMarker which you should be supplying a callback. Change your call to the following google.maps.event.addDomListener(map, 'tilesloaded', function() { addMarker(location) }); Right now you're instead directly invoking addMarker which returns no value. This means you're effectively passing undefined to the API and the google library is hitting the error attempting to invoke your callback
{ "pile_set_name": "StackExchange" }
Q: How to get two results as single table I have two result sets as I want both results as a single table with two columns(education,schools). Can I use any temp tables or is there any easy way?? Thank you edited A: If you have a relation to use then you can just join the tables as normal: WITH Eduction AS ( SELECT item, ID = ROW_NUMBER() OVER(ORDER BY Item) FROM fnSplit((SELECT DegreeType FROM HR_EmpEducation WHERE EmpID = 9), '|') ), Schools AS ( SELECT item, ID = ROW_NUMBER() OVER(ORDER BY Item) FROM fnSplit((SELECT School_Inst FROM HR_EmpEducation WHERE EmpID = 9), '|') ) SELECT Eduration = ISNULL(e.Item, ''), Schools = ISNULL(s.Item, '') FROM Education e FULL JOIN Schools s ON e.ID = s.ID; I have used a FULL JOIN to account for one split function having more results than the other.
{ "pile_set_name": "StackExchange" }
Q: Let $A_i= \left \{...,-2,-1,0,1,...,i \right\}$. Find $\bigcup_{i=1}^{n} A_i$ and $\bigcap_{i=1}^{n} A_i$ I have the following assignment: Let $A_i= \left \{...,-2,-1,0,1,...,i \right\}$. Find a) $\displaystyle \bigcup_{i=1}^{n} A_i$ b) $\displaystyle \bigcap_{i=1}^{n} A_i$ I think the first one is: $\displaystyle \bigcup_{i=1}^{n} \left \{...,-2,-1,0,1,...,i \right\} = \left \{...,-2,-1,0,1,2...,n \right\}$ But what about the second one? A: HINT: $A_i\subseteq A_j$ whenever $i\le j$. You can use this to answer both questions. (Your answer to the first question is correct.)
{ "pile_set_name": "StackExchange" }
Q: Creating a plist file programmatically this question is regarding xcode objective c and iphone development: So I want to store an array in a new plist file and I know how to retrieve the file path and write the data into the file (at least I think I do) and all that jazz once the plist is created, but how do I actually create the plist file the first time the app is run or the first time I go to enter data into it? I want it to live in the documents folder of my app. I'm assuming this is pretty simple I just can't seem to find documentation on it. I ended up using NSKeyedValue there was a great tutorial here: http://vimeo.com/1454094 I know technically this is not the answer to the question but it did solve my problem. A: To save: NSMutableArray *array = [[NSMutableArray alloc] init]; [array writeToFile:[@"/path/to/file.plist"] atomically: TRUE]; To retrieve: NSMutableArray *array = [[NSMutableArray arrayWithContentsOfFile:[@"/path/to/file.plist"]] retain];
{ "pile_set_name": "StackExchange" }
Q: SQL large CASE vs. JOIN efficiency on a large SELECT output I work with a fairly unoptomized database- performance varies daily so I would like to make my output as quick as possible. I was hoping to figure out the most efficient way to append values to my output. With most sets, I have to export fairly wide final dimensions (upwards of 20-60 columns, 60-500k rows), so processing has to be accounted for as well. Benchmarking is a little tricky on this, because it seems to vary with server load. So, join on a large table, vs appending with a long CASE argument- both seem ungainly, but whats the best course of action? Example: --Entity Table output would result 250k rows, 50 col --Entity Types Table has 1k rows, 2 col (key and description) select e.*, et.description from Entities e inner join entity_types et ON e.entity_type_key = et.entity_type_key; ~or~ select e.* case when e.entity_type_key = 1 then 'Description 1 from entity_types' when e.entity_type_key = 2 then 'Description 2 from entity_types' (repeat about 1k times).. from Entities e A: In this particular case you will not see a big difference. Table will be cached (probably) and lookup will be very fast (and we can assume that table is very small). Case statement requires slightly more time for parsing (some nanoseconds, I don't know) and slightly more network traffic but... again, I don't think you should think about it at all. You can even map it on the application layer. Or just use join because it is more configurable and more readable.
{ "pile_set_name": "StackExchange" }
Q: How to prevent multiple form submissions in PHP I'm trying stop multiple submit buttons.I'm new to php and javascript.I did try lot of different options of stack overflow answers.I did check session token but it is not working for me because i'm submitting the form from JavaScript.You can see the code to disabled button . When i click the button it is disabled and form submited but it is not reaching the btn-paid code of php. Please help. php code1: <?php include('sessionstart.php'); include('session.php'); include('processtransaction.php'); ?> <script src="js/mytransaction.js"></script> php code1 will call the javascript and javascript has the form submit. If the form is submitted then it disable/(session token process) the button paid and it should call the code of btn-paid. javascript code mytransaction: $(document).ready(function() { var table = $('#myTransactionitems').dataTable(); //Initialize the datatable var user = $(this).attr('id'); if(user != '') { $.ajax({ url: 'transactions', dataType: 'json', success: function(s){ console.log(s); table.fnClearTable(); for(var i = 0; i < s.length; i++) { var disp1 = ''; if (s[i][4] != 'Reserved') { disp1 = 'display:none;' } table.fnAddData([ "<form method='post' action='reservationdetails'><input name = 'transactionid' type='hidden'\ value='"+s[i][0]+"'></input><input type='submit' id = 'btn-bank' name='btn-bank' value = '"+s[i][0]+"' class='btn btn-link'>\ </input></form>", s[i][1], s[i][2], s[i][3], s[i][4], s[i][5], "<form method='post'><input name = 'transactionid' type='hidden'\ value='"+s[i][0]+"'><input name = 'donationid' type='hidden'\ value='"+s[i][2]+"'><input name = 'splitamount' type='hidden'\ value='"+s[i][3]+"'></input></input><input type='submit' id = 'btn-paid' name='btn-paid' value = 'Paid' onclick='this.disabled=true;this.form.submit();' style='" + disp1 +"' class='btn btn-sm btn-success pull-left '>\ </input></form><form method='post'><input name = 'transactionid' type='hidden'\ value='"+s[i][0]+"'><input name = 'donationid' type='hidden' \ value='"+s[i][2]+"'><input name = 'splitamount' type='hidden'\ value='"+s[i][3]+"'></input><input type='submit' id = 'btn-cancel' name='btn-cancel' value = 'Cancel' onclick='this.disabled=true;this.form.submit();' style='" + disp1 +"' class='btn btn-sm btn-danger pull-right'>\ </input></form>" ]); } // End For }, error: function(e){ console.log(e.responseText); } }); } }); php code2 processtransaction: <?php if (isset($_POST['btn-paid'])) { require_once("dbcontroller.php"); $db_handle = new DBController(); $conn = $db_handle->connectDB(); $query = "update MYTRANSACTION set STATUS =? where DONATION_ID=? AND ID=?"; $stmt = $conn->prepare($query); $stmt->bind_param("sii",$status,$donation_id, $transaction_id); $stmt->execute(); $stmt->close(); $db_handle->closeDB($conn); } ?> A: If you want to prevent the user from clicking twice before page ends loading (causing 2 posts), it would better to use javascript. As you are already using jQuery, you can do the following: $("input[type='submit']").click(function(e) { e.preventDefault(); // Prevent the page from submitting on click. $(this).attr('disabled', true); // Disable this input. $(this).parent("form").submit(); // Submit the form it is in. }); Edit: To cater for someone immediately submitting before page loads completely (ie before JS loads), you can make the following changes. In your HTML form, add disabled to your submit button: <input type="submit" value="Submit" disabled /> And change your JS to the following: $("input[type='submit']").attr('disabled', false); // Enable this input. $("input[type='submit']").click(function(e) { e.preventDefault(); // Prevent the page from submitting on click. $(this).attr('disabled', true); // Disable this input. $(this).parent("form").submit(); // Submit the form it is in. }); What this does is makes the submit button disabled until JS has loaded. Once JS loads, it will enable the submit button and then remaining things will work as before.
{ "pile_set_name": "StackExchange" }
Q: Signal handler inside a class I am trying to write a class to handle signals using the signal python module. The reason for having a class is to avoid the use of globals. This is the code I came up with, but unfortunately it is not working: import signal import constants class SignalHandler (object): def __init__(self): self.counter = 0 self.break = False self.vmeHandlerInstalled = False def setVmeHandler(self): self.vmeBufferFile = open('/dev/vme_shared_memory0', 'rb') self.vmeHandlerInstalled = True signal.signal(signal.SIGUSR1, self.traceHandler) signal.siginterrupt(signal.SIGUSR1, False) #...some other stuff... def setBreakHandler(self): signal.signal(signal.SIGINT, self.newBreakHandler) signal.siginterrupt(signal.SIGINT, False) def newBreakHandler(self, signum, frame): self.removeVMEHandler() self.break = True def traceHandler(self, signum, frame): self.counter += constants.Count def removeVMEHandler(self): if not self.vmeHandlerInstalled: return if self.vmeBufferFile is None: return signal.signal(signal.SIGUSR1, signal.SIG_DFL) self.vmeHandlerInstalled = False On the main program I use this class in the following way: def run(): sigHandler = SignalHandler() sigHandler.setBreakHandler() sigHandler.setVmeHandler() while not sigHandler.break: #....do some stuff if sigHandler.counter >= constants.Count: #...do some stuff This solution is not working, as it appears that the handler for the signal.SIGUSR1 installed in the setVmeHandler method never gets called. So my question is: is it possible to handle signal inside a class or shall I use globals? A: To answer your question, I created the following simple code: import signal import time class ABC(object): def setup(self): signal.signal(signal.SIGUSR1, self.catch) signal.siginterrupt(signal.SIGUSR1, False) def catch(self, signum, frame): print("xxxx", self, signum, frame) abc = ABC() abc.setup() time.sleep(20) If I run it: python ./test.py Then in another window send a USR1 signal: kill -USR1 4357 The process prints the expected message: ('xxxx', <__main__.ABC object at 0x7fada09c6190>, 10, <frame object at 0x7fada0aaf050>) So I think the answer is Yes, it possible to handle signal inside a class. As for why you code doesn't work, sorry, I have no idea.
{ "pile_set_name": "StackExchange" }
Q: Why does pandas.DataFrame.mean() work but pandas.DataFrame.std() does not over same data I'm trying to figure out why the pandas.DataFrame.mean() function works over a ndarray of ndarrays, but the pandas.DataFrame.std() does not over the same data. The following is a minimum example. x = np.array([1,2,3]) y = np.array([4,5,6]) df = pd.DataFrame({"numpy": [x,y]}) df["numpy"].mean() #works as expected Out[231]: array([ 2.5, 3.5, 4.5]) df["numpy"].std() #does not work as expected Out[231]: TypeError: setting an array element with a sequence. However, if I do it through df["numpy"].values.mean() #works as expected Out[231]: array([ 2.5, 3.5, 4.5]) df["numpy"].values.std() #works as expected Out[233]: array([ 1.5, 1.5, 1.5]) Debug information: df["numpy"].dtype Out[235]: dtype('O') df["numpy"][0].dtype Out[236]: dtype('int32') df["numpy"].describe() Out[237]: count 2 unique 2 top [1, 2, 3] freq 1 Name: numpy, dtype: object df["numpy"] Out[238]: 0 [1, 2, 3] 1 [4, 5, 6] Name: numpy, dtype: object A: Assuming you have the following orginal DF (containing numpy arrays of the same shape in cells): In [320]: df Out[320]: file numpy 0 x [1, 2, 3] 1 y [4, 5, 6] Convert it to the following format: In [321]: d = pd.DataFrame(df['numpy'].values.tolist(), index=df['file']) In [322]: d Out[322]: 0 1 2 file x 1 2 3 y 4 5 6 Now you are free to use all the Pandas/Numpy/Scipy power: In [323]: d.sum(axis=1) Out[323]: file x 6 y 15 dtype: int64 In [324]: d.sum(axis=0) Out[324]: 0 5 1 7 2 9 dtype: int64 In [325]: d.mean(axis=0) Out[325]: 0 2.5 1 3.5 2 4.5 dtype: float64 In [327]: d.std(axis=0) Out[327]: 0 2.12132 1 2.12132 2 2.12132 dtype: float64
{ "pile_set_name": "StackExchange" }
Q: Access/Change JEditorPane's html loaded elements + HTMLEditorKit problem with Unicode (Java) that's going to be a long question so bear with me :) My Application I'm developing a Java (with JFrame GUI) desktop application that does the following: Scan (.txt) files. Parses some numbers from these files, performs some calculations on them and finally stores the results in String variables. Outputs these numbers in a special (table) format. (Note: the format includes some Unicode (Arabic) Characters.) Problem The first two parts went smoothly. However when I came to the 3th part (the formatted output) I didn't know how to display this special format so, What is the best way to display a special formatted output (table) in Java? Note: Formatter is not going to help because it has no proper support for tables. Solution One: I did my research and found that I could use JEditorPane, since it can display special formats such as "html". So I decided to create an "html" page with the needed (table) format and then display this page on [JEditorPane][4]. I did that and it went smoothly until I wanted to change some html elements' values to the parsed numbers from those (.txt) files. How can I have an access to an html element(e.g. <td></td>) and change its value? Note that the (.html) is loaded inside JEditorPane using setPage(url). The Unicode characters are displayed properly but I couldn't change some of the elements values (e.g. I want to change the value of <td> 000,000,000 </td> to <td> MainController.getCurrentTotalPayment() </td> Solution Two: I've found a workaround to this which involves using HTMLDocument and HTMLEditorKit, That way I can create the (.html) using HTMLEditorKit from scratch and display it on the JEditorPane using kit.insertHTML. I have successfully added the content using the above method and I also was able to add the parsed numbers from (.txt) files because I have them stored in my (MainController) class. Unfortunately, the Unicode Arabic characters were not displayed properly. How can I display these Unicode characters properly? So the first solution lacks the access to html elements and the second lacks the Unicode support! My colleagues advised me to use JSP code in the html document that can have an access to my MainController.java class. Therefore, loading the page into JEditorPane with the html elements changed already. Isn't there a way to do that without the help of JSP? Some other people recommended the use of JTidy but isn't there a way to do it within Java's JDK? I'm open to all possible solutions. Please help. My Code: Some code content were omitted because they are not relevant MainController.java class MainController { private static String currentTotalPayment; public static void main(String[] args) { CheckBankFilesView cbfView = new CheckBankFilesView(); cbfView.setVisible(true); } public static void setCurrentTotalPayment(String totalPayment) { MainController.currentTotalPayment = totalPayment; } public static String getCurrentTotalPayment() { return currentTotalPayment; } } MyFormattedOuputSolutionOne.java: public class MyFormattedOuputSolutionOne extends javax.swing.JFrame { private void MyFormattedOuputSolutionOne() { jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); myFormattedOuput = new javax.swing.JEditorPane(); myFormattedOuput.setContentType("text/html"); //myFormattedOuput.setContentType("text/html; charset=UTF-8"); //Doesn't seem to work myFormattedOuput.setEditable(false); jScrollPane1.setViewportView(myFormattedOuput); myFormattedOuput.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); try{ myFormattedOuput.setPage(getClass().getResource("resources/emailFormat2.html")); //How can I edit/change html elements loaded in 'myFormattedOuput'? }catch(Exception e){ } } } MyFormattedOuputSolutionTwo.java: public class MyFormattedOuputSolutionTwo extends javax.swing.JFrame { private void MyFormattedOuputSolutionTwo() { jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); myFormattedOuput = new javax.swing.JEditorPane(); myFormattedOuput.setContentType("text/html"); //myFormattedOuput.setContentType("text/html; charset=UTF-8"); //Doesn't seem to work myFormattedOuput.setEditable(false); jScrollPane1.setViewportView(myFormattedOuput); HTMLEditorKit kit = new HTMLEditorKit(); HTMLDocument doc = new HTMLDocument(); myFormattedOuput.setEditorKit(kit); myFormattedOuput.setDocument(doc); myFormattedOuput.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); try{ // Tried to set the charset in <head> but it doesn't work! //kit.insertHTML(doc, 1, "<meta http-equiv = \"Content-Type\" content = \"text/html; charset=UTF-8\">", 0, 0, HTML.Tag.META); kit.insertHTML(doc, doc.getLength(), "<label> السلام عليكم ورحمة الله وبركاته ,,, </label>", 0, 0, null); //Encoding problem kit.insertHTML(doc, doc.getLength(), "<br/>", 0, 0, null); // works fine kit.insertHTML(doc, doc.getLength(), MainController.getCurrentTotalPayment(), 0, 0, null); // works fine //How can I solve the Unicode problem above? }catch(Exception e){ } } } htmlFormatTable.html: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <meta http-equiv = "Content-Type" content = "text/html; charset=UTF-8"> </head> <body> <label> السلام عليكم ورحمة الله وبركاته ,,, </label> <br/> <label> الأخوة الكرام نفيدكم بتفاصيل المدفوعات لشهر </label> XX/143X </label> هـ كما هو موضح ادناه </label> <br/> <table align="right" border="1" width="600" cellpadding="5" cellspacing="0"> <tr char="utf-8" bgcolor="cccccc" align="center"> <td colspan="3"> <label> تفاصيل مدفوعات بنك الرياض </label> <img src="..\images\riyadh.gif" width="65" height="15"/> </td> </tr> <tr align="center"> <td></td> <td id="cell1">0,000,000.00</td> <td align="right"> معاشات </td> </tr> <tr align="center"> <td></td> <td id="cell2">0,000,000.00</td> <td align="right"> أخطار </td> </tr> <tr align="center"> <td bgcolor="cccccc"> المجموع </td> <td bgcolor="cccccc"> 0,000,000.00 <label> ريال سعودي </label> </td> <td></td> </tr> </table> <br/> <label> شاكرين لكم حسن تعاونكم ...... </label> <br/> <label> فريق العمليات بقسم الحاسب الآلي </label> </body> </html> Thank you for reading my long multiple questions thread and cannot wait for your answer. Update: Thanks to @Howard for this insight, if I replace the arabic character with its corresponding unicode (e.g. ب = \u0628) it works fine but there must be a way to do it without the need to replace each character, right? A: Solution One It is possible to edit HTML loaded into JEditorPane. Here's the complete code based on your MyFormattedOuputSolutionOne.java: import java.awt.ComponentOrientation; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.JEditorPane; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.Element; import javax.swing.text.SimpleAttributeSet; public class MyFormattedOuputSolutionOne extends javax.swing.JFrame { private MyFormattedOuputSolutionOne() { super("MyFormattedOuputSolutionOne"); setDefaultCloseOperation(DISPOSE_ON_CLOSE); JScrollPane jScrollPane1 = new javax.swing.JScrollPane(); final JEditorPane myFormattedOuput = new javax.swing.JEditorPane(); getContentPane().add(jScrollPane1); myFormattedOuput.setContentType("text/html"); //myFormattedOuput.setContentType("text/html; charset=UTF-8"); //Doesn't seem to work myFormattedOuput.setEditable(false); jScrollPane1.setViewportView(myFormattedOuput); myFormattedOuput.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); try{ myFormattedOuput.setPage(getClass().getResource("htmlFormatTable.html")); myFormattedOuput.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if ("page".equals(evt.getPropertyName())) { Document doc = myFormattedOuput.getDocument(); Element html = doc.getRootElements()[0]; Element body = html.getElement(1); Element table = body.getElement(1); try { Element tr2 = table.getElement(1); Element tr2td1 = tr2.getElement(0); doc.insertString(tr2td1.getStartOffset(), "1: 123,456", SimpleAttributeSet.EMPTY); Element tr3 = table.getElement(2); Element tr3td1 = tr3.getElement(0); doc.insertString(tr3td1.getStartOffset(), "2: 765.123", SimpleAttributeSet.EMPTY); } catch (BadLocationException e) { e.printStackTrace(); } myFormattedOuput.removePropertyChangeListener(this); } } }); //How can I edit/change html elements loaded in 'myFormattedOuput'? } catch(Exception e){ e.printStackTrace(); } pack(); setSize(700, 400); setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new MyFormattedOuputSolutionOne(); } }); } } It loads document asynchronously and waits for page to be loaded. When page is loaded, it accesses the elements of the document to search for elements and inserts text into the first <td> in the 2nd and 3rd row of the table. By the way your HTML is not valid! You should clean it up. When you do it, the indexes of the document elements will change and you'll have to adjust code which finds the insertion points. The window looks this way: Solution Two I've found no issues with encoding. The characters display correctly. Yet I had to set the encoding of Java files to UTF-8 in the Eclipse project. Solution Three Have you considered using JTable to display table of results in the UI? The HTML might look this way: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <meta http-equiv = "Content-Type" content = "text/html; charset=UTF-8"> </head> <body> <p> السلام عليكم ورحمة الله وبركاته ,,, </p> <p> الأخوة الكرام نفيدكم بتفاصيل المدفوعات لشهر </p> <p>XX/143X </p> <p> هـ كما هو موضح ادناه </p> <table align="right" border="1" width="600" cellpadding="5" cellspacing="0"> <tr bgcolor="cccccc" align="center"> <td colspan="3">تفاصيل مدفوعات بنك الرياض <img src="..\images\riyadh.gif" width="65" height="15"/></td> </tr> <tr align="center"> <td></td> <td id="cell1">0,000,000.00</td> <td align="right">معاشات</td> </tr> <tr align="center"> <td></td> <td id="cell2">0,000,000.00</td> <td align="right">أخطار</td> </tr> <tr align="center"> <td bgcolor="cccccc">المجموع</td> <td bgcolor="cccccc">0,000,000.00 ريال سعودي</td> <td></td> </tr> </table> <p> شاكرين لكم حسن تعاونكم ...... </p> <p> فريق العمليات بقسم الحاسب الآلي </p> </body> </html> Since I don't understand a word, I cannot propose a better formatting. First of all, <label> elements are allowed only in <form>. You had a sequence of three <label>s above the table where only one of them had opening <label> tag, there were three closing </label> tags. I made them all into <p>; however if you meant them to be headers for table columns, you should have used a table row with three <th> elements. With this structure of the HTML, <table> element in the HTML tree would be at index 4, i.e. you should change the line Element table = body.getElement(1); to Element table = body.getElement(4); The indexes 0–3 are now <p> elements. As a side note, instead of editing HTML after loading it into JEditorPane, which loads it into text model of HTMLDocument, you could edit your HTML document before passing to setPage so that it already contains the correct data in <td> elements. Since JEditorPane.setPage method accepts only URL, then your choice would be read which accepts an InputStream and Object which describes the model (should be instance of HTMLDocument in your case). StringBufferInputStream is the best candidate for this task yet it was deprecated because it cannot correctly read UTF-8 characters. Having this in mind, you would rather use String.getBytes("UTF-8") function (since J2SE 6), and ByteArrayInputStream, your HTML declares the encoding and JEditorPane would respect it when reading.
{ "pile_set_name": "StackExchange" }
Q: ActionEvent stop How do I stop the action event of Button2 and more runs after Button1. Button1 need to do only Button1 Action Event and stop then. Please Help me, thank you public void actionPerformed(ActionEvent ae) { if (ae.getSource().equals(button1)){ System.out.println("Button 1"); } if (ae.getSource() == button2){ System.out.println("Button 2!"); } edit: sorry, wrong code in main: Button1.addActionListener(this); jPanel1.add(Button1); Button2.addActionListener(this); jPanel1.add(Button2); not in main: public void actionPerformed(ActionEvent ae) { Object Button1 = null; if (!ae.getSource().equals(Button1)){ System.out.println("Oben"); } Object Button2 = null; if (ae.getSource() == (Button2)){ System.out.println("Links"); } } if i press my Button1, i get "Oben" if i press my Button2 i get "Oben", too why i dont get "Links" A: There are two problems in your code: You are setting Button1 and Button2 to null Your if-statements are layed out in such a way that more than one of them can run in a single invocation of actionPerformed Try this: public void actionPerformed(ActionEvent ae) { if(ae.getSource().equals(this.Button1)) { System.out.println("Button 1"); } else if (ae.getSource().equals(this.Button2)) { System.out.println("Button 2"); } } This code assumes that Button1 and Button2 are members of the class that the actionPerformed method belongs to.
{ "pile_set_name": "StackExchange" }
Q: How does the day/night cycle work? Zones in the world follow a day / night cycle that does not follow real time. How does it work? Does it have any effect besides the visuals? A: My source (via the Wiki) for this is in French, but it should work something like this: Are they going to include a day/night cycle? Yes. The cycle will be faster than real time. Events and monster spawning will change based on the time of day. Centaurs might attack a camp at dawn, and ghosts haunting an ancient battlefield might only be visible at night. Currently, the cycle lasts 2 hours with 80 minutes of day and 40 minutes of night, but this is subject to change before release. Sylvari glow at night.
{ "pile_set_name": "StackExchange" }
Q: Does $\log_1{n}$ have any analytical significance in counting digits of unary numbers? If $\lfloor{\log_b{n}}\rfloor+1$ counts the number of digits required to represent a number $n$ of radix $b$, what is the significance of $\log_1{n}$ in terms of counting digits of unary numbers? For instance: $\lfloor\log_{10}{5}\rfloor+1=1$ $\lfloor\log_{2}{101_2}\rfloor+1=3$ $\lfloor\log_{1}{00000_1}\rfloor+1$ is undefined although you would expect the pattern to continue and tell us that $5$ in base-1 has indeed $5$ digits. This would effectively mean that $\lfloor\log_1{n}\rfloor+1=n$ and would serve as an identity function. It does not and here's why: $$\log_b{n}=\frac{\log{n}}{\log{b}}$$ $$\log_1{n}=\frac{\log{n}}{\log{1}}=\frac{\log{n}}{0}$$ and so $\log_1{n}$ for any real $n$ is undefined. This is further supported by the fact that $\lim_{b\to1^{+}}{\log_b{n}}=\infty$ and $\lim_{b\to1^{-}}{\log_b{n}}=-\infty$ for $n>1$. Not to mention the very logical contradiction with how any exponential with base of $1$ must equal $1$. Why does this digit counting property of logarithms make sense but not in the general case? To extend the idea further, is there any other way to logically associate $\log_1{n}$ with the identity function? A: Added emphasis on the parts of the original post where the confusion lies... $\lfloor\log_{1}{00000_1}\rfloor+1$ is undefined although you would expect the pattern to continue and tell us that $5$ in base-1 has indeed $5$ digits. Calling the unary representation "base-1" is more of a poetic license than math reality, although it is casually (mis)used that way quite often. Indeed, the very article hyperlinked to "base-1" in the quoted wikipedia page leads to radix which very clearly refers to "a system with radix $b$ ($\,\color{red}{b > 1}\,$)", therefore not applicable to the so-called "base-1" case. Back to logarithms now, they do relate to the number of digits in the base-$b$ representation of numbers in positional notation with $b \gt 1$, because in that case each digit $\,d_k\,$ corresponds to a power $\,b^k\,$ of the base, and the rest follows from definitions. However, the unary representation is not a positional notation, but merely a bijective numeration one. Therefore any expectation that the relation between logarithms and number of digits in positional notation with base $b \gt 1$ would somehow carry over to non-positional unary notation is misplaced.
{ "pile_set_name": "StackExchange" }
Q: Data is invalid error when loading XML I am trying to load a very basic XML document but everytime I get to the LoadXml(string url) line, the program crashes and reports an exception ("Data at the root level is invalid. Line 1, position 1" XmlException). XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(@"C:\Websites\TestHarness\TestHarness\TestHarness\ExampleXml.xml"); XmlNode node = xmldoc.DocumentElement; My XML looks like this (this is a sample xml document from W3Schools and it opens in IE fine): <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> This is pasted exactly as is with no whitespace. I can't see anything wrong with this code, the stack trace doesn't tell me much and I suspect there is an environmental issue somewhere. Does anyone have any ideas? EDIT: The formatting of the XML isn't right. The XML is the same as the sample document on here: http://w3schools.com/xml/default.asp A: Use Load() instead of LoadXml().
{ "pile_set_name": "StackExchange" }
Q: Why Ruby convention is not followed for Array#keep_if? There is a Ruby convention for method naming using bang(!). The convention is if the method changes self, we use bang to let know others about the self modifying bahaviour. For example Array#select doesn't change self, but Array#select! does. But Array#keep_if does change self. There is nothing called Array#keep_if!. What might be the reason for not following the convention? A: Matz, the creator of Ruby, wrote: The bang (!) does not mean "destructive" nor lack of it mean non destructive either. The bang sign means "the bang version is more dangerous than its non bang counterpart; handle with care". Since Ruby has a lot of "destructive" methods, if bang signs follow your opinion, every Ruby program would be full of bangs, thus ugly. Source: Ruby Forum
{ "pile_set_name": "StackExchange" }
Q: To show that $n!f(x) \in \mathbb{Z}[x]$ If $f(x)$ is a polynomial such that if $y \in\mathbb{Z}$, then $f(y)\in\mathbb{Z}$, show that there exist $n$ such that $n!f(x)\in\mathbb{Z}[x]$ A: A well known result is that any integer-valued polynomial is the sum of integer multiples of $\binom{x}{k} =\dfrac{x(x-1)...(x-k+1)}{k!} $. https://en.wikipedia.org/wiki/Integer-valued_polynomial By multiplying by the largest $k!$, we get your statement.
{ "pile_set_name": "StackExchange" }
Q: Heegard genus of hyperbolic Haken 3-manifolds Is there an example of a closed Haken hyperbolic 3-manifold of Heegaard genus 2? A: Even better, there are hyperbolic surface bundles with Heegaard genus two. These are all described in Jesse Johnson's paper, titled Surface bundles with genus two Heegaard splittings. You will need to use some criterion to recognize pseudo-Anosov maps, however.
{ "pile_set_name": "StackExchange" }
Q: Duplicate words in a listbox I am creating a simple GUI application to manage unknown words while learning a new language. The problem is when I enter the word, restart the application, then enter another word and restart the application again - the first word I entered doubles itself. The number of duplicate words rises with the number of words entered. Here is what I have done: # Vocabulary.py # GUI program to manage unknown words from tkinter import * from tkinter import ttk from tkinter import messagebox import xml.etree.ElementTree as ET import os class Word: def __init__(self, wordorphrase, explanation, translation, example): self.wordorphrase = wordorphrase self.explanation = explanation self.example = example self.translation = translation class Vocabulary(Frame): def __init__(self, master): Frame.__init__(self, master) self.master = master self.master.resizable(width = False, height = False) self.master.title("Vocabulary") self.create_widgets() self.words = [] self.load_words() def create_widgets(self): self.buttons_frame = Frame(self.master) self.buttons_frame.grid(row = 10, sticky = W) self.search_frame = Frame(self.master) self.search_frame.grid(row = 1, sticky = W, columnspan = 2) self.comboBox = ttk.Combobox(self.search_frame, width = 3) self.comboBox.grid(row = 0, column = 14, sticky = W) self.comboBox['values'] = ( 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ) self.btn_Add = Button(self.buttons_frame, text = 'Add', command = self.add_item) self.btn_Add.grid(row = 0, sticky = W) self.btn_Remove = Button(self.buttons_frame, text = 'Remove', command = self.remove_item) self.btn_Remove.grid(row = 0, column = 1, sticky = W) self.btn_Edit = Button(self.buttons_frame, text = 'Edit', command = self.edit_item) self.btn_Edit.grid(row = 0, column = 2, sticky = W) self.btn_Save = Button(self.buttons_frame, text = 'Save', command = self.save_item) self.btn_Save.grid(row = 0, column = 3, sticky = W) self.btn_Refresh = Button(self.buttons_frame, text = 'Refresh', command = self.refresh_all) self.btn_Refresh.grid(row = 0, column = 4, sticky = W) self.lblSearch = Label(self.search_frame, text = 'SEARCH: ') self.lblSearch.grid(row = 0, column = 5, sticky = W) self.txt_Search = Text(self.search_frame, height = 1, width = 70) self.txt_Search.grid(row = 0, column = 6, columnspan = 3, sticky = W) self.lblWordsOrPhrases = Label(self.master, text = 'WORDS/PHRASES:') self.lblWordsOrPhrases.grid(row = 2, column = 0) self.lblWordOrPhrase = Label(self.master, text = 'Word or phrase:') self.lblWordOrPhrase.grid(row = 2, column = 1, sticky = W) self.listBox = Listbox(self.master, selectmode='multiple', height = 34, width = 38) self.listBox.grid(row = 3, column = 0, rowspan = 7, sticky = W) self.txt_WordOrPhrase = Text(self.master, height = 1, width = 40) self.txt_WordOrPhrase.grid(row = 3, column = 1, sticky = N) self.lblExplanation = Label(self.master, text = 'Explanation:') self.lblExplanation.grid(row = 4, column = 1, sticky = W) self.txt_Explanation = Text(self.master, height = 10, width = 40) self.txt_Explanation.grid(row = 5, column = 1, sticky = N) self.lblTranslation = Label(self.master, text = 'Translation:') self.lblTranslation.grid(row = 6, column = 1, sticky = W) self.txt_Translation = Text(self.master, height = 10, width = 40) self.txt_Translation.grid(row = 7, column = 1, sticky = N) self.lblExamples = Label(self.master, text = 'Example(s):') self.lblExamples.grid(row = 8, column = 1, sticky = W) self.txt_Example = Text(self.master, height = 10, width = 40) self.txt_Example.grid(row = 9, column = 1, sticky = S) def get_word(self): return self.txt_WordOrPhrase.get('1.0', '1.0 lineend') def get_explanation(self): return self.txt_Explanation.get('1.0', '1.0 lineend') def get_translation(self): return self.txt_Translation.get('1.0', '1.0 lineend') def get_example(self): return self.txt_Example.get('1.0', '1.0 lineend') def add_item(self): w = Word(self.get_word(), self.get_explanation(), self.get_translation(), self.get_example()) self.words.append(w) self.listBox.insert(END, w.wordorphrase) self.clear_all() self.save_all() def remove_item(self): self.listBox.delete(ACTIVE) def edit_item(self): pass def save_item(self): pass def load_words(self): self.listBox.delete(0, END) self.words.clear() path = os.path.expanduser('~/Desktop') vocabulary = os.path.join(path, 'Vocabulary', 'Words.xml') if not os.path.exists(vocabulary): if not os.path.exists(os.path.dirname(vocabulary)): os.mkdir(os.path.dirname(vocabulary)) doc = ET.Element('Words') tree = ET.ElementTree(doc) tree.write(vocabulary) else: tree = ET.ElementTree(file = vocabulary) for node in tree.findall('Word'): w = Word(node.find('Word').text, node.find('Explanation').text, node.find('Translation').text, node.find('Examples').text) self.words.append(w) self.listBox.insert(END, w.wordorphrase) def save_all(self): path = os.path.expanduser('~/Desktop') vocabulary = os.path.join(path, 'Vocabulary', 'Words.xml') tree = ET.ElementTree(file=vocabulary) for xNode in tree.findall('Words'): tree.remove(xNode) for w in self.words: xTop = ET.Element('Word') xWord = ET.Element('Word') xExplanation = ET.Element('Explanation') xTranslation = ET.Element('Translation') xExamples = ET.Element('Examples') xWord.text = w.wordorphrase xExplanation.text = w.explanation xTranslation.text = w.translation xExamples.text = w.example xTop.append(xWord) xTop.append(xExplanation) xTop.append(xTranslation) xTop.append(xExamples) tree.getroot().append(xTop) tree.write(vocabulary) def clear_all(self): self.txt_WordOrPhrase.delete('1.0', END) self.txt_Explanation.delete('1.0', END) self.txt_Translation.delete('1.0', END) self.txt_Example.delete('1.0', END) def refresh_all(self): pass def on_closing(self): self.save_all if messagebox.askokcancel("Quit", "Do you want to quit?"): self.master.destroy() def main(): root = Tk() gui = Vocabulary(root) root.protocol('WM_DELETE_WINDOW', gui.on_closing) root.mainloop() if __name__ == '__main__': main() A: Your problem is not in the listbox, but in the way you save your words in XML in save_all(self). To properly reset the tree, you should replace: for xNode in tree.findall('Words'): tree.remove(xNode) with for xNode in tree.getroot().findall('Word'): tree.getroot().remove(xNode)
{ "pile_set_name": "StackExchange" }
Q: SQL Server GROUP BY COUNT Consecutive Rows Only I have a table called DATA on Microsoft SQL Server 2008 R2 with three non-nullable integer fields: ID, Sequence, and Value. Sequence values with the same ID will be consecutive, but can start with any value. I need a query that will return a count of consecutive rows with the same ID and Value. For example, let's say I have the following data: ID Sequence Value -- -------- ----- 1 1 1 5 1 100 5 2 200 5 3 200 5 4 100 10 10 10 I want the following result: ID Start Value Count -- ----- ----- ----- 1 1 1 1 5 1 100 1 5 2 200 2 5 4 100 1 10 10 10 1 I tried SELECT ID, MIN([Sequence]) AS Start, Value, COUNT(*) AS [Count] FROM DATA GROUP BY ID, Value ORDER BY ID, Start but that gives ID Start Value Count -- ----- ----- ----- 1 1 1 1 5 1 100 2 5 2 200 2 10 10 10 1 which groups all rows with the same values, not just consecutive rows. Any ideas? From what I've seen, I believe I have to left join the table with itself on consecutive rows using ROW_NUMBER(), but I am not sure exactly how to get counts from that. Thanks in advance. A: You can use Sequence - ROW_NUMBER() OVER (ORDER BY ID, Val, Sequence) AS g to create a group: SELECT ID, MIN(Sequence) AS Sequence, Val, COUNT(*) AS cnt FROM ( SELECT ID, Sequence, Sequence - ROW_NUMBER() OVER (ORDER BY ID, Val, Sequence) AS g, Val FROM yourtable ) AS s GROUP BY ID, Val, g Please see a fiddle here.
{ "pile_set_name": "StackExchange" }
Q: Wait for dialog click to restart an activity Hello everybody and thanks in advance for the help. I have two activities. I´m calling a dialog in activity two from activity one. The thing is that I want the dialog to restart activity one if positive button is pressed, but I can`t see how to do it. This is my code... Activity one: @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { Funciones Funciones1 = new Funciones(); Funciones1.MuestraDialogo(CluefichaActivity.this); return true; } return super.onOptionsItemSelected(item); } Activity two: public class Funciones extends Activity { private static final int DIALOGO = 1; private AlertDialog.Builder ventana; Activity miActividad; @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOGO: ventana = new AlertDialog.Builder(miActividad); ventana.setIcon(miActividad.getResources().getIdentifier("my_icon", "drawable", miActividad.getPackageName())); ventana.setTitle("title"); ventana.setMessage("message"); ventana.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int boton) { Intent intent = miActividad.getIntent(); miActividad.finish(); startActivity(intent); } }); } ventana.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int boton) { } }); return ventana.create(); } return null; } ... ... public void MuestraDialogo (Activity actividad) { miActividad = actividad; showDialog(DIALOGO); } I get this error when I run it... Process: com.myproject.projectname, PID: 1841 java.lang.NullPointerException at android.app.Activity.startActivityForResult(Activity.java:3511) at android.app.Activity.startActivityForResult(Activity.java:3472) at android.app.Activity.startActivity(Activity.java:3714) at android.app.Activity.startActivity(Activity.java:3682) at com.myproject.projectname.Funciones$1.onClick(Funciones.java:130) at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:157) at android.app.ActivityThread.main(ActivityThread.java:5356) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081) at dalvik.system.NativeStart.main(Native Method) where "Funciones.java:130" is this line of code: "startActivity(intent);" Can anybody help, please? Thanks! A: You need to send a broadcast (LocalBroadcast) from your sub-Activity dialog to your main activity and process that broadcast to instigate termination: In your main Activity, say MainActividad static final String BROADCAST_ACTIVITY_CLOSE = "com.example.ACTIVITY_CLOSE_BROADCAST"; private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals(BROADCAST_ACTIVITY_CLOSE)) { terminateCleanly(); finish(); } } }; Then in onCreate: LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(this); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(BROADCAST_ACTIVITY_CLOSE); broadcastManager.registerReceiver(broadcastReceiver, intentFilter); Saves updating your manifest and I think is cleaner. Your dialog invokes this with: Intent RTReturn = new Intent(MainActividad.BROADCAST_ACTIVITY_CLOSE); LocalBroadcastManager.getInstance(this).sendBroadcast(RTReturn);
{ "pile_set_name": "StackExchange" }
Q: Dynamically populate LI's inside last UL I want to create something like this, but dynamically: <ul class="list-group list-group-flush"> <li class="list-group-item list-group-item-light"> <div class="row"> <label for="label1" class="col-sm-10 col-form-label col-form-label-sm">Label 1</label> <div class="col-sm-2"> <input type="text" class="form-control form-control-sm" id="label1" placeholder="Label1" value="50"> </div> </div> </li> <li class="list-group-item list-group-item-light"> <div class="row"> <label for="label2" class="col-sm-10 col-form-label col-form-label-sm">Label 2</label> <div class="col-sm-2"> <input type="text" class="form-control form-control-sm" id="label1" placeholder="Label2" value="3"> </div> </div> </li> <li class="list-group-item list-group-item-light"> <div class="row"> <label for="label3" class="col-sm-10 col-form-label col-form-label-sm">Label 3</label> <div class="col-sm-2"> <input type="text" class="form-control form-control-sm" id="label1" placeholder="Label3" value="17"> </div> </div> </li> </ul> The amount of li items depends on how many rows it fetched from the database. I tried something like this: rows.forEach(function(obj) { $('#custom-fields').append('<li class="list-group-item list-group-item-light"><div class="row"><label for="'+obj.id+'" class="col-sm-10 col-form-label col-form-label-sm">'+obj.label+'</label><div class="col-sm-2"><input type="text" class="form-control form-control-sm" id="'+obj.id+'" placeholder="'+obj.placeholder+'" value="50"></div></div></li>'); }); ...but I can't figure out how to wrap the ul around it. The thing is also that there are a lot of uls on the page, so I can't simply use something like $('#custom-fields ul').append('... Any tips? A: You can make, and append to, a new ul, and then append that to the page. var $newUL = $('<ul>'); rows.forEach(function(obj) { $newUL.append('<li class="list-group-item list-group-item-light"><div class="row"><label for="'+obj.id+'" class="col-sm-10 col-form-label col-form-label-sm">'+obj.label+'</label><div class="col-sm-2"><input type="text" class="form-control form-control-sm" id="'+obj.id+'" placeholder="'+obj.placeholder+'" value="50"></div></div></li>'); }); $('#custom-fields').append($newUL);
{ "pile_set_name": "StackExchange" }
Q: Overriding 2 functions in vendor package class I'm currently trying to retrieve the SMTP Queue-ID when using the Laravel (5.6) Mail class. I have copied the file vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php to /app/OverriddenAbstractSmtpTransport.php and made an alias in config/app.php, made my changes: 1: on line#395 I added return in front of the line, so we obtain the output 2: line#492 replaced with $message->queue_ids[] = $this->streamMessage($message); So I can access queue_ids from the message property in the Illuminate\Mail\Events\MessageSent-event Now this works, but I don't think it's a very safe approach to modifying the vendor class, as it might cause a breaking change when running security updates. Is there a simpler/better/safer solution to this ? A: Copying the whole class is risky - if any updates are done to the vendor class in a newer version, they'll never make it into your copy. A safer way is to extend the original class and overwrite those 2 functions. There is still a risk of some changes being done to those functions in vendor class, but it's much lower now. Another option would be to extend the original class and add new methods - they will have access to all public and protected properties/methods of the original class and that could be enough to get you what you need. Whatever version you choose, you'll need to later register the new class as a new driver/transport for Swift. Check the following snippet for an example: https://gist.github.com/maxwellimpact/46ded5c553f68946d13d
{ "pile_set_name": "StackExchange" }
Q: Calculate time differences between multiple set of data This is a data set in a mysql table which is related to a error log of an electronic divice. i need to calculate the total down time. time_stamp error_type error_status 1467820110 1 1 1467820120 2 1 1467820130 3 1 1467820140 3 0 1467820150 1 0 1467820160 2 0 1467820180 1 1 1467820185 1 0 1467820191 2 1 1467820300 2 0 1467820302 1 1 1467820404 3 1 1467820408 3 0 1467820409 1 0 error_status 1 = error occored error_status 0 = error fixed 1st down time 1467820160 - 1467820110 = 50 2nd down time 1467820185 - 1467820180 = 5 3rd down time 1467820300 - 1467820191 = 109 4th down time 1467820409 - 1467820302 = 107 total down time = 50 + 5 + 109 + 107 = 271 How can i write a mySQL compatible SQL statement to achieve this. A: Basically, you need to calculate the number of cumulative errors that have occurred. Then identify groups where the values are greater than 0. This can be done by doing a cumulative count of the number of "0"s for the cumulative errors. There is a challenge getting the final timestamp. One trick is to get the next status 0 timestamp for the error. This acts as an "end". Finally, an aggregation get the information for each period: select count(*) as num_errors, max(end_timestamp) - min(timestamp) from (select t.*, (@grp := @grp + if(cume_errors = 0, 1, 0)) as grp from (select t.*, (select t2.timestamp from t t2 where t2.error_type = t.error_type and t2.error_status = 0 and t2.timestamp > t.timestamp order by t2.timestamp asc limit 1 ) as end_timestamp, (@e := @e + if(error_status > 0, 1, -1)) as cume_errors from t cross join (select @e := 0) params order by timestamp ) t cross join (select @grp := 0) params order by timestamp ) t where error_status > 0 group by grp; You can aggregate over this query to get the total period of downtime. Here is a SQL Fiddle.
{ "pile_set_name": "StackExchange" }
Q: Ergodic for the mean, but not ergodic stochastic process? Is there an example of a strictly stationary (zero mean, finite variance) stochastic process $(X_t\mid t\in \mathbb{N})$ that satisfies the conclusion of the ergodic theorem, i.e., the sample mean $\overline{X}_n\rightarrow_{a.s.} 0$, as $n\rightarrow \infty$, such that $X_s$ is uncorrelated with $X_t$, whenever $t\neq s$, but $(X_t\mid t\in \mathbb{N})$ is not ergodic (i.e., the underlying shift operator is not an ergodic transformation)? Any ideas? Many thanks! A: Let $Z$ be a random variable with $P(Z=1) =P(Z=2)=1/2$. Let $Y_1, Y_2, \dots$ be iid and independent of $Z$ with $P(Y_t = 1) = P(Y_t = -1) = 1/2$. Set $X_t = Z Y_t$. Then $X_t$ is stationary, and by the strong law of large numbers, $\overline{X}_n = Z \overline{Y}_n \to Z E[Y_t] = 0$ almost surely. It is also uncorrelated, since for $s \ne t$ we have $$E[X_s X_t] = E[Z^2 Y_s Y_t] = E[Z^2] E[Y_s] E[Y_t] = 0 = E[X_s] E[X_t].$$ But $X_t$ is not ergodic; for example, the event $A = \{X_t = 2 \text{ i.o.}\}$ is shift invariant, but since $A = \{Z=2\}$ we have $P(A) = 1/2$. A: Consider the process $X_n = (-1)^n X_0$ where $X_0$ is a random variable with distribution symmetric about $0$ (but $|X|$ not a.s. constant).
{ "pile_set_name": "StackExchange" }
Q: Spring boot app gracefully catch the SIGTERM signal and invoke the predestroy method I have a spring boot application which needs to clear or clean up the resources when we kill the process using kill pid. @predestroy annotated method is not working and not getting called. Please suggest how can we catch the SIGTERM and invoke the predestroy method A: Ideally, it should work but make sure SIGTERM is called and not SIGKILL I have a few cases where we run spring boot application Docker When you execute docker stop what happens behind the scene is Stop one or more running containers The main process inside the container will receive SIGTERM, and after a grace period, SIGKILL kill kill 9955 => SIGTERM is called kill -9 9955 => SIGKILL is called Refer here for more detail on kill. Now coming back to @PreDestroy I have added following line in my SpringBoot Application @PreDestroy public void tearDown() { System.out.println("Shutting Down...............the "); } I get following output when I do kill portno 2019-01-04 10:52:44.776 INFO o.s.s.c.ThreadPoolTaskScheduler / shutdown - 208 : Shutting down ExecutorService 'taskScheduler' 2019-01-04 10:52:44.783 INFO o.s.s.c.ThreadPoolTaskExecutor / shutdown - 208 : Shutting down ExecutorService 'applicationTaskExecutor' 2019-01-04 10:52:44.785 INFO o.s.o.j.LocalContainerEntityManagerFactoryBean / destroy - 597 : Closing JPA EntityManagerFactory for persistence unit 'default' 2019-01-04 10:52:44.792 INFO c.z.h.HikariDataSource / close - 350 : HikariPool-1 - Shutdown initiated... 2019-01-04 10:52:44.800 INFO c.z.h.HikariDataSource / close - 352 : HikariPool-1 - Shutdown completed. Shutting Down............... As you can see in Log I have 2 Scheduler Task running and JPA Entity Manager. On receiving SIGTERM it closes all that first and finally call preDestory. I am not sure what more clean up you need to do but do make sure if its already cleaned. Shut down embedded servlet container gracefully You can also customize and write your own shutdown gracefully hook. Refer to this good discussion and sample code on this Restructure embedded web server packages Pls be mindful of the sample code from above link. If you are using newer version of Springboot changes are package might be missing. Refer this for more detail on changed methods and classes
{ "pile_set_name": "StackExchange" }
Q: Java script which will show me the alert like Versioning is enabled or not for that document library when user access any document library I need to create java script which will show me the alert like Versioning is enabled or not for that document library when user open any document library. Please let me know how I can achieve this by using java script any reference A: Add content editor webpart on list view web page and add below code snippet <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script><script> $(document).ready(function () { $listName = ctx.ListTitle; $siteurl = _spPageContextInfo.webAbsoluteUrl; var url = $siteurl+"/_api/web/lists/getbytitle('"+$listName+"')?$select=EnableVersioning" getData(url).done(function (data) { console.log(data.EnableVersioning); if(data.EnableVersioning) { alert("Versioning is enalbe"); }else { alert("Versioning is not enabled") } }) }) getData = function (url) { return $.getJSON(url); }; </script>​​​​
{ "pile_set_name": "StackExchange" }
Q: PHP Nested array to govern a navigation function won't work Can someone tell me why this isn't working? The "isTrue" => true is actually a function that determines if the the content for that field exists or not, I've var_dumped it and it works. I'm trying to output one (or all, depends on "isTrue" => true) of the navigation links as this: <li><a class="gallery-tab" href="#gallery-tab">gallery</a></li> as a content type specific navigation element. I had this working before in a much cruder way but I'm trying to make my code more maintainable and this has been one frustrating road block for me. When I run the code below, I get NULL While I'm pretty comfortable with PHP, I'm not a seasoned vet of it. Usually when I show a problem like this to you guys, someone sees the problems pretty quickly and I've just been banging my head against the wall trying to figure it out. Here is the code in question: <?php $navArray[0] = array( "title" => "statement", "class" => "statement-tab", "isTrue" => true ); $navArray[1] = array( "title" => "gallery", "class" => "gallery-tab", "isTrue" => true ); $navArray[2] = array( "title" => "video", "class" => "video-tab", "isTrue" => true ); $navArray[3] = array( "title" => "poetry", "class" => "poetry-tab", "isTrue" => true ); function get_nav() { foreach ($navArray as $array ) { if ($array["isTrue"] == true) { $output = ""; $output = $output . "<li>"; $output = $output . '<a class="' . $array["class"] . '" href="#' . $array["class"] . '" />'; $output = $output . $array["title"]; $output = $output . "</a>"; $output = $output . "</li>"; return $output; } } } $getNav = get_nav(); ?> <pre><?php var_dump($getNav); ?></pre> If anything is unclear please let me know and I'll do my best to clarify. EDIT: zeantsoi kindly pointed out that I was calling in the wrong array. I fixed and tested it and still no luck. A: I can see a couple of problems. Firstly, $nav_array doesn't exist. Even assuming it should be $navArray, it still doesn't exist in the scope of the function. I'd suggest something like this: function get_nav($navArray) { foreach($navArray as $array) { ... $getNav = get_nav($navArray); The second issue is that you are only ever going to get the first nav item, because you're compiling and returning the output inside the loop. So you need to update it to be something like this: function get_nav($navArray) { $output = ""; foreach($navArray as $array) { if ($array["isTrue"] == true) { $output .= "<li>"; $output .= '<a class="' . $array["class"] . '" href="#' . $array["class"] . '" />'; $output .= $array["title"]; $output .= "</a>"; $output .= "</li>"; } } return $output; }
{ "pile_set_name": "StackExchange" }
Q: Django - "Find latest" of children for all rows I'm having difficulties with 'aggregate' and 'latest' . I've got these two models : class Word(models.Model): ESSENTIALWORDS = 'EW' FOOB = 'ER' OTHER = 'OT' WORDSOURCE_TYPE_CHOICES = ( (ESSENTIALWORDS, 'Essential Words'), (FOOB, 'FOOB'), (OTHER, 'OTHER'), ) level = models.IntegerField() word = models.CharField(max_length=30) source = models.CharField(max_length=2, choices=WORDSOURCE_TYPE_CHOICES, default=OTHER) hint = models.CharField(max_length=30, null=True, blank=True) class Attempt(models.Model): learner = models.ForeignKey(Learner) word = models.ForeignKey(Word) when = models.DateTimeField(auto_now_add=True) success = models.BooleanField(default=False) I want to find all Word objects for which the most recent Attempt (based on the Field when) has a success value of True. A: This should work: from django.db.models import Max, F Word.objects.annotate(latest=Max('attempt__when')) .filter(attempt__success=True, attempt__when=F('latest')) First, every Word is annotated with the date of the most recent (i.e. the Max) attempt. Then the Word objects are filtered to only include ones that have a matching Attempt where success is True and where the date matches the latest date. (F is used to represent the value of another column—or in this case, an annotation.)
{ "pile_set_name": "StackExchange" }
Q: Java.util.Map to JSON Object with Jersey / JAXB / Jackson I've been trying to create a Jersey REST Webservice. I want to receive and emit JSON objects from Java classes like the following: @XmlRootElement public class Book { public String code; public HashMap<String, String> names; } This should be converted into JSON like this: { "code": "ABC123", "names": { "de": "Die fabelhafte Welt der Amelie", "fr": "Le fabuleux destin d'Amelie Poulain" } } However I can not find a standard solution for this. Everybody seems to be implementing his own wrapper solution. This requirement seems extremly basic to me; I can't believe that this is the generally accepted solution to this, especially since Jersey is really one of the more fun parts of Java. I've also tried upgrading to Jackson 1.8 which only gives me this, which is extremly obfusicated JSON: { "code": "ABC123", "names": { "entry": [{ "key": "de", "value": "Die fabelhafte Welt der Amelie" }, { "key": "fr", "value": "Le fabuleux destin d'Amelie Poulain" }] } } Are there any proposed solutions for this? A: I don't know why this isn't the default setting, and it took me a while figuring it out, but if you want working JSON conversion with Jersey, add <init-param> <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name> <param-value>true</param-value> </init-param> to your web.xml and all your problems should be solved. PS: you also need to get rid of the @XmlRootElement annotations to make it work A: You can use google-gson. Here is a sample code: @Test public void testGson(){ Book book = new Book(); book.code = "1234"; book.names = new HashMap<String,String>(); book.names.put("Manish", "Pandit"); book.names.put("Some","Name"); String json = new Gson().toJson(book); System.out.println(json); } The output is {"code":"1234","names":{"Some":"Name","Manish":"Pandit"}} A: I know it's been asked long time ago, but things changed mean time, so for the latest Jersey v2.22 that do not have anymore the package com.sun.jersey, these two dependencies added in the project pom.xml solved the same problem: <dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-json-jackson</artifactId> <version>2.22</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.jaxrs</groupId> <artifactId>jackson-jaxrs-json-provider</artifactId> <version>2.5.4</version> <!-- jackson version used by jersey v2.22 --> </dependency> No need to add anything in web.xml. First dependency will instruct jersey to use jackson for POJO to JSON transformations. Second dependency will register jackson as jersey JSON provider. Also for the null problem in POJO, add this annotation to the POJO class: @JsonInclude(JsonInclude.Include.NON_NULL)
{ "pile_set_name": "StackExchange" }
Q: Firebase with kotlin array of ratings problem I cant get the ratings all at the same time and do the average! Anyone knows how to do this? Get a problem saying "none of the following functions can be called with the arguments supplied" val ref = FirebaseDatabase.getInstance().getReference("recipes/$id/reci_ratings/") ref.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(p0: DataSnapshot) { p0.children.forEach{ val rt= it.child("rating").value val numbers = arrayOf(rt) var sum = 0 for (element in numbers) { sum += element } val average = sum / numbers.size } } A: Welcome to SO. You're more likely to get good answers if you follow these tips: https://stackoverflow.com/help/how-to-ask But nevertheless...your code seems to lack the closing bracket with parenthesis, but maybe you just missed to add that in your question? Another thing is that your numbers array will never contain more than one ratings value. You should declare and populate it like so: val ref = FirebaseDatabase.getInstance().getReference("recipes/$id/reci_ratings/") var numbers: ArrayList<Int> = arrayListOf() // Change to whatever type is accurate in your case var sum = 0 ref.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(p0: DataSnapshot) { p0.children.forEach { val rt = it.child("rating").value numbers.add(rt) } // After the forEach loop is finished you should have all the ratings in the numbers array } })
{ "pile_set_name": "StackExchange" }
Q: Finding expected value and variance from CDF $1 - \frac{81}{x^4}$ if $x \geq 3$ The CDF is as follows: $$F(x) =\begin{cases} 0, & \text{if } x \leq 3;\\ 1 - \frac{81}{x^4}, & \text{if } x \geq 3.\end{cases}$$ From this I derived for the PDF, which would be $324/x^5$, but I'm having a hard time visualizing this and calculating the expected value from it. For example, I attempted to calculate the answers for several values of x, hoping to simply insert them into the $E(X)$ formula, $$E(X) = \sum_x p(x),$$ But when I enter values like $1, 2$, or $3$ in the PDF I obviously get crazy high numbers ($324, 20$, and $4$) which doesn't make sense for a probability problem. Shouldn't they be between $0$ and $1$ like they are for the CDF? Furthermore, how can I get the variance? Can I get it through the CDF instead, via subbing in values for $E(X)$ and $E(X^2)$, or can I only get there from the PDF? A: There seem to be a bunch of problems with your understanding of probability and expectation. First, this problem is continuous, rather than discrete. What this means is that your random variable $X$ can take values on the range from $[3,\infty)$ rather than on some discrete set of values, e.g., $\{3,4,\ldots,\infty\}.$ Now, the first question you have in there is why are the values you're getting above one in PDF? The answer is because, for a continuous problem, the PDF doesn't give you probabilities. Understanding this can be a question of its own, but the short answer is, integrating under the PDF gives you probabilities on ranges of values. For example, if we call $f(x)$ the PDF of $X$ and want to know the probability that $X$ is between $5$ and $10$ we can integrate, $$\mathbb{P}(5\leq X \leq 10) = \int_5^{10}f(x)dx.$$ This means that the probability of getting any individual value is zero, that is, $$\mathbb{P}(X = a)=\mathbb{P}(a\leq X \leq a) = \int_a^{a}f(x)dx = 0.$$ So in this way, the PDF doesn't give probabilities and there is no reason to think that it will have a range of $[0,1]$. Rather, you can think about areas where the PDF is high being ranges of values which are likely. Now, as for the expectation calculation, again you need to compute it differently because $X$ is continuous. In particular, $$\mathbb{E}(X) = \int_{-\infty}^{\infty}xf(x)dx = \int_3^{\infty}x\cdot \frac{324}{x^5}dx = \left. -\frac{108}{x^3}\right|_3^{\infty} = 4.$$ Where the first equality is simply by definition, and the following equalities are for your particular problem. Similarly, you can compute $$\mathbb{E}(X^2) = \int_{-\infty}^{\infty}x^2f(x)dx = \int_3^{\infty}x^2\cdot \frac{324}{x^5}dx = \left. -\frac{162}{x^2}\right|_3^{\infty} = 18.$$ To be complete, we can then take these numbers to compute the variance, $$\text{Var}(X) = \mathbb{E}\left[\left(X - \mathbb{E}(X)\right)^2\right] = \mathbb{E}(X^2) - \left(\mathbb{E}(X)\right)^2 = 18 - 4^2 = 2.$$
{ "pile_set_name": "StackExchange" }
Q: HTML Canvas - Drag and resize uploaded image I am doing a drawing app for a college project and currently im able to upload images into the canvas and i want to make those images resizable/draggable. I've seen this great example and tried to apply it in my project for hours but with no success. Is it possible to apply it to an uploaded image instead of preloaded image like in that example? My javascript code to upload image and a fiddle. Thanks in advance. var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); function el(id){return document.getElementById(id);} function readImage() { if ( this.files && this.files[0] ) { var FR= new FileReader(); FR.onload = function(e) { var img = new Image(); img.onload = function() { ctx.drawImage(img, true, true); }; img.src = e.target.result; }; FR.readAsDataURL( this.files[0] ); } } el("fileUpload").addEventListener("change", readImage, false); A: As you have provided a nice example, I just included those methods and variables in your code and added jquery then declared the var img = new Image(); variable outside of the readImage function. That's it I did and it worked as you expected. Here you go, var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var canvasOffset = $("#canvas").offset(); var offsetX = canvasOffset.left; var offsetY = canvasOffset.top; var startX; var startY; var isDown = false; var pi2 = Math.PI * 2; var resizerRadius = 8; var rr = resizerRadius * resizerRadius; var draggingResizer = { x: 0, y: 0 }; var imageX = 50; var imageY = 50; var imageWidth, imageHeight, imageRight, imageBottom; var draggingImage = false; var startX; var startY; function el(id){return document.getElementById(id);} var img = new Image(); function readImage() { if ( this.files && this.files[0] ) { var FR= new FileReader(); FR.onload = function(e) { img = new Image(); img.onload = function() { imageWidth = img.width; imageHeight = img.height; imageRight = imageX + imageWidth; imageBottom = imageY + imageHeight draw(true, false); }; img.src = e.target.result; }; FR.readAsDataURL( this.files[0] ); } } el("fileUpload").addEventListener("change", readImage, false); function draw(withAnchors, withBorders) { // clear the canvas ctx.clearRect(0, 0, canvas.width, canvas.height); // draw the image ctx.drawImage(img, 0, 0, img.width, img.height, imageX, imageY, imageWidth, imageHeight); // optionally draw the draggable anchors if (withAnchors) { drawDragAnchor(imageX, imageY); drawDragAnchor(imageRight, imageY); drawDragAnchor(imageRight, imageBottom); drawDragAnchor(imageX, imageBottom); } // optionally draw the connecting anchor lines if (withBorders) { ctx.beginPath(); ctx.moveTo(imageX, imageY); ctx.lineTo(imageRight, imageY); ctx.lineTo(imageRight, imageBottom); ctx.lineTo(imageX, imageBottom); ctx.closePath(); ctx.stroke(); } } function drawDragAnchor(x, y) { ctx.beginPath(); ctx.arc(x, y, resizerRadius, 0, pi2, false); ctx.closePath(); ctx.fill(); } function anchorHitTest(x, y) { var dx, dy; // top-left dx = x - imageX; dy = y - imageY; if (dx * dx + dy * dy <= rr) { return (0); } // top-right dx = x - imageRight; dy = y - imageY; if (dx * dx + dy * dy <= rr) { return (1); } // bottom-right dx = x - imageRight; dy = y - imageBottom; if (dx * dx + dy * dy <= rr) { return (2); } // bottom-left dx = x - imageX; dy = y - imageBottom; if (dx * dx + dy * dy <= rr) { return (3); } return (-1); } function hitImage(x, y) { return (x > imageX && x < imageX + imageWidth && y > imageY && y < imageY + imageHeight); } function handleMouseDown(e) { startX = parseInt(e.clientX - offsetX); startY = parseInt(e.clientY - offsetY); draggingResizer = anchorHitTest(startX, startY); draggingImage = draggingResizer < 0 && hitImage(startX, startY); } function handleMouseUp(e) { draggingResizer = -1; draggingImage = false; draw(true, false); } function handleMouseOut(e) { handleMouseUp(e); } function handleMouseMove(e) { if (draggingResizer > -1) { mouseX = parseInt(e.clientX - offsetX); mouseY = parseInt(e.clientY - offsetY); // resize the image switch (draggingResizer) { case 0: //top-left imageX = mouseX; imageWidth = imageRight - mouseX; imageY = mouseY; imageHeight = imageBottom - mouseY; break; case 1: //top-right imageY = mouseY; imageWidth = mouseX - imageX; imageHeight = imageBottom - mouseY; break; case 2: //bottom-right imageWidth = mouseX - imageX; imageHeight = mouseY - imageY; break; case 3: //bottom-left imageX = mouseX; imageWidth = imageRight - mouseX; imageHeight = mouseY - imageY; break; } if(imageWidth<25){imageWidth=25;} if(imageHeight<25){imageHeight=25;} // set the image right and bottom imageRight = imageX + imageWidth; imageBottom = imageY + imageHeight; // redraw the image with resizing anchors draw(true, true); } else if (draggingImage) { imageClick = false; mouseX = parseInt(e.clientX - offsetX); mouseY = parseInt(e.clientY - offsetY); // move the image by the amount of the latest drag var dx = mouseX - startX; var dy = mouseY - startY; imageX += dx; imageY += dy; imageRight += dx; imageBottom += dy; // reset the startXY for next time startX = mouseX; startY = mouseY; // redraw the image with border draw(false, true); } } $("#canvas").mousedown(function (e) { handleMouseDown(e); }); $("#canvas").mousemove(function (e) { handleMouseMove(e); }); $("#canvas").mouseup(function (e) { handleMouseUp(e); }); $("#canvas").mouseout(function (e) { handleMouseOut(e); }); #canvas { border:1px solid black; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='file' id="fileUpload" /> <canvas id="canvas" width="500" height="500"></canvas>
{ "pile_set_name": "StackExchange" }
Q: PIM NoClassDefFoundError but the jar is in the classpath I am implementing the PIM API in my J2ME app when I run it on the KEmulator or on the device (Sony Ericsson k800i) I am getting this exception java.lang.NoClassDefFoundError: javax/microedition/pim/PIMException though the jar file has the PIMException.class file inside the javax/microedition/pim package. A: Well the problem is solved, all i needed to do is add the JSR api as refrence library.
{ "pile_set_name": "StackExchange" }
Q: How to create a jQuery-Ajax-Request but not send it right away to the server In Mootools, I can create an AJAX-request and save it in a variable for further use. When I create the request, I can send it later by calling myRequest.send(); or myRequest.get(); In jQuery, whenever I create an AJAX-request, it is sent right away to the server. Is it possible to create a request without sending it at the same moment? A: As @Sergio and @adeneo stated above in the comments: Some things about MooTools are ready "out of the box". Request in MooTools is a Class and you can "prepare it" and fire the .send()method when you want. With jQuery you cannot do that, you either fire it ritgh away, or create another function with a ajax funcion inside and pass it parameters when you call it. I prefer the MooTools way... Thanks!
{ "pile_set_name": "StackExchange" }
Q: Cleartrip Flight API - "Not authorized to access the service" error I am using Cleartrip Flight API to get flight fare details. When request the URL with API key, i am getting "Not authorized to access the service" error. Here is my Java code using Apache HttpComponents HttpHost proxy = new HttpHost("My IP", Port No, "http"); String url = "https://api.cleartrip.com/air/1.0/search?from=BOM&to=DEL&depart-date=2013-06-06&return-date=2013-06-06"; //String url = "http://www.google.com/search?q=developer"; HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); HttpGet request = new HttpGet(url); // add request header request.addHeader("X-CT-API-KEY", "My API Key"); request.addHeader("User-Agent", "Mozilla/5.0"); System.out.println(" header "+request.getHeaders("X-CT-API-KEY")[0]); HttpResponse response = client.execute(request); System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("Response Code : " + response.getStatusLine().getStatusCode()); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } System.out.println(result.toString()); } Can anyone help me !!! A: Even i had the same issue. Later i came to know that all the api (which you get during singn up process) are blocked by default. You have to write a mail to [email protected] They will ask your company details, business model and business case. If they are satisfied with those details then they will unblock your api key. Since my project is for my final semester they have rejected my api key query. Here i am sharing my java code. So that it might be useful for some one. HttpClient client = new DefaultHttpClient(); String getURL =URL; Log.d("URL",getURL); HttpGet get = new HttpGet(getURL); get.setHeader("X-CT-API-KEY", (my api key)); HttpResponse responseGet = client.execute(get); HttpEntity resEntityGet = responseGet.getEntity(); if (resEntityGet != null) { Log.i("GET ", EntityUtils.toString(resEntityGet)); } Since i was not authorized to use this api i got the following response. <?xml version="1.0" encoding="UTF-8" standalone="yes"?><faults xmlns="http://www.cleartrip.com/apigateway/common"><fault><fault-message>Not authorized to access the service</fault-message></fault></faults> HTTP URL is as follows https://api.cleartrip.com/air/1.0/search?from=BOM&to=DEL&depart-date=2013-11-11&return-date=2013-12-12
{ "pile_set_name": "StackExchange" }
Q: Paypal integration with java i want to know how to integrate paypal payment gateway with java. I need steps or sample code A: There's a complete Java SDK for the Classic API's as well as the new REST API's at http://paypal.github.io/ Additionally, "paypal payment gateway" doesn't exist. PayPal is the company, and Website Payments Standard, Express Checkout, Website Payments Pro, Adaptive Payments, Express Checkout for Digital Goods, Payflow Link and Payflow Pro are their products. Which product are you trying to use?
{ "pile_set_name": "StackExchange" }
Q: What is the meaning of "ought not"? Consider this example: A few strong branches over water reach for what they ought not reach. Which of the meanings comes closest to “ought not” in this sentence? Is it “doesn't have to”, “should not” or “must not”? A: Some might prefer the sentence to have to before reach, but otherwise it is well-formed. It’s impossible to be sure of the meaning out of context. It could be should not or it could be must not, or possibly something else, but not doesn't have to (which would in any case have to be don't have to in order to agree in number with the subject). A: There appear to be several issues entangled here. One issue, the answer to the OP's original question, is that they're all different modal constructions, each with different sources, different syntax, different idioms, and different possible senses, which nevertheless often overlap, in the right contexts. And they're all irregular as hell. Another issue is the metaphoric source of ought, which is, as many of us know, the old past participle of the verb to owe, and is caught up with the concepts of credit and debit, authority and duty. One ought to do something if one owes one's action (to some person, or some abstract principle) to pay a debt, to pay one's due(s), to do one's due-ty, etc, etc. Ought (or more commonly oughta) is principally a weak Necessity deontic modal, like should, rooted in a Face and Credit social system (rather than a Strict Authority system, like the strong Necessity modals must and hafta) but there is an epistemic sense as well, usually functioning wherever emotions can be invoked or inferred, as in anger over a misplaced item. Compare Dammit! It oughta be here. with Dammit! It should be here. which sounds a little weaker to my ear by comparison. But that could be personal usage bias. There's a lot of that, with all modals. Still another issue is the use of ought as a true modal auxiliary verb (which means no to on infinitive complements), or as a semi-modal auxiliary, (like need or dare, which allow to before infinitive complements, under certain circumstances). Ought is a paraphrase of a true modal auxiliary (in this case should) that hasn't quite assimilated yet, at least not enough to lose the to everywhere. Like the true modal auxiliary should, it precedes not, but there are variant past constructions -- hadn't oughta, shouldn't oughta. Also like should (and would, could, might and must), it's formed from a preterite stem but can refer to the future naturally. But should never takes to. However, ought, if it's separated from its infinitive by a negative, can suffer stack overflow, lose its modal binding field, revert to regular verb status, and allow automatic generation of an infinitive complementizer to. This alternation of ought not go vs ought not to go resembles the behavior of need and dare, which are also Negative Polarity Items as modals, though with a different syntax. Outside negative polarity environments, though, the to in ought to seems likely to remain for a while. It is reinforced by the bisyllabic nature of all the periphrastic modal proto-auxiliaries oughta, hafta, gonna, wanna, etc, which are all in the same kind of boat, but whose individual grammars all leak in different places. A: In general usage, should not. "Doesn't Have to" does not really make sense to me in that context, whilst "must not" appears too strong. A few strong branches over water reach for what they should not reach However looking at that sentence it does seem a little odd. I am still confident that that is the best fit.
{ "pile_set_name": "StackExchange" }
Q: Unable to compile my first JSP program <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <form method=post action="Check.jsp"> <center><h3>Voter Application</h3></center> Enter your Age:<input type="text" name="age"> <input type="submit" value = "Check Age"> </form> </body> Second jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <% int age = Integer.parseInt(request.getParametes(age)); if(age>=18){ %><h1>You are eligible to vote</h1> <% else{ %> <h2>Sorry, you cant vote yet</h2> <%} %> </body> </html> </html> Here is the error: The second JSP shows a compilation error at the ending curly brace of else. All of the java code is within the <% %> as per the rules but I cant get my around this one. After running the program on the server the error is HTTP status 500 . Unable to compile class for JSP A: You are missing a curly brace on the else line. Change to this: <% } else { %> <h2>Sorry, you cant vote yet</h2>
{ "pile_set_name": "StackExchange" }
Q: Error running ./node_modules/.bin/cucumber-js in GitLab CI I am setting up a CI build for my node project. Although my npm run test works as expected in my local environment, the gitlab ci is throwing an exception. The test command fails in: > nyc ./node_modules/.bin/cucumber-js ./test/BDD/**/*.feature -f node_modules/cucumber-pretty -f json:./test/report/cucumber_report.json --require-module ts-node/register --require ./test/**/*.ts Error: Parse error in 'test/BDD/step-definition.ts': (1:1): expected: #EOF, #Language, #TagLine, #FeatureLine, #Comment, #Empty, got 'import { StepDefinitionCode, Given, When, Then, StepDefinitionOptions } from "cucumber";' at /builds/cristianmercado19/basic-package/node_modules/cucumber/src/cli/helpers.js:66:13 at Array.forEach () at forEach (/builds/cristianmercado19/basic-package/node_modules/cucumber/src/cli/helpers.js:54:10) at Generator.next () at Generator.tryCatcher (/builds/cristianmercado19/basic-package/node_modules/bluebird/js/release/util.js:16:23) at PromiseSpawn._promiseFulfilled (/builds/cristianmercado19/basic-package/node_modules/bluebird/js/release/generators.js:97:49) at /builds/cristianmercado19/basic-package/node_modules/bluebird/js/release/generators.js:201:15 at getTestCases (/builds/cristianmercado19/basic-package/node_modules/cucumber/lib/cli/helpers.js:102:18) at getTestCases (/builds/cristianmercado19/basic-package/node_modules/cucumber/src/cli/helpers.js:32:13) at Generator.next () at Generator.tryCatcher (/builds/cristianmercado19/basic-package/node_modules/bluebird/js/release/util.js:16:23) at PromiseSpawn._promiseFulfilled (/builds/cristianmercado19/basic-package/node_modules/bluebird/js/release/generators.js:97:49) at Promise._settlePromise (/builds/cristianmercado19/basic-package/node_modules/bluebird/js/release/promise.js:579:26) at Promise._settlePromise0 (/builds/cristianmercado19/basic-package/node_modules/bluebird/js/release/promise.js:619:10) at Promise._settlePromises (/builds/cristianmercado19/basic-package/node_modules/bluebird/js/release/promise.js:699:18) at _drainQueueStep (/builds/cristianmercado19/basic-package/node_modules/bluebird/js/release/async.js:138:12) Screenshot: My .gitlab-ci.yml configuration: image: node:latest stages: - build - test cache: paths: - node_modules/ install_dependencies: stage: build script: - npm install - npm build artifacts: paths: - node_modules/ testing_testing: stage: test script: npm test My cucumber folder structure: I have tried... to get the artifacts and compare the cucumber folder with my local. Both are the same. removing nyc updating packages versions this minimum script also fails "test": "./node_modules/.bin/cucumber-js test/BDD/**/*.feature --require-module ts-node/register --require ./test/**/*.ts", A: I do not know for what reason this script does not work in the GitLab CI (works in my local) "test": "nyc cucumber-js -f node_modules/cucumber-pretty -f json:./test/report/cucumber_report.json --require test/**/*.ts ./test/BDD/**/*.feature", Instead, I have extracted that configuration in a cucumber.js file let common = [ 'test/**/*.feature', '--require-module ts-node/register', '--require test/**/*.ts', '--format node_modules/cucumber-pretty', '--format json:./test/report/cucumber_report.json' ].join(' '); module.exports = { default: common, }; And replaced test script by: "test": "nyc ./node_modules/.bin/cucumber-js -p default",
{ "pile_set_name": "StackExchange" }
Q: Is coalescing triggered for accessing memory in reverse order? Let's say I have several threads and they access memory at addresses A+0, A+4, A+8, A+12 (each access = next thread). Such access is coalesced, right? However if I have access the same memory but in reverse order, meaning: thread 0 -> A+12 thread 1 -> A+8 thread 2 -> A+4 thread 3 -> A+0 Is coalescing here also triggered? A: Yes, for cc 2.0 and newer GPUs, coalescing will occur for any random arrangement of 32 bit data elements to threads, as long as all the requested 32-bit data elements are coming from (requested from) the same 128 byte (and 128 byte aligned) region in global memory. The GPU has something like a "crossbar switch" in the memory controller that will distribute elements as needed. You may be interested in this GPU webinar which discusses coalescing and will illustrate this particular case pictorially (on slide 12). The NVIDIA webinar page has other useful webinars you may be interested in as well. For pre-cc2.0 devices the specifics vary by compute capability, but compute 1.0 and 1.1 capable devices do not have this ability to coalesce reads that are in "reverse order" or random order.
{ "pile_set_name": "StackExchange" }
Q: Logging out of Stack Overflow or any Stack Exchange site? I want to log out of Stack Overflow or any Stack Exchange site, but always it shows me logged in! How do I log out of this site? Note: I have yet to register; the site currently always shows my name and default email. I wish to log out so that I may start a new session! A: Use the logout button at the top of the page? Also, nominally belongs on 'Meta'. Note that since this question was asked and answered, the site has changed multiple times. As of 2014-03-14, there is a logout link accessible from the black top bar; activate the 'Stack Exchange' drop down menu and the 'logout' link should be beside the entry for the site you're currently accessing (along with 'blog' and 'chat'). However, this question is a duplicate of another, and you should consult the other question for more information — or add comments to that question — rather than add to this one. As of 2017-03-20, the 'logout' option is on the drop-down menu from the right-most icon on the menu bar: There will be other changes in future; you will need to search for it.
{ "pile_set_name": "StackExchange" }
Q: How can I check the version of sed in OS X? I know if sed is GNU version, version check can be done like $ sed --version But this doesn't work in OS X. How can I do that? A: This probably isn't the answer you're looking for, but you can't. Mac OS X sed has no option to show the version number. There is not even a version number in the binary: $ strings $(which sed) $FreeBSD: src/usr.bin/sed/compile.c,v 1.28 2005/08/04 10:05:11 dds Exp $ $FreeBSD: src/usr.bin/sed/main.c,v 1.36 2005/05/10 13:40:50 glebius Exp $ $FreeBSD: src/usr.bin/sed/misc.c,v 1.10 2004/08/09 15:29:41 dds Exp $ $FreeBSD: src/usr.bin/sed/process.c,v 1.39 2005/04/09 14:31:41 stefanf Exp $ @(#)PROGRAM:sed PROJECT:text_cmds-88 malloc %lu: %s: unexpected EOF (pending }'s) 0123456789/\$ %lu: %s: command expected %lu: %s: invalid command code %c %lu: %s: command %c expects up to %d address(es), found %d %lu: %s: unexpected } %lu: %s: extra characters at the end of %c command %lu: %s: command %c expects \ followed by text %lu: %s: extra characters after \ at the end of %c command %lu: %s: filename expected w command read command branch label %lu: %s: empty label %lu: %s: substitute pattern can not be delimited by newline or backslash %lu: %s: unterminated substitute pattern %lu: %s: extra text at the end of a transform command %lu: %s: unterminated regular expression %lu: %s: expected context address realloc %lu: %s: whitespace after %s %lu: %s: duplicate label '%s' %lu: %s: RE error: %s %lu: %s: \ can not be used as a string delimiter %lu: %s: newline can not be used as a string delimiter %lu: %s: unbalanced brackets ([]) bin/sed Unix2003 123456789 %lu: %s: \%c not defined in the RE %lu: %s: unescaped newline inside substitute pattern %lu: %s: unterminated substitute in regular expression %lu: %s: more than one number or 'g' in substitute flags %lu: %s: overflow in the 'N' substitute flag %lu: %s: no wfile specified %lu: %s: bad flag in substitute command: '%c' %lu: %s: transform pattern can not be delimited by newline or backslash %lu: %s: unterminated transform source string %lu: %s: unterminated transform target string %lu: %s: transform strings are not the same length %lu: %s: undefined label '%s' %lu: %s: unused label '%s' Eae:f:i:ln setlinebuf() failed stdout "%s" ..." -i may not be used with stdin stdin rename() %s: %s %s in-place editing only works for regular files %s: name too long %s/.!%ld!%s %s: %s usage: sed script [-Ealn] [-i extension] [file ...] sed [-Ealn] [-i extension] [-e script] ... [-f script_file] ... [file ...] first RE may not be empty RE error: %s %lu: %s: \%d not defined in the RE COLUMNS \abfrtv \%03o A: Looking though the various version of sed in text_cmds there are not many changes. 10.0.0 Used NetBSD sed from fall 1998 10.3.0 Used FreeBSD sed from fall 2002 but left the man-page unchanged, adding -E extended regular expressions and -i in-place editing. 10.4.0 Had some fixes for in-place editing, and changed the man-page to the FreeBSD man-page from fall 2004. 10.5.0 Updated to FreeBSD sed from fall 2005, adding -l line-buffered output and more refinements/fixes to in-place editing. 10.6.0 Added a reference to compat(5) in the man-page. The version of the operating-system can be checked, instead of the sed utility, by either using uname -r or sw_vers -productversion: case $(sw_vers -productversion) in 10.[012].*) echo no in-place editig, EREs, or line-buffered output;; 10.[45].*) echo no line-buffered output;; 10.[6789].*) echo newest version as of writing;; 10.1[01].*) echo newest version as of writing;; esac (BSD utilities are not versioned because they are considered part of their operating-system)
{ "pile_set_name": "StackExchange" }
Q: How to create a new directory from Force Fortran 2.0 I need to create a new directory from my code to be able to write a data file to it. I am using Force Fortran 2.0 from Windows 8 and I am also wondering if this syntax is going to vary from one operating system to the other due to the front/backslash issue. A: Force Fortran uses older compilers (g77, g95, gfortran [unknown version]), so I'll present a solution with system. For compilers that support it, it's better to use the Standard-conforming EXECUTE_COMMAND_LINE. You can simply use mkdir, which is present on both Windows and Unix machines. By default, mkdir creates the folder and (non-existing) parent folders on Windows. This has to be explicitly given on Unix (-p). Using system you can execute this from Fortran: program test implicit none #ifdef _WIN32 character(len=*),parameter :: MKDIR = 'mkdir ' ! ^ ! The blank is intentional! #else character(len=*),parameter :: MKDIR = 'mkdir -p ' ! ^ ! The blank is intentional! #endif integer :: stat stat = system( MKDIR // 'testFolder' ) if ( stat /= 0 ) then print *, 'mkdir: failed to create folder! ' endif end program You still need to create a routine that takes care of the correct folder delimiter, here is a quick&dirty example: module conv_mod contains function conv2win(str) result(res) implicit none character(len=*),intent(in) :: str character(len=len(str)) :: res integer :: i res = str do i=1,len(res) if ( res(i:i) == '/' ) res(i:i) = '\' enddo ! i end function function conv2unix(str) result(res) implicit none character(len=*),intent(in) :: str character(len=len(str)) :: res integer :: i res = str do i=1,len(res) if ( res(i:i) == '\' ) res(i:i) = '/' enddo ! i end function end module program conv use conv_mod print *,conv2win('some/path') print *,conv2win('some\path') print *,conv2unix('some\path') end program This doesn't take care of things like C:\, though... As @VladimirF noted, you can use / in Windows, too. You would still need to convert the backslash to / in Unix.
{ "pile_set_name": "StackExchange" }
Q: Orthogonal Trajectories of Cassinian Curves Preamble The Cassinian curves are the pre-images of concentric circles (centered at $1+0\,i$) under the map $z\mapsto z^2$. Using this fact and the fact that complex polynomials are conformal we can deduce that the orthogonal trajectories to the Cassinian curves map to straight lines passing through the point $1+0\,i$. These lines can be writen as $$w(\lambda) = 1 + \lambda \,e^{i\theta}$$ Where $\theta$ is the angle the line makes with the real axis. Applying the function $z\mapsto \sqrt{z}$ to these lines then gives us back the othogonal trajectories to the Cassinian curves. Question The book I am working through asks the reader to use this to show that the orthogonal trajectories are hyperbolae but I can't seem to make much headway with it. How does one show this? Attempt I tried expanding the real and imaginary components of the line ($w=u+i\,v$) and its image ($z=x+i\,y$), equating $z=\sqrt{w}$ and squaring both sides, which gives $$x^2-y^2 + 2 i\,xy = \underbrace{1+\lambda\,\cos(\theta)}_u + i\,\underbrace{\lambda\sin(\theta)}_v$$ but apart from the fact we have $x^2-y^2$ in there this doesn't seem so useful to me. It might also be useful to note that the orthogonal trajectories must pass through $z=\pm 1$. A: The preimage of the real line under $f(z) = z^2$ is not a hyperbola, it's the limiting case, the two coordinate axes. For all other straight lines passing through $1$, let us describe them by an equation: $L_c = \{ u+i v : u-1 = cv\}$, and let $H_c = f^{-1}(L_c)$. For $H_c$, we then obtain the describing equation $$x^2-y^2-1 = c(2xy)\qquad \text{resp.} \qquad x^2 - 2cxy - y^2 = 1.\tag{1}$$ That is the equation of a hyperbola, but not yet in standard form (except for $c = 0$). We obtain an equation in standard form by rotating the coordinate system. Let $\alpha = \frac{1}{2} \arctan c$. Then we can write $(1)$ as $$\begin{align} x^2 - 2xy\tan 2\alpha - y^2 &= 1\\ x^2\cos 2\alpha - 2xy\sin 2\alpha - y^2\cos 2\alpha &= \cos 2\alpha\\ (x\cos\alpha - y\sin\alpha)^2 - (x\sin\alpha + y\cos\alpha)^2 &= \cos 2\alpha \end{align}$$ and in the rotated coordinates $$\begin{pmatrix}\xi\\ \eta\end{pmatrix} = \begin{pmatrix}\cos\alpha & -\sin\alpha\\ \sin\alpha &\cos\alpha \end{pmatrix} \begin{pmatrix} x \\ y\end{pmatrix}$$ we have the standard form $$\xi^2 - \eta^2 = \cos 2\alpha.\tag{2}$$ Thus we obtain $$H_{c} = e^{\large -\frac{i}{2}\arctan c}\cdot \left\{\xi + i\eta : \xi^2-\eta^2 = \frac{1}{\sqrt{1+c^2}}\right\}.$$
{ "pile_set_name": "StackExchange" }
Q: How to Customize Humanized Moment js Date Result I want to customize the humanize date result with moment js. Let's say I have a date and I want to take the remaining time that return back a result "in 3 months" moment("20141001", "YYYYMMDD").fromNow(); // in 3 months How can I customize the resultant string like 3 months left ? Is moment provide any external parameter to customize the resultant or any other way I can achieve this? A: "Like moment#fromNow, passing true as the second parameter returns value without the suffix. This is useful wherever you need to have a human readable length of time." Moment documentation So, var start = moment([2007, 0, 5]); var end = moment([2007, 0, 10]); start.from(end); // "in 5 days" start.from(end, true); // "5 days" start.from(end, true) + " left"; // "5 days left"
{ "pile_set_name": "StackExchange" }
Q: NameError : name 'pass_result' not defined line 25? Index.html: <html> <head> <title>Login Page</title> <link type="text/css" rel="stylesheet" href="coach.css" /> </head> <body> <img src="images/logo-cel-transparent_0.png" width="74" height="64"><strong><img src="images/logo-cel-transparent_0.png" alt="Cel logo" width="74" height="64" align="right"> </strong> <h1 align="center"><strong>Central Electronics Limited</strong></h1> <p>&nbsp;</p> <h2 align="center">Storage Management System</h2> <p>&nbsp;</p> <p align="center">Login To System</p> <p align="center">&nbsp;</p> <form action="cgi-bin/validate.py" method="post"> <div align="center">Username : <input type="text" name="username"> <br> Password : <input type="text" name="password"> <br> <input type="submit" value="Submit"> </div> </form> <p align="center">&nbsp;</p> </body> </html> validate.py: import cgi import yate import sqlite3 import sys connection = sqlite3.connect('users.sqlite') cursor = connection.cursor() print('Content-type:text/html') form=cgi.FieldStorage() for each_form_item in form.keys(): if (each_form_item=='username'): username=form[each_form_item].value if (each_form_item=='password'): password=form[each_form_item].value result=cursor.execute('SELECT USERNAME from validate') usernames=[row[0] for row in result.fetchall()] print(usernames) for each_username in usernames: if (username==each_username): pass_result=cursor.execute('SELECT PASSWORD from validate where username=?',(each_username,)) password1=[row[0] for row in pass_result.fetchall()] for each_password in password1: if (each_password==password): with open("C:\Python34\ProjectShivam\webapp\cgi-bin\successvalidate.py") as f: code = compile(f.read(), "successvalidate.py", 'exec') exec(code) else: print('') print('Login Failure') successvalidate.py: import yate print(yate.start_response()) print(yate.para("Login Successful")) print(yate.include_footer({"Click here to Go to Welcome Page":"/welcome.html"})) simple_httpd.py(The server code): from http.server import HTTPServer, CGIHTTPRequestHandler port = 8080 httpd = HTTPServer(('', port), CGIHTTPRequestHandler) print("Starting simple_httpd on port: " + str(httpd.server_port)) httpd.serve_forever() I run the server(simple_httpd.py) using command prompt. The index page opens up. I enter the 1st set of username and password. It runs as expected and successvalidate.py opens up. But when i enter the 2nd set of username and password(i.e, the second row of table validate in users.sqlite)(validate table contains two set of usernames and passwords), it displays on cmd: 127.0.0.1 - - [18/Jun/2015 20:59:29] b'Traceback (most recent call last):\r\n F ile "C:\\Python34\\ProjectShivam\\webapp\\cgi-bin\\validate.py", line 25, in <mo dule>\r\n password1=[row[0] for row in pass_result.fetchall()]\r\nNameError: name \'pass_result\' is not defined\r\n' Also any other username does not result in the text 'Login Failure' being printed on the web browser but instead same error shows on server. What is wrong? A: you are getting the error when this condition is not met: if (username==each_username): pass_result=cursor.execute('SELECT PASSWORD from validate where username=?',(each_username,)) set a default value to pass_result, e.g. pass_result = None and then handle it before using, e.g. if pass_result is not None:
{ "pile_set_name": "StackExchange" }
Q: Automatic download from jQuery POST request I have a jQuery click event that makes a POST request to a PHP script that generates an XLS file. The PHP script returns the appropriate headers. When manually setting post variables and requesting RAW I see everything returns properly. I can even see this in firebug's console. The automatic "Save or Open" download box is not coming up however. I can not simply do: window.location = ./path/to/generator.php since the XLS returned is dependent on the POST variables passed. How can I achieve similar functionality. A: I don't think you can actully. Try to send the POST to your PHP script, generate the file and save it in the cache. Response to the client with the cache ID, and redirect the client so it makes a new GET request. Send the cached file with the modified headers.
{ "pile_set_name": "StackExchange" }
Q: Confirmation of thread safety with std::unique_ptr/std::shared_ptr My application has an IRC module that essentially is a normal client. Since this is heavily threaded, I stand the risk of a plug-in retrieving, for example, a users nickname - it is valid at the time, but the parser triggers an update, changing said nickname. Once the other thread has execution again, it's dealing with a pointer to now-invalid memory, since it'll be impossible to have the return + copy as an atomic operation. Is my assumption about this correct, based on the code below? As such, I guess I'd have to use the usual mutex lock/unlock method, unless someone can confirm or suggest otherwise (I'd rather not have to convert and return a shared_ptr, but I guess it is a valid option, it's just I intend on SWIG'ing this and don't know if it wouldn't like them). IrcUser.h class IrcUser : public IrcSubject { private: ... std::shared_ptr<std::string> _nickname; std::shared_ptr<std::string> _ident; std::shared_ptr<std::string> _hostmask; public: ... const c8* Ident() const { return _ident.get()->c_str(); } const c8* Hostmask() const { return _hostmask.get()->c_str(); } const u16 Modes() const { return _modes; } const c8* Nickname() const { return _nickname.get()->c_str(); } bool Update( const c8 *new_nickname, const c8 *new_ident, const c8 *new_hostmask, const mode_update *new_modes ); }; IrcUser.cc bool IrcUser::Update( const c8 *new_nickname, const c8 *new_ident, const c8 *new_hostmask, const mode_update *new_modes ) { if ( new_nickname != nullptr ) { if ( _nickname == nullptr ) { *_nickname = std::string(new_nickname); } else { _nickname.reset(); *_nickname = std::string(new_nickname); } Notify(SN_NicknameChange, new_nickname); } ... } A: I'd suggest that locking on such finegrained levels is likely (way) overkill. I'd suggest doing atomic updates to the IrcUser object itself, which could be lock-free depending on your library implementation and target architecture. Here is a sample that uses std::atomic_is_lock_free<std::shared_ptr> std::atomic_load<std::shared_ptr> std::atomic_store<std::shared_ptr> See http://en.cppreference.com/w/cpp/memory/shared_ptr/atomic for documentation. Disclaimer I don't know how many compilers/C++ library implementations already implement this C++11 feature. Here's what it'd would look like: #include <atomic> #include <memory> #include <string> struct IrcSubject {}; typedef char c8; typedef uint16_t u16; typedef u16 mode_update; class IrcUser : public IrcSubject { private: // ... std::string _nickname; std::string _ident; std::string _hostmask; u16 _modes; public: IrcUser(std::string nickname, std::string ident, std::string hostmask, u16 modes) : _nickname(nickname), _ident(ident), _hostmask(hostmask), _modes(modes) { } // ... std::string const& Ident() const { return _ident; } std::string const& Hostmask() const { return _hostmask; } const u16 Modes() const { return _modes; } std::string const& Nickname() const { return _nickname; } }; //IrcUser.cc bool Update(std::shared_ptr<IrcUser>& user, std::string new_nickname, std::string new_ident, std::string new_hostmask, const mode_update *new_modes ) { auto new_usr = std::make_shared<IrcUser>(std::move(new_nickname), std::move(new_ident), std::move(new_hostmask), *new_modes /* ??? */); std::atomic_store(&user, new_usr); //Notify(SN_NicknameChange, new_nickname); return true; } bool Foo(IrcUser const& user) { // no need for locking, user is thread safe } int main() { auto user = std::make_shared<IrcUser>("nick", "ident", "hostmask", 0x1e); mode_update no_clue = 0x04; Update(user, "Nick", "Ident", "Hostmask", &no_clue); { auto keepref = std::atomic_load(&user); Foo(*keepref); } } A: The code has a race condition, and therefore undefined behaviour, as there is a potential read (the ->get()) and write (the .reset() or =) on the same object (a std::shared_ptr<std::string> instance) from separate threads: access to the std::shared_ptrs must be synchronized. Note locking a std::mutex within the getter and returning the c_str() is insufficient as the caller of the getter would be using the result of c_str() outside of the lock: the getter needs to return a shared_ptr by value. To correct: add a std::mutex to IrcUser (note this now makes the class non-copyable): mutable std::mutex mtx_; // Must be mutable for use within 'const' lock the std::mutex in the getters and Update(), using a std::lock_guard for exception safety: std::shared_ptr<std::string> Nickname() const { std::lock_guard<std::mutex> l(mtx_); return _nickname; } bool IrcUser::Update(const c8 *new_nickname, const c8 *new_ident, const c8 *new_hostmask, const mode_update *new_modes) { if (new_nickname) { { std::lock_guard<std::mutex> l(mtx_); _nickname.reset(new std::string(new_nickname)); } // No reason to hold the lock here. Notify(SN_NicknameChange, new_nickname); } return true; } Consider just using a std::string if the copying is acceptable as the shared_ptr may be adding unnecessary complexity.
{ "pile_set_name": "StackExchange" }
Q: I can't fail an MVC view test on an error I use templated helpers in an ASP.NET MVC 3 project. One display template had a typo -- an accidental extra code block -- that caused a compiler error when that view was returned ("Don't put @if in a code block," you know). All fine, except that the test method that called that view was still succeeding. I'm having a hard time figuring out how I would fail this code block in a unit test. Here's the bad display template: @model MemberSelectorViewModel @{ Layout = "~/Views/Shared/_DisplayFormItem.cshtml"; } @section DataContent { @{ // <- this was the typo, and it... @if (Model.idMember.HasValue) // <- causes this to throw a compiler error { @Html.ActionLink(Model.FullName, "Details", "Member", new { id = Model.idMember.Value }, null ) @Html.HiddenFor(m=> m.idMember) } } } Here's the test that I think ought to be failing: [TestMethod] public void DetailsReturnsView() { MemberJobController target = new MemberJobController(TestHarness.Context); memberjob mj = TestHarness.UnitOfWork.MemberJobRepository.FirstOrDefault(x => true); ActionResult result = target.Details(mj.idmemberjob); // <- this should hit the compiler error, I would have thought Assert.IsNotNull(result); } But that test succeeds. Any idea how I'd write a test that would fail on the " @{ @if () " typo in a templated helper? A: I think you might have misunderstood something about how unit tests work on a controller. They never hit the view actually. So no matter how many errors you did in your view, when you call the controller action in a unit test, all that happens is that the body of this action is executed. And that's all. It will never go to the view. So if you want to test your views you are no longer doing unit tests. You are doing integration tests where you send an HTTP request to your site which is deployed on a staging server and verifying that the returned HTML complies to your requirements. In this case if you made a typo or something in your view the actual HTML which is returned when you hit the particular controller action with an HTTP request will obviously differ than what you expect.
{ "pile_set_name": "StackExchange" }
Q: Hyperlinks in JLabels This is the code I have in a file called Test2.java in a package called test2 in a project called Test2; package test2; import javax.swing.JFrame; public class Test2 { public static void main(String[] args) { JFrame mainWindow = new HtmlWindow("<html>" + "<a href=\"http://stackoverflow.com\">" + "blah</a></html>"); mainWindow.setVisible(true); } } In the same package I have this code in a file called HtmlWindow.java ; package test2; import java.awt.BorderLayout; import java.awt.Container; import javax.swing.JFrame; import javax.swing.JLabel; class HtmlWindow extends JFrame { public HtmlWindow(String refreshGrid) { super("blah"); setSize(300, 100); Container content = getContentPane(); String labelText = refreshGrid; JLabel coloredLabel = new JLabel (labelText, JLabel.CENTER); content.add(coloredLabel, BorderLayout.NORTH); } } When I run the project, I get a window with the word "blah" in the expected location, blue and underlined, but the cursor does not change when I hover over the word, nor does anything happen when I click on it. My questions are as follows; Is it possible to put hyperlinks in jLabels? If so, am I doing something wrong, or is the programme not running properly? If not, what is a good alternative? The reason I am not using JButtons, is that eventually I want to create a grid of an arbitrary number of hyperlinks, and I want the hyperlinks to be images, and whilst JButtons can have images on them, I don't want the hyperlinks to look like "buttons". I suppose I could use a non-editable JEditorPane? A: Swing is not a fully functioned browser. It supports simple HTML including links but do not change the cursor style automatically. As far as I know you have to do it programmatically, i.e. add mouse listener to your label and change the cursor style when your mouse is over your label. Obviously you can write your own class LinkLabel that implements this logic and then use it every time you need. A: It does not seem that just by doing a hyper link you will get your usual web browser behaviour. According to examples on line, what is usually done is to implement an ActionListener on the JLabel and call Desktop.getDesktop().browse(new URI("..."));. The problem with this call is that it does not seem to work with all operating systems. What you could do would be to see if you can open the link in a browser from command line, if you can do this, you should be able to do what you need by using the exec method from the Process class. This will however, most likely be platform dependant. That being said, it is of my opinion that labels should be used to depict text (even though I think that upon seeing a link, the user sort of knows what will happen, so I think that in this case, we can call it as an exception). If you want to have a component which triggers and action you could use a JButton instead.
{ "pile_set_name": "StackExchange" }
Q: Can a Twilio SMS number be sent via email to one of the big carriers? I have a service that sends me SMS messages, and I'd like to filter them with a Twilio number. So I have a Twilio phone number now. However, when I sign up for the service, I have to give my SMS number, AND the "Carrier" which that number is on... and they list the usual suspects, Verizon, AT&T, Sprint, T-Mobile, etc. I'm guessing they do the "[email protected]" or whatever so the service sends email, and then you get a text. SO: Can I name one of the major carriers for my Twilio number? If so, which one? Thanks! A: This is not possible and here is why. They are not actually sending you an SMS. They are sending you an email which your phone provider then converts to an SMS and sends to your phone. Twilio does not have a system like that. Every carrier allows this. For example.. Carrier Email to SMS Gateway Alltel [10-digit phone number]@message.alltel.com Example: [email protected] AT&T (formerly Cingular) [10-digit phone number]@txt.att.net [10-digit phone number]@mms.att.net (MMS) [10-digit phone number]@cingularme.com Example: [email protected] Boost Mobile [10-digit phone number]@myboostmobile.com Example: [email protected] Nextel (now Sprint Nextel) [10-digit telephone number]@messaging.nextel.com Example: [email protected] Sprint PCS (now Sprint Nextel) [10-digit phone number]@messaging.sprintpcs.com [10-digit phone number]@pm.sprint.com (MMS) Example: [email protected] T-Mobile [10-digit phone number]@tmomail.net Example: [email protected] US Cellular [10-digit phone number]email.uscc.net (SMS) [10-digit phone number]@mms.uscc.net (MMS) Example: [email protected] Verizon [10-digit phone number]@vtext.com [10-digit phone number]@vzwpix.com (MMS) Example: [email protected] Virgin Mobile USA [10-digit phone number]@vmobl.com Example: [email protected] What you could do is set up your own so that it converts an email to sms and then sends it to you, then contact whoever you are having send you those messages and have them add your name to the list they support. Here is even a blog to help you get started https://www.twilio.com/blog/2014/05/send-and-receive-sms-messages-via-email-with-twilio-and-sendgrid.html
{ "pile_set_name": "StackExchange" }
Q: Simplest way to create drop down menu on a web page? I am creating a small project on ASP.NET. I want a simple drop down menu. Most of the solutions on web use jquery. Is there any simpler way or should I learn jquery ? One more thing. The menu should work on IE. A: Some of the cleanest drop down implementations I have seen are based on semantic HTML (unordered lists, nav element(s), etc.) and the CSS :hover pseudo class. Semantic structures degrade nicely when script is not available and are interpreted well when consumed by devices like screen readers. Older versions of IE which do not support the :hover pseudo class can be accommodated with a snippet of script (no jQuery required). Suckerfish/Son of Suckerfish is a good example of this technique. Code/Description Examples Example Here is the simplest implementation I could create which works in IE7+, Chrome, FF, etc. No script required. Complete sample: http://jsfiddle.net/BejB9/4/ HTML I'd wrap this in a nav tag in a finished document <ul class="nav"> <li>This item has a dropdown <ul> <li>Sub item 1</li> <li>Sub item 2</li> </ul> </li> <li>Item</li> <li>So does this item <ul> <li>Sub item 1</li> <li>Sub item 2</li> </ul> </li> </ul> CSS UL.nav > LI { list-style: none; float: left; border: 1px solid red; position: relative; height: 24px; /* height included for IE 7 */ } UL.nav UL{ left: -10000px; position: absolute; } UL.nav > LI:hover UL{ left: 0; top: 24px; /* IE7 has problems without this */ } ​
{ "pile_set_name": "StackExchange" }
Q: Import Tag from xml file to another using JAVA I do my work with this piece and my problem is simple. Just changing the place of transfer. I did not know what is the matter responsible for determining the place of transportation in the first or last content. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; Document doc = null; Document doc2 = null; String a = "E:\\1.xml" ; String c ; try { db = dbf.newDocumentBuilder(); doc = db.parse(new File(a)); doc2 = db.parse(new File("E:\\L (1).xml")); NodeList ndListFirstFile = doc.getElementsByTagName("med"); Node nodeArea = doc.importNode(doc2.getElementsByTagName("end").item(0), true); NodeList nList2 = doc2.getElementsByTagName("end"); for (int i = f; i <g; i++) { c = +i+"" ; doc2 = db.parse(new File("E:\\L ("+c+").xml")); for (int temp = 0; temp < nList2.getLength(); temp++) { nodeArea = doc.importNode(doc2.getElementsByTagName("end").item(temp), true); ndListFirstFile.item(0).appendChild(nodeArea); } } This is done from two files, and it works well, but the place of transferring the tag is at the end of the content. I want it at the beginning of the content <med> I move the Tag "dat" and it is moved at the end of the Tag "med" content <dat>We have come to the wrong place, my friend</dat></med> <med><dat>We want to get better here</dat> I want to move Tag dat To be the first content from Tag med </med> That's it A: From the appendChild docs: Adds the node newChild to the end of the list of children of this node. So it is adding it to the end as expected. To insert it before any other element on that node, you can try: ndListFirstFile.item(0).insertBefore(nodeArea, ndListFirstFile.item(0).getFirstChild());
{ "pile_set_name": "StackExchange" }
Q: How to convert Drupal 6 profile taxonomy value to array? In Drupal 6, Profile module stores taxonomy values for users with this format: a:3:{s:17:"Local Development";s:17:"Local Development";s:35:"Environmental Policy and Management";s:35:"Environmental Policy and Management";s:22:"Environmental Research";s:22:"Environmental Research";} Is there a way to programmatically convert that to an array using PHP and/or Drupal 7 functions? This is the array I would like to obtain: Local Development Environmental Policy and Management Environmental Research A: The drupal stores the users data in serialized format to get it in array format you can use unserialize ( string $str [, array $options ] ) function in php. here is the example for you to get better understanding PHP : unserialize() function
{ "pile_set_name": "StackExchange" }
Q: Firebase Email/PW Auth Won't Register I have a simple app that allows users to register to Firebase through the Auth method. Here's my code: public class SignUpActivity extends AppCompatActivity { private FirebaseAuth mAuth; private EditText tbemail; private EditText tbpassword; private Button btnCreate; private Button btnSignIn; private String str_email; private String str_password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_up); mAuth = FirebaseAuth.getInstance(); //GUI DECLARATIONS tbemail = (EditText) findViewById(R.id.tb_email); tbpassword = (EditText) findViewById(R.id.tb_password); btnCreate = (Button) findViewById(R.id.btn_create); btnSignIn = (Button) findViewById(R.id.btn_signin); btnCreate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { str_email = tbemail.getText().toString().trim(); str_password = tbpassword.getText().toString().trim(); mAuth.createUserWithEmailAndPassword(str_email, str_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ //TASK SUCCESSFUL Toast.makeText(SignUpActivity.this, "User Created Successfully!", Toast.LENGTH_LONG).show(); } else { //TASK ERROR Toast.makeText(SignUpActivity.this, "There was an error. Please Try Again.", Toast.LENGTH_LONG).show(); } } }); } }); btnSignIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent signInIntent = new Intent(SignUpActivity.this, MainActivity.class); finish(); startActivity(signInIntent); } }); } } But when I tried inputing the textboxes and hitting "Create User" it gives me the "Sorry there was an error..." toast suggesting it failed in registering the new user. Logcat says E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb2b31680Any ways to fix this? Update I already connected my project to firebase; just in case you're wondering. Update 2 It suddenly showed me this in logcat Local module descriptor class for com.google.firebase.auth not found. Just now. (I didn't do anything) A: Check this in your fire base console Authentication -> Sign-In-Method -> Email/Password is enable. In the Firebase console, open the Authentication section. On the Sign in method tab, enable the Email/password sign-in method and click Save. you must add Internet permission in AndroidManifest.xml file <uses-permission android:name="android.permission.INTERNET" /> The possible reasons for failure are: The email address is malformed Sign-in by email/password is disabled The user account corresponding to the email does not exist or has been deleted The user account corresponding to the email has been disabled The password is wrong The user's token is not valid
{ "pile_set_name": "StackExchange" }
Q: Why place all of your Javascript code in one file? Why place all of your Javascript code in one file? Is it possible and is it make sense to split into smaller logical file units? A: With only one JS file you would get less HTTP header overhead. In regards to web development: you have to fit your target audience. Web traffic is expensive, so you must minimize the web traffic and maximize the message. A: You can have two different "builds" of the JS code. One nice, modular version that you write, then use Google's JS compiler to build a fast, optimized, small version for live use. A: Yep. Looking at the source to this page alone, I see at least four javascript files referenced, plus an inline script element on the page itself. You should split up your files however you think it's appropriate. Most of the time you'll have a library of related classes and methods all in one file, or maybe in separate files that can be included by calling an intermediate file that's responsible for, in turn, including all the others. Logical grouping is key. On the other hand, when you run a site like SO, there are other things to take into account - if you put all your javascript in separate files, that's at least four (for this page) separate requests to the server (or to several servers) to load the page, which could mean gigabytes of bandwidth just in additional HTTP headers if you run a popular site, and might be a compelling reason to consolidate your javascript files. Not many people have to worry about that, but it pays to think about these things.
{ "pile_set_name": "StackExchange" }
Q: How do you index incomplete strings to JSON keys? I would like to be able to type in "Hammerhead" to call the "Hammerhead Shark" object without its full name. Is this possible and if so how? I tried using array.indexOf(string) though it doesn't really seem to help since it requires an exact match such as typing "Hammerhead Shark" JS: const JSON = require('animals.json'); var animals = Object.keys(JSON); if (animals.indexOf("Hammerhead")) { console.log(JSON["Hammerhead"].name); } JSON: { "Hammerhead Shark": { "name": "Shark", "age": "300" }, "Duck": { "name": "Duck", "age": "1000" } } I expect the output to be "Shark" instead of undefined. A: It seems you want to get access the value in object. By its partial name. Get the entries of object using Object.entries() Find the key which includes() the given partial key. return the second element of the found entry. const obj = { "Hammerhead Shark": { "name": "Shark", "age": "300" }, "Duck": { "name": "Duck", "age": "1000" } } function getValueByPartialKey(obj,key){ return (Object.entries(obj).find(([k,v]) => k.includes(key)) || [])[1] } console.log(getValueByPartialKey(obj,"Hammerhead"))
{ "pile_set_name": "StackExchange" }
Q: SVG thick curved paths not behaving as expected I'm creating a Sankey diagram in D3 using paths as chunky connectors to indicate flow. However, I'm finding the paths that are thicker than they are long start behaving really oddly. You can see an example here, where I'm splitting the path into sections: The blue and orange overlap, because the blue (and also the grey behind it) don't curve in the same way as the thinner paths, they've got a kind of "kink" in them. All the line curves work well, except these large ones. I made a simple example with just SVG: <SVG height=800 width=800> <g transform="translate(40,400)"> <Path class="link1" d="M29,-129C104.5,-129 104.5,-202.125 180,-202.125" /> <Path class="link2" d="M29,-129C104.5,-129 104.5,-202.125 180,-202.125" /> <Path class="link3" d="M29,-129C104.5,-129 104.5,-202.125 180,-202.125" /> <Path class="normal" d="M29,-129 L104.5,-129" /> <Path class="normal" d="M104.5,-202 L180,-202.125" /> </g> You can see it here: https://jsfiddle.net/hanvyj/t91pbp4w/ I couldn't find anything on google, I was hoping someone would have come across the issue and know a fix, or has more SVG experience and know a good alternative to 'SVG:Path' that wouldn't do this? A: SVG stroke-width behaving differently Problem example: <svg width="800px" height="600px" viewBox="0 0 100 100"> <path stroke-width="15" stroke="rgba(0,0,0,0.5)" fill="none" d="m0,40 c 20,0 20,-10 40,-10" /> <path stroke-width="3" stroke="rgba(0,0,0,0.5)" fill="none" D="m40,24 c 5,0 5,-5 10,-5" /> <path stroke-width="3" stroke="rgba(0,0,0,0.5)" fill="none" D="m40,27 c 5,0 5,-2 10,-2" /> <path stroke-width="3" stroke="rgba(0,0,0,0.5)" fill="none" D="m40,30 10,0" /> <path stroke-width="3" stroke="rgba(0,0,0,0.5)" fill="none" D="m40,33 c 5,0 5,2 10,2" /> <path stroke-width="3" stroke="rgba(0,0,0,0.5)" fill="none" D="m40,36 c 5,0 5,5 10,5" /> <path stroke-width="3" stroke="rgba(255, 200, 50, 0.7)" fill="none" d="m0,46 c 20,0 20,-10 40,-10" /> </svg> Solution: <svg width="800px" height="600px" viewBox="0 0 100 100"> <path stroke-width="15" stroke="rgba(0,0,0,0.5)" fill="none" d="m0,40 c 20,0 20,-10 40,-10" /> <path stroke-width="3" stroke="rgba(0,0,0,0.5)" fill="none" D="m40,24 c 5,0 5,-5 10,-5" /> <path stroke-width="3" stroke="rgba(0,0,0,0.5)" fill="none" D="m40,27 c 5,0 5,-2 10,-2" /> <path stroke-width="3" stroke="rgba(0,0,0,0.5)" fill="none" D="m40,30 10,0" /> <path stroke-width="3" stroke="rgba(0,0,0,0.5)" fill="none" D="m40,33 c 5,0 5,2 10,2" /> <path stroke-width="3" stroke="rgba(0,0,0,0.5)" fill="none" D="m40,36 c 5,0 5,5 10,5" /> <path stroke-width="3" stroke="rgba(255, 200, 50, 0.7)" fill="none" d="m0,46 c 22,0 22,-10 40,-10" /> </svg> Wait what did you do to the path? Lets take a look at the d attribute on those orange paths. Problem path: m0,46 c 20,0 20,-10 40,-10 Solution path: m0,46 c 22,0 22,-10 40,-10 I simply adjusted the C curve command by 2 units. I want pictures of the differences... ohhhh wel okay: A: While Persijn's solution was good, it wasn't quite perfect - it matched the curve of the 'overaying' thinner line to the underlying kinked line. Ideally, I wanted to remove the kink altogether. As maioman suggested, for this kind of shape it is probably best I define the full path and use fill, rather than stroke width. This gives me a lot more control. The stroke-width keeps the thickness constant throughout the lines length, that's not what I actually wanted and as people pointed out, it's impossible when the width is larger than it's length. I wanted the height in the x axis to be constant along it's length. I created a function that produces the shape I actually want, in case anyone comes across this: var linkPath = function(sourceTop,sourceBottom, targetTop,targetBottom) { //middle var MiddleDelta =(targetTop.x - sourceTop.x)/2; console.log(MiddleDelta); //start in the top left var d = "M"; //top left corner d += sourceTop.x + ", " + sourceTop.y + " "; d += "C" + (sourceTop.x+MiddleDelta) + "," + sourceTop.y + " "; d += (targetTop.x - MiddleDelta) + "," + targetTop.y + " "; //top right corner d += "" + targetTop.x + "," + targetTop.y + " "; //bottom right corner d += "L" + targetBottom.x + "," + targetBottom.y + " "; d += "C" + (targetBottom.x-MiddleDelta) + "," + targetBottom.y + " "; d += (sourceBottom.x + MiddleDelta) + "," + sourceBottom.y + " "; //bottom left corner d += "" + sourceBottom.x + "," + sourceBottom.y + " "; return d; }; It produces this: as oposed to this: A: Your line is so thick that when it follows the bezier curve, it passes outside the starting point of the other end of the line. Almost any non-straight bezier curve will have a limit on how thick it can get before it starts self-intersecting. You are just exceeding that limit here. If the start and end points were further apart, you would be able to get a bit thicker.
{ "pile_set_name": "StackExchange" }
Q: Invalid property name in a simple example I've copied this code from a book about Kivy and python main.py from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.properties import ObjectProperty from kivy.network.urlrequest import UrlRequest import json class AddLocationForm(BoxLayout): search_input = ObjectProperty() search_results = ObjectProperty() def search_location(self) : search_template = "http://api.openweathermap.org/data/2.5/find?q={}&type=like" search_url = search_template.format(self.search_input.text) request = UrlRequest(search_url, self.found_location) def found_location(self, request, data) : data = json.loads(data.decode()) cities = [ "{} ({})".format(d['name'], d['sys']['country']) for d in data['list'] ] self.search_results.item_strings = cities class WeatherApp(App): pass if __name__ == "__main__" : WeatherApp().run() weather.kv AddLocationForm: <AddLocationForm>: orientation: "vertical" search_input: search_box search_results: search_results_list BoxLayout: height: "40dp" size_hint_y: None TextInput: id: search_box size_hint_x: 50 Button: text: "Search" size_hint_x: 25 on_press: root.search_location() Button: text: "Current location" size_hint_x: 25 ListView: id : search_results_list item_strings: [] Why do I get the following error? Traceback (most recent call last): File "main.py", line 27, in <module> WeatherApp().run() File "C:\Kivy\kivy\kivy\app.py", line 765, in run self.load_kv(filename=self.kv_file) File "C:\Kivy\kivy\kivy\app.py", line 585, in load_kv root = Builder.load_file(rfilename) File "C:\Kivy\kivy\kivy\lang.py", line 1444, in load_file return self.load_string(data, **kwargs) File "C:\Kivy\kivy\kivy\lang.py", line 1491, in load_string parser = Parser(content=string, filename=fn) File "C:\Kivy\kivy\kivy\lang.py", line 1049, in __init__ self.parse(content) File "C:\Kivy\kivy\kivy\lang.py", line 1122, in parse objects, remaining_lines = self.parse_level(0, lines) File "C:\Kivy\kivy\kivy\lang.py", line 1218, in parse_level level + 1, lines[i:], spaces) File "C:\Kivy\kivy\kivy\lang.py", line 1228, in parse_level 'Invalid property name') kivy.lang.ParserException: Parser: File ".\weather.kv", line 21: ... 19: size_hint_x: 25 20: ListView: >> 21: id : search_results_list 22: item_strings: [] ... Invalid property name A: id : search_results_list It's because you have a space after id, it should be id: search_results_list If this is in the book, I guess it's a typo.
{ "pile_set_name": "StackExchange" }
Q: Odd structure - 何か 見つけました? Recently I have been enjoying the show Chii Sanpou. I expect a few of you have seen or heard of it. The former actor walking around parts of Japan. The Japanese is a mix of casual and polite. Anyway in one episode he spots something and the narrator says 何か、 見つけました? which to me is an odd pattern. I think it is "what did you see?". It appears to be polite Japanese but the structure is not what I have been taught. I would have expected 何を見つけましたか? I would like to know more about this other form. Is it appropriate for polite / formal Japanese or is it a bit slangy? Can I use it in business? A: なにか means "something/anything". 何を見つけましたか? -- "What did you find?" 何か見つけましたか? -- "Did you find something/anything?" The narration 「何か、見つけました?」 with a rising tone, with the question particle か dropped, can mean "Did he find anything?" (「何か見つけました。」 with a falling tone would mean "He found something.") It is the polite form / 丁寧形 and I don't think it's slangy. I think you can use it in business (though it might be more appropriate to use the honorific form / 尊敬語 depending on who performs the action). Similar examples: 誰かいましたか? (or いました?) -- Was anyone there? 誰がいましたか? (or いました?) -- Who was there? 何か食べましたか? (or 食べました?) -- Did you eat anything? 何を食べましたか? (or 食べました?) -- What did you eat?
{ "pile_set_name": "StackExchange" }
Q: How can i push to an custom typed array Im using Angular 5 with typescript 2.7.1. In typescript i have a custom type arr: {id: string; name: string; }[]; and i want to push an element to the array, and have tried the following: this.arr.push({id: "text", name: "text"}) ERROR TypeError: Cannot read property 'push' of undefined let array2 : {id: "id", name: "name"} this.arr.push(array2) ERROR TypeError: Cannot read property 'push' of undefined I don't understand why it wont work, I am defining id and name in push, I just want to add more elements to the array, am i missing something? A: You need to initialize the array with an empty array before you use the field: this.rows = []; Or directly upon declaration rows: {id: string; name: string; }[] = [];
{ "pile_set_name": "StackExchange" }
Q: Custom print of object in C# Interactive Consider this MCVE class: public class Foo<T> { private readonly T value; public Foo(T value) { this.value = value; } } When I evaluate and print such an object in C# Interactive, it looks like this: > new Foo<string>("bar") Foo<string> { } That's not useful. I'd like it to look like this: Foo<string> { "bar" } How do I do that? I've tried overriding ToString like this: public override string ToString() { return $"Foo{typeof(T)} {{ {value} }}"; } This doesn't produce quite what I'd like: > new Foo<string>("bar") [Foo<System.String> { bar }] There's at least three issues with this output: The value is not in quotes. I'd like it to be "bar" instead of bar. The type argument is displayed as System.String instead of string. The entire value is surrounded by square brackets. This is the least of my concerns. Is there a way to make C# interactive display an object with a custom format? I know that I can add a public property to the class in order to display the value, but I don't want to do that because of encapsulation concerns. To be clear, though, here's what I mean: public class Foo<T> { public Foo(T value) { Value = value; } public T Value { get; } } This prints closer to what I'd like: > new Foo<string>("bar") Foo<string> { Value="bar" } but, as I wrote, I don't want to add a public property. How do I get it to behave like the following? > new Foo<string>("bar") Foo<string> { "bar" } > new Foo<int>(42) Foo<int> { 42 } Notice that when using anything else than a string (e.g. an int), there should be no quotes. A: You could use the [DebuggerDisplay] attribute to customize the object print. Beside overriding ToString(), you can use any methods/properties in this attribute. For example: [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] public class Foo<T> { private readonly T value; public Foo(T value) { this.value = value; } private string GetDebuggerDisplay() { var val = value is string ? "\"" + value + "\"" : value?.ToString(); return $"Foo<{typeof(T).Name.ToLower()}> {{ {val} }}"; } } This avoids having to override ToString(), or use a different implementation. Such as returning the string representation of T value. You'll need to add a switch/case to transform class names such as Int32 to int. The nq part of the [DebuggerDisplay] attribute removes the quotes around the value. The result looks like: > new Foo<string>("bar") Foo<string> { "bar" } For further reference, please check out the excellent blog post of Jared Parson about the [DebuggerDisplay] attribute: https://blogs.msdn.microsoft.com/jaredpar/2011/03/18/debuggerdisplay-attribute-best-practices/. A: As Kristian Hellang suggests, this can be simply and easily addressed by adding a [DebuggerDisplay] attribute to the class: [DebuggerDisplay("{ value }")] public class Foo<T> { private readonly T value; public Foo(T value) { this.value = value; } } This addresses all concerns: > new Foo<string>("bar") Foo<string>("bar") > new Foo<int>(42) Foo<int>(42) > new Foo<DateTime>(new DateTime(2018, 4, 23)) Foo<DateTime>([23.04.2018 00:00:00]) The rendering doesn't use curly brackets, but rather the normal brackets indicated by the constructor, but I only find that appropriate.
{ "pile_set_name": "StackExchange" }
Q: Alternative chmod for git hook in Windows 7 I am trying to activate one git hook under Windows 7, but I don´t find the alternative to chmod +x post-commit (in my case) in this operating system, with Unix is working correctly Thanks for your help. A: There's no chmod needed. Just call the file post-commit and you're done. If you have for example a perl file, you'll need a shebang: #!/usr/bin/perl -w
{ "pile_set_name": "StackExchange" }
Q: get keywords in input and store them in an array with jquery I was wondering how I could store a query such as this in an array : "hello again world" the keywords would be in an input field with id = status, and would have to be split by " ". Also how would I escape certain words and characters in this array as matched by the words/characters in the array stopwords A: //split the words by space var keywds = $("#status").val().split(" "); $.each(keywds,function(i,val){ //check if its an empty string if($.trim(val) == ""){ keywds.splice(i); }//Check if it's in stopwords else if($.inArray(val,stopwords)>= 0) { keywds.splice(i); } }); http://jsfiddle.net/pfQnt/
{ "pile_set_name": "StackExchange" }
Q: Default boot into XP on a triple XP/Vista/window7 install I installed windows XP, vista then 7 in that order. Right now when i boot up i get a login screen where i can select which of the 3 os to use with the default highlighting windows 7. After a bit on no input it logs into windows 7. How can i have it log into windows XP instead by default? in fact if i can make the screen disappear and only appear when i hold down a button that would be terrific (bootcamp does this). Is there a way i can by default boot into windows XP? A: Get EasyBCD, it will help you manage your bootloader with a simple GUI
{ "pile_set_name": "StackExchange" }
Q: How can I add a field in a form from another distinct model in django? I have a form which is based in a model X which has some attribute fields, and I want to add a field, which is not from that model (the field is from another distinct model, in fact), in the same form. How can I add it? A: Just add another model form or form class instance to your view: class YourModelForm(forms.ModelForm): class Meta: model = YourModel class YourOtherForm(forms.Form): non_model_field = forms.CharField(max_length=100) # view def your_view(request): your_model_form = YourModelForm(request.POST or None) your_other_form = YourOtherForm(request.POST or None) if request.method == 'POST' and your_model_form.is_valid and your_other_form.is_valid: your_model_form.save() # handle your_other_form, as forms.Form doesn't have a built-in .save return render(request, 'your_template.html', {'your_model_form': your_model_form, 'your_other_form': your_other_form}) # template <form action="." method="post" enctype="application/x-www-form-urlencoded"> <ul> {{ your_model_form.as_ul }} {{ your_other_form.as_ul }} </ul> <button type="submit">Submit</button> </form> Django doesn't care how many forms you have in your view.
{ "pile_set_name": "StackExchange" }
Q: The hover property lost when click on any of the menu item In the code given below i tried to give a hover property background-color with a value blue. But it works initially before we select any of the menu item (apps ,layout,widjets,etc..),and then it's not working.how can i fix it? function functionButton() { document.getElementById("flip-up-menu").style.display = "block"; } function buttonSec() { document.getElementById("flip-up-menu").style.display = "none"; } function displaySubMenu(e) { var k = e; if (k === 2) { if(document.getElementById("first-drop-down-icon").className=="spinner-icon in fa fa-caret-down"){ document.getElementById("sub-menu-one").style.display="none"; } else{ document.getElementById("sub-menu-one").style.display = "block"; document.getElementById("flip-main-two").style.background = "rgba(105,193,132,1)"; document.getElementById("sub-menu-two").style.display = "none"; document.getElementById("flip-main-one").style.background = "none"; document.getElementById("flip-main-three").style.background = "none"; document.getElementById("flip-main-four").style.background = "none"; } } else if (k === 3) { if(document.getElementById("second-drop-down-icon").className=="spinner-icon in fa fa-caret-down"){ document.getElementById("sub-menu-two").style.display="none"; } else{ document.getElementById("sub-menu-two").style.display = "block"; document.getElementById("flip-main-three").style.background = "rgba(105,193,132,1)"; document.getElementById("sub-menu-one").style.display = "none"; document.getElementById("flip-main-one").style.background = "none"; document.getElementById("flip-main-two").style.background = "none"; document.getElementById("flip-main-four").style.background = "none";} } else if (k === 1) { document.getElementById("flip-main-one").style.background = "rgba(105,193,132,1)"; document.getElementById("sub-menu-one").style.display = "none"; document.getElementById("sub-menu-two").style.display = "none"; document.getElementById("flip-main-two").style.background = "none"; document.getElementById("flip-main-three").style.background = "none"; document.getElementById("flip-main-four").style.background = "none"; } else if (k === 4) { document.getElementById("flip-main-four").style.background = "rgba(105,193,132,1)"; document.getElementById("sub-menu-one").style.display = "none"; document.getElementById("sub-menu-two").style.display = "none"; document.getElementById("flip-main-one").style.background = "none"; document.getElementById("flip-main-three").style.background = "none"; document.getElementById("flip-main-two").style.background = "none"; } else { document.getElementById("sub-menu-one").style.display = "none"; document.getElementById("sub-menu-two").style.display = "none"; } } function rotateIcon(m) { var key = m; if ( key === 2) { if(document.getElementById("first-drop-down-icon").className=="spinner-icon in fa fa-caret-down") { document.getElementById("first-drop-down-icon").className="spinner-icon out fa fa-caret-down"; } else { document.getElementById("first-drop-down-icon").className="spinner-icon in fa fa-caret-down"; document.getElementById("second-drop-down-icon").className = "spinner-icon out fa fa-caret-down"; } } else if(key === 3) { if(document.getElementById("second-drop-down-icon").className=="spinner-icon in fa fa-caret-down") { document.getElementById("second-drop-down-icon").className="spinner-icon out fa fa-caret-down"; } else { document.getElementById("second-drop-down-icon").className="spinner-icon in fa fa-caret-down"; document.getElementById("first-drop-down-icon").className = "spinner-icon out fa fa-caret-down"; } } else{ document.getElementById("second-drop-down-icon").className="spinner-icon out fa fa-caret-down"; document.getElementById("first-drop-down-icon").className="spinner-icon out fa fa-caret-down"; } } .flip-container-main-menu-parent{ cursor: pointer; margin-left: -1rem; padding-left: 1rem; margin-right: -1rem; padding-bottom: .5rem; } .flip-menu-main-icon{ float:none; margin-right:10px; margin-left: 0; position: relative; top:0; min-width: 1.5rem; list-style-type: none; text-transform: none; letter-spacing: normal; word-wrap: normal; } .fa.flip-menu-main-icon{ font-size: 13px; width: 1em; height: 1em; line-height: 2.5rem; font-style: normal; font-weight: normal; opacity:1; } .flip-menu-text{ text-align: left; font-weight:500; line-height: 1.125rem; padding: .5625rem 0; margin: 0; outline: 0; border: 0; font-size: 14px; } .flip-sub-menu{ opacity: 0.75; padding-top: .4375rem; padding-bottom: .4375rem; padding-right: 9.4rem; padding-left: 4rem; margin-left: -2rem; text-align: left; line-height: 1.125rem; display:block; background-color: rgba(24,33,118,1); color: rgba(255,255,255,.87)!important; width: 100%; display: none; } ul.flip-sub-menu li a{ color: rgba(255,255,255,.87)!important; line-height: 2rem; } #flip-up-container .flip-up-container-main-menu-parent:hover { background-color: #122112; } #flip-up-container ul:hover{ background-color: #122112; } .flip-container-sub-menu-one li a { color: white; } .flip-container-submenu-one li:hover{ background-color: #0f0f3e; } .flip-container-sub-menu-two li a { color: white; } .flip-container-sub-menu-two li:hover{ background-color: #0f0f3e; } .flip-menu-drop-down-icon{ float: right; padding-right: 5%; margin-top: 5%; margin-left:-3rem; } .spinner-icon{ font-size:13px; float: right; margin-top: 5%; margin-right: 7%; transition: all 0.3s ease-in-out; opacity:0.75; } .fa.spinner-icon{ font-size: 13px; } .spinner-icon.in{ transform: rotate(-180deg); } .spinner-icon.out{ transform:rotate(0deg); } .flip-container-main-menu-parent:hover { background-color:rgba(24,33,118,1); font-weight: 600; } .flip-sub-menu li:hover{ background-color: rgba(120,130,140,.13); } <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css"> <ul class="flip-container-main-menu"> <li class="flip-container-main-menu-parent" id="flip-main-one" onclick="displaySubMenu(1);rotateIcon('first-drp-down-icon');"><i class="flip-menu-main-icon fa fa-glass "></i><span class="flip-menu-text">Dashboard</span></li> <li class="flip-container-main-menu-parent" id="flip-main-two" onclick="displaySubMenu(2);rotateIcon(2);"><i class="flip-menu-main-icon fa fa-th"></i><span class="flip-menu-text">Apps</span> <i id="first-drop-down-icon" class="spinner-icon fa fa-caret-down"></i> </li> <ul id="sub-menu-one" class="flip-sub-menu"> <li> <a href="#">Inbox</a> </li> <li> <a href="#">Condact</a> </li> <li> <a href="#">Calendar</a> </li> </ul> <li class="flip-container-main-menu-parent" id="flip-main-three" onclick="displaySubMenu(3);rotateIcon(3);"><i class="flip-menu-main-icon fa fa-th-large"></i><span class="flip-menu-text">Layouts</span><i id="second-drop-down-icon" class="spinner-icon fa fa-caret-down"></i> </li> <ul id="sub-menu-two" class="flip-sub-menu"> <li> <a href="#">Header</a> </li> <li> <a href="#">Aside</a> </li> <li> <a href="#">Footer</a> </li> </ul> <li class="flip-container-main-menu-parent" id="flip-main-four"onclick="displaySubMenu(4);rotateIcon(4);"><i class="flip-menu-main-icon fa fa-align-justify"></i><span class="flip-menu-text">Widjets</span></li> </ul> A: Do not set "none" as background, because this will be a property which is not affected by a hover effect. Just delete the background color with an empty string. Tidy up your code and make it more clean ;) You can iterate through some items and do it DRY-style (do not repeat yourself). function functionButton() { document.getElementById("flip-up-menu").style.display = "block"; } function buttonSec() { document.getElementById("flip-up-menu").style.display = "none"; } function displaySubMenu(e) { var k = e; if (k === 2) { if(document.getElementById("first-drop-down-icon").className=="spinner-icon in fa fa-caret-down"){ document.getElementById("sub-menu-one").style.display="none"; } else{ document.getElementById("sub-menu-one").style.display = "block"; document.getElementById("flip-main-two").style.background = "rgba(105,193,132,1)"; document.getElementById("sub-menu-two").style.display = "none"; document.getElementById("flip-main-one").style.background = ""; document.getElementById("flip-main-three").style.background = ""; document.getElementById("flip-main-four").style.background = ""; } } else if (k === 3) { if(document.getElementById("second-drop-down-icon").className=="spinner-icon in fa fa-caret-down"){ document.getElementById("sub-menu-two").style.display="none"; } else{ document.getElementById("sub-menu-two").style.display = "block"; document.getElementById("flip-main-three").style.background = "rgba(105,193,132,1)"; document.getElementById("sub-menu-one").style.display = "none"; document.getElementById("flip-main-one").style.background = ""; document.getElementById("flip-main-two").style.background = ""; document.getElementById("flip-main-four").style.background = "";} } else if (k === 1) { document.getElementById("flip-main-one").style.background = "rgba(105,193,132,1)"; document.getElementById("sub-menu-one").style.display = "none"; document.getElementById("sub-menu-two").style.display = "none"; document.getElementById("flip-main-two").style.background = ""; document.getElementById("flip-main-three").style.background = ""; document.getElementById("flip-main-four").style.background = ""; } else if (k === 4) { document.getElementById("flip-main-four").style.background = "rgba(105,193,132,1)"; document.getElementById("sub-menu-one").style.display = "none"; document.getElementById("sub-menu-two").style.display = "none"; document.getElementById("flip-main-one").style.background = ""; document.getElementById("flip-main-three").style.background = ""; document.getElementById("flip-main-two").style.background = ""; } else { document.getElementById("sub-menu-one").style.display = "none"; document.getElementById("sub-menu-two").style.display = "none"; } } function rotateIcon(m) { var key = m; if ( key === 2) { if(document.getElementById("first-drop-down-icon").className=="spinner-icon in fa fa-caret-down") { document.getElementById("first-drop-down-icon").className="spinner-icon out fa fa-caret-down"; } else { document.getElementById("first-drop-down-icon").className="spinner-icon in fa fa-caret-down"; document.getElementById("second-drop-down-icon").className = "spinner-icon out fa fa-caret-down"; } } else if(key === 3) { if(document.getElementById("second-drop-down-icon").className=="spinner-icon in fa fa-caret-down") { document.getElementById("second-drop-down-icon").className="spinner-icon out fa fa-caret-down"; } else { document.getElementById("second-drop-down-icon").className="spinner-icon in fa fa-caret-down"; document.getElementById("first-drop-down-icon").className = "spinner-icon out fa fa-caret-down"; } } else{ document.getElementById("second-drop-down-icon").className="spinner-icon out fa fa-caret-down"; document.getElementById("first-drop-down-icon").className="spinner-icon out fa fa-caret-down"; } } .flip-container-main-menu-parent{ cursor: pointer; margin-left: -1rem; padding-left: 1rem; margin-right: -1rem; padding-bottom: .5rem; } .flip-menu-main-icon{ float:none; margin-right:10px; margin-left: 0; position: relative; top:0; min-width: 1.5rem; list-style-type: none; text-transform: none; letter-spacing: normal; word-wrap: normal; } .fa.flip-menu-main-icon{ font-size: 13px; width: 1em; height: 1em; line-height: 2.5rem; font-style: normal; font-weight: normal; opacity:1; } .flip-menu-text{ text-align: left; font-weight:500; line-height: 1.125rem; padding: .5625rem 0; margin: 0; outline: 0; border: 0; font-size: 14px; } .flip-sub-menu{ opacity: 0.75; padding-top: .4375rem; padding-bottom: .4375rem; padding-right: 9.4rem; padding-left: 4rem; margin-left: -2rem; text-align: left; line-height: 1.125rem; display:block; background-color: rgba(24,33,118,1); color: rgba(255,255,255,.87)!important; width: 100%; display: none; } ul.flip-sub-menu li a{ color: rgba(255,255,255,.87)!important; line-height: 2rem; } #flip-up-container .flip-up-container-main-menu-parent:hover { background-color: #122112; } #flip-up-container ul:hover{ background-color: #122112; } .flip-container-sub-menu-one li a { color: white; } .flip-container-submenu-one li:hover{ background-color: #0f0f3e; } .flip-container-sub-menu-two li a { color: white; } .flip-container-sub-menu-two li:hover{ background-color: #0f0f3e; } .flip-menu-drop-down-icon{ float: right; padding-right: 5%; margin-top: 5%; margin-left:-3rem; } .spinner-icon{ font-size:13px; float: right; margin-top: 5%; margin-right: 7%; transition: all 0.3s ease-in-out; opacity:0.75; } .fa.spinner-icon{ font-size: 13px; } .spinner-icon.in{ transform: rotate(-180deg); } .spinner-icon.out{ transform:rotate(0deg); } .flip-container-main-menu-parent:hover { background-color:rgba(24,33,118,1); font-weight: 600; } .flip-sub-menu li:hover{ background-color: rgba(120,130,140,.13); } <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css"> <ul class="flip-container-main-menu"> <li class="flip-container-main-menu-parent" id="flip-main-one" onclick="displaySubMenu(1);rotateIcon('first-drp-down-icon');"><i class="flip-menu-main-icon fa fa-glass "></i><span class="flip-menu-text">Dashboard</span></li> <li class="flip-container-main-menu-parent" id="flip-main-two" onclick="displaySubMenu(2);rotateIcon(2);"><i class="flip-menu-main-icon fa fa-th"></i><span class="flip-menu-text">Apps</span> <i id="first-drop-down-icon" class="spinner-icon fa fa-caret-down"></i> </li> <ul id="sub-menu-one" class="flip-sub-menu"> <li> <a href="#">Inbox</a> </li> <li> <a href="#">Condact</a> </li> <li> <a href="#">Calendar</a> </li> </ul> <li class="flip-container-main-menu-parent" id="flip-main-three" onclick="displaySubMenu(3);rotateIcon(3);"><i class="flip-menu-main-icon fa fa-th-large"></i><span class="flip-menu-text">Layouts</span><i id="second-drop-down-icon" class="spinner-icon fa fa-caret-down"></i> </li> <ul id="sub-menu-two" class="flip-sub-menu"> <li> <a href="#">Header</a> </li> <li> <a href="#">Aside</a> </li> <li> <a href="#">Footer</a> </li> </ul> <li class="flip-container-main-menu-parent" id="flip-main-four"onclick="displaySubMenu(4);rotateIcon(4);"><i class="flip-menu-main-icon fa fa-align-justify"></i><span class="flip-menu-text">Widjets</span></li> </ul>
{ "pile_set_name": "StackExchange" }
Q: email differant person depending on select option in form i trying to make a form that emails someone different depending on what is selected on the form. when i submit the form i just get a blank page with the url pointing to "../wp-content/test/test.php" it wont even go to the default oops page. im not sure what im doing wrong. any input appreciated. everything worked fine until i added the switch. i can sent an email to just one person for all option just fine. here is my form: <form name="contactform" method="post" action="../wp-content/test/test.php"> <input type="text" name="name" maxlength="50" size="30"> <input type="text" name="email" maxlength="80" size="30"> <select id="club" name="club"> <option name="wordone" value="wordone">wordone</option> <option name="wordtwo" value="wordtwo">wordtwo</option> </select> <input type="submit" value="Submit"> </form> this is my php: <?php if(isset($_POST['Submit'])){ $name = $_POST['name']; $club = $_POST['club']; $email_from = $_POST['email']; $email_subject = 'New Form submission'; $email_body = '...'; $headers = "From: $email_from \r\n"; $headers .= "Reply-To: $email_from \r\n"; switch($_POST['club']){ case 'wordone': $to = "[email protected]"; mail($to,$email_subject,$email_body,$headers); header('Location: http://website.com/thanks2'); break; case 'wordtwo': $to = "[email protected]"; mail($to,$email_subject,$email_body,$headers); header('Location: http://website.com/thanks1'); break; default: header('Location: http://website.com/oops'); } } A: Now that the original question has been edited to remove the offending pieces of code mentioned earlier it is still not obvious as to why the code is failing but perhaps the following, condensed code, might be of use. The only thing I can see is that you test explicitly for $_POST['Submit'] but the submit button does not have a name. <?php /* check that all expected POST variables are present */ if( isset( $_POST['submit'], $_POST['name'], $_POST['club'], $_POST['email'] ) ){ /* set POST variables as named vars for convenience */ $name = trim( $_POST['name'] ); $club = trim( $_POST['club'] ); $email= trim( $_POST['email'] ); $php=phpversion(); $default = false; /* do these change on a person by person user or stay the same? */ $subject = 'New Form submission'; $body = '...'; switch( $club ){ case 'wordone': $to = "[email protected]"; $redirect='http://website.com/thanks1'; break; case 'wordtwo': $to = "[email protected]"; $redirect='http://website.com/thanks2'; break; default: $default=true; $result=false; $redirect='http://website.com/oops'; break; } /* send the email */ if( !$default ){ $headers = "From: {$email}\r\n"; $headers .= "Reply-To: {$email}\r\n"; $headers .= "X-Mailer: PHP/{$php}\r\n"; $result=@mail( $to, $subject, $body, $headers ); } /* redirect */ header( 'Location: '.$redirect.'?mailsent='.$result ); } ?> <form name="contactform" method="post" action="../wp-content/test/test.php"> <input type="text" name="name" maxlength="50" size="30"> <input type="text" name="email" maxlength="80" size="30"> <!-- no need for the `name` attribute in an `option` and they can remain unclosed like this --> <select id="club" name="club"> <option value="wordone">wordone <option value="wordtwo">wordtwo </select> <input type="submit" name='submit' value="Submit"> </form>
{ "pile_set_name": "StackExchange" }
Q: Creating R's formula using Python I am writing a program that interacts with R using Python. Basically, I have some R libraries that I want to ingest into my Python code. After downloading rpy2, I define my R functions that I want to use in a separate .R file script. The R function requires that we pass the formula to it for applying some oversampling technique. Below is the R function that I wrote: WFRandUnder <- function(target_variable, other, train, rel, thr.rel, C.perc, repl){ a <- target_variable b <- '~' form_begin <- paste(a, b, sep=' ') fmla <- as.formula(paste(form_begin, paste(other, collapse= "+"))) undersampled = RandUnderRegress(fmla, train, rel, thr.rel, C.perc, repl) return(undersampled) } I am passing, from python, the target variable name, as well as a list containing all the other columns' names. As I want it to be as follows: my_target_variable ~ all other columns However in these line: a <- target_variable b <- '~' form_begin <- paste(a, b, sep=' ') fmla <- as.formula(paste(form_begin, paste(other, collapse= "+"))) The formula does not always get formulated if I have many columns in my data. What should I do to make it always work? I am concatenating all columns'names with a + operator. A: Thanks to @nicola, I was able to solve this problem by doing the following: create_formula <- function(target_variable, other){ # y <- target_variable # tilda <- '~' # form_begin <- paste(y, tilda, sep=' ') # fmla <- as.formula(paste(form_begin, paste(other, collapse= "+"))) # return(fmla) y <- target_variable fmla = as.formula(paste(y, '~ .')) return(fmla) } I call this function from my python program using rpy2. This issues no problem because whenever we use this formula, we will be attaching the data itself to it, so it won't possess a problem. A sample code to demonstrate what I'm saying: if self.smogn: smogned = runit.WFDIBS( # here is the formula call (get_formula is a python function that calls create_formula defined above in R) fmla=get_formula(self.target_variable, self.other), # here is the data dat=df_combined, method=self.phi_params['method'][0], npts=self.phi_params['npts'][0], controlpts=self.phi_params['control.pts'], thrrel=self.thr_rel, Cperc=self.Cperc, k=self.k, repl=self.repl, dist=self.dist, p=self.p, pert=self.pert)
{ "pile_set_name": "StackExchange" }
Q: How to create a listview with checkbox settings in Titanium Appcelerator I want to create a tableview with checkboxes for android using titanium mobile. The problem is i dont know how and where i can store and check the state of the checkboxes using javascript in titanium. A: Use Titanium.App.Properties to save and recall the data. See http://developer.appcelerator.com/apidoc/mobile/latest/Titanium.App.Properties-module
{ "pile_set_name": "StackExchange" }
Q: How to click this button using Selenium C#? <div class="mdl-align"> == $0 : :before <button class="fp-upload-btn btn-primary btn">Upload this file</button> == $0 : :after </div> The above codes are from a website, however I am unable to click this button despite trying multiple attempts. Im using selenium with C# to do an automation testing. What this button does, is to simply submit a form. A: Try to use xpath locator to click on Upload this file button. driver.FindElement(By.XPath("//button[contains(text(), 'Upload this file')]")).Click();
{ "pile_set_name": "StackExchange" }
Q: How would I efficiently make fake tile shadows? So I'm making a tile based game and I'd like to add some fake shadows to the tiles. It's kinda hard to explain so I'll do it with pictures: Let's say this is my tile world: And I want it to have shadows like this: Because the world is tile based, I can split all the shadow parts into separate images: But now I have no idea how I would bring this to code. Well, actually I do have ideas, but they're incredible tedious and they don't work optimally. I've tried a massive if-statement... bool ul = adjacentBlocks[0, 0] == Block.Type.Rock; //Upper Left bool um = adjacentBlocks[1, 0] == Block.Type.Rock; //Upper Middle bool ur = adjacentBlocks[2, 0] == Block.Type.Rock; //Upper Right bool ml = adjacentBlocks[0, 1] == Block.Type.Rock; //Center Left //bool cm = adjacentBlocks[1, 1] == Block.Type.Rock; //CURRENT BLOCK - NOT NEEDED bool mr = adjacentBlocks[2, 1] == Block.Type.Rock; //Center Right bool ll = adjacentBlocks[0, 2] == Block.Type.Rock; //Lower Left bool lm = adjacentBlocks[1, 2] == Block.Type.Rock; //Lower Middle bool lr = adjacentBlocks[2, 2] == Block.Type.Rock; //Lower Right if (ml) { texture = "Horizontal"; flipX = false; flipY = false; } if (mr) { texture = "Horizontal"; flipX = true; flipY = false; } if (um) { texture = "Vertical"; flipX = false; flipY = false; } if (lm) { texture = "Vertical"; flipX = false; flipY = true; } if (ml && ul && um) texture = "HorizontalVertical"; //More if statements I can't be bothered to write if (ul && um && ur && ml && mr && ll && lm & lr) texture = "Full"; And a massive lookup table... var table = new List<TextureBlockLayout> { new TextureBlockLayout("Horizontal", false, false, new[,] { { true, true, false }, { true, true, false }, { true, true, false } }), new TextureBlockLayout("Horizontal", true, false, new[,] { { false, true, true }, { false, true, true }, { false, true, true } }), new TextureBlockLayout("Full", false, false, new[,] { { true, true, true }, { true, true, true }, { true, true, true } }) }; But either I'm doing something wrong or they just refuse to work at all. Any ideas? A: Each tile has eight neighbors. Each neighbor has two possible states. Map the states of the neighbors into bits in a byte, and use the byte as an index into a 256-element lookup table. Yes, this is the "brute force" solution, and you might be able to get by with a much smaller table using some cleverer approach. But 256 elements isn't that much (you can easily load it from a data file), and the nice thing about this approach is that it's completely general — you can have all the 256 tiles look subtly different if you like. OK, taking a closer look at the way your example tiles are shaded, it looks like you really only need four bits (and thus a 16-element table): Set this bit if the north, west and northwest neighbors are all green. Set this bit if the north, east and northeast neighbors are all green. Set this bit if the south, west and southwest neighbors are all green. Set this bit if the south, east and southeast neighbors are all green. Even some of these 16 tiles are still rotated / mirrored versions of each other, but it may be easiest to store the orientation in the table alongside the tile index rather than trying to calculate it in the code.
{ "pile_set_name": "StackExchange" }
Q: EJB lifecycle ( request from client) Hello everybody I am newbie for EJB component technology and i have to learn this in order to prepare my colloquium exam. I am not sure I can understand all details of the life cycle. The life cycle includes these steps: -The client request to EJB Container ( but how this request could be done ? Is the location of the request I mean that remote " outside of the EJB container" or local" inside of the EJB container" is important or not?) -By depending on the request one bean instance is created in the pool and return to the client and after use from the client it returns again in the pool ( depending on the bean type(?). I think this scenario appropriate for the stateless session bean but I am not sure. Because in stateful session bean scenario there is no pool.) Advance thanks for all helps. A: "client" in this context just means "application code that will lookup/inject an EJB and call EJBs"; it is the opposite of "application code of the EJB itself" (which does not have a well-defined term; I've seen the term "EJB" overloaded for this meaning, or "service", etc.). Local EJB vs remote EJB is not relevant in this context, even though "client" also has a well-defined meaning for remote. Yes, pooling of session beans refers only to stateless session beans. Stateful and singleton session beans do not have a pool. Message-driven beans can also be pooled, but they are not directly invoked by a client per se, even though there can be a logical client; e.g., the one that send the JMS message. (Entity beans can also be pooled, but they're not really relevant these days.)
{ "pile_set_name": "StackExchange" }
Q: Magento - half page breaking i am stuck with an issue on magento store. half of page display and then it breaks. here is my page. http://www.statecertification.com/regshop/class-locator.html if you look page source, this is code where it breaks <script type="text/javascript"> var marker, i; var map; var store_locations = <?php echo json_encode($Stores); ?>; can any one look into , same page is working on other servers. Thanks A: What version of magnento and php are you using because it definitely a php error? json_encode require php >= 5.2.0 Also try var store_locations = '<?php echo Mage::helper('core')->jsonEncode($Stores);?>';
{ "pile_set_name": "StackExchange" }
Q: bash grep for a mix of special characters some of which to be interpreted literally I have data.txt that has the following format blah<TAB>string1_with_spaces_quotes_dots_etc<TAB>blah blah<TAB>string2_with_spaces_quotes_dots_etc<TAB>blah ... Some of the stringJ_... appear more than once. The file is not sorted in any way. I also have strings.txt that have the form stringA_with_spaces_quotes_dots_etc stringC_with_spaces_quotes_dots_etc stringB_with_spaces_quotes_dots_etc ... These strings appear only once but this file is not sorted either. What I need is, for every string from strings.txt find lines in data.txt where the middle string is exactly the one from strings.txt. So, for example, if the string I am looking for is foo. Then I need to extract the following lines blah<TAB>foo.<TAB>blah but not lines like blah<TAB>foo. bar<TAB>blah blah<TAB>foo<TAB>blah The difficulty here is that those strings can have characters like dots that can be interpreted as special chars, while I need literal matches. What is the right set of grep options in the loop below? Or should I use a different command altogether? while read t do grep <OPTIONS> "\t${t}\t" data.txt done < strings.txt A: Once you get beyond simple regexp matching (e.g. anything involving targeting a specific column/field), you want awk, not grep: awk -F'\t' 'NR==FNR{a[$0];next} $2 in a' strings.txt data.txt The above does string matching, not regexp matching, so there are no "special characters" and is entirely focused on matching on the whole of the 2nd tab-separated field of data.txt so there are no partial or other false matches possible. It will only match exactly what you want. Also, any time you're considering writing a shell loop to manipulate text, read https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice to understand some, but not all, of the reasons why you shouldn't.
{ "pile_set_name": "StackExchange" }
Q: having multiple forms on same php page I would like to create a php page where Initially, there are two textboxes, and a submit button called submit On clicking the submit button, it shows a table containing checkboxes, and a submit button called submit2 On checking a few checkboxes, and clicking the submit button called submit2, I would like to get all the checkboxes that were checked. This is my attempt for the above. Steps 1 and 2 work fine, however, I'm not able to proceed with Step 3. PS : I require all three steps to be on the same page, without jumping pages everytime there is a new submit button. Also, I'm using GET and not POST. <html> <body> <form action="self.php" method="get"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit" name="submit"> </form> </body> </html> <?php if(isset($_GET['name'])) { $array1 = array(1, 2, 3, 4, 5); $a=count($array1); echo "<table width=100% border=1 cellspacing=0 cellpadding=0><tr><th>Array1</th><th>Array2</th><th>Checkboxes</th></tr>"; for($i=0;$i<$a;$i++) { echo "<tr><td>".$array1[$i]."</td>"; echo "<td>".$array1[$i]."</td>"; echo '<td><input type="checkbox" name="checkbox[]" value="" id="checkbox"></td>'; echo '</tr>'; } echo "</table>"; echo '<input type="submit" name="submit2">'; } if(isset($_GET['submit2'])) { echo "pressed the second submit button"; } ?> A: Just wrap php code into <form> tag like echo '<form action="self.php" method="get">'; if(isset($_GET['name'])) { $array1 = array(1, 2, 3, 4, 5); $a=count($array1); echo "<table width=100% border=1 cellspacing=0 cellpadding=0><tr><th>Array1</th><th>Array2</th><th>Checkboxes</th></tr>"; for($i=0;$i<$a;$i++) { echo "<tr><td>".$array1[$i]."</td>"; echo "<td>".$array1[$i]."</td>"; echo '<td><input type="checkbox" name="checkbox[]" value="" id="checkbox"></td>'; echo '</tr>'; } echo "</table>"; echo '<input type="submit" name="submit2">'; } echo '</form>'; Also, if you need to pass name and email variables from Step 1 to Step 3, add echo "<input type='hidden' name='name' value='{$_GET['name']}'>"; echo "<input type='hidden' name='email' value='{$_GET['email']}'>"; inside if(isset($_GET['name']))
{ "pile_set_name": "StackExchange" }
Q: cUrl Converting into Javascript possible? is there a way to convert this into javascript? <?php $url = 'http://www.yourdomain.com/'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); echo $output; ?> A: Pure JavaScript? No. JavaScript with a standard browser environment? Maybe. There is the XHR object (which includes the status property, which will tell you if it was successful or not), but there is also the same origin policy.
{ "pile_set_name": "StackExchange" }
Q: An example of a smooth manifold with a group structure which is not a Lie group I'm looking for an example of a smooth manifold which is also a group but the group operations are not smooth. Most introductory books on differential geometry don't discuss such examples which makes me conjecture that the examples are not easy to describe. A: Let $M$ denote any manifold of positive dimension which can not be given the structure of a Lie group, e.g. $S^2$, or any nonorientable manifold. Pick your favorite set theoretic bijection with $\mathbb{R}$. Such a bijection exists: any chart has cardinality $|\mathbb{R}^n|=|\mathbb{R}|$ and since manifolds are second countable, $M$ can be covered by countably many charts, $|M|\leq |\mathbb{R}|^{|\mathbb{N}|}=|\mathbb{R}|$. Call such a bijection $f:M \rightarrow \mathbb{R}$. Now, for $a,b\in M$, define $a+b= f^{-1}(f(a)+f(b))$. This gives $M$ the structure of a group isomorphic to $\mathbb{R}$.
{ "pile_set_name": "StackExchange" }
Q: how to create an ip range fast as fast as possible? how to get the fastest result i write the code below. for (int i = 0; i < 256; i++) for (int j = 0; j < 256); j++) for (int k = 0; k < 256; k++) for (int p = 0; p < 256; p++) { writer.WriteLine(string.Format("{0}.{1}.{2}.{3}", i, j, k, p)); } but my users told me that it is dammed slow. i dont have any idea how to boost the progress. share the problem, maybe someone knows that. thanks. A: You can try with IPAddressRange : https://www.nuget.org/packages/IPAddressRange/ But it will still be very long if you want to get all the ipv4 range! var range = NetTools.IPAddressRange.Parse("192.168.0.10 - 192.168.10.20"); System.Text.StringBuilder builder = new System.Text.StringBuilder(); foreach (var item in range) { builder.Append(item); }
{ "pile_set_name": "StackExchange" }
Q: Hidden view in NSStackView not hiding? I have created a vertical NSStackView that contains two NSView subclasses (they are just NSViews that draw a background color). I have the stack view set to detach hidden views. I have set one of the views to be hidden. Neither view hides in the stack view. To make sure I'm not insane, I also set up two of the same NSViews next to each other, hiding one. Sure enough, one does hide. The stack view's distribution is set to Fill Proportionally (not that that seems to matter). In IB the behavior seems correct; one of the views hides. I must be missing something incredibly obvious here, right? In case it is relevant, the NSView subclass: #import "ViewWithBackgroundColor.h" @implementation ViewWithBackgroundColor - (void)drawRect:(NSRect)dirtyRect { [super drawRect:dirtyRect]; [self.backgroundColor set]; [NSBezierPath fillRect:dirtyRect]; if(self.bottomBorderColor != nil) { NSBezierPath *linePath = [[NSBezierPath alloc] init]; [self.bottomBorderColor set]; linePath.lineWidth = 2.0; [linePath moveToPoint:NSMakePoint(0, 0)]; [linePath lineToPoint:NSMakePoint(dirtyRect.size.width, 0)]; [linePath stroke]; } } - (NSColor *) backgroundColor { if (_backgroundColor) { return _backgroundColor; } else { return [NSColor clearColor]; } } @end A: This looks like an issue with IB and stack view (please file a bug report if you already haven't). To workaround it you could either: Don't hide the button in IB, and set it to be hidden at runtime. or Uncheck the 'Detaches Hidden Views' stack view property in IB (visible in your screen shot), and set it at runtime with -[NSStackView setDetachesHiddenViews:].
{ "pile_set_name": "StackExchange" }
Q: Last line of csv file is not read by fread from package data.table with error message 'Discarded single-line footer' I have a csv file that has windows line endings (CR LF) and is separated by semicolon. The last line in the file is an empty line, i.e. no semicolons contained or any other character. When reading the file with fread from the data.table package the second last line, i.e. the last data row, is not loaded and the error message says "Discarded single-line footer". A: Try inserting fill = TRUE. In my case, inserting fill = true all works correctly.
{ "pile_set_name": "StackExchange" }
Q: ReactJS PropType to check values of associative arrays I'm passing in an object, which is an associative array, as a prop. I don't know the keys (property names) beforehand, I only know that the values should be strings or booleans (for example). How can I validate this using PropTypes? EDIT: An example would be: { "20161001": true, "20161002": true, "20161003": true, "20161004": false, "20161005": true, "20161006": false } A: I needed this again today, and found out this is supported using PropTypes.objectOf(). See https://reactjs.org/docs/typechecking-with-proptypes.html : // An object with property values of a certain type optionalObjectOf: PropTypes.objectOf(PropTypes.number)
{ "pile_set_name": "StackExchange" }
Q: IOS: one company two IOS developer program Possible Duplicate: IOS: one account two iOS developer program excuse me if it's not a programming question, but I have this problem the problem is that now I'm enrlolling in a iOS developer program (I'm using fictitious names), with a company called "My Company", ok? then when I release an app in app store I see on the top "App Store > Games > MYCOMPANYONE " (it's an example) and below on the left there is Category:... Version:.. Size... and "Developer: My Company" it's all ok and now I explain my problem. Now I want enrlonn in an other iOS developer program but ever with the same "My Company" but in app store when I release an app it must be so: on the top "App Store > Games > MYCOMPANYTWO" and below on the left Category:... Version:.. Size... and "Developer: My Company" with the same company is it possible this? can you help me please? A: No, this is not possible. When you purchase one developer license, you get one license. The developer name that the user sees is whatever you entered when you set up the iTunes Connect account, and cannot be changed. This is, in part, to prevent abuse. If you want to release a second product with a different developer name, you'll have to register a new company to do so and pay the $99 again.
{ "pile_set_name": "StackExchange" }
Q: When Ubuntu Server restarts eth0 Doesn't come back up Every time I restart my Ubuntu Server 11.10 I can't ssh into it because ETH0 doesn't come up automatically. I never had this problem before upgrading to 11.10. I have to login to the server and start the ETH0 manually. I would appreciate it any help. Thanks. Here is my /etc/network/interfaces file: #The loopback network interface auto lo eth0 iface lo inet loopback # The primary network interface iface eth0 inet static address 192.168.1.102 netmask 255.255.255.0 broadcast 192.168.1.255 network 192.168.1.0 gateway 192.168.1.1 A: Joel, add a line with auto eth0 before the iface eth0 inet static line, that should bring it up on boot.
{ "pile_set_name": "StackExchange" }
Q: Android: How to save an instance of parcelable object? I am trying to save an instance of StatusBarNotification, so that i could show the notification later to the user. I noticed that StatusBarNotifcation is not Serializable but Parcelable. Is there any way to store the exact instance state in the database so that even if user turns of his phone, the instance object is stored. I know its not the best practice to store the Parcelable object in database. But I need to do it. If there is any way i could get the byte array of the instance, I am open for suggetions. EDIT I found out today that, if I turn off my android phone with some un-attended notification, when I restart my phone I am still able to see the same notifications. That being said, android is somehow saving the same instance of notification. Now my question is, how?? And if android does why can't us. A: Is there any way to store the exact instance state in the database so that even if user turns of his phone, the instance object is stored. No. In particular, not only do you have no way of persisting the PendingIntents associated with the Notification, but you have no way of recreating them with all the security rules intact. A PendingIntent is tied closely to the app that creates it; you are not the app that created those PendingIntents originally. A: I think you cannot save the parcelable object of notification in the database (also not a good practice).
{ "pile_set_name": "StackExchange" }
Q: curl not grabbing page on second pass instead returning an empty string? I have the following code: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> char * return_next(char *link, int rand_flag); char* strip_parens(char* string); char* strip_itals(char* string); char* strip_tables(char* string); struct MemoryStruct { char *memory; size_t size; }; static size_t WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data) { size_t realsize = size * nmemb; struct MemoryStruct *mem = (struct MemoryStruct *)data; mem->memory = realloc(mem->memory, mem->size + realsize + 1); if (mem->memory == NULL) { /* out of memory! */ printf("not enough memory (realloc returned NULL)\n"); exit(EXIT_FAILURE); } memcpy(&(mem->memory[mem->size]), ptr, realsize); mem->size += realsize; mem->memory[mem->size] = 0; return realsize; } int main(void) { char *page = malloc(1000); page = strcpy(page, "http://en.wikipedia.org/wiki/Literature"); char *start = malloc(1000); start = strcpy(start, page); printf("%s\n\n", page); int i = 0, rand_flag = 0; while(strcmp(page, "http://en.wikipedia.org/wiki/Philosophy")){ i++; page = return_next(page, rand_flag); printf("deep: %d, %s\n\n", i, page); rand_flag = 0; } printf("start link: %s, is %d clicks from philosophy", start, i); return 0; } char * return_next(char *link, int rand_flag){ CURL *curl_handle; struct MemoryStruct chunk; chunk.memory = malloc(1); chunk.size = 0; curl_global_init(CURL_GLOBAL_ALL); curl_handle = curl_easy_init(); curl_easy_setopt(curl_handle, CURLOPT_URL, link); curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk); curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1"); if(rand_flag){ curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1); } curl_easy_perform(curl_handle); curl_easy_cleanup(curl_handle); char *theString = malloc(strlen(chunk.memory)+1); char *theString1 = malloc(strlen(theString) + 1); theString = strstr(chunk.memory, "div id=\"body"); theString1 = strip_tables(theString); if(chunk.memory) free(chunk.memory); theString = strstr(theString1, "<p>"); theString1 = strip_itals(theString); theString = strip_parens(theString1); curl_global_cleanup(); return theString; } char* strip_parens(char* string) { long len = strlen(string); char* result = malloc(len + 1); int num_parens = 0; int i, j = 0; for(i=0; i < len; i++) { char c = string[i]; if(c == '(') { num_parens++; } else if(c == ')' && num_parens > 0) { num_parens--; } else if(num_parens == 0) { if(c == '<'){ if (string[i+1] == 'a'){ if (string[i+2] == ' ') { if(string[i+3] == 'h'){ i = i+9; for(;string[i] != '"'; i++){ result[j] = string[i]; j++; } result[j] = '\0'; len = strlen("http://en.wikipedia.org"); char *final = malloc(j+len); final = strcpy(final, "http://en.wikipedia.org"); return strcat(final, result); } } } } } } result[j] = '\0'; return result; } char* strip_itals(char* string) { long len = strlen(string); char* result = malloc(len + 1); int inside = 0; int i, j = 0; for(i=0; i < len; i++) { //printf(".%d, %c, %d\n", i, string[i], inside); char c = string[i]; if(c == '<' && inside == 0) { if (string[i+1] == 'i'){ if (string[i+2] == '>') { inside++; i = i+2; } } } else if(c == '<' && inside > 0) { //printf("first if\n"); if (string[i+1] == '/'){ if (string[i+2] == 'i') { inside--; i=i+3; } } } if(inside == 0) { result[j] = c; j++; } } result[j] = '\0'; return result; } char* strip_tables(char* string) { //printf("%s\n", string); long len = strlen(string); //long len = 1000000; char* result = malloc(len + 1); int inside = 0; int i, j = 0; for(i=0; i < len; i++) { //printf(".%d, %c, %d\n", i, string[i], inside); char c = string[i]; if(c == '<' && inside == 0) { if (string[i+1] == 't'){ if (string[i+2] == 'a') { if (string[i+3] == 'b') { if (string[i+4] == 'l') { inside++; i = i+4; } } } } } else if(c == '<' && inside > 0) { //printf("first if\n"); if (string[i+1] == '/'){ if (string[i+2] == 't') { if (string[i+3] == 'a') { if (string[i+4] == 'b') { if (string[i+5] == 'l') { inside--; i=i+7; } } } } } } if(inside == 0) { result[j] = c; j++; } } result[j] = '\0'; return result; } That given a link to a wiki article will return the first link back, then in main I loop over this function till I arrive at a specified article. I ran from some random article and discovered when it passes over "Literature" it gets "Art" as the next page but when it goes to search Art curl returns a blank string- if i print("%s", chunk.memory) after the call I get (null). If I manually force the function to start at art it works fine, trailing all the way to philosophy. For the life of me I cant see any differences... I put some diagnostic printfs in and got the following- this is the address ~> !http://en.wikipedia.org/wiki/Art!, rand flag = 0 With the link inbetween the exlamation marks, so I know it's parsing the link back properly, and rand_flag is always set to 0 at the moment. Any tips, pointers or solutions much appreciated. A: It is not generally possible to say anything about a program if all you have is an uncompilable piece of code. So I'm going to give some generic recommendations. Check return values of your functions. Set up callbacks to libcurl so that you can print every byte that goes in and out with a flip of a switch (much like curl -v does — look at its source if you need guidance). Sniff your network traffic. If you see that a request is not sent at all, or that it's sent but no data is returned, you have narrowed your problem a bit.
{ "pile_set_name": "StackExchange" }
Q: How to create custom native query in spring data rest without duplicating their ResourceAssembler? I have a controller that looks like that @RestController public class LocationsController { @Autowired private EntityManager manager; private String withinQuery = "WITH L as\n" + "\n" + "(SELECT *\n" + "FROM location\n" + "\n" + "WHERE ST_Distance(ST_FlipCoordinates(location.shape), ST_FlipCoordinates(ST_GeomFromGeoJSON('%s'\n" + " )))=0)\n" + "\n" + "SELECT *\n" + "FROM L\n" + "WHERE id NOT IN (\n" + "SELECT metalocation_id FROM location\n" + "WHERE metalocation_id IS NOT NULL\n" + ")"; private String nearestQuery = "select * from location order by ST_Distance(ST_FlipCoordinates(location.shape), ST_FlipCoordinates(St_GeomFromGeoJSON('%s'))) limit 1"; @RequestMapping(value="near", method = RequestMethod.GET) public List<Location> getNearestLocations(@RequestParam(value = "point") String pointAsString) throws IOException { List<Location> locationCloseToPoint = manager.createNativeQuery(String.format(withinQuery, pointAsString), Location.class).getResultList(); if (locationCloseToPoint.size() == 0) { List<Location> closesLocation = manager.createNativeQuery(String.format(nearestQuery, pointAsString), Location.class) .getResultList(); locationCloseToPoint.addAll(closesLocation); } return locationCloseToPoint; } } As you can see it return list of locations. @Entity public class Location { public Geometry getShape() { return shape; } public void setShape(Geometry shape) { this.shape = shape; } @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotNull private Geometry shape; @ManyToOne(cascade = CascadeType.ALL) private Location metalocation; The problem with that is I want to return this list in format that spring data rest uses for location resource with all hateoas fields and stuff. More specifically I want to have a link to metalocation in the output. I've read about spring-hateoas and ResourceAssembler and @RepositoryRestController and I think I could replicate what spring-data-rest is doing via writing custom ResourceAssembler, but I don't want to, because you know, why would I want to write the code that is already written by spring-data-rest, right? They doing all this assembling stuff automatically, right? Because I see it in the http output. So I think there should be a way to use it. A: You can try the following. First annotate your controller with @RepositoryRestController instead of @RestController. You can then use the resource assembler that spring data rest uses internally - PersistentEntityResourceAssembler The example below works for me. @RepositoryRestController public class DemoController { private final ProductRepository productRepository; private final PagedResourcesAssembler<Object> pagedResourcesAssembler; @Autowired public DemoController(ProductRepository productRepository, PagedResourcesAssembler<Object> pagedResourcesAssembler) { this.productRepository = productRepository; this.pagedResourcesAssembler = pagedResourcesAssembler; } //use PersistentEntityResourceAssembler and PagedResourcesAssembler to return a resource with paging links @RequestMapping(method = GET, path="/products/search/listProductsPage", produces = HAL_JSON_VALUE) public ResponseEntity<PagedResources<PersistentEntityResource>> getAllPage(Pageable pageable, PersistentEntityResourceAssembler persistentEntityResourceAssembler) { Iterable<?> all = productRepository.findAll(pageable); return ResponseEntity.ok(pagedResourcesAssembler.toResource((Page<Object>) all, persistentEntityResourceAssembler)); } //return Resources of entity resources @RequestMapping(method = GET, path="/products/search/listProducts", produces = HAL_JSON_VALUE) public ResponseEntity<Resources<PersistentEntityResource>> getAll(Pageable pageable, PersistentEntityResourceAssembler persistentEntityResourceAssembler) { return ResponseEntity.ok(new Resources<PersistentEntityResource>(productRepository.findAll().stream() .map(persistentEntityResourceAssembler::toResource) .collect(Collectors.toList()))); } } The getAll method is probably what you want. I added also the getAllPage variant that converts a Page into a PagedResource - this is what spring data rest generates if you get a collection resource. Here you also have to use PagedResourcesAssembler to generate the page links. Is this what you are searching for? In your case I would also try to avoid the custom controller - If you could express your native query as a repository finder, spring data rest would automatically expose the finder. Spring data jpa seems to support native queries via annotation - http://docs.spring.io/spring-data/jpa/docs/1.9.1.RELEASE/reference/html/#jpa.query-methods.at-query
{ "pile_set_name": "StackExchange" }
Q: How can I add tabs from PyQt4 to my text editor? How can I display tabs for my text editor and to be able to replace the "New" action's function to create a new tab and for the "Open" action's to open the file into a new tab? Here is my code: #Imports import sys, os from PyQt4 import QtGui, QtCore from PyQt4.QtGui import QApplication, QColumnView, QFileSystemModel, QSplitter, QTreeView from PyQt4.QtCore import Qt, QDir class Window(QtGui.QMainWindow): #Window Settings def __init__(self): super(Window, self).__init__() self.showMaximized() self.setWindowTitle("Editory") self.setWindowIcon(QtGui.QIcon('favicon.png')) #Text Window self.text = QtGui.QTextEdit(self) self.text.setTabStopWidth(12) self.setCentralWidget(self.text) # Font variables fontBox = QtGui.QFontComboBox(self) fontBox.currentFontChanged.connect(self.FontFamily) fontSize = QtGui.QComboBox(self) fontSize.setEditable(True) fontSize.setMinimumContentsLength(3) fontSize.activated.connect(self.FontSize) # Font Sizes fontSizes = ['6','7','8','9','10','11','12','13','14', '15','16','18','20','22','24','26','28', '32','36','40','44','48','54','60','66', '72','80','88','96'] for i in fontSizes: fontSize.addItem(i) #New Input new = QtGui.QAction("&New", self) new.setShortcut("Ctrl+N") new.triggered.connect(self.New) #Open Input open = QtGui.QAction("&Open", self) open.setShortcut("Ctrl+O") open.triggered.connect(self.Open) #Save Input save = QtGui.QAction("&Save", self) save.setShortcut("Ctrl+S") save.triggered.connect(self.Save) #Print Input prints = QtGui.QAction("&Print", self) prints.setShortcut("Ctrl+P") prints.triggered.connect(self.Print) #Quit Input quit = QtGui.QAction("&Quit", self) quit.setShortcut("Ctrl+Q") quit.triggered.connect(self.Quit) self.statusBar() #Menubar menubar = self.menuBar() #File Menu file = menubar.addMenu('&File') #File Inputs file.addAction(new) file.addAction(open) file.addAction(save) file.addAction(prints) file.addSeparator() file.addAction(quit) #Cut Input cut = QtGui.QAction("&Cut", self) cut.setShortcut("Ctrl+X") cut.triggered.connect(self.Cut) #Copy Input copy = QtGui.QAction("&Copy", self) copy.setShortcut("Ctrl+C") copy.triggered.connect(self.Copy) #Paste Input paste = QtGui.QAction("&Paste", self) paste.setShortcut("Ctrl+V") paste.triggered.connect(self.Paste) #Undo Input undo = QtGui.QAction("&Undo", self) undo.setShortcut("Ctrl+Z") undo.triggered.connect(self.Undo) #Redo Input redo = QtGui.QAction("&Redo", self) redo.setShortcut("Ctrl+Y") redo.triggered.connect(self.Redo) #Edit Menubar edit = menubar.addMenu('&Edit') #Edit Inputs edit.addAction(cut) edit.addAction(copy) edit.addAction(paste) edit.addSeparator() edit.addAction(undo) edit.addAction(redo) #Fullscreen Input fullscreen = QtGui.QAction("&Fullscreen", self) fullscreen.setShortcut("F11") fullscreen.triggered.connect(self.Fullscreen) #Align Left Input align_left = QtGui.QAction("&Align Left", self) align_left.triggered.connect(self.Align_Left) #Align Right Input align_right = QtGui.QAction("&Align Right", self) align_right.triggered.connect(self.Align_Right) #Align Center Input align_center = QtGui.QAction("&Align Center", self) align_center.triggered.connect(self.Align_Center) #Align Justify Input align_justify = QtGui.QAction("&Align Justify", self) align_justify.triggered.connect(self.Align_Justify) #View Menubar view = menubar.addMenu('&View') #View Inputs view.addAction(fullscreen) view.addSeparator() view.addAction(align_left) view.addAction(align_right) view.addAction(align_center) view.addAction(align_justify) #Font Family Input font_family = QtGui.QWidgetAction(self) font_family.setDefaultWidget(fontBox) #Settings Menubar settings = menubar.addMenu('&Settings') menu_font = settings.addMenu("&Font") menu_font.addAction(font_family) font_size = QtGui.QWidgetAction(self) font_size.setDefaultWidget(fontSize) menu_size = settings.addMenu("&Font Size") menu_size.addAction(font_size) self.toolbar() #Input Functions def New(self): self.text.clear() def Open(self): filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File') f = open(filename, 'r') filedata = f.read() self.text.setText(filedata) f.close() def Save(self): name = QtGui.QFileDialog.getSaveFileName(self, 'Save File') file = open(name,'w') text = self.textEdit.toPlainText() file.write(text) file.close() def Print(self): print_dialog = QtGui.QPrintDialog() if print_dialog.exec_() == QtGui.QDialog.Accepted: self.text.document().print_(print_dialog.printer()) def Quit(self): sys.exit() def Undo(self): self.text.undo() def Redo(self): self.text.redo() def Cut(self): self.text.cut() def Copy(self): self.text.copy() def Paste(self): self.text.paste() def Align_Left(self): self.text.setAlignment(Qt.AlignLeft) def Align_Right(self): self.text.setAlignment(Qt.AlignRight) def Align_Center(self): self.text.setAlignment(Qt.AlignCenter) def Align_Justify(self): self.text.setAlignment(Qt.AlignJustify) def Fullscreen(self): if not self.isFullScreen(): self.showFullScreen() else: self.showMaximized() def FontFamily(self,font): self.text.setCurrentFont(font) def FontSize(self, fontsize): self.text.setFontPointSize(int(fontsize)) #Toolbar def toolbar(self): #New Tool new = QtGui.QAction(QtGui.QIcon('icons/new.png'), 'New', self) new.triggered.connect(self.New) #Open Tool open = QtGui.QAction(QtGui.QIcon('icons/open.png'), 'Open', self) open.triggered.connect(self.Open) #Save Tool save = QtGui.QAction(QtGui.QIcon('icons/save.png'), 'Save', self) save.triggered.connect(self.Save) #Print Tool prints = QtGui.QAction(QtGui.QIcon('icons/print.png'), 'Print', self) prints.triggered.connect(self.Print) #Quit Tool quit = QtGui.QAction(QtGui.QIcon('icons/quit.png'), 'Quit', self) quit.triggered.connect(self.Quit) #Cut Tool cut = QtGui.QAction(QtGui.QIcon('icons/cut.png'), 'Cut', self) cut.triggered.connect(self.Cut) #Copy Tool copy = QtGui.QAction(QtGui.QIcon('icons/copy.png'), 'Copy', self) copy.triggered.connect(self.Copy) #Paste Tool paste = QtGui.QAction(QtGui.QIcon('icons/paste.png'), 'Paste', self) paste.triggered.connect(self.Paste) #Undo Tool undo = QtGui.QAction(QtGui.QIcon('icons/undo.png'), 'Undo', self) undo.triggered.connect(self.Undo) #Redo Tool redo = QtGui.QAction(QtGui.QIcon('icons/redo.png'), 'Redo', self) redo.triggered.connect(self.Redo) #Toolbar Menu self.toolbar = self.addToolBar("Toolbar") self.toolbar.addAction(new) self.toolbar.addAction(open) self.toolbar.addAction(save) self.toolbar.addSeparator() self.toolbar.addAction(cut) self.toolbar.addAction(copy) self.toolbar.addAction(paste) self.toolbar.addSeparator() self.toolbar.addAction(undo) self.toolbar.addAction(redo) self.toolbar.addSeparator() self.toolbar.addAction(prints) self.toolbar.addSeparator() self.toolbar.addAction(quit) #Reveals The Toolbar self.show() #Run Function def run(): app = QtGui.QApplication(sys.argv) GUI = Window() sys.exit(app.exec_()) run() I attempted to use the answer provided by Drewness and plug it into my code but I got this error: TypeError: 'QTextEdit' object is not callable A: First of all, having a lot does not help to have a legible code, so I took the liberty of reducing it and ordering it. You must set a QTabWidget as centralWidget, and in each tab create a QTextEdit, but you must have a current QTextEdit, which is changed when another tab is selected, for this you must use the currentChanged signal. All actions must be done to that QTextEdit, and in the case of new and open you have to create a QTextEdit, and fill it in if necessary. import os import sys from PyQt4 import QtGui, QtCore class Window(QtGui.QMainWindow): def __init__(self): super(Window, self).__init__() self.showMaximized() self.setWindowTitle("Editory") self.setWindowIcon(QtGui.QIcon('favicon.png')) self.current_editor = self.create_editor() self.editors = [] self.tab_widget = QtGui.QTabWidget() self.tab_widget.setTabsClosable(True) self.tab_widget.currentChanged.connect(self.change_text_editor) self.tab_widget.tabCloseRequested.connect(self.remove_editor) self.new_document() self.setCentralWidget(self.tab_widget) self.configure_menuBar() self.configure_toolbar() def configure_menuBar(self): menubar = self.menuBar() menubar_items = { '&File': [ ("&New", "Ctrl+N", self.new_document), ("&Open", "Ctrl+O", self.open_document), ("&Save", "Ctrl+S", self.save_document), ("&Print", "Ctrl+P", self.print_document), None, ("&Quit", "Ctrl+Q", self.quit), ], '&Edit': [ ("&Cut", "Ctrl+X", self.cut_document), ("&Copy", "Ctrl+C", self.copy_document), ("&Paste", "Ctrl+V", self.paste_document), None, ("&Undo", "Ctrl+Z", self.undo_document), ("&Redo", "Ctrl+Y", self.redo_document) ], '&View': [ ("&Fullscreen", "F11", self.fullscreen), None, ("&Align Left", "", self.align_left), ("&Align Right", "", self.align_right), ("&Align Center", "", self.align_center), ("&Align Justify", "", self.align_justify) ] } for menuitem, actions in menubar_items.items(): menu = menubar.addMenu(menuitem) for act in actions: if act: text, shorcut, callback = act action = QtGui.QAction(text, self) action.setShortcut(shorcut) action.triggered.connect(callback) menu.addAction(action) else : menu.addSeparator() # Font Family Input fontBox = QtGui.QFontComboBox(self) fontBox.currentFontChanged.connect(self.FontFamily) fontSize = QtGui.QComboBox(self) fontSize.setEditable(True) fontSize.setMinimumContentsLength(3) fontSize.activated.connect(self.FontSize) # Font Sizes fontSizes = ['6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '18', '20', '22', '24', '26', '28', '32', '36', '40', '44', '48', '54', '60', '66', '72', '80', '88', '96' ] fontSize.addItems(fontSizes) font_family = QtGui.QWidgetAction(self) font_family.setDefaultWidget(fontBox) # Settings Menubar settings = menubar.addMenu('&Settings') menu_font = settings.addMenu("&Font") menu_font.addAction(font_family) font_size = QtGui.QWidgetAction(self) font_size.setDefaultWidget(fontSize) menu_size = settings.addMenu("&Font Size") menu_size.addAction(font_size) def configure_toolbar(self): items = (('icons/new.png', 'New', self.new_document), ('icons/open.png', 'Open', self.open_document), ('icons/save.png', 'Save', self.save_document), None, ('icons/cut.png', 'Cut', self.cut_document), ('icons/copy.png', 'Copy', self.copy_document), ('icons/paste.png', 'Paste', self.paste_document), None, ('icons/undo.png', 'Undo', self.undo_document), ('icons/redo.png', 'Redo', self.redo_document), None, ('icons/print.png', 'Print', self.print_document), None, ('icons/quit.png', 'Quit', self.quit), ) self.toolbar = self.addToolBar("Toolbar") for item in items: if item: icon, text, callback = item action = QtGui.QAction(QtGui.QIcon(icon), text, self) action.triggered.connect(callback) self.toolbar.addAction(action) else : self.toolbar.addSeparator() def remove_editor(self, index): self.tab_widget.removeTab(index) if index < len(self.editors): del self.editors[index] def create_editor(self): text_editor = QtGui.QTextEdit() text_editor.setTabStopWidth(12) return text_editor def change_text_editor(self, index): if index < len(self.editors): self.current_editor = self.editors[index] # Input Functions def new_document(self, checked = False, title = "Untitled"): self.current_editor = self.create_editor() self.editors.append(self.current_editor) self.tab_widget.addTab(self.current_editor, title + str(len(self.editors))) self.tab_widget.setCurrentWidget(self.current_editor) def open_document(self): filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File') if filename: f = open(filename, 'r') filedata = f.read() self.new_document(title = filename) self.current_editor.setText(filedata) f.close() def save_document(self): name = QtGui.QFileDialog.getSaveFileName(self, 'Save File') file = open(name, 'w') if file: text = self.current_editor.toPlainText() file.write(text) file.close() def print_document(self): print_dialog = QtGui.QPrintDialog() if print_dialog.exec_() == QtGui.QDialog.Accepted: self.current_editor.document().print_(print_dialog.printer()) def quit(self): self.close() def undo_document(self): self.current_editor.undo() def redo_document(self): self.current_editor.redo() def cut_document(self): self.current_editor.cut() def copy_document(self): self.current_editor.copy() def paste_document(self): self.current_editor.paste() def align_left(self): self.current_editor.setAlignment(Qt.AlignLeft) def align_right(self): self.current_editor.setAlignment(Qt.AlignRight) def align_center(self): self.current_editor.setAlignment(Qt.AlignCenter) def align_justify(self): self.current_editor.setAlignment(Qt.AlignJustify) def fullscreen(self): if not self.isFullScreen(): self.showFullScreen() else : self.showMaximized() def FontFamily(self, font): self.current_editor.setCurrentFont(font) def FontSize(self, fontsize): self.current_editor.setFontPointSize(int(fontsize)) def run(): app = QtGui.QApplication(sys.argv) GUI = Window() sys.exit(app.exec_()) run()
{ "pile_set_name": "StackExchange" }
Q: How to get login history of a facebook user How can I get the login history of a facebook user? I want to get a timestamp; when user successfully logged in to facebook using facebook.com. Is there a way? A: There is no Facebook API which can be used to retrieve that information
{ "pile_set_name": "StackExchange" }
Q: Can't combine the two xpath expression in a single one I've written an xpath to locate a certain element. However, the thing is the element i'm after may be available in either childNodes[10] or childNodes[12]. I'would like to create an expression combining the two in a single expression and it will still locate the both irrespective of its position. The two expressions are: First one: element = driver.find_element_by_xpath("//td[@class='data']/table//th") name = driver.execute_script("return arguments[0].childNodes[10].textContent", element).strip() Second one: element = driver.find_element_by_xpath("//td[@class='data']/table//th") name = driver.execute_script("return arguments[0].childNodes[12].textContent", element).strip() I tried like this but won't get any result: element = driver.find_element_by_xpath("//td[@class='data']/table//th") name = driver.execute_script("return arguments[0].childNodes[10].textContent|return arguments[0].childNodes[12].textContent", element).strip() How can I cement the both in a single expression? Btw, I'm using this xpath in python + selenium script. Here is the link to the html: "https://www.dropbox.com/s/vl8anp8te48ktl2/For%20SO.txt?dl=0" A: If one of text nodes is an empty string you can try: element = driver.find_element_by_xpath("//td[@class='data']/table//th") name = driver.execute_script("return arguments[0].childNodes[10].textContent", element).strip() or driver.execute_script("return arguments[0].childNodes[12].textContent", element).strip() This should return you name with non-empty string (the first occurence of non-empty text node)
{ "pile_set_name": "StackExchange" }