qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
sequence
response
stringlengths
0
115k
9,943,119
*Context: I was discussing C# vs. Java at work when the following question came up, and I wondered how (or if) it could be elegantly resolved in C++.* Let's say you have two classes `A` and `B` (whose details are not important) and then two templated class `G` and `H` described as something like: ``` template <typename T> | template <typename T> class G | class H { | { public : | public : T * foo() ; | virtual T * foo() = 0 ; // etc. | // etc. } ; | } ; ``` Then we have the class `C` and `D` described like: ``` class A { /* ... */ } ; class B { /* ... */ } ; class C : public G<A>, public G<B> { } ; class D : public H<A>, public H<B> { // ??? } ; ``` I want to be able to call for `C` the method `foo` from `G<A>` and foo from `G<B>`. And I want to be able to override for `D` the method `foo` from `H<A>` and `H<B>`. In the end, I want to be able to use C and D like in the following examples: ``` C c ; A * a = c.??? ; (I want to call G<A>::foo()) B * b = c.??? ; (I want to call G<B>::foo()) D d ; A * a = c.??? ; (I want to call H<A>::foo()) B * b = c.??? ; (I want to call H<B>::foo()) ``` There always are ways to do it (and I have some ideas), but I'm interested a list of elegant and safe ways to do it, including pros/cons. So, **how would you do it?**
2012/03/30
[ "https://Stackoverflow.com/questions/9943119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14089/" ]
The two ways I can think of: ``` C x; x.G<A>::foo(); // 1 static_cast<G<A>&>(x).foo(); // 2 ``` That is: either explicitly qualifying the function’s name, or upcast in the type hierarchy.
26,538,636
I'd like to write a regular expression for following type of strings in Pyhton: > > 1 100 > > > 1 567 865 > > > 1 474 388 346 > > > i.e. numbers separated from thousand. Here's my regexp: > > r"(\d{1,3}(?:\s\*\d{3})\*) > > > and it works fine. However, I also wanna parse > > 1 100,34848 > > > 1 100 300,8 > > > 19 328 383 334,23499 > > > i.e. separated numbers with decimal digits. I wrote > > rr=r"(\d{1,3}(?:\s\*\d{3})\*)(,\d+)?\s > > > It doesn't work. For instance, if I make > > sentence = "jsjs 2 222,11 dhd" > > > re.findall(rr, sentence) > > > [('2 222', ',11')] > > > Any help appreciated, thanks.
2014/10/23
[ "https://Stackoverflow.com/questions/26538636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4175888/" ]
How about ``` SELECT COUNT(*) FROM (SELECT DISTINCT * FROM Table) ```
69,268,010
good day. There is a code for generating passwords. ```vb Dim i_keys As Integer Dim numKeys As Integer = 8 Dim chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*" Dim stringChars = New Char(7) {} Dim random = New Random() For i As Integer = 0 To stringChars.Length - 1 stringChars(i) = chars.Chars(random.Next(chars.Length)) Next i Dim finalString = New String(stringChars) For i_keys = 1 To numKeys ListBox1.Items.Add(finalString) Next ``` But as a result, I get the following: ``` 0EbrQ4Pf 0EbrQ4Pf 0EbrQ4Pf 0EbrQ4Pf 0EbrQ4Pf 0EbrQ4Pf 0EbrQ4Pf 0EbrQ4Pf ``` Tell me how you can make it so that you get 10 random (not repeated) passwords at the output.
2021/09/21
[ "https://Stackoverflow.com/questions/69268010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15895460/" ]
You need the last loop to encompass a bit more code. ``` Dim i_keys As Integer Dim numKeys As Integer = 8 Dim chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*" Dim random = New Random() For i_keys = 1 To numKeys Dim stringChars = New Char(7) {} For i As Integer = 0 To stringChars.Length - 1 stringChars(i) = chars.Chars(random.Next(chars.Length)) Next i Dim finalString = New String(stringChars) ListBox1.Items.Add(finalString) Next ```
68,082,864
I'm currently building a "formula editor" in a GUI application in python. I use sympy to parse and check the validity of the typed formula, based on a dictionary of `subs`. No problem with that. Sometimes, user will need to type "complex" formulae with redundant parameters. See this example below: ``` Array([0.9, 0.8, 1.0, 1.1])[Mod(p-1, 4)] ``` The list `[0.9, 0.8, 1.0, 1.1]` is chosen by the user and can be of any length. Given the value of `p` variable, il will result in one of the four elements of the list. The number `4` is obviously `len([0.9, 0.8, 1.0, 1.1]`. The user can easily mistype the formula... Rather, I would like to create my own function, eg. `userlist()`, taking the list as argument and behaving as needed. I have read [this](https://stackoverflow.com/questions/49306092/parsing-a-symbolic-expression-that-includes-user-defined-functions-in-sympy) which helped me start with functions taking numbers as argument. It did not help me much with arguments which are lists. Thank you in advance. --- **EDIT:** In a nutshell, I need to define `userlist()` in some way so that this line ``` parse_expr("userlist(p, [8, 4, 6, 7])").evalf(subs={'p': 10}) ``` returns the `Mod(p-1, len(list))`th element of the list (here the 2nd element: `4`).
2021/06/22
[ "https://Stackoverflow.com/questions/68082864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16283580/" ]
After adding the base case, as recommended by @DavidTonhofer, you can change the order of the first two arguments of the predicate to avoid **spurious choice points** (since Prolog apply first argument indexing to quickly narrow down applicable clauses): ``` addZ([], _, []). addZ([X|Xs], Z, [Y|Ys]):- Y is X + Z, addZ(Xs, Z, Ys). ``` Example: ``` ?- addZ([1,2,3], 1, Z). Z = [2, 3, 4]. ?- ```
25,909,917
I'm researching about SDN and NFV. In the concept of NFV on Wikipedia , it says : "Network Functions Virtualization (NFV) is a network architecture concept that proposes using IT virtualization related technologies, to virtualize entire classes of network node functions into building blocks that may be connected, or chained, together to create communication services."==> first thing to consider that it will reduce the cost of facilities. So in real life implementation, for example, how can we virtualize a network nodes like a router? NFV was created for the networks to be capable to extend in a dynamically way(virtualize the router) , not a static way(buy a new router), that is we must implement the router functions in the server or a computer instead of buying and then adapting the new router to the current nextwork , in this case I don't see any different in this implementation , because buying a server to implement a virtualized router is not cheaper than buying a new router. Can anyone explain this for me , or Am i wrong understanding the NFV concept? Thanks.
2014/09/18
[ "https://Stackoverflow.com/questions/25909917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2760331/" ]
For some time I was thinking that this is my problem as well, but for normal apps (**non-iOS-8-extension**) you just need to change one build setting in your casual Xcode 6 iOS Universal Framework target (**set Mach-O Type to Static Library**): ![Set it to Static Library](https://i.stack.imgur.com/itgBr.png) There should be no problem with iTunes Connect and iOS 7 after that :)
41,107,555
My app is using `spring-data-rest` and `spring-restdocs`. My setup is really standard; copied from the docs almost entirely, but I've included the samples below in case I'm missing something. When my mvc test runs, it fails with: ``` org.springframework.restdocs.snippet.SnippetException: The following parts of the payload were not documented: { "_links" : { "self" : { "href" : "https://my-api/item/10" }, "item" : { "href" : "https://my-api/item/10" } } } ``` This is my test code: ``` @Rule public JUnitRestDocumentation restDocs = new JUnitRestDocumentation("target/generated-snippets"); // ... mockMvc = webAppContextSetup(wac) //WebApplicationContext .apply(documentationConfiguration(restDocs) .uris() .withHost("my-api") .withPort(443) .withScheme("https")) .build(); // .... mockMvc.perform(get("/items/{id}", "10")) .andDo(documentation) ``` Here's the stack: ``` at org.springframework.restdocs.payload.AbstractFieldsSnippet.validateFieldDocumentation(AbstractFieldsSnippet.java:176) at org.springframework.restdocs.payload.AbstractFieldsSnippet.createModel(AbstractFieldsSnippet.java:100) at org.springframework.restdocs.snippet.TemplatedSnippet.document(TemplatedSnippet.java:64) at org.springframework.restdocs.generate.RestDocumentationGenerator.handle(RestDocumentationGenerator.java:196) at org.springframework.restdocs.mockmvc.RestDocumentationResultHandler.handle(RestDocumentationResultHandler.java:55) at org.springframework.test.web.servlet.MockMvc$1.andDo(MockMvc.java:177) at com.example.my.api.domain.MyRepositoryRestTest.findOne(MyRepositoryRestTest.java:36) ``` How do I get `spring-restdocs` and `spring-data-rest` to play nice? --- **EDIT(S):** My `documentation` instance is defined as follows: ``` ResultHandler documentation = document("items/findOne", preprocessRequest(prettyPrint(), maskLinks()), preprocessResponse(prettyPrint()), responseFields( fieldWithPath("name").description("Item name.") // Bunch more )); ``` As @meistermeier indicated, (and following [the restdocs docs for ignoring links](http://docs.spring.io/spring-restdocs/docs/current/reference/html5/#documenting-your-api-hypermedia-ignoring-common-links), I can add ``` links(linkWithRel("self").ignored(), linkWithRel("_self").ignored().optional()) // docs suggest this. /shrug ``` But that still leaves me with: ``` SnippetException: Links with the following relations were not documented: [item] ``` Seems like the `_links` are always going to have that self-reference back to the same entity, right? How do I cleanly handle this without ignoring an entity-specific link for every test, like: ``` links(linkWithRel("item").ignored()) ``` Even if I **do** add the above line (so that all fields `self` `_self` `curies` and `item` are all `ignored()` and/or `optional()`), the result of the test returns to the original error at the top of this question.
2016/12/12
[ "https://Stackoverflow.com/questions/41107555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1281468/" ]
> > Seems like the \_links are always going to have that self-reference back to the same entity, right? > > > Yes, that's right. I may have your solution for ignoring some links in [a small github sample](https://github.com/meistermeier/spring-rest-docs-sample/blob/master/src/test/java/com/meistermeier/BeerRepositoryTest.java#L106). Especially the part: ``` mockMvc.perform(RestDocumentationRequestBuilders.get(beerLocation)).andExpect(status().isOk()) .andDo(document("beer-get", links( linkWithRel("self").ignored(), linkWithRel("beerapi:beer").description("The <<beers, Beer resource>> itself"), linkWithRel("curies").ignored() ), responseFields( fieldWithPath("name").description("The name of the tasty fresh liquid"), fieldWithPath("_links").description("<<beer-links,Links>> to other resources") ) )); ``` where I completely ignore all *"generated"* fields and only create a documentation entry for the domain. Your `item` link would be my `beerapi:beer`. I really don't know what is best practice here, but I would always document as much as possible since you can use asciidoctor links (like `<<beer-links,Links>>`) wherever possible to reference other parts with more documentation.
45,070,283
I want to make ActionBarDrawerToggle(Hamburger) Icon bigger. I have try changing the width of bar, but it can't change. And what should I do?
2017/07/13
[ "https://Stackoverflow.com/questions/45070283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8299049/" ]
Try this: ``` for (int i = 0; i < mToolbar.getChildCount(); i++) { if(mToolbar.getChildAt(i) instanceof ImageButton){ mToolbar.getChildAt(i).setScaleX(1.5f); mToolbar.getChildAt(i).setScaleY(1.5f); } } ```
89,968
I am still not sure what should be considered as "literature" for inclusion in a literature review and what are not when writing a research proposal. For instance: > > A research proposal: 500-1000 words outlining your plans for your PhD > Please include a 'literature review’ of works you’ve consulted and > where your ‘contribution to new knowledge’ may > potentially be made. > > > Can books be considered as "literature" for inclusion in literature reviews? For instance: * Michio Kaku. (2011) Physics of the Future: The Inventions That Will -Transform Our Lives. Reprint, Penguin, 2012. * Carl Sagan. (1995) The Demon-Haunted World: Science as a Candle in the Dark. Reprint, New York: Ballantine Books, 2000. I googled and found [this](https://laverne.libguides.com/c.php?g=34942&p=222059) and it says: > > "The Literature" refers to the collection of scholarly writings on a > topic. This includes peer-reviewed articles, books, dissertations and > conference papers. > > > It mentions books but does *The Literature* above mean *literature review*? Also, what about online sources/ articles? Are they "literature" for literature reviews? For example: * <https://www.brainpickings.org/2014/01/03/baloney-detection-kit-carl-sagan/> * <https://www.theguardian.com/culture/2009/jul/05/can-artists-save-the-world> * <http://www.theoryculturesociety.org/elinor-carmi-cookies-meets-eye/>
2017/05/25
[ "https://academia.stackexchange.com/questions/89968", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/73965/" ]
Note carefully the word *scholarly* in that description. It refers to works whose intended audience is experts in the field, and which either present novel research or interpret existing results in a novel way. Books can fit that description; often they will have been published by an academic publisher and reviewed for academic merit by expert editors or referees, prior to publication. Scholarly books are sometimes called *monographs*, especially in the sciences. The books you mentioned by Kaku and Sagan are not *scholarly* books. They are intended for a non-expert popular audience, and they don't present new research or expand the state of the art. The same goes for the online sources you listed; they are newspaper articles or blog posts intended for a popular audience. A literature review is how you show that you are familiar with the state of the art. It convinces the reader that they should believe you when you say that your proposed project is feasible, novel, and interesting. You want to show that you are an expert, or are on your way to becoming one. Citing a popular book won't achieve that; it puts you at the same level as any random person interested in science who can read a bestseller list.
40,478,159
I'm trying to create a new `Business Notebook` over PHP but I'm having no luck. I've tried following [this documentation](https://dev.evernote.com/doc/articles/business.php) and adapting the code to what is available to me using the [Thrift module: NoteStore](https://dev.evernote.com/doc/reference/NoteStore.html#Fn_NoteStore_createNotebook). From my understanding of how the flow is meant to be, it's; create a new notebook, using the returned notebook get its shareKey, shareID, and businessId, use that information to create a linked notebook in the business note store. I first tried to creating a new notebook using the non business note store, however the new notebook returned did not contain a shareKey, or any other information needed for creating a linked notebook. Instead I found creating a new notebook using the business note store returned a new notebook with some of this the required information under the 'sharedNotebooks' feild however the businessNotebook parameter was null, and there was no shareId within sharedNotebooks. And even though this new notebook is returned successfull, it is not visable in my personal or business accounts. The returned notebook looks like ``` { "guid": "d341cd12-9f98-XXX-XXX-XXX", "name": "Hello World", "updateSequenceNum": 35838, "defaultNotebook": false, "serviceCreated": 1478570056000, "serviceUpdated": 1478570056000, "publishing": null, "published": null, "stack": null, "sharedNotebookIds": [603053], "sharedNotebooks": [{ "id": 603053, "userId": 40561553, "notebookGuid": "d341cd12-9f98-XXX-XXX-XXX", "email": "jack@businessEvernoteAccountEmail", "notebookModifiable": true, "requireLogin": null, "serviceCreated": 1478570056000, "serviceUpdated": 1478570056000, "shareKey": "933ad-xxx", "username": "xxx", "privilege": 5, "allowPreview": null, "recipientSettings": { "reminderNotifyEmail": null, "reminderNotifyInApp": null } }], "businessNotebook": null, "contact": { "id": 111858676, "username": "XXX", "email": "jack@personalEvernoteAccountEmail", "name": "Jack XXXX", "timezone": null, "privilege": null, "created": null, "updated": null, "deleted": null, "active": true, "shardId": null, "attributes": null, "accounting": null, "premiumInfo": null, "businessUserInfo": null }, "restrictions": { "noReadNotes": null, "noCreateNotes": null, "noUpdateNotes": null, "noExpungeNotes": true, "noShareNotes": null, "noEmailNotes": true, "noSendMessageToRecipients": null, "noUpdateNotebook": null, "noExpungeNotebook": true, "noSetDefaultNotebook": true, "noSetNotebookStack": true, "noPublishToPublic": true, "noPublishToBusinessLibrary": null, "noCreateTags": null, "noUpdateTags": true, "noExpungeTags": true, "noSetParentTag": true, "noCreateSharedNotebooks": null, "updateWhichSharedNotebookRestrictions": null, "expungeWhichSharedNotebookRestrictions": null } } ``` Thus far, my code flow is as follows //Try catches left out for sortness ``` //Check if business user $ourUser = $this->userStore->getUser($authToken); if(!isset($ourUser->accounting->businessId)){ $returnObject->status = 400; $returnObject->message = 'Not a buisness user'; return $returnObject; } // authenticateToBusiness and get business token $bAuthResult = $this->userStore->authenticateToBusiness($authToken); $bAuthToken = $bAuthResult->authenticationToken; //Create client and set up business note store $client = new \Evernote\AdvancedClient($authToken, false); $bNoteStore = $client->getBusinessNoteStore(); //Create a new notebook in business note store- example result is json above $newNotebook = new Notebook(); $newNotebook->name = $title; $newNotebook = $bNoteStore->createNotebook($bAuthToken, $newNotebook); //Look at new notebook and get information needed to create linked notebook $sharedNotebooks = $newNotebook->sharedNotebooks[0]; $newLinkedNotebook = new LinkedNotebook(); $newLinkedNotebook->shareName = $title; $newLinkedNotebook->shareKey = $sharedNotebooks->shareKey; $newLinkedNotebook->username = $sharedNotebooks->username; //$newLinkedNotebook->shardId = $sharedNotebooks->shardId; //isnt there //This is where I think the trouble is happening ??? $newLinkedNotebook = $bNoteStore->createLinkedNotebook($bAuthToken, $newLinkedNotebook); //Trying with business token throws //{"errorCode":3,"parameter":"authenticationToken"} //Even though within Evernote itself, I can add notebooks to this business //Alternatively trying with the regular $authToken i receive //{"errorCode":12,"message":"s570","rateLimitDuration":null} // error code 12 being SHARD_UNAVAILABLE //and trying on the regular noteStore $newLinkedNotebook = $noteStore->createLinkedNotebook($authToken, $newLinkedNotebook); //returns {"errorCode":5,"parameter":"LinkedNotebook.shardId"} ```
2016/11/08
[ "https://Stackoverflow.com/questions/40478159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5531521/" ]
You just need to start from limit and ends when it reaches 11 ``` for(int x = limit; x > 10; x--){ if(x! = 44 && x != 22){ System.out.print(x + " "); } } ```
37,374,652
The title says it all! but to be more clear, please check this screenshot. This is a 360 video playback using the Google VR <https://developers.google.com/vr/ios/> but I want to know if it is possible to remove this little (info) button? and instead overlay our own set of video controlers? [![enter image description here](https://i.stack.imgur.com/peX8C.jpg)](https://i.stack.imgur.com/peX8C.jpg)
2016/05/22
[ "https://Stackoverflow.com/questions/37374652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247658/" ]
Google allow you to create a custom GVRView which doesn't have the (i) icon - but it involves creating your own OpenGL code for viewing the video. A hack working on v0.9.0 is to find an instance of QTMButton: ```js let videoView = GVRVideoView(frame: self.view.bounds) for subview in self.videoView.subviews { let className = String(subview.dynamicType) if className == "QTMButton" { subview.hidden = true } } ``` It is a hack though so it might have unintended consequences and might not work in past or future versions.
37,929,067
In every tutorial I've seen dealing with keeping track of submitted user data, table views / collection views are used in conjunction with arrays + indexPath.row to keep track of which post is which. I'm working on an app where multiple users are able to make posts, but instead of a tableview, I'm wanting the posts to be contained in buttons that can be moved around on the screen freely. I'm having a hard time wrapping my head around how to keep track of which post is which when it's outside of a structured tableview where the indexes match up. I'm using firebase as a backend, and so ideally when a user clicks on a post button it'd load up the corresponding post..which would normally be done by grabbing the indexpath.row out of a saved array from firebase. I've got a working app using tableviews so I'm definitely not asking on how to retrieve data from firebase or anything, but moreso how to transition to the button concept. So basically, how do you keep track of posts or "things" on a screen when they're not in a list-format? This sort of thing is done all of the time in games seemingly?.. but I'm not sure how to apply that same kind of logic into a non-game app.
2016/06/20
[ "https://Stackoverflow.com/questions/37929067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4988582/" ]
* You should use -Dsonar.gitlab... instead of -Psonar.gitlab... etc. (see <https://groups.google.com/forum/#!topic/sonarqube/dx8UIkcz55c> ) * In the newest version of the plugin you can enable to add a comment when no issue is found. This helps with debugging. @1: The comments will be added to your commits and will then show up in the discussion section of a merge request @2: We are running a full analysis on master and a preview on any branches.
61,684,418
I have a query that selects specific items as a keyword as shown below. ``` SELECT system_title as Request, Description.Words as Changes, Projects.ProjectNodeName as ProjectName, COALESCE(Engineer.Name + ' <' + UPPER(Engineer.Domain + '\' + Engineer.Alias) + '>', 'N/A') as Engineer ``` I want to use `ORDER BY Request` to order each selected item basted off of `Request` Where would I put the `ORDER BY Request` in here to make the syntax work and do what I want?
2020/05/08
[ "https://Stackoverflow.com/questions/61684418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13090977/" ]
You need the license so that they can keep an eye on you if you are making more than 1 million USD. however you don't need to download the installer, just import `registerLicense` like so and then put your API key within the `registerLicense('api key')` and you're good to use the component without any popup on the application. ``` import { registerLicense } from '@syncfusion/ej2-base' registerLicense('api key'); ``` You can grab the API key from your syncfusion dashboard "Downloads and keys" -> "Get License key".
6,562,988
I need something that can be run both on JVM and .NET. What is the best option to achieve that?
2011/07/03
[ "https://Stackoverflow.com/questions/6562988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/826887/" ]
Python, perhaps? Jython for Java, and IronPython for .NET Another option is Scala, however I have yet to actually play with that...
42,703,329
I am stucked at ex 18,chapter lists and function from CODECADEMY. "Create a function called flatten that takes a single list and concatenates all the sublists that are part of it into a single list." "1 On line 3, define a function called flatten with one argument called lists. 2 Make a new, empty list called results. 3 Iterate through lists. Call the looping variable numbers. 4 Iterate through numbers. 5 For each number, .append() it to results. 6 Finally, return results from your function." Here is my code: And the error: **Oops, try again. flatten([[1, 2], [3, 4]]) returned [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4] instead of [1, 2, 3, 4]** ``` n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]] # Add your function here results=[] def flatten(lists): for numbers in lists: for number in numbers: results.append(number) return results print flatten(n) ``` I can't figure out what is wrong.
2017/03/09
[ "https://Stackoverflow.com/questions/42703329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7546554/" ]
I have tried to reproduce your issues using a bare-bone recreation of the class hierarchy that you are describing an I don't get a compilation error. So I'm assuming that there is something else in your case that were are missing. I include my code here so that you can confirm that we are on the same page: ``` abstract class A<T> { public abstract R<T> getR(); } final class B extends A<X> { public R<X> getR() { return new E(); } } class D<T> extends R<T> {}; class E extends D<X> {}; class R<T> {} class X {}; ``` No compilation error using javac 1.8.x
15,559,218
I have a chrome extension that pulls down the RSS feed of Hacker News, which uses HTTPS. Ever since I upgraded to the newest version of the chrome extension manifest, I can't get it to work. The ajax request fails without any explanation. I'm 99% sure that my javascript code that makes the request is correct, so I think it's a permissions issue. Here is the permissions and content security policy section from my manifest: ``` "permissions": [ "tabs", "https://news.ycombinator.com/", "http://news.ycombinator.com/", "notifications" ], "content_security_policy": "script-src 'self' 'unsafe-eval' https://news.ycombinator.com; object-src 'self' 'unsafe-eval' https://news.ycombinator.com" ``` Any ideas? Thanks! --- Edit: Here's a link to the Github Repo: <https://github.com/adamalbrecht/hacker-news-for-chrome/>
2013/03/21
[ "https://Stackoverflow.com/questions/15559218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/138265/" ]
I think you should do `"permissions": [ "tabs", "https://news.ycombinator.com/*", "http://news.ycombinator.com/*", "notifications" ],` because Chrome wants a pattern of permitted hosts. See [this](http://developer.chrome.com/extensions/match_patterns.html).
50,133,887
Example HTML ``` <a class="accordion-item__link" href="/identity-checking/individual"><!-- react-text: 178 -->Australia<!-- /react-text --></a> ``` When I run ``` soup.find("a", text="Australia") ``` it returns nothing. If I run `soup.find("a", href="/identity-checking/individual")` it finds the tag. `soup.find("a", href="/identity-checking/individual").text` also returns 'Australia' is it something to do with the comments?
2018/05/02
[ "https://Stackoverflow.com/questions/50133887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9730072/" ]
For some reason, detecting the tag text gets flipped when there is an `xml` comment. You can use this as a workaround: ``` [ele for ele in soup('a') if ele.text == 'Australia'] ```
10,871,651
My current PHP code is working and styling my "*Theme Options*" page (located under the WP API Appearance menu) the way I want it to look, however... The CSS stylesheet is also being applied to every other menu in the WP dashboard (such as affecting the "Settings > General-Options") page too. How am I able to go about applying the stylesheet just to my "*Theme Options*" page only and not tamper with anything else? My stylesheet is named 'theme-options.css", located within a folder called "include" > include/theme-options.css. The code below is placed within a "theme-options.php" page. ``` <?php // Add our CSS Styling add_action( 'admin_menu', 'admin_enqueue_scripts' ); function admin_enqueue_scripts() { wp_enqueue_style( 'theme-options', get_template_directory_uri() . '/include/theme-options.css' ); wp_enqueue_script( 'theme-options', get_template_directory_uri() . '/include/theme-options.js' ); } ```
2012/06/03
[ "https://Stackoverflow.com/questions/10871651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1356483/" ]
I was placing the CSS & JS files separately from the building blocks of my page (just above that function). The code is now ***inside*** my page build function and I am now getting the results I was after. Previously: ``` ... // Add our CSS Styling function theme_admin_enqueue_scripts( $hook_suffix ) { wp_enqueue_style( 'theme-options', get_template_directory_uri() . '/include/theme-options.css', false, '1.0' ); wp_enqueue_script( 'theme-options', get_template_directory_uri() . '/include/theme-options.js', array( 'jquery' ), '1.0' ); // Build our Page function build_options_page() { ob_start(); ?> <div class="wrap"> <?php screen_icon();?> <h2>Theme Options</h2> <form method="post" action="options.php" enctype="multipart/form-data"> ... ... ``` Solution: ``` // Build our Page function build_options_page() { // Add our CSS Styling wp_enqueue_style( 'theme-options', get_template_directory_uri() . '/include/theme-options.css' ); wp_enqueue_script( 'theme-options', get_template_directory_uri() . '/include/theme-options.js' ); ob_start(); ?> <div class="wrap"> <?php screen_icon();?> <h2>Theme Options</h2> <form method="post" action="options.php" enctype="multipart/form-data"> ... ... ```
50,822,946
i'm new to sql and having trouble joining a query result table with an existing table. i've been trying to name the query result as res\_tab but it doesn't seem to work.i just want to be able to join the query result with an existing table. here's what i have so far: ``` (select distinct op_id from cmpr_dept_vmdb.cust_promotion where promo_id in ('TB4M40', 'TB4M41', 'TB4M42') and regstrn_status_cd = 'R') as res_tab; select elite_hist.op_id from cmpr_dept_vmdb.elite_hist_detail as elite_hist where elite_hist.instant_elt_promo_cd in ('F1', 'F2', 'F3') inner join elite_hist on res_tab.op_id = elite_hist.op_id ``` it's returning the following error: Syntax error: expected something between ')' and the 'as' keyword
2018/06/12
[ "https://Stackoverflow.com/questions/50822946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9424545/" ]
SQL `select` syntax is ``` [SELECT] ... [FROM] ..... [JOIN] .... [WHERE] .... [GROUP BY] ..... ``` You seem like want to `join` like this. ``` select elite_hist.op_id from cmpr_dept_vmdb.elite_hist_detail as elite_hist inner join ( select distinct op_id from cmpr_dept_vmdb.cust_promotion where promo_id in ('TB4M40', 'TB4M41', 'TB4M42') and regstrn_status_cd = 'R' ) as res_tab; on res_tab.op_id = elite_hist.op_id where elite_hist.instant_elt_promo_cd in ('F1', 'F2', 'F3') ```
444
I'm planning a whitewater rafting trip, and I'm worried what I should do if the raft flips over. Is there a standard set of procedures I should go through to get back on the raft?
2012/01/26
[ "https://outdoors.stackexchange.com/questions/444", "https://outdoors.stackexchange.com", "https://outdoors.stackexchange.com/users/39/" ]
Generally if someone asks this question they don't have a lot of experience and are going with a guide so I will approach it from that point of view. The first thing to do is bring your feet up to the top of the water and get to the raft as fast as you can. You want to keep your feet up to help against hitting any debris you may be floating over and or getting drawn by hydraulics (basically strong pulling water that is caused by passing over obstacles). The guide will probably crawl on top of the raft and flip it over by grabbing a side and using his weight as leverage. However, if the rapids are particularly strong at this point, it's not uncommon to get on the raft upside down and wait until you have reached a more docile point in the river to right it. Something that may go against your natural instincts, it's generally advised not to leave the raft and help others. This may end up in you getting separated from the raft and probably the other person. Biggest things to remember are: * Stay Calm * Stay with the raft * Do exactly as the guide says. He knows the river and knows what he is talking about.
54,104,062
Here is a link to my github repo: <https://github.com/hertweckhr1/api_foodcycle> My user endpoints work great. However when I try to reach my endpoint localhost:8000/api/donation/donations, I get back the error: ProgrammingError at api/donation/donations relation "core\_donation" does not exist Line 1: ...n"."pickup\_endtime", "core\_donation"....: [Link to Error Message](https://i.stack.imgur.com/VTYsD.png) I have tried makemigrations donation and migrate several times. It says my migrations are up to date. Other posts similar to this, I have not been able to find a solution that works for me. Thanks in advance!
2019/01/09
[ "https://Stackoverflow.com/questions/54104062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10887957/" ]
It depends on which http module you are using. For "@angular/common/http", `this.http.get('https://yourapi.com').subscribe(data => { this.trackingorder = data; console.log(this.trackingorder.ShipmentData); }` For '@ionic-native/http', `this.http.get('https://yourapi.com').subscribe(data => { this.trackingorder = JSON.parse(data); console.log(this.trackingorder.ShipmentData); }`
49,771,589
I just made the transition from Spyder to VScode for my python endeavours. Is there a way to run individual lines of code? That's how I used to do my on-the-spot debugging, but I can't find an option for it in VScode and really don't want to keep setting and removing breakpoints. Thanks.
2018/04/11
[ "https://Stackoverflow.com/questions/49771589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4482349/" ]
If you highlight some code, you can right-click or run the command, `Run Selection/Line in Python Terminal`. We are also planning on [implementing Ctrl-Enter](https://github.com/Microsoft/vscode-python/issues/1349) to do the same thing and looking at [Ctr-Enter executing the current line](https://github.com/Microsoft/vscode-python/issues/480).
70,438,651
I have Amazon AWS S3 Bucket and images inside. Every object in my bucket has its own link. When I open it a browser ask me to download the image. So, it is a download link, but not directly the link of the image in the Internet. Of course, when I put it to `<img src="https://">` it doesn't works. So my question is *how I can display images from S3 on my client so that I will not be forced to download images instead of just watching them on the site*. My Stack: Nest.js & React.js (TypeScript) How I upload images: one service: ``` const svgBuffer = Buffer.from(svgString, 'utf-8'); mainRes = await uploadFile(currency, svgBuffer); ``` another service I got uploadFile function from: ``` uploadFile = (currency: string, svg: Buffer) => { const uploadParams = { Bucket: this.config.S3_BUCKET_NAME, Body: svg, Key: `${currency}-chart`, }; return this.s3.upload(uploadParams).promise(); }; ``` How I supposed to get my images: ``` <img src=`https://${s3bucketPath}/${imagePath}`> ```
2021/12/21
[ "https://Stackoverflow.com/questions/70438651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13284630/" ]
It could be a problem with object metadata. Check the metadata and validate the Content type. For example for an PNG image should be: ``` Content-Type='image/png' ``` If object's Content-Type is 'binary/octet-stream' then it will download instead of display. Add the corresponding parameter when uploading through JavaScript SDK: ``` const uploadParams = { Bucket: this.config.S3_BUCKET_NAME, Body: svg, Key: `${currency}-chart`, ContentType: 'image/png', }; ``` UPD from the author: Add this and all gonna work ``` ContentType: 'image/svg+xml' ```
661,575
I need to solve this: $y'' + ay' + by = x(t)$ where nothing about the form of $x$ is known, except that it is bounded and non-negative. In addition it is known that $y(0) = 0$ and $y'(0) = 0$ (and $y''(0) = 0$ as well). I plugged this into the [Wolfram ODE solver](http://www.wolframalpha.com/widgets/view.jsp?id=66d47ae0c1f736b76f1df86c0cc9205) and got back a 'possible Lagrangian', which I really don't know how to use. (I have an undergraduate degree in math but I never took differential equations.) I also found this resource [pt1](http://www.math.psu.edu/tseng/class/Math251/Notes-2nd%20order%20ODE%20pt1.pdf), [pt2](http://www.math.psu.edu/tseng/class/Math251/Notes-2nd%20order%20ODE%20pt2.pdf), but it assumes that the solution is exponential in nature, which seems to violate my initial conditions since exponentials are never 0. I'm hoping there's a way to get my head around this without putting myself through the full course of diff eq so any help would be much appreciated. **Update:** So actually Wolfram Alpha [will solve this equation](http://www.wolframalpha.com/input/?i=Solve%20the%20differential%20equation%20y%27%27%28t%29%20%2b%20a%2ay%27%28t%29%20%2b%20b%2ay%28t%29%20=%20x%28t%29) (simplified slightly in this edit), it was just the 'widget' that stopped short. However, it, as well as the techniques given in the references, explicitly assumes that the solution has an exponential form. Apparently this is a standard assumption but it is not the case for my data. $y$ is roughly sigmoidal. Coding up Wolfram's solution and choosing arbitrary constants $c\_1$, $c\_2$ so as to minimize the error in a case where $y$ was known produced a clearly wrong answer. So, I will sharpen my question: How to solve the above differential question *without* assuming that $y$ is proportional to $e^{\lambda t}$?
2014/02/03
[ "https://math.stackexchange.com/questions/661575", "https://math.stackexchange.com", "https://math.stackexchange.com/users/116930/" ]
Let $f\_\pm (t) := \exp(\lambda\_\pm t)$ where $\lambda\_\pm := (-a \pm \sqrt{a^2 - 4 b})/2$ be the fundamental solutions to the homogenous equation. Then the solution to the ODE, subject to $y(0)=r\_0$ and $y^{'}(0)= \mu\_0$, reads: \begin{equation} y(t) = \left(\begin{array}{cc} f\_+(t) & f\_-(t) \end{array}\right) \cdot \left( \begin{array}{cc} f\_+(0) & f\_-(0) \\ f\_+^{'}(0) & f\_-^{'}(0) \end{array} \right)^{-1} \cdot \left( \begin{array}{c} r\_0 \\ \mu\_0 \end{array} \right) + \int\limits\_0^t \left(\frac{f\_+(\xi) f\_-(t)-f\_-(\xi) f\_+(t)}{f\_+(\xi) f\_-^{'}(\xi) - f\_-(\xi) f\_+^{'}(\xi)}\right) x(\xi) d\xi \end{equation} This can be proven using the Green's function method, for instance. Now, the first term on the right hand side is the generic solution to the homogenous equation and the second term is a specific solution to the inhomogenous equation.The quantity in the denominator in the integrand is called the Wronskian $W(\xi)$ and it reads: \begin{equation} W(\xi) = (\lambda\_- - \lambda\_+) e^{(\lambda\_- + \lambda\_+) \xi} = - \sqrt{a^2 - 4 b} e^{-a \xi} \end{equation} In our case $r\_0=0$ and $\mu\_0 = 0$ and so the solution reads: \begin{equation} y(t) = \frac{-1}{\sqrt{a^2 - 4 b}} \left( e^{\lambda\_- t} \int\limits\_0^t e^{(\lambda\_++a) \xi} x(\xi) d \xi - e^{\lambda\_+ t} \int\limits\_0^t e^{(\lambda\_-+a) \xi} x(\xi) d \xi \right) \end{equation}
337,258
For example, > > In NoSQL, ***technically*** replication and sharding ***approach*** is used for supporting **large data**. > > > Was reading [this article](http://highscalability.com/blog/2010/12/6/what-the-heck-are-you-actually-using-nosql-for.html) about NoSQL use cases. It mentions that NoSQL can be used for **faster key-value access**: > > This is probably the second most cited virtue of NoSQL in the general mind set. When latency is important it's hard to beat hashing on a key and reading the value directly from memory or in as little as one disk seek. Not every NoSQL product is about fast access, some are more about reliability, for example. but what people have wanted for a long time was a better memcached and many NoSQL systems offer that. > > > What ***technical approach*** does Key-Value NoSQL databases take to provide **faster key-value access**? `replication and sharding` is to `large data` `???` is to `faster key-value access`
2016/12/01
[ "https://softwareengineering.stackexchange.com/questions/337258", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/255180/" ]
The first big difference is that key-value stores require the user to have the entire key for lookup, and can *only* be looked up by the key. Contrast that with relational databases which can typically be looked up by partial values of any column. This means a key-value store can create a hash of that key and use that hash to determine a *precise* node and disk location where the record is stored. Relational databases have a much more involved process to locate and retrieve a record, because of inherent extra complexity. This single key also makes possible a single ordering on disk. Key-value stores typically keep a memory cache, an append-only commit log, then occasionally write out a more permanent compacted and sorted storage to disk. Relational databases don't have a single ordering that makes sense, so they can't take advantage of this optimization. Most key-value stores also offer the ability to tune the consistency level, so if you have 3 replicas of each record, you can accept a write as complete after only 2 nodes have reported complete, for example, or even 1, if you like to live on the edge and the data isn't critical. All 3 replicas will be written eventually, but the client doesn't wait for it. This is called *eventual consistency*. Most relational databases maintain absolute consistency at all times, which keeps your data somewhat safer, but also costs speed. Last but not least, since key-value stores can only be looked up by their keys, users end up trading storage space for speed. Where relational database users might do a join that is relatively slow to execute at query time, key-value users will have written redundant tables in parallel at write time, and can query just as fast as any other single-table query. For example, a relational join of a `players` and `location` table would end up as a query using a `(player, location)` tuple for a key, with completely redundant records to a table containing just the `player` key. In summary, key-value stores accept limitations like requiring full keys for lookup, lack of joins, eventual consistency, and need for extra storage in exchange for greater speed.
820
I often hear people say "less than", but shouldn't it be "lesser than"? Which one is correct?
2013/01/31
[ "https://ell.stackexchange.com/questions/820", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/-1/" ]
*Less*, *lesser*, and *littler* are all comparative forms of *little*. They are used like this: * **little - littler - littlest** when you mean "small in size" * **little - less - least** when you mean "small in amount" * **little - lesser - least** when you mean "inferior or smaller in importance" So if you mean one quantity or number is smaller than another, you say "less than".
3,283,984
In Python 2, converting the hexadecimal form of a string into the corresponding unicode was straightforward: ``` comments.decode("hex") ``` where the variable 'comments' is a part of a line in a file (the rest of the line does *not* need to be converted, as it is represented only in ASCII. Now in Python 3, however, this doesn't work (I assume because of the bytes/string vs. string/unicode switch. I feel like there should be a one-liner in Python 3 to do the same thing, rather than reading the entire line as a series of bytes (which I don't want to do) and then converting each part of the line separately. If it's possible, I'd like to read the entire line as a unicode string (because the rest of the line is in unicode) and only convert this one part from a hexadecimal representation.
2010/07/19
[ "https://Stackoverflow.com/questions/3283984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/391126/" ]
Something like: ``` >>> bytes.fromhex('4a4b4c').decode('utf-8') 'JKL' ``` Just put the actual encoding you are using.
2,053,854
Let $0 < p < 1$ and $f: X \longrightarrow (0,\infty)$ measuarable with $\int\_X f d\mu = 1$. Prove that $\int\_A f^p d\mu \leq \mu(A)^{1-p}$. Someone please help?
2016/12/11
[ "https://math.stackexchange.com/questions/2053854", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
It's a direct application of Hölder's inequality, using the exponents $1/p $ and $1/(1-1/(1/p))=1-p $. So $$ \int\_A f^p\,d\mu\leq\left (\int\_A (f^p)^{1/p}\,d\mu\right)^p\left (\int\_A1^{1/(1-p)}\,d\mu\right)^{1-p}\leq\mu (A)^{1-p}. $$
26,835,786
I think I am getting a vector overflow.(?) However I do not know how to solve it. The exercise I am trying to complete states the following: Exercise 3.20 Part 1: Read a set of integers into a vector. Print the sum of each pair of adjacent elements. location of run time error: ``` for (int sum; v1 < ivec.size();++v1){ //executes for statement as long as v1 < ivec.size() is true. sum = ivec[v1] + ivec[v1 + 1]; // same as sum = ivec[0] + ivec[1]. cout << sum << endl; sum = 0; // prints the result of sum = ivec[v1] + ivec[v1 + 1]. ``` The code for the whole program is below. ``` #include "stdafx.h" #include <iostream> #include <vector> using namespace std; int main(){ vector<int> ivec; decltype (ivec.size()) v1 = 0; unsigned int i1 = 0; while (cin >> i1){ ivec.push_back(i1);} // receive input and stores into ivec. for (int sum; v1 < ivec.size();++v1){ //executes for statement as long as v1 < ivec.size() is true. sum = ivec[v1] + ivec[v1 + 1]; // same as sum = ivec[0] + ivec[1], v1 is now = 1. cout << sum << endl; sum = 0; // prints the result of sum = ivec[v1] + ivec[v1 + 1]. } system("pause"); return 0; } ```
2014/11/10
[ "https://Stackoverflow.com/questions/26835786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3089453/" ]
It will update your entity. The Sugar ORM overwriting your existing e.g Name and updated it with "new name" after the save() method call.
33,081,454
In my application I have splitted my classes into files: One class for example looks like: ``` module App.Classes.Bootgrid { import DefaultJQueryAjaxSettings = App.Classes.JQuery.DefaultJQueryAjaxSettings; export class DefaultBootgridOptions implements IBootgridOptions { ajax = true; columnSelection= false; ajaxSettings= new DefaultJQueryAjaxSettings(); } } ``` Whereas DefaultJQueryAjaxSettings.ts looks like ``` module App.Classes.JQuery { export class DefaultJQueryAjaxSettings implements JQueryAjaxSettings { async =false; contentType = "application/x-www-form-urlencoded; charset=UTF-8"; method = "GET"; statusCode: { [index: string]: any; }; type = "GET"; } } ``` At runtime I always get the the error: > > Uncaught TypeError: Cannot read property 'DefaultJQueryAjaxSettings' of undefined > > > as of App.Classes.JQuery is `undefined` at point of execution. Looking at the `Network` tab in Chromes Developer tools, it shows me, that `DefaultJQueryAjaxSettings.js` file is loaded **after** the `DefaultBootgridOptions.js` which causes for sure the described error. How can I set the order of the file to be loaded?
2015/10/12
[ "https://Stackoverflow.com/questions/33081454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615288/" ]
If you are just dealing with an `int` and `double` then you could just overload the function for the differnt types of vectors. ``` int getValue(vector<int> & data) { return 0; } int getValue(vector<double> & data) { return 1; } ``` If you want to keep `getValue` as a template function and specialize for `int` and `double` then you could use ``` template<typename T> int getValue(std::vector<T> & data) { return -1; } template <> int getValue(std::vector<int> & data) { return 0; } template <> int getValue(std::vector<double> & data) { return 1; } ``` `[Live Example](http://coliru.stacked-crooked.com/a/e3100ae63360d5b5)`
21,457,105
I'm trying to click on state link given url then print title of next page and go back, then click another state link dynamically using for loop. But loop stops after initial value. My code is as below: ``` public class Allstatetitleclick { public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.manage().window().maximize(); driver.get("http://www.adspapa.com/"); WebElement catBox = driver.findElement(By.xpath("html/body/table[1]/tbody/tr/td/table/tbody/tr/td[1]/table")); List<WebElement> catValues = catBox.findElements(By.tagName("a")); System.out.println(catValues.size()); for(int i=0;i<catValues.size();i++){ //System.out.println(catValues.get(i).getText()); catValues.get(i).click(); System.out.println(driver.getTitle()); driver.navigate().back(); } System.out.println("TEST"); } } ```
2014/01/30
[ "https://Stackoverflow.com/questions/21457105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3253148/" ]
The problem is after navigating back the elements found previously will be expired. Hence we need to update the code to refind the elements after navigate back. Update the code below : ``` WebDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.manage().window().maximize(); driver.get("http://www.adspapa.com/"); WebElement catBox = driver.findElement(By.xpath("html/body/table[1]/tbody/tr/td/table/tbody/tr/td[1]/table")); List<WebElement> catValues = catBox.findElements(By.tagName("a")); for(int i=0;i<catValues.size();i++) { catValues.get(i).click(); System.out.println(driver.getTitle()); driver.navigate().back(); catBox = driver.findElement(By.xpath("html/body/table[1]/tbody/tr/td/table/tbody/tr/td[1]/table")); catValues = catBox.findElements(By.tagName("a")); } driver.quit(); ``` I have tested above code at my end and its working fine.You can improve the above code as per your use.
4,250
I am working to connect my server to the clients via an MQTT broker. The MQTT client gets connected. But after publishing a message, the subscribe code receives a connection acknowledgment. The on\_message() function never gets called. I am stuck here. I have pasted the subscribe client code and the output. ```python import paho.mqtt.client as paho import time client = paho.Client("local_test") topic = "topic_1" def on_log(client, userdata, level, buff): # mqtt logs function print(buff) def on_connect(client, userdata, flags, rc): # connect to mqtt broker function if rc == 0: client.connected_flag = True # set flags print("Connected Info") else: print("Bad connection returned code = " + str(rc)) client.loop_stop() def on_disconnect(client, userdata, rc): # disconnect to mqtt broker function print("Client disconnected OK") def on_publish(client, userdata, mid): # publish to mqtt broker print("In on_pub callback mid=" + str(mid)) def on_subscribe(client, userdata, mid, granted_qos): # subscribe to mqtt broker print("Subscribed", userdata) def on_message(client, userdata, message): # get message from mqtt broker print("New message received: ", str(message.payload.decode("utf-8")), "Topic : %s ", message.topic, "Retained : %s", message.retain) def connectToMqtt(): # connect to MQTT broker main function print("Connecting to MQTT broker") client.username_pw_set(username=user, password=passwd) client.on_log = on_log client.on_connect = on_connect client.on_publish = on_publish client.on_subscribe = on_subscribe client.connect(broker, port, keepalive=600) ret = client.subscribe(topic, qos=0) print("Subscribed return = " + str(ret)) client.on_message = on_message connectToMqtt() # connect to mqtt broker client.loop_forever() ``` And the output I get after publishing the message on the same topic is: ```python Connecting to MQTT broker Sending CONNECT (u1, p1, wr0, wq0, wf0, c1, k600) client_id=b'local_test' Sending SUBSCRIBE (d0) [(b'topic_1', 0)] Subscribed return = (0, 1) Received CONNACK (0, 0) Connected Info Received SUBACK Subscribed None Sending CONNECT (u1, p1, wr0, wq0, wf0, c1, k600) client_id=b'local_test' Received CONNACK (0, 0) Connected Info ``` **EDIT 1:** Also, I am seeing that my broker has sent the message from the publisher to the client, but the client isn't able to receive it.
2019/06/21
[ "https://iot.stackexchange.com/questions/4250", "https://iot.stackexchange.com", "https://iot.stackexchange.com/users/6645/" ]
It would be relatively easy to build something to do what you want. A Raspberry Pi 3 with a extra WiFi USB dongle should be enough. Set the Pi up with [hostapd](https://learn.sparkfun.com/tutorials/setting-up-a-raspberry-pi-3-as-an-access-point/all) to act as a WiFi Hotspot using the built in WiFi adapter. It should probably also run something like dnsmasq to provide DHCP and DNS caching/forwarding. Then set up the extra USB WiFi adapter to connect to the phone's WiFi hotspot. Set up the Pi to act as a NAT gateway for any traffic on it's own hostspot and have a default route via the phone. This should automatically connect to the phone when it's in range allowing access to the wider Internet while also providing a local always on LAN for devices while you are away. (It is technically possible to do this all with just the build in WiFi adapter, but it's easier and you will get better through put with 2 adapters) Of course this does mean that a lot of the benfits of most consumer IoT devices will be lost, as you will not be able to control any devices while away from home or receive alerts from them as they will have not connection.
29,677,339
I'm getting an `InvalidStateError` at the blob creation line on IE 11. Needless to say, it works in Chrome and Firefox. I can see that the binary data is my client side. Are there any alternatives to download this as a file? ``` var request = new ActiveXObject("MicrosoftXMLHTTP"); request.open("post", strURL, true); request.setRequestHeader("Content-type", "text/html"); addSecureTokenHeader(request); request.responseType = 'blob'; request.onload = function(event) { if (request.status == 200) { var blob = new Blob([request.response], { type: 'application/pdf' }); var url = URL.createObjectURL(blob); var link = document.querySelector('#sim'); link.setAttribute('href', url); var filename = request.getResponseHeader('Content-Disposition'); $('#sim').attr("download", filename); $(link).trigger('click'); fireEvent(link, 'click'); } else { // handle error } } ```
2015/04/16
[ "https://Stackoverflow.com/questions/29677339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1709463/" ]
After instantiating an `XmlHttpRequest` with `xhr.responseType = "blob"` I was getting an `InvalidStateError`. However, moving `xhr.responseType = "blob"` to `onloadstart` solved it for me! :) ``` xhr.onloadstart = function(ev) { xhr.responseType = "blob"; } ```
63,748,751
I am trying to retrieve the user's IP address and assign it to a variable: ``` var ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR") || Request.ServerVariables("REMOTE_ADDR") || Request.ServerVariables("HTTP_HOST"); Response.Write(Request.ServerVariables("HTTP_HOST") + "<br />\n\n"); // produces "localhost" Response.Write(Request.ServerVariables("REMOTE_ADDR") + "<br />\n\n"); // produces "::1" Response.Write(Request.ServerVariables("HTTP_X_FORWARDED_FOR") + "<br />\n\n"); // produces "undefined" Response.Write("ipAddress = " + typeof ipAddress + " " + ipAddress + "<br />\n\n"); // produces "ipAddress = object undefined" ``` I am using JScript for Classic ASP. I am unsure as to what to do at this point. Can anyone help? Thanks
2020/09/04
[ "https://Stackoverflow.com/questions/63748751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1544358/" ]
Things work in ASP with JScript a little bit different than ASP with VBScript. Since everything is an object in JavaScript, with `var ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")` you get an object reference instead of a string value because like most of other `Request` collections, the `ServerVariables` is a collection of `IStringList` objects So, to make that short-circuit evaluation work as you expect, you need to play with the values, not the object references. You can use the `Item` method that returns the string value of `IStringList` object if there's a value (the key exists), otherwise it returns an `Empty` value that evaluated as `undefined` in JScript. ```js var ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR").Item || Request.ServerVariables("REMOTE_ADDR").Item || Request.ServerVariables("HTTP_HOST").Item; ```
14,519,295
I have a grails application running on tomcat and I'm using mod\_proxy to connect http server with it. My goal is to secure the login process. My VirtualHost configuration to force https is: ``` ProxyPass /myapp/ http://127.0.0.1:8080/myapp ProxyPassReverse /myapp/ http://127.0.0.1:8080/myapp RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^(myapp/login) https://%{HTTP_HOST}:443/$1 [NC,R=301,L] ``` When I go to <https://mydomain.com/myapp/adm> - which requires authentication - it redirects to <http://mydomain.com/myapp/login/auth;jsessionid=yyyyyy>, with no security so the rewrite is not working (if I manually replace http with https, it works fine). Any hints?
2013/01/25
[ "https://Stackoverflow.com/questions/14519295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/253944/" ]
Simply speaking, the default comparator compares object instances. * In your first example, both `_emp1` and `_emp2` are pointing to the same instance of `Employee` and therefore `Equals` returns true. * In your second example, you create two `Employee` objects, `_emp1` and `_emp2` being two distinctly different objects. Therefore, `Equals` returns false. --- Note that copy constructors are *not implicitly called* for reference types. Were you to do: ``` Employee _emp1 = new Employee(); Employee _emp2 = new Employee(_emp1); //or _emp1.Clone() if that is implemented ``` then `Equals` using a the default comparator will return false since they are two unique objects. Also note that this behavior is *not the same* for value types. --- Furthermore, if you (as you should) override the default behavior of `Equals` and `CompareTo`, all the above becomes moot. A standard technique might be (assuming a little bit): ``` public bool Equals(object rhs) { var rhsEmployee = rhs as Employee; if(rhsEmployee == null) return false; return this.Equals(rhsEmployee); } public bool Equals(Employee rhs) { return this.EmployeeId == rhs.EmployeeId; } ``` --- Further reading: * [`Object.Equals`](http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx) * [`Object.ReferenceEquals`](http://msdn.microsoft.com/en-us/library/system.object.referenceequals.aspx) * [Value Types and Reference Types](http://msdn.microsoft.com/en-us/library/t63sy5hs%28v=vs.80%29.aspx)
1,687,368
I'm creating a trigger in SQL Server after INSERT, UPDATE and DELETE. Is there a way to know inside the trigger code if it is running on the insert update or delete statement, because I need different behaviors on each case, or I need to create a trigger for each one of them. Thanks in advance, Paulo
2009/11/06
[ "https://Stackoverflow.com/questions/1687368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/157693/" ]
There are datasets called INSERTED and DELETED. Depending on the action that invoked the trigger, there's data in these datasets. For updates, IIRC, the original data is in DELETED, the new data is in INSERTED. See [here](http://msdn.microsoft.com/en-us/library/aa258254(SQL.80).aspx).
16,132,677
I'm very new in building web application using ember.js. I went through the ember.js official guide and found ember.js is very much interesting. I have learned the basic structure of ember.js. But I need a tutorial which will help me to go through building a complete web application using ember.js describing different part of its development process. That may be in document or video tutorial. Please help me to find out the best tutorial to learn ember.js.
2013/04/21
[ "https://Stackoverflow.com/questions/16132677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1954018/" ]
You can find a lot of material on [EmberWatch](http://emberwatch.com/), I'd suggest starting with the one which considered to be the [official guide](http://emberjs.com/guides/) by Tom Dale.
1,612,438
im trying to create a semi-transparent form which is displayed in a panel. i can display the form in the panel but the opacity property wont work and the form is non-transparent. ``` private void button1_Click(object sender, EventArgs e) { Form fr = new Form(); fr.FormBorderStyle = FormBorderStyle.None; fr.BackColor = Color.Black; fr.TopLevel = false; fr.Opacity = 0.5; this.panel1.Controls.Add(fr); fr.Show(); } ``` any ideas how i can handle that? Thanks for your answeres!
2009/10/23
[ "https://Stackoverflow.com/questions/1612438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/195201/" ]
Winforms only supports partial transparency for top-level forms. If you want to create an application with partially-transparent UI elements, you either need to use WPF, or handle all the drawing yourself. Sorry to be the bearer of bad news.
61,002,320
I looked online and every method for extracting numbers from strings uses the `[int(word) for word in a_string.split() if word.isdigit()]` method, however when I run the code below, it does not extract the number `45` ``` test = "ON45" print(test) print([int(i) for i in test.split() if i.isdigit()]) ``` This is what python prints ``` ON45 [] ``` The second list is empty, it should be `[45]` which I should be able to access as integer using `output_int = test[0]`
2020/04/02
[ "https://Stackoverflow.com/questions/61002320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2056201/" ]
[`str.split`](https://docs.python.org/3.8/library/stdtypes.html#str.split) with no arguments splits a string on whitespace, which your string has none of. Thus you end up with `i` in your list comprehension being `ON45` which does not pass `isdigit()`; hence your output list is empty. One way of achieving what you want is: ``` int(''.join(i for i in test if i.isdigit())) ``` Output: ``` 45 ``` You can put that in a list if desired by simply enclosing the `int` in `[]` i.e. ``` [int(''.join(i for i in test if i.isdigit()))] ```
2,244,272
How can I make WebClient download external css stylesheets and image bodies just like a usual web browser does?
2010/02/11
[ "https://Stackoverflow.com/questions/2244272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123927/" ]
What I'm doing right now is: ``` public static final HashMap<String, String> acceptTypes = new HashMap<String, String>(){{ put("html", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); put("img", "image/png,image/*;q=0.8,*/*;q=0.5"); put("script", "*/*"); put("style", "text/css,*/*;q=0.1"); }}; protected void downloadCssAndImages(HtmlPage page) { String xPathExpression = "//*[name() = 'img' or name() = 'link' and @type = 'text/css']"; List<?> resultList = page.getByXPath(xPathExpression); Iterator<?> i = resultList.iterator(); while (i.hasNext()) { try { HtmlElement el = (HtmlElement) i.next(); String path = el.getAttribute("src").equals("")?el.getAttribute("href"):el.getAttribute("src"); if (path == null || path.equals("")) continue; URL url = page.getFullyQualifiedUrl(path); WebRequestSettings wrs = new WebRequestSettings(url); wrs.setAdditionalHeader("Referer", page.getWebResponse().getRequestSettings().getUrl().toString()); client.addRequestHeader("Accept", acceptTypes.get(el.getTagName().toLowerCase())); client.getPage(wrs); } catch (Exception e) {} } client.removeRequestHeader("Accept"); } ```
55,070,711
I'm using MSYS2 but without pip (SSL error), and when I try to run ``` python vin.py ``` It throws me this error: ``` Traceback (most recent call last): File "vin.py", line 1, in <module> import requests ModuleNotFoundError: No module named 'requests' ``` What can I do? Thanks in advance
2019/03/08
[ "https://Stackoverflow.com/questions/55070711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10811266/" ]
I think it is because you installed the `requests` module for Python 3 while you are running Python 2. To specifically install the package for Python 2, try entering this command: ``` pip2 install requests ``` or ``` python -m pip install requests ``` If you want to run the script with Python 3 instead, simply change `python` to `python3`, so: ``` python3 vin.py ```
18,106,312
This should be pretty simple - Get content from a `h1` tag, strip the `span` tag and put the remaining into a `input` tag **I have this HTML:** ``` <div id="contentArea"> <h1><span>Course</span>Arrangementname<h1> <input type="hidden" id="arr1Form_Arrangement" name="arr1Form_Arrangement"> </div> ``` **jQuery** ``` var eventname = $('#contentArea h1').html(); eventname.find("span").remove(); var eventnametrim = eventname.html(); //alert(eventnametrim); $( "input[name*='Form_Arrangement']" ).val( eventnametrim ); ``` But nothing happens - the alert is also empty. My firebug tells me that `"eventname.find is not a function"` it's jQuery 1.9.0 Can someone please telle me whats going on?
2013/08/07
[ "https://Stackoverflow.com/questions/18106312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680223/" ]
If the desired output is `Arrangementname` then the problem is the first line, which should be: ``` var eventname = $('#contentArea h1'); ``` ...because that makes `eventname` a jQuery object, on which you can use `.find()` to get the span and remove it with your existing second line. Though that actually removes the span element from the page completely, so you might want to do this: ``` var eventname = $('#contentArea h1').clone(); ``` ...so that you have a working copy that won't affect what is displayed on the page. The next problem is that you have a variable called `eventnametrim` that you then refer to on the last line of your code as `$eventnametrim`. Remove the `$` from the latter so the names match. If you're trying to get an output of `CourseArrangementname`, i.e., to ignore the `<span>` and `</span>` tags but keep the text content, you can do it like this: ``` var eventname = $('#contentArea h1').text(); $( "input[name*='Form_Arrangement']" ).val( eventname ); ```
30,766,016
I have a large record import job running on our web application. The import is run by a PORO which calculates how many objects it needs to import and divides the number by an index of the current object it is presently on, leaving me with a clean way to calculate the percentage complete. After it does this calculation I am saving this percentage to the database in order to poll it and let the user know how far along this import has come. It doesn't appear that sidekiq allows for these database writes to touch the database until the entire job is over, leaving me with this quesiton: **Is every sidekiq job wrapped entirely in a transaction?** *(I'm not lazy I just don't have a lot of time to go through the code and discover this myself.)*
2015/06/10
[ "https://Stackoverflow.com/questions/30766016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1005669/" ]
I'm not entirely sure I understand your question given that your code does work. But stylistically, for metafunctions that yield a type, that type should be named `type`. So you should have: ``` using type = decltype( test((T*)0) ); ^^^^ ``` Or, to avoid the zero-pointer-cast-hack: ``` using type = decltype(test(std::declval<T*>())); ``` Also, your `test` doesn't need a definition. Just the declaration. We're not actually *calling* it, just checking its return type. It doesn't have to be `constexpr` either, so this suffices: ``` template<class U> static std::true_type test(Base<U> *); static std::false_type test(...); ``` Once you have that, you can alias it: ``` template <typename T> using is_Base_t = typename is_Base<T>::type; ``` And use the alias: ``` template <typename T, typename = std::enable_if_t< is_Base_t<T>::value>> void foo(T const&) { } ```
16,572,771
My game is turnbased, but it does have some realtime elements like chat, so it needs to be speedy. One server should ideally support a couple thousand online players. I know Datasets tend to store large amounts of data in memory but I figured that's what I needed to avoid having to do db calls twice every milliscecond. I'm leaning away from Entity Framework because I don't seem to have as much control of whats happens under the hood, and it struck me as less efficient somehow. Now I know neither of these (nor c# in general) are the most blazingly fast solution to ever exist in life but I do need a little convenience. By the way I can't easily use .Net 4.0 because of some other iffy dependencies. Those could be fixed but to be honest I don't feel like investing the time in figuring it out. I rather just stick with 3.5 which my dependencies work well with.
2013/05/15
[ "https://Stackoverflow.com/questions/16572771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1379635/" ]
I have done a game with a database back-end. Word to the wise: updating caches in a real-time game is difficult. Your players will be interacting all the time. You have to think about whether you want to keep all players on the same server - if so, caching is simple, but you will limit growth. If not, think how you can keep people interacting on the same server. A chat server, for example, would solve the chat issues. However if you have geography, you might want to segment by world areas, if you don't, might want to keep groups of players, or if you have different game instances, you can segment by that. Another issue is locking - your players might access the same data that another is updating. You will almost certainly have to deal with transaction isolation levels - i. e. read uncommitted will help with locking. For this, ADO offers more control. However EF lets you write much cleaner update code, and the performance will not be different if you are updating by ID. You could go for a mix - read via ADO and write via EF. You could even write a transactional db context that uses ADO underneath. That way they look alike but do different things in the background. Just my thoughts, I hope this helps you figure out your solution.
22,559,804
So far, I've been using Git and it's tolerable for simple pushes and merges, but I just got a curve ball thrown at me. The developers of the source code I am using just released a new version release as a source tree. Several files have been changed and I am having difficulty figuring out how to incorporate the new source such that I can keep the old version of their code with my modifications as one branch, say Version 1.0, and the new version of their code with the same modifications as another branch, say Version 2.0. I'm the only one working on the project, so I don't care about rewriting the history if I have too. Ideally, I would like to be able to continue making my modifications and have them apply to both versions.
2014/03/21
[ "https://Stackoverflow.com/questions/22559804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148298/" ]
You can use submodule for code of library you are using , so will be able to have 2 brunches in this submodule (Version 1.0 and Version 2.0) and use master branch for your code. In such case when your changes will be done you will be able to easily provide them with both Version 1.0 and Version 2.0 just by switching branch in submodule code example ``` cd /path/to/project/ mv lib /some/other/location/ git rm lib git commit -m'move lib to submodule' cd /some/other/location/lib git init git add . git commit cd /path/to/project/ git submodule add /some/other/location/lib git commit -m'add submodule' cd /some/other/location/lib git checkout -b version2 do some modifications git commit -m'version2' cd /path/to/project/lib git fetch --all ``` now you can simply switch between version1 and version2 by ``` cd /path/to/project/lib git checkout version2 git checkout master ``` another variant using rebase (not recommended). lets say you have muster branch with version1 of you lib ``` git checkout -b version2 apply changes in you lib wich will bring it to version 2. git commit git checkout master ``` now do your work in master (commit something). To see your master changes in version2 branch do ``` git checkout version2 git rebase master ```
110,106
I have stepped by a [YouTube video](https://youtu.be/-NqaupGcCpw) showing Vienna Philharmonic, under John Williams, playing theme from “Jurassic Park”. In [1:44 minute](https://youtu.be/-NqaupGcCpw?t=104) of this video the drummer is doing *something* with a valve placed next to drums: [![enter image description here](https://i.stack.imgur.com/jUXs0.jpg)](https://i.stack.imgur.com/jUXs0.jpg) Can you explain this? What kind of drum is this? And why he is using a valve at all / like that?
2021/01/23
[ "https://music.stackexchange.com/questions/110106", "https://music.stackexchange.com", "https://music.stackexchange.com/users/74673/" ]
It's a kettledrum, aka timpanum.The handles are for changing the tension on the head, which changes the pitch of the drum. There is also a pedal which can be operated by foot, to go from one tuned pitch to another. Valves are what they're not - there's no gas or liquid passing, only tension produced by a screwing motion.
2,184,625
I have a written a [blog](http://dev.haaga.org/~macy/Blog/index.php) using php and mysql which has a login feature. When you are logged out and hit back it should not show the features of a member since you are no longer logged in. How do I correct it so that when a user is no longer logged in and hit back button, the previous page should be in the state before he logged in?
2010/02/02
[ "https://Stackoverflow.com/questions/2184625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/262926/" ]
It's hard to discern what authentication mechanism you're using, but assuming this is a pure caching issue you can add the following statements to the beginning of all .php pages displayed while logged in. ``` header("Cache-Control: no-cache, must-revalidate"); header("Expires: Mon, 1 Jan 1970 05:00:00 GMT"); ``` That should take care of caching issues. And make sure that you `unset()` the access variable you used to keep track of wether or not the user is logged in (in `$_SESSION` or similar).
17,713,470
Hi I am a new guy to hadoop. Recently, I put a large amount of text files into HDFS. What I wanna do is to read these files and put them into HBase using Pig (LOAD, STORE). However, I found it takes long long time to store into HBase. Does anyone meet similar situations before? If YES, how to solve this problem? Thanks
2013/07/18
[ "https://Stackoverflow.com/questions/17713470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2593688/" ]
I face the same issue when I use HBaseStorage. Actualy HbaseStorage does sequential PUT operations to load data into HBase. Its not really a bulk load. see this unresolved Jira. <https://issues.apache.org/jira/browse/PIG-2921> But I get significant performance difference after using **ImportTSV** option. <http://hbase.apache.org/book/ops_mgt.html#importtsv> The bulk load involved three steps *1. Pig : Read data from source , format in HBASE table structure, load to hdfs. 2. ImportTsv : preparing StoreFiles to be loaded via the completebulkload. 3. completebulkload : move generated StoreFiles into an HBase table. (It's like cut-pest)* Hope this is useful :)
35,469,209
I have a worksheet that lists marines where in column G I have two values, trained and untrained. In column J the value is the unit the marine is with. I want to find the amount trained in each specific unit. Currently I am using `=countif(G2:G99,"TRAINED)` where g2:g99 is the range of marines in unit C, manually finding the range isn't hard, but I want to know if there is a way I can formulate countif that automatically finds the range based on the value in column J hopefully my question is worded correctly and makes sense
2016/02/17
[ "https://Stackoverflow.com/questions/35469209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5942906/" ]
I was actually able to get this to work 100% of the time (in my testing at least) by using files under 500kb. Anything larger seemed to have mixed results. I also seemed to have missed this page (<https://www.twilio.com/user/account/messaging/logs>) within my account. Clicking on the DateTime stamp will provide more detailed error messaging.
31,643,209
I got the following error message when calling the constructor of the class VS1838B ``` error: no matching function for call to ‘IRrecv::IRrecv()’ VS1838B::VS1838B(int pinoReceptorIR){ ^ ``` This is part of the header for the VS1838B class: ``` #ifndef INFRAREDRECEIVERVS1838B_H #define INFRAREDRECEIVERVS1838B_H #include "Arduino.h" #include "IRremote.h" #include "IRremoteInt.h" class VS1838B{ public: //Constructor VS1838B(int pinIR); //Atributes int _pinInput; IRrecv _receptorIR; decode_results _buffer; }; #endif /* INFRAREDRECEIVERVS1838B_H */ ``` And this is part of the cpp for the same class: ``` #include "Arduino.h" #include "InfraRedReceiverVs1838b.h" #include "IRremote.h" #include "IRremoteInt.h" VS1838B::VS1838B(int pinIR){ _pinInput = pinIR; IRrecv receptorIR(_pinInput); decode_results buffer; _receptorIR = receptorIR; _buffer = buffer; } ``` Note: IRrecv and decode\_results are custom types and their libraries are already included.
2015/07/26
[ "https://Stackoverflow.com/questions/31643209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4686873/" ]
Since you **did not provide a whole code example**, I'll instead explain what's wrong since I can still tell. Your constructor's definition is written like this: ``` VS1838B::VS1838B(int pinIR) { // stuff } ``` Regardless of what `// stuff` is, the compiler will actually insert code... ``` VS1838B::VS1838B(int pinIR) // <--- here { // stuff } ``` Which calls the default-constructor of every non-POD-type instance in your class, in order, which you did not specifically initialize, in that same spot. Because you didn't initialize `_receptorIR`, it is inserting a default-constructor call so your constructor REALLY looks like this: ``` VS1838B::VS1838B(int pinIR) : _receptorID () // ERROR: No default initializer! , _buffer () // assuming _buffer is non-POD { // stuff } ``` However, `_receptorID` apparently does not have a default constructor that's accessible. You SHOULD be doing this: ``` VS1838B::VS1838B(int pinIR) : _pinInput ( pinIR ) , _receptorID ( pinIR ) , _buffer () { // stuff // Note: you actually don't need to put ANYTHING you // wrote in your example here because the initializer-list // above did it all for you. } ``` But seriously, **POST THE WHOLE CODE**. The error was CLEARLY with the constructor of IRrecv and you didn't even post its prototype.
169,286
Referencing *Star Trek - The Voyage Home*, where Kirk saves the whales by traveling back in time to San Francisco. Are whales extinct in the Kelvin timeline? And did the "Probe" ever visit Earth?
2017/09/09
[ "https://scifi.stackexchange.com/questions/169286", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/84323/" ]
Fundamentally, we don't know, but humpback whales are probably extinct, at least during the events of the feature films we've seen so far. There are two basic points of view. One is that everything that happened before Nero's incursion into the past is exactly the same in both timelines. Although I can't find good quotes from Orci that specifically state this, this seems to be the attitude the writing staff from the first movie had. They also have an attitude that even events AFTER the split are more-or-less the same (with some big differences of course) because (quoting from [this interview](http://www.startrek.com/article/exclusive-orci-opens-up-about-star-trek-into-darkness-part-1)): > > We can do whatever we want. However, the rule that we have for ourselves is that it has to harmonize with canon. This is going to get way too geeky, and I apologize ahead of time… Quantum mechanics, which is how we based our time travel, is not just simple time travel. Leonard Nimoy didn’t just go back and change history (as Spock Prime in the 2009 film), and then everything is like Back to the Future. It’s using the rules of quantum mechanics, which means it’s an alternate universe where there is no going back. There is no fixing the timeline. There’s just another reality that is the latest and greatest of time travel that exist. So, on the one hand we’re free. On the other hand, these same rules of quantum mechanics tell us that the universes that exist, they exist because they are the most probable universe. (...) And, therefore, the things that happened in The Original Series didn’t just happen because they happened, they happened because it’s actually what’s most probably going to happen. > > > Under this view, humpback whales absolutely don't exist at any point in time that we see in the Kelvin timeline, and the probe might have visited Earth in the distant past (if it did when they first made contact with whales--this was never specified), and for the same reasons it did in the Prime timeline probably will appear a few decades after Star Trek: Beyond. Simon Pegg, on the other hand, wrote this in a [blog post](http://simonpegg.net/2016/07/11/a-word-about-canon/) about Sulu's sexuality (which may arguably have been altered in the Kelvin timeline despite being born before the point of divergence) > > With the Kelvin timeline, we are not entirely beholden to existing canon, this is an alternate reality and, as such is full of new and alternate possibilities. “BUT WAIT!” I hear you brilliant and beautiful super Trekkies cry, “Canon tells us, Hikaru Sulu was born before the Kelvin incident, so how could his fundamental humanity be altered? Well, the explanation comes down to something very Star Treky; theoretical, quantum physics and the less than simple fact that time is not linear. Sure, we experience time as a contiguous series of cascading events but perception and reality aren’t always the same thing. Spock’s incursion from the Prime Universe created a multidimensional reality shift. The rift in space/time created an entirely new reality in all directions, top to bottom, from the Big Bang to the end of everything. As such this reality was, is and always will be subtly different from the Prime Universe. I don’t believe for one second that Gene Roddenberry wouldn’t have loved the idea of an alternate reality (Mirror, Mirror anyone?). This means, and this is absolutely key, the Kelvin universe can evolve and change in ways that don’t necessarily have to follow the Prime Universe at any point in history, before or after the events of Star Trek ‘09, it can mutate and subvert, it is a playground for the new and the progressive and I know in my heart, that Gene Roddenberry would be proud of us for keeping his ideals alive. Infinite diversity in infinite combinations, this was his dream, that is our dream, it should be everybody’s. > > > Under this view, anything goes (but with the understanding that a lot of things are still pretty dang similar in both). So, theoretically, it's possible that in the Kelvin timeline, humpback whales still exist without time travel reasoning being involved. As far as I know, we've seen no evidence for it, and considering how many other things tended to stay the same, despite wild changes, Orci's view has some weight behind it in regards to most of the past. Probably, Humpback whales went extinct on schedule in the past of both timelines. Probably, the probe still visited in Earth's distant past (if that is indeed what happened in the Prime universe). Now, because of time travel, we here get into a sticky and thus-far unrevealed part of canon: **Did, in the Kelvin timeline, the crew of the Enterprise (albeit using a Klingon Bird of Prey) appear in the 80s to steal two humpback whales and bring them to the future?** Again, we don't know, we haven't reached the point in the Kelvin timeline in which they would have made that trip, nor do we know whether previous temporal incursions 'stick' despite the timeline changing (this might in fact be related to Pegg's outlook, the entire history of the universe might have subtly changed in part because of all the time travel that people from the Kelvin timeline would eventually have done differently, or not done at all, that made small alterations to the pre-Kelvin history as well). So it's possible that, as in Orci's view, the most probable course of quantum events is, in a couple decades, the probe returning and devastating Earth while it waits for a reply, Spock (but now Kelvin-Spock) still figuring out they need Humpback whales, and using the time travel trick to go back in time to get them, and return. Or it's possible that this will have been changed too, maybe the Enterprise crew is in another part of the galaxy when the probe returns (after all, Wrath of Khan must happen much differently, or not at all, after Into Darkness, and the ship's status and mission in III and IV all spiral directly out of events in II), nobody else will think of going back in time to get whales, nobody ever appeared back in the 80s either, whales are still extinct, and Earth in the Kelvin timeline is in severe danger when it reaches the equivalent time period of Star Trek IV. Or, it's possible that a Klingon Bird of Prey (piloted by the Prime-Crew) appeared in the 80s to kidnap whales (and the disappearance of said whales, the scientist studying them, and any other associated historical impact from STIV is recorded by the Kelvin timeline's history), and yet again no corresponding Klingon Bird of Prey goes back in time to get them and returns to put them in the ocean (because they came from, and returned to, the Prime timeline) and whales are still extinct so Earth is likely doomed in this scenario too. (But we'll probably never get to see how that winds up affecting the future of the Kelvin timeline and maybe they'll find another solution...) Or it's possible (though unlikely) that in the Kelvin timeline whales aren't extinct BECAUSE George and Gracie aren't removed from the population in the 80s, and that made all the difference, so there's no reason for the probe to revisit. That's a lot of possibilities, as must be expected when you're dealing with an unrevealed part of canon complicated by something like time travel that hasn't been used with consistency over a show's run, but most of the possibilities still point towards humpback whales being extinct at least during the timeline of the movies.
11,884,839
If I have a string of HTML, maybe like this... ``` <h2>Header</h2><p>all the <span class="bright">content</span> here</p> ``` And I want to manipulate the string so that all words are reversed for example... ``` <h2>redaeH</h2><p>lla eht <span class="bright">tnetnoc</span> ereh</p> ``` I know how to extract the string from the HTML and manipulate it by passing to a function and getting a modified result, but how would I do so whilst retaining the HTML? I would prefer a non-language specific solution, but it would be useful to know php/javascript if it must be language specific. Edit ---- I also want to be able to manipulate text that spans several DOM elements... ``` Quick<em>Draw</em>McGraw warGcM<em>warD</em>kciuQ ``` Another Edit ------------ Currently, I am thinking to somehow replace all HTML nodes with a unique token, whilst storing the originals in an array, then doing a manipulation which ignores the token, and then replacing the tokens with the values from the array. This approach seems overly complicated, and I am not sure how to replace all the HTML without using REGEX which I have learned you can go to the stack overflow prison island for. Yet Another Edit ---------------- I want to clarify an issue here. I want the text manipulation to happen over `x` number of DOM elements - so for example, if my formula randomly moves letters in the middle of a word, leaving the start and end the same, I want to be able to do this... ``` <em>going</em><i>home</i> ``` Converts to ``` <em>goonh</em><i>gmie</i> ``` So the HTML elements remain untouched, but the string content inside is manipulated (as a whole - so `goinghome` is passed to the manipulation formula in this example) in any way chosen by the manipulation formula.
2012/08/09
[ "https://Stackoverflow.com/questions/11884839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/665261/" ]
If you want to achieve a similar visual effect without changing the text you could cheat with css, with ``` h2, p { direction: rtl; unicode-bidi: bidi-override; } ``` this will reverse the text example fiddle: <http://jsfiddle.net/pn6Ga/>
30,738,344
I am trying to learn ASP.NET 5. I am using it on Mac OS X. At this time, I have a config.json file that looks like the following: **config.json** ``` { "AppSettings": { "Environment":"dev" }, "DbSettings": { "AppConnectionString": "..." }, "EmailSettings": { "EmailApiKey": "..." }, } ``` I am trying to figure out how to load these settings into a configuration file in Startup.cs. Currently, I have a file that looks like this: **Configuration.cs** ``` public class AppConfiguration { public AppSettings AppSettings { get; set; } public DbSettings DbSettings { get; set; } public EmailSettings EmailSettings { get; set; } } public class AppSettings { public string Environment { get; set; } } public class DbSettings { public string AppConnectionString { get; set; } } public class EmailSettings { public string MandrillApiKey { get; set; } } ``` Then, in Startup.cs, I have the following: ``` public IConfiguration Configuration { get; set; } public Startup(IHostingEnvironment environment) { var configuration = new Configuration().AddJsonFile("config.json"); Configuration = configuration; } public void ConfigureServices(IServiceCollection services) { services.Configure<AppConfiguration>(Configuration); } ``` However, this approach doesn't work. Basically, its like it doesn't know how to map between the .json and the Config classes. How do I do this? I would really like to stay with the DI approach so I can test my app more effectively. Thank you
2015/06/09
[ "https://Stackoverflow.com/questions/30738344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4703156/" ]
In your `Startup` class, first specify your configuration sources: ``` private readonly IConfiguration configuration; public Startup(IHostingEnvironment env) { configuration = new Configuration() .AddJsonFile("config.json") .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true); } ``` *The `env.EnvironmentName` is something like `"development"` or `"production"`. Suppose it is `"development"`. The framework will try to pull configuration values from `config.development.json` first. If the requested values aren't there, or the `config.development.json` file doesn't exist, then the framework will try to pull the values from `config.json`.* Configure your `config.json` sections as services like this: ``` public void ConfigureServices(IServiceCollection services) { services.Configure<AppSettings>(configuration.GetSubKey("AppSettings")); services.Configure<DbSettings>(configuration.GetSubKey("DbSettings")); services.Configure<EmailSettings>(configuration.GetSubKey("EmailSettings")); } ``` *Calling `Configure<T>(IConfiguration)` on the `IServiceCollection` registers the type `IOptions<T>` in the dependency injection container. Note that you don't need your `AppConfiguration` class.* Then specify dependencies to be injected like this: ``` public class EmailController : Controller { private readonly IOptions<EmailSettings> emailSettings; public EmailController (IOptions<EmailSettings> emailSettings) { this.emailSettings = emailSettings; } public IActionResult Index() { string apiKey = emailSettings.Options.EmailApiKey; ... } } ```
57,772,105
* I am making an application in which database products will be added to an xml file. + after querying the xml file, these products will be added to an array. + This array would be sent to the other activity, such as, MainActivity for Menu, but **I can't send the array through `Intent`**. ``` //MainActivity public class MainActivity extends AppCompatActivity { public ArrayList<Produto> array; private File Produtos; private FileOutputStream fileos; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); array = new ArrayList<Produto>(); //if there is no xml file this goes to the database and adds the products in an xml file if ((Produtos.exists() == false)) AdicionarProdutosXML(); //query xml file and add the products in an array ConsultarFicheirosXml(); //pass the array from one activity to another Intent i=new Intent(MainActivity.this,Menu.class); i.putExtra("array",array); startActivity(i); } public void ConsultarFicheirosXml() { int tipo=0; String nome=""; float pvp=0; int quantidade; int eventType=0; XmlPullParser parser=null; File file=null; FileInputStream fis=null; XmlPullParserFactory factory; try { factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); parser = factory.newPullParser(); file = new File("/mnt/sdcard/Produtos.xml"); try { fis = new FileInputStream(file); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } parser.setInput(new InputStreamReader(fis)); eventType=parser.getEventType(); } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } while(eventType!=XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_DOCUMENT: break; case XmlPullParser.START_TAG: if (parser.getName().equalsIgnoreCase("Tipo")) { Produto p = new Produto(); try { tipo= Integer.valueOf(parser.nextText()); parser.nextTag(); nome=parser.nextText(); parser.nextTag(); pvp=Float.valueOf(parser.nextText()); parser.nextTag(); quantidade=Integer.valueOf(parser.nextText()); parser.nextTag(); p.tipo=tipo; p.nome=nome; p.pvp=pvp; p.quantidade=quantidade; array.add(p); } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } break; case XmlPullParser.END_TAG: break; case XmlPullParser.END_DOCUMENT: break; } try { eventType = parser.next(); } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //another activity public class Menu extends AppCompatActivity { public ArrayList<Produto> arrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu); Bundle produtos=getIntent().getExtras(); } ```
2019/09/03
[ "https://Stackoverflow.com/questions/57772105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11990252/" ]
Just post it here to help everyone that have same problem Update your tsconfig.json file with either options ``` "skipTemplateCodegen": false, "strictMetadataEmit": false ``` or ``` "skipTemplateCodegen": true, "strictMetadataEmit": true, "fullTemplateTypeCheck": true ``` Another suggest link to take a look at <https://github.com/gevgeny/angular2-highcharts/issues/156#issue-207301509> Update double check my config with your to see if it work tsconfig.json ``` { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "module": "esnext", "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "importHelpers": true, "target": "es2015", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2018", "dom" ] } } ``` angular.json ``` { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "angular8": { "projectType": "application", "schematics": { "@schematics/angular:component": { "style": "scss" } }, "root": "", "sourceRoot": "src", "prefix": "app", "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "outputPath": "dist/angular8", "index": "src/index.html", "main": "src/main.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.app.json", "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "src/styles.scss" ], "scripts": [] }, "configurations": { "production": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ], "optimization": true, "outputHashing": "all", "sourceMap": false, "extractCss": true, "namedChunks": false, "aot": true, "extractLicenses": true, "vendorChunk": false, "buildOptimizer": true, "budgets": [ { "type": "initial", "maximumWarning": "2mb", "maximumError": "5mb" } ] } } }, "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "angular8:build" }, "configurations": { "production": { "browserTarget": "angular8:build:production" } } }, "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { "browserTarget": "angular8:build" } }, "test": { "builder": "@angular-devkit/build-angular:karma", "options": { "main": "src/test.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.spec.json", "karmaConfig": "karma.conf.js", "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "src/styles.scss" ], "scripts": [] } }, "lint": { "builder": "@angular-devkit/build-angular:tslint", "options": { "tsConfig": [ "tsconfig.app.json", "tsconfig.spec.json", "e2e/tsconfig.json" ], "exclude": [ "**/node_modules/**" ] } }, "e2e": { "builder": "@angular-devkit/build-angular:protractor", "options": { "protractorConfig": "e2e/protractor.conf.js", "devServerTarget": "angular8:serve" }, "configurations": { "production": { "devServerTarget": "angular8:serve:production" } } } } }}, "defaultProject": "angular8" } ```
6,168,935
Hopefully a quick question. I'm trying to validate a double. Making sure it's positive to one decimal place. Good Values: 0.1, 2.5, 100.1, 1, 54 Bad Values: -0.1, 1.123, 1.12, abc, 00012.1 So I've tried Regex here: ``` public boolean isValidAge(String doubleNumber) { DoubleValidator doubleValidator = new DoubleValidator(); return doubleValidator.isValid(doubleNumber,"*[0-9]\\\\.[0-9]"); } ``` I've also tried: `"*[0-9].[0-9]"`, `"\\\\d+(\\\\.\\\\d{1})?"`, `"[0-9]+(\\\\.[0-9]?)?"` Nothing seems to be working. I've been using `org.apache.commons.validator.routines.DoubleValidator` Is there another way I can do this any reason why these regex's aren't working? I don't have to use regex. Thanks
2011/05/29
[ "https://Stackoverflow.com/questions/6168935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152405/" ]
This will match a number and only a number with either a multi-digit pre-decimal point number with no leading zero(s), or just a zero, and optionally a decimal point with one decimal digit. Includes match of the beginning/end of string, so it won't match a number in a larger string (*updated to not accept leading zeros, credit @Nicklas A*): ``` ^([1-9]\d*|0)(\.\d)?$ ``` Use the `java.util.regex.Pattern` library instead. <http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html> Because you're putting the regex into a string, be sure to escape the backslashes ``` "^([1-9]\\d*|0)(\\.\\d)?$" ``` I recommend that you read up on regular expressions here, they are an important tool to have "under your belt" so to speak. <http://www.regular-expressions.info/>
42,743,413
Animating with jQuery is straightforward. Here's an example of animating a number from 0 to 1000 over 2 seconds: ``` var $h1 = $('h1'), startValue = parseInt($h1.text(), 10), endValue = parseInt($h1.data('end-value'), 10); $({ int: startValue }) .animate({ int: endValue }, { duration: 2 * 1000, step: function () { $h1.text(Math.ceil(this.int)); } }); ``` *Working example: <http://codepen.io/troywarr/pen/NpjyJE?editors=1010#0>* This animation looks nice, but makes it difficult to read the number at any point during the animation, as the next number replaces it within milliseconds. Ideally, I'd like to animate the number over the same length of time but using fewer steps (increasing the length of the update interval), so that it's easier to read the number at a glance as it animates. It doesn't appear that jQuery offers direct control over the number of steps in the animation, nor the update interval; it only seems to accept a [`step` function](http://api.jquery.com/animate/ "jQuery .animate() method documentation") that receives an interpolated value. Is there a way to adjust the number of steps that jQuery uses to interpolate the animation over its duration?
2017/03/12
[ "https://Stackoverflow.com/questions/42743413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/167911/" ]
You can use `regular expression` to achieve this, ``` var result = "3 rolls 7 buns 9 bars 7 cooks".split(/\s(?=\d)/); conosole.log(result); //["3 rolls", "7 buns", "9 bars", "7 cooks"] ``` The regex concept used here is `positive look ahead`.
61,818,424
I have a little problem here. I am trying to write a script shell that shows background processes, but at a certain date. The date is a positional parameter. I've searched on Internet about the date validation, but all the info I found got me confused. I'm fairly new at this so a little help would be appreciated. How do I verify if the date parameter is in a valid format in my shell script?
2020/05/15
[ "https://Stackoverflow.com/questions/61818424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13548504/" ]
Could you please try following, tested and written with shown samples. ``` awk 'match($0,/{ [^}]*/){print substr($0,RSTART+2,RLENGTH-2)}' Input_file ``` ***2nd solution:*** considering that your Input\_file is same as shown Input\_file. ``` awk -F'domain { | }' '{print $2}' Input_file ``` ***3rd solution:*** With `sed`. ``` sed 's/^ domain { \([^ }]*\).*/\1/' Input_file ```
6,501,970
I have two separate converters for visibility, one based on whether a field has been updated and one based on whether a field is allowed to be seen. I use the updatedField one for each text item on my page so that a star shows up next to an updated field. But some text items only are visible to some users based on permission levels. For example: ``` <Image Visibility="{Binding ElementName=MyObject, Path=UpdatedFields, Mode=OneWay, Converter={StaticResource updatedFieldConverter}, ConverterParameter=FieldToTest}" Source="Properties:Resources.star_yellow" /> ``` and ``` <TextBlock FontSize="21" Foreground="{DynamicResource LabelBrush}" Text="{x:Static Properties:Resources.Some_Text}" Visibility="{Binding Source={StaticResource allowedFields}, Path=Some_Text_Field, Converter={StaticResource visibilityConverter}}" /> ``` My problem is that for the case of the permission-required fields I need to run both converters to determine if the star shows up. Is there a way to do a boolean "And" on the results of two converters? I looked at [this post](https://stackoverflow.com/questions/1594357/wpf-how-to-use-2-converters-in-1-binding) but it doesn't seem to allow for different sets of parameters to be passed into to the two different converters. -------Update-------- I also tried to create a MultiValueConverter with this xaml ``` <Image Grid.Row="4" Grid.Column="0" Source="star_yellow.png"> <Image.Visibility> <MultiBinding Converter="{StaticResource combinedVisibilityConverter}" ConverterParameter="FieldToTest" > <Binding ElementName="allowedFieldsModel" Path="Some_Text_Field" Mode="OneWay" /> <Binding ElementName="MyObject" Path="UpdatedFields" Mode="OneWay" /> </MultiBinding> </Image.Visibility> </Image> ``` But when it enters the converter both values are "DependencyProperty.UnsetValue". So I'm apparently doing something wrong here. --------Solution--------- I had to modify to this, but then it worked. ``` <Image.Visibility> <MultiBinding Converter="{StaticResource combinedVisibilityConverter}" ConverterParameter="FieldToTest"> <Binding Source="{StaticResource allowedFieldsModel}" Path="Some_Text_Field" /> <Binding Path="MyObject.UpdatedFields" /> </MultiBinding> </Image.Visibility> ```
2011/06/28
[ "https://Stackoverflow.com/questions/6501970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/818540/" ]
You could use a MultiBinding together with a short, hand made IMultiValueConverter. **Example:** ``` <StackPanel> <StackPanel.Resources> <local:MultiBooleanToVisibilityConverter x:Key="Converter" /> </StackPanel.Resources> <CheckBox x:Name="Box1" /> <CheckBox x:Name="Box2" /> <TextBlock Text="Hidden Text"> <TextBlock.Visibility> <MultiBinding Converter="{StaticResource Converter}"> <Binding ElementName="Box1" Path="IsChecked" /> <Binding ElementName="Box2" Path="IsChecked" /> </MultiBinding> </TextBlock.Visibility> </TextBlock> </StackPanel> ``` ... and the converter ... ``` class MultiBooleanToVisibilityConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { bool visible = true; foreach (object value in values) if (value is bool) visible = visible && (bool)value; if (visible) return System.Windows.Visibility.Visible; else return System.Windows.Visibility.Hidden; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } ```
8,138,539
Apologies for if the question is obvious but I can't figure out why it is suddenly not working. I have a jquery datepicker that has been working fine as long as I can remember, but all of a sudden, when I try to submit the form that the datepicker is on the datepicker reappears as though the date I am submitting is invalid. I have already set my date to uk style using the following line of code: ``` <script type="text/javascript"> $(document).ready(function () { $('.date').datepicker({ dateFormat: "dd/mm/yy", minDate: 0 }); }); </script> ``` And I setup the datepicker in my view like this: ``` @Html.TextBox("DateDue", "", new { @class = "date" }) ``` I think that something is requiring the datestring selected to be in US format (as it will submit a valid us date (mm/dd/yyyy) but not the UK format, even though it has been set in the javascript. Am I missing something obvious? Could anyone tell me what I'm doing wrong here? Am not sure if it is necessary but the form that the datepicker is on is created like this: ``` @using ( Html.BeginForm( Html.BeginForm( "Create", "Task", FormMethod.Post, new { id = "taskCreateForm" } ) ) ) ``` PS. The datestring actually works and posts without a problem in Firefox but not in Chrome Any help appreciated EDIT: The problem goes away when I disable the unobtrusive js validation: ``` <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> ``` I had a feeling it was something to do with this and tried remoing the [Required] and [DataType(DataType.Date)] from the model annotation but this didn't do the trick. Not sure how to leave the unobtrusive js in as well as have the uk date string working ok, but am more and more turning to write my own javascript validation for forms than to even bother with the built in stuff, which never seems to work for anything more complicated than a 'required' validation check..
2011/11/15
[ "https://Stackoverflow.com/questions/8138539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/896631/" ]
a google search gave a lot of results relating to localizing/globalizing asp.net mvc 3 validation. this article in particular might be on to something: <http://www.hanselman.com/blog/GlobalizationInternationalizationAndLocalizationInASPNETMVC3JavaScriptAndJQueryPart1.aspx> scroll down to: "Globalized jQuery Unobtrusive Validation" the answer to this question might help as well: [Localizing jquery validation with asp.net mvc 3](https://stackoverflow.com/questions/7438754/localizing-jquery-validation-with-asp-net-mvc-3) jQuery allows you to override the different validation functions like so: ``` $.validator.methods.number = function (value, element) { return !isNaN($.parseFloat(value)); } ``` you could do something like this for the date validator, and run it against a regEx for a valid UK date.
26,425,032
I want to have a `DropdownMenu` from which i can choose how i want to sort my `ListView`. This is my current code for it : ``` <asp:DropDownList ID="DropDownSelect" runat="server" AutoPostBack="True" OnSelectedIndexChanged="GetProducts"> <asp:ListItem Selected="True" Value="DesDate"> Descending Date </asp:ListItem> <asp:ListItem Value="AsDate"> Ascending Date </asp:ListItem> <asp:ListItem Value="AsAlp"> Ascending Alphabetical </asp:ListItem> <asp:ListItem Value="DesAlp"> Decentind Alphabetical </asp:ListItem> </asp:DropDownList> ``` And I have this `ListView` to display my data: ``` <asp:ListView ID="productList" runat="server" DataKeyNames="NewsID" GroupItemCount="1" ItemType="SiteStiri.Models.News" SelectMethod="GetProducts"> <EmptyDataTemplate> <table> <tr> <td>No data was returned.</td> </tr> </table> </EmptyDataTemplate> <EmptyItemTemplate> <td/> </EmptyItemTemplate> <GroupTemplate> <tr id="itemPlaceholderContainer" runat="server"> <td id="itemPlaceholder" runat="server"></td> </tr> </GroupTemplate> <ItemTemplate> <td runat="server"> <table> <tr> <td> <a href="NewsDetails.aspx?newsID=<%#:Item.NewsID%>"> <img src="/Catalog/Images/Thumbs/<%#:Item.ImagePath%>" width="100" height="75" style="border: solid" /></a> </td> </tr> <tr> <td> <a href="NewsDetails.aspx?newsID=<%#:Item.NewsID%>"> <p style="color: black;"> <%#:Item.NewsTitle%> </p> </a> </td> </tr> <tr> <td>&nbsp;</td> </tr> </table> </p> </td> </ItemTemplate> <LayoutTemplate> <table style="width:100%;"> <tbody> <tr> <td> <table id="groupPlaceholderContainer" runat="server" style="width:100%"> <tr id="groupPlaceholder"></tr> </table> </td> </tr> <tr> <td></td> </tr> <tr></tr> </tbody> </table> </LayoutTemplate> </asp:ListView> ``` The thing that i have no idea how to do is: After selecting a sorting rule from the dropdown menu, i can't figure out how to write(or where to write) the method that would update my ListView as it should. My attemp is : ``` public IQueryable<News> GetProducts() { var _db = new SiteStiri.Models.NewsContext(); IQueryable<News> query = _db.News; if (("DesDate").Equals(DropDownSelect.SelectedItem.Value)) { query.OrderByDescending(u => u.ReleaseDate); } if (("AsDate").Equals(DropDownSelect.SelectedItem.Value)) { query.OrderBy(u => u.ReleaseDate); } if (("AsAlp").Equals(DropDownSelect.SelectedItem.Value)) { query.OrderBy(u => u.NewsTitle); } if (("DesApl").Equals(DropDownSelect.SelectedItem.Value)) { query.OrderByDescending(u => u.NewsTitle); } return query; } ``` which gives me a bunch of errors and it doesn't even work .... a little bit of help please? I am new to this (2 days).
2014/10/17
[ "https://Stackoverflow.com/questions/26425032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2948157/" ]
Let's fix your code step by step. 1. Event handlers need to have a certain signature. In case of every ASP.NET control I can remember of, they need to receive two parameters, event arguments and event source object, and return void. Also note that just calling `GetProduct` is not going to update `ListView`, we need to trigger databinding for the control itself. We'll get to that later. For now let's introduce a proper handler: ``` public void DropDownSelect_SelectedIndexChanged(object sender, EventArgs e) ``` Don't forget to update markup as well: ``` OnSelectedIndexChanged="DropDownSelect_SelectedIndexChanged" ``` 2. The conditions on how you show data in the `ListView` have changed. That means that you need to rebind it with calling `DataBind`, which should call `GetProducts` (as a one specified in `SelectMethod`): ``` public void DropDownSelect_SelectedIndexChanged(object sender, EventArgs e) { productList.DataBind(); } ``` 3. Finally in `GetProducts` note that LINQ calls do not update the current object, but rather they produce new one every time. So you should have something like this: ``` if ("DesDate".Equals(DropDownSelect.SelectedItem.Value)) { query = query.OrderByDescending(u => u.ReleaseDate); } ```
576,532
Recently I attended Jeffrey Richter's training courses about .NET. He mentions one strategy of coding "Dying is awesome". That is, don't write "catch (Exception ex)" even at the root of program or event loop. If some exception thrown that is not handled, just let the process die. I'm not sure this is right. Personally, I prefer to have a "`try {...} catch(Exception ex) {log and try to recover}`" to wrap at the top level of execution. Actually, ASP.NET doesn't die if any exception is throw from asXx. If it does die for exception, then one silver-bullet request can silence the whole service. What do you think?
2009/02/23
[ "https://Stackoverflow.com/questions/576532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26349/" ]
I think it depends on what kind of app you are running and what the consequences of 'dying' are. For many client apps, dying is awesome. For servers, often not so much (and swallow-and-log is appropriate). There's no one-size-fits-all solution.
2,129,957
Does anyone with experience using Wordpress know why it would not use my `comments.php` file that is in a theme folder?
2010/01/25
[ "https://Stackoverflow.com/questions/2129957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143030/" ]
I got it working now, I had to change `<?php comments_template(); ?>` into this ``` <?php comments_template('', true); ?> ``` instead, weird but it fixed my problem
151,651
I'm starting to read chapter 11 of Stan Wagon's third edition of Mathematica in Action, a section written by Mark McClure (and there is a package for the notebook). I start with: ``` f[z_] := z^2; Subscript[z, 0] = 0.9 + 0.15 I; orbit = NestList[f, Subscript[z, 0], 10] ``` Then: ``` Attributes[ComplexTicks] = Listable; ComplexTicks[s_?NumericQ] := {s, s I} /. Thread[{-1. I, 0. I, 1. I} -> {-I, 0, I}] ``` What this does, I believe, is create a list of tick marks drawn with the specified labels. For example: ``` ComplexTicks[Range[0, .4, 0.1]] ``` Produces: {{0., 0}, {0.1, 0. + 0.1 I}, {0.2, 0. + 0.2 I}, {0.3, 0. + 0.3 I}, {0.4, 0. + 0.4 I}} So, for example, at 0.0 we'll mark with 0; at 0.1 we'll mark with 0.+0.1I; etc. Now, his next code is: ``` ListPlot[{Re[#], Im[#]} & /@ orbit, Frame -> True, FrameTicks -> {Automatic, ComplexTicks[Range[0, 0.4, 0.1]], None, None}] ``` Which is supposed to produce this image: [![enter image description here](https://i.stack.imgur.com/RIozS.png)](https://i.stack.imgur.com/RIozS.png) But that was in an older version of Mathematica. In Mathematica 11.1.1, it produces this image. [![enter image description here](https://i.stack.imgur.com/I9nEX.png)](https://i.stack.imgur.com/I9nEX.png) The current way to set FrameTicks in Mathematica is FrameTicks->{{left, right},{bottom, top}}. So I adjusted the code as follows: ``` ListPlot[{Re[#], Im[#]} & /@ orbit, Frame -> True, FrameTicks -> {{ComplexTicks[Range[0, 0.4, 0.1]], None}, {Automatic, None}}] ``` But that gives this image: [![enter image description here](https://i.stack.imgur.com/pzCeH.png)](https://i.stack.imgur.com/pzCeH.png) Any way to turn off the real zeros in each complex tick number? **Update:** Thanks to the help from my colleagues, I gave this a try. ``` Attributes[ComplexTicks] = Listable; ComplexTicks[s_?NumericQ] := {s, s "\[ImaginaryI]"} /. Thread[{-1. "\[ImaginaryI]", 0. "\[ImaginaryI]", 1. "\[ImaginaryI]"} -> {-I, 0, I}] f[z_] := z^2; z0 = 0.9 + 0.15 I; orbit = NestList[f, z0, 10]; ListPlot[{Re[#], Im[#]} & /@ orbit, Frame -> True, FrameTicks -> {{ComplexTicks[Range[0, 0.4, 0.1]], None}, {Automatic, None}}] ``` The resulting image is next: [![enter image description here](https://i.stack.imgur.com/cfeQb.png)](https://i.stack.imgur.com/cfeQb.png) Any thoughts?
2017/07/17
[ "https://mathematica.stackexchange.com/questions/151651", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5183/" ]
At some point, Mathematica started showing the real part in inexact complex numbers. To workaround this, I would change `ComplexTicks` to something like: ``` ComplexTicks[s_?NumericQ] := {s, s Defer[I]} ``` or ``` ComplexTicks[s_?NumericQ] := {s, s HoldForm[I]} ```
20,901,966
I have got a map with markers as below. I want to show the div "popup" close to the particular img I clicked on (cursor position). The markers are loaded by an ajax call. JQuery (JS): ``` $( "img").on('click', function(event) { var div = $("#popup"); div.css( { display:"absolute", top:event.pageY, left: event.pageX}); return false; }); ``` HTML: ``` <img class="leaflet-tile leaflet-tile-loaded" style="width: 256px; height: 256px; left: 483px; top: -188px;" src="http://a.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/10/540/357.png"></img> <img class="leaflet-tile leaflet-tile-loaded" style="width: 256px; height: 256px; left: 739px; top: -188px;" src="http://b.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/10/541/357.png"></img> <img class="leaflet-tile leaflet-tile-loaded" style="width: 256px; height: 256px; left: 227px; top: 68px;" src="http://a.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/10/539/358.png"> </img> <div id="popup">showme</div> ```
2014/01/03
[ "https://Stackoverflow.com/questions/20901966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69834/" ]
Apparently you just used the CSS property "display" instead of "position" in your JS. Here's a working fiddle: <http://jsfiddle.net/T32ZV/> And here's the working code: ``` $( "img").on('click', function(event) { var div = $("#popup"); div.css({ position:"absolute", top:event.pageY, left: event.pageX }); return false; }); ```
48,257,736
I am using Vim80 on Windows 10. Using Netrw command , by default it will open up my `%HOME%` path. I want to open specific disk drive on my computer like `F:` using netrw. I have searched through similar questions on Stack Overflow and found answers like using `:Ex F:` or `:cd F:\` but it does not change the default directory. What is the netrw vim command that will enable me to change the drive I am working on?
2018/01/15
[ "https://Stackoverflow.com/questions/48257736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9116264/" ]
i was able to fix the issue , it was due to missing no\_proxy which when i added for my ipaddress it started working.
8,280,186
There's an article here: <http://richnewman.wordpress.com/2007/04/15/a-beginner%E2%80%99s-guide-to-calling-a-net-library-from-excel/> But on user pc it's not possible to modify registries, so is there possible to deploy com for excel without doing so ? Update: seems not possible as addin, then is it possible if just using a com object.
2011/11/26
[ "https://Stackoverflow.com/questions/8280186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/310291/" ]
The new HTML5 form elements can deal with what you need, but there is still the issue of backward compatibility. Basically you can test the value of an input field by listening to the `onblur` event and correct, remove value, or alert the user if the value is not in the set. Alternatively, you can just use the `<select>` element to "force" the user to select from a fixed set of values.
376,536
The title basically is the question. Well, I know why Apple added chip to their cables and changed the connector for good measure. That's of course not a corporate greed but a loving care about their customers... and making sure it would cost them a fortune to leave. But nowhere in the USB specification it requires anything but the wire. Of course high speed introduces strict limits to electrical characteristics etc. But still... it is JUST A WIRE! Billions of cables in the world work just fine without anything else. However when it comes to magnetic cables, which are basically regular cables with connector attached to wires by some pins and magnets, they all have chips inside. The end result is that it is practically impossible to find cable which works with all USB devices in home. Each cable comes with a list of incompatible devices almost as long as compatible. Fast charging that used to be enabled by simple pull-up in micro connector now requires "improved smart chip" and does not work with half of the mobile phones. The question is - why? Is there any reason I don't see? Unlike Apple products these cables are dirt-cheap, and if there is no increased cost then there should not be a reason for manufacturers to make all this mess out of perfectly simple and extremely useful idea. Update: Regarding suggestions to tear down some cable - yes, tearing down and analyzing them with DSO may provide an answer to compatibility problems. But the whole point of posting a question here was the hope that there could be an electrical engineer who *knows* an answer. Also, according to (very limited) marketing info, some manufacturers include identification chip into **plug** portion, designed to trick Apple devices into thinking they connected to authentic cable and avoid annoying pop-ups. Legal issues aside, this has nothing to do with the question, since those cables still have more chips in the connector portion. Funny thing though, is that most devices on "incompatible" lists are Android micro-B / type-C devices. Anyway, here are the theories presented so far: 1. By @pjc50: To simulate the **order of connection** required by USB spec and guaranteed mechanically in regular cables. This is top contender at the moment, because it is applicable to all 3 types of cables on the market (non-reversible, electronically reversible and mechanically reversible). 2. By @Ali\_Chen: To provide additional **ESD protection** highly important here due to exposed pins. This is another strong argument for having chips in the cable, also applicable to all types of cables. 3. By @dim: To avoid **dangling pins** in dual-row models, which might affect high-speed transmission. Not sure if this is critical for USB 2.0 speeds though. 4. By @dim: To **reverse outputs** in single-row models. Yes, this certainly is the case. Note that many cables reverse power only, leaving you without data. Also note, that simple reversing *should not* result in selective compatibility issues. 5. By @tom: To **control the LED**. Now, this is certainly a reason to have some circuitry inside. But if the price is loss of primary function with half of the devices then this is dubious reason, to say the least. Update 2: Is seems there is no one here with insider knowledge of what is really going on in those connectors. So, I am willing to accept @pjc50 and @agent-l suggestions that those chips facilitate an **order of connection** required by USB specification, as something that is *supposed* to be inside from engineering point of view. At the same time, considering how cheap those cables are, I'd like to point out @ali-chen suggestion that they are simple TVS as something that is *actually* there. As a side note, very interesting idea came out of @ali-chen comments - that there are *more reasons to have chips inside plugs* than inside cables. I know that iPhone plugs have chips in them to simulate genuine Apple cable. But since those plugs expose USB interface pins to all the ESD around, having TVS in all plugs regardless of connector type strikes me as another *must have*. Also for electrically-reversible cables the simplest solution to swap power lines would be to put diode bridge in the plug, instead of trying to somehow guess the insertion direction and manage power in the connector. So, until someone tears down actual cable and tells us the truth I propose to consider this question answered.
2018/05/26
[ "https://electronics.stackexchange.com/questions/376536", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/187920/" ]
It is usually very difficult to short out a regular USB cable. Both male and female connectors have covers and recessed pins. This is not the case for magnetic connectors so they will require a microcontroller, or at least an IC, to determine whether a connection has been made and therefore whether it is safe to deliver power and data. They also appear to have fewer pins than a regular connector, so I assume some data conversion is required at either end.
43,953,617
I want to use stored procedures in C# to get data from a SQL Server table. I want to print the city with the id that I'll pass as a parameter, but I don't know the correct syntax of using parameters like that for a stored procedure in C#. This is the C# code that I'm using: ``` string connString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString; using (SqlConnection conn = new SqlConnection(connString)) { conn.Open(); SqlCommand command = new SqlCommand("SP_GetCityByID where id = 2", conn); command.CommandType = CommandType.StoredProcedure; SqlParameter param = command.Parameters.Add("@ID", SqlDbType.Int); param.Direction = ParameterDirection.Input; command.ExecuteNonQuery(); Console.WriteLine(param.Value); } ```
2017/05/13
[ "https://Stackoverflow.com/questions/43953617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7871297/" ]
``` SqlCommand command = new SqlCommand("SP_GetCityByID ", conn); ``` You don't put a `where` condition when you call a stored procedure. `where` condition needs to be inside the body of stored procedure which should compare the `id` column of your city table with `@ID` parameter you are passing to stored procedure. Secondly, `ExecuteNonQuery` function which you have written at the end will not serve your purpose. Use `ExecuteScalar` function instead as given below: ``` String cityName= command.ExecuteScalar(); ``` I am assuming your stored procedure accepts parameter `@ID` and returns matching city name in the form of table.
13,647,658
Let's say I have next construction ``` <table id="mainTable"> <tr> <td> <div class="parentDiv"> <input class="childInput"/> <table> <tbody> <tr> <td> <span>I am here!</span> <td> </tr> </tbody> </table> </div> </td> </tr> </table> ``` How can I get `input` element from `span`? Using jQuery or standart methods. `mainTable` has many rows so I can't use `id` on input. I can do it with: ``` $($(spanElement).parents(".parentDiv")[0]).children(".childInput")[0] ``` Do you know an easier way?
2012/11/30
[ "https://Stackoverflow.com/questions/13647658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1143825/" ]
For really simple data storage needs you can just use the [java File Writer library](http://docs.oracle.com/javase/1.4.2/docs/api/java/io/FileWriter.html) for writing simple primitive data types to a file, then when you need to retrieve the data just use the [File Reader Library](http://docs.oracle.com/javase/1.4.2/docs/api/java/io/FileReader.html). This is about as simple as you can get with storing data with java. If that is to simple, then I would suggest look at serializing your data objects and writing them to a file instead. Here's a [link](http://www.ibm.com/developerworks/java/library/j-5things1/index.html), discusses the merits of object Serialization.
61,944,530
We are using the marvelous `exams` package to produce items to be imported to Moodle. Although we noticed that using LaTeX code (i.e. {}) creates conflict with the Moodle code when importing questions. As so, we would like to know alternatives to use all LaTeX functionalities within Moodle. E.g. the $H\_0: \mu\_{males}=\mu\_{females}$ won't be imported due to the "{}"
2020/05/21
[ "https://Stackoverflow.com/questions/61944530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7773713/" ]
I just had the same error. I think the docs for [editing app/build.gradle](https://flutter.dev/docs/deployment/android#configure-signing-in-gradle) are a bit confusing. Here is how I solved it. Note the duplicate buildTypes block. ``` signingConfigs { release { keyAlias keystoreProperties['keyAlias'] keyPassword keystoreProperties['keyPassword'] storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null storePassword keystoreProperties['storePassword'] } } buildTypes { release { signingConfig signingConfigs.release } } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug } } ``` Here is my full app/build.gradle (remember to change the applicationId). ``` def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } apply plugin: 'com.google.gms.google-services' apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" def keystoreProperties = new Properties() def keystorePropertiesFile = rootProject.file('key.properties') if (keystorePropertiesFile.exists()) { keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) } android { compileSdkVersion 28 sourceSets { main.java.srcDirs += 'src/main/kotlin' } lintOptions { disable 'InvalidPackage' } defaultConfig { applicationId "!!!YOUR APP ID HERE!!!" minSdkVersion 16 targetSdkVersion 28 versionCode flutterVersionCode.toInteger() versionName flutterVersionName testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" multiDexEnabled true } signingConfigs { release { keyAlias keystoreProperties['keyAlias'] keyPassword keystoreProperties['keyPassword'] storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null storePassword keystoreProperties['storePassword'] } } buildTypes { release { signingConfig signingConfigs.release } } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug } } } flutter { source '../..' } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test:runner:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' } ```
4,392,176
Wow, this should be so simple, but it' just not working. I need to inset a "\" into a string (for a Bash command), but escaping just doesn't work. ``` >>> a = 'testing' >>> b = a[:3] + '\' + a[3:] >>> File "<stdin>", line 1 >>> b = a[:3] + '\' + a[3:] ^ >>>SyntaxError: EOL while scanning string literal >>> b = a[:3] + '\\' + a[3:] >>> b 'tes\\ting' >>> sys.version '2.7 (r27:82500, Sep 16 2010, 18:02:00) \n[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)]' ``` The first error is understandable and expexted. The end quote is being eaten, and the interpreter barfs. However, the second example should work. Why is there two slashes? Python 2.7 Thanks, Edit: Thanks Greg. It was a problem with working at the interpreter and not using repr(b). Python was working correctly, but I wasn't looking at the correct version of the output.
2010/12/08
[ "https://Stackoverflow.com/questions/4392176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/466448/" ]
You are being misled by Python's output. Try: ``` >>> a = "test\\ing" >>> print(a) test\ing >>> print(repr(a)) 'test\\ing' >>> a 'test\\ing' ```
46,903,286
I have an activity which contains 2 buttons - Login and Sign up. Both of these has an activity linked (Fragment based Tabbed activity) which contains the Login/Signup form. Now I'm unable to navigate to the particular tab when clicked on a button. ie, If signup button is clicked, it should open Signup fragment based tab and If login button is clicked, it should open login fragment based tab. How do I achieve this? Below are my codes for the respective actions. **Home Activity.java -** ``` public class HomeActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); findViewById(R.id.signup_btn).setOnClickListener(listener_signup_btn); findViewById(R.id.signin_btn).setOnClickListener(listener_signin_btn); } View.OnClickListener listener_signup_btn = new View.OnClickListener() { @Override public void onClick(View view) { //Intent intent = new Intent(HomeActivity.this, SignupActivity.class); //startActivity(intent); } }; View.OnClickListener listener_signin_btn = new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(HomeActivity.this, HomeTaberActivity.class); startActivity(intent); } }; } ``` **HomeTaberActivity.java -** ``` public class HomeTaberActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener { private TabLayout hometabLayout; private ViewPager homeviewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hometaber); hometabLayout = (TabLayout) findViewById(R.id.hometabLayout); hometabLayout.addTab(hometabLayout.newTab().setText("Sign In")); hometabLayout.addTab(hometabLayout.newTab().setText("Sign Up")); hometabLayout.setTabGravity(TabLayout.GRAVITY_FILL); homeviewPager = (ViewPager) findViewById(R.id.homepager); HomePager adapter = new HomePager(getSupportFragmentManager(), hometabLayout.getTabCount()); adapter.Initialise(new LoginActivity(),new SignupActivity()); adapter.addstring("Sign In"); adapter.addstring("Sign Up"); homeviewPager.setAdapter(adapter); hometabLayout.setupWithViewPager(homeviewPager); } @Override public void onTabSelected(TabLayout.Tab tab) { homeviewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } } ```
2017/10/24
[ "https://Stackoverflow.com/questions/46903286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8769268/" ]
Well, maybe this is not the most elegant solution, but I hope it helps! ``` library(shiny) ui <- fluidPage( textInput("jobid", label = "Enter job ID", value = ""), uiOutput("button"), textOutput("downloadFail") ) server <- function(input, output, session) { output$button <- renderUI({ if (input$jobid == ""){ actionButton("do", "Download", icon = icon("download")) } else { downloadButton("downloadData", "Download") } }) available <- eventReactive(input$do, { input$jobid != "" }) output$downloadFail <- renderText({ if (!(available())) { "No job id to submit" } else { "" } }) output$downloadData <- downloadHandler( filename = function() { paste("data-", Sys.Date(), ".csv", sep="") }, content = function(file) { write.csv(data, file) }) } shinyApp(ui, server) ```
11,072,268
While creating an array, the compiler has to know the size of it? For example, the following code snippet does not compile. ``` class A { int n; int arr[n]; }; ``` But, the following compiles. ``` int main() { int n; std::cin >> n; int arr[n]; } ``` Why?
2012/06/17
[ "https://Stackoverflow.com/questions/11072268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1461955/" ]
Standard C++ does not support variable-length arrays.1 If you want this behaviour, I would suggest using a `std::vector` rather than a raw C-style array. --- 1. However, you can find them in C99, or in non-standard language extensions.
28,021,734
I could not understand how to update Q values for tic tac toe game. I read all about that but I could not imagine how to do this. I read that Q value is updated end of the game, but I haven't understand that if there is Q value for each action ?
2015/01/19
[ "https://Stackoverflow.com/questions/28021734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4462426/" ]
You have a `Q` value for each state-action pair. You update one `Q` value after every action you perform. More precisely, if applying action `a1` from state `s1` gets you into state `s2` and brings you some reward `r`, then you update `Q(s1, a1)` as follows: ``` Q(s1, a1) = Q(s1, a1) + learning_rate * (r + discount_factor * max Q(s2, _) - Q(s1, a1)) ``` In many games, such as tic-tac-toe you don't get rewards until the end of the game, that's why you have to run the algorithm through several episodes. That's how information about utility of final states is propagated to other states.
36,331,289
I have one MYSQL query with me I want to execute this query in laravel. ``` select d1.update_id from ( select update_id, count(update_id) as ct from updates_tags where tag_id in (67,33,86,55) group by update_id) as d1 where d1.ct=4 ``` Please guide me how do i Do it easily. I have one reference with me.... It is not working ``` $updateArray = DB::table('updates_tags') ->select('update_id', DB::raw('count(*) as update_id')) ->whereIn('tag_id',$jsontags) ->groupBy('update_id') ->having('update_id','=',count($jsontags)) ->lists('update_id'); ```
2016/03/31
[ "https://Stackoverflow.com/questions/36331289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6139469/" ]
change the `where('total','=',count($tags)) to having('total','=',count($tags))` ``` $update = DB::table('tags') ->select('t_id', 'u_id', DB::raw('count(*) as total')) ->whereIn('t_id',$tags) ->groupBy('u_id') ->having('total','=',count($tags)) ->lists('u_id'); ```
1,132,336
> > Let $G$ be a finite group and define the power map $p\_m:G\to G$ for any $m\in\mathbb Z$ by $p\_m(x)=x^m$. > When is this map a group homomorphism? > > > **Elaborately**: Can we somehow describe or classify those groups $G$ and numbers $m$ for which $p\_m$ is a homomorphism? > For example, is the image $p\_m(G)$ necessarily an abelian subgroup like in all of my examples? > If a group admits a nontrivial $m$ (that is, $m\not\equiv0,1\pmod N$) for which $p\_m$ is a homomorphism, is the group necessarily a product of an abelian group and another group? > > > Observations ------------ 1. The $p\_m$ is clearly a homomorphism whenever $G$ is abelian. 2. Also, if $N$ is the least common multiple of orders of elements of $G$, then $p\_{m+N}=p\_m$ for all $m$ so the answer only depends on $m$ modulo $N$. (Note that $N$ divides $|G|$ but need not be equal to it.) Also, $p\_0$ and $p\_1$ are always homomorphisms and $p\_{-1}$ is so if and only if $G$ is abelian. Examples -------- 1. If $G=C\_4\times S\_3$ (where $C\_n$ denotes the cyclic group of order $n$), then $p\_6$ is a nontrivial homomorphism (neither constant nor identity). Its image is $C\_2\times0<C\_4\times S\_3$. 2. More generally, if $G\_1$ is any nonabelian group and $n$ coprime to $m=|G\_1|$, then $p\_m$ is a nontrivial homomorphism for $G=C\_n\times G\_1$.
2015/02/03
[ "https://math.stackexchange.com/questions/1132336", "https://math.stackexchange.com", "https://math.stackexchange.com/users/166535/" ]
You can't prove that it always produces primes, because that is not true. The way to prove that it *doesn't* always produce primes is to show a counterexample. The smallest counterexample is $$ q\_6 = 2\cdot 3\cdot 5\cdot7\cdot 11\cdot 13+1 = 30031 = 59\cdot 509 $$ It's hard to state categorically that this *can't* be proved other than exhibiting a counterexample. Conceivably we could find some property that the $q\_i$ sequence has (and prove that it has it without computing so much that we run into the counterexample itself) and then prove that no sequence with that property can consist entirely of primes. But even if that can be carried out, it would surely (in this case) be more complex than showing the counterexample.
41,992,735
I have a very simple page.php that should display all URL parameters. (I am having this issue in a more complex page but stripped it down to only this test, and the issue persists) ``` <?php if (!isset($_SESSION)) { session_start(); } print_r($_GET); ?> ``` When I navigate directly to page.php?someProperty=testing , I sometimes get an empty array(), followed by working as expected on the second attempt, and every subsequent attempt. It seems to always fail the first time I make a request from the server after having been away for a while. I'm beginning to think it's something lower level. It's very difficult to debug because as soon as I observe it, it goes away. What could cause this? **Environment Info:** * PHP 5.3 * Apache 2 * Redhat Linux PS - I've read other similar posts, but in each case, someone had forgotten to initialize a session or something. I also made sure no whitespace or headers are set before the session is initialized Update - When the page fails to read the URL parameters, the browser also immediately drops the query string from the location bar as well, reducing it to domain.com/page.php Even if I manually type in the full address for page.php?test=test into the URL bar, it just immediately shortens, and the page outputs a blank array. Also, there is no rewriting of any kind enabled in Apache
2017/02/02
[ "https://Stackoverflow.com/questions/41992735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3554288/" ]
Try like this.For matching multiple words you have use `contains` again. ``` $("td:contains('hour'):contains('day')").css("color", "red"); ``` Example ```js $("p:contains('is'):contains('name')").css("background-color", "red"); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>My name is Donald.</p><!--it will matched contains both `is` and `name`--> <p>I live in Duckburg.</p><!--not matched --> <p>My best friend is Mickey.</p><!--not matched contains only `is`--> ```
53,951,386
<https://imgur.com/bcKQIJr> <-- Calendar Image I have a calendar that requires a double click select dates. I'm working in Javascript, and the NodeJS Selenium-webdriver library has a pretty limited set of events, with no double click option... Do I need to incorporate another library for a double click feature or something? I've really hit a wall. I know this code doesn't work, I've tried a little bit of everything. I just need to double click on a list of elements like the one below. ``` `el = driver.findElement(By.xpath("//div[@class='container']//table[2]//tbody[1]//tr[1]//td[3]")); el.click() .then(_ => driver.sleep(250)) .then(_ => el.click()) ` ``` I can see the clicks happening, so I know I have the element right and the event is happening at the right place/time... but I can't trigger the "selected" dates with what I've got.
2018/12/27
[ "https://Stackoverflow.com/questions/53951386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10458621/" ]
In case of some case (specific to browsers) this might not work for calendars. You might need to use javascript executer for this purpose. Below is some code for your reference. ``` let ele = document.evaluate("//th[@title='Chrome']", document, null,XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; var clickEvent = document.createEvent ('MouseEvents'); clickEvent.initEvent ('dblclick', true, true); ele.dispatchEvent (clickEvent); ``` This should simulate double click on the element. Store this script in a variable (e.g. scrpit) and send to browser for execution using js executor. below is some sample code assuming variable `script` has the js script ``` driver.executeScript(script).then(function(return_value) { console.log('returned ', return_value) }); ```
37,587
Since I married Mjoll the Lioness recently she's set up shop in my home and it seems like the merchandise she sells varies greatly depending her current location/actual inventory. I traded her things like dragon scales/materials and checked her shop to find those materials listed there as well. If this is the case, I guess my real question is are the items that are listed in her store ***my*** items? and will they ever be sold or "disappear" somehow without my consent or knowledge? I really don't want to find out that valuable items/weapons/armor I spent a long time acquiring ended up being the "deal of the week." Are items in my spouse's shop mine and will they ever be sold against my will?
2011/11/21
[ "https://gaming.stackexchange.com/questions/37587", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/14934/" ]
If your spouse was a merchant before you married them, they will sell the same goods they would normally. If not, they will sell pawnbroker-type goods and (reportedly) loose items you leave in their inventory. They will not sell items you leave around the house. Their inventory "refreshes" like other shopkeeper inventories, so don't sell them something you are planning to buy back later.
52,717,879
I have a project with the following directory structure: ``` src/main/java src/main/resources src/test/java src/test/resources ``` I want to add a new folder, `integrationTest`: ``` src/integrationTest/java src/integrationTest/resources ``` Where I want to keep integration tests totally separate from unit tests. How should I go about adding this? In the build.gradle, I'm not sure how to specify a new task that'd pick this folder build it and run the tests separately.
2018/10/09
[ "https://Stackoverflow.com/questions/52717879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3719089/" ]
Gradle has a concept of `source sets` which is exactly what you need here. You have a detailed documentation about that in the *Java Plugin* documenation here : <https://docs.gradle.org/current/userguide/building_java_projects.html#sec:java_source_sets> You can define a new source set "integrationTest" in your `build.gradle` ``` sourceSets { integrationTest { java { compileClasspath += main.output + test.output runtimeClasspath += main.output + test.output srcDir file('src/integration-test/java') } resources.srcDir file('src/integration-test/resources') } } ``` This will automatically create new *configurations* `integrationTestCompile` and `integrationTestRuntime`, that you can use to define an new *Task* `integrationTests`: ``` task integrationTest(type: Test) { testClassesDirs = sourceSets.integrationTest.output.classesDirs classpath = sourceSets.integrationTest.runtimeClasspath } ``` For reference : a working full example can be found here : <https://www.petrikainulainen.net/programming/gradle/getting-started-with-gradle-integration-testing/>
134,978
i know hexadecimal charchter ( 0 1 2 3 4 5 6 7 8 9 A B C D E F) when i write code ``` string a= hex"011a" //it is ok ``` but when write this code ``` string a=hex"011aa" // get Error ``` why? and how can i take advantage of this in solidity
2022/09/04
[ "https://ethereum.stackexchange.com/questions/134978", "https://ethereum.stackexchange.com", "https://ethereum.stackexchange.com/users/107176/" ]
First, you need to add the characters in pairs, since a pair of hex digit is a byte. The line that is showing an error has an uneven set of characters: ```js string a=hex"011aa" // get Error ``` Better do this: ```js string a2 =hex"011a0a"; ``` Also, the reason is that you need to add bytes whose values are within the range (in decimal) of 0-127. Because those are the value printable UTF-8 characters that Solidity support. For example, look at this table: <https://www.asciitable.com/> You will see that it goes from 0 to 127 in decimal. In hexadecimal, the range goes from 0-7F. If you try this: ```js string a = hex"aa"; ``` It will not work, because the decimal value of the hex `aa` is 170, and we know that it should not be greater than 127. So we are limited to the range 0-7F in hex: ```js string min_max_accii_value = hex"00_7f"; ``` Do your own conversion here: <https://www.rapidtables.com/convert/number/hex-to-decimal.html?x=aa> So, you can do something like this, and separate it with `_` to make it more readable: ```js string a3 = hex"00_0a_7f"; ``` Here the docs: <https://docs.soliditylang.org/en/v0.8.11/types.html#unicode-literals>
5,581,261
Today is my first day trying to use Oracle databases in Asp.NET so I have no idea of what I need to do. I have added this code ``` Dim oOracleConn As OracleConnection = New OracleConnection() oOracleConn.ConnectionString = "Data Source=xxxxx;User Id=yyy;Password=psw;" oOracleConn.Open() Response.write("Connected to Oracle.") oOracleConn.Close() oOracleConn.Dispose() End Sub ``` But it gives me the error > > Type 'OracleConnection' is not defined. > > > Now i've had a look on the internet and it says that it may be the reference to the DLL that is missing? I know I have got a DLL reference in my page and I don't think I even have the DLL anywhere on my server. Where do I get this DLL from? I've downloaded the ODBC .NET data provider but this didn't seem to help. I've tried to add a reference in Visual Studio but I can't find the Oracle client reference in the list. Any ideas? Thanks
2011/04/07
[ "https://Stackoverflow.com/questions/5581261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/372364/" ]
The Oracle recommended method is to use the [Oracle Data Provider for .NET](http://www.oracle.com/technetwork/topics/dotnet/index-085163.html) You'll need an Oracle Client that is compatible with the version of the database you are using installed on your dev machine and the web sever machine. There are some quirks with how you have to specify the database connection string. Some kind internet soul has [documented](http://www.connectionstrings.com/oracle) the database connection strings for the oracle providers. The oracle client has a file, called TNSNAMES.ORA, which is typically located in the /NETWORK/ADMIN folder under the oracle home where the client was installed (the installation location varies by version and installation settings). This file contains a list of databases with the Port Number, Hostname, and Oracle SID which allows the oracle client to make a connection to a server. Once all of this is configured (or you decide to use the "TNS-less" connection string), you should be able to make database connections to oracle. The ODP.NET provider documentation also provides some sample code which is very helpful when getting started with it.
17,135,857
I got a form called Form1 and a rich text box called richtextbox1, which is automatically generated, so it's private. I got another class that connects to a server, I want to output the status of connecting but I can only access the richtextbox1.Text in the Form1 class, I got 2 possible solutions for this, which would be better or is there a better one that I don't know of? 1. making the textbox public 2. instead of : ``` Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); ``` creating a form1 object first and using that to store the form that is running: ``` //somewhere global Form1 theform = new Form1(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(theform); ``` Then using the object somewhere in my connection class.
2013/06/16
[ "https://Stackoverflow.com/questions/17135857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2373581/" ]
I'd create a public property in `Form1` that you can use. `Form1.cs` ``` public string TextBoxText { get { return myTextBox.Text; } set { myTextBox.Text = value; } } ``` You can then set the value from another class. `AnotherClass.cs` ``` myForm1.TextBoxText = "Current server status"; ``` How you get access to `myForm1` depends on how you're calling the other class. For example, you could pass the form into the other class's constructor. ``` private Form1 myForm1 = null; public AnotherClass(Form1 mainForm) { myForm1 = mainForm; myForm1.TextBoxText = "Current server status"; } ```
42,765,259
**Background:** On a project I am working on, we've switched from using AngularJS (1.6.2) with JavaScript, to TypeScript 2.1.5. We have a decorator applied to the `$exceptionHandler` service that causes JavaScript exceptions to make a call to a common API that send the development team an e-mail; in this way, we can easily see what front-end errors our end-users are encountering in the wild. **Problem:** I recently converted this decorator from JavaScript, to TypeScript. When I try to run the application, I encounter a whitescreen of nothing. After much debugging I discovered that the issue is because AngularJS expects the `$provide.decorator` to pass a function along with a list of dependencies. However, an object is instead being observed, and thus forcing Angular to fail-safe. I diagnosed the problem by setting breakpoints inside of `angular.js` itself; it specifically will fail on line 4809 (inside of function `createInternalInjector(cache, factory)`) due to a thrown, unhandled JavaScript exception, but the part that's actually responsible for the failure is line 4854, inside of function `invoke(fn, self, locals, serviceName)`. The reason it fails, is because the dependencies passed come across as `['$delegate', '$injector',]`; the function is missing from this set. Lastly, one thing I considered doing was simply defining a JavaScript function in the class code. This does not work in my case for two reasons. First, in our `ts.config`, we have `noImplicitAny` set to true; functions are implicitly of the `any` type. Additionally, TypeScript itself appears not to recognize `function` as a keyword, and instead tries and fails to compile it as a symbol on class `ExceptionHandler`. **TypeScript Exception Handler:** ``` export class ExceptionHandler { public constructor( $provide: ng.auto.IProviderService ) { $provide.decorator('$exceptionHandler`, [ '$delegate', '$injector', this.dispatchErrorEmail ]); } public dispatchErrorEmail( $delegate: ng.IExceptionHandlerService, $injector: ng.auto.IInjectorService ): (exception: any, cause: any) => void { return (exception: any, cause: any) => { // First, execute the default implementation. $delegate(exception, cause); // Get our Web Data Service, an $http wrapper, injected... let webDataSvc: WebDataSvc = $injector.get<WebDataSvc>('webDataSvc'); // Tell the server to dispatch an email to the dev team. let args: Object = { 'exception': exception }; webDataSvc.get('/api/common/errorNotification', args); }; } } angular.module('app').config(['$provide', ExceptionHandler]); ``` **Original JS:** ``` (function () { 'use strict'; angular.module('app').config(['$provide', decorateExceptionHandler]); function decorateExceptionHandler($provide) { $provide.decorator('$exceptionHandler', ['$delegate', '$injector', dispatchErrorEmail]); } function dispatchErrorEmail($delegate, $injector) { return function (exception, cause) { // Execute default implementation. $delegate(exception, cause); var webDataSvc = $injector.get('webDataSvc'); var args = { 'exception': exception, }; webDataSvc.get('/api/common/ErrorNotification', args); }; } })(); ``` **Questions:** 1. In what way can I rewrite the TypeScript Exception Handler to be properly picked up by AngularJS? 2. If I can't, is this an AngularJS bug that needs to be escalated? I know for a fact I'm not the only person using AngularJS with TypeScript; being unable to decorate a service due to language choice seems like a pretty major problem.
2017/03/13
[ "https://Stackoverflow.com/questions/42765259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1404206/" ]
Converting everything to classes isn't the purpose of TS, there's no use for classes here. JS code is supposed to be augmented with types and probably be enhanced with `$inject` annotation. ``` angular.module('app').config(decorateExceptionHandler); decorateExceptionHandler.$inject = ['$provide']; export function decorateExceptionHandler($provide: ng.auto.IProviderService) { $provide.decorator('$exceptionHandler', dispatchErrorEmail); } dispatchErrorEmail.$inject = ['$delegate', '$injector']; export function dispatchErrorEmail( $delegate: ng.IExceptionHandlerService, $injector: ng.auto.IInjectorService ): (exception: any, cause: any) => void { ... } ``` `config` expects a regular function, not a constructor. And the reason why the original TS code fails is that `ExceptionHandler` isn't called with `new`, thus `this` is not an object, and `this.dispatchErrorEmail` is not a function.
77,723
Jumping cursor while typing on my Asus EEE PC 1015PE. Keyboard shortcut--Function key plus F3 also not working, as well as a few other function keys not working. Would appreciate any help. Note: mouse/touchpad "Disable touchpad while typing" setting is enabled, but does not work.
2011/11/10
[ "https://askubuntu.com/questions/77723", "https://askubuntu.com", "https://askubuntu.com/users/33124/" ]
``` gksudo gedit /etc/modprobe.d/options.conf ``` Add this line to the file and save it: > > options psmouse proto=imps > > > Restart. Source: <https://bugs.launchpad.net/ubuntu/+source/xserver-xorg-input-synaptics/+bug/355326/comments/9>
67,113,324
I made a function that replaces multiple instances of a single character with multiple patterns depending on the character location. There were two ways I found to accomplish this: 1. This one looks horrible but it works: def xSubstitution(target\_string): ``` while target_string.casefold().find('x') != -1: x_finded = target_string.casefold().find('x') if (x_finded == 0 and target_string[1] == ' ') or (target_string[x_finded-1] == ' ' and ((target_string[-1] == 'x' or 'X') or target_string[x_finded+1] == ' ')): target_string = target_string.replace(target_string[x_finded], 'ecks', 1) elif (target_string[x_finded+1] != ' '): target_string = target_string.replace(target_string[x_finded], 'z', 1) else: target_string = target_string.replace(target_string[x_finded], 'cks', 1) return(target_string) ``` 2. This one technically works, but I just can't get the regex patterns right: import re def multipleRegexSubstitutions(sentence): ``` patterns = {(r'^[xX]\s'): 'ecks ', (r'[^\w]\s?[xX](?!\w)'): 'ecks', (r'[\w][xX]'): 'cks', (r'[\w][xX][\w]'): 'cks', (r'^[xX][\w]'): 'z',(r'\s[xX][\w]'): 'z'} regexes = [ re.compile(p) for p in patterns ] for regex in regexes: for match in re.finditer(regex, sentence): match_location = sentence.casefold().find('x', match.start(), match.end()) sentence = sentence.replace(sentence[match_location], patterns.get(regex.pattern), 1) return sentence ``` From what I figured it out, the only problem in the second function is the regex patterns. Could someone help me? EDIT: Sorry I forgot to tell that the regexes are looking for the different x characters in a string, and replace an X in the beggining of a word for a 'Z', in the middle or end of a word for 'cks' and if it is a lone 'x' char replace with 'ecks'
2021/04/15
[ "https://Stackoverflow.com/questions/67113324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14244437/" ]
If we need the same output as in `final_outcome` ``` library(dplyr) my_data %>% mutate(attempt = start - cumsum(change)) %>% arrange(age_grp) ``` -output ``` # age_grp start change final_outcome attempt #1 1 0.42 0.034 0.125 0.125 #2 2 0.42 0.027 0.159 0.159 #3 3 0.42 0.030 0.186 0.186 #4 4 0.42 0.032 0.216 0.216 #5 5 0.42 0.032 0.248 0.248 #6 6 0.42 0.027 0.280 0.280 #7 7 0.42 0.031 0.307 0.307 #8 8 0.42 0.029 0.338 0.338 #9 9 0.42 0.033 0.367 0.367 #10 10 0.42 0.020 0.400 0.400 ```
41,155,262
I have a JSON object in string that looks like `'{"key1":"value1", "key2": "value2", "key3": "value3"}'` I can use `json.loads` to make that into a JSON object, but when I try to print it in HTML, it prints the entire JSON object like `{"key1":"value1", "key2": "value2", "key3": "value3"}` my function looks like: ``` def jsonPretty(json_string): return json.loads(json_string) ``` and in HTML/Django: ``` {{kvpair|jsonLoadsPretty}} ``` However I want it to print `key1 value1 key2 value2 key3 value3` The format can vary a little, but I want each key-value pair to separate by a `\n`, and the brackets should be removed. What would be the best way of doing this? EDIT: I'm using `{% with kvpair|jsonPretty as kvjson %}` before running a for loop with ``` {% for k, v in kvjson.items %} <p> {{k}} {{v}}</p> ``` and now it works fine. Thanks for @Andrey Shipilov 's help!
2016/12/15
[ "https://Stackoverflow.com/questions/41155262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3450594/" ]
``` {% for key, value in kvpair %} <p>{{ key }} {{ value }}</p> {% endfor%} ``` <https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#for>
23,438,364
Basically my question is whether or not there is way to validate a non-root element according to a given XSD schema. I am currently working on some legacy code where we have some C++ classes that generate XML elements in string format. I was thinking about a way to unit test these classes by verifying the generated XML (I'm using Xerces C++ under the hood). The problem is that I can't reference an element from another schema different from the root. This is a more detailed description of what I'm doing: I have a class called BooGenerator that generates a 'booIsNotRoot' element defined in 'foo.xsd'. Note that 'boo' is not the root element :-) I have created a test.xsd schema, which references 'booIsNotRoot' in the following way: ``` <?xml version="1.0" encoding="utf-8"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://acme/2014/test" xmlns:foo="http://acme/2014/foo" targetNamespace="http://acme/2014/test" elementFormDefault="qualified"> <xsd:import namespace="http://acme/2014/foo" schemaLocation="foo.xsd"/> <xsd:complexType name="TestType"> <xsd:choice minOccurs="1" maxOccurs="1"> <xsd:element ref="foo:booIsNotRoot"/> </xsd:choice> </xsd:complexType> <xsd:element name="test" type="TestType"/> </xsd:schema> ``` Then I wrap the string generated by BooGenerator with a test element: ``` <test xmlns="xmlns="http://acme/2014/test" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:foo="http://acme/2014/foo xsi:schemaLocation="http://acme/2014/test test.xsd"> (code generated by BooGenerator prefixed with 'foo') </test> ``` but as I said before it doesn't work. If I reference the root element in foo.xsd it works. So I wonder if there is a way to work around this. Thanks in advance.
2014/05/02
[ "https://Stackoverflow.com/questions/23438364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1192525/" ]
``` Basically my question is whether or not there is way to validate a non-root element according to a given XSD schema. ``` Theoretically speaking, yes, [Section 5.2 Assessing Schema-Validity](http://www.w3.org/TR/xmlschema-1/#validation_outcome) of the XSD Recommendation allows for non-root element validity assessment. (Credit and thanks to [C. M. Sperberg-McQueen](https://stackoverflow.com/users/1477421/c-m-sperberg-mcqueen) for [pointing this out](https://stackoverflow.com/a/23464674/290085).) Practically speaking, no, not directly. XML Schema tools tend to validate against XML documents — not selected, individual elements — and XML documents must have a single root element. Perhaps you might embed the element you wish to validate within a rigged context that simulates the element's ancestry up to the proper root element for the document. > > If I reference the root element in foo.xsd it works. > > > The root element in foo.xsd had better be `xsd:schema`, actually. You probably mean to say > > If I reference an element **defined globally (under `xsd:schema`)** in foo.xsd it works. > > > That is also how `@ref` is defined to work in XML Schema — it cannot reference locally defined elements such as `foo:booIsNotRoot`. Furthermore, *any* globally defined element can serve as a root element. (In fact, *only* globally defined elements can serve as a root element.) So, your options include: 1. Rig a valid context in which to test your targeted element. 2. Make your targeted element globally defined in its XSD. 3. Identify an implementation-specific interface to your XSD validator that provides element-level validation.
67,634,218
The official documentation recommands to use the same receiver name everywhere. But does it really make sense to comply with that? I mean, I imagine something like `func (first Foo) concat(second Foo) (combinded Foo)` to be more expressive, while `first` does only make sense in that very context of concatenation. If we don't go that route, we're basically forced to resort to some agnostic but useless receiver naming like `f`, wasting an opportuniy for self-documenting code.
2021/05/21
[ "https://Stackoverflow.com/questions/67634218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5767484/" ]
[Go Wiki: Receiver Names:](https://github.com/golang/go/wiki/CodeReviewComments#receiver-names) > > The name of a method's receiver should be a reflection of its identity; often a one or two letter abbreviation of its type suffices (such as "c" or "cl" for "Client"). Don't use generic names such as "me", "this" or "self", identifiers typical of object-oriented languages that gives the method a special meaning. In Go, the receiver of a method is just another parameter and therefore, should be named accordingly. The name need not be as descriptive as that of a method argument, as its role is obvious and serves no documentary purpose. It can be very short as it will appear on almost every line of every method of the type; familiarity admits brevity. **Be consistent, too: if you call the receiver "c" in one method, don't call it "cl" in another.** > > > If you have a single method, it probably doesn't matter. If you have a type with many (maybe even dozens of methods), it does help if you use the same receiver name in all. It's much easier to read and understand. Also if you want / have to copy some code from one method to another (refactoring), if the receiver name is the same, you can just do copy / paste and your done, you don't have to start editing the different names. Also Dave Cheney: Practical Go: Real world advice for writing maintainable Go programs: > > ### [2.4. Use a consistent naming style](https://dave.cheney.net/practical-go/presentations/qcon-china.html#_use_a_consistent_naming_style) > > > Another property of a good name is it should be predictable. The reader should be able to understand the use of a name when they encounter it for the first time. When they encounter a *common* name, they should be able to assume it has not changed meanings since the last time they saw it. > > > For example, if your code passes around a database handle, make sure each time the parameter appears, it has the same name. Rather than a combination of `d *sql.DB`, `dbase *sql.DB`, `DB *sql.DB`, and `database *sql.DB`, instead consolidate on something like; > > > > ``` > db *sql.DB > > ``` > > Doing so promotes familiarity; if you see a `db`, you know it’s a `*sql.DB` and that it has either been declared locally or provided for you by the caller. > > > **Similar advice applies to method receivers; use the same receiver name every method on that type. This makes it easier for the reader to internalise the use of the receiver across the methods in this type.** > > > Also an interesting reading: [Neither self nor this: Receivers in Go](https://blog.heroku.com/neither-self-nor-this-receivers-in-go)
10,735,381
I have some Data coming out of my DB Model. What I want to do is get the total amount of the PAYMENTS\_total and then times it by VAT (0.20) I'm assuming I need to creat some sort of FOR loop somewhere, But not too sure where? My Code for the controller is : ``` function vat_list() { if(isset($_POST['search_date'])) { $search_date = $this->input->post('search_date', TRUE); } else { $search_date = date('D j M Y', strtotime('today - 7 days')) . ' to ' . date('D j M Y'); } $my_result_data = $this->Invoices_model->read_vat($this->viewinguser->BUSINESSES_id, $search_date); $my_results = $my_result_data->result(); $vat_total = $my_results[0]->PAYMENTS_total; $vat_total = number_format($my_results[0]->PAYMENTS_total, 2, '.', '') * 0.20; $this->template->set('title', 'View VAT Reports'); $this->template->set('subtitle', $search_date); $this->template->set('vat_items', $my_results); $this->template->set('vat_total', $vat_total); $this->template->build('accounts/invoices/vat_list'); } ``` Thanks
2012/05/24
[ "https://Stackoverflow.com/questions/10735381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/265431/" ]
**EDIT** Don't do this - don't use floating point arithmetic for dealing with monetary calculations. Use something that implements fixed-point (decimal) data types, there are several libraries available for this, such as <https://github.com/mathiasverraes/money> or <https://github.com/sebastianbergmann/money>. The original answer is left here for historical purposes only. --- Without knowing the structure of your `$my_results` array I can't say for sure, but I'm guessing this is what you're after: ``` // ... $my_results = $my_result_data->result(); // The VAT rate (you never know, it *might* go down at some point before we die) $vatPercent = 20; // Get the total of all payments $total = 0; foreach ($my_results as $result) { $total += $result->PAYMENTS_total; } // Calculate the VAT on the total $vat = $total * ($vatPercent / 100); // The total including VAT $totalIncVat = $total + $vat; // You can now number_format() to your hearts content $this->template->set('title', 'View VAT Reports'); // ... ```
261,967
> > Power can be murder to resist. > > > This is the tagline of the novel and film *The Firm*. What does it mean for something to "be murder to resist"?
2015/07/24
[ "https://english.stackexchange.com/questions/261967", "https://english.stackexchange.com", "https://english.stackexchange.com/users/130356/" ]
"Murder to " do something means that it is very very hard. For example "That mountain is murder to climb", or "That course is murder to get an A in". In this case the tag is playing on the literal sense of murder also.
53,086
I understand that both are added to imperatives to add some tone to speech but it is not clear to me how different they are in tone. Is "gefälligst" mainly to show mild annoyance, even if you may not be really annoyed among friends? > > Hey, entscheid dich **gefälligst**! > > > Hey, entscheid dich **ruhig**! > > >
2019/07/06
[ "https://german.stackexchange.com/questions/53086", "https://german.stackexchange.com", "https://german.stackexchange.com/users/38692/" ]
No. Unless used ironically, * *gefälligst* "expresses, as part of a command or an instruction the imperious-domineering attitude of the speaker" * *ruhig* "in sentences that contain a permission or a demand, expresses the benevolent attitude of the speaker vis-a-vis the addressee" and is used to signal that the speaker "does not object to the behaviour concerned." (Definitions from *Métrich/Faucher*, Wörterbuch deutscher Partikeln, 2009, my translation) Therefore, * *Hey, entscheid dich gefälligst!* is a rude way of telling someone to make up their mind. It implies urgency, and communicates the assumption that the other person has to obey your command (immediately). * *Hey, entscheid dich ruhig!* sounds somewhat strange (because people generally don't expect that they need to be given permission to "decide") but, aside from that, would indicate that the other person shall feel free to decide. Note that the particle generally implies that the action concerned is something the other person may be willing to do. Which also makes it prone to ironic use: *Du könntest dich bei Tante Stefanie ruhig auch mal bedanken!* (A passive-aggressive way of telling your child that it would be appropriate for her to thank aunt Stefanie.)
56,670,633
I am trying to put logo on Gtk.Headerbar directly in place of title. Logo is created in microsoft word. below is my portion of code class MainWindow(Gtk.Window): """Main window containing notebook""" def **init**(self): Gtk.Window.**init**(self, title="") # since the title is blank, the default header bar with Python icon self.set\_border\_width(10) screen = self.get\_screen() screen\_width = screen.get\_width() screen\_height = screen.height() ``` if screen_width > 1366 or screen_height > 768: self.set_size_request(1300, 800) else: self.set_size_request(screen_width, screen_height) self.set_resizable(True) self.set_resizable(True) # self.maximize() # Creating headerbar & adding it to our window title = "Pareto" subtitle = "Shape your world" header_bar = Gtk.HeaderBar(title=title, subtitle=subtitle) header_bar.set_show_close_button(True) samco_logo = Gtk.Image.new_from_file(r"C:\Users\njoshi\Desktop\pareto\icons\pareto_logo1.png") # this line convert the created icon to an image header_bar.pack_start(samco_logo) time_label = TimeLabel() # show time on header bar header_bar.pack_end(time_label) self.set_titlebar(header_bar) # creating a notebook notebook = Gtk.Notebook() ``` Right now I am using Gtk.Image widget for Logo. Can I design logo directly in my code using html?
2019/06/19
[ "https://Stackoverflow.com/questions/56670633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11368574/" ]
I got it!There is no way we can put logo directly on any of the widgets in GTK 3. Only way is add image widget on top of header bar. ``` self.header_bar = Gtk.HeaderBar() self.header_bar.props.title = "Pareto" self.header_bar.set_show_close_button(True) pareto_logo = Gtk.Image.new_from_file(r"loc\image.png") self.header_bar.pack_start(pareto_logo) ```
58,549,235
I can understand why `10 % "test"` returns `NaN`... because "test" is converted to a number first which gives `NaN` and then any subsequent arithmetic operation involving `NaN` results in `NaN` too. But why does ``` 10 % "0" ``` return `NaN` ? `"0"` is usually converted to a number as `0` e.g. in `1 * "0"`. If I try `10 / "0"` this gives `Infinity` which also makes sense. So... why does that expression `10 % "0"` return `NaN` ?! Any logic behind this?
2019/10/24
[ "https://Stackoverflow.com/questions/58549235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2300597/" ]
Your guess is right, in all the *number only* operators, if used in strings, Javascript will try to convert them in numbers. The same also happens with the remainder operator: ```js const x = "10"%"3"; console.log('10 % 3 = ' + x); ``` So why you get `NaN` evaluating `10%"0"`? Well, it will be converted to `10%0`, but the remainder operator has no particualr meaning if used on 0 (you can't divide by 0 in first instance). So you get NaN: ```js const x = 10 % 0; // numeric only operation console.log('10 % 0 = ' + x); // NaN, the above operation has no meaning ```
55,021,817
i am finding to difficult to add values to list. i did many research but none it seems working. please find my below codes ``` public class Test(){ List <String> list=new ArrayList<>(String); // global public Object method1(){ // here am adding the values to list } String method2(){ if(list.Contains("somethig")) //true} } ``` when i call method2 directly through junit, the list is empty. how can i add values to list in junit? this is where exactly am difficult to add values. i tried below approcah but its not working. **it throws null pointer exception** ``` List<Test> obj=new ArrayList<Test>(); Test cObject=Mockito.mock(Test.class); cObject.list.add("something"); //getting error in this line obj.add(cObject); ``` how can i solve the problem without refactoring my code? where am i making mistakes?
2019/03/06
[ "https://Stackoverflow.com/questions/55021817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11022960/" ]
Try replacing the following lines of code : ``` let data8 = data["latitude"] as? [Double] let data9 = data["longitude"] as? [Double] ``` *Cause: Accessing data with wrong keys*
16,930,978
If I start a IronPyThon Engine in a C# thread, the python script will start a number of threads. However, when I kill the C# thread, all of the threads in the python script are still running. How can I kill all of the threads in the Python script?
2013/06/05
[ "https://Stackoverflow.com/questions/16930978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413174/" ]
The simple Idea will be to start it as a `Process`, after you kill the `Process` every `Thread` of it will also be killed.
923,266
The result of a hypergeometric distribution question that I posted about [earlier this evening](https://math.stackexchange.com/questions/923163/hypergeometric-rv-what-is-the-sample-population) is what follows: $$\frac{{30 \choose 10}{20 \choose 5}}{{50 \choose 15}}$$ This becomes: $$\frac{\frac{30!}{10!20!}\frac{20!}{5!15!}}{ \frac{50!}{15!35!}}$$ $$\frac{30! \cdot 35!}{10!\cdot5!\cdot50!}$$ $$\frac{30! \cdot 35!}{10!\cdot5!\cdot50!}$$ I see that I can, for example, cancel out 35! on the numerator and then that makes the 50! become $50\cdot49\cdots36$, so you get: $$\frac{30!}{10!\cdot5!\cdot(50\cdot49\cdots36)}$$ and subsequently you can do: $$\frac{(30\cdot29\cdots11)}{5!\cdot(50\cdot49\cdots36)}$$, but is there some way to compute these if I didn't have a computer or a long time to perform the arithmetic? I know there are a few expansions but they seemed to be not particularly helpful either... Thanks
2014/09/08
[ "https://math.stackexchange.com/questions/923266", "https://math.stackexchange.com", "https://math.stackexchange.com/users/11086/" ]
For any ring $A$, commutative, with $1$, $GL(2,A)$ is the set of $2\times 2$ matrices with elements in $A$ with determinant an invertible element of $A$. For $A= \mathbb{Z}$ we get $GL(2,\mathbb{Z})$ the set of $2\times 2$ matrices with integral elements and determinant $\pm 1$. For $A=F$ a field we get us $GL(2,F)$ the $2\times 2$ matrices with elements in $F$ and determinant $\ne 0$. So yes,$\ GL(2,A)$ is a group.
55,018,918
I am currently working on a project, where I am creating a feature model out of Xtext grammar. My task is to transform grammar syntax into a CSV file importable into eclipse plug-in pure::variants. Feature model is basicaly tree of features. These features are different types ( mandatory, optional, alternative etc. ). For constructing the tree, I am using generated ecore meta model of my xtext grammar syntax. This file ( .ecore ) is basically a XML file with objects of the grammar. It is consistent, simple and easy to create tree out of. My problem is, that I need to assign types ( mandatory, alternative etc. ) to the nodes of my created tree. These types of features correspond to a cardinality operators. These operators are written in xtext grammar like this: ´(no operator)´, ´?´, ´\*´ and ´+´ ( this can be seen in xtext user manual section 2.1.3 <https://www.eclipse.org/Xtext/documentation/1_0_1/xtext.pdf>). Problem is, that these cardinalities of xtext grammar don't seem to be anywhere to find. I thought that they would appear in .ecore or .genmodel files, but there are no cardinalities at all. I imagine that if xtext is able to check and control these cardinalities, it has to have some kind of meta model, where these cardinalities can be seen and are easily gettable ( something like .xml file similiar to .ecore or .genmodel file). So my question is: Is there some kind of xtext generated file, which contains these cardinalities? If there is not, I would have to somehow get these cardinalities out of grammar itself, but it would be unneccessarily time consuming and complicated, maybe even impossible, because written grammar doesn't fully correspond with ecore metamodel I am getting my feature tree out of and is really complex. Only generated file I was able to find, which contains something "maybe useful" is generated file XXXXGrammarAccess.java ( XXXX stands for name of the grammar ), which is complex generated file, with a lot of library depedencies and I have no idea how to get these cardinalities out of that or if it is even possible. I imagine that there is a possibility, because this file uses a lot of IGrammarAccess methods, such as getRule(), getKeyword() and more, but I am not able to use this file, or print something out of it, because it is a generated file and I am not able to run it on itself. If there is not some kind of meta model I am looking for, is there any possibility to somehow get these cardinalities different way during generating? Thank you very much for your answers.
2019/03/06
[ "https://Stackoverflow.com/questions/55018918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8198679/" ]
try this: ``` def main(): w= [1,2,3] x= [4,5,6] y= [7,8,9] z= [10,11,12] print map(list, zip(w, x, y, z)) ``` > > output : [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]] > > >
6,379,919
I'm trying to automate a secure application(with useragent - iphone) which asks for authentication when i open the site. I tried giving the credentials in the URL itself to bypass the authentication but it pops up a dialogbox for confirmation which i'm unable to handle it through code. ```java FirefoxProfile profile = new FirefoxProfile(); profile.setPreference("general.useragent.override", "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420.1" + "(KHTML, like Gecko) Version/3.0 Mobile/3B48b Safari/419.3)"); WebDriver driver = new FirefoxDriver(profile); String site = "http://akamai:[email protected]"; driver.get(site); ``` Any help on this is highly appreciated. Thanks, Bhavana
2011/06/16
[ "https://Stackoverflow.com/questions/6379919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745995/" ]
Mozilla blocks fishing attempts. Did you check [Network.http.phishy-userpass-length](http://kb.mozillazine.org/Network.http.phishy-userpass-length)? By the way, according to [Selenium's issue 34#8](http://code.google.com/p/selenium/issues/detail?id=34#c8), this should work: ```java FirefoxProfile profile = new FirefoxProfile(); profile.setPreference("network.http.phishy-userpass-length", 255); driver = new FirefoxDriver(profile); driver.get("http://username:[email protected]/"); ``` Note: this question is almost the same as [BASIC Authentication in Selenium 2 - set up for FirefoxDriver, ChromeDriver and IEdriver](https://stackoverflow.com/q/5672407/413020).
68,164
I am trying to self-study a bit of philosophy. I am an applied mathematician by trade, and am therefore drawn to Kant's work on the limits of human knowledge, in particular his exchange with Hume. I was wondering if anybody could clarify a point for me: As far as I understand it, Kant agrees with Hume to the extent that we can never know the true nature of things such as causation, which Hume argues may not exist at all. Now, Kant takes this skepticism a step further by saying that we don't even observe the "real world" at all, only a representation of it in our minds. However, in doing so, he somehow saves the existence of causation. This is where I could use some help. Here is my first attempt to understand what Kant is saying: What Kant is saying is that the mind has certain methods of structuring the data it receives ("forms of intuition") in order to paint our mental pictures. These include notions of space, time, causation, etc. From here, he uses a sort of Descartes "I think therefore I am" to these forms of intuition. That is, causation is a fundamental tool for structuring how I perceive the world, therefore causation exists, at least in this sense. Is this a rough idea of what is going on? Thanks in advance!
2019/11/02
[ "https://philosophy.stackexchange.com/questions/68164", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/34713/" ]
Perhaps the major difference is that Hume derives from experience whatever categories he uses - or supposes that he does so. To take causation as a star example: Hume derives the category of causation from experience in the following way. When event A is prior to event B (priority); when A and B are close in space and time (contiguity); and when A-type events are regularly followed by B-type events (constant conjunction): then by the association of ideas we assume that event A causes event B. This is Hume's essential picture. Kant's picture is radically different. For Kant, we do not *derive* the category of causation from experience. Rather, it is a part of the cognitive apparatus of the mind that we *bring to* experience. It is only by means of an inherent network of categories, such as causation, that coherent experience is possible for us. In other words, for Kant, Hume is precisely wrong. There is not, first experience and then the derivation of the category of causation from experience. On the contrary there is first the category of causation and this structures (or plays a role in structuring) experience in such a way that we can even think of A-type or B-type events. Causation, involving (unless we get into really technical science) the *priority* of the cause to the effect, and *contiguity*, closeness in space and time, between cause and effect, presuppose space and time: these 'forms of intuition' (or roughly 'forms of representation') are not empirical in origin and we do not derive them from experience. On the contrary, again, unless we *already* had these forms of intuition we could not order or locate events in time and space. This is a highly brief account, with endless details missing, but it may serve to the fundamentally different approach between Hume and Kant as regards experience and the empirical.
47,613,633
Hi all, I have pretty awfull query, that needs optimizing. I need to select all records where date of created matches NOW - 35days, but the minutes and seconds can be any. So I have this query here, its ugly, but working: Any optimisation tips are welcome! ``` SELECT * FROM outbound_email oe INNER JOIN (SELECT `issue_id` FROM `issues` WHERE 1 ORDER BY year DESC, NUM DESC LIMIT 0,5) as issues ON oe.issue_id = issues.issue_id WHERE year(created) = year( DATE_SUB(NOW(), INTERVAL 35 DAY) ) AND month(created) = month( DATE_SUB(NOW(), INTERVAL 35 DAY) ) AND day(created) = day( DATE_SUB(NOW(), INTERVAL 35 DAY) ) AND hour(created) = hour( DATE_SUB(NOW(), INTERVAL 35 DAY) ) AND campaign_id IN (SELECT id FROM campaigns WHERE initial = 1) ```
2017/12/02
[ "https://Stackoverflow.com/questions/47613633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2411192/" ]
So what I learnt in the process of debugging this issue was that: * During the creation of a Kubernetes Cluster you can specify permissions for the GCE nodes that will be created. * If you for example enable Datastore access on the cluster nodes during creation, you will be able to access Datastore directly from the Pods without having to set up anything else. * If your cluster node permissions are disabled for most things (default settings) like mine were, you will need to create an appropriate Service Account for each application that wants to use a GCP resource like Datastore. * Another alternative is to create a new node pool with the `gcloud` command, set the desired permission scopes and then migrate all deployments to the new node pool (rather tedious). So at the end of the day I fixed the issue by creating a Service Account for my application, downloading the JSON authentication key, creating a Kubernetes secret which contains that key, and in the case of Datastore, I set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to the path of the mounted secret JSON key. This way when my application starts, it checks if the `GOOGLE_APPLICATION_CREDENTIALS` variable is present, and authenticates Datastore API access based on the JSON key that the variable points to. Deployment YAML snippet: ``` ... containers: - image: foo name: foo env: - name: GOOGLE_APPLICATION_CREDENTIALS value: /auth/credentials.json volumeMounts: - name: foo-service-account mountPath: "/auth" readOnly: true volumes: - name: foo-service-account secret: secretName: foo-service-account ```