text
stringlengths
64
81.1k
meta
dict
Q: Passing query string to ModelForm hidden field - Django I want to pass a query string e.g., ?refcode='A1234' to a hidden field called inbound_referral_code in a ModelForm. My model is as follows: class User(models.Model): email = models.EmailField(max_length=255, blank=False, unique=True) inbound_referral_code = models.CharField(max_length=255) My ModelForm is currently as follows: class UserForm(forms.ModelForm): model = User fields = ['email', 'inbound_referral_code'] widgets = {'inbound_referral_code': forms.HiddenInput()} My View is: def register(request): if request.method == 'POST': form = UserForm(request.POST) [...] else: form = UserForm() return render(request, 'register.html', {'form': form}) And my template is currently: <form action="{% url 'register' %}" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"/> </form> Two questions: How do I assign ?refcode parameter to inbound_referral_code field? What happens if ?refcode isn't provided? A: Combining the different answers, the following solution worked: Set the "initial" value of the form parameter, and ensure the template renders with the bound form if validation fails. The correct view function is: def register(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): return redirect([...]) else: refcode = request.GET.get('refcode') form = UserForm(intial={'inbound_referral_code': refcode) return render(request, 'register.html', {'form': form}) Note that the bottom return render(...) needed to be moved so that it is also called with the form from the POST request if it contains validation errors...
{ "pile_set_name": "StackExchange" }
Q: Selenium on Python test result is ran 0 tests in 0.000s I'm doing selenium tests in Python and I have many tests in project. I migrated from linux server to windows test server (browser and tests are running on this server) Everything goes fine, but every new test that is created I can't run and I don't know why. It writes "Ran 0 test in 0.000s" "OK" Other test I can run properly. Two commands in cmd (first is failing, second is correct): C:\Python27\python.exe -m unittest discover ../autotesty "test_systemlive_2_4_2_6-7_extensions.py" C:\Python27\python.exe -m unittest discover ../autotesty "test_systemlive_2_4_2_1_new_rec_unit.py" File test_systemlive_2_4_2_6-7_extensions.py - Failed test (this writes to cmd "Ran 0 tests in 0.000s" "OK"): # coding=utf-8 __author__ = 'u-zima00m1' from lib import selenium_tools as st import unittest import time class Extensions(unittest.TestCase): def setUp(self): st.set_up(self) def test_13_01_extensions(self): driver = self.driver st.login(self, "bossboss", "Bossboss1") st.select_roles(self, "God", "root") st.switch_to_page(self, "System") st.switch_to_sub_page(self, "CTI") st.switch_to_sub_sub_page(self, "CTI Servers") st.wait_for_element(self, "//a[@title='New']/img[@src='/experience/img-dist/New.svg']", "XPATH") driver.find_element_by_xpath("//a[@title='New']/img[@src='/experience/img-dist/New.svg']").click() time.sleep(1) # Other long code ... def tearDown(self): st.tear_down(self) if __name__ == "__main__": unittest.main() File tests_systemlive_2_4_2_1_new_rec_unit.py - Correct test (this will run browser and selenium does his job): # coding=utf-8 __author__ = 'u-zima00m1' from lib import selenium_tools as st import unittest import time class NewRecUnit(unittest.TestCase): def setUp(self): st.set_up(self) def test_10_01_create_RU(self): driver = self.driver suite = unittest.TestLoader().discover('.', pattern="rex_simulator.py") unittest.TextTestRunner(verbosity=3).run(suite) st.login(self, "bossboss", "Bossboss1") st.select_roles(self, "God", "root") st.switch_to_page(self, "System") st.switch_to_sub_page(self, "Recording sources") st.switch_to_sub_sub_page(self, "Recording units") driver.find_element_by_xpath("//a[@title='New']/img[@src='/experience/img-dist/New.svg']").click() time.sleep(1) # Other long code ... def tearDown(self): st.tear_down(self) if __name__ == "__main__": unittest.main() setUp and tearDown in both tests are from the same method - there isn't problem I think. Any solutions? A: It is dash (-) in filename "test_systemlive_2_4_2_6-7_extensions.py"
{ "pile_set_name": "StackExchange" }
Q: Multiline Text in a WPF Button How do I get multi-line text on a WPF Button using only C#? I have seen examples of using <LineBreak/> in XAML, but my buttons are created completely programmatically in C#. The number and labels on the buttons correspond to values in the domain model, so I don't think I can use XAML to specify this. I have tried the naive approach below, but it does not work. Button b = new Button(); b.Content = "Two\nLines"; or b.Content = "Two\r\nLines"; In either case, all i see is the first line ("Two") of the text. A: OR in XAML directly: <Button> <TextBlock>Two<LineBreak/>Lines</TextBlock> </Button> A: I prefer this way: <Button Width="100"> <TextBlock TextWrapping="Wrap">This is a fairly long button label</TextBlock> </Button> it worked for me. A: Answer is very simple. Just use &#xa; to introduce line-break, i.e.: <Button Content="Row 1 Text &#xa; Row 2 Text"/>
{ "pile_set_name": "StackExchange" }
Q: Plot discrete values using geom tile and scale_gradient_manual I have the following part of a data frame which is much bigger than this: x y A 1 1 0.1176405 2 2 0.1176405 3 3 0.1219375 4 4 0.09942536 5 5 0.1031696 6 6 0.1384145 And I'm trying to plot using ggplot2: p <- ggplot(df, aes(x,y)) + geom_tile(aes(fill=A))+ scale_fill_gradient(low = "black", high = "red") But I always get this error: Error: Non-continuous variable supplied to scale_fill_gradient. When I try as.numeric(A) in the plot it does work but the values in the plot looks weird and does not present my values. that's the output of str(): 'data.frame': 289 obs. of 3 variables: $ x: num 1 2 3 4 5 ... $ y: num 1 2 3 4 5 6 7 8 9 10 ... $ A: Factor w/ 181 levels "0.1176405","0.1219375",..: 1 1 2 3 4 4 5 6 7 8 ... So what should I do to make this plot work? A: Looks like A in your data frame is a factor and needs to be converted to numeric. Try: df$A <- as.numeric(as.character(df$A)) and then run your code. Casting factors to numeric with as.numeric without converting to character first is a common gotcha: as.numeric(factor(50:55)) [1] 1 2 3 4 5 6 See R Inferno 8.2.1
{ "pile_set_name": "StackExchange" }
Q: python- list of tuples loop; check if any tuple element is in the next tuple I have a list of tuples like: list=[('Jim','Pam'),('Jim','Homer'),('Bart','Marge')] I am trying to compare the elements of the current tuple with the elements of the next tuple and print "back to back". In my list, 'Jim' appears in list element 0 and list element 1, so it should print back to back. This is not the case in list elements 1 and 2. I've attempted: for pair in list: for i in range(len(list)): if pair[0] or pair[1] in list[i+1]: print("back to back") A: You can zip list with list[1:] to get all adjacent pairs. for a, b in zip(lst, lst[1:]): if any(x in b for x in a): print("back to back")
{ "pile_set_name": "StackExchange" }
Q: .htaccess 301 redirect example /old-page/?utm_source=twitter.com to /new-folder/new-page/?utm_source=twitter.com Been hacking away at this for a while now. How would I redirect old pages and their folder structures to new pages and their folder structures with everything intact in the URL at the end? Something like: RedirectMatch 301 /old-page/(.*) /new-folder/new-page/$1 A: RewriteRule ^old-page/(.*) /new-folder/new-page/$1 [L,R] L flag tells Apache that it's the last rule to be executed for any matches. R flag does the redirect with 302 as default; if you want a different redirect type, use [L,R=301] for example.
{ "pile_set_name": "StackExchange" }
Q: How can I use execle with a va_list like execvpe? The version of glibc I am using does not have the execvpe function. However, I need that exact functionality for what I am trying to do. The user will pass in an argument list that is their linux command for me to run (with its argument list). Here is what it looks like: foo.c int main(int argc, char *argv[], char *envp[]) { char * newenvp[] = ...; execvpe(argv[1], &argv[1], newenvp); } Example Usage foo echo -e "Hello World.\n" Is there a workaround to replace execvpe with execle? A: I believe I have solved my own question. A workaround for using execvpe is to use setenv followed by execvp. I believe the functionality is the same: int main(int argc, char *argv[], char *envp[]) { setenv("MYVAR", "MYVALUE", 1); /* More calls to setenv can be used if needed. */ execvp(argv[1], &argv[1]); }
{ "pile_set_name": "StackExchange" }
Q: intuition behind the revelance of hyperbolic polynomial A hyperbolic polynomial $p$ is a homogenous polynomial such that given any direction $e$, and any scalar $t$ $$ p(x - t e) \text{ has only real roots}. \tag{1} $$ This is how many texts on hyperbolic polynomial starts. The definition above is intuitive, but what are its practical implications? To give a comparison, in linear programming the objective is down to earth: maximize a linear polynomial over a constrained sets. With hyperbolic polynomial, the texts generally continue from the definition above by saying that the function in (1) is convex and they give several other properties. What is the big picture? Where does this help in solving an optimization problem? A: Let me give a little example. In the plane, take $$ f(x,y) = xy. $$ This is an indefinite quadratic form. When $e = (A,B)$ with both $A,B \neq 0,$ then any line in the plane $\vec{x} + t \vec{e}$ will intersect the pair of axes twice, no matter where the starting point $\vec{x}$ might lie. This includes the case going through the origin with a double root. However, if $\vec{e} = (1,0)$ with $\vec{x} = (1,1),$ the line $\vec{x} + t \vec{e}$ intersects the axes just once, at $(0,1).$ Indeed, $f(\vec{x} + t \vec{e}) = f(1+t, 1) = 1+t $ has only one root... need to read something careful about this. There needs to be something about the number of roots staying constant counting multiplicity.
{ "pile_set_name": "StackExchange" }
Q: How can I be a good reviewer? Someday, as strange as it feels to me right now, I might be asked to review an article for publication. A while ago my advisor and I were talking about this, and it hit me that I don't really know how to be a good reviewer, beyond the basics: Respond timely to things, Make your report clear and detailed, Have actually read the paper, Etc. Beyond this, though, I'm completely in the dark. So I'd like to ask: What's some good advice for a first-time reviewer? My field is math, but I'm really interested in general advice (although advice specific to math, or another field, would also be interesting and useful). I'd like to make this question "community wiki" or analogous, but I can't seem to figure out how - if someone can do so, please do, and then I will delete this paragraph. A: This is mostly just a whole bunch of comments strung together. First, I think you should look for advice specific to refereeing math papers, as refereeing in math is quite different than most other fields. (Though it's perfectly valid to ask for general advice now, at some point you should want to know about refereeing specifically in math.) Second, here are some places with advice: Attributes of an ideal referee, Notices of the AMS Refereeing a paper, from MathOverflow How do I referee a paper, from TCS SE One thing I would disagree with in the first article is the statement that "The referee is expected primarily to check the correctness of the paper." I would say the primary job is to assess the importance of the paper, which includes correctness, though it is not always expected that the referee check every detail. Anyway, since your question is rather broad, I suggest you read this and other Q&A's here and on MO, and then if you have more specific questions you can ask them separately. A: I think reviewing is a good "golden rule" situation: treat others as you yourself would like to be treated. For me, that means: Be prompt Be respectful and professional in tone State clearly what you find of value in the paper, as well as your critiques Clearly separate critiques into three categories: Serious problems that can affect the soundness or relevance of the work presented Issues that need to be addressed, but don't call the work into question Minor points for the improvement and polishing of the manuscript. Base all of your statements on supportable fact, not opinion. A: in addition to the above; Be frank if you: a) are unable to be timely b) feel you are not qualified to review the article (lacking knowledge in the used methodology, statics or field). This will save all parties time and resources
{ "pile_set_name": "StackExchange" }
Q: Duplicate PK in MySQL I was told a while ago on this site that the only way to go with a many-to-many (in my case a facebook-ish "friend-ing" system) is to do something like this: uid(PK) friend_id 4 23 4 20 4 54 32 20 32 89 Wont this leave me with lots of identical primary keys (which i believe isn't possible?) And if I can't set uid as a PK, how can I quickly search the table? There must be a way to get away with this with a PK. Thanks! A: make it a composit key PK = (uid,frield_id) A: If you have a many to many relationship, you can develop a table in between where you create a dual primary key with the UID and the Friend_ID together. That way there should only be one instance of a pair of UID/Friend_ID.
{ "pile_set_name": "StackExchange" }
Q: Suppose $V$ is a vector space such that the only subspaces of $V$ are $\{0\}$ and $V$. Determine the dimension of $V$. Suppose $V$ is a vector space such that the only subspaces of $V$ are $\{0\}$ and $V$. Determine the dimension of $V$. I have no idea how to prove that. I know that $\{0\}$ and $V$ are always subspaces of $V$. That is we have to find subspace having no proper subspaces and find its dimension. How to get this. Please help. A: Let $v\in V$ be a non-zero vector. Then $\Bbb R\cdot v = \{r\cdot v: r\in\Bbb R\}$ is a subspace. Since it is clearly not the zero subspace, it is all of $V$ by assumption. So by definition $V$ has dimension $1$.
{ "pile_set_name": "StackExchange" }
Q: Prove that a homomorphism is injective or trivial Let A,B be groups, and assume that |A| = 29. Let φ:A→B be a homomorphism. a) Prove that either φ is injective or trivial. (φ is trivial if for all a∈A φ(a) = e) b) If |B|=80, prove that φ is trivial. Now I know that a homomorphism is injective iff the kernel is trivial. But I can't seem to figure out how to start this question. Should I assume by contradiction that φ is not injective and not trivial and try to arrive at a contradiction? Or should I show that the kernel is trivial so φ has to be injective. Any hints or suggestions would be really appreciated. Thanks! A: By the first isomorphism theorem, $A/\ker\varphi \cong \varphi(A)$. In particular: \begin{equation}\frac{29}{|\ker\varphi|}=|\varphi(A)|.\end{equation} Since 29 is a prime number, either $\ker\varphi=\{0\}$ (which implies $\varphi$ is injective) or $\ker\varphi=A$ (i.e. $\varphi$ is trivial). If $|B|=80$ then since $\varphi(A)$ is a subgroup of $B$, $|\varphi(A)|$ divides $80$ by Lagrange's theorem. But $|\varphi(A)|$ also divides 29, so $|\varphi(A)|=1$ and $|\ker\varphi|=29$, which implies $\varphi$ is trivial. A: Hints: The kernel of $\phi$ is a subgroup of $A$. The order of a subgroup must divide the order of the group. The image of $\phi$ is a subgroup of $B$.
{ "pile_set_name": "StackExchange" }
Q: How can I access block metadata from custom plugin instance? Using the block_example module, I created two instances of the example_configurable_text block in the UI and would like to now access their underlying metadata, specifically uuids. By looking at the config table in the database, I can see that there is a record for each (select * from config where name like "%example%";). However, when I debug ExampleConfigurableTextBlock::build, I can't seem to access any of it. I'm aware that configuration can be loaded via \Drupal::config('<name>'), but I need to be able to access the configuration dynamically from with my plugin class instance. Is extending BlockBase the right way to go? Do I need to use derivatives? What is the connection between a block instance in the config table and an instance of a block plugin? So many questions. A: Generate unique form ID based on context contains the answer you're looking for. Short answer is, you have to make this unique id yourself. See the mentioned simplenews project and how I solved it there. Keep in mind that block plugins are not only usable by core block entities, they can also be used by Page Manager/Panels, where you have many blocks in a single variant and even by projects like block_field, which allow to use block plugins on content entities. You must not rely on anything but your own configuration array. I think I once opened a core issue about this, to introduce a method so that a unique ID can bet set on a block plugin, but I can't find it anymore, only another core issue (https://www.drupal.org/node/2405879) where I mentioned that I can't find that issue anymore :)
{ "pile_set_name": "StackExchange" }
Q: Can the Forbiddance spell be placed on a moving area? (like a ship) The spell Forbiddance reads: Forbiddance seals an area against all planar travel into or within it. Can this area be mobile? Such as a the deck of a ship? More specifically, my campaign is in Eberron, can this be used on an airship? A: There is no RAW answer The rules do not address this case (casting an location-based spell on a movable location). You would have to venture outside RAW to find an answer.
{ "pile_set_name": "StackExchange" }
Q: How should I unit test Java that calls a MySQL stored procedure? I'm writing a simple application that will read some records and insert them in a database. I've written a stored procedure that handles the insertion logic, and plan to test that separately. Now I'd like to write a good unit test for the portion of the logic that takes a business object and passes it to the stored procedure call. I think what I want to do is pass a mock of the database connection, then assert that the call is made with expected parameter values: Connection dbConnection = makeMockConnection(); // how? MyObjectWriter writer = new MyObjectWriter(dbConnection); writer.write(someSampleObject); // somehow assert that dbConnection called // `sp_saveMyObject` with param values x, y, and z However, it seems like a lot of work dig around inside java.sql.Connection, understand how it works, then mock all the results. Is there a test library that does all this for me? Am I coming at this the wrong way? A: You could create an in-memory HSSQL database with a mock stored procedure. The mock sproc would insert a row into a table to show that it ran and what it's parameters were. Run the code under test and then look in the db to see what happened.
{ "pile_set_name": "StackExchange" }
Q: Java - Get metadata of files in a directory with million files in it I am writing a Java app to get the file metadata of files in a directory and exporting it to a csv file. The app works fine if the number of files is less. But if I feed in a path that has like a 320000 files in all of directories and sub-direcories it is taking forever. Is there a way I can speed up things here ? private void extractDetailsCSV(File libSourcePath, String extractFile) throws ScraperException { log.info("Inside extract details csv"); try{ FileMetadataUtil fileUtil = new FileMetadataUtil(); File[] listOfFiles = libSourcePath.listFiles(); for(int i = 0; i < listOfFiles.length; i++) { if(listOfFiles[i].isDirectory()) { extractDetailsCSV(listOfFiles[i],extractFile); } if(listOfFiles[i].isFile()){ ScraperOutputVO so = new ScraperOutputVO(); Path path = Paths.get(listOfFiles[i].getAbsolutePath()); so.setFilePath(listOfFiles[i].getParent()); so.setFileName(listOfFiles[i].getName()); so.setFileType(getFileType(listOfFiles[i].getAbsolutePath())); BasicFileAttributes basicAttribs = fileUtil.getBasicFileAttributes(path); if(basicAttribs != null) { so.setDateCreated(basicAttribs.creationTime().toString().substring(0, 10) + " " + basicAttribs.creationTime().toString().substring(11, 16)); so.setDateLastModified(basicAttribs.lastModifiedTime().toString().substring(0, 10) + " " + basicAttribs.lastModifiedTime().toString().substring(11, 16)); so.setDateLastAccessed(basicAttribs.lastAccessTime().toString().substring(0, 10) + " " + basicAttribs.lastAccessTime().toString().substring(11, 16)); } so.setFileSize(String.valueOf(listOfFiles[i].length())); so.setAuthors(fileUtil.getOwner(path)); so.setFolderLink(listOfFiles[i].getAbsolutePath()); writeCsvFileDtl(extractFile, so); so.setFileName(listOfFiles[i].getName()); noOfFiles ++; } } } catch (Exception e) { log.error("IOException while setting up columns" + e.fillInStackTrace()); throw new ScraperException("IOException while setting up columns" , e.fillInStackTrace()); } log.info("Done extracting details to csv file"); } public void writeCsvFileDtl(String extractFile, ScraperOutputVO scraperOutputVO) throws ScraperException { try { FileWriter writer = new FileWriter(extractFile, true); writer.append(scraperOutputVO.getFilePath()); writer.append(','); writer.append(scraperOutputVO.getFileName()); writer.append(','); writer.append(scraperOutputVO.getFileType()); writer.append(','); writer.append(scraperOutputVO.getDateCreated()); writer.append(','); writer.append(scraperOutputVO.getDateLastModified()); writer.append(','); writer.append(scraperOutputVO.getDateLastAccessed()); writer.append(','); writer.append(scraperOutputVO.getFileSize()); writer.append(','); writer.append(scraperOutputVO.getAuthors()); writer.append(','); writer.append(scraperOutputVO.getFolderLink()); writer.append('\n'); writer.flush(); writer.close(); } catch (IOException e) { log.info("IOException while writing to csv file" + e.fillInStackTrace()); throw new ScraperException("IOException while writing to csv file" , e.fillInStackTrace()); } } } A: Many filesystems are not efficient at handling directories with that many entries in them. There's very little you can do, codewise, to fix that. You need to try to move those files into multiple directories, to get better speed. Other possible reasons for slowness are that you're either using a data structure that takes O(n) for each entry (resulting in O(n²) total runtime), or you're running out of heap space (so that GC dominates runtime).
{ "pile_set_name": "StackExchange" }
Q: Jpg content type I have the next content-types: image/gif image/png application/vnd.ms They all work and recognized the files (gif, png, xls)... But what is the content-type for jpg? i know that its the type for jpeg: image/pjpeg , image/jpeg But it's not work for jpg. (I use that with the code: if (contentType == "image/JPEG") ..... if (contentType == "image/gif")... For category the files by their extension. maybe there is other way to do that? not by content- type ?) A: Caveat: I know almost zero C#. I suspect this is a casing issue. Try this: if (contentType.ToLower() == "image/jpeg") RFC1341 indicates that The type, subtype, and parameter names are not case sensitive. For example, TEXT, Text, and TeXt are all equivalent. This means that if contentType is coming verbatim from a user-agent, it could have any capitalization, or none at all.
{ "pile_set_name": "StackExchange" }
Q: MySQL How to check if an value is already in the results? I've got a complicated problem. How can I force MySQL to replace the first "command.deagle2" (Mode 1) with the second "command.deagle2" (Mode 0) ? I simply show you the code and I hope you can help me. Here my code: SELECT DISTINCT `right`.`name` AS `Right`, 1 AS `Mode` FROM `user` INNER JOIN `user_group` ON `user`.`id` = `user_group`.`user_id` INNER JOIN `group` ON `user_group`.`group_id` = `group`.`id` INNER JOIN `group_right` ON `group`.`id` = `group_right`.`group_id` INNER JOIN `right` ON `group_right`.`right_id` = `right`.`id` WHERE `user`.`username` = 'Dominik' UNION SELECT DISTINCT `right`.`name` AS `Right`, `user_right`.`mode` AS `Mode` FROM `user`, `right`, `user_right` WHERE `user`.`id` = `user_right`.`user_id` AND `right`.`id` = `user_right`.`right_id` AND `user`.`username` = 'Dominik' This query returns the following results: Right | Mode ----------------------- command.deagle | 1 command.deagle2 | 1 command.gmx | 1 command.givegun | 1 command.deagle2 | 0 Sample dataset: http://pastebin.com/m5LHsDRi I already saw that there is an REPLACE keyword, but I dont really know how to use it properly. Thanks for your Time. Dominik A: I take it your "mode" column constitutes a priority, and you want the only the distinct value of "Right" with the lowest-numbered priority in your result set. Try wrapping this query around the query you gave us: SELECT Right, MIN(Mode) AS Mode, FROM ( /* your big query */ ) AS q GROUP BY Right That will give you what you want. By the way, you can remove the DISTINCT keyword from your main query if you do this; the GROUP BY will fill the same purpose.
{ "pile_set_name": "StackExchange" }
Q: Plone's MailHost queue processor thread is stopped at startup I have problems with the queue processor of the MailHost. If I enable the mail queue in the ZMI the processor thread starts inmediately, but if I restart plone the processor thread never starts itself, I must log into the ZMI and start it manually. Since I have never used the mail queue in Plone I don't know if this is the correct behavior. If I must start the processor thread manually I think the mail queue is unusable on a production site. Anyone there that can help me to get the processor thread started automatically on plone startup? A: I see the same after startup, but after I send the first mail (using the sendto_form) the queue processor thread is listed as running. So it looks like the queue processor thread only starts up at the moment you send the first mail. After that, it keeps running. This is in a Plone 4.2 that is restarted at least several times a week by memmon. I checked, and no mails are lingering in the mail queue directory.
{ "pile_set_name": "StackExchange" }
Q: in-app purchase for auto-renewal subscriptions notifications I've been reading the various threads on in-app purchases auto-renewal subscriptions, and I think I've pieced together most of the information I need, but there are a few missing pieces. I'm hoping someone can help me. The situation: I have various subscription packages the user can subscribe to (e.g., package A for £1 a month, package B for £2 a month, etc.). I store the user's subscription information in my database. When the user logs in, I check which package he's on and if it's expired or not. My website, android and iOS all use the same database, hence this approach seems to make sense. Subscribing users via in-app purchase seems straight forward enough. I check paymentQueue and once the payment is cleared, I can update my database. My questions: 1) My understanding is the user can use iTunes to manage their subscription. Say, they go in to iTunes and cancel their subscription, how can I be notified so I can update my database? Do I need a daemon that checks expired subscriptions to see if the user renewed? 2) If the user wants to upgrade their subscription from Package A to Package B, how do I handle the pricing? Say on Jan 1st, they buy Package A, I charge them £1.00 and set the expiry date to Jan. 31st. On Jan. 15th, they want to upgrade to package B via in-app purchase. Ideally, I would charge them £2 for Package B minus £0.50 of credit they have for Package A and set the new expiry date to feb 14th. However, Apple forces me to associate each package with a tier price. How can I handle this? I don't want the user to wait until the end of the month to put them on a higher tier package...if they upgraded mid-month, it means they want the new content package B will deliver to them immediately. Any help appreciated! Thanks! A: EDITED For the second question, Apple's auto-renewable subscription system does not technically offer upgradeable plans between different products. Every subscription is a stand alone product and it's up to the user to turn on/off subscriptions manually using the Subscription Manager in the iTunes Store. However if package A and package B offer the exact same content only different duration than what ajay_nasa said is correct, you can create an single auto-subscription product with different duration options. If the user is on 1 month subscription and then the user tries to change to 2-months subscription they will get the following error message asking them go to the App Store's subscriptions manager So basically the ONLY place the user can actually change the subscription's length is in the App Store. Whether Apple decide to pro-rate the amount left on the old subscription or just append it to the current one is really up to Apple. You need to make sure the user have access to the subscription as long as it's active by reading the Original Purchase Date and Subscription Expiration Date field from each receipt entry and determining the start and end dates of the subscription. A: 1) Yes you'll have to reverify your receipt check out the Receipt Validation Programming Guide in the documentation. They mention some important keys: status - 0 if receipt is valid, or an error code receipt - JSON response of the receipt latest_receipt (auto-renewable only) - base 64 encoded receipt for the most recent renewal latest_receipt_info - JSON version of latest_receipt With this information, when a purchase is made, send the receipt to your backend for validation, the backend will keep the receipt in the DB and verify with status = 0 that it's a valid receipt. From there, every x days you can validate that receipt with a chron job, daemon, etc. and reverify. The response back each time will have latest_receipt_info that you now need to save to your DB so you have an up-to-date receipt for the next check in x days. This way you will always have the latest receipt. There is no instant notification for telling when a user cancels a subscription, but with this you'll know every x days if they have the subscription still. 2) Pricing like this unfortunately can't be handled. It was not intended for a user to "upgrade" with subscriptions - each subscription is access to it's own exclusive content as of this writing. However, if a customer emails in and complains about it, you could ask for their user name and figure out in your DB if this user has indeed upgraded mid-month and reimburse them appropriately. Very old-school and not feasible for a big user base, but hopefully you won't have that many and can keep them happy.
{ "pile_set_name": "StackExchange" }
Q: Render asp.net partial in Bootstrap modal I need to display a partial (view component) in a bootbox control. This partial receive some parameters from my current view and build a form to be submitted. Until MVC 5 I did that rendering my partial to a string and send it back to view. In MVC 6 I can't get this to work. What is the correct way to do this? A: After some research, I find out a way to do this, very easily. Just use the jquery's "load" function. The example bellow is using default WebApplication created by VisualStudio. Main view code (Views/Home/About.cshtml): <button class="btn btn-default details" >Click me</button> <div class="modal" id="modal"></div> @section scripts{ <script> $(function () { $(".details").click(function () { $("#modal").load("Contact", function () { $("#modal").modal(); }) }); }) </script> } Modal view code (Views/Home/Contact.cshtml): <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button> <h4 class="modal-title">Modal title</h4> </div> <div class="modal-body"> <address> One Microsoft Way<br /> Redmond, WA 98052-6399<br /> <abbr title="Phone">P:</abbr> 425.555.0100 </address> <address> <strong>Support:</strong> <a href="mailto:[email protected]">[email protected]</a><br /> <strong>Marketing:</strong> <a href="mailto:[email protected]">[email protected]</a> </address> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog -->
{ "pile_set_name": "StackExchange" }
Q: Should this design be an STI or separate models? Ive got an app where users can upload media: song, video, photos. I was thinking of having an STI called medium. Song, Video and Photo inherit from Medium. Or should I have Song, Video and Photo as separate classes / models? I also have a Comment model. If I go with an STI approach, then the Comment model would only need the medium_id as the FK. If I go with separate classes, then my Comment model would have to be polymorphic. I guess both approaches work. But which one should be more considered over the other? Second, are there any advantages? A: When you have several requirements that overlap a lot in terms of data being captured, context for presentation, and relationships, you may want to go with STI. Your example here is one of them. I find STI is often easier to manage when you're dealing with several things that are often aggregated and presented as if they are interchangeable. For instance, a list of most recently uploaded "media" would contain all of your types and could be sorted or filtered as required. It's also not uncommon to have a polymorphic relationship on a Comment class so that anything can be commented on. The only down-side to this is that polymorphic relationships are harder to join and validate on a database level, so they will always be a tiny bit slower. The more database-friendly approach is to make Comment act as a tree or list, and then have your Media model belong_to a root, placeholder comment, and the actual comment contents goes into children.
{ "pile_set_name": "StackExchange" }
Q: Accessing bit-field in C by its address What is the reason behind not allowing to access a bit field in C using its address, is it cause it might not be an address that is not system word aligned ..? or as it doesn't make sense to get bit's address within a byte...?(cause this types pointer arithmetic will be awkward ?) A: Bits do not have addresses. That's why you can't refer to them by address. The granularity of addressing is the char. I guess the reasoning is that the language was design to match the architecture it targeted, and I know of no machine which allows addressing of individual bits. A: The smallest unit of addressable memory in C is a char, because this corresponds to the smallest unit of addressable memory on most CPU architectures.* It doesn't make sense to talk about the address of a bit. * One could imagine a hypothetical machine that allowed addressing of individual bits, but it would be pretty esoteric.
{ "pile_set_name": "StackExchange" }
Q: some manual calculations I have a ratio between two probabilities $$ \frac{(1-p)^{1000}+1000*p*(1-p)^{999}}{ \binom{1000}{2}*p^2*(1-p)^{998}}$$ and it is asked to show that this ratio is >1 (without a calculator) $p=2/1000$ I arrived to this passage. $$ \frac{(1-p)^{1000}+1000*p*(1-p)^{999}}{ \binom{1000}{2}*p^2*(1-p)^{998}}= \frac{(1-p)^{2}+1000*p*(1-p)}{ 500*999*p}$$ Then the suggested solution says $$ \frac{(1-p)^{2}+2*p*(1-p)}{ 999*p}$$ but i don't understant where does it come from? it there something that I'm ignoring? A: Write ${1000 \choose 2}=\frac 12 \cdot 1000 \cdot 999$. Divide numerator and denominator by $(1-p)^{998}$ and use the extra factor of $p$ in the denominator to cancel the $\frac {1000}2$
{ "pile_set_name": "StackExchange" }
Q: WWV, WWVH, and WWVL may be shut down. Are there any alternatives? The US government is proposing to shut down the NIST standard time and frequency stations WWV, WWVH, and WWVB in Colorado and Hawaii. If that actually happens, are there any free or inexpensive alternative frequency standards available so that we can accurately calibrate our transceivers, frequency counters, etc. with at least 1 Hz accuracy? https://www.google.com/search?q=wwv+discontinued https://www.eham.net/articles/41765 http://www.arrl.org/news/concern-rising-within-amateur-radio-community-over-wwv-wwvh-shut-down-proposal https://forums.qrz.com/index.php?threads/wwv-discontinuing-operations.624002/ WWVB is a time station only; without its radio transmissions, millions of consumer "atomic" radio clocks would have nothing to keep them accurate. A: GPS-based frequency standards @larsks answer rightly pointed at devices that use GPS to generate the 1-second pulsing. That's the correct way to go. Curiously, these modules only address the once-per-second accuracy issue, not the frequency standard issue, which GPS is indeed commonly used to solve: You'll find a lot of modules on the market that will not only give you a Pulse Per Second (PPS), but also a frequency standard signal, most commonly 10 MHz, but there's other frequencies, too. Frequency standards in cellular infrastructure GPS-discplined oscillators (GPSDOs) are really common in cellular base station technology, where you must very accurately coordinate frequency (and time), to be able to use the (billions of euros) licenses for the limited spectrum you've got most efficiently – avoid the guard band between you cell's "own" band and the neighboring cell, as well as minimize frequency-error induced losses in transmission. GPS-disciplined oscillators Thus, in the professional world, WWVB and similar things are pretty much forgotten, since the signal simply is too narrowband to give you a good frequency and timing estimate within short time. You can find a lot of these modules on the surplus/used market – Trimble GPS comes to mind, for example – but you can also build such things yourself: The Opendigitalradio project (a project to establish broadcasting systems for digital audio broadcasting), or rather Matthias HB9EGM himself, has built a GPSDO: Aside from the uBlox LEA-M8F GPS receiver, reference clock + PPS generator module, there's barely anything on that board – a chip to regulate the supply voltage, and one to protect against ESD if one decides to solder on the USB debugging plug. Then, one buffer for 30.72 MHz (or configurable frequency, IIRC) and PPS each. Don't know if it'll need special communication via the serial port headers soldered on below to start (don't actually think so!), but these could be trivially supplied using just any $5 USB-to-TTL adapter out there. Why are those more expensive than the typical GPS module? Note that the LEA-M8F is much more expensive than your average GPS module, just because it's also supplying a reference frequency, not only location and PPS. I know that people also simply use digital PLLs (i.e. counters) and VCOs to generate reference clocks from the PPS signal – it's easy: I count the oscillations between two rising PPS edges (there's a lot of microcontrollers that can do that in hardware for you, without any need for running a counter in software). If it's higher than it should be, lower the control voltage to the VCO, and vice versa. Of course, the better your VCO gets, and the better you filter that control voltage, and the smartser you get at calculating the adjustment, the less overshoot and beat frequency you'll have. That means that if you don't need the speed at regulation and the full accuracy that a proper GPSDO can give you, a simple GPS receiver that gives you only a PPS can also be used as a frequency standard. About it's quality compared to WWVB, see the next section. Comparison of even cheapest GPS-based solution to what you can achieve using WWVB But: if you can leave your microcontroller + GPS running all day, have a good place to put your GPS antenna (i.e. any roof) and thus your oscillator can have all time in the world to reach a stable frequency, well, pretty sure that $10 in hardware will give you a better frequency standard than most WWVB receivers; leave alone the timing accuracy, which is (really) laughable in WWVB: GPS specifies some +- 50 ns accuracy, whereas you're free to calculate which SNR you'll need to achieve that in a receiver that has maybe 100 Hz of bandwidth. Hint: It's a lot of SNR; the diagrams you find online for WWVB act as if the edge of the PPS are "straight up", of course, that's physically/mathematically impossible within limited bandwidth, so these edges are very sloped actually, and to get a reliable timing estimate, you'd have to "count the second" when you cross a very exact voltage threshold – but noise will make these slopes "jiggly", and thus, you'll need to average enough of these crossing times to get a good estimate. GPS isn't that different there, but the bandwidth is much higher, so that each PPS is already the result of quite a lot of averaging. Commercially availability of GPSDOs As said above, such devices are necessary for cellular infrastructure – and there's a lot of demand for that, so there's company specializing in such devices, Trimble, or Jackson Labs for example. Observation/Correction based approach also known as: give me a lousy clock, but tell me its error. A completely different approach can be taken if you've got a device from which you can extract the mixing frequency (base): There's tools like kalibrate (I think that's even shipped with some Linux distros!) with which you can just scan the frequencies on which GSM works, and estimate the GSM "carrier frequency" (it's a tiny bit more complicated, but in essence it's just estimating a carrier), based on your device's inaccurate clock. Now, GSM is cellular, and is, you guess it, frequency-based off GPS. You use those estimates to measure the error of your receiver's frequency, and thus, you can now just incorporate that relative error (e.g. "the frequency is off by -0.0008%") to just adjust the frequency you configure e.g. your classical transceiver to, if you base it off the same reference frequency. I've not done it, but if you have a (modified) RTL-SDR dongle with a slightly more stable oscillator (which is ... not hard to achieve), you could add a high-z-input buffer to that oscillator, modify Kalibrate to work with the RTL-SDR, and use the estimated error. You'd have a "correctable" 28.8 MHz oscillation – which can be extremely helpful, especially when you consider that there's a lot of very flexible LO synthesizers, which you could feed with 28.8 MHz and use to generate a Phase-locked 10 MHz (or 20 MHz, or 2.4 GHz or, really, whatever rationally related frequency) directly from that. There's a whole bunch of so-called clock nuts (I call them like that, because the only two I personally know call themselves such) that specialize in having good frequency and time standards. If that's your thing: Go for their community ;) A: In No WWVB? No problem!, KB6NU points at two projects that show you how to build your own low-powered WWVB-replacement to keep your clocks in sync: μWWVB: A Tiny WWVB Station. This project uses an attiny44 microcontroller and a USGlobalSat EM-506 GPS module to simulate WWVB. One Component Radio Clock Time Transmitter: This project uses an attiny45 microcontroller to simulate WWVB. As is, you set the time by changing some defines in the code. You’ll probably want to change that to get the time variables from a GPS source or an ntp source, but at least you’ll be able to generate the 60 kHz once you have that time information. A: Don't forget about CHU (and here is the official site) which is the Canadian equivalent to WWV. It's at lower power and it's not as well-located geographically (it's located near Ottawa), but it's receivable in most of the eastern US and increasingly less well as you head west. Here in VE5-land (Saskatchewan) I certainly receive it sometimes, but I also don't have an ideal HF antenna setup either. It transmits at 3 kW at 3.33 and 14.67 MHz as well as with 10 kW of power at 7.85 MHz. One nice feature is that it frequently transmits time data in Bell 103 modem format, which is fairly easy to decode. It of course also has spoken word time.
{ "pile_set_name": "StackExchange" }
Q: Lightweight, general-purpose, stable, standalone/embedded SQL server for Windows? I realise this question is a little subjective, but I think there are only a very small number of DBMSs that match the requirement. I'm looking for some recommendations for a standalone SQL server. Something that can either be bundled on compile, or already have a driver built-in to Windows. I'd usually use MySQL or MS SQL, depending on environment, but I'd like to "graduate" to SQL for things I'd usually do in XML files for Windows. The db should be accessible without an internet connection, and preferably be stable and mature. I don't mind what flavour SQL it is. It'd only really be for a single concurrent user at a time, i.e. to store program user data. I'm looking for something "general-purpose", that I can rapidly integrate with new projects/small tools I make. From my research, the two I'm coming up with, that still look like they're in development are: the well known SQLite, and also Firebird. What are the pro's and con's of each? Have I missed any killer standalone SQL servers? I've used Sybase SQL Anywhere in the past, but it has its quirks. A: Have you looked at SQL Server Compact Edition? Sounds like it might meet your criteria.
{ "pile_set_name": "StackExchange" }
Q: Youtube Data API: Daily Limit for Unauthenticated Use Exceeded (with API key) Error Message: { "error" : { "message" : "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.", "errors" : [ { "message" : "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.", "reason" : "dailyLimitExceededUnreg", "domain" : "usageLimits", "extendedHelp" : "https:\/\/code.google.com\/apis\/console" } ], "code" : 403 } } I have registered, generated an API key for iOS, set the bundle identifier, enabled the API in the APIs Library and I still got this error after the very first request I made. No idea what i'm doing wrong, please help. Thanks. A: I was escaping characters incorrectly in my request string. Not a very helpful error message.
{ "pile_set_name": "StackExchange" }
Q: How to add metadata to streaming grpc calls in c++ I am trying to do something similar as below (i.e. sending data from client to server using streaming grpc call). Code reference is taken from grpc example given on the official site for explanation purposes: Client Side Code: ClientContext context; context.AddMetadata("authorization", "abcd"); context.set_deadline(...); std::unique_ptr<ClientWriter<RequestObjectClass>> writer(stub_->grpcCall(&context, &response)); writer->WaitForInitialMetadata(); // Setting request parameters request.set...(...); request.set...(...); request.set...(...); request.set...(...); if (!writer->Write(request)) { Status status = writer->Finish(); if (status.error_code() == UNAUTHENTICATED) { std::cout << "UNAUTHORIZED" << std::endl; break; } // Broken stream. throw Exception("Broken Stream"); } writer->WritesDone(); Status status = writer->Finish(); if (status.ok()) { std::cout << "RPC succeeded." << std::endl; } else { std::cout << "RPC failed." << std::endl; } Server Side Code: std::multimap<grpc::string_ref, grpc::string_ref> metadata = context->client_metadata(); auto auth = metadata.find("authorization"); if (auth == metadata.end()) { return Status(StatusCode::UNAUTHENTICATED, "UNAUTHORIZED"); } I get "Broken stream" exception because the Status had code "DEADLINE_EXCEEDED" and details as "Deadline Exceeded". My deadline timeout for ClientContext is system_clock::now() + 5 seconds. What am I doing wrong? A: I just removed this line "writer->WaitForInitialMetadata();" and it started working. I think this line makes client wait for some metadata from server. Not sure though.
{ "pile_set_name": "StackExchange" }
Q: Stream doesn't preserve the order after grouping I have a List name availableSeats I am sorting and grouping by the blockIndex property like below: availableSeats.stream() .sorted(Comparator.comparing(SeatedTicketAssignment::getBlockIndex)) .collect(Collectors.groupingBy(SeatedTicketAssignment::getBlockIndex)) .forEach((block, blockAssignments) -> { //Rest of the code } The problem is that the result of grouping by is not sorted by the blockIndex. A: Keep in mind, Collectors#groupingBy(Function) will return a HashMap, which does not guarantee order. If you want the ordering to be in the order that the aggregate identity (your i % 2 == 0 result) shows up, then you can use LinkedHashMap: .collect(Collectors.groupingBy(i -> i % 2 == 0, LinkedHashMap::new, Collectors.toList())) Would return a LinkedHashMap<Boolean, List<SeatedTicketAssignment>> (since your collector is grouped by a boolean). Additionally, since the list utilized by the collector is an ArrayList, it should preserve the iteration order of the stream relative to the list.
{ "pile_set_name": "StackExchange" }
Q: HTTP Request packet getting corrupted When I received an HTTP request of smaller length it's fine, but when receiving long packet getting corrupted. I took a trace through wire shark and I printed packet in hex value in JAVA console. Some additional values are showing in that printing. Why? How can I solve it? Is there anything wrong with conversion of HTTP request to Hex. Following code is used to convert String to Hex. ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream responseData = request.getInputStream(); byte[] buffer = new byte[1000]; int bytesRead = 0; while ((bytesRead = responseData.read(buffer)) > 0) { baos.write(buffer, 0, bytesRead); sb=baos.toString(); str = baos.toString(); sb.append(str); sb = new String(baos.toByteArray(),UTF8); } baos.close(); // connection.close(); A: You can't convert the read bytes to a String until all your input is read because a fraction of the input might be invalid UTF-8 encoded data. Also don't use ByteArrayOutputStream.toString() because it uses the platform's default character set to decode bytes to characters (String) which is indeterministic. Instead use ByteArrayOutputStream.toString(String charsetName) and specify the encoding. Also you should use ServletRequest.getCharacterEncoding() to detect encoding and revert to UTF-8 for example if it is unknown. First read all input, and then convert it to a String: String encoding = ServletRequest.getCharacterEncoding(); if (encoding == null) encoding = "UTF-8"; // First read all input data while ((bytesRead = responseData.read(buffer)) > 0) { baos.write(buffer, 0, bytesRead); } // We have all input, now convert it to String: String text = baos.toString(encoding); Better Alternative Since you convert the binary input to a String, you should use ServletRequest.getReader() instead of reading binary data using ServletRequest.getInputStream() and converting it to String manually. E.g. reading all lines: BufferedReader reader = request.getReader(); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { // Process line, here I just append it to a StringBuilder sb.append(line); // If you want to preserve newline characters, keep the next line: sb.append('\n'); }
{ "pile_set_name": "StackExchange" }
Q: How to edit synaptics configuration? xorg.conf way doesen't work I need to bind the TapButton3 as central mouse button so i do: synclient TapButton3=2 it works great but when i restart or wake up from suspension it forgets the setting. i know that i have to create the xorg.conf as follows Section "InputClass" Identifier "touchpad catchall" Driver "synaptics" MatchIsTouchpad "on" Option "TapButton3" "2" EndSection but this doesen't work. anyone can help me? ...please? A: I created the /etc/X11/xorg.conf.d/71-synaptics.conf file with the following contents with sudo vi: Section "InputClass" Identifier "touchpad catchall" Driver "synaptics" MatchIsTouchpad "on" Option "TapButton3" "2" EndSection and I can see in /var/log/Xorg.0.log that the option has been set. [ 91056.468] (**) Option "TapButton3" "2" The option was merged with options I had set similarly in my 70-synaptics.conf file. If your device uses a different device or different driver (see the /var/log/Xorg.0.log to see), you should adjust the Identifier and Driver lines appropriately. Another approach is to disable the gnome mouse settings plugin. To do this start a terminal with Alt+Ctl+T, and then install the dconf-editor: apt-get install dconf-editor hleinone Launch dconf-editor dconf-editor and navigate the tree to org.gnome.settings-daemon.plugins.mouse. Finally, uncheck the Active box A drawback of this latter approach is that no settings you configure in System Settings-> Mouse and Touchpad will be effective. This approach, from the comments, is from here by way of hleinone.
{ "pile_set_name": "StackExchange" }
Q: Open IE and read page for IE 7 or newer c# I need to open a browser (Internet Explorer 7 or above) for a given URL and then read the contents once it has finished loading. leaving the browser open for the user to use as normal afterwards. Then I need to replace the page (if still open) with a new URL later if needed and read that page... As I'm needing to leave them in IE after I have read the page I assume I can't use the browser control, so how would I do this? This is a windows classic forms app using .Net4. many thanks. A: It can be done. Look http://www.codeproject.com/KB/shell/AutomateShellWindow.aspx Once you have access to IWebBrowser2 you can do everything you need, including navigate, read content etc.
{ "pile_set_name": "StackExchange" }
Q: Insert text field content based on what checkboxes are selected php mysql Hey Fellow Programmers, I have a slight problem and I cant find the right answer online. Basically what I need to do is, a user inserts content into a text box and then selects a check box. Whichever check box is selected is what table the text box content is supposed to insert into. **Both check boxes can be selected so the user can upload to two diff tables, before you ask no I cannot just upload to a diff row it has to be a completely diff table. Let me know if I am not clear, and thanks in advance HTML CODE: <body class="login"> <div class="wrapper"> <h1><a href="index.php"><img src="img/logo-big.png" alt="" class='retina-ready' width="59" height="49">FLAT</a></h1> <div class="login-body"> <form action="db_pre_panel.php" name="login" class='form-validate' id="test" method="post"> <div class="control-group"> <div class="email controls"> <h3>TEST</h3> <input type="text" name="content" maxlength="500" placeholder="Content" /> </div> </div> <div class="control-group"> <input type="checkbox" name="Ck_1" /> <label>Ck_1</label>//If selected then INSERT content into tbl_connect <input type="checkbox" name="Ck_2" /> <label>Ck_2</label>//If selected then INSERT content into tbl_share </div> <div class="submit"> <input type="submit" value="Simplicity" /> </div> PHP CODE: <?php //Define Content, Post & Share $content=$_POST['content']; $post=$_POST['ck_1']; $share=$_POST['ck_2']; //Insert into the db $sql_post="INSERT INTO $tbl_connect (wall) VALUES ('$connect', '$post')"; $sql_share="INSERT INTO $tbl_share (wall) VALUES ('$connect', '$share')"; //Make sure it insert into db $result_post = mysql_query($sql_post); $result_share = mysql_query($sql_share); if($result_post){ header("location:alert.php"); }else{ header("location:error.html"); } if($result_share){ header("location:http://www.google.com"); }else{ header("location:error.html"); } ?> A: Just keep it simple: //Define Content, Post & Share $content = $_POST['content']; // you should sanitize this to prevent SQL injection if ( !empty($_POST['ck_1']) ) { $sql_post = "INSERT INTO `tbl_connect` (wall) VALUES ('$connect')"; // if you have more than one value, then you need to specify more than one column... } if ( !empty($_POST['ck_2']) ) { $sql_share = "INSERT INTO `tbl_share` (wall) VALUES ('$connect')"; }
{ "pile_set_name": "StackExchange" }
Q: Log with GUI in Objective-C I have tried many objects in Xcode's object library, but I can't seem to find the correct objects. What I am trying to do is create a log for my app, for development purposes, but also for any future users who just feel like having a log. I don't want to use NSLog(NSString). I need an Obj-C equivalent of Java's javax.swing.JTextArea that has the following properties: 1. can be contained in a scroll pane (and how do I do this) 2. can be set to un-editable (Java equivalent of myTextArea.setEditable(false)) 3. (in code) can receive \n as "new line" (shouldn't be a problem) Does this exist, and if not, how can I create something similar (for example covering a text area with a layer)? Thanks A: Cocoa's NSTextView class fits this perfectly. It can be found in the object library as "text view". It can be set to non-editable in the properties inspector and can receive "\n" as a new line. It already has scroll bars.
{ "pile_set_name": "StackExchange" }
Q: Class Mage not found in Shell Script on some servers We have a custom script in shell with require_once 'abstract.php'; and our class extends Mage_Shell_Abstract. On our dev environments this is working fine, but on staging we get the error PHP Fatal error: Class 'Mage' not found in /var/www/foo/public/shell/abstract.php on line 86 What can be the reason? A: There seems to be a PHP bug caused by mixing relative and absolute paths. See stackexchange https://stackoverflow.com/q/26885077/288568
{ "pile_set_name": "StackExchange" }
Q: SecKeychainFindInternetPassword Prompt I'm using SecKeychainFindInternetPassword to retrieve the proxy username and password from the Keychain Access. The app it's an updater, it looks for a new version. If the user is using a proxy I need the username and password (if there is one). The code is working but it shows a prompt asking to allow reading the key (it's an updater I do not want a prompt). The app already has administrator permissions to run. The question is... Is there a parameter for SecKeychainFindInternetPassword to avoid the prompt or there is another function that returns the Keychain without the prompt? Thanks, Fiury A: This likely means that you haven't signed the app with the same key as the previous app. Generally if the app has the same signing key, it will inherit the predecessor's permissions, but will not otherwise.
{ "pile_set_name": "StackExchange" }
Q: How to use reflection to get extension method on generic type From various sources on teh interwebs I've gleaned this following function: public static Nullable<T> TryParseNullable<T>(this Nullable<T> t, string input) where T : struct { if (string.IsNullOrEmpty(input)) return default(T); Nullable<T> result = new Nullable<T>(); try { IConvertible convertibleString = (IConvertible)input; result = new Nullable<T>((T)convertibleString.ToType(typeof(T), CultureInfo.CurrentCulture)); } catch (InvalidCastException) { } catch (FormatException) { } return result; } I've made it into an extension method, and it works just fine if I call it directly: int? input = new int?().TryParseNullable("12345"); My problem occurs when I try to call it using reflection from within the context of another generic function. SO is full of answers describing how to get the MethodInfo of generic methods and static methods, but I can't seem to put these together in the right way. I've correctly determined that the passed generic type is itself a generic type (Nullable<>), now I want to use reflection to call the TryParseNullable extension method on the Nullable<>: public static T GetValue<T>(string name, T defaultValue) { string result = getSomeStringValue(name); if (string.IsNullOrEmpty(result)) return defaultValue; try { if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>)) { MethodInfo methodInfo; //using the TryParse() of the underlying type works but isn't exactly the way i want to do it //------------------------------------------------------------------------------------------- NullableConverter nc = new NullableConverter(typeof(T)); Type t = nc.UnderlyingType; methodInfo = t.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder, new[] { typeof(string), t.MakeByRefType() }, null); if (methodInfo != null) { var inputParameters = new object[] { result, null }; methodInfo.Invoke(null, inputParameters); return (T) inputParameters[1]; } //start of the problem area //------------------------- Type ttype = typeof(T); //this works but is undesirable (due to reference to class containing the static method): methodInfo = typeof(ParentExtensionsClass).GetMethod("TryParseNullable", BindingFlags.Public | BindingFlags.Static); if (methodInfo != null) Console.WriteLine(methodInfo); //standard way of getting static method, doesn't work (GetMethod() returns null): methodInfo = ttype.GetMethod("TryParseNullable", BindingFlags.Public | BindingFlags.Static); if (methodInfo != null) Console.WriteLine(methodInfo); //Jon Skeet's advised method, doesn't work in this case (again GetMethod() returns null): //(see footnote for link to this answer) methodInfo = ttype.GetMethod("TryParseNullable"); methodInfo = methodInfo.MakeGenericMethod(ttype); if (methodInfo != null) Console.WriteLine(methodInfo); //another random attempt (also doesn't work): methodInfo = ttype.GetMethod("TryParseNullable", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder, new[] { typeof(string) }, null); if (methodInfo != null) Console.WriteLine(methodInfo); } // if we get this far, then we are not handling the type yet throw new ArgumentException("The type " + defaultValue.GetType() + " is not yet supported by GetValue<T>.", "T"); } catch (Exception e) { [snip] } } Can someone put me out of my misery? The typeof(T) returns the correct type info, I figure that maybe I'm using it a little incorrectly with the GetMethod() call, or I haven't specified the right parameters with the call to GetMethod(). 1. Link to referenced Jon Skeet answer A: The problem is that extension methods don't modify the type they are 'extending'. What actually happens behind the scenes is that the compiler transparently translates all the calls that seem to be made on the object in question to calls to your static method. ie. int? input = new int?().TryParseNullable("12345"); // becomes... int? input = YourClass.TryParseNullable(new int?(), "12345"); From there it becomes obvious why it's not showing up via reflection. This also explains why you have to have a using directive for the namespace where YourClass is defined for the extension methods to be visible to the compiler. As to how you can actually get at that information, I'm not sure there is a way, short of running over all the declared types (perhaps a filtered list of interesting classes, if you know that sort of information at compile time) looking for static methods with the ExtensionMethodAttribute ([ExtensionMethod]) defined on them, then trying to parse the MethodInfo for the parameter list to work out if they work on Nullable<>.
{ "pile_set_name": "StackExchange" }
Q: Give an example of a group G and elements a , b ∈ G such that a^{-1}(ba) ≠ b. Give an example of a group G and elements $a,b ∈ G$ such that $a^{-1}ba \not=b$. Any ideas as to how I would go about finding it? Thanks A: $a^{-1}ba \not = b$ is the same as $ab \not = ba$, which is just saying that the group is not abelian. So you can just look at any non-abelian group and try some non-identity elements.
{ "pile_set_name": "StackExchange" }
Q: Queuing models in R, $\lambda$ Little It's noted that the number of folks in a stationary system will maintain an average equal to the rate of arrival multiplied by the mean of the service distribution. The formula $L = \lambda w$ is valid for any queueing model in steady-state, where $L$ and $w$ are long-term steady-state average values respectively, and $\lambda$ denotes the arrival rate to the system. We can add up the total service time in the system as follows: $$\sum w_{j} = \sum i T_i$$ where $T_i$ represents the time units in which $i$ entities were in the system. But things are always more interesting with sample sizing and simulating results, so say in $5000$ iterations we estimate a state of a system in 1-min intervals, between the first minute and the last arrival at a determined time. So suppose we use a random interarrival rate of $\lambda = 2$ per minute and the service distribution is $N(8,1)$ minutes for the system. How can I simulate this model in R, using rexp() and rnorm()? I also want to display in ts() to show in time plot. A: Not directly answering your question of how to code it manually but for discrete simulation of queues in R I would strongly recommend the simmer package. The minimal code for your example would look like this (adapted from the tutorial). library(simmer) library(simmer.plot) lambda <- 2 queue <- trajectory() %>% seize("server", amount=1) %>% timeout(function() {rnorm(1, 8, 1)}) %>% release("server", amount=1) env <- simmer() %>% add_resource("server", capacity=1) %>% add_generator("arrival", queue, function() {rnorm(1, lambda)}) %>% run(until=100000) resources <- get_mon_resources(env) arrivals <- get_mon_arrivals(env) plot(resources, metric = "usage", items = "server") plot(arrivals, metric = "flow_time") However, looking at the plot of flow times I am unsure if you conceived a stable queuing system - for mean = 1 in the service time it looks better: Service Time Mean 8: Service Time Mean 1:
{ "pile_set_name": "StackExchange" }
Q: Simplifying expression using eulers equation I have the following expression which I've been told to simplify using Eulers equation: $$\cos(22t)+\cos(10t)$$ I think I have to substitute these expressions in (from rewriting Eulers equation) $$\cos(22t)+\cos(10t)=\frac{e^{i22t}+e^{-i22t}}2+\frac{e^{i10t}+e^{-i10t}}2$$ But I just have no idea where to go from here. Can anyone give me a hint? A: As pointed out in the comments, this expression is equal to: $$\dfrac { \left( e ^ { 16 i t } + e ^ { - 16 i t } \right) \left( e ^ { 6 i t } + e ^ { - 6 i t } \right) } { 2 }$$ Using Euler's formula again, we get: $$\cos(22t) + \cos(10t) =\dfrac { 2\cos(16t) \cdot 2 \cos(6t) } { 2 } = 2\cos(16t) \cos(6t).$$
{ "pile_set_name": "StackExchange" }
Q: Regex to match a minimum of 1 special character I have the following regex that requires 1 number, 1 letter upper and 1 letter lower (w/ a minimum of 8 length) Regex.IsMatch(password, "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,}$") I need to add another filter to ensure one of the following special characters is present (any help?) #, $, @, !, %, &, * ? A: Simple!: Regex.IsMatch(Password,"[#$@!%&*?]");
{ "pile_set_name": "StackExchange" }
Q: IUPAC naming for compounds containing carboxylic acid and anhydride together? According to IUPAC, the carboxylic acid comes first in priority order for functional groups, while anhydride has no prefix. Then how do you name a compound which contains both a carboxylic acid and an anhydride in it? A: Acids are senior to anhydrides; therefore, a compound that contains both functional groups is named as acid. The acid is substituted using the usual principles of substitutive nomenclature. The prefix ‘oxo’, denoting $\ce{=O}$, is used to indicate a carbonyl group when the group cannot be cited as suffix. The group $\ce{R-CO-O-{}}$ is indicated by an acyloxy prefix (e.g. ‘acetyloxy’, ‘propanoyloxy’, etc.). For example: 3-(acetyloxy)-3-oxopropanoic acid (Cyclic anhydrides, however, are named as heterocyclic pseudo ketones.)
{ "pile_set_name": "StackExchange" }
Q: mvc 1.0 doesnt work on IIS6 I have a strange problem with my MVC 1.0 application that I published on IIS6. When I try to surf to the pages no routes match and I get page not found. I have installed 3.5sp1 on the webserver and everything needed. Seems like there is lots of files missing (?) or the filestructure isnt the same as in my project folder. What might be wrong here? /M A: Did you set up wildcard mappings? http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx
{ "pile_set_name": "StackExchange" }
Q: Insert cascade with @RepositoryRestResource, foreign key always null Maybe I am pushing my luck, but I am trying to implement a repository with @RepositoryRestResource, but the foreign key of the parent is not set in the child. I will try to explain what I did and what I found.. First let's show what I did : UML : My Potato entity : @Data @Entity @Table(name = "POTATO") public class PotatoEntity { @Id @Column(name = "ID") @GeneratedValue(strategy = GenerationType.IDENTITY) private BigInteger id; @Column(name = "FIRSTNAME") private String firstname; @Column(name = "LASTNAME") private String lastname; @OneToMany(mappedBy = "potato", cascade = CascadeType.PERSIST) private List<DetailPotatoEntity> detailPotatoList; } My DetailPotato entity : @Data @Entity @Table(name = "DETAIL_POTATO") public class DetailPotatoEntity { @Id @Column(name = "ID") private BigInteger id; @Column(name = "WEIGHT") private BigDecimal weight; @Column(name = "HEIGHT") private BigDecimal height; @JoinColumn(name = "POTATO_ID", nullable = false) @ManyToOne @JsonBackReference(value = "potato-detailPotato") private PotatoEntity potato; } My Potato repository : @RepositoryRestResource(collectionResourceRel = "potatos", path = "potatos") public interface PotatoRepository extends CrudRepository<PotatoEntity, BigInteger> { } The thing is that when I am pushing the following json : { "firstname":"patate", "lastname":"potato", "detailPotatoList": [ { "weight":12, "height":13 } ] } the POTATO_ID in DETAIL_POTATO is always null. Normally, when you have your own controller et service, you would set the PotatoEntity in every DetailPotatoEntity and everything would have been alright. So, I would have tought that @RepositoryRestResource would have done it for me.. But it's not the case. How I "solved" it ? Or did I ?: @PrePersist public void prePersist() { detailPotatoList.forEach(detailPotato-> detailPotato.setPotato(this)); } OR public void setDetailPotatoList(List<DetailPotato> detailPotatoList) { detailPotatoList.forEach(detailPotato-> detailPotato.setPotato(this)); this.detailPotatoList = detailPotatoList; } My question here is, is it normal that I have to do that ? Should @RepositoryRestResource suppose to manage that by its own ? Here is my observation : -Maybe @RepositoryRestResource should be use only for one entity only? -I did a try with a DetailPotatoRepository just to see (in case you would check by your own, beware that you need to remove the PotatoRepository annoteted by @RepositoryRestResource to work): @RepositoryRestResource(collectionResourceRel = "detailsPotato", path = "detailsPotato") public interface DetailPotatoRepository extends CrudRepository<DetailPotatoEntity, BigInteger> { } and when I pushed the following json : { "weight":12, "height":13, "potato": { "firstname":"pomme", "lastname":"apple" } } the POTATO_ID was set and everything was fine. Conclusion When the parent tells his children to persist, the children have no idea who is his parent. But, when the child tells his parent to persist, the child knows his parent. Here again the question : Should @RepositoryRestResource suppose to manage that by its own ? Or @RepositoryRestResource should be use only for one entity ? A: You are using a bidirectional association. In this case you should provide a synchronization of your entities. Try to implement this in your Potato#detailPotatoList setter. Like this, for example: public void setDetailPotatoList(List<DetailPotatoEntity> details) { if (detailPotatoList != null) { detailPotatoList.forEach(d -> d.setPotato(null)); } if (details != null) { details.forEach(d -> d.setPotato(this)); } detailPotatoList = details; } See my example. Additional hint: hibernate-enhance-maven-plugin
{ "pile_set_name": "StackExchange" }
Q: JS use pre-arranged numbers/letters from a list instead of generating letters/numbers? For example: for (var x=iFirst; x<=iLast; x++) { var s = "GET " + sBase.Replace("##", 4 + Math.random().toString().substr(2, 6)) + " HTTP/1.1\r\n\r\n"; } Will replace a string of characters with a random 7 digit number beginning with 4. As long as iFirst is less than iLast it will repeat. I'd like to to the same thing, except instead of generating random numbers. Use number from a pre-compiled list such as: 1234567 1234367 1234377 1434377 Alternatively, I'd like to replace ## with a snippet of text, spaces and special characters, such as: holl"a back' Hoot & "sc99t M7ss :piggy "hot" Thanks! A: var num_list = [1234567 1234367 1234377 1434377]; for (var x=iFirst; x<=iLast; x++) { var s = "GET " + sBase.Replace("##", 4 + num_list[x-iFirst]) + " HTTP/1.1\r\n\r\n"; }
{ "pile_set_name": "StackExchange" }
Q: Need details for configuring the digium card I need to know the appropriate configurations for digium card. what are the things needs to be followed for configuring digium card with PRI. Please can anyone provide me url or document related to digium card configuration. Thanks in advance. A: The Outside Connectivity chapter of "Asterisk: The Definitive Guide" covers this topic. The link is to a web version of the book that you can read for free. If you have trouble, contact Digium Support. They provide free installation support for Digium hardware.
{ "pile_set_name": "StackExchange" }
Q: Do previous versions of .NET framework come with every new version of windows? What versions of .NET framework are in Window XP, 7 or 8?Some programs require a framework on Windows 8, but not on 7. It seems like there is no backward compatibility of .NET versions between Windows. Or they are hidden and I should activate it? A: No, all previous version aren't installed by default on a system, though at least one version is hidden to default users and can be installed by accessing: Turn Windows features on or off in the Control Panel (Windows 7). If you really want older versions, you will have to download and install them.
{ "pile_set_name": "StackExchange" }
Q: Setting UI contents only adds last line Basically what I'm doing here is importing the contents of a text file into user input fields (there are 7 of them. I run a loop to go through them for command [i]. The code works fine within the console, but it wont work for the GUI as it only inputs the last line for each field. Have you got any clue what the problem is? Here is the UI: http://imageshack.us/f/692/21778853.jpg As you can see, it prints into the console fine, but when I import data by clicking import on the GUI then it just puts the last command of the txt file My code is: final JTextField Command[];//Create one dimensional array Command = new JTextField[8];//Declare Command as a JTextField for (int i = 1; i < 8; i++)//Run the loop through each selection { Command[i] = new JTextField(i);//Read through each text field } //Add user input fields including their absolute position on the panel Command[1].setText("Please enter the commands...");//Starting text Command[1].setBounds(121, 13, 236, 25);//Set the position of the text field getContentPane().add(Command[1]);//Add this text field to the content Command[2].setBounds(121, 47, 236, 25);/fsdfsdf getContentPane().add(Command[2]); Command[3].setBounds(121, 83, 236, 25);/fasdfasd getContentPane().add(Command[3]); Command[4].setBounds(121, 119, 236, 25);/fsfasdasdf getContentPane().add(Command[4]); Command[5].setBounds(121, 155, 236, 25); getContentPane().add(Command[5]); Command[6].setBounds(121, 191, 236, 25); getContentPane().add(Command[6]); Command[7].setBounds(121, 227, 236, 25); getContentPane().add(Command[7]); //IMPORT FILE JMenuItem Import = new JMenuItem("Import"); File.add(Import); Import.addActionListener(new ActionListener() {//Call up ActionListener function public void actionPerformed(ActionEvent arg0) {//Event handler try { //use buffering, reading one line at a time //FileReader always assumes default encoding is OK! BufferedReader input = new BufferedReader(new FileReader("W:\\EclipsePortable\\Data\\workspace2\\" + "RobotController\\src\\RobotController\\Import commands.txt")); try { String line = null; //not declared within while loop while (( line = input.readLine()) != null) { System.out.println(line);//Print the lines for(int i = 1; i < 8; i++) { Command[i].setText(line); } }} finally { input.close(); } } catch (IOException ex){ ex.printStackTrace(); } }});` A: So, in your file import code you are doing this... for(int i = 1; i < 8; i++) { Command[i].setText(line); Which is applying the current line of text to ALL the fields (the same line of text for all the fields), which means by the time you finish reading the file, you've only got the last line of the file. Instead, I would keep a reference to the field index and increment in each line read Added Example String line = null; //not declared within while loop int fieldIndex = 0; while (( line = input.readLine()) != null) { System.out.println(line);//Print Command[fieldIndex].setText(line); fieldIndex++ if (fieldIndex > 7) { break; }
{ "pile_set_name": "StackExchange" }
Q: MongoDB Morphia. Update only new fields but not old fields I get the response from Json like this { "id":"1090", "title" : "My User", "description" : "First User", "country" : "US", "state" : "FL", "city" : "Miam" "auth" : "Scott" } I need to write an update which updates only the fields which are changed. If the updated JSON looks like { "id":"1090", "title" : "New User", "description" : "First User", "country" : "US", "state" : "Texas", "city" : "Dallas" "auth" : "Scott"} I can achieve using below Blog blogDB=datastore.find(Blog.class, "blog_ID", blog.getBlog_ID()).get(); Query<Blog> query = datastore.createQuery(Blog.class).field("_id").equal(blogDB.getId()); //Find the object that is in database UpdateOperations<Blog> ops = datastore.createUpdateOperations(Blog.class).set("title", blog.getcountry()).set("country", blog.getcity()).set("city", .... datastore.update(query, ops); I don't want to write an UpdateOperations as shown above. Is there any more efficient way? A: There is no dirty state tracking in Morphia, no. You'll need to track those changes manually.
{ "pile_set_name": "StackExchange" }
Q: Select2 render multiple time when navigating to previous page I have a select2 drop down $('.range-selection').select2({width: 'resolve', placeholder: "Select range", prompt: "select" }); Its working fine but when navigating to a different page and then navigating to same page again the select2 field gets render multiple times. How to avoid select2 render multiple time. A: You have to destroy the select2 field when turbolinks:before-cache, This will prevent the multiple select2 in the page $(document).on("turbolinks:before-cache", function() { $('.range-selection').select2('destroy'); });
{ "pile_set_name": "StackExchange" }
Q: DynamoDB UpdateItem calculation with numbers? I would like my UpdateItem function to add the new value to the previous one but I can't figure out how to use numbers for the calculation and access the current value to be added to the new one. Here is my working function, what I want to do is included in comment. How can I do it? { "TableName": "Votes", "Key": { "votesId": { "S": "$input.path('$.votesId')" } }, "UpdateExpression": "set buy = :val1", "ExpressionAttributeValues" : { ":val1": { "N": "$input.path('$.buy')" //Would like: "N": "buy + $input.path('$.buy')" } }, "ReturnValues": "ALL_NEW" } Here is how I test it: { "votesId":1, "down":0, "up":0, "hold":0, "buy":0, "sell":0 } A: You can use UpdateExpression to indicate which attributes are to be updated and what actions to perform. Specifically in your case, UpdateExpression supports the following: SET myNum = myNum + :val
{ "pile_set_name": "StackExchange" }
Q: If ln is given paricular times can we find least value for which it is defined? I was just doing some time-pass with my calculator but then I observe something.I don't know whether it is senseful to ask.So here's my question. ln ln (1) is not defined but for all values greater than 1 it is defined.So then I try to find values for which ln ln ln(x) is defined,then I get to know that it get's defined from 2.72.If ln is taken 4 times it's start giving values from 15.2.So my question is if ln is given particular times how I can come to know the infimum of values for which it is defined? A: $\ln (x)$ is defined for $x>0$ $\ln (\color{blue}{\ln (x)})$ will be defined for $\color{blue}{\ln (x)}>0 \implies x >1$ $\ln (\color{blue}{\ln ( \ln (x))})$ is defined for $\color{blue}{\ln ( \ln (x))}>0 \implies \color{blue}{ \ln (x)}>1 \implies x>e$ You see the pattern now? $$0, e^0, e^1, e^e, e^{e^e} \ldots$$
{ "pile_set_name": "StackExchange" }
Q: The C++ Prog Lang book page 139 e.g I am studying "The C++ Programming language" by Bjarne Stroustrup. On page 139 it gives the following example of code that will not compile. bool b2 {7}; // error : narrowing When I tried this example it does compile. Can anyone explain why? A: Most compilers (unfortunately IMHO) do not fully conform to the C++ standard in their default modes. For g++ and clang++, you can use the options -std=c++11 -pedantic-errors to enforce the language requirements. However, the released versions of g++ do not catch this particular error, which is a flaw in g++. Using g++ 8.2.0, the declaration incorrectly compiles with no diagnostics: $ cat c.cpp bool b2 {7}; $ g++ -std=c++11 -pedantic -c c.cpp $ Using clang++ 6.0.0, the error is correctly diagnosed: $ clang++ -std=c++11 -pedantic -c c.cpp c.cpp:1:10: error: constant expression evaluates to 7 which cannot be narrowed to type 'bool' [-Wc++11-narrowing] bool b2 {7}; ^ c.cpp:1:10: note: insert an explicit cast to silence this issue bool b2 {7}; ^ static_cast<bool>( ) 1 error generated. $ Using a newer (unreleased, built from source) version of gcc: $ g++ -std=c++11 -pedantic -c c.cpp c.cpp:1:11: error: narrowing conversion of ‘7’ from ‘int’ to ‘bool’ [-Wnarrowing] 1 | bool b2 {7}; | ^ $ clang++ already correctly diagnoses this error. Expect g++ to do so in version 9.0.0 when it's released. If you want the conversion to be done without a diagnosis, you can use one of the other initialization syntaxes, such as: bool b1 = 7; // sets b1 to true, no diagnostic
{ "pile_set_name": "StackExchange" }
Q: How do I implement a model for an Oracle package in CakePHP? I have an Oracle package that I need to access in CakePHP. I am trying to determine the best way to implement the code for calling this function. I need to pass for variables from the UI to the procedure being called. I want to be able to use the model for the field validation before submitting to the package. It is a very specific procedure call: begin SCHEMA.package.function_name(vars); end; At the same time, there isn't the standard $this->save() or $this->find() to a package. Does anyone have CakePHP experience with this? Or any suggestions for implementation? Should I just put it in a model by itself? A: Well, after no response I did some digging this week, and I think I have a great solution to this. I was actually thinking it was more complicated than what it really is. Set up a model to point to the package you create. Within the package there may be multiple functions. So the model will contain all of the functions for the package that are required for your application. Here is what my model looks like: <?php class {PACKAGENAME} extends AppModel { var $name = {PACKAGENAME}; var $useTable = false; function {PACKAGE_METHOD}() { return $this->query('begin SCHEMA.PACKAGE.FUNCTION(); end;'); } } Replace the {PACKAGENAME} with the name of the Oracle package. The rest should be self explanatory. You can also configure the function to handle variables, of course.
{ "pile_set_name": "StackExchange" }
Q: In today's money, what was the value of a 1492 Spanish maravedí? Satava (2007) estimates that the costs of Columbus's 1492 voyage was 1,765,734 maravedís. In today's money, what was the value of a 1492 Spanish maravedí? A: Walsh (1931): The author of this work has translated maravedis into dollars of 1929 by reference to statistics on purchasing power in wheat, corn and other staples. Hence his opinion that the maravedi was worth about two American cents of 1929. According to the BLS inflation calculator, \$1 in 1929 is about \$15 today (2020). So, if we accept Walsh's estimate, then one maravedi in 1492 converts to about \$0.30 today. (And if we also accept Satava's estimate, then Columbus's voyage cost 1,765,734 $\times$ \$0.30 $\approx$ \$529,720 in today's USD.) A: dtcm840's answer is about as good as you're going to do for a single actual number: it is clear, well-sourced, and almost certainly misleading. That's not their fault: all comparisons over time periods this far off are rendered meaningless by the very different markets & relative prices of commodities & labor between now and then. This question does not have an answer in the way you'd like. I am suspicious of the Walsh source cited in dtcm840's answer: it used purchasing power based on staple foodstuffs for a basis for comparison; however food simply cost a far greater amount relative to other goods in the early modern period. An estimate based on the price of grain commodities between 1490 and 1920 will wind up dramatically undervaluing non-food goods. This may account for why a recent reproduction of the Santa Maria alone, if we use Wilson's conversion, cost about 7 times as much as Satava's estimate for Columbus' entire voyage. Obviously, modern materials, and safety consideration, and they were building a museum, etc. But a factor of 7 times, for only the construction of just one of the ships? Clearly something isn't quite comparable here. The potential for confusion with a simple conversion rate becomes particularly obvious if you look at things like wages, or the purchasing power available to actual people. A woman employed nursing foundling children in the period would've been paid about 100-200 maravedis per month, which on the Wilson estimate works out to an annual salary of \$750. Obviously this is an extremely low-status and correspondingly low-paid job, but it still highlights the difference between period and modern labor markets. And that's why you can't really answer the question: it will only lead to confusion to say "A maravedi is worth about thirty cents" without also noting that a person's yearly labor was worth maybe a couple grand. Even saying that, conversion into modern currency doesn't help us understand that economy, because so much of Europe (and the world) was living under the current UN international poverty line, as an inevitable consequence of the different productivity levels of their economy and ours. That's without getting into the implication that an iPad would have been about 2750 maravedis. If you want to understand how much Columbus' voyage cost, you're better off comparing the price of the voyage to either the other activities undertaken by the Spanish state at the time, or to the total crown revenues, or something of this nature. Even then, recordkeeping is pretty spotty, and requires a lot of estimation--and estimates vary wildly. The answer here would probably be another question (and might be more appropriate for the history stack). If you are interested in the finances of the Spanish crown, this seems to be worth a read--although it'd have to be a closer reading than the one I've given it. One chart suggests that the Spanish military expenditures in 1565 were on the order of 1.8 million ducats, which by the 375 mrs to ducat conversion factor would be 675 million mrs, at which point Columbus' voyage is a rounding error. (Of course, at the 30-cent conversion rate, that would suggest Phillip II had a \$200-million annual military budget, roughly the amount Hitler sent Franco--a comment notes this is well into the inflationary period caused by importing New World specie; but even if prices tripled over those 70 years, it's still a rounding error in one year's military expenditures). For another way to try to understand the magnitude of the outlay for this voyage, Vasco da Gama, the Portuguese admiral who opened the circum-African sea route to India, was awarded a royal pension of 300,000 reis upon his return in 1499. On this source, in the 1480s one Portuguese real was worth about 96/100ths of a maravedi, meaning da Gama's pension was roughly 285,000 mrs. (Contemporary conversions between currencies aren't perfect, but much less fraught than trying to create exchange rates 500 years apart.) So Portugal, one-fifth the size of Spain, was ready to pay the guy every 6 years what Satava estimates it cost to finance Columbus' entire voyage, just as a reward for prior services rendered.
{ "pile_set_name": "StackExchange" }
Q: How to run TypeScript program on Windows? If we write a Typescript program then how should we run it on Windows? We already know how to run Javascript (.js) from a command line on Windows: C:\Users\Harikesh>cscript MyScriptFile.js What is the equivalent for TypeScript (.ts) files? A: You can compile the Typescript down to Javascript, and then run it from a command line with Node.js, or in a web browser: 1) Download and install Node.js. 2) Open a Windows command prompt and run: npm install -g typescript 3) Navigate to the directory where your typescript file is in, and type: tsc yourtypescriptfile.ts 4a) Run the resulting JavaScript file with Node.js: node yourtypescriptfile.js -or- 4b) Make an HTML file (in the same directory) that includes yourtypescriptfile.js using <source></source> tags: <script src="yourtypescriptfile.js"></script> 5) Open your HTML file in a web browser. Help from: http://javascript.info/tutorial/adding-script-html
{ "pile_set_name": "StackExchange" }
Q: Count records for every month, including those with zero results How do I count the number of results from MySql database for every month in the past year wherein there might not exist a record for a specific month but it would show zero as the count? For instance, I would like to count the number of registrations that occurred every month, and include those results too where no registrations occurred. Month Count 1 4 2 2 . . . . 6 0 . . . . A: While although a lot of answers exist, I found most of them difficult to read and understand. However, using derived tables, I think it's easier to do so with the given query below, where we are trying to count the number of registrations for the past 12 months from user table: select derived.mm as month, count(u.reg_date) as count from ( SELECT 1 mm UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 ) derived left join user u on derived.mm = month(reg_date) and u.reg_date > LAST_DAY(DATE_SUB(curdate(),INTERVAL 1 YEAR)) group by derived.mm HOW THIS WORKS It derives a table (alias derived) which returns 12 rows, 1 for each of the 12 months, i.e. 1 to 12 [in the subquery; line 2]. It joins the month number of the registration date to the corresponding month number from the given derived table. [for months where no registrations occured, the joined reg_date result is null] And clause is as usual, counting the previous 12 months [current month will be indexed at 12] It groups the results by the original month index. Hope this comes to help someone out.
{ "pile_set_name": "StackExchange" }
Q: In Python, how does one catch warnings as if they were exceptions? A third-party library (written in C) that I use in my python code is issuing warnings. I want to be able to use the try except syntax to properly handle these warnings. Is there a way to do this? A: To handle warnings as errors simply use this: import warnings warnings.filterwarnings("error") After this you will be able to catch warnings same as errors, e.g. this will work: try: some_heavy_calculations() except RuntimeWarning: import ipdb; ipdb.set_trace() P.S. Added this answer because the best answer in comments contains misspelling: filterwarnigns instead of filterwarnings. A: To quote from the python handbook (27.6.4. Testing Warnings): import warnings def fxn(): warnings.warn("deprecated", DeprecationWarning) with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") # Trigger a warning. fxn() # Verify some things assert len(w) == 1 assert issubclass(w[-1].category, DeprecationWarning) assert "deprecated" in str(w[-1].message) A: Here's a variation that makes it clearer how to work with only your custom warnings. import warnings with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") # Call some code that triggers a custom warning. functionThatRaisesWarning() # ignore any non-custom warnings that may be in the list w = filter(lambda i: issubclass(i.category, UserWarning), w) if len(w): # do something with the first warning email_admins(w[0].message)
{ "pile_set_name": "StackExchange" }
Q: Dynamic rows using CSS Grid I'm using Grid to present some data. I would like to have a layout where the first row is headers, the second row is sub-headers and the third is the main content. This is quite simple to achieve using the grid-template-areas property for the grid-container. My problem is that i'd like the first row to be generated only once whereas the second and third rows should be dynamic. I am stuck trying to get the first two rows right so I will only refer to those two in my example. I have my CSS grid container defined as follows: .grid-container { display:grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: auto; grid-template-areas: "header1 header2 header3" "subheader1 . subheader2"; } .header-item-1 { grid-area: header1; } .header-item-2 { grid-area: header2; } .header-item-3 { grid-area: header3; } .sub-header-item-1 { grid-area: subheader1; } .sub-header-item-2 { grid-area: subheader2; } My html is as follows: <ul class="grid-container"> <li class="header-item-1">header1</li> <li class="header-item-2">header2</li> <li class="header-item-3">header3</li> <!-- ko foreach: { data: subheaderItem, as: 'subheader' } --> <li class="sub-header-item-1" data-bind="text: subheader.name"></li> <li class="sub-header-item-2" data-bind="text: subheader.type></li> <!-- /ko --> </ul> What this produces is a layout where the first row is correct, the second row has the correct layout but all iterations of the sub-headers are placed in the same cells like: * * * *** *** What i'm after is: * * * * * * * * * .... Would appreciate any tips on how to get this done ;) A: You can remove grid-template-areas (same grid areas will overlap - see another example here) and use a 3-column layout using grid-template-columns: repeat(3, 1fr) and then setting grid-column: 1 for sub-header-item-1 and grid-column: 3 for sub-header-item-2. See demo below: .grid-container { display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: auto; } .sub-header-item-1 { grid-column: 1; } .sub-header-item-2 { grid-column: 3; } <ul class="grid-container"> <li class="header-item-1">header1</li> <li class="header-item-2">header2</li> <li class="header-item-3">header3</li> <li class="sub-header-item-1">1</li> <li class="sub-header-item-2">3</li> <li class="sub-header-item-1">1</li> <li class="sub-header-item-2">3</li> <li class="sub-header-item-1">1</li> <li class="sub-header-item-2">3</li> </ul>
{ "pile_set_name": "StackExchange" }
Q: In Rails 3, what is the most efficient to way to track the number of visits to a given RESTful resource? I searched for this and was surprised not to find an answer, so I might be overcomplicating this. But, basically I have a couple of RESTful models in my Rails 3 application that I would like to keep track of, in a pretty simple way, just for popularity tracking over time. In my case, I'm only interested in tracking hits on the GET/show method–Users log in and view these two resources, their number of visits go up with each viewing/page load. So, I have placed a "visits" column on the Books model: == AddVisitsToBooks: migrating =============================================== -- add_column(:books, :visits, :integer) -> 0.0008s == AddVisitsToBooks: migrated (0.0009s) ====================================== The column initializes to zero, then, basically, inside the books_controller, def show unless @book.owner == current_user #hypothetically, we won't let an owner "cheat" their way to being popular @book.visits = @book.visits + 1 @book.save end And this works fine, except now every time a show method is being called, you've got not only a read action for the object record, but a write, as well. And perhaps that gets to the heart of my question; is the total overhead required just to insert the single integer change a big deal in a small-to-midsize production app? Or is it a small deal, or basically nothing at all? Is there a much smarter way to do it? Everything else I came up with still involved writing to a record every time the given page is viewed. Would indexing the field help, even if I'm rarely searching by it? The database is PostgreSQL 9, by the way (running on Heroku). Thanks! A: What you described above has one significant cons: once the process updates database (increase visit counter) the row is blocked and if there is any other process it has to wait.. I would suggest using DB Sequence for this reason: http://www.postgresql.org/docs/8.1/static/sql-createsequence.html However you need to maintain the sequence custom in your code: Ruby on Rails+PostgreSQL: usage of custom sequences A: After some more searching, I decided to take the visits counter off of the models themselves, because as MiGro said, it would be blocking the row every time the page is shown, even if just for a moment. I think the DB sequence approach is probably the fastest, and I am going to research it more, but for the moment it is a bit beyond me, and seems a bit cumbersome to implement in ActiveRecord. Thus, https://github.com/charlotte-ruby/impressionist seems like a decent alternative; keeping the view counts in an alternate table and utilizing a gem with a blacklist of over 1200 robots, etc, etc.
{ "pile_set_name": "StackExchange" }
Q: Flatten some directories but not others automatically? I have a directory with several thousand subdirectories inside (no subdirectories within those subdirectories however), and I need to flatten the contents of only some of the subdirectories, so basically bringing the contents of those directories to the root directory. But I can't do that with all the subdirectories, and the ones which I can't flatten have multiple files in them. Any way to do this automatically? Python script, perl script, bash, or whatever? I really, really, really don't want to have to do this by hand... A: Something like this, in bash (foo represents the directory you want to flatten): for x in foo/* do COUNT=`ls -1 "$x" | wc -l` if ([ -d "$x" ] && (test $COUNT -le 1)) then if test $COUNT -eq 1; then mv "$x"/* $1 fi rmdir "$x" fi done This will also remove an empty subdirectory from foo. You can also put this into a shell script file and use $1 as the directory name: # Exit it a directory name isn't given if [ "$1" = "" ] ; then echo "Usage: $0 directory" echo "Flattens directory" exit fi for x in "$1"/* do COUNT=`ls -1 "$x" | wc -l` if ([ -d "$x" ] && (test $COUNT -le 1)) then if test $COUNT -eq 1; then mv "$x"/* "$1" fi rmdir "$x" fi done You can put that into a file called flatten then run sh flatten foo to flatten the directory foo. Or, chmod +x flatten and run ./flatten foo. Ultimately, if you use it a lot over time, you can move it to a directory that's in our PATH so you can just type flatten foo. What I have is a bin file in my home directory on Linux where I put my own tools I want when I'm logged in, and I put my ~/bin in my PATH (set in the bash profile).
{ "pile_set_name": "StackExchange" }
Q: Rotational-vibrational spectroscopy of a molecule I want to ask if the rotational-vibrational spectra of a molecule is related to any one mode of frequency or if it is related to the whole molecule? Additionally, the vibrational levels that we say are composed of lower rotational energy levels. Are these vibrational energy levels of certain vibrational normal modes or of the whole molecule? A: I'm not quite sure what you mean by 'vibrational levels composed of lower rotational energy levels' so I try to explain the whole thing, briefly. In analysing the electronic, vibrational & rotational spectra of molecules the Born-Oppenheimer approximation has to be used. This is applicable because the vibrational period (a few femtoseconds) is far faster than rotation period (a few picoseconds) thus these motions do to interact appreciably with one another to a good approximation. This allows the energy levels of, rotation and vibrational motions to be added together. A normal mode vibration is the motion of all atoms in the molecule in a fixed phase relationship with one another. For N atoms there are $3N-6$ normal modes ($3N-5$ for a linear molecule). How how far and in what direction each atom moves has to be determined by calculation, but the overall symmetry species ($A_1, B_g, E_u$ etc) of the total motion of all atoms is given by the Point Group of the molecule, $C_{3v},D_{2h}, O_h$ etc. The symmetry species determines the relative phase of each atoms motion with respect to all the others. By 'phase' is meant that as some bonds contract others extend but they always do this together. As energy levels add each vibrational normal mode has its own stack of rotational levels. (Because the B.O. approximation is not exact a more detailed analysis in needed to add the interaction between vibration and rotation.) The figure shows a typical spectrum (calculated) of a (perpendicular band) of a symmetric top molecule such as $\ce{PCl3 , CHCl3} \mathrm { ~or~ } \ce{CH3Cl}$. The total spectrum is shown on the bottom line and its separation into individual PQR rotational bands above this. There will be similar complicated features for each vibrational normal mode. Clearly the analysis of spectra such as this is non-trivial :) (In symmetric top molecules two of its three moments of inertia are the same but different from the third. Two quantum numbers are needed J for total angular momentum and K to fix the angular momentum about the symmetry axis and this is why there are so many rotational bands for a single vibration.) (Spectrum is taken from G. Herzberg, ' Infra-red and Raman Spectra of Polyatomic Molecules')
{ "pile_set_name": "StackExchange" }
Q: Strip spaces/tabs/newlines - python I am trying to remove all spaces/tabs/newlines in python 2.7 on Linux. I wrote this, that should do the job: myString="I want to Remove all white \t spaces, new lines \n and tabs \t" myString = myString.strip(' \n\t') print myString output: I want to Remove all white spaces, new lines and tabs It seems like a simple thing to do, yet I am missing here something. Should I be importing something? A: Use str.split([sep[, maxsplit]]) with no sep or sep=None: From docs: If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Demo: >>> myString.split() ['I', 'want', 'to', 'Remove', 'all', 'white', 'spaces,', 'new', 'lines', 'and', 'tabs'] Use str.join on the returned list to get this output: >>> ' '.join(myString.split()) 'I want to Remove all white spaces, new lines and tabs' A: If you want to remove multiple whitespace items and replace them with single spaces, the easiest way is with a regexp like this: >>> import re >>> myString="I want to Remove all white \t spaces, new lines \n and tabs \t" >>> re.sub('\s+',' ',myString) 'I want to Remove all white spaces, new lines and tabs ' You can then remove the trailing space with .strip() if you want to. A: import re mystr = "I want to Remove all white \t spaces, new lines \n and tabs \t" print re.sub(r"\W", "", mystr) Output : IwanttoRemoveallwhitespacesnewlinesandtabs
{ "pile_set_name": "StackExchange" }
Q: Firefox. Allow access to IFrame elements via javascript I'm writing a tool for finding css selectors on outer web page. It's plain html page that contains iframe with target site and few control elements. All logic is also in javascript using jquery, so no server-side for now. The problem I faced is that a can't add handlers/classes to iframe document elements using Firefox 26.0 . Sample code: iframe.contents().find("*").hover(function() { console.log("This is " + $(this).get(0).tagName + "element"); } I get next error message in console: Error: Permission denied to access property 'document'. I understand that it's a security feature indeed, but I just need to workaround it somehow. What I've tried: Using Google Chrome - it allows to run browser with special flag (--disable-web-security) that turns off such security features. It helped and my tool is working just as I expected, but I need to use exactly Firefox. Using addon https://addons.mozilla.org/en-US/firefox/addon/forcecors/ . It didn't helped at all. I also tried to add x-frames-origin header by that tool, but no result. Turning off security.fileuri.strict_origin_policy flag in firefox configuration. Also didn't help. Maybe I missed something and there is some other workaround/better solution? I'll appreciate any help. Update: page and iframe are NOT on the same site. My tool is just local .html file, iframe source - any site(wikipedia, yahoo etc.) A: Finally I found the solution. I used an addon GreaseMonkey. It allowed me to insert my js code into iframe, so I am able to interact with code one my page using message API. Examples: Preventing from running code in parent window: if (window.top == window.self) return; Recieving something from main window: window.addEventListener('message', yourHandlerHere, false); Posting something to main window: window.parent.postMessage(yourDataHere);
{ "pile_set_name": "StackExchange" }
Q: Connecting buttons Ok so I am trying to make a code where by clicking one button you hide a button and make another appear. All the buttons appear and work but I have no clue how to make button 3 and 4 be hidden until button one is clicked. <input type="button" onclick="b()";>no</button> <script> function a() { alert ("button 1") } function b() { alert ("button 2") } </script> <input type="button" onclick="c()";>button 3</button> <input type="button" onclick="d()";>button 4</button> <script> function c() { alert ("button 3") } function d() { alert ("button 4") } A: function button1Clicked() { document.getElementById('3').classList.remove('hidden'); document.getElementById('4').classList.remove('hidden'); } .hidden { display: none; } <input type="button" id="1" value="Button 1" onclick="button1Clicked();" /> <input type="button" id="2" value="Button 2" /> <input type="button" id="3" class="hidden" value="Button 3" /> <input type="button" id="4" class="hidden" value="Button 4" /> Normally, you would keep your HTML, JS, and CSS in separate files. <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="my.css"> </head> <body> <script type="text/javascript" href="my.js"></script> <input type="button" id="1" value="Button 1" onclick="button1Clicked();" /> <input type="button" id="2" value="Button 2" /> <input type="button" id="3" class="hidden" value="Button 3" /> <input type="button" id="4" class="hidden" value="Button 4" /> </body> </html> If you want to keep everything in one file, you could just replace the link tag with a style tag and keep your JS in the script tag, like so: <style> .hidden { display: none; } </style> <script type="text/javascript"> function button1Clicked() { document.getElementById('3').classList.remove('hidden'); document.getElementById('4').classList.remove('hidden'); } </script>
{ "pile_set_name": "StackExchange" }
Q: Creating Zip without third party DLLs. Getting Part URI must start with a forward slash error I have a problem and due to that reason i am working on a pure c# solution to zip files. This is for a classic asp site and I will register my dll on ther server. I already have tested other third party libraries... I am getting the following error: Part URI must start with a forward slash. Here is the implementation that i have been able to build by googling around. My error is in method "AddFileToZip" on line: PackagePart newFilePackagePart = zipFilePackage.CreatePart(partURI, contentType, CompressionOption.Normal); [TestMethod] public void ArchiveFile() { string dir = "\\\\filebox01\\data\\test"; string file = "text.xls"; ZipClassic zip = new ZipClassic(); bool ok = zip.ArchiveFile(dir, file, "singleFileArchive.zip"); Assert.IsTrue(ok); } Main method: public bool ArchiveFile(string fileDir, string fileToArchive, string newArchiveFileName) { FileSystem fso = new FileSystem(); bool ok = !String.IsNullOrWhiteSpace(fileDir) && !String.IsNullOrWhiteSpace(fileToArchive) && fso.FileExists(Path.Combine(fileDir, fileToArchive)) && fileToArchive.Contains("."); if (ok) { if (!String.IsNullOrWhiteSpace(newArchiveFileName)) { if (!newArchiveFileName.ToLower().Contains(".zip")) newArchiveFileName = String.Concat(newArchiveFileName, ".zip"); } else { string filePart = fileToArchive.Substring(0, fileToArchive.LastIndexOf(".", System.StringComparison.Ordinal)); newArchiveFileName = String.Concat(filePart, ".zip"); } //if archve file already exists then delete it if (fso.FileExists(Path.Combine(fileDir, newArchiveFileName))) ok = fso.FileDelete(Path.Combine(fileDir, newArchiveFileName)); } if (ok) { Impersonate impersonate = new Impersonate(); impersonate.DoImpersonate(); Package zipFile = Package.Open(Path.Combine(fileDir, newArchiveFileName), FileMode.OpenOrCreate, FileAccess.ReadWrite); FileInfo file = new FileInfo(Path.Combine(fileDir, fileToArchive)); AddFileToZip(file, zipFile); zipFile.Close(); impersonate.Dispose(); ok = fso.FileExists(Path.Combine(fileDir, newArchiveFileName)); } return ok; } protected void AddFileToZip(FileInfo file, Package zipFilePackage) { string physicalfilePath = file.FullName; //Check for file existing. If file does not exists, //then add in the report to generate at the end of the process. if (File.Exists(physicalfilePath)) { string fileName = Path.GetFileName(physicalfilePath); // Remove the section of the path that has "root defined" physicalfilePath = physicalfilePath.Replace("./", ""); // remove space from the file name and replace it with "_" physicalfilePath = physicalfilePath.Replace(fileName, fileName.Replace(" ", "_")); try { //Define URI for this file that needs to be added within the Zip file. Uri partURI = new Uri(physicalfilePath, UriKind.Relative); string contentType = GetFileContentType(physicalfilePath); PackagePart newFilePackagePart = zipFilePackage.CreatePart(partURI, contentType, CompressionOption.Normal); byte[] fileContent = File.ReadAllBytes(physicalfilePath); newFilePackagePart.GetStream().Write(fileContent, 0, fileContent.Length); } catch (Exception ex) { throw new ApplicationException("Unable to archive: " + ex.Message); } } } protected string GetFileContentType(string path) { string contentType = System.Net.Mime.MediaTypeNames.Application.Zip; switch (Path.GetExtension(path).ToLower()) { case (".xml"): { contentType = System.Net.Mime.MediaTypeNames.Text.Xml; break; } case (".txt"): { contentType = System.Net.Mime.MediaTypeNames.Text.Plain; break; } case (".rtf"): { contentType = System.Net.Mime.MediaTypeNames.Application.Rtf; break; } case (".gif"): { contentType = System.Net.Mime.MediaTypeNames.Image.Gif; break; } case (".jpeg"): { contentType = System.Net.Mime.MediaTypeNames.Image.Jpeg; break; } case (".tiff"): { contentType = System.Net.Mime.MediaTypeNames.Image.Tiff; break; } case (".pdf"): { contentType = System.Net.Mime.MediaTypeNames.Application.Pdf; break; } case (".doc"): case (".docx"): case (".ppt"): case (".xls"): { contentType = System.Net.Mime.MediaTypeNames.Text.RichText; break; } } return contentType; } A: Problem was in creating partUri. I have used the full path where as it should have been the file name. Uri partUri = PackUriHelper.CreatePartUri(new Uri(String.Concat(@".\", fileName), UriKind.Relative)); This link helped to reolve the problem. http://weblogs.asp.net/jgalloway/archive/2007/10/25/creating-zip-archives-in-net-without-an-external-library-like-sharpziplib.aspx
{ "pile_set_name": "StackExchange" }
Q: How to create Android directory automatically if it doesn't already exist I am creating a gallery app using a tutorial but get the following error: abc directory path is not valid! Please set the image directory name AppConstant.java class Please visit the following link to see the entire tutorial's code as I am using the same code: http://www.androidhive.info/2013/09/android-fullscreen-image-slider-with-swipe-and-pinch-zoom-gestures/ I found this code in Utils Class: else { // image directory is empty Toast.makeText( _context, AppConstant.PHOTO_ALBUM + " is empty. Please load some images in it !", Toast.LENGTH_LONG).show(); } } else { AlertDialog.Builder alert = new AlertDialog.Builder(_context); alert.setTitle("Error!"); alert.setMessage(AppConstant.PHOTO_ALBUM + " directory path is not valid! Please set the image directory name AppConstant.java class"); alert.setPositiveButton("OK", null); alert.show(); } return filePaths; How can I create the missing directory programmatically instead of display this error dialog? A: Here's how you create directories if they don't exist. Considering that directory is indeed a directory. // If the parent dir doesn't exist, create it if (!directory.exists()) { if (parentDir.mkdirs()) { Log.d(TAG, "Successfully created the parent dir:" + parentDir.getName()); } else { Log.d(TAG, "Failed to create the parent dir:" + parentDir.getName()); } } mkdirs() will also create missing parent directories (i.e. all directories that lead to directory).
{ "pile_set_name": "StackExchange" }
Q: Weighted round robin dns between 2 Cloudfront distributions We are trying to use aws to do some a gradual deployment test with our javascript code, but it seems to fail us we created 2 S3 buckets with CF distributions : a.example.net -> aaa.cloudfront.net b.example.net -> bbb.cloudfront.net than we created a weighted round robin DNS entry in route53 test.example.net -> (cname) -> aaa.cloudfront.net (5) test.example.net -> (cname) -> bbb.cloudfront.net (95) in the S3 bucket we put a file with the CF corresponding domain name for each bucket : http://test.example.net/dns-test/test.txt What I am expecting is to get 95% of the time bbb and 5% of the time d3nrwpaeicu4xy. What we actually get is aaa 100% of the time :( I opened a ticket to the route53 team to check if this is a problem with the dns configuration but they have shown me , and I have seen it myself that the dns queries split between the 2 buckets. Hope this is clear enough. A: Unfortunately what you are trying to do is not possible. CloudFront, or any HTTP server for that matter, only see's the host header of test.example.com. It has no idea how you got there, be it WRR DNS or hosts file, it only see's the host header. I'm not sure how you configured the same CNAME on two CloudFront distributions, it shouldn't be possible. For this to work, you would need to utilize two different services, for example, S3 and CloudFront. Create a bucket for test.example.net and a CloudFront distribution configured with test.example.net. Then you can WRR as both services will serve your content for test.example.net
{ "pile_set_name": "StackExchange" }
Q: Why GetText method returns empty string I wrote the following, after run this code it returns empty String value. Can any one suggest me to solve this problem? Here I used gettext() method. It does not retrieve the link names. My code is: package Practice_pack_1; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class CheckingUncheckingCheckbox { WebDriver driver; @BeforeTest public void open() { driver=new FirefoxDriver(); driver.navigate().to("http://openwritings.net/sites/default/files/radio_checkbox.html"); } @AfterTest public void teardown() throws InterruptedException { Thread.sleep(3000); driver.quit(); } @Test public void CheckingChkbox() throws InterruptedException{ WebElement parent = driver.findElement(By.xpath(".//*[@id='fruits']")); List<WebElement> children = parent.findElements(By.tagName("input")); int sz= children.size(); System.out.println("Size is: "+sz); for (int i = 0; i <sz; i++) { boolean check= children.get(i).isSelected(); if(check==true) { System.out.println(children.get(i).getText()+ "is selected"); } else { System.out.println(children.get(i).getText()+ "is not selected"); } } } } Output is: Size is: 3 is selected is not selected is selected PASSED: CheckingChkbox A: Regarding your application you may need to use getAttribute("value") instead of getText() as getText return the inner text.
{ "pile_set_name": "StackExchange" }
Q: Silverlight scrollviewer's scrollbar invisible when not active How do i detect when scrolling is unavailable to the scrollviewer control and make it invisible. And the scrollbar only visible when there is a chance to scoll up or down. Thanks, Shawn McLean A: Specifying HorizontalScrollBarVisibility="Auto" and VerticalScrollBarVisibility="Auto" acheives this goal with out you needing to do any "detecting" of your own.
{ "pile_set_name": "StackExchange" }
Q: MSTest Asserts fail with null reference Trying to create a simple test method for a .NET 4.7 Framework project. All of the examples are for Core or older versions of the MSTest framework. I can get the test to pass with a simple check for the returned object. If I try anything more complex, like verify the number of records returned, the tests fail as contentResult is always coming up as null. I indicated which Asserts are failing. using Locations.Api.Controllers; using Locations.Api.Domain.Models; using Locations.Api.Domain.Services.Interfaces; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Results; namespace Locations.Api.Tests { [TestClass] public class TestLocationsController { [TestMethod] public void GetAllLocations_ShouldReturnAllLocations() { // Arrange List<Location> testLocations = GetTestLocations(); Mock<ILocationsService> locationsServiceMock = new Mock<ILocationsService>(); locationsServiceMock.Setup(location => location.GetAllLocations()) .Returns(testLocations); LocationsController controller = new LocationsController(locationsServiceMock.Object); // Act IHttpActionResult locations = controller.GetAllLocations(); // Assert Assert.IsNotNull(locations, "locations is null"); var contentResult = locations as OkNegotiatedContentResult<Location>; // THESE ALL FAIL Assert.IsInstanceOfType(locations, typeof(List<Location>), "Wrong Model"); // ERROR: type:<System.Collections.Generic.List`1[Locations.Api.Domain.Models.Location]>. Actual type:<System.Web.Http.Results.OkNegotiatedContentResult`1[System.Collections.Generic.List`1[Locations.Api.Domain.Models.Location]]>. Assert.IsNotNull(contentResult.Content, "contentResult is null"); // ERROR: System.NullReferenceException Assert.AreEqual(1, contentResult.Content.Id); // ERROR: System.NullReferenceException Assert.AreEqual(2, locations.Count(), "Got wrong number of locations"); // ERROR: 'IHttpActionResult' does not contain a definition for 'Count' } private static List<Location> GetTestLocations() { return new List<Location> { new Location { Id = 1, Name = "Albuquerque", Category = "Terminal", Street = "301 Airport Road NW", City = "Albuquerque", State = "NM", ZipCode = "87121", Latitude = 35.0822720000M, Longitude = -106.7169960000M, NearestMajorCity = "Albuquerque", Phone1 = "(505) 344-1619", Phone2 = null, Avaya = null, GateCode = "1234", SpecificEntranceDirections = "Enter via front gate", SwiftCharitiesAmbassador = "Homer Simpson", Extras = "stuff" }, new Location { Id = 2, Name = "Columbus", Category = "Terminal", Street = "4141 Parkwest Drive", City = "Columbus", State = "OH", ZipCode = "43228", Latitude = 39.9668110000M, Longitude = -83.1153610000M, NearestMajorCity = "Cincinnati", Phone1 = "(614) 274-5204", Phone2 = null, Avaya = null, GateCode = "5678", SpecificEntranceDirections = "Enter on west side", SwiftCharitiesAmbassador = "Marge Simpson", Extras = "none" } }; } } } A: Your first error on the first failing assertion shows why this isn't working: locations is of type OkNegotiatedContentResult<List<Location>>, not OkNegotiatedContentResult<Location>. Since you're using the safe cast, as, and the type of location is not OkNegotiatedContentResult<Location>, the result of the cast will always be null. You could adjust the code as follows: var contentResult = locations as OkNegotiatedContentResult<List<Location>>; Assert.IsNotNull(contentResult, "contentResult should not be null."); Assert.IsInstanceOfType(contentResult.Content, typeof(List<Location>), "Wrong Model"); Assert.IsNotNull(contentResult.Content, "contentResult.Content is null"); Assert.AreEqual(1, contentResult.Content[0].Id); Assert.AreEqual(2, contentResult.Content.Count, "Got wrong number of locations");
{ "pile_set_name": "StackExchange" }
Q: In my case, you can star and change stop shimmer animation? I have a case of such a want to do so after refresh a couple of seconds were loaded with shimmer and finished animation. my code starAnimatiom : func startAnimation() { for animateView in getSubViewsForAnimate() { animateView.clipsToBounds = true let gradientLayer = CAGradientLayer() gradientLayer.colors = [UIColor.clear.cgColor, UIColor.white.withAlphaComponent(0.8).cgColor, UIColor.clear.cgColor] gradientLayer.startPoint = CGPoint(x: 0.7, y: 1.0) gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.8) gradientLayer.frame = animateView.bounds animateView.layer.mask = gradientLayer let animation = CABasicAnimation(keyPath: "transform.translation.x") animation.duration = 1.5 animation.fromValue = -animateView.frame.size.width animation.toValue = animateView.frame.size.width animation.repeatCount = .infinity gradientLayer.add(animation, forKey: "") } } func getSubViewsForAnimate() -> [UIView] { var obj: [UIView] = [] for objView in view.subviewsRecursive() { obj.append(objView) } return obj.filter({ (obj) -> Bool in obj.shimmerAnimation }) } My code function stopAnimation; @objc func stopAnimation() { for animateView in getSubViewsForAnimate() { animateView.layer.removeAllAnimations() animateView.layer.mask = nil timerShimmer.invalidate() refresh.endRefreshing() } } When I pull down and do the update the animation continues to act and for some reason does not stop.What did I do wrong? @objc func obnova() { self.startAnimation() self.tableView.reloadData() self.loadObjects1() self.loadObjects2() self.loadObjects3() // self.refresh.endRefreshing() } override func viewDidLoad() { super.viewDidLoad() timerShimmer = Timer.init(timeInterval: 0.2, target: self, selector: #selector(stopAnimation), userInfo: nil, repeats: true) } Help me Please? A: Change the last section like below and try func startTimer() { if timerShimmer != nil { timerShimmer.invalidate() timerShimmer = nil } timerShimmer = Timer.init(timeInterval: 0.2, target: self, selector: #selector(stopAnimation), userInfo: nil, repeats: true) } @objc func obnova() { self.startAnimation() self.tableView.reloadData() self.loadObjects1() self.loadObjects2() self.loadObjects3() startTimer() } override func viewDidLoad() { super.viewDidLoad() startTimer() }
{ "pile_set_name": "StackExchange" }
Q: Looking to achieve frame effect with shadows at corners Where can I find PSD file or tutorial to create the effect of frame with shadow (see red arrow in image) A: I agree with Lèse that there would also appear to be a slight outer glow or secondary shadow applied to the frame in your posted image.
{ "pile_set_name": "StackExchange" }
Q: How to mitigate DDOS attacks on AWS? I have web application (NodeJS) and I plan to deploy it to AWS. To minimize the cost it will run on single EC2 instance. I'm worried though about what will happen if someone decides to bless me with DDOS attack and hence have few questions. Now, I did quite a bit of research, but as my understanding is clearly lacking I apologise if some of the questions are plain stupid: I want to avoid people flooding my site with layer 4 attacks. Would it be sufficient to set my Security Group to accept traffic only (in additions to SSH port 22) from: Type HTTP Protocol TCP Port Range 80 Would above stop UDP flood and others from hitting my EC2 instance? Via Security Group I would allow SSH connections to port 22 only from my static IP address. Would that keep attackers away from trying to attack port 22 completely? My EC2 instance will run Ubuntu. I want to avoid application layer attacks (layer 7) and was planning to do it directly from my application, so somehow detect if certain IP floods particular URLs and block them if necessary. This however seems a bit late as the traffic already hits my web server and my server have to do the work anyway. So instead of doing this directly from my application I was thinking if that was possible to use IP tables to block any dodgy traffic before it comes to my web server. Is there set of some common settings that would be able to recognise rogue behaviour and block offenders? I was planning to look into fail2ban in hope this would simplify the process. Now, I do understand if it gets that far it will hit my EC2 instance anyway, but I want to protect my application also from e.g. brute force attacks. Would AWS CloudFront take care of most DDOS Layer 4 attacks? If not then using free CloudFlare would make any difference? Say that someone floods my website anyway and this results in more traffic then I anticipated. Is there any way to stop charges at some point? There are billing alerts but I cannot see any way to set hard limits on AWS and say get instance offline if bandwidth exceeded. I also do realise that there is now way to completely prevent DDOS attacks but I want to protect at least against basic attempts. Thank you in advance for any help. A: 1) Setting Security Group is easy and important layer of security. If you are running any web app than port 80/443 are one that to be open to the world and 22 for accessing server remotely via ssh should be allowed from a particular IP address only. Other than these 3 ports all traffic will be blocked. You can test with Port Scanning or NMAP tool. 2) Limit access for SSH to a your static IP address only and also for accessing EC2 Instance via ssh you need a key. If attacker somehow get to know your IP address he/she cannot access your server without key. Note :- If you are using CDN(CloudFlare) than your EC2 Static IP is already hidden. 3) You can limit the amount of concurrent connections from the same IP address to your server. You can use linux firewall rules for that :- iptables -I INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --set iptables -I INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --update --seconds 60 --hitcount 10 -j DROP iptables-save >/etc/iptables.up.rules The first line will Watch the IP connecting to your eth0 interface. The second line will Check if the connection is new within the last 60 seconds and if the packet flow is higher than ten and if so it will drop the connection. The third line will Make the rules persistent in case of a reboot. To verify the number of concurrent connections from all clients that are connected to your server :- netstat -tn 2>/dev/null | grep :80 | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head It will show a list of the current active connections by IP address and the offending IP is usually the one with a high number of connections. 12 10.1.1.1 160 162.19.17.93 In the example above the first number is the number of connections followed by the Originating IP address. Note :- In a heavily loaded server the number of connections may be above 100, but during DDOS attack the number will go even higher. For an average host, if you have more than 30 connections from a single IP, chances are you are under attack. If more than 5 such IP/Host connected from same network , that's a very clear sign of DDOS attack. Output of lsof,netstat and tcpdump are very useful in detecting such type of issues. Now you get the IP address of the client you can use IPtables to block that IP or tcpkill command to do so. TCPKILL is part of dsniff package. apt-get install dsniff Then issue :- tcpkill host x.x.x.x The above method is good and it will help you to mitigate small DDOS Attack if applied correctly. Now if you are using CDN ( CloudFlare ) than you can block the attacker at that level only. You can use CloudFlare API to block the IP address. In this traffic will not come to you server. Read more at CloudFlare API Doc Refer to above method and create a script that will help you in automation. 4) In my opinion CloudFlare is better than CloudFront. CloudFlare is easy to setup and from one control panel you can handle everything. Even if you find heavy amount of unnecessary traffic than cloudflare "I am Under Attack" mode will mitigate it in under 5-10 seconds. Read more about DDOS and I'm Under attack mode in Cloudflare Blogs. 5) You can setup AWS Alarms to stop/Terminate EC2 instance if your Network Bandwidth exceeds the limit. AWS Alarm Sample Edit:- One important thing is try to setup Monitoring tool (Like Nagios) and Log Management tool of web app access. This will help you to find the bottleneck.
{ "pile_set_name": "StackExchange" }
Q: Can this simple integral be zero for a Jordan curve? The following simple problem came up while doing some unrelated research. Does there exist a Jordan curve $\gamma : [0,2\pi] \to \mathbb{C}$ of positive orientation, lets say $C^1$-smooth (just to simplify the problem) that satisfies: $$\int_0^{2\pi} \gamma(t)e^{-it} dt = 0 $$ I am hoping that such a curve does not exist, but I could be overlooking something simple. A: Yes it exists. Think of the curve which goes from $1$ to $2+\varepsilon{\cdot} i$ and then to $-1$ and which is symmetric with respect to real axis; so $\gamma(-t)=\bar \gamma(t)$ and it is defined in $[-\pi,\pi]$. For such curves the integral is real. If we run the arc from $2- \varepsilon{\cdot} i$ to $2+\varepsilon{\cdot} i$ too fast then your integral is positive. if we run it slow and spend a lot of time near $\pm\pi$ close to $2$ then your integral is negative. So somewhere you will get zero.
{ "pile_set_name": "StackExchange" }
Q: Pool items in database until minimum sample size reached and find all permutations in R This is an example. df <- data.frame(item=letters[1:5], n=c(3,2,2,1,1)) df item n 1 a 3 2 b 2 3 c 2 4 d 1 5 e 1 Item needs to be grouped so that the group has a sample size of at least 4. This would be the solution if you follow the sorting of df. item n cluster 1 a 3 1 2 b 2 1 3 c 2 2 4 d 1 2 5 e 1 2 How to get all possible unique solutions? Further, the code should also not allow any clusters to have a sample size less than 4. A: Below, we have a brute force approach using the package partitions. The idea is that we find every partition of the rows of df. We then sum each group and check to see that the requirement has been met. df <- data.frame(item=letters[1:5], n=c(3,2,2,1,1)) minSize <- 4 funGetClusters <- function(df, minSize) { allParts <- partitions::listParts(nrow(df)) goodInd <- which(sapply(allParts, function(p) { all(sapply(p, function(x) sum(df$n[x])) >= minSize) })) allParts[goodInd] } clusterBreakdown <- funGetClusters(df, minSize) allDfs <- lapply(clusterBreakdown, function(p) { copyDf <- df copyDf$cluster <- 1L clustInd <- 2L for (i in p[-1]) { copyDf$cluster[i] <- clustInd } copyDf }) Here is the output: allDfs [[1]] item n cluster 1 a 3 1 2 b 2 1 3 c 2 1 4 d 1 1 5 e 1 1 [[2]] item n cluster 1 a 3 1 2 b 2 2 3 c 2 2 4 d 1 1 5 e 1 1 [[3]] item n cluster 1 a 3 2 2 b 2 1 3 c 2 1 4 d 1 2 5 e 1 1 [[4]] item n cluster 1 a 3 2 2 b 2 1 3 c 2 1 4 d 1 1 5 e 1 2 [[5]] item n cluster 1 a 3 2 2 b 2 1 3 c 2 2 4 d 1 1 5 e 1 1 [[6]] item n cluster 1 a 3 2 2 b 2 2 3 c 2 1 4 d 1 1 5 e 1 1 It should be noted, that there is a combinatorial explosion as the number of rows increases. For example, just with 10 rows we would have to test 115975 different partitions. As @chinsoon comments, RcppAlgos could be a good choice for an acceptable solution for larger cases. Disclaimer, I am the author. I have answered similar questions with much larger inputs and have had good success. Allocating tasks to parallel workers so that expected cost is roughly equal Split a set into n unequal subsets with the key deciding factor being that the elements in the subset aggregate and equal a predetermined amount? @AllanCameron also has a great answer and nice methodology to attacking this problem. You should give that a read as well. Lastly, the following vignette by Robin K. S. Hankin (author of the partitions package) and Luke J. West is not only a great read, but very applicable to problems like the one presented here. Set Partitions in R
{ "pile_set_name": "StackExchange" }
Q: MySQL query unknown error I'm trying to run this query on MySQL server: CREATE PROCEDURE forum.eventlog_create( i_UserID INT, i_Source VARCHAR(128), i_Description TEXT, i_Type INT, i_UTCTIMESTAMP DATETIME) MODIFIES SQL DATA BEGIN INSERT INTO forum.EventLog (UserID, Source, Description, ´Type´) VALUES (i_UserID, i_Source, i_Description, i_Type); END; However upon executing it I get the following error: Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 12 and I'm unable to fix it. I tried to search for a solution and asked a co-worker but we were unable to find the solution, as last resort I decided to ask it here. I get error code 1064 but the right syntax near '' is the message and I dont understand what the problem could be. It would be easier if it said which syntax gives the error, I only get the line number. Thank you for your time A: There is one error caused by the escape character around type which should be either backticks or dropped and you should try setting delimiters https://dev.mysql.com/doc/refman/5.7/en/stored-programs-defining.html delimiter $$ CREATE PROCEDURE eventlog_create( i_UserID INT, i_Source VARCHAR(128), i_Description TEXT, i_Type INT, i_UTCTIMESTAMP DATETIME) MODIFIES SQL DATA BEGIN INSERT INTO forum.EventLog (UserID, Source, Description, `Type`) VALUES (i_UserID, i_Source, i_Description, i_Type); END $$ delimiter ;
{ "pile_set_name": "StackExchange" }
Q: Dispatching Brainfuck commands using if-else or dictionary Here's the first, straightforward version of BF interpreter: def run(step_limit, memo, m_i, code): """ Runs valid BF code. """ if len(code) == 0: return i = 0 for step in range(step_limit): cmd = code[i] # Switch - case if cmd == '+': memo[m_i] += 1 elif cmd == '-': memo[m_i] -= 1 elif cmd == '>': m_i += 1 elif cmd == '<': m_i -= 1 elif cmd == '.': print (memo[m_i]) elif cmd == ',': memo[m_i] = int ( input ( "Input: " ) ) elif cmd == '[': if memo[m_i] == 0: i = code.find(']', i, len(code) ) else: # if cmd == ']' if memo[m_i] != 0: i = code.find('[', 0, i ) i += 1 if i == len(code): break And the second one: """ Second version of the same method. """ # I tried to use namedtuples but I failed. Using simple, usual tuples instead. def plus (args): return args[1]+1, args[2]+1, args[3] def minus (args): return args[1]+1, args[2]-1, args[3] def rigth (args): return args[1]+1, args[2], args[3]+1 def left (args): return args[1]+1, args[2], args[3]-1 def output (args): print (args[2]) return args[1]+1, args[2], args[3] def u_input (args): return args[1]+1, int (input ("Input: ") ), args[3] def loop_begin (args): if args[2] == 0: return args[0].find(']', args[1], len(args[0]))+1,args[2],args[3] else: return args[1]+1, args[2], args[3] def loop_end (args): if args[2] != 0: return args[0].find('[', 0, args[1] )+1, args[2], args[3] else: return args[1]+1, args[2], args[3] def nothing (args): # So that memo[m_i] wouldn't go out of index return args[1], args[2], args[3] commands = { '+' : plus, '-' : minus, '>' : rigth, '<' : left, '.' : output, ',' : u_input, '[' : loop_begin, ']' : loop_end, ' ' : nothing } def run(step_limit, memo, m_i, code): """ Runs valid BF code. """ if len(code) == 0: return code += ' ' # So that memo[m_i] wouldn't go out of index i = 0 for step in range(step_limit): args = (code, i, memo[m_i], m_i) i, memo[m_i], m_i = commands[ code[i] ] ( args ) if args[1] == len(args[0]) - 1 or code[i] == ' ': break # Now we have to add space after program so that memo[m_i] wouldn't go out of index run(1000000000, [478234, 5161845], 1, "[-<+>]<. ") # TEST, adds two numbers Yes, I know I should have used dictionaries to increase readability because now the indexes are horrible, but this is just a quick concept. Question: would you ever prefer second structure over the first one, and under what conditions? Maybe you know a solution better than both of these versions? Some of my thoughts: Second version is 2x slower. Benchmarked with run(1000000000, [478234, 5161845], 1, "[-<+>]<. "), finishes in 73.5s while first one does the job in 36s. In my opinion, second version is more decompositioned, thus easier to maintain and expand in very big projects, but not worthy the effort in the small ones. A: A few coding points: I think you could simplify the arguments a lot by using kwargs, rather than passing a tuple of arguments. Having your dict in the global namespace, rather than the function's local namespace, will slow it down considerably. 0 is False, so if args[2] != 0: can just be if args[2]. For unused variables, like step, I consider it better to mark it as such by using _ as the variable name. Half of the functions are simple one-liners that can use lambdas. Although half of the functions can be lambdas, some of them would work better by doing in-place operations on memo. If you want to search until the end, you don't need to specify an end to find. You add 1 to i in every case, so that can be moved out of the functions. As for your questions: There are three major situations where I would use the dict structure. The functions can either be lambdas or external functions that are short and easy-to-read as dict values. Usually this is better with only one or a few consistent arguments. The functions are so long that putting them in an if chain makes it hard to keep track of the flow. Again, usually this is better with only one or a few consistent arguments. There are a huge number of possible inputs, which makes for an overly long if test chain, but where there are again only one or a few consistent arguments. The problem with your case is that this is in-between, they are simple enough that you can follow the flow easily in an if test, but they are not all so simple that they can be put into lambdas without sacrificing clarity (it is possible to put all but one in lambdas, but half would be really hard to read). Further, there are not so many situations that it becomes hard to read in an if chain (although it is getting close), and there are enough arguments (or enough inconsistency in the arguments) that it is getting to the point where I would not use the dict approach even if all the other criteria were satisfied (although again it is kind of borderline). Ultimately, what it comes down to is whether the dict approach helps or hurts readability. In your case, I think it hurts it. If the criteria I described above hold, then it will probably help it (although you really need to look on a case-by-case basis, since there will be corner cases either way).
{ "pile_set_name": "StackExchange" }
Q: Winter food : Should I change my habits for winter? Should I change my food habits for my winter activities? Is simply increasing the quantities or choosing food with higher calories enough? A: Caloric intake is certainly the largest factor. Calories are energy. If you are on a low fat diet normally and a very fit individual, you'll likely need to increase your fat intake. However the primary concern is that you are getting fats, so if you are already, you should be fine. Drink more water! It's very counter intuitive, but you dehydrate faster in the cold. A: One other difference - in the winter, your food and water can freeze during the day. Make sure that your lunch (or anything else you'd eat without cooking) is something that you can actually chew when its frozen. Also, camelback-style water bladders can be a little more difficult to use, as the water in the tube can freeze up.
{ "pile_set_name": "StackExchange" }
Q: What is wrong with this RSpec expectation? I am using rspec version 2.14.8 and Ruby 2.1.1. I have the following in test_spec.rb describe 'My code' do it 'should work' do expect ( nil ).to be_nil expect ( "test" ).to eq( "test") end end When I run this simple spec (rspec test_spec.rb), I get the following error: Failures: 1) My code should work Failure/Error: expect ( nil ).to be_nil NoMethodError: undefined method `to' for nil:NilClass # ./test_spec.rb:3:in `block (2 levels) in <top (required)>' What is wrong!? A: You must not put a space between expect and the opening paren (. The working code sample is as follows: describe 'My code' do it 'should work' do expect( nil ).to be_nil expect( "test" ).to eq( "test") end end
{ "pile_set_name": "StackExchange" }
Q: Wireless disconnects and reconnects especially when I download from deluge and firefox In general, my wireless connection seems to be working fine but it keeps disconnecting and reconnecting when I start downloading files from deluge and Firefox. I have tried most of the tweaks and workarounds I could find online in similar questions, but without any success so far. I am a very new Linux user so I would appreciate if somebody told me what I should post (perhaps from my log or something) in order to see if this problem can be solved. I am running Ubuntu 15.04, and the command "type lshw -C network" gives me the following *-network description: Wireless interface product: AR9285 Wireless Network Adapter (PCI-Express) vendor: Qualcomm Atheros physical id: 0 bus info: pci@0000:03:00.0 logical name: wlan0 version: 01 serial: e0:ca:94:1f:f3:07 width: 64 bits clock: 33MHz capabilities: pm msi pciexpress bus_master cap_list ethernet physical wireless configuration: broadcast=yes driver=ath9k driverversion=3.19.0-28-generic firmware=N/A ip=192.168.1.2 latency=0 link=yes multicast=yes wireless=IEEE 802.11bgn resources: irq:17 memory:f6600000-f660ffff *-network description: Ethernet interface product: RTL8101E/RTL8102E PCI Express Fast Ethernet controller vendor: Realtek Semiconductor Co., Ltd. physical id: 0 bus info: pci@0000:04:00.0 logical name: eth0 version: 05 serial: 00:1f:c6:9d:ff:ed size: 10Mbit/s capacity: 100Mbit/s width: 64 bits clock: 33MHz capabilities: pm msi pciexpress msix vpd bus_master cap_list ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd autonegotiation configuration: autonegotiation=on broadcast=yes driver=r8169 driverversion=2.3LK-NAPI duplex=half firmware=rtl_nic/rtl8105e-1.fw latency=0 link=no multicast=yes port=MII speed=10Mbit/s resources: irq:29 ioport:a000(size=256) memory:e2c04000-e2c04fff memory:e2c00000-e2c03fff I thank you in advance for your help. A: There are a lot of people on the low channels, especially channel 1. You are currently on channel 2. Try changing your wifi router to use channel 11 for now. Other problems may include your wireless router overheating or filling up with logs and having to reset. So, also check your wireless router logs immediately after the problem occurs so you can see if there is any helpful information like a recent reset or reboot. Also, according to this post here, you might want to run the following command after suspending to reset wpa_supplicant: systemctl restart wpa_supplicant
{ "pile_set_name": "StackExchange" }
Q: cookie handling in php i get the notice Notice: Undefined index: date_cook in C:\wamp\www\project work\calendar.php on line 5 when i try to run the following code written in php to handle a calendar :- <?php if(!isset($_COOKIE['date_cook'])) { setcookie('date_cook',0); $date_inc=$_COOKIE['date_cook']; } else { if(!isset($_POST['nxt'])) { $date_inc=$_COOKIE['date_cook']; } else { $date_inc=$_COOKIE['date_cook']; $date_inc++; setcookie('date_cook',$date_inc); unset($_POST['nxt']); } } ?>//the calendar code follows here after. the notice is displayed for line number 5 of the code can somebody tell me where did i go wrong...?? A: Once you setcookie(), it's not instantly stored in $_COOKIE. You either have to put it there manually ($_COOKIE['date_cook'] = 0) or use a variable instead.
{ "pile_set_name": "StackExchange" }
Q: Algebraic Substitution Of Fractions I already tried to putting the square root like this: $\sqrt{\frac{x}{5 + x}}$ but I dont know what to do next. $$\int \frac{\sqrt{x}}{\sqrt{5+x}}dx$$ A: $$\frac x{5+x}=u^2\implies x=\frac{5u^2}{1-u^2}\implies dx=\frac{10u\,du}{(1-u^2)^2}\implies$$ $$\int\sqrt\frac x{5+x}\,dx=\int\frac{10u^2}{(1-u^2)^2}du$$ and now you have the integral of a rational function. Do, for example, partial fractions, or whatever. A: Another method would be to let $u=\sqrt{x+5}$, so $x=u^2-5 \text{ and } dx=2udu$ to get $\;\;\;\displaystyle\int\frac{\sqrt{u^2-5}}{u}\cdot 2u\;du=2\int{\sqrt{u^2-5}}\;du$ . Now let $u=\sqrt{5}\sec\theta, du=\sqrt{5}\sec\theta\tan\theta d\theta$ to get $10\int\tan^{2}\theta\sec\theta\;d\theta$, and integrate by parts.
{ "pile_set_name": "StackExchange" }
Q: modal pop up like google How to make modal popup like gmail (when we try to upload exe the pop up that generates covers scrollbar of the page) A: GMail runs on a iframe and the overlay div is not inside this iframe, so it stays on top o the iframe consequently on top of the scrollbar. Code from GMail html, body { height:100%; margin:0; overflow:hidden; /* no scrollbars (only in the iframe) */ width:100%; } .cO { /* this is the iframe */ height:100%; width:100%; } .Kj-JD { background-color:#C3D9FF; border:1px solid #4E5766; color:#000000; outline:0 none; padding:5px; position:absolute; top:0; width:450px; z-index:501; /* div stays on top */ } .Kj-JD-Jh { /* the shadow */ background-color:#808080; left:0; position:absolute; top:0; z-index:500; } Sample HTML <body> <iframe class="cO">...</iframe> <!-- the scroll works on the iframe, not the body --> <div class="Kj-JD"></div> <!-- outside the iframe --> <div class="Kj-JD-Jh" style="opacity: 0.5; width: 1440px; height: 361px;"></div> <!-- black background --> </body> To show a div on top I recommend jqModal, it does all the hard work for you. A: Check out the following modal dialog plugins for jQuery: jqModal ThickBox BlockUI jQuery UI Dialog Facebox
{ "pile_set_name": "StackExchange" }
Q: PHP if...elseif....else statement Hoping someone can hep with this... I have four logos, I want a three of them to display if a user is on a certain page and I want the fourth logo to display if the user is on any other page. I just can't get my head round conditional statements? if (is_page('870')   Show logo 1; elseif (is_page('891')   Show logo 2; elseif (is_page('886')   Show logo 3; else   Show logo 4; A: if (!page4) { // show logo 1, 2, and 3 } else { // show logo 4 } Perhaps, I misunderstand your grammar. You are missing parenthesis. if (is_page('870')) Show logo 1; else if (is_page('891')) Show logo 2; else if (is_page('886')) Show logo 3; else Show logo 4;
{ "pile_set_name": "StackExchange" }
Q: s.sendall doesn't work inside a thread in python I'm trying to develop a chat program in python. I want it to have multiple clients so I'm using threading to handle this. However when I try to send the message to all connected clients, the server only sends it to the client which sent the message. I'm not sure if I'm just missing something obvious but here is the code for the server: import socket from thread import * host = '192.168.0.13' port = 1024 users = int(input("enter number of users: ")) def clienthandler(conn): while True: data = conn.recv(1024) if not data: break print data conn.sendall(data) conn.close() serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversock.bind((host, port)) serversock.listen(users) for i in range(users): conn, addr= serversock.accept() print 'Connected by', addr start_new_thread(clienthandler, (conn,)) And here is the code for the client: import socket host = '192.168.0.13' port = 1024 usrname = raw_input("enter a username: ") usrname = usrname + ": " clientsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clientsock.connect((host, port)) while True: x = raw_input('You: ') x = usrname + x clientsock.sendall(x) data = clientsock.recv(1024) print data A: The "all" in sendall means that it sends all of the data you asked it to send. It doesn't mean it sends it on more than one connection. Such an interface would be totally impractical. For example, what would happen if another thread was in the middle of sending something else on one of the connections? What would happen if one of the connections had a full queue? sendall: Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Unlike send(), this method continues to send data from string until either all data has been sent or an error occurs. None is returned on success. On error, an exception is raised, and there is no way to determine how much data, if any, was successfully sent. -- 17.2. socket
{ "pile_set_name": "StackExchange" }
Q: Linq filter returned data repeated I am trying to filter a list of object using Linq method Where, however, after filter execution the list returned the first element that fulfilled the condition repeated across the whole list (i.e., repeated the number of times for other elements fulfilling the condition too). For example, I am returning employees only with country id = 3 and I should have three employees Green, Blue, and Red, however, I got only Blue repeated 3 times Blue, Blue, Blue. I am using MySql as my backing store and I am using Entity Framework with MySqlConnection object public class Repository<T> : IRepository<T> where T : class { public IEnumerable<T> SelectAll() { return db.Set<T>().ToList(); } } public class AnalyticsRepository : Repository<Analytics> { public new List<Analytics> SelectAll() { return base.SelectAll().ToList<Analytics>(); } } public IEnumerable<Analytics> SelectByCountryAndProduct(string countrycriteria, string productcriteria) { List<Analytics> result = null; using (AppDbContext db = new AppDbContext(factory.GetConnection())) { db.Database.CommandTimeout = 6000; analyticsRepository = new AnalyticsRepository(db); result = analyticsRepository.SelectAll(); } return result .Where( a => a.CountryId.ToString() == countrycriteria && a.ProductId.ToString() == productcriteria) .ToList(); } Debugging and trying another sample solution on a list with dummy data which is worked fine A: I knew what causes the problem. The problem lies in the Analytics model configuration. I configured the Analytics with a composite key, CountryId and ProductId, respectively. On the other hand, CountryId and ProductId together do not uniquely identify rows within the database. They are repeated across the returned result set. After applying the filter I got only the first occurrence being repeated number of times for other objects that qualify the filter condition. For example, lets say that I have 532 different rows having the same country id and product id after applying the Linq Where I got the first occurrence within the 532 rows being repeated 532 times within the returned list.
{ "pile_set_name": "StackExchange" }
Q: inner join on true My table: abc +--------+ | letter | +--------+ | a | | b | +--------+ Query: SELECT * FROM abc t1 INNER JOIN abc t2 ON true Result: +--------+--------+ | letter | letter | +--------+--------+ | a | a | | b | a | | a | b | | b | b | +--------+--------+ What does or how does ON true do/work? A: While I've never seen this exact syntax (for obvious reasons - it really serves little purpose and I wouldn't expect to encounter it in the real world) my guess would be that the result will be a cartesian product as the condition states that rows in t1 should be matched with rows in t2 when condition evaluates as true, which it always does. So all rows in the first set will be matched to all rows in the second set. The condition is never tried against anything else, just itself and true will always evaluate as true.
{ "pile_set_name": "StackExchange" }
Q: jQuery ui datepicker conflict with bootstrap datepicker I want to show two months using bootstrap datepicker. After search on google I am not able to find how to show multiple months using bootstrap datepicker. I found that I can use JQuery UI for displaying multiple months. But problem is: In my application they are using bootstrap date picker. When I am trying to use JQuery UI datepicker then Bootstrap datepicker override it and I am not able to see JQuery UI datepicker. Could you please suggest how to replace bootstrap datepicker to JQuery UI? I wanted to achieve this: http://jqueryui.com/datepicker/#multiple-calendars A: This issue can be solved using the noConflict method of bootstrap-datepicker $.fn.datepicker.noConflict = function(){ $.fn.datepicker = old; return this; }; You can just do $.fn.datepicker.noConflict() which replaces the bootstrap datepicker with the older datepicker which was present, in this case jQuery UI. For those who wants to keep both datepickers, you can do something along the following: if (!$.fn.bootstrapDP && $.fn.datepicker && $.fn.datepicker.noConflict) { var datepicker = $.fn.datepicker.noConflict(); $.fn.bootstrapDP = datepicker; } after which you'll be able to initialize jQuery UI datepicker using datepicker() method, and bootstrap one using bootstrapDP() Side note: Make sure you load bootstrap datepicker after jquery ui so that we can use it's noConflict() $(function() { if (!$.fn.bootstrapDP && $.fn.datepicker && $.fn.datepicker.noConflict) { var datepicker = $.fn.datepicker.noConflict(); $.fn.bootstrapDP = datepicker; } $("#jquery-ui-datepicker").datepicker({}); $('#bootstrap-datepicker').bootstrapDP({}); }); #left { width: 50%; float: left; } #bootstrap-datepicker { width: 50%; float: right; } <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" /> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.1/css/bootstrap-datepicker.css" rel="stylesheet" /> <link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.1/js/bootstrap-datepicker.min.js"></script> <div id="left"> <p>Date: <input type="text" id="jquery-ui-datepicker"> </p> </div> <div id="bootstrap-datepicker" class="input-group date"> <input type="text" class="form-control"><span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span> </div>
{ "pile_set_name": "StackExchange" }
Q: @@ROWCOUNT is incorrect on a DELETE (SQL Server 2017) I've never run into this before. I'm trying to verify that a query is accurate, so I'm doing this: SELECT * FROM MyTable mt JOIN OtherTable ot ON ot.ID = mt.OtherTableID JOIN @tablevar tv ON tv.ID = mt.TableVarID; DELETE mt FROM MyTable mt JOIN OtherTable ot ON ot.ID = mt.OtherTableID JOIN @tablevar tv ON tv.ID = mt.TableVarID; SELECT @@ROWCOUNT; SELECT * FROM MyTable mt JOIN OtherTable ot ON ot.ID = mt.OtherTableID JOIN @tablevar tv ON tv.ID = mt.TableVarID; The numbers I'm getting, though, are weirdly off. I'm getting the following results: Table with 5208 rows Success - 51 rows affected 51 Empty table The part I don't get is this: the select condition and the delete condition are, so far as I can tell, identical. So why does the SELECT return 5k rows, the DELETE removes 51 rows, the @@ROWCOUNT claims only 51 rows were affected, but the final SELECT shows that the correct number of rows (5k) were removed? I am aware that @@ROWCOUNT is pretty fragile -- anything will overwrite it, just about. So I looked for triggers in the table in question and found none. Has anyone run across this? A: You are deleting rows from MyTable. So, the delete is saying that 51 rows are being deleted from this table. Your select has two joins that are clearly multiplying the number of rows. If you want to see what is being deleted, then use exists: SELECT mt.* FROM MyTable mt WHERE EXISTS (SELECT 1 FROM OtherTable ot JOIN @tablevar tv ON tv.ID = mt.TableVarID WHERE ot.ID = mt.OtherTableID ); You can use the same logic in the DELETE. Also, to see the rows actually being deleted, you might consider an OUTPUT clause. This allows you to see the rows, not just the count.
{ "pile_set_name": "StackExchange" }
Q: Powershell query to find the total disk usage I am trying to find a powershell (or WMI) query to find the sum of disk space utilization in a PC. I have the following query... But as you can see in the image, it is showing separate rows for each drive. How Can I get the total of disk space. Sebastian A: Measure-Object should do that work for you nicely. You didnt say what data you were looking for exactly so this would give both sums of FreeSpace and Size. Get-WmiObject -class win32_logicaldisk | Measure-Object -Sum freespace,size -or- Get-WmiObject -class win32_logicaldisk | Measure-Object -Sum size You need to extract the sum from that for it to be useful.
{ "pile_set_name": "StackExchange" }
Q: Tomcat doesn't run if "metadata-complete" is set as false I'm using Eclipse for Java EE developers. I'm trying to run this servlet: package br.com.caelum.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.annotation.WebServlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet( name = "OiServlet3", urlPatterns = {"/oi"}, initParams = { @WebInitParam(name = "param1", value = "value1"), @WebInitParam(name = "param2", value = "value2")} ) public class OiMundo extends HttpServlet { protected void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); // escreve o texto out.println("<html>"); out.println("<head>"); out.println("<title>Primeira Servlet</title>"); out.println("</head>"); out.println("<body>"); ServletConfig config = getServletConfig(); String parameter1= config.getInitParameter("param1"); out.println("Value of parameter 1: " + parameter1); String parameter2 = config.getInitParameter("param2"); out.println("<br>Value of parameter 2: " + parameter2); out.println("<h1>Hi Servlet!</h1>"); out.println("</body>"); out.println("</html>"); out.close(); } } If I set metadata-complete="false" (or don't set it) at the web.xml file, I got this error when trying to start Tomcat: 'Publishing to Tomcat v8.0 at Locahost...' has encountered a problem. Publishing the configuration... I I set it to true, it runs. However, it is printed: value of parameter 1: null value of parameter 2: null Because the annotation was ignored (that's what happens when you set metada-complete to true). help! A: You should check all again (web.xml especially). With empty metadata-complete, I run your code: package br.com.caelum.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.annotation.WebServlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet( name = "OiServlet3", urlPatterns = {"/oi"}, initParams = { @WebInitParam(name = "param1", value = "value1"), @WebInitParam(name = "param2", value = "value2")} ) public class OiMundo extends HttpServlet { protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); // escreve o texto out.println("<html>"); out.println("<head>"); out.println("<title>Primeira Servlet</title>"); out.println("</head>"); out.println("<body>"); ServletConfig config = getServletConfig(); String parameter1 = config.getInitParameter("param1"); out.println("Value of parameter 1: " + parameter1); String parameter2 = config.getInitParameter("param2"); out.println("<br>Value of parameter 2: " + parameter2); out.println("<h1>Hi Servlet!</h1>"); out.println("</body>"); out.println("</html>"); out.close(); } } no problem, it works:
{ "pile_set_name": "StackExchange" }
Q: Default filter from scorecard to another scorecard I am using SharePoint Server 2013 and PerformancePoint Dashboard Designer 2013. I have two scorecards, primary and secondary as shown in the following figure. Fig: Primary and secondary scorecards. The primary scorecard at left has Date dimension in the rows. The secondary scorecard at right has City dimension in the rows. Both of them have common measures, viz. Previous Snapshot and Current Snapshot which are calculated members from SSAS cube. I have connected the Date dimension from the primary scorecard to the Page level of secondary scorecard. When I click any date from the primary scorecard, the data in secondary scorecard changes accordingly as expected. Now I want to have a default connection from primary scorecard to secondary scorecard. When the dashboard page loads for the first time, I want the first row of the Date dimension i.e. 24 March 2014 to be selected by default and this member to be send to the filter. Is it possible? If yes, please let me know. A: The scorecard does not have any Out of the Box feature to provide default filter values as a PerformancePoint filter does. However I was able to exploit the beauty of Named Sets to craft a solution of my own to achieve this behavior. The primary scorecard has Date dimension members on the rows. Currently, the non-empty values are 10 March 2014, 17 March 2014 and 24 March 2014. I have used a Named Set to display non-empty dates in descending order. I have this Named Set (Date dimension) from primary KPI connected to the Page of secondary scorecard. So when we load the page, non of the KPI is selected in the primary scorecard and the secondary scorecard displays the values for whole data without any filtering. My objective was to have the secondary scorecard displayed as if KPI on 24 March 2014 was selected. Create a new Named Set for secondary scorecard that will select only the desired date. In my scenario, it is the latest non-empty date. Drag and drop this new Named Set into secondary scorecard. Modify the existing connection between two scorecards as shown below. Replace Member Unique Name -> Page connection with something like Member Unique Name -> /Set Formulas ([New Named Set]) Deploy the dashboard. Now I have the default value selected in secondary scorecard because of the new Named Set in secondary scorecard. And the KPI selection in primary scorecard changes the data in secondary scorecard accordingly. :) Cheers :)
{ "pile_set_name": "StackExchange" }
Q: How to fetch a property only if it's not null in Hibernate In Hibernate query how do i check if a property is null? Depending on the result i want to fetch that property and if it is not null i have to fetch another property. A: Following two ways are valid HQL queries and both are also valid JPA 2.0 JPQL queries. Using coalesce (returns first non-null, or null if both are null): SELECT coalesce(e.property, e.otherProperty) FROM SomeEntity e Equivalent select-case, which is bit longer: SELECT CASE WHEN e.property IS NULL THEN e.otherProperty ELSE e.property END FROM SomeEntity e
{ "pile_set_name": "StackExchange" }
Q: affect only only certain elements of class so I have a class and in that class I have a table and a text object(<p>). I only want to style the table and not the text object but i do not want to style all tables like this. is this possible and if so, how do I do this? <html> <head> <title>Insert title</title> <link rel="stylesheet" type="text/css" href="styles.css"> </head> <body> <div id=COA> <img src="IMG/mainImgsmall.jpg" alt="Coat of Arms"> </div> <div id=navBar> <table> <tr> <td><a href="index.html">Home</a></td> <td><a href="away.html">Away</a></td> <td><a href="test0.html">test0</a></td> <td><a href="test1.html">test1</a></td> </tr> </table> <p>hfef</p> </div> <p>this is home</p> </body> </html> A: Use a selector like #navBar table { ... }
{ "pile_set_name": "StackExchange" }
Q: SQL Server Query with count returns null or no result I have the following query: SELECT Centre.Centre_Name, Count(Shop_No) AS shopcount FROM Centre INNER JOIN Space ON Centre.Centre_Name = Space.Centre_Name GROUP BY Centre.Centre_Name I need it to return the list of centres from the centre table and the amount of shops per centre from the Space table. So it counts the number of shop_no in the Space table and returns the centre name plus number of shops per centre. However, if a centre doesn't have any shops yet assigned to it in the Space table, then it doesn't return the centre name from the Centre table. I need it to return 0 if the centre doesn't exist in the Space table. Please advise :) A: Use a LEFT JOIN instead of an INNER JOIN: SELECT Centre.Centre_Name, Count(Shop_No) AS shopcount FROM Centre LEFT JOIN Space ON Centre.Centre_Name = Space.Centre_Name GROUP BY Centre.Centre_Name
{ "pile_set_name": "StackExchange" }
Q: How to limited EditText for start characters just english alphabet in Android In my application I want use EditText and I want start characters just English alphabet. My mean is, First of characters has just English alphabet (a to z). I write below codes : registerUsernameEdtTxt.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { if (charSequence.toString().length() < 2) { registerUsernameEdtTxt.setFilters(new InputFilter[]{new InputFilter() { public CharSequence filter(CharSequence src, int start, int end, Spanned dst, int dstart, int dend) { if (src.toString().matches("[a-zA-Z ]+")) { registerUsernameInptLay.setErrorEnabled(false); return src; } registerUsernameInptLay.setError(context.getResources().getString(R.string.insertJustEnglish)); return ""; } }}); } } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { } }); But not work me! How can I it? Please help me A: Try this: EditText et = findViewById(R.id.text_field); // This part is to keep the existing filters of the EditText. InputFilter[] filters = et.getFilters(); InputFilter[] newFilters = Arrays.copyOf(filters, filters.length + 1); InputFilter firstFilter = new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { if (source != null && source.length() > 0 && dstart == 0){ if (!source.toString().matches("^[A-Za-z].*")) return ""; } return null; } }; // Add the filter to the array of filters newFilters[newFilters.length - 1] = firstFilter; et.setFilters(newFilters); Can be simplified like this (if the previous InputFilter are not required) EditText et = findViewById(R.id.text_field); InputFilter firstFilter = new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { if (source != null && source.length() > 0 && dstart == 0){ if (!source.toString().matches("^[A-Za-z].*")) return ""; } return null; } }; et.setFilters(new InputFilter[]{firstFilter}); EDIT If you want to keep the rest of the string (for example if the user pastes the text): @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { if (source != null && source.length() > 0 && dstart == 0) { String s = source.toString(); if (!s.matches("^[A-Za-z].*")) { Toast.makeText(getApplicationContext(), "This is a Toast", Toast.LENGTH_SHORT).show(); return s.substring(1, s.length()); } } return null; } EDIT 2 The above versions don't work on deletion or when a text is pasted with more than a forbidden char at the beginning (e.g. '88sdfs') as only the first one was removed and the rest kept. This new version should cover all these cases. I'd suggest to create a separated class for the InputFilter. InputFilter firstFilter = new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { if (dstart != 0) { // The modified part is not beginning of the text return null; // Nothing need to be changed } if (source.length() > 0) { // text is added return onTextAdded(source.toString()); } else { // text is removed return onTextRemoved(dest, dend); } } private CharSequence onTextRemoved(Spanned dest, int dend) { // check what the string will look like after the text being removed String substring = dest.toString().substring(dend, dest.length()); // if there is still a string and it's not valid if (substring.length() > 0 && !isValid(substring)) { displayError(); // return the deleted part for the string to not change return dest.subSequence(0, dend); } return null; } private String onTextAdded(String s) { if (isValid(s)) { return null; } else { String substring; // We want to keep a part of the added string (it can be a paste). // so we remove all the first characters as long as the string doesn't match // the requirements for (int i = 1; i < s.length(); i++) { substring = s.substring(i, s.length()); if (isValid(substring)) break; } displayError(); return substring; } } private boolean isValid(String s) { return s.matches("^[A-Za-z].*"); } private void displayError() { Toast.makeText(getApplicationContext(), "This is a Toast", Toast.LENGTH_SHORT).show(); } }; et.setFilters(new InputFilter[]{firstFilter});
{ "pile_set_name": "StackExchange" }
Q: phpspec - running same test with multiple values Using phpspec, is it possible to run the same test with multiple values, using annotations or similar? For example, say i have the following test: public function it_should_return_sum_of_numbers_passed() { $number1 = 1; $number2 = 1; $expectedresult = $number1 + $number2; $this->add($number1, $number2)->shouldReturn($expectedResult); } Thats fine. But it only tests a single set of parameters. What about passing -1 and 1, -1 and -2 etc etc. Fair enough this is a massively simplified scenario but it would mean having to create a new method for each edge case. A: There's no data providers in phpspec (at least not yet). You have to do something like: public function it_should_return_sum_of_numbers_passed() { $examples = array( array(1, 2, 3), array(-1, 1, 0), array(-1, -2, -3) ); foreach ($examples as $example) { $number1 = $example[0]; $number2 = $example[1]; $expectedResult = $example[2]; $this->add($number1, $number2)->shouldReturn($expectedResult); } }
{ "pile_set_name": "StackExchange" }
Q: Using jQuery selectors to find all ids that end a certain way I am adding a row using the clone() function and then am having to rename all of the divs in the newly cloned row. I was trying to do that this way: // Add button for new TOEFL entry $("#add-TOEFL").button().click(function( event ){ event.preventDefault(); var tag = 'TOEFL', testDate = $("#TOEFLtestDate-0").val(), reading = $("#readingTOEFLScore-0").val(), listening = $("#listeningTOEFLScore-0").val(), speaking = $("#speakingTOEFLScore-0").val(), writing = $("#writingTOEFLScore-0").val(), applicantId = $("#applicantId").val(), dataString = 'applicantId=' + applicantId + '&dateTaken=' + testDate + '&listeningScore=' + listening + '&readingScore=' + reading + '&speakingScore=' + speaking + '&writingScore=' + writing; // Insert New Record $.ajax({ type: "POST", url: "ajax/insertEntry.cfm?xAction=TOEFL", data: dataString, success: function(newIdx){ // Make sure returned value is a number newId = jQuery.trim(newIdx) * 1; // clone new row newDivId = tag + '-Entry-' + newId; newRow = $('#' + tag + '-Entry-0').clone().attr('id', newDivId); console.log('New row cloned. DivId: ' + newDivId); // get all ids $("#" + newDivId).find("[@id$='-0']").each(function(){ selectedDivId = $(this).attr("id"); alert(selectedDivId); }) } }) Here is the HTML markup: <div id="TOEFL-Entry-0" style="display: none" > <p style="margin:5px 0 0 0"> Taken <input name="TOEFLtestDate-0" type="text" id="TOEFLtestDate-0" class="inputDateField" style="margin-left:5px; margin-right:15px;"/> Reading <input name="readingTOEFLScore-0" type="text" id="readingTOEFLScore-0" class="inputTinyScoreField" style="margin:0 8px 0 5px"/> Listening <input name="listeningTOEFLScore-0" type="text" id="listeningTOEFLScore-0" class="inputTinyScoreField" style="margin:0 8px 0 5px"/> Speaking <input name="speakingTOEFLScore-0" type="text" id="speakingTOEFLScore-0" class="inputTinyScoreField" style="margin:0 8px 0 5px"/> Writing <input name="writingTOEFLScore-0" type="text" id="writingTOEFLScore-0" class="inputTinyScoreField" style="margin:0 8px 0 5px"/> <button id="add-TOEFL-0">Add</button> </p> </form> </div> Even thought there should be a bunch of ids that match this criteria, I am not seeing the alert. What am I doing wrong? Josh A: Thanks for all the help. The problem was actually that the cloned row was not shown yet and needed to be referenced as 'newRow' instead of as $("#" + newDivId). Once I changed that, it works like a champ. Not quite sure why that is the case, but that makes it worse.
{ "pile_set_name": "StackExchange" }
Q: Polymorphic wrapper around matrix/linear algebra libraries - C++, starting with Eigen I am writing a custom C++ numerical library that relies heavily on linear algebra routines. I am also using Eigen to cater for the actual matrix operations. I want to decouple my library from the Eigen implementation so that it is unaware of Eigen. This will allow me to keep Eigen references in one place and make it easy to change the linear algebra library to another implementation in the near future. In java, this would be relatively simple. However I am running into difficulties with Eigen as it uses templates. In particular I am using the types MatrixXd and VectorXd. Does anyone have any suggestions about constructing a wrapper around these classes that will provide a solid boundary between Eigen and my library? My first attempt was implemented using composition so that calls to MyBaseMatrix were directed to calls in the contained type (e.g. MatrixXd) as suggested here: https://forum.kde.org/viewtopic.php?f=74&t=87072&p=154014&hilit=wrap+eigen#p154014. However I am sceptical that I will retain Eigen under-the-hood optimisations? Two other solutions are suggested here: http://eigen.tuxfamily.org/dox-devel/TopicCustomizingEigen.html#ExtendingMatrixBase, (extending MatrixBase or inheriting Matrix). However they don't seem to allow me the strict boundary between Eigen types and my numerical library. Also extending MatrixBase doesn't seem to allow operator overloading? I considered inheriting Matrix and MyBaseMatrix (multiple inheritance), but the templating has caused me headaches when trying to retain a clean boundary. Does anyone have any experience with this particular problem, or solutions to similar problems in C++? A: I would not recommend doing this from a code design standpoint, as a linear algebra library is not something you are likely to replace. So encapsulating it will most likely not be beneficial and will make your code more complicated. However if you really want to do this, you would use template specialization. Something along the lines of the following: template< typename InternalMatrixType> class Matrix { private: InternalMatrixType _matrix; public: // Example function float operator[](unsigned index) { return _matrix[index]; } }; For a particular linear algebra library: template<> class Matrix<EigenMatrixType> { private: EigenMatrixType _matrix; public: // Example function float operator[](unsigned index) { return _matrix.get(index); } }; Edit: Added information on typedefs to clarify usage. Based on below comment from moodle. Throughout the library you could then typedef the template class. This will allow you to use something like cMatrix vs Matrix<InternalMatrixType>. typedef Matrix<InternalMatrixType> cMatrix;
{ "pile_set_name": "StackExchange" }