text
stringlengths
64
89.7k
meta
dict
Q: Simple (to code) secure hash function I need a secure (cryptographic) hash function with the following properties: Can be coded in as few lines as possible (in R5RS Scheme). Hopefully under 50. Memory and CPU performance within reason for password-length data. (e.g. it does not have to be super efficient or create hashes for millions of bytes of data) Most secure hash functions I can find are designed with speed/memory efficiency in mind and are complex to code as a result. The current candidate is Mash-1 (or Mash-2): Handbook of applied cryptography. Google Books Thanks. Edit: Thank you all for your answers so far. Please forgive me if the following comes off as rude, I just want to be clear. Please trust me that I have done my homework and considered the "standard" options. I know the easiest thing to do is use one of those, but that's not what I'm looking for. The single question I am trying to answer is: What cryptographically secure hash algorithm can be implemented in the smallest amount of "readable" code? I have already posted the best candidate I could find. Any suggestions about something simpler, or commentary about Mash-1/2 would be most helpful. A: If you want a secure hash function for the purpose of actually securing something (say, as part of an encryption algorithm), you would be best served using a library implmentation of SHA-512 (or perhaps RIPEMD-160 or a few others). If you want it for hashing passwords, I would say a hash function like MASH would fit the bill of being resistant to brute force (when used with a salt) and rainbow tables. I still wouldn't use it unless I had stringent requirements forbidding or precluding me from using a library implmentation - but it sounds like you may have just those. If you want it for something less secure, say file integrity checking, almost anything would do unless you're explicitly concerned about malicious users generating collisions. In that case, depending on the value of what you're protecting, I would range from something simple like MASH to something more resistant like SHA-512 or RIPEMD-320. A: If you prefer simplicity and pedagogical value over efficiency then the VSH hash function might be an option. It comes with strong arguments that VSH is a collision resistant hash function, though this function lacks some other properties (e.g. pseudorandomness) that other hash functions have.
{ "pile_set_name": "StackExchange" }
Q: How to create an object of any class that is available in the solution I have a serious question for you guys. I am working on a project that has hundreds of classes. Why cant i access all classes if i want to create an object of that class. For example: I have Class A, B and C. In Page 1, i can create an object of A and B but not C. When i try to type in Class C, the intellisense does not work. I need to access class C to get some of the functions used in it. What can i do to get access to create objects of class C?? A: Chances are you're missing either: An assembly reference (to the project containing class C) A using directive for the namespace containing class C For example, to use the NetworkStream class, you'd need a reference to the System.dll assembly, and you'd usually have a using directive like this: using System.Net.Sockets; in the class that needed to use it. You don't have to have a using directive - you can specify the full name explicitly - but it's usually a good idea. Now it's also possible that class C is internal to the project it's part of, and you're in a different project - which means that you don't have access to it (and you're not meant to). Or perhaps you're trying to call a constructor and there aren't any publicly available ones, for example.
{ "pile_set_name": "StackExchange" }
Q: How to segue from UIAlert and pass information I am pretty new to Swift and programming in general. I am making a quiz app and I want to transfer information between my quiz view controller and a new view controller. I have managed to successfully do that but now I want to use a UIAlertView to segue the information. The problem I having is that when it transitions to the new view controller the arrays are not being populated. I had it working when I used a normal UI Button but with the UI alert it doesn't seem to work. User Submits Answers When this button is pressed the program checks if the user has answered all the questions and then creates a UIAlertView - If the user presses Yes then it should segue to the next controller and pass the required information, but it doesn`t. There is no issue with the arrays in the destination view controller as it has all been working fine until I decided to make this switch. @IBAction func submitAll(sender: UIButton) { let hasAnsweredAllQuestions = questions.reduce(true) { (x, q) in x && (q.usersAnswer != nil) } println("has user answered all questions?: \(hasAnsweredAllQuestions)") if hasAnsweredAllQuestions == true { let alert: UIAlertView = UIAlertView() alert.delegate = self alert.title = "Submit Answers?" alert.message = "If you click yes, your answers will be submitted. If you aren`t finished with the exam press continue." alert.addButtonWithTitle("Yes") alert.addButtonWithTitle("Continue") alert.show() println(userAnswers) } else if hasAnsweredAllQuestions == false { let alert = UIAlertView() alert.title = "Hey, Wait!" alert.message = "You have not answered all questions. Please finish the quiz." alert.addButtonWithTitle("Ok") alert.show() } } Switch / Case Function Here the program appends all the users responses and the correct answers to a new array and gets them ready to ship off to the next view controller. As a mode of debugging I created a simple if statement that made sure the array was being populated. Here the program segues into the next view controller but the arrays in the destination view controller are not being populated. It was originally working when I just used a simple UIButton and not an alert. func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int){ switch buttonIndex{ case 0: // Yes for (index, _) in enumerate(questions) { userAnswers.append(questions[index].usersAnswer!) correctAnswers.append(questions[index].answer!) println("this is working") } if userAnswers.count == 4 { self.performSegueWithIdentifier("segue.push.alert", sender: self) func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if(segue.identifier == "segue.push.alert") { var answerSummary = segue.destinationViewController as! ResultsViewController answerSummary.correctAnswersResults = correctAnswers answerSummary.userAnswersResults = userAnswers } } } break; default: // Continue NSLog("Default"); break;} } A: Your prepareForSegue(_:sender:) method is embedded within your alertView(_:clickedButtonAtIndex:) method. While this is legal in Swift, UIKit won't call this method. It needs to be a method within your view controller subclass (like your alertView(_:clickedButtonAtIndex:) method). You may want to review some of the documentation on Xcode debugging; I think setting a breakpoint in the method would show you that it's never called.
{ "pile_set_name": "StackExchange" }
Q: How to determine op-amp gain with active feedback? The Howland current pump uses an op-amp in the configuration below with a resistive feedback network which gives me the gain show below: But if I decide to swap the feedback resistor for an instrumentation amplifier for less noise and better resolution, what will the new gain be? I've tried searching but can't seem to find anything on this. simulate this circuit – Schematic created using CircuitLab A: What you need to do is add a couple of resistors simulate this circuit – Schematic created using CircuitLab If the instrumentation amp has a gain G, then, since the current through R1 must equal the current through R2, Vin/R1 = G iL Rs/R2, where iL is the load current. Rearranging the terms gives iL = Vin(R2 /R1 G Rs) Note that, strictly speaking, an instrumentation amp is not required, since Rs is grounded, and a simple non-inverting op amp would do the job. In practice, an instrumentation amp would be a good idea, since tiny differences in ground resistance will have a noticeable effect due to the large gain of the amp. Also note that this configuration will almost certainly oscillate like crazy. The phase shift caused by the instrumentation amp will need careful compensation.
{ "pile_set_name": "StackExchange" }
Q: Converting data types in SSIS I get an input CSV file that I have to upload to my oracle database. Here is some sample data ContractId, Date, HourEnding, ReconciledAmount 13860,"01-mar-2010",1,-.003 13860,"01-mar-2010",2,.923 13860,"01-mar-2010",3,2.542 I have to convert the incoming column to DB_TIMESTAMP (to match the structure in the destination table). But when I use Data Conversion to convert, I get an error Data conversion failed while converting column "Date" (126) to column "Date" (496). The conversion returned status value 2 and status text "The value could not be converted because of a potential loss of data. What should I do to be able to properly convert this data? A: What you could do in this situation is change the Text Qualifer in your Flat File connection to be a single double quote ("). This will cause SSIS to interperet 13860,"01-mar-2010",1,-.003 as 13860,01-mar-2010,1,-.003 This also has the added bonus of being able to catch any embedded commas in your data if they are also qualfied with quotes.
{ "pile_set_name": "StackExchange" }
Q: Encapsulate text of element instead of entire element I have a list with links, except for the current pager item (li.pager-current). I would like to encapsulate it with a link also. Source html: <ul class="pager"> <li class="pager-first first"><a href="...">« eerste</a></li> <li class="pager-previous"><a href="...">‹ vorige</a></li> <li class="pager-item"><a href="...">1</a></li> <li class="pager-current">2</li> <li class="pager-item"><a href="...">3</a></li> <li class="pager-next"><a href="...">volgende ›</a></li> <li class="pager-last last"><a href="...">laatste »</a></li> </ul> Current code I have is: $('ul.pager li.pager-current').wrapAll(<a />); Which makes it into: <a><li class="pager-current">2</li></a> But wanted result is: <li class="pager-current"><a>2</a></li> A: I'd suggest: $('.pager-current').wrapInner('<a href="#"></a>'); JS Fiddle demo. Or, alternatively, using html(): $('.pager-current').html(function(i,h){ return '<a href="#">' + h + '</a>'; }); JS Fiddle demo. References: html(). wrapInner().
{ "pile_set_name": "StackExchange" }
Q: jQuery - re-use CSS value on another element I have a background colour set on a series of buttons, .button1, .button2., .button3 & .button4. Each of these buttons has a different background colour set in CSS. I want to use jQuery to detect the background colour of the button when it is clicked and apply that colour to .toolbar. Is this possible? A: You could do: $('button[class^="button"]').click(function(){ $('.toolbar').css('background-color', $(this).css('background-color')); }); This is generic and will automatically detect clicked button rather than writing code for each button having different classes. Also, this code makes sure that it does the stuff only for those buttons whose class names start with button.
{ "pile_set_name": "StackExchange" }
Q: Why can I assign a value to unallocated memory in my float 2d array in c? I have been playing around with '2D arrays' (double pointers) in c, and noticed that assigning data to memory I have not allocated works. #include <stdio.h> #include <stdlib.h> int main() { float **arr; int i; arr = (float **) malloc(5 * sizeof(float*)); for(int i = 0; i < 5; i++) { arr[i] = (float *) malloc(5 * sizeof(float)); } arr[4][1000] = 6; printf("%f\n", arr[4][1000]); return 0; } This program successfully compiles and runs, with no segmentation fault. However, if I were to change the reference to arr[1000][1000], it is then I get the segmentation fault. Why does this occur? A: arr = (float **) malloc(5 * sizeof(float*)); for(int i = 0; i < 5; i++) { arr[i] = (float *) malloc(5 * sizeof(float)); } arr[4][1000] = 6; "Why does this occur?" - it is undefined behavior. It might work it might not. Do not attempt to index outside allocation. Instead: arr = malloc(sizeof *arr * 5); assert(arr); for (int i = 0; i < 5; i++) { arr[i] = malloc(sizeof *(arr[i]) * 1001); assert(arr[i]); } arr[4][1000] = 6;
{ "pile_set_name": "StackExchange" }
Q: SQL WHERE clause filter from more than one column I have a table: RowID QuestionNum Survey -------------------------------- ABC 1 1 DEF 2 1 ASD 3 1 RDS 4 1 TGH 5 1 YHG 1 2 TGF 2 2 UHJ 3 2 UJH 4 2 IJK 5 2 UJH 6 2 RowID is string, QuestionNum and Survey are INT. All I want to do is exclude: QuestionNum 5 and Survey 1 QuestionNum 6 and Survey 2 This is my SQL: SELECT RowID, QuestionNum, SurveyType FROM dbo.tblTest WHERE (SurveyType <> 1) AND (QuestionNum <> 5) OR (SurveyType <> 2) AND (QuestionNum <> 6) But it returns all rows - what am I missing? Thanks. A: All I want to do is exclude QuestionNum 1 and Survey 1 AND QuestionNum 6 and Survey 2 You could phrase this condition as : WHERE NOT ( (SurveyType = 1 AND QuestionNum = 5) OR (SurveyType = 2 AND QuestionNum = 6) ) A: If the list of pairs is too big you can use a set based approach: SELECT RowID, QuestionNum, Survey FROM t WHERE NOT EXISTS ( SELECT 1 FROM (VALUES (1, 1), (6, 2) -- add moar pairs ) AS e(QuestionNum, Survey) WHERE t.QuestionNum = e.QuestionNum AND t.Survey = e.Survey ) Demo on db<>fiddle
{ "pile_set_name": "StackExchange" }
Q: HTML5 Can I use with I wonder if I can use tag <img> like <video>. When I want to add a video to my website I use: <video> <source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> </video> The result is that browser loads only first file, which are supported. It's possible to do the same with <img>? I want to add icons in svg and png/jpg format, so browser will loads the one, which support. Or maybe is better to do it with some Javascript to detect user-agent and then replace graphics in other format? A: No, you cannot combine <img> with <source>. It was deliberately not allowed, because it created backwards-compatibility problems. However, for this use case, the new element <picture> was introduced: <picture> <source type="image/svg+xml" srcset="image.svg"> <img src="fallback.jpg" alt=""> </picture> It is gaining support, but since it's brand-new, some important browsers are missing yet.
{ "pile_set_name": "StackExchange" }
Q: Confused by a sentence using “erleben” Recently I found the following sentence at the end of a novel which I was reading in translation (i.e. it’s the German translation of an English-language novel). Dann mache ich mir eine Liste im Kopf und verzeichne darauf jeden Akt der Güte, den ich je erlebt habe. To me, this means “… every act of good which I have ever experienced”, i.e. which has ever been done to me. But the original turns out to be: That's when I make a list in my head of every act of goodness I’ve seen someone do. Suzanne Collins: Mockingjay The English version also includes act of goodness which the speaker has witnessed. For example if you have seen someone giving your brother some cake, it would be included on the list in the English-language version. But when I was reading the German, it did not seem to me that such an act would be included on the list in the German version. Whereas, if someone had given you some cake, then it would be included on both lists. I would like to know how a native speaker would translate this use of erleben. Does it suggest only those good things that the writer has experienced, or does it also encompass good things which the writer has witnessed someone else experience? A: Well, one of the many senses that the English word to see has is: 3 experience or witness (an event or situation) Oxford Dictionary Now, if you look up the German word erleben you find out that it has quite the same meaning. The bold bits are highlighted by me to emphasize those words that -imho- represents to experience or witness a situtation most appropriately. Bedeutung: eine Erfahrung machen, bei etwas dabei sein Synonyme: dabei sein, etwas mit ansehen, etwas erfahren So, it's not astonishing that I have seen was translated as ich je erlebt habe. Both the German and the English sentence means to experience something but also in both languages it's more appropriate to not use this word here and instead go with to see and erleben, respectively. Regarding your ultimate question: In both languages I rather understand that she only refers to those acts of goodness that she has witnessed. But to tell for sure if she also includes those she experienced herself, I guess you must read the full book. In respect to the comments I'd like to make it more clear: The word erleben can indeed have a slight difference in meaning. In one sense you are the person who experiencing something, i.e. it happens to you. In the other sense, however, you are just the person who is observing something, i.e. it does not happen to you. Usually it's quite clear from context what is meant. Compare those simple examples: Heute habe ich erlebt, was es bedeutet, wenn man keinen Strom hat. Heute habe ich erlebt, wie jemand die Verkäuferin zusammen geschnauzt hat. In OPs example it's hard to say whether the speaker is talking about things happen to themselves or not. As a stand-alone sentence it may suggest that the acts of goodness were directed to themselves but not with absolute certainty. Both the English and the German sentence are ambiguous. There's some room for interpretation. But I think the translation is absolutely fine. A: It may not be the best wording, but then I suppose the context should make the meaning clear. Without context and in isolation, as a native speaker, I interpreted it the way you did when I first read it. In general, erleben means to experience as in be witness to something, whether you are merely a by-stander or an active recipient. However, in the case of being a by-stander, there is a strong connotation of be emotionally touched or impressed included. There is a common expression you might know. Dass ich das noch erleben durfte! ([I am glad/happy] That I lived [long enough] to see/hear/... this [happen]!) Dass ich das jemals erleben würde! (That this would ever happen [I never would have thought]; not as strong as the first expression, but essentially the same) The das in both expression could refer to "hearing him apologize", "the revolution being successful", "your (grand) daughter giving birth", etc. You might or might not be directly involved, but what is common to all situations is you(r feelings) are involved in some way. A: While the other answers are right in that "erleben" can mean "to witness" as well as "to experience", I suppose that most Germans who read the book will primarily understand this sentence to refer to acts of goodness done to the speaker. One could say that in this case, something gets lost in translation, BUT: a) Does it really matter that much in this particular instance? b) This is literature, so style should be a consideration, and a big one at that. I'd argue that an unambiguous translation, e.g. "miterleben", might have an awkward quality to it, making the sentence stand out more than it perhaps should. I'd say the translator has done a pretty good job - as long as it's not essential for the speaker to be characterised as particularly perceptive and sensitive, noticing all the little acts of goodness occurring around him (so that the narrow interpretation of "to personally experience" still makes sense), or (if it is vital that acts the speaker has only witnessed are included) the context makes it clear that the speaker is referring to these as well.
{ "pile_set_name": "StackExchange" }
Q: Find key in array in a foreach I have this foreach function: foreach($total_data as $arrays){ //debug //print_r($total_data); //exit; if($arrays['code']=='d_payment_fee'){ $dpaymentfeetext = ' - '.$arrays['title']; $dpaymentfeevalue = $arrays['value']/1.20; } if($arrays['code']=='shipping'){ $api->addItem(array( 'name' => $arrays['title'].$dpaymentfeetext, 'quantity' => 1, 'unit' => 'ks', 'unit_price' => ($arrays['value']+$dpaymentfeevalue)*1.20 )); } } This works fine, if the first array item is the d_payment_fee, and the second is the shipping: [0] => Array ( [order_total_id] => 214950 [order_id] => 4779 [code] => d_payment_fee [title] => COD [text] => 1,00€ [value] => 1.0000 [sort_order] => 2 ) [1] => Array ( [order_total_id] => 214951 [order_id] => 4779 [code] => shipping [title] => Free [text] => 0,00€ [value] => 0.0000 [sort_order] => 3 ) There are cases when d_payment_fee is not on the first place, like here: [0] => Array ( [order_total_id] => 216352 [order_id] => 4796 [code] => shipping [title] => Free shipping [text] => 2,50€ [value] => 2.5000 [sort_order] => 2 ) [1] => Array ( [order_total_id] => 216353 [order_id] => 4796 [code] => d_payment_fee [title] => COD [text] => 1,00€ [value] => 1.0000 [sort_order] => 3 ) In this case I got undefined variable $dpaymentfee*. Can we find the d_payment_fee if it is not on the first place? A: You could always loop through the array twice and break out of the first loop once you find the d_payment_fee code: $dpaymentfeetext = ''; $dpaymentfeevalue = ''; foreach ($total_data as $data) { if ($data['code'] == 'd_payment_fee') { $dpaymentfeetext = ' - '.$data['title']; $dpaymentfeevalue = $data['value']/1.20; break; } } // Then do your original loop here
{ "pile_set_name": "StackExchange" }
Q: Polysaccharides from non-cyclic sugars? I have only come across polysaccharides from monosaccharides that has undergone intramolecular cyclization reaction. I was wondering if it is possible for polysaccharides to form from linear sugars? I think that the answer lies in how the other glycosidic bond is formed, however my knowledge of chemistry is limited so I don't know if bond formation is possible with a linear sugar. I know a carboxylic acid group can react with a hydroxyl group, and aldehyde can be oxidised to carboxylic acid. So my guess is that it is possible to create a long ester chain from aldoses but not ketoses (as ketone group cannot react and is fully oxidised). Although then I think it would no longer classify as a polysaccharide but a poly(ester)? I'm sure these exist — I have heard of polyester of course! — although I have not come across any others specifically. A: In theory and especially synthetically there is no real reason why one should restrict oneself to polysaccharides where all monomers are in cyclic forms. A linear monosaccharide could, for example, act as a bifurcating branching site with two different sugars attached to the aldehyde carbon to build up the required O,O-acetal. Another variant may be to have a methyl group block the second acetal oxygen. In any case, you want to avoid the aldehyde becoming a hemiacetal because these are too reactive and would degrade quickly. $$\begin{align}\ce{\underset{aldehyde}{R-CH=O}} && \ce{\underset{hemiacetal}{R-CH(OH)(OR)}} && \ce{\underset{acetal}{R-CH(OR)(OR)}}\end{align}$$ You may want to look up acetal and acetalisation in the general organic chemistry textbook of your choice to learn more about why hemiacetals are much less stable than acetals. In practice, however, linearised monomers in polysaccharides are not interesting. To the best of my knowledge, they do not occur in nature due to the labile hemiacetal intermediate that would be required — but to a much greater extent due to the fact that nature optimised the connection of cyclic monosaccharides into polysaccharides and is fully content with what it has. There is no need to evolve a synthase that is able to shield the highly reactive intermediates from the surroundings and thus it didn’t happen. While the formation of oligosaccharides can also be a spontaneous process given a catalyst, linear monomers in oligosaccharides will not form that way. For most natural product or bioorganic chemists, it is by far more interesting to synthesise species that are known in nature or logical extensions thereof. While a linearised monosaccharide might qualify as an extension, it is not that logic an extension and thus of much lesser value.
{ "pile_set_name": "StackExchange" }
Q: Using the php engine inside a c# application I would like to give my users the ability to configure some php script to interact with my applycation. I would like to give the user a Memo. The user writes some code with a php syntax, then press execute. The php engine executes the code, so I can print a result. For example I would like to write something like: PHPassembly = Assembly.LoadFrom("php5ts.dll"); ExecutePHPScript(PHPassembly,StringContainingAScript); ResultVar=GetPHPVar(PHPassembly,"ResultVar"); I don't have a web server. I don't have an internet connection. Only a local application for windows. I have tryed to load the php5ts.dll, but the compiler says that I need an assembly manifest. Someone knows how to interact with php? A: You need 2 files (from php-5.3.5-Win32-VC9-x86) php-win.exe and php5ts.dll Than just place those 2 files in you executable directory and run: string code = "echo 'test';"; System.Diagnostics.Process ProcessObj = new System.Diagnostics.Process(); ProcessObj.StartInfo.FileName = "php-win.exe"; ProcessObj.StartInfo.Arguments = String.Format("-r \"{0}\"", code); ProcessObj.StartInfo.UseShellExecute = false; ProcessObj.StartInfo.CreateNoWindow = true; ProcessObj.StartInfo.RedirectStandardOutput = true; ProcessObj.Start(); ProcessObj.WaitForExit(); string Result = ProcessObj.StandardOutput.ReadToEnd(); MessageBox.Show(Result);
{ "pile_set_name": "StackExchange" }
Q: Add a KeyUsage extension on a Bouncycastle certificate request Could anyone post a Java code for adding to a PKCS10 bouncycastle certificate request an extension regarding a KeyUsage (for example a KeyUsage.keyEncipherment). I didn't find anything ad i cannot find a proper contructor for X509Extension with a KeyUsage. Thanks A: try this import org.bouncycastle.asn1.x509.KeyUsage; KeyUsage keyUsage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign); X509Extension extension = new X509Extension(true, new DEROctetString(keyUsage));
{ "pile_set_name": "StackExchange" }
Q: Two-way replication between SQL Server 2005 and SQL Server 2008 We currently have a SQL Server 2008 and SQL Server 2005 participating in one-way transactional replication of a single database. If possible we would like to set this up as a Two-way replication. What would be the preferred method of replication to achieve this? There is a moderately high latency between these servers. However, the growth of the database to be replicated is minimal. A: From your comment update, it sounds like Merge replication could work well for you, mostly due to the minimal updates. It's a lot simpler to set up and manage than two-way transactional (which is what the scary link I mentioned deals with--I should have left that for later). In a nutshell: https://blogs.technet.microsoft.com/meamcs/2011/01/06/merge-replication-step-by-step/
{ "pile_set_name": "StackExchange" }
Q: Using aws-api s3.upload gives 403 error on file location How I can access data.Location which is a response from s3.upload from an audio src? Right now when I try <audio src"{pathToFile}" ></audio> I get this error in the console GET https://my-buc.s3.amazonaws.com/693v36g6j9o7pdi6qg4gafClean.mp3 403 (Forbidden) Here is my code: const s3 = new AWS.S3({ accessKeyId: process.env.REACT_APP_S3_KEY, secretAccessKey: process.env.REACT_APP_S3_SECRET }); const params = { Bucket: "my-buc", // pass your bucket name Key: this.state.filename, Body: this.state.uploadedFile }; s3.upload( params, function(err, data) { console.log(err, data); console.log(data.Location); this.setState({ pathToFile: data.Location }); //extracting data.Location }.bind(this) ); my-buc policy { "Version": "2012-10-17", "Id": "Policy##########", "Statement": [ { "Sid": "St##########", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::699######:user/user" }, "Action": "s3:*", "Resource": "arn:aws:s3:::my-buc" }] } A: Easy Easy Fix const params = { Bucket: "my-buc", // pass your bucket name Key: this.state.filename, Body: this.state.uploadedFile ACL: "public-read" //public read allows you to use the return URL };
{ "pile_set_name": "StackExchange" }
Q: Alternative "Fibonacci" sequences and ratio convergence So the well known Fibonacci sequence is $$ F=\{1,1,2,3,5,8,13,21,\ldots\} $$ where $f_1=f_2=1$ and $f_k=f_{k-1}+f_{k-2}$ for $k>2$. The ratio of $f_k:f_{k-1}$ approaches the Golden Ratio the further you go: $$\lim_{k \rightarrow \infty} \frac{f_k}{f_{k-1}} =\phi \approx 1.618$$ Let's define a class of similar sequences $F_n$ where each $f_k$ is the sum of the previous $n$ numbers, $f_k=f_{k-1} + f_{k-2} + \dots + f_{k-n}$ so that the traditional Fibonacci sequence would be $F_2$ but we can talk about alternatives such as $$F_3 = \{1,1,1,3,5,9,17,\dots \}$$ where we initialized the values $f_1$ through $f_3$ to be $1$ and we can show that in this case $$ \lim_{k \rightarrow \infty} \frac{f_k}{f_{k-1}} \approx 1.839286755 $$ The following table gives some convergences for various values of $n$: $$ \begin{matrix} F_n & \text{Converges to} \\ \hline F_2 & \phi \\ F_3 & 1.839286755 \\ F_4 & 1.927561975 \\ F_5 & 1.965948237 \\ F_{6} & 1.983582843 \\ F_{10} & 1.999018626 \end{matrix} $$ Just by inspection, it seems that the convergence values are converging toward $2$ as $n \rightarrow \infty$. So my primary question is: What is the proof that the convergence converges to 2 (assuming it does). A: From the standard theory of linear recurrence,s $F_n$ is the positive real root of the equation $z^n = z^{n-1} + z^{n-2} + \cdots + z + 1$. Multiplying both sides by $1-z$ and rearranging, you get that $F_n$ is the positive real root of $f_n(z) = z^{n+1} - 2z^n + 1 = 0$ that is not $z = 1$. (By Descartes' rule of signs (https://en.wikipedia.org/wiki/Descartes%27_rule_of_signs), there are either 0 or 2 positive real roots of this polynomial; we know there is at least 1 , so there must be 2.) Now, we have $$ f_n(2)= 2^{n+1} - 2 \cdot 2^{n} + 1 = 1 $$ and $$f_n(2 - 1/2^{n-1}) = (2 - 1/2^{n-1})^{n+1} - 2 \cdot (2-1/2^{n-1})^n + 1. $$ We aim to show that $f_n(2-1/2^{n-1}) < 0$; then $f_n$ must have a root between $2 - 1/2^{n-1}$ and $2$. Factoring out powers of 2, we get $$f_n(2 - 1/2^{n-1}) = 2^{n+1} (1-1/2^n)^{n+1} - 2^{n+1} (1-1/2^n)^n + 1.$$ Factoring out $2^{n+1} (1-1/2^n)^n$ from the first two terms gives $$f_n(2 - 1/2^{n-1}) = 2^{n+1} (1-1/2^n)^n (-1/2^n) + 1$$ or, finally, $$f_n(2 - 1/2^{n-1}) = 1-2(1-1/2^n)^n. $$ So the result that $f_n$ has a root in the interval $[2-1/2^{n-1}, 2]$, for $n$ sufficiently large, follows from the fact that $(1-1/2^n)^n > 1/2$ for $n$ sufficiently large. Since $\lim_{n \to \infty} (1-1/2^n)^n = 1$ (use for example L'Hopital's rule) this follows. Thus $F_n \in [2 - 1/2^{n-1}, 2]$ and the desired result follows, for example, from the squeeze theorem.
{ "pile_set_name": "StackExchange" }
Q: Почему код не проходит условие? Добрый день! В моём коде нужно было ввести что-то при помощи сканера... Scanner sc = new Scanner(System.in); // создаём сканер String v; // переменную для ввода v = sc.nextLine(); // вводим if(v == "w") { // проверяем System.out.print("OK"); }else System.out.print("ERROR"); ... И если это "w" то, по логике, должно вывести "OK", но выводит "ERROR". Не могу понять почему так. Заранее спасибо. A: Нужно использовать не "==", а equals, так как вы сравниваете значения. if(v.equals("w")) { // проверяем System.out.print("OK");
{ "pile_set_name": "StackExchange" }
Q: In React how to decide whether to use componentWillReceiveProps or componentWillMount? componentWillMount is called once at first render componentWillReceiveProps is called for subsequent renders So - if I want to do some action (e.g. initialise some data in a store) when the component is rendered where do I put this code? - Which depends on a prop passed in from a higher level component. The problem is I don't know for sure if the prop will be initialised by the time the first render is called. (The prop depends on asynchronous data). So - I can't put the code in componentWillMount. But if I put it in componentWillReceiveProps and then change something higher up the component chain so that the data is fulfilled synchronously now my code in componentWillReceiveProps is never run. The motivation for this post is that I just did just that and now have to refactor a bunch of components. It seems the only solution is to put the code in both methods. There is no lifecycle method which is always called - for the first time and subsequent. But how can you know for sure if your data in top level components will necessarily be available by the time of the first render? Or for that matter necessarily not. Or maybe you can be - but then you change this. This lifecyle approach seems very fragile to me. Have I missed something? (Most likely). A: You already have the answer: put the code in both methods. However, I'd suggest to convert the props to state in both methods, and use the state as your single source of truth. componentWillMount () { this.checkAndUpdateState(this.props); } componentWillReceiveProps (nextProps) { this.checkAndUpdateState(nextProps); } checkAndUpdateState (props) { this.setState({ isLoaded: !!props.yourData }); }
{ "pile_set_name": "StackExchange" }
Q: grails command object and fields with prefixes Im using grails 1.3.7 and here is the case... Have a huge form with a few different prefixes for its fields (later used in data binding) and trying to validate thru a command object... however the lovely DOT used in prefixes is giving me a hard time and cannot get the names mapped properly in command object... any suggestion please? in the form have fields like field like this one: <input name="dealer.name" value="${dealer.name}" type="text"> and for command object: class somethingCommand { String name Map dealer = [:] static constraints = { dealer validator: { val, obj -> obj.properties["name"] != "" } } } what if.... we look at it in another way and map the parameters before passing to command object... how should I pass my parameters to a command object without using grails magic?!?!?! tnx A: you could grab the "dealer" map in the controller via def dealerMap = params["dealer"] and then create a dealer command opject by hand and bind the map content to it. def dealerCommand = new DealerCommand() bindData(dealerCommand , dealerMap) you can then use the validation of the command object as normal
{ "pile_set_name": "StackExchange" }
Q: Variable $_SESSION does not work PHP I want to add a simple "login/logout" script to my web site but it does not work. <?php if(isset($_POST["signin"])){ session_start(); $username=stripslashes($_POST["username"]); $password=stripslashes($_POST["password"]); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); $nom=checkUser($username, $password); if(!$nom=="") { $_SESSION['name'] = $nom; header("location:account.php"); } else { echo 'WRONG USERNAME OR PASSWORD';} }?> the script above is header.php which means it's included in every single page; now here is the page of "account.php" <?php if(isset($_SESSION['name'])) { include('header.php'); echo' </article> <article class="col1 pad_left1"> <p>Bienvenue '.$_SESSION['name'].'</p> </article> </header> </div>'; include('footer.php');} header("location:index.php"); ?> The problem is that i always get to the index.php even if i'm logged in as if this test if(isset($_session['name'])) is always false. A: I guess you rather want to use if($nom!="") than if(!$nom==""). Additionally, you need to call session_start() before you can use $_SESSION (you're doing it the other way round at the moment).
{ "pile_set_name": "StackExchange" }
Q: Unhandled error TypeError: snapshot.val is not a function when using forEach Firebase Cloud Functions I'm writing a Firebase Cloud Function, with an HTTPS trigger, and I am starting more that one read operation at once using Promise.all(arrayOfPromises), when all of the promises are fulfilled the then(snapshotContainsArrayOfSnapshots) method gets triggered, and I try to iterate the snapshotContainsArrayOfSnapshots with forEach(snapshot) method, but I get this Error: Unhandled error TypeError: snapshot.val is not a function Here is the code: f let promisesArray = [] for(let i = 0; i < 10; i++){ const promise = db.ref(`/questions/en/${i}`) promisesArray.push(promise) } return Promise.all(promisesArray) .then((snapshotContainsArrayOfSnapshots) => { let data = [] snapshotContainsArrayOfSnapshots.forEach((snapshot) => { data.push(snapshot.val()) }) return JSON.stringify(data) }) Remember: This ISN'T an onWrite trigger so I dont need to call change.after. A: What you are adding to the promisesArray are References, see doc here For each of your references, you should query the data at the reference with the once() method (doc here) and it is the promise returned by this method that you need to add to your promisesArray. So do as follows: let promisesArray = [] for(let i = 0; i < 10; i++){ const promise = db.ref(`/questions/en/${i}`).once('value'); promisesArray.push(promise) } return Promise.all(promisesArray) .then((snapshotContainsArrayOfSnapshots) => { let data = [] snapshotContainsArrayOfSnapshots.forEach((snapshot) => { data.push(snapshot.val()) }) return JSON.stringify(data) })
{ "pile_set_name": "StackExchange" }
Q: clojure.lang.Lazysez cannot be cast to clojure.lang.IFn Hey im making an A* search on a eight puzzle and I have 2 main questions. FIXED: First I get clojure.lang.Lazysez cannot be cast to clojure.lang.IFn when I run this on the line in the second part of the polymorph in the for loop but im not sure why. Here is my code: (defn a-star ([board history] (if (at-end? board) (println board) ( (let [options (filter #(possible-move? % board) *moves*) move (into (pm/priority-map) (for [move options] [move (global-man-dis (move-tile board move))]))] (for [pair move :let [next-move (key pair)]] (do (println (move-tile board next-move)) (a-star (move-tile board next-move) next-move (conj history board)) ) ) ) ))) ([board prev-move history] (if (or (at-end? board) (history-check history board)) (println board) ( (let [options (get-queue board (dont-go-back prev-move)) move (into (pm/priority-map) (for [move options] [move (global-man-dis (move-tile board move))]))] (for [pair move :let [next-move (key pair)]] (do (println (move-tile board next-move)) (a-star (move-tile board next-move) next-move (conj history board)) ) ) ) )))) (defn -main [& args] (println "insert a list all numbers no spaces or letters") (def board (mapv (fn [^Character c] (Character/digit c 10)) (read-line))) ;(def testt [0 8 4 7 2 1 3 5 6]) ;(def testt [1 2 3 5 4 6 8 0 7]) (a-star board []) ) Tried since post: removing "else" parens around let statement but now returns nothing FIXED removed the else parenthesis and changed for to doseq as for is lazy and wont output anything in this case. ill ask the other question seperatly again A: Some of your base cases in a-star return lazy sequences. You are calling the output of a-star as a function, because of the extra pair of parens around the let statements.
{ "pile_set_name": "StackExchange" }
Q: Deleting Rows from a UITableView That has Multiple Sections I'm developing an iPad Application, in which one of the screens has an embedded tableview with multiple sections. Each section is populated by its own array (array1, and array2). I've created a button that puts this table into editting mode. However, I need to change my $tableView:commitEditingStyle:forRowAtIndexPath somehow to determine what section the selected row is in, and delete the entry from the associated array as well. Does anyone have any ideas? -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{ if(editingStyle == UITableViewCellEditingStyleDelete){ //This is the line i need to change... [array1 removeObjectAtIndex:indexPath.row]; [myTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; } } A: Looks like you need to remove the row from the correct array... using a switch statement on the sections might work (but only if there's a set number of sections, which you seem to indicate there is) So where you're removing the object from the array, make sure you're removing it from the correct array based on the section. switch (indexPath.section) { case 0 [array0 removeObjectAtIndex:indexPath.row]; break; case 1 [array1 removeObjectAtIndex:indexPath.row]; break; } etc.
{ "pile_set_name": "StackExchange" }
Q: Laravel InvalidArgumentException hi all im having issue with a script i am helping a friend install InvalidArgumentException in FileViewFinder.php line 137: View [admin.cms] not found. in FileViewFinder.php line 137 at FileViewFinder->findInPaths('admin.cms', array('/volume1/web/resources/views')) in FileViewFinder.php line 79 at FileViewFinder->find('admin.cms') in Factory.php line 174 at Factory->make('admin.cms', array('data' => ''), array()) in helpers.php line 858 at view('admin.cms', array('data' => '')) in CmsController.php line 70 at CmsController->dashboard() at call_user_func_array(array(object(CmsController), 'dashboard'), array()) in Controller.php line 55 at Controller->callAction('dashboard', array()) in ControllerDispatcher.php line 44 at ControllerDispatcher->dispatch(object(Route), object(CmsController), 'dashboard') in Route.php line 189 at Route->runController() in Route.php line 144 at Route->run(object(Request)) in Router.php line 653 at Router->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 53 at Pipeline->Illuminate\Routing\{closure}(object(Request)) in RedirectIfNotCms.php line 24 at RedirectIfNotCms->handle(object(Request), object(Closure)) in Pipeline.php line 137 at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckLanguage.php line 27 at CheckLanguage->handle(object(Request), object(Closure)) in Pipeline.php line 137 at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 at Pipeline->Illuminate\Routing\{closure}(object(Request)) in SubstituteBindings.php line 41 at SubstituteBindings->handle(object(Request), object(Closure)) in Pipeline.php line 137 at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Authenticate.php line 43 at Authenticate->handle(object(Request), object(Closure), 'cms') in Pipeline.php line 137 at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 at Pipeline->Illuminate\Routing\{closure}(object(Request)) in VerifyCsrfToken.php line 65 at VerifyCsrfToken->handle(object(Request), object(Closure)) in Pipeline.php line 137 at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 at Pipeline->Illuminate\Routing\{closure}(object(Request)) in ShareErrorsFromSession.php line 49 at ShareErrorsFromSession->handle(object(Request), object(Closure)) in Pipeline.php line 137 at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 at Pipeline->Illuminate\Routing\{closure}(object(Request)) in StartSession.php line 64 at StartSession->handle(object(Request), object(Closure)) in Pipeline.php line 137 at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 at Pipeline->Illuminate\Routing\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37 at AddQueuedCookiesToResponse->handle(object(Request), object(Closure)) in Pipeline.php line 137 at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 at Pipeline->Illuminate\Routing\{closure}(object(Request)) in EncryptCookies.php line 59 at EncryptCookies->handle(object(Request), object(Closure)) in Pipeline.php line 137 at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 104 at Pipeline->then(object(Closure)) in Router.php line 655 at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 629 at Router->dispatchToRoute(object(Request)) in Router.php line 607 at Router->dispatch(object(Request)) in Kernel.php line 268 at Kernel->Illuminate\Foundation\Http\{closure}(object(Request)) in Pipeline.php line 53 at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Debugbar.php line 51 at Debugbar->handle(object(Request), object(Closure)) in Pipeline.php line 137 at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 46 at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in Pipeline.php line 137 at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 104 at Pipeline->then(object(Closure)) in Kernel.php line 150 at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 117 at Kernel->handle(object(Request)) in index.php line 53 at fileviewfinder.php 137 protected function findInPaths($name, $paths) { foreach ((array) $paths as $path) { foreach ($this->getPossibleViewFiles($name) as $file) { if ($this->files->exists($viewPath = $path.'/'.$file)) { return $viewPath; } } } throw new InvalidArgumentException("View [$name] not found."); } /** Im not sure what issue is i have checked that the paths are correct. any help or a point in direction would be greatly appreciated Server is Running Apache 2.4 and php version 7.2 Im not sure what issue is i have checked that the paths are correct. any help or a point in direction would be greatly appreciated Server is Running Apache 2.4 and php version 7.2 A: Make sure that your view file is in resources folder, and it got .blade.php as extension. you can do this as well dd(view()->exists($yourview)); it should return true if the view exists, false if not. Start from there and you will get to the solution.
{ "pile_set_name": "StackExchange" }
Q: Need to Format Current Date in Specific Format in React Native using Libraries Actually in my app. I am trying to display current date & time in a specific format like this " 27/02/2019 1:40 PM ". I have done this by making use of custom formatting codes. But what i actually need is, I need to achieve this by making use of libraries. Thanks for helping.! Using this:(Manually formatting Date & Time) var d = new Date(); var date = d.getDate(); var month = d.getMonth() + 1; var year = d.getFullYear(); var hours = d.getHours(); var ampm = hours >= 12 ? 'PM' : 'AM'; hours = hours % 12; hours = hours ? hours : 12; var min = d.getMinutes(); min = min < 10 ? '0'+min : min; var result = date + '/' + month + '/' + year + ' ' + hours + ':' + min + ' ' + ampm; console.log(result); //Prints DateTime in the above specified format A: Use moment.js https://momentjs.com/ moment().format('DD/MM/YY h:mm A') will give you your desired output.
{ "pile_set_name": "StackExchange" }
Q: Is is possible to read in a list of numbers in SML? I'm trying to make a program in SML that will read in a series/list/sequence of numbers from the user, process the numbers, and output the result. I don't know how many numbers the user will input. The program can either read in all the numbers and output the results all together or read and output one at a time. I don't care whether the input is in a separate file or manually input at a console. What do I need to do to be able to read input? fun fact x = if x<2 then 1 else x*fact(x-1); let val keepgoing:bool ref = ref true in while !keepgoing do let val num = valOf(TextIO.inputLine TextIO.stdIn) in print( Int.toString( fact( valOf( Int.fromString( num ) ) ) ) ); keepgoing := (null(explode(num))) end end; Sorry about the convoluted conversions. If you also know an easier way to read in integers, I'd appreciate that, too. A: Your logic is just flawed here. You want keepgoing := not (null (explode num)). Right? It works fine for me with that change. You need to implement removal of the final newline (so null explode does what you want) and parsing a line with more than one number, but you basically have the right idea.
{ "pile_set_name": "StackExchange" }
Q: What are the best Pre-Processing techniques for Sentiment Analysis.? I am trying to classify a dataset of reviews in to two classes say class A and class B. I am using LightGBM to classify. I have changed the parameters for the classifier many times but I can't get a huge difference in the results. I think the problem is with the pre-processing step. I defined a function as shown below to take care of pre-processing. I used Stemming and removed stopwords. I don't know what I am missing. I have tried LancasterStemmer and PorterStemmer stops = set(stopwords.words("english")) def cleanData(text, lowercase = False, remove_stops = False, stemming = False, lemm = False): txt = str(text) txt = re.sub(r'[^A-Za-z0-9\s]',r'',txt) txt = re.sub(r'\n',r' ',txt) if lowercase: txt = " ".join([w.lower() for w in txt.split()]) if remove_stops: txt = " ".join([w for w in txt.split() if w not in stops]) if stemming: st = PorterStemmer() txt = " ".join([st.stem(w) for w in txt.split()]) if lemm: wordnet_lemmatizer = WordNetLemmatizer() txt = " ".join([wordnet_lemmatizer.lemmatize(w) for w in txt.split()]) return txt Are there any more pre-processing steps to be done to get a better accuracy.? URL for the dataset : Dataset EDIT : Parameters that I used are as mentioned below. params = {'task': 'train', 'boosting_type': 'gbdt', 'objective': 'binary', 'metric': 'binary_logloss', 'learning_rate': 0.01, 'max_depth': 22, 'num_leaves': 78, 'feature_fraction': 0.1, 'bagging_fraction': 0.4, 'bagging_freq': 1} I have altered the depth and num_leaves parameters along with others. But the accuracy is kind of stuck at a certain level.. A: There are a few things to consider. First of all your training set is not balanced - the class distribution is ~ 70%/30%. You need to consider this fact in training. What types of features are you using? Using the right set of features could improve your performance.
{ "pile_set_name": "StackExchange" }
Q: EF Core Missing Method HasIndex I've just started to migrate to a SQL database and running into a problem with a MissingMethodException being thrown. Here is the configuration class that is throwing the error: using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Project.Core.Entities.Users; namespace Project.Persistance.Configuration.Users { public class UserClaimTypeConfiguration : IEntityTypeConfiguration<UserClaimType> { public void Configure(EntityTypeBuilder<UserClaimType> builder) { builder.HasKey(entity => entity.Id); builder.Property(entity => entity.Name) .IsRequired() .HasMaxLength(30); builder.HasIndex(entity => entity.Name); builder.Property(entity => entity.Description) .IsRequired(false) .HasMaxLength(100); builder.Ignore(entity => entity.ValueType); } } } And this is error I am getting in the console: PM> add-migration user System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.MissingMethodException: Method not found: 'Microsoft.EntityFrameworkCore.Metadata.Builders.IndexBuilder Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder`1.HasIndex(System.Linq.Expressions.Expression`1<System.Func`2<!0,System.Object>>)'. at Project.Persistance.Configuration.Users.UserClaimTypeConfiguration.Configure(EntityTypeBuilder`1 builder) at Microsoft.EntityFrameworkCore.ModelBuilder.ApplyConfiguration[TEntity](IEntityTypeConfiguration`1 configuration) I've tried 'Goggle' and the Microsoft docs but can't seem to find any reference to this issue - so it must be my setup. Just can't figure out what is causing it! A: Breaking change in .NET Core 3.0 preview 3. Fixed in preview 4: ASP.NET Core Issue 8467 (RESOLVED)
{ "pile_set_name": "StackExchange" }
Q: javascript function does not work I am currently in the middle of the development of a website. If a user presses a button an javascript function needs to be called. I simplified this function to: <html> <head> <script type="text/javascript"> function newProd(number,customer,software,hardware,name) { //I simplified this function alert('number is: '+number+'customer is: '+customer+' software is: '+software+' hardware is: '+hardware+' name is: '+name); } </script> </head> <body> <input type="text" name="textfieldCustomer"><br> <input type="text" name="textfieldSoftware"><br> <input type="text" name="textfieldHardware"><br> <input type="text" name="textfieldDescription"><br> <input type="button" name="button" value="go to function" onClick="newProd('a number',textfieldCustomer.value,textfieldSoftware.value,textfieldHardware.value,textfieldDescription.value)"> </body> when the user presses the button in Internet explorer, the function works perfectly! Unfortunately the function does not work in Chrome or Safari. Does anyone have any idea what is going wrong? A: The form fields are not supposed to be defined as global variables. Maybe in IE they are but that's not a behavior you can depend on. Try this: onClick="newProd('a number', this.form.textfieldCustomer.value, this.form.textfieldSoftware.value, this.form.textfieldHardware.value, this.form.textfieldDescription.value)"> Oh, and add a form to wrap the inputs of course. Demo: http://jsfiddle.net/kdUMc/
{ "pile_set_name": "StackExchange" }
Q: Logic - Need to find overlapping ranges of numbers Say I have an array of "numbers" object with a "startNo" integer and "endNo" integer. There can be multiple "numbers" in the array and I want to get a new array with modified objects which will only have the ranges with no overlap. For eg: if the array has: number ( startNo:1 endNo:3) ( startNo:1 endNo:7) ( startNo:2 endNo:9) ( startNo:15 endNo:18) ( startNo:50 endNo:60) ( startNo:55 endNo:65) I want to get an array like this: number ( startNo:1 endNo:9) ( startNo:15 endNo:18) ( startNo:50 endNo:65) I have been trying hands on different approaches with structs, fors and everything but all I get is multi-level-confusion. I am working on objective-C platform if that helps To add: The startPage can be a big number and endPage can be a small number. A: //It's written in C# language. But concept can be implemented in any programming language. public class Range { public int startNo { get; set; } public int stopNo { get; set; } public Range(int start, int stop) { startNo = start; stopNo = stop; } } public void GetUniqueRanges() { var rangeList = new List<Range>(); rangeList.Add(new Range(7,4)); rangeList.Add(new Range(3, 15)); rangeList.Add(new Range(54, 35)); rangeList.Add(new Range(45, 60)); rangeList.Add(new Range(60,75)); rangeList.Add(new Range(76,100)); rangeList.Add(new Range(6,10)); rangeList.Add(new Range(16,24)); rangeList.Add(new Range(19,34)); var sorted = new List<Range>(); foreach (var range in rangeList) { var item = new Range(Math.Min(range.startNo, range.stopNo), Math.Max(range.startNo, range.stopNo)); sorted.Add(item); } var result = new List<Range>(); sorted = sorted.OrderBy(x => x.startNo).ToList(); var counter = sorted.Count; for (var i = 0; i < counter; ) { var item = new Range (sorted[i].startNo, sorted[i].stopNo ); var j = i + 1; for (; j < counter; j++) { if (sorted[j].startNo <= item.stopNo) { item.stopNo =Math.Max(item.stopNo, sorted[j].stopNo); } else { break; } } i = j; result.Add(item); } }
{ "pile_set_name": "StackExchange" }
Q: How to remove text from a specific line in file without creating unwanted space using c#? I'm trying to remove text from a specific line in the file that i have created "Test.txt". Here is the text written in Test.txt: 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 Now what i want to happen is when i'm going to remove 2 - 4 in the 2nd iteration, the output should be like this: 1 2 3 4 5 1 5 1 2 3 4 5 What i want is to remove only spaces that the corresponding text was removed from and preferably without involving other spaces. But when i tried the code it gave me this output: 1 2 3 4 5 1 5 1 2 3 4 5 As you can see the above output, that is the unwanted space that i'm talking about. Below is the code that I have tried: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestCode { class Program2 { static void Main() { lineChanger("", @"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\Test.txt", 8); lineChanger("", @"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\Test.txt", 9); lineChanger("", @"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\Test.txt", 10); } static void lineChanger(string newText, string fileName, int line_to_edit) { string[] arrLine = File.ReadAllLines(fileName); arrLine[line_to_edit - 1] = newText; File.WriteAllLines(fileName, arrLine); } } } Also please feel free to suggest any proper techniques and kindly include actual examples. A: Please see is this ok? int removeAt = 7; //or any thing you want int linesToRemove = 3; //or any thing you want string s = System.IO.File.ReadAllText("Test.txt"); List<string> arr = s.Split("\n".ToCharArray()).ToList(); for (int i = 0; i < linesToRemove; i++) arr.RemoveAt(removeAt); string result = ""; foreach (string str in arr) { result += str; } System.IO.File.WriteAllText("Test.txt", result); I'm happy that you say it works for you, and here i add another solution, maybe in some cases you need to use this: int removeAt = 7; //or any thing you want int linesToRemove = 3; //or any thing you want string s = System.IO.File.ReadAllText("Test.txt"); List<string> arr = s.Split(new char[] { '\n' }).ToList(); List<int> realBareRows = new List<int>(); for (int i = 0; i < arr.Count; i++) { if (string.IsNullOrEmpty(arr[i].Replace("\r", ""))) realBareRows.Add(i); } List<string> newArr = s.Split(System.Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList(); foreach (int j in realBareRows) newArr.Insert(j, "\n"); for (int i = 0; i < linesToRemove; i++) newArr.RemoveAt(removeAt); string result = ""; foreach (string str in newArr) { result += str + System.Environment.NewLine; } System.IO.File.WriteAllText("Test.txt", result);
{ "pile_set_name": "StackExchange" }
Q: Activate App but keep script running Applescript I would like to open another app (applescript applet) with Applescript but still move on to the next line in my script. I though it would automatically do this but it does not for some reason. Here is my code: ... if selectedMenu is "1" then set theDisplay to "⬟" my display(theDisplay) tell application "/Users/Patrick/Documents/Programming/Applescript/Applications/NoWatch.app/Contents/Resources/Both.app" to activate tell application "/Users/Patrick/Documents/Programming/Applescript/Applications/NoWatch.app/Contents/Resources/VNC.app" to quit saving no tell application "/Users/Patrick/Documents/Programming/Applescript/Applications/NoWatch.app/Contents/Resources/SSH.app" to quit saving no ... I included the part after the activation just incase that is what is causing this. Also, after closing the app I activated, the script continues like normal. A: ignoring application responses tell application "Finder" to activate end ignoring
{ "pile_set_name": "StackExchange" }
Q: Next/Done button using Swift with textFieldShouldReturn I have a MainView that adds a subview (signUpWindow) when a sign up button is pressed. In my signUpWindow subview (SignUpWindowView.swift), I set up each field with a function, as an example: func confirmPasswordText() { confirmPasswordTextField.frame=CGRectMake(50, 210, 410, 50) confirmPasswordTextField.placeholder=("Confirm Password") confirmPasswordTextField.textColor=textFieldFontColor confirmPasswordTextField.secureTextEntry=true confirmPasswordTextField.returnKeyType = .Next confirmPasswordTextField.clearButtonMode = .WhileEditing confirmPasswordTextField.tag=5 self.addSubview(confirmPasswordTextField) } I have the keyboard moving the signUpWindow up and down when it appears and disappears in the MainView. SignUpWindowView implements the UITextFieldDelegate My problem is that I am trying to configure the Next/Done button on the keyboard and am not sure which view (MainView or SignUpWindowView) to add the textFieldShouldReturn function. I have tried both, but can't even get a println to fire to test to see if the function is even being executed. Once I get the textFieldShouldReturn to fire, I am confident I can execute the necessary code to get the Next/Done buttons to do what I want, and will post the final solution to include the Next/Done function. UPDATED to include an abbreviated version of SignUpWindowView.swift import UIKit class SignUpWindowView: UIView,UITextFieldDelegate { let firstNameTextField:UITextField=UITextField() let lastNameTextField:UITextField=UITextField() override func drawRect(rect: CGRect){ func firstNameText(){ firstNameTextField.delegate=self firstNameTextField.frame=CGRectMake(50, 25, 200, 50) firstNameTextField.placeholder="First Name" firstNameTextField.returnKeyType = .Next self.addSubview(firstNameTextField) } func lastNameText(){ lastNameTextField.delegate=self lastNameTextField.frame=CGRectMake(260, 25, 200, 50) lastNameTextField.placeholder="Last Name" lastNameTextField.returnKeyType = .Done self.addSubview(lastNameTextField) } func textFieldShouldReturn(textField: UITextField!) -> Bool{ println("next button should work") if (textField === firstNameTextField) { firstNameTextField.resignFirstResponder() lastNameTextField.becomeFirstResponder() } return true } firstNameText() lastNameText() } A: You need to implement UITextFieldDelegate in your class and set that object as the delegate for the UITextField. Then implement the method textFieldShouldReturn: like this: func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() if textField == someTextField { // Switch focus to other text field otherTextField.becomeFirstResponder() } return true } In your example you are missing this line: confirmPasswordTextField.delegate = self If you have implemented the delegate of course. A: I was attempting to test my textfields in the SignUpWindowView.swift, which is where all of the textFields are created. But, since I place SignUpWindowView into my MainViewController as a subview, all of my UITextField "handling" needed to be done in the MainView and NOT its subview. So here is my entire code (at the moment) for my MainViewController, which handles moving my SignUpWindowView up/down when the keyboard is shown/hidden and then moves from one field to the next. When the user is in the last text field (whose keyboard Next button is now set to Done in the subview) the keyboard tucks away and the user can then submit the form with a signup button. MainViewController: import UIKit @objc protocol ViewControllerDelegate { func keyboardWillShowWithSize(size:CGSize, andDuration duration:NSTimeInterval) func keyboardWillHideWithSize(size:CGSize,andDuration duration:NSTimeInterval) } class ViewController: UIViewController,UITextFieldDelegate { var keyboardDelegate:ViewControllerDelegate? let signUpWindow=SignUpWindowView() let signUpWindowPosition:CGPoint=CGPointMake(505, 285) override func viewDidLoad() { super.viewDidLoad() // Keyboard Notifications NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) // set the textFieldDelegates signUpWindow.firstNameTextField.delegate=self signUpWindow.lastNameTextField.delegate=self signUpWindow.userNameTextField.delegate=self signUpWindow.passwordTextField.delegate=self signUpWindow.confirmPasswordTextField.delegate=self signUpWindow.emailTextField.delegate=self } func keyboardWillShow(notification: NSNotification) { var info:NSDictionary = notification.userInfo! let keyboardFrame = info[UIKeyboardFrameEndUserInfoKey] as! NSValue let keyboardSize = keyboardFrame.CGRectValue().size var keyboardHeight:CGFloat = keyboardSize.height let animationDurationValue = info[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber var animationDuration : NSTimeInterval = animationDurationValue.doubleValue self.keyboardDelegate?.keyboardWillShowWithSize(keyboardSize, andDuration: animationDuration) // push up the signUpWindow UIView.animateWithDuration(animationDuration, delay: 0.25, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.signUpWindow.frame = CGRectMake(self.signUpWindowPosition.x, (self.signUpWindowPosition.y - keyboardHeight+140), self.signUpWindow.bounds.width, self.signUpWindow.bounds.height) }, completion: nil) } func keyboardWillHide(notification: NSNotification) { var info:NSDictionary = notification.userInfo! let keyboardFrame = info[UIKeyboardFrameEndUserInfoKey] as! NSValue let keyboardSize = keyboardFrame.CGRectValue().size var keyboardHeight:CGFloat = keyboardSize.height let animationDurationValue = info[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber var animationDuration : NSTimeInterval = animationDurationValue.doubleValue self.keyboardDelegate?.keyboardWillHideWithSize(keyboardSize, andDuration: animationDuration) // pull signUpWindow back to its original position UIView.animateWithDuration(animationDuration, delay: 0.25, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.signUpWindow.frame = CGRectMake(self.signUpWindowPosition.x, self.signUpWindowPosition.y, self.signUpWindow.bounds.width, self.signUpWindow.bounds.height) }, completion: nil) } func textFieldShouldReturn(textField: UITextField) -> Bool { switch textField { case signUpWindow.firstNameTextField: signUpWindow.lastNameTextField.becomeFirstResponder() break case signUpWindow.lastNameTextField: signUpWindow.userNameTextField.becomeFirstResponder() break case signUpWindow.userNameTextField: signUpWindow.passwordTextField.becomeFirstResponder() break case signUpWindow.passwordTextField: signUpWindow.confirmPasswordTextField.becomeFirstResponder() break case signUpWindow.confirmPasswordTextField: signUpWindow.emailTextField.becomeFirstResponder() break default: textField.resignFirstResponder() } return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillDisappear(animated: Bool) { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } @IBAction func signup() { signUpWindow.frame=CGRectMake(signUpWindowPosition.x, signUpWindowPosition.y, 485,450) signUpWindow.backgroundColor=UIColor.clearColor() self.view.addSubview(signUpWindow) } } A: Using tags makes it easier. Assign tags in ascending order to all the text fields you are using on your screen. func textFieldShouldReturn(_ textField: UITextField) -> Bool { let textTag = textField.tag+1 if let nextResponder = textField.superview?.viewWithTag(textTag) as UIResponder { //textField.resignFirstResponder() nextResponder.becomeFirstResponder() } else { // stop editing on pressing the done button on the last text field. self.view.endEditing(true) } return true }
{ "pile_set_name": "StackExchange" }
Q: Auto Fill in tr's Javascript edit I got this Javascript from here.. Here's JS: <script> var tables = document.getElementsByTagName('table'); var table = tables[tables.length - 1]; var rows = table.rows; for(var i = 0, td; i < rows.length; i++){ td = document.createElement('td'); td.appendChild(document.createTextNode(i + 1)); rows[i].insertBefore(td, rows[i].firstChild); } </script> This creates a td before all td's like example if we create this table: <table> <tr> <td>First TD </td> <tr></tr> <td>Second TD </td> </tr> </table> This script will create this like this.. <table> <tr> <td>1 </td> <td>First TD </td> </tr> <tr> <td>2 </td> <td>Second TD </td> </tr> </table> I want to exclude the TH part to create a td before that.. A: I'm not sure if I understand you correctly, but you would like to do something like I did in this jsFiddle: http://jsfiddle.net/YbM97/3/ I modified the for-loop and made the first 1 to do a TH element before.EDITED: Added class "not-sortable" to th elements. Javascript: var tables = document.getElementsByTagName('table'); var table = tables[tables.length - 1]; var rows = table.rows; var th = document.createElement('th'); th.className = "not-sortable"; th.appendChild(document.createTextNode("ID")); rows[0].insertBefore(th, rows[0].firstChild); for(var i = 1, td; i < rows.length+1; i++){ var td = document.createElement('td'); td.appendChild(document.createTextNode(i)); rows[i].insertBefore(td, rows[i].firstChild); } HTML: <table> <tr> <th class="not-sortable">Name</th> </tr> <tr> <td>First TD</td> </tr> <tr> <td>Second TD</td> </tr> </table>
{ "pile_set_name": "StackExchange" }
Q: How to reject a promise on NativeScript - Angular 2 I have a code that works in angular 2, but when I try to use it in a nativescript project fails. I´m trying to reject a promise like this: login(credentials:Credentials):Promise<User> { if (!valid) { return Promise.reject<User>("Invalid password"); }else { return Promise.resolve(new User("some user")); } } And I get this error: Error:(32, 22) TS2346: Supplied parameters do not match any signature of call target. A: You missed to return promise when you Rejected it. Error directly says that you aren't returning Promise<User> from function. As method return type is Promise<User>, it always return that object. PS: After edit in OP found that method can return two types of data, on success it would be User object, on reject its string. So for such case I'd prefer you to change the method return type to User | string Code login(credentials:Credentials):Promise<User | string> { if (!valid) { //returned promise here which was missing and failing compilation return Promise.reject("Invalid password"); }else { return Promise.resolve(new User("some user")); } }
{ "pile_set_name": "StackExchange" }
Q: Detecting when a tcp client is not active for more than 5 seconds Im trying to make a tcp communication, where the server sends a message every x seconds through a socket, and should stop sending those messages on a certain condition where the client isnt sending any message for 5 seconds. To be more detailed, the client also sends constant messages which are all ignored by the server on the same socket as above, and can stop sending them at any unknown time. The messages are, for simplicity, used as alive messages to inform the server that the communication is still relevant. The problem is that if i want to send repeated messages from the server, i cannot allow it to "get busy" and start receiving messages instead, thus i cannot detect when a new messages arrives from the other side and act accordingly. The problem is independent of the programming language, but to be more specific im using python, and cannot access the code of the client. Is there any option of receiving and sending messages on a single socket simultaneously? Thanks! A: Option 1 Use two threads, one will write to the socket and the second will read from it. This works since sockets are full-duplex (allow bi-directional simultaneous access). Option 2 Use a single thread that manages all keep alives using select.epoll. This way one thread can handle multiple clients. Remember though, that if this isn't the only thread that uses the sockets, you might need to handle thread safety on your own
{ "pile_set_name": "StackExchange" }
Q: problem in action script3 function prevFrame i made a button if you rollover on it it's size is larger i want if you roll out on it it's size return back to it's original size i use this function prevFrame but my problem is when i use it it stops on the previous frame only and i want to stop from the starting A: You can label your frames an use the gotoAndStop() method function onRollover(event:MouseEvent):void { gotoAndStop('largeSize'); } function onRollOut(event:MouseEvent):void { gotoAndStop('normalSize'); }
{ "pile_set_name": "StackExchange" }
Q: MariaDB COLUMN_JSON query returns binary I've been trying to use dynamic columns with an instance of MariaDB v10.1.12. First, I send the following query: INSERT INTO savedDisplays (user, name, body, dataSource, params) VALUES ('Marty', 'Hey', 'Hoy', 'temp', COLUMN_CREATE('type', 'tab', 'col0', 'champions', 'col1', 'averageResults')); Where params' type was defined as a blob, just like the documentation suggests. The query is accepted, the table updated. If I COLUMN_CHECK the results, it tells me it's fine. But when I try to select: "SELECT COLUMN_JSON(params) AS params FROM savedDisplays; I get a {type: "Buffer", data: Array} containing binary returned to me, instead of the {"type":"tab", "col0":"champions", "col1":"averageResults"} I expect. EDIT: I can use COLUMN_GET just fine, but I need every column inside the params field, and I need to check the type property first to know what kind of and how many columns there are in the JSON / params field. I could probably make it work still, but that would require multiple queries, as opposed to only one. Any ideas? A: Try: SELECT CONVERT(COLUMN_JSON(params) USING utf8) AS params FROM savedDisplays In MariaDB 10 this works at every table: SELECT CONVERT(COLUMN_JSON(COLUMN_CREATE('t', text, 'v', value)) USING utf8) as json FROM test WHERE 1 AND value LIKE '%12345%' LIMIT 10; output in node.js [ TextRow { json: '{"t":"test text","v":"0.5339044212345805"}' } ]
{ "pile_set_name": "StackExchange" }
Q: Biztalk Sharepoint Adapter Permissions Error Pretty basic question I think, but I'm kind of at a loss. I'm trying to do some Biztalk->Sharepoint integration. Eventually I'll be moving to dynamic ports etc. but right now all I'm trying to do is add an item to a list in sharepoint. I have a personal site on the company intranet where I have "Full control". The list has two columns, and my schema has two elements. Very similar to this blog. I'm pretty sure it's the right structure. I've gone to my biztalk host (BiztalkServerApplication) and made it use my Logon: "domain\username". This is the same logon that has "full permission" on my sharepoint site. When I don't use this account and try to set it in the adapter instead, I get a "System.ServiceModel.CommunicationObjectFaultedException"... I've kind of gone off of this link for help in terms of providing my credentials to this Host Instance. Now I'm getting a "Access denied. You do not have permission..." Error when I try to send this list message! (From a file if that matters). I'm at a loss here. My host instance has my domain credentials. I'm (nearly) positive they're identical to what's on the host site. I don't know what I'm doing wrong because it seems like I'm following everything perfectly to the letter from what I've found on the internet. Though there's hardly anything when it comes to using the BT2013 Sharepoint Adapter. What are common mistakes that people make with this adapter? I don't feel like I should have to go to our Systems guys to change something on the sharepoint site. Any and all help appreciated! A: You don't mention what version of SharePoint you are using. There are limitations on the version of SharePoint you can interact with using the new BizTalk 2013 adapter with Client Side Object Model (CSOM). The CSOM only allows you to interact with SharePoint services on SP2010, SP2013 and SharePoint Online. It's even more limited with CSOM disabled - this means you would be using Service Side Object Model (SSOM) and you are limited to only SharePoint 2010. The BizTalk 2013 SharePoint Services Adapter using CSOM requires you install Windows Identity Foundation, or turn it on as a feature, depending on which version of the OS you are running the BizTalk Server. Ensure you've correctly setup a proper receive location as well as the send port (be it static or dynamic): http://msdn.microsoft.com/en-us/library/jj735586(v=bts.80).aspx If you've chosen to disable CSOM on the SharePoint Adapter, you would have had to install a service on the server hosting SharePoint (assuming it's different to the BizTalk Server). In this case you need to ensure the IIS apppool hosting that server uses a domain account. In this scenario (with CSOM disabled) you can also get access denied issues if you have a double hop. If there are three computers involved (BizTalk Server, SharePoint Services and SQL Server) and you haven't enabled kerberos/setspn (on the domain accounts for SQL and the AppPool account hosting the sharepoint service) then you will have authentication issues. You can determine this by checking the IIS logs. You would see in your IIS logs a failed status code, eg. 401.2, followed by a 401.1, following by another 4xx error. A: Looks like long story short what I THOUGHT was a list was in fact not a list. I was trying to add an element to something that looked and acted exactly like every other SP list but wasn't one which is what produced the permissions error. Awesome. I opened up InfoPath and created a new list on my "personal" sharepoint, then targeted that with my Biztalk Sharepoint adapter with hardcoded values for the columns. After dropping in a message, it worked correctly. For more useful information see @lantrix 's reply to this question.
{ "pile_set_name": "StackExchange" }
Q: Calculating continuation of movement I have a sprite that is controlled using the device's accelerometer. My code for that is like this: // for rotation double myRadians = Math.atan2(previousRoll, previousPitch); float myDegress = Math.round(((myRadians*180)/Math.PI)); // set rotation of sprite sprite.setRotation(myDegress+90); // for movement float yChange = Math.round(previousRoll); float xChange = Math.round(previousPitch); float yMove = Math.round(yChange/1.5); float xMove = Math.round(xChange/1.5); // set the position of the sprite sprite.setPosition(sprite.getX()+xMove, sprite.getY()+yMove); Which works just fine. When the user presses the back key the game gets paused, and, obviously, stops the sprite from moving. But say if the sprite was just about to collide, the user would just be able to pause, then tilt the device in the opposite direction and voila! They get away! All I have here is the speed, which is defined by the device's tilt, and I do store the tilt before the pause event is fired and use that for the movement when the game resumes. So, how would I go about preventing the above? I was thinking I could move the sprite to the final position that it would have ended up if the game had not been paused. How would I calculate the distance from the current position to the end position, given that I have the speed. I know distance = speed * time, so is there a way to get time in this context? Or is there another way of doing this? I'm not too good with Physics, as you have probably figured =]] Anyway, thanks in advance. A: Finally, I solved my issue, what I done was found the final position based on distance = speed * time. So, now my sprite moves to the "final position". Thanks for the help.
{ "pile_set_name": "StackExchange" }
Q: hdf5 in maven project I'm trying to import hdf.hdf5lib.H5 into my maven project in NetBeans. It has this as import line import hdf.hdf5lib.H5; as suggested here: https://support.hdfgroup.org/products/java/JNI3/jhi5/index.html However, it throws this exception: java.lang.ExceptionInInitializerError Caused by: java.lang.RuntimeException: Uncompilable source code - package hdf.hdf5lib does not exist NetBeans already warned me about it by saying at the import line "packadge does not excist". So I let it "search dependencies at Maven repositories". It does find something and it adds this to my pom.xml: <dependency> <groupId>org.hdfgroup</groupId> <artifactId>hdf-java</artifactId> <version>2.6.1</version> <type>jar</type> </dependency> Unfortunately it keeps the warning at the import line "packadge does not excist" and the error exception. It seems this addition to the pom.xml does nothing. I am a beginner in all of this, so maybe the solution is obvious, but I cannot find it. These questions already date back to between 2012 and 2014, but didn't help me: http://hdf-forum.184993.n3.nabble.com/maven-repository-for-java-release-td4026938.html http://hdf-forum.184993.n3.nabble.com/HDF-Java-on-Maven-td4025772.html add hdf5 libs (java & c++) to public maven repository? How to use HDF5 in Windows Java project with NetBeans Getting Started with hdf5 Java library As suggested by ddarellis this might be a version problem. It seems there are two options. HDF Java 3.3.2, and HDF5-1.8.19 (HDFView Version 2.14) Java HDF Object Package 3.0.0, and HDF5-1.10 I'll try both, but the suggestion from maven to use HDF Java 2.6.1 is wrong. This post was helpfull for adding jarhdf5-3.3.2.jar to the dependencies. https://forums.netbeans.org/post-62903.html#62903 In Maven project open "Add dependency" dialog Make up some groupId, artifactId and version and fill them, OK. Dependency will be added to the pom.xml and will appear under "Libraries" node of maven project Right-click Lib node and "manually install artifact", fill the path to the jar Jar should be installed to local Maven repo with coordinates entered in step 2). Ok, so I installed HDF5 1.8.19 HDFView2.14 and added jarhdf5-3.3.2 to the dependencies. However I get this error when I try to run: Caused by: java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory at hdf.hdf5lib.H5.<clinit>(H5.java:230) A: At the link you have posted you can see this at the top: Very Important Change: Version 3.0 (and above) of the JHI5 packages all HDF library calls as "hdf.hd5flib", note that the "ncsa" has been removed. Source code which used earlier versions of the JHI5 should be changed to reflect this new implementation. What this means is if you use lower library version from v3.0 which you are (v2.6.1) you have to include ncsa.hdf.hdf5lib.H5 in-front of the package name. You can find tutorials here. A: The link you refer to contains out-of-date examples, you should use these examples instead. As pointed by ddarellis, the correct package is: ncsa.hdf.hdf5lib Here is a working example of opening an HDF5 file: import ncsa.hdf.hdf5lib.H5; import ncsa.hdf.hdf5lib.HDF5Constants; import ncsa.hdf.hdf5lib.exceptions.HDF5Exception; public class Foo { public void openHdf5File() { int flags = HDF5Constants.H5P_DEFAULT; int access = HDF5Constants.H5F_ACC_RDWR; try { int file_id = H5.H5Fopen("myFile.hdf", flags, access); } catch (HDF5Exception ex) { System.err.println("Failed to open HDF5 file"); } } } The maven dependency you have is correct and is the latest available on maven central.
{ "pile_set_name": "StackExchange" }
Q: How do I Align my widgets with MediaQuery for all devices in Flutter? I have three widgets that I am trying to align on my screen in refernce to each other. I have a golden border that I want to set as my background, the wheel in the center and the center of the wheel which is also a seperate asset. I have aligned the assets using MediaQuery however every time I debug it on a different device the MediaQuery has some difference and the alignmnet isn't proper. This is how Im calling my widgets: Widget build(BuildContext context) { return Scaffold( body: Stack( children: <Widget>[ //this is for the GOLDEN BORDER Positioned( top: MediaQuery.of(context).size.height * 0.082, child: Image.asset( 'assets/app/border3.png', height: MediaQuery.of(context).size.width, )), //This is the WHEEL Column( children: <Widget>[ SizedBox(height: MediaQuery.of(context).size.height * 0.344), Container( //color: Theme.of(context).primaryColor.withAlpha(180), child: Center( child: Winwheel( handleCallback: ((handler) { ctrl = handler; }), textFontFamily: 'Netflix', controller: ctrl, numSegments: 3, outerRadius: MediaQuery.of(context).size.height * 0.41 / 2, innerRadius: 28, strokeStyle: Colors.white, textFontSize: 20.0, textFillStyle: Colors.white, textFontWeight: FontWeight.bold, textAlignment: WinwheelTextAlignment.center, textOrientation: WinwheelTextOrientation.horizontal, wheelImage: 'assets/app/spin2.png', drawMode: WinwheelDrawMode.code, drawText: true, imageOverlay: false, textMargin: 0, pointerAngle: 0, pointerGuide: PointerGuide( display: true, ), segments: <Segment>[ Segment( textFontFamily: 'Netflix', fillStyle: Color(0xff9b57fc), textFillStyle: Colors.white, text: '400', strokeStyle: Colors.transparent), Segment( textFontFamily: 'Netflix', fillStyle: Color(0xff17a8f9), textFillStyle: Colors.white, text: '400', strokeStyle: Colors.transparent, ), Segment( textFontFamily: 'Netflix', fillStyle: Colors.pink, textFillStyle: Colors.white, text: '900', strokeStyle: Colors.transparent, ), Segment( textFontFamily: 'Netflix', fillStyle: Color(0xffef225b), textFillStyle: Colors.white, text: '500', strokeStyle: Colors.transparent, ), ], pins: Pin( visible: false, number: 16, margin: 6, // outerRadius: 5, fillStyle: Colors.transparent, ), animation: WinwheelAnimation( type: WinwheelAnimationType.spinToStop, spins: 4, duration: const Duration( seconds: 15, ), callbackFinished: (int segment) { setState(() { isPlaying = false; }); print('animation finished'); print(segment); }, callbackBefore: () { setState(() { isPlaying = true; }); }, ), ), ), ), ], ), //This is the GOLDEN CENTER Positioned( top: MediaQuery.of(context).size.height * 0.285, left: MediaQuery.of(context).size.width * 0.359, child: Image.asset('assets/app/center.png', height: MediaQuery.of(context).size.height * 0.16)), ], ), ); } I am using the winwheel dependency for the Spinning wheel. This is what the final output looks like. It isn't properly aligned in all devices even though it looks fine in the image . A: Maybe you can try usign AspectRatio Widget with an aspectRatio of 1.0 to keep the width and height the same (as a circle) and align the stack in the center Scaffold( body: Center( child: Padding( padding: EdgeInsets.all(8), child: AspectRatio( aspectRatio: 1.0, //Give it an aspectRatio of 1 child: MyWidget() ), ) ), ), class MyWidget extends StatelessWidget { @override Widget build(BuildContext context) { return Stack( alignment: Alignment.center, //align the Widgets to the Center of the Stack children: [ //this is for the WHEEL Container( decoration: BoxDecoration( color: Colors.orange[800], shape: BoxShape.circle, ), ), //This is the GOLDEN BORDER Container( decoration: BoxDecoration( border: Border.all(width: 20, color: Colors.yellow), color: Colors.transparent, shape: BoxShape.circle, ), ), //This is the GOLDEN CENTER Container( width: MediaQuery.of(context).size.width / 12, decoration: BoxDecoration( color: Colors.yellow[200], shape: BoxShape.circle, ), ), ] ); } } I don't have the assets so I make some Containers with colors but it should look like that So for you try it without the positioned widgets (the Stack is now centered so there is no need) class MyWidget extends StatelessWidget { @override Widget build(BuildContext context) { return Stack( alignment: Alignment.center, //align the Widgets to the Center of the Stack children: [ //This is the WHEEL Winwheel( .... ), //this is for the GOLDEN BORDER Image.asset('assets/app/border3.png', fit: BoxFit.contain), //or try BoxFit.scaledown if that doesn't work //This is the GOLDEN CENTER Image.asset('assets/app/center.png', width: MediaQuery.of(context).size.width / 12, fit: BoxFit.scaleDown) ] ); } }
{ "pile_set_name": "StackExchange" }
Q: Replace Single Quotes (') in Filenames I received a good suggestion in another thread to support the removal/replacement of specific characters from filenames in a directory structure. Works as expected for common ascii characters (like &). PowerShell (works fine to remove & character from filenames): powershell.exe -c "Get-ChildItem 'c:\Media\Downloads' -Filter '*&*' -Recurse | Rename-Item -NewName {$_.name -replace '&','' }" I also need remove single quotes from some files: Example: mark's_file.txt. I've tried a few variants without success. I think I am running into a punctuation issue I am unable sort out. I also tried using a variable = char(39) and adding to the string. No luck. Any ideas to accomplish? Note: Would like a self contained batch file approach, vs calling an external .ps1 file. A: A Batch file also works fine to remove both & and ' characters from filenames: @echo off setlocal EnableDelayedExpansion rem Remove "&" characters: for /R "c:\Media\Downloads" %%a in ("*&*") do ( set "fileName=%%~NXa" ren "%%a" "!filename:&=!" ) rem Remove "'" characters: for /R "c:\Media\Downloads" %%a in ("*'*") do ( set "fileName=%%~NXa" ren "%%a" "!filename:'=!" ) ... but the Batch file start run much faster than the PS one!
{ "pile_set_name": "StackExchange" }
Q: Setting canvas position inside a function in javascript I'm having some issues positioning a canvas with javascript. The flow of my operation is the following: An Ajax request is sent to the server On response received I get my data from a JSON value and call a function on those data The function operates with simpleheat in order to draw an heatmap on the canvas, overlayed to the original image. Here's the HTML <div id="rightPanel" class="col-md-9"> <img id="worldMap" width="800" height="600" /> <canvas class="coveringCanvas" id="heatmap" /> </div> The class coveringCanvas is .coveringCanvas { position: absolute; } My AJAX request: function OnUpdateClick() { begin = beginDate.GetDate().toLocaleString("it-IT"); end = endDate.GetDate().toLocaleString("it-IT"); if (begin == null || end == null) { alert("Immettere delle date!") } else { $.post("/Heatmap/getHeatmap", { beginDate: begin, endDate: end }, function (data) { map = data["mapImage"]; var img = document.getElementById('worldMap'); img.src = arrayBufferDataUri(map); positions = data["positions"]; drawPoints(positions); }); } and the DrawPoints function: function drawPoints(data) { var img = document.getElementById('worldMap'); var canvas = document.getElementById('heatmap'); console.log("Image x: " + img.x) console.log("Image y: " + img.y) canvas.width = img.width; canvas.height = img.height; canvas.style.left = img.x + "px"; canvas.style.top = img.y + "px"; simpleheat('heatmap').data(data).radius(30,25).draw(); } Now, setting height and width for my canvas is no problem. Setting top and left is. If I repeat the same instructions from the javascript console in my browser (Firefox Quantum), the positioning works flawlessly. If I log the img.x and img.y values they are correct in the function too, the problem seems to be the assignment to canvas. What can it be? A: Perhaps you could set the Style position Property inside the function prior to left and top? Example: function drawPoints(data) { var img = document.getElementById('worldMap'); var canvas = document.getElementById('heatmap'); console.log("Image x: " + img.x) console.log("Image y: " + img.y) canvas.width = img.width; canvas.height = img.height; canvas.style.position = 'absolute'; // Right Here! canvas.style.left = "15px"; canvas.style.top = "15px"; simpleheat('heatmap').data(data).radius(30,25).draw(); }
{ "pile_set_name": "StackExchange" }
Q: OAuth2: What is the "client"? When using OAuth2 system in an API we talk about client_id and client_secret. What exactly is a client? Is it a person/user? Or is it the platform? iPhone, Android, etc.? A: Client in most cases is the App. In OAuth you have 3 roles, ServiceProvider, ResourceOwner and Client. There is also an additional role for Authorization server but for most implementations AuthServer and ServiceProvider are both the same. I can give you an example that will help you understand better. Take the app 'Tweetdeck' that you want to use to post tweets onto your Twitter account. Here, Tweetdeck is a client, You are resource owner and Twitter is the ServiceProvider and AuthServer. Tweetdeck(Client) will need your permission(login) to access your Twitter Account (Resources) on Twitter(Service Provider). So the Tweekdeck team will signup with Twitter for a Client Account for which Twitter issues them a client_id and client_secret. OAuth is a specification that standardizes this interaction.
{ "pile_set_name": "StackExchange" }
Q: Return reference to *this without a copy constructor? I've written a class similar to the following: class ScriptThread { public: ScriptThread(): mParent() {} private: ScriptThread(ScriptThread *parent): mParent(parent) {} public: ScriptThread(ScriptThread &&rhs); ScriptThread &operator = (ScriptThread &&rhs); // copy constructor/assignment deleted implicitly ScriptThread &execute(const Script &script); ScriptThread spawn(); ScriptThread spawn(const Script &script); private: ScriptThread *mParent; }; ScriptThread &ScriptThread::execute(const Script &script) { // start executing the given script return *this; } ScriptThread ScriptThread::spawn() { // create a ScriptThread with "this" as its parent return ScriptThread(this); } ScriptThread ScriptThread::spawn(const Script &script) { // convenience method to spawn and execute at the same time return spawn().execute(script); // ERROR: "use of deleted function" } As written, g++ fails to compile it at the line marked "ERROR", claiming that it's trying to use the (deleted) copy constructor. However, if I replace the last function with this: ScriptThread ScriptThread::spawn(const Script &script) { ScriptThread thread = spawn(); thread.execute(script); return thread; } It compiles without an error. Even after referring to a number of articles, references, and other SO questions, I don't understand: why does the first invoke the copy constructor at all? Isn't the move constructor enough? A: execute(script) returns an lvalue. You can't implicitly move from an lvalue, so to use the move constructor for the returned object you would need to say return std::move(spawn().execute(script)); You didn't do this so it tries to use the copy constructor, because that's how you make new objects from lvalues. In your replacement case you have: return thread; Here thread is also an lvalue, but it's about to go out of scope as soon as the function ends, so conceptually it can be considered to be like a temporary or other variable that is going to disappear at the end of the expression. Because of this there is a special rule in the C++ standard that says the compiler treats such local variables as rvalues, allowing the move constructor to be used even though thread is really an lvalue. See Barry's more complete answer for the references to the standard where the special rule is defined, and the full details of the rule. A: ScriptThread is noncopyable (the implicit copy constructor/assignment operators are defined as deleted because you declared move constructor/assignment). In spawn(), your original implementation: ScriptThread ScriptThread::spawn(const Script &script) { return spawn().execute(script); } is attempting to construct a ScriptThread from an lvalue reference (execute returns a ScriptThread&). That will call the copy constructor, which is deleted, hence the error. However, in your second attempt: ScriptThread ScriptThread::spawn(const Script &script) { ScriptThread thread = spawn(); thread.execute(script); return thread; } we run into the rule, from [class.copy]: When the criteria for elision of a copy/move operation are met, but not for an exception-declaration, and the object to be copied is designated by an lvalue, or when the expression in a return statement is a (possibly parenthesized) id-expression that names an object with automatic storage duration declared in the body or parameter-declaration-clause of the innermost enclosing function or lambda-expression, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue. Even though thread is an lvalue, we perform overload resolution on the constructor of ScriptThread as if it were an rvalue. And we do have a valid constructor for this case: your move constructor/assignment. That's why the replacement is valid (and uses move construction), but the original failed to compile (because it required copy construction).
{ "pile_set_name": "StackExchange" }
Q: Did the Apollo lunar module descent stage have a role as a sort of service module? To minimize the re-entry mass of the Apollo command module, essentially all of the mission supply of command module consumables was stored in the service module. Was there a similar arrangement between the ascent and descent stages of the lunar module? In other words, to minimize lunar liftoff mass, were the majority of lunar module crew consumables (oxygen and water) stored in the descent stage? How much reserve was carried in the ascent stage (how much endurance was available for rendezvous attempts)? A: Was there a similar arrangement between the ascent and descent stages of the lunar module? In other words, to minimize lunar liftoff mass, were the majority of lunar module crew consumables (oxygen and water) stored in the descent stage? To some degree, yes, consumables were split across the descent and ascent stages with the majority kept in the descent stage. From the specifications, we can see, for example: Water Ascent stage: 85 lbs Descent stage: 333 lbs Battery Ascent stage: 592 Amp-hours Descent stage: 1660 (early) or 2075 (A15-A17) Amp-hours From Apollo Experience Report - Lunar Module Environmental Control Subsystem: Oxygen: Ascent stage: 4.8 lbs Descent stage: 48 lbs In addition to the O2 capacity, the lithium-hydroxide scrubber cartridges which removed carbon dioxide from the cabin air, as we know from Apollo 13, were also a limited consumable resource in the LM. The scrubbers do not return free oxygen to the air, so oxygen consumption is still a limit. How much reserve was carried in the ascent stage (how much endurance was available for rendezvous attempts)? Unfortunately, I have not found a simple answer to the "what was the endurance of the ascent stage" question. @Uwe tells me a person uses 0.35-1.1 g/min of oxygen depending on activity levels; that works out to a 16-48 hour supply of oxygen for two crew if the ascent O2 tanks are full at liftoff. For the CO2 scrubber cartridges, we can make a rough estimate using times from Apollo 13 and Apollo 12. On A13, the crew of three were on the LM's life support starting at around 59 hours into the mission; they had to install an incompatible cartridge from the CM using an improvised adapter at around 90 hours, so the LM carts were expended after 31 hours: about 93 crew-hours worth of LM scrubbers. For the normal 2-person LM crew that would be ~46 hours. On A12, two crew were on the LM's life support starting at about 105 hours, and the ascent stage left the moon at about 142 hours. Subtracting 8 hours of EVA (when the crew would be on PLSS rather than on the cabin air), that works out to 29 hours, so the ascent stage should be able to provide fresh air for roughly 17 hours after liftoff - more limiting than the O2 capacity. A scenario where the ascent stage's endurance would be severely tested is unlikely. None of the Apollo flights had any difficulty with the ascent and rendezvous portion of the mission. If the ascent stage didn't reach a safe orbit, it would crash to the surface of the moon within 10 minutes. Once safely in orbit, either the CSM or the ascent stage could perform the rendezvous maneuvers: 100% redundancy of what were already, individually, reliable spacecraft. Even if the CSM and ascent stage couldn't hard-dock, the last resort would be to EVA back to the CSM cabin. A: The service module and descent stage did share the same design philosophy that any mass not needed to safely return the crew and scientific results would be left behind. However, there are both similarities and differences between the two modules. Both the service module and the decent stage have a main engine, plus tanks with the fuel and oxidizer for these engines. However, the partner modules differ whether they also have a main engine/fuel/oxidizer; the ascent stage does, whereas the command module does not. The service module has a reaction control system (RCS) for attitude control and low amounts of thrust; the descent stage has no RCS. In the partner modules, the ascent stage has a complete RCS, whereas the command module has a limited number of RCS thrusters. Electrical power in the service module comes from three fuel cells. This is supplanted by 3 rechargable batteries in the command module for high current demands, reentry, and post-landing; 2 non-rechargable batteries in the CM for pyrotechnics; and after Apollo 13, one auxiliary battery in the SM. The descent stage has 4 batteries, and the ascent stage has 2 batteries. The service module has oxygen tanks (which infamously blew in Apollo 13) for cabin oxygen and the fuel cells, plus hydrogen tanks for the fuel cells. The descent module has only an oxygen tank. Water was produced by the fuel cells in the service module, and stored in tanks in the command module. In the descent stage, one or (Apollo 15-17) two tanks were filled with water prior to launch. Neither the service module nor the descent stage carried crew, food, waste, personal items, instrumentation, or controls. The service module had heat radiators; the lunar module used heat exchangers and sublimators to remove excess heat. The service module had both high-gain (dish) and low-gain (scimitar) radio antennas. No antennas were mounted on the descent stage. The descent stage and ascent stage each had radar. Neither the command module nor the service module had radar. The descent stage was the only module with landing gear. Prior to Apollo 15, only the descent stage had a bay to store scientific equipment. Starting with Apollo 15, it was enlarged to hold the lunar rover, and a bay was added to the service module for the service instrument module (SIM). Update: The OP clarified the question for reserve oxygen (see section below). This section was my answer for reserve propellant. As far as reserve propellant, the best information that I've found is the level for the "fuel warning" light: ... and a descent propellant quantity low­ level warning light. The low-level sensors provide a discrete signal to cause the warning light to go on when the propellant level in any tank is down to 9.4 inches (equivalent to 5.6% propellant remain­ing). When this warning light goes on, the quantity of propellant remaining is sufficient for only 2 minutes of engine burn at hover thrust (approx­imately 25%). I am skeptical that the service module and descent stage had comparable levels of reserve fuel/oxidizer. The sizes of the tanks were already established well before the unmanned Apollo test flights. However, the amount of propellants actually used depend on the vehicle masses (which were changing throughout the Apollo program) and the flight parameters (which varied between flights). So the amount of propellants left over will vary a lot, and it's doubtful that they would be comparable between these two modules. It's like asking how much "reserve" is in your car's gas tank. The tank has a fixed capacity, and the amount you actually use can vary trip to trip. The missions did carry extra oxygen. Like propellants, the tanks were designed for a certain capacity, and the actual use varied from mission to mission. Here is the CSM usage for Apollo 15: 58.4% of the oxygen was planned to be used, and 59.0% was actually consumed. and the lunar module usage for Apollo 15: 47.5% of the descent stage oxygen was planned for use, and 55.7% was actually consumed. A: There were tanks for fuel, oxidator, water, helium (for pressurization) and oxygen in both the ascent and descent stage. Also batteries in both stages, descent: four (Apollo 9-14) or five (Apollo 15-17) 28–32 V, 415 A·h silver-zinc batteries; 135 lb (61 kg) each, ascent: two 28–32 volt, 296 ampere-hour silver-zinc batteries; 125 lb (57 kg) each. The rendezvous radar needed for the return to the CSM only in the ascent stage, the landing radar only in the descent stage.
{ "pile_set_name": "StackExchange" }
Q: PHP: don't output date if user agent is a search engine crawler One of my websites has blog-style updates on the home page, but the website is certainly not a blog. It is being indexed by Google and the search engine results page summary shows the date of the latest update. I do not want the date to show in the search engine results page. I've found other posts related to this issue suggesting to render the date using javascript after the page is loaded (tried and google still gets it), or to render the date as an image (would prefer to avoid doing that). I was wondering if I could simply use PHP to detect if the user agent is a Google bot (or bing, etc.) and in those cases just not output the dates on posts. Is there any drawback to this? Would the search engines be able to detect that I am giving them a modified version of my site and would they penalize me for it? A: Please do not do it. This is considered black hat SEO, and you have a chance of being penalized. Google do not just go to your page like GoogleBot, he also visit as a normal Browser and compare versions. Since creation date is considered on ranking, what you is doing will be considered good. If you really want to do, do it also in your normal page, so will have less chance to being penalized, but with this will offer a worse user experience to your visitors.
{ "pile_set_name": "StackExchange" }
Q: Is it still bad etiquette to force a link to open in a new tab? Now tabbed browsing is the norm, is it still considered bad etiquette to force links to open in a new 'Window' (target="_blank")? For a page that I am designing, I think it is by far the best option for a set of links, but I don't want to upset any purists who visit my site. What is the polite thing to do in 2012? Edit: The links I am talking about are to external pages. A: Most (popular) browsers have options to override how new windows / popups / tabs are handled. There's nothing wrong with opening a link in a new tab, as long as it's not a link to your own site. If you're linking to pages on your own site, make the link open in the same tab (So don't supply any target) Otherwise, people might end up with a load of tabs opened with your site, slowing their system, and generally being annoying. Personally, I force all pages that want to open in a new window, to open in a tab instead. Users with more "technical" experience tend to Ctrl+Click / Middle-Click to open pages in new tabs, if they want them to. Otherwise, they'll most often expect them to open in the same page. As a rule of thumb: Don't force a specific sort of behaviour on your users. Make your site behave as expected.
{ "pile_set_name": "StackExchange" }
Q: Question about Matlab: passing strings as split parameters to function Hey there, I have the following problem: I have a string in matlab: str='foo bar' which I want to use for a certain command: mex(..., str) which does NOT work since mex handles str as ONE parameter (thus as mex(..., 'foo bar')). How to do this, that matlab recognizes it as a function call like that: mex(..., 'foo', 'bar') I don't this hardcoded on this certain example with 2 Parameters, it could also come a time where the strings expands to str='foo bar blupp' -> pass as mex(..., 'foo', 'bar', 'blupp'). Thanks! A: Use strread to convert to a cell array, and then {:} indexing to expand that back to a "comma separated list". >> x = 'foo bar baz' x = foo bar baz >> xc = strread( x, '%s' ) xc = 'foo' 'bar' 'baz' >> fprintf( 'Hello: %s\n', xc{:} ) Hello: foo Hello: bar Hello: baz Where the last line is exactly equivalent to fprintf( 'Hello: %s\n', 'foo', 'bar', 'baz' )
{ "pile_set_name": "StackExchange" }
Q: Can I shorten automatic shut down time from 60s to 5? Just loaded Ubuntu 10.10 and loaded all updates on a hard drive by itself (without Windows). Would like to change the time for the system to shut down automatically from 60 seconds to 5 seconds, thus just hitting the shutdown icon once and in 5 seconds the system would shut down or give me just enough time to hit the restart button if I wanted to restart. Any way to do it?? A: There's no way to configure the timeout currently, and in fact the timeout has been removed. But there is a couple of wishlist bugs to add it back and make it configurable that you might be interested in commenting on: https://bugs.launchpad.net/indicator-session/+bug/623804 and https://bugs.launchpad.net/indicator-session/+bug/607575 You shouldn't shutdown a user session with "sudo shutdown -h now" but should instead tell the session you want to shutdown with "gnome-session-save --logout" or if there are programs inhibiting the layout "gnome-session-save --force-logout".
{ "pile_set_name": "StackExchange" }
Q: Is there a design pattern for an informational pane? What I'm picturing is a side panel that updates with region-specific information as I mouse over portions of the form. Is there a name for this pattern? It's like a Two-panel Selector, but not selecting or navigating anything, just providing information. I seem to recall seeing it in some applications when I open help. A: I believe i'd call that a detail pane layout. Mouse over or focus on something in the left pane and get information regarding your selection in a pane on the right.
{ "pile_set_name": "StackExchange" }
Q: Can't share data between app and today extension I am developing to-do list app. In this app, i add the today extension. It is used to show the to-do list for today. This is the code for share data between app and today extension. For testing purpose i add the only one item in the NSUserDefaults. App code for saving the data to NSUserDefaults. NSUserDefaults *shared = [[NSUserDefaults alloc]initWithSuiteName:@"group.compname.appname"]; [shared setValue:@"Test" forKey:@"test"]; [shared synchronize]; Today extension code for fetch the data from NSUserDefaults NSUserDefaults *shared = [[NSUserDefaults alloc]initWithSuiteName:@"group.compname.appname"]; NSString *str = [ shared valueForKey:@"test"] ; NSLog(@" Text = %@", str); I am always getting the 'null' value. A: Sounds like you haven't added the group to the entitlements/capabilities. From this site: http://www.shinobicontrols.com/blog/posts/2014/07/21/ios8-day-by-day-day-2-sharing-extension Go to the capabilities tab of the app's target Enable App Groups Create a new app group, entitled something appropriate. It must start with group.. In the demo the group is called group.ShareAlike Let Xcode go through the process of creating this group for you.
{ "pile_set_name": "StackExchange" }
Q: What is the best practice to select users from DB ordered by online? I have table 'user', which has about 1 million users. I have query which select online users like this select *, CASE WHEN abstime ( last_login_time + 600 ) >= now ( ) THEN 3 ELSE 1 END AS onsitegen from user where blocked=0 order by onsitegen desc limit 3; But it's too slow and I understand why. It's because I use order by onsitegen. But what another method to select online users you can advise? A: First create an index: CREATE INDEX abc ON users( blocked, last_login_time ); and then try this query: SELECT * FROM ( SELECT U.*, 3 As onsitegen from users u WHERE u.blocked = 0 AND u.last_login_time >= now() - 600 * interval '1' second LIMIT 3 ) x UNION ALL SELECT * FROM ( SELECT U.*, 1 As onsitegen from users u WHERE u.blocked <> 0 AND u.last_login_time < now() - 600 * interval '1' second LIMIT 3 ) y ORDER BY onsitegen DESC LIMIT 3
{ "pile_set_name": "StackExchange" }
Q: Get label of json element with its id I have json elements in this form; <rect style="fill: #888888; display: inline;" id="17" width="35.823246" height="35.823246" x="456.61066" y="65.9505" class="seatObj" label="A18"></rect> How can I get the attribute label value? Suppose <rect .../> tag a part of xml, then how can I get the same using C# console application? A: Try this: var elem = document.getElementsById('17'); var label = elem.getAttribute('label'); alert(label); Using jQuery: alert($('#17').attr('label')); You have 300 elements like this: then try this: $('rect').each(function(){ alert($(this).attr('label')); }); here is the Demo Another way of doing this by adding a class attribute into your rect element and select them by using that class. I have added class="sample" rect element. Check this Fiddle $('.sample').each(function(){ alert($(this).attr('label')); }); Sample xml file. <?xml version="1.0" encoding="utf-8" ?> <Test> <rect style="fill: #888888; display: inline;" id="17" width="35.823246" height="35.823246" x="456.61066" y="65.9505" class="seatObj" label="A18"></rect> <rect style="fill: #888888; display: inline;" id="18" width="35.823246" height="35.823246" x="456.61066" y="65.9505" class="seatObj" label="A19"></rect> </Test> Parsing xml using c# console application: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace Sample { class Program { static void Main(string[] args) { XmlDocument doc = new XmlDocument(); doc.Load("Url for Sample.xml"); XmlNodeList elemList = doc.GetElementsByTagName("rect"); for (int i = 0; i < elemList.Count; i++) { string attrVal = elemList[i].Attributes["label"].Value; Console.WriteLine(attrVal); } Console.ReadLine(); } } }
{ "pile_set_name": "StackExchange" }
Q: Show that $\ker F$ is trivial. Let $A,B,$ and $C$ be multiplicative groups, let $f:A→B$ and $g:A→C$ be group homomorphisms such that $\ker f ∩ \ker g=\{1\}.$ Let $F:A→B×C$ be defined by $F(a)=(f(a),g(a))$. (a) Show that $\ker F$ is trivial. (b) Find a subgroup of $B × C$ that is isomorphic to $A$. My attempt: First, we can show that $F$ is also a group homomorphism: $F(a_1a_2)=(f(a_1a_2),g(a_1a_2))=(f(a_1)f(a_2),g(a_1)g(a_2))$ (since $f:A→B$ and $g:A→C$ are group homomorphisms) $=(f(a_1),g(a_1))(f(a_2),g(a_2))$ (the operation on the direct product $B×C$ is component-wise) $=F(a_1)F(a_2)$. Now, for part a) I tried to use the fact that the kernel of a group homomorphism $F$ is trivial if and only if $F$ is injective. So suppose $F(a_1)=F(a_2)$, then $$(f(a_1),g(a_1))=(f(a_2),g(a_2)) \iff \begin{cases} f(a_1)=f(a_2) \\ g(a_1)=g(a_2) \end{cases}.$$ But I don't think this is the correct way to prove it, I believe we need to use the fact that $\ker f ∩ \ker g=\{1\}$ somehow. $\ker f ∩ \ker g=\{1\}$ doesn't imply $\ker f=\ker g=\{1\}$ right? As for part b) I am completely stuck and have no ideas whatsoever. Any help would be appreciated. A: Let $x$ be in $\textrm{Ker}(F)$. As the neutral element of $B \times C$ is $(1_B, 1_C)$, one has $(f(x), g(x)) = (1_B, 1_C)$. So,$x$ belongs to both $\textrm{Ker}(f)$ and $\textrm{Ker}(g)$. Thus, $x = 1_A$ and $\textrm{Ker}(F)$ is trivial because included in $\{ 1_A \}$ (the reciprocal inclusion is obvious). This fact is a characterisation of the injectivity of group homomorphisms. This is sufficient to claim that the kernel of $F$ is included in $\{ 1_A \}$. As $F$ is injective, $F(A)$ is isomorphic to $A$ and as $F$ is a group homomorphism, $F(A)$ is a subgroup of $B \times C$. So $F(A)$ is the subgroup you are looking for.
{ "pile_set_name": "StackExchange" }
Q: Doubts with BroadcastReceiver I have an alarm that obviously calls a receiver and in the receiver it have to do some tasks and it may take some time to be done. But i heard that the onReceive() method is killed after some seconds. I made a debug on my code and "stopped" inside the receiver and suddenly the debug stops, it happens because the onReceive() was killed? So, what should i do? A: But i heard that the onReceive() method is killed after some seconds Correct. onReceive() is called on the main application thread. You want to get off of that thread as soon as possible. If your UI happens to be in the foreground when the broadcast is received, your UI will be frozen. Even if your UI is not in the foreground, you cannot take very long on that thread without your work being terminated. So, what should i do? Delegate the work to an IntentService, where you start that service in onReceive(). If the work may take 15+ seconds, I would recommend using WakefulBroadcastReceiver, so that you can ensure the device will stay awake long enough for your work to complete. But even then, "some time to be done" should be measured in seconds, maybe minutes.
{ "pile_set_name": "StackExchange" }
Q: Using Elixir inside string interpolation is not working properly in my template I'm rendering a template and passing some options to it. In one of them I have this code: main: "#{ @comp[:contentItem] unless Regex.match?(~r/width:/, to_string @comp[:contentItem]) do "width: 165px;" end unless Regex.match?(~r/height:/, to_string @comp[:contentItem]) do "height:65px;" end }" I found that only the second code inside unless executes and that if I copy the first unless and repeat it again after the second unless it works, so there seems to be a problem running the code immediately after @comp[:contentItem]. I've tried using () and other combinations with no luck. A: If you add multiple code blocks in a string interpolation like this, all except the last one are ignored. Elixir also shows a warning for this (maybe eex doesn't): iex(1)> "#{1 ...(1)> 2 ...(1)> 3}" warning: code block contains unused literal 1 (remove the literal or assign it to _ to avoid warnings) iex:1 warning: code block contains unused literal 2 (remove the literal or assign it to _ to avoid warnings) iex:1 "3" The fix is to use 3 separate interpolations. For your code, this should work: main: "#{@comp[:contentItem]}\ #{unless Regex.match?(~r/width:/, to_string @comp[:contentItem]) do "width: 165px;" end}\ #{unless Regex.match?(~r/height:/, to_string @comp[:contentItem]) do "height:65px;" end}" I'm using \ at the end to make sure there's no extra space(s) inserted between the 3 expressions. Edit: As @cdegroot pointed out, adding such complex logic to templates is considered a terrible practice. You should do this computation in the relevant view, controller, model, or a separate module. It's considered a best practice to have as simple templates as possible, usually just loops and printing out fields of assigns/maps/structs.
{ "pile_set_name": "StackExchange" }
Q: GLSL frag shader - only works on nVidia, non-standard code? EDIT: I'm sorry Stack Overflow, but I'm retarded. frac(tex_offset) -> fract(tex_offset), and it works fine on ATI cards, and also nVidia cards when #version is specified now. This must be why most of the programmers I know don't have much hair left. - I'm working on a game for a school project. It's a vertical scroller, so one of the required features was a scrolling background. I tried a few approaches, but I eventually wrote a simple fragment shader (this is the first time I touch shader programming, so don't really know what I'm doing): uniform sampler2D tex; uniform float tex_offset; void main() { vec2 coords = vec2(gl_TexCoord[0].s, gl_TexCoord[0].t - frac(tex_offset)); gl_FragColor = texture2D(tex, coords); } I use SFML so I don't touch much of the stuff behind the scenes, but the texture I'm using is passed to the tex variable, and the tex_offset is generated in my game loop by taking the total elapsed seconds multiplied by a factor to control the scrolling speed. This appears to do what it's supposed to; it indefinitely scrolls a seamless repeating texture in one direction. It works on my laptop, and it works on my home computer, which both have nVidia cards. However, when we tried to run it on a group member's computer with an ATI card, it simply did nothing. I did some googling and it seems like the nVidia cards accept "non-standard" GLSL code as well, which might explain the issues with compatibility. I find it difficult to find good tutorials/explanation on GLSL as most of the stuff I dig up is from version 1.2-1.4 and I'm apparently using syntax that was deprecated in version 3 (gl_FragColor, gl_TexCoord). However, when I tried to set #version to 120 or 140 or whatever, the shader also stopped working on my nVidia computers. So, to try to phrase this into question form: what is wrong about this shader code? Is there any way to debug the syntax, and how do I turn on "standards" mode for my nVidia cards if this is possible? A: Changed frac(tex_offset) to fract(tex_offset), and it works fine on ATI cards, and also nVidia cards when #version is specified now.
{ "pile_set_name": "StackExchange" }
Q: Multiple rows returned by a subquery used as an expression I have the following query which runs perfectly well on both Oracle and SQL Server 2008 however it doesn't seem to run on PostgreSQL. The query is intended to return a count of records that match the given criteria. Can someone explain the reason for this and also offer a solution to how this query can be modified to allow it to produce the expected result. Query: select count(*) from tma_notices where TNOT_NOTICE_TYPE ='0400' and TNOT_NOTICE_STATUS = 'OK' and tnot_notice_id >= ( select NOTICE_NUM_AT_MIDNIGHT from RWOL_COUNTER_QUERY_TYPE where QUERY_TYPE = 'START_NOTICES_TODAY' and USER_NAME = 'PUBLIC' ) UPDATE: This error was caused by unforeseen duplicate records in the PostgreSQL database. Where the duplicates came from needs to be investigated. A: It's pretty clear that the subquery could return a set of rows and the condition tnot_notice_id >= isn't valid if compared with a set of rows and not with only a single value. Are you sure that exist a unique record that satisfy your where conditions? If you want to avoid that behaviour, I suggest you to use tnot_notice_id >= ALL ( subquery )
{ "pile_set_name": "StackExchange" }
Q: Overload java method by List<> I have the code, where methods is overlays with List<> arguments RetrunType1 func(List<Type1> arg); ReturnType2 func(List<Type2> arg); and Type1!=Type2, but that code compile and work fine on jdk1.6.0_45. I know that this sample don't compile and work. How I can understand that? A: This is due to type erasure. The generic type parameters do not follow through to the byte code, so if the overloading you suggest would be legal, you would end up with a name collision in the byte code: ReturnType1 func(List arg); ReturnType2 func(List arg); The solution is to use different names for the functions. The reason it worked in Java 6 was due to a bug that was fixed in Java 7.
{ "pile_set_name": "StackExchange" }
Q: org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException... why? I develop server using spring mvc and hibernate. So, I write my server program using Spring mvc and maven. However when I start my server program at tomcat server, Error occurs. That is things expected. so, I search using my error message. However I can't find answer. help me.... This is my servlet-context.xml <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" xmlns:tx="http://www.springframework.org/schema/tx"> <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> <!-- Enables the Spring MVC @Controller programming model --> <annotation-driven /> <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> <resources mapping="/resources/**" location="/resources/" /> <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix" value="/WEB-INF/views/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean> <context:component-scan base-package="kr.ac.jbnu.jinggumdari" /> <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" /> <beans:property name="url" value="jdbc:mysql://localhost:3306/jinggumdari" /> <beans:property name="username" value="root" /> <beans:property name="password" value="mysql1234" /> </beans:bean> <!-- Hibernate 4 SessionFactory Bean definition --> <beans:bean id="hibernate4AnnotatedSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <beans:property name="dataSource" ref="dataSource" /> <beans:property name="annotatedClasses"> <beans:list> <beans:value>kr.ac.jbnu.jinggumdari.model.Member</beans:value> </beans:list> </beans:property> <beans:property name="hibernateProperties"> <beans:props> <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect </beans:prop> <beans:prop key="hibernate.show_sql">true</beans:prop> </beans:props> </beans:property> </beans:bean> <beans:bean id="memberDAO" class="kr.ac.jbnu.jinggumdari.DAO.MemberDAOImpl"> <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" /> </beans:bean> <beans:bean id="memberService" class="kr.ac.jbnu.jinggumdari.serviceImplementation.MemberManageServiceImpl"> <beans:property name="memberDAO" ref="memberDAO"></beans:property> </beans:bean> <tx:annotation-driven transaction-manager="transactionManager" /> <beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" /> </beans:bean> </beans:beans> This is my pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jbnu</groupId> <artifactId>jinggumdari</artifactId> <name>server</name> <packaging>war</packaging> <version>1.0.0-BUILD-SNAPSHOT</version> <properties> <java-version>1.6</java-version> <org.springframework-version>4.1.5.RELEASE</org.springframework-version> <org.aspectj-version>1.8.5</org.aspectj-version> <org.slf4j-version>1.6.6</org.slf4j-version> <hibernate.version>4.3.9.Final</hibernate.version> </properties> <dependencies> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework-version}</version> <exclusions> <!-- Exclude Commons Logging in favor of SLF4j --> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${org.springframework-version}</version> </dependency> <!-- AspectJ --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${org.aspectj-version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${org.aspectj-version}</version> </dependency> <!-- Logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${org.slf4j-version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${org.slf4j-version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${org.slf4j-version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.15</version> <exclusions> <exclusion> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> </exclusion> <exclusion> <groupId>javax.jms</groupId> <artifactId>jms</artifactId> </exclusion> <exclusion> <groupId>com.sun.jdmk</groupId> <artifactId>jmxtools</artifactId> </exclusion> <exclusion> <groupId>com.sun.jmx</groupId> <artifactId>jmxri</artifactId> </exclusion> </exclusions> <scope>runtime</scope> </dependency> <!-- @Inject --> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <!-- Servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- Test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.7</version> <scope>test</scope> </dependency> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <!-- JDBC --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.30</version> </dependency> <!-- javax.persistence --> <dependency> <groupId>javax.persistence</groupId> <artifactId>persistence-api</artifactId> <version>1.0.2</version> </dependency> <!-- apache DBCP --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-eclipse-plugin</artifactId> <version>2.9</version> <configuration> <additionalProjectnatures> <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature> </additionalProjectnatures> <additionalBuildcommands> <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand> </additionalBuildcommands> <downloadSources>true</downloadSources> <downloadJavadocs>true</downloadJavadocs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>1.6</source> <target>1.6</target> <compilerArgument>-Xlint:all</compilerArgument> <showWarnings>true</showWarnings> <showDeprecation>true</showDeprecation> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <configuration> <mainClass>org.test.int1.Main</mainClass> </configuration> </plugin> </plugins> </build> </project> This is error messages. ERROR: org.springframework.web.servlet.DispatcherServlet - Context initialization failed org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 69 in XML document from ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 69; columnNumber: 67; cvc-complex-type.2.4.c: matching wildcard is strict but no declaration can be found for 'tx:annotation-driven' element. at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:399) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94) at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129) at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:452) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5262) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5550) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: org.xml.sax.SAXParseException; lineNumber: 69; columnNumber: 67; cvc-complex-type.2.4.c: matching wildcard is strict but no declaration can be found for 'tx:annotation-driven' element. at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.reportSchemaError(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.emptyElement(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source) at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:76) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadDocument(XmlBeanDefinitionReader.java:429) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:391) ... 29 more A: your xsi:schemaLocation attribute is missing the schema for the tx namespace. add http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd It is also weird that the tx:annotation-driven is in the middle of the beans. It might have a specific place in the xml specified by the schema, can't remember. You'll get a different specific error if it is in the wrong place.
{ "pile_set_name": "StackExchange" }
Q: Resume app when tapping a received toast notification I'm trying to open my app when a user taps the received toast notification. I have setup the server to post this message: <?xml version="1.0" encoding="utf-8"?> <wp:Notification xmlns:wp="WPNotification"> <wp:Toast> <wp:Text1>Message</wp:Text1> <wp:Text2>Resume application</wp:Text2> </wp:Toast> </wp:Notification> When my app is in the background (or fully closed) I'm getting a notification as expected but when I tap the notification it will just open the app and run my main page. Instead, I would like it to: if app closed => open main page (as it does now) if app in background => resume app I have tried with the "wp:Param" argument as well with both a absolute url to a page (which is not what I want) and by starting with "?" (to indicate it should transfer that parameter to the main page). A: The way the internal mechanism works, the application will always launch in a new instance when called from a toast.
{ "pile_set_name": "StackExchange" }
Q: Why does this code not download the file and the downloader can download it successfully The problem begins with this link https://i1.pixiv.net/img-zip-ugoira/img/2017/04/05/00/24/41/62259492_ugoira600x600.zip the file downloaded with the downloader is complete. enter image description here and I try to use python to download the file from urllib import request import sys request.urlretrieve('https://i1.pixiv.net/img-zip-ugoira/img/2017/04/05/00/24/41/62259492_ugoira600x600.zip', '123.zip') Traceback (most recent call last): File "C:/Users/ssshooter/PycharmProjects/first/111.py", line 3, in <module> request.urlretrieve('https://i1.pixiv.net/img-zip-ugoira/img/2017/04/05/00/24/41/62259492_ugoira600x600.zip', '123.zip') File "C:\Users\ssshooter\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 248, in urlretrieve with contextlib.closing(urlopen(url, data)) as fp: File "C:\Users\ssshooter\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 223, in urlopen return opener.open(url, data, timeout) File "C:\Users\ssshooter\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 532, in open response = meth(req, response) File "C:\Users\ssshooter\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 642, in http_response 'http', request, response, code, msg, hdrs) File "C:\Users\ssshooter\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 570, in error return self._call_chain(*args) File "C:\Users\ssshooter\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 504, in _call_chain result = func(*args) File "C:\Users\ssshooter\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 650, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 403: Forbidden It doesn't work. A: The differences are: You're using different SSL information: You're browser has a built-in set of certificate authorities. Python uses a set which comes with the OS. They differ & if the site you're accessing uses one know to your browser but not known to python, the python will throw an exception. You're accessing using different User-Agents. Your browser is telling the server it's Chrome or IE or whatever. Python is telling the server it's python. For whatever reason, the server may decide it doesn't like that and return Forbidden. The server may be working harder than you think: while it appears the request is for a simple file, you're really requesting a resource. It may be (though unlikely in this case) that the resource you're requesting results in multiple interactions between the server and your browser -- cookies, javascript, etc -- which are executed successfully in your browser, returned to the server & it then delivers the file. Your python request is not doing any of that. Your browser (may) have existing state which your python does not. You say you can access the file using your browser, but it could be that works only because you've accessed other resources on the site, or logged in, or whatever. Your browser is communicating that information (perhaps a session_id via cookie?) with the server recognizes. Your python code states with no previous state, so the server forbids that. Which is it in this case? You'll need to investigate. Can you get wget or curl to work? Debug your browser's access: what headers are being sent, what are you receiving in reply?
{ "pile_set_name": "StackExchange" }
Q: Having trouble with a simple Java program Trying to write a Java program to satisfy this: Duke Shirts sells Java t-shirts for $24.95 each, but discounts are possible for quantities as follows: 1 or 2 shirts, no discount and total shipping is $10.00 3-5 shirts, discount is 10% and total shipping is $8.00 6-10 shirts, discount is 20% and total shipping is $5.00 11 or more shirts, discount is 30% and shipping is free Write a Java program that prompts the user for the number of shirts required. The program should then print the extended price of the shirts, the shipping charges, and the total cost of the order. Use currency format where appropriate. Here is my code: import java.lang.Math; import java.util.Scanner; public class Excercise2_3 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); System.out.println("How many shirts do you need?"); double shirts = input.nextInt(); if (shirts <= 2) System.out.printf("The extended cost is : $%.2", (shirts * 24.95)); System.out.printf("The shipping charges are $10.00"); System.out.printf("The total cost is : $%.2", (shirts * 24.95) + 10); if (shirts > 2 && shirts <= 5) System.out.printf("The extended cost is : $%.2", ((shirts * 24.95)*.10)); System.out.printf("The shipping charges are $8.00"); System.out.printf("The total cost is : $%.2", ((shirts * 24.95)*.10) + 8); if (shirts > 5 && shirts <= 10) System.out.printf("The extended cost is : $%.2", ((shirts * 24.95)*.20)); System.out.printf("The shipping charges are $5.00"); System.out.printf("The total cost is : $%.2", ((shirts * 24.95)*.20) + 5); if (shirts > 10) System.out.printf("The extended cost is : $%.2", ((shirts * 24.95)*.00)); System.out.printf("Shipping is free!"); System.out.printf("The total cost is : $%.2", ((shirts * 24.95)*.30)); } } Can anyone shed some light on why it isn't compiling correctly? Thanks! A: You are missing your curly braces around the if statements. Also your printf format string should be %.2f. You were missing the f and you were missing newlines. import java.util.Scanner; public class TempApp { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("How many shirts do you need?"); double shirts = input.nextInt(); if (shirts <= 2) { System.out.printf("The extended cost is : $%.2f\n", (shirts * 24.95)); System.out.printf("The shipping charges are $10.00\n"); System.out.printf("The total cost is : $%.2f\n", (shirts * 24.95) + 10); } if (shirts > 2 && shirts <= 5) { System.out.printf("The extended cost is : $%.2f\n", ((shirts * 24.95) * .10)); System.out.printf("The shipping charges are $8.00\n"); System.out.printf("The total cost is : $%.2f\n", ((shirts * 24.95) * .10) + 8); } if (shirts > 5 && shirts <= 10) { System.out.printf("The extended cost is : $%.2f\n", ((shirts * 24.95) * .20)); System.out.printf("The shipping charges are $5.00\n"); System.out.printf("The total cost is : $%.2f\n", ((shirts * 24.95) * .20) + 5); } if (shirts > 10) { System.out.printf("The extended cost is : $%.2f", ((shirts * 24.95) * .00)); System.out.printf("Shipping is free!"); System.out.printf("The total cost is : $%.2f", ((shirts * 24.95) * .30)); } } }
{ "pile_set_name": "StackExchange" }
Q: How can i share 2 differents types with only one share intent? In my app there's a share button that calls this method: Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); String audioClipFileName="bell.mp3"; sendIntent.setType("audio/mp3"); sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://com.gruchka.guessthesound/" + R.raw.bell)); startActivity(Intent.createChooser(sendIntent, "Get help with:")); This button shares the audio file: 'bell.mp3'. I want this button to also share the text below the audio file. How can i solve this issue? Thanks A: Use this below setType line: sendIntent.putExtra(Intent.EXTRA_TEXT, "YOUR_TEXT"); Only would works in apps that support it.
{ "pile_set_name": "StackExchange" }
Q: How to show and hide a LineObject by using formula in crystal report? I'm using a Crystal Report connected with VB.NET 2010, here I using a Line object, which I need to show or hide depending on data field. Where do I need to set the formula? This project I use is running with SQL 2008 and VB.NET 2010. I've tried some Formula Field for this topic. But the result is not look like that I want to show. I use the following code on Formula Field:- IF isNull({PrintParticularList.CUST_INVOICE_No}) or {PrintParticularList.CUST_INVOICE_No}="" THEN "" ELSE "--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------" I also try this following Code :- IF isNull({PrintParticularList.SLNO}) or {PrintParticularList.CUST_INVOICE_No}="" THEN Line25.Suppress=True ELSE Line25.Suppress=False But here I got error on Line25. A number, currency amount,boolean, date, time, date-time, or string is expected here. A: In the Report Designer use the Insert Line tool to draw the line where you want it to appear on your report. The right-click the line object and select "Format Line..." to open the Format Editor dialog box. On this window you will find a check box labeled "Suppress" with an X-2 button to the right. Click the X-2 button and this will open a Formula Workshop window where you will enter the formula that determines if this drawing object should be suppressed or not. I would recommend the following formula based upon your previous attempts at creating one. IF isNull({PrintParticularList.SLNO}) or {PrintParticularList.CUST_INVOICE_No}="" THEN True ELSE False -----EDIT----- Since you don't have the X-2 button I have 2 more ideas. 1.) Take the 1 section you current have and split it into 3 sections. Then you could place all the content above the line in the first section, place the line in the second section, and the content below the line in the third section. They use the formula to suppress the second section when the line is not needed. 2.) Insert a blank text box in place of the line and set either the top or bottom border of the text box to a single line. Then use the suppress formula to determine if the text box should be shown or hidden.
{ "pile_set_name": "StackExchange" }
Q: vaadin table must sort entries in chronological order descending i.e. latest at the top then down to the earliest notes I have a vaadin table which is displaying Notes, with created date time. I want to sort entries in chronological order descending (i.e. latest at the top then down to the earliest notes) by default. When I added a new value it should be in top. This is a Java EE web application which is using Vaadin. I tried ... setSortContainerPropertyId(NoteContainer.DATE_CREATED); setSortAscending(false); sort(); inside my NoteTable constructor. But it only added the sorting functionality to DATE_CREATED column. when I clicked the that column header only it starts to sort. Please give me a proper solution...? Note Table class constructor.. public NoteTable() { dataSource = new NoteContainer(); setContainerDataSource(dataSource); NoteTableColumnGenerator columnGenerator = new NoteTableColumnGenerator(); addGeneratedColumn(ACTION, columnGenerator); addGeneratedColumn(CREATED_BY, columnGenerator); addGeneratedColumn(TEXT, columnGenerator); setVisibleColumns(NoteContainer.NATURAL_COL_ORDER); setSizeFull(); Object[] columns = getVisibleColumns(); for (int i = 0; i < columns.length; i++) { if (((String) columns[i]).equals(NoteContainer.DATE_CREATED)) setColumnWidth(columns[i], 150); else if (((String) columns[i]).equals(NoteContainer.CREATED_BY)) setColumnWidth(columns[i], 150); else if (((String) columns[i]).equals(NoteContainer.ACTION)) setColumnWidth(columns[i], 150); else setColumnWidth(columns[i], 550); } setColumnHeaders(NoteContainer.COL_HEADERS_ENGLISH); setSelectable(true); setImmediate(true); setSortContainerPropertyId(NoteContainer.DATE_CREATED); setSortAscending(false); sort(); } Note Container class public class NoteContainer extends BeanItemContainer<CaseNote> implements Serializable { private static final long serialVersionUID = -5926608449530066014L; public static final String DATE_CREATED = "dateCreated"; public static final String CREATED_BY = "createdBy"; public static final String TEXT = "text"; public static final String ACTION = "Action"; public static final Object[] NATURAL_COL_ORDER = new Object[] { ACTION, DATE_CREATED, CREATED_BY, TEXT }; public static final String[] COL_HEADERS_ENGLISH = new String[] { "ACTION", "Date Created/Updated", "Created/Updated By", "Note" }; /** * Default Constructor. * */ public NoteContainer() { super(CaseNote.class); } } Note : CaseNote is an Entity Class. A: I resolved it by my self.. I added sort(); inside the table refresh() method instead of NoteTable constructor. Now it is working fine. thank you everyone, who tried to help me.. :)
{ "pile_set_name": "StackExchange" }
Q: Wi-Fi stops working frequently I recently keep having the problem that my internet stops working. On firefox, I get server not found. And the usual make sure that you didn't type ww instead of www. Wi-Fi is still connected. A restart always fixes the problem. In Skype, I get multiple messages with people going offline at the exact same moment. Is there a way to fix this so I don't have to keep restarting it? $ lspci -knn | grep Net -A2 01:00.0 Ethernet controller [0200]: Broadcom Corporation NetXtreme BCM57765 Gigabit Ethernet PCIe [14e4:16b4] (rev 10) Subsystem: Broadcom Corporation NetXtreme BCM57765 Gigabit Ethernet PCIe [14e4:16b4] Kernel driver in use: tg3 01:00.1 SD Host controller [0805]: Broadcom Corporation BCM57765/57785 SDXC/MMC Card Reader [14e4:16bc] (rev 10) -- 02:00.0 Network controller [0280]: Broadcom Corporation BCM4331 802.11a/b/g/n [14e4:4331] (rev 02) Subsystem: Apple Inc. AirPort Extreme [106b:00f5] Kernel driver in use: bcma-pci-bridge UPDATE: It seems that Skype keeps fluctuating between everyone offline and some online. But it happens separately to when the browser stops working I have a MacBook Pro with Ubuntu as a partition A: Your wireless wl driver is not installed. You probably tried to install a wrong version that did not build for 14.04. When wl driver is installed, lspci -knn | grep Net -A2 shows Kernel driver in use: wl Install the driver this way.
{ "pile_set_name": "StackExchange" }
Q: Is Netty handler unique for each connection? I've been looking over at the proxy server example from Netty website: The example source code handler has a volatile variable private volatile Channel outboundChannel; which takes care of the channel that connects to another server for proxy. This got me to wonder if this is the correct and safe way to implement for multiple connections for proxy. I would like to allow multiple connections(inbound) to connect to different outbounds, while making sure that every inbound connection is uniquely linked to the outbound channel. According to my knowledge, Netty generates a new pipeline for each connection. Does this mean a newly generated handler by pipeline factory is uniquely dedicated to the new connection(channel)? p.s. If I have 1,000 active connections to my Netty server, does this mean there are 1,000 different pipelines? A: There is one pipeline created per connection, but the pipeline may contain both shared and exclusive handlers. Some handlers do not keep state and a single instance can be inserted into multiple [all] pipelines. Netty provided handlers that can be shared are annotated with ChannelHandler.Sharable. See the section titled Shared and Exclusive Channel Handlers in this tutorial.
{ "pile_set_name": "StackExchange" }
Q: Generate random numbers in a specific range with a standard deviation? I already know how to generate random numbers in a range. I can do this by using rand.nextInt((max - min) + 1) + min; The problem is that I would also like to set a standard deviation for these numbers. The numbers also need to be positive and they are not between 0 and 1 EDIT I removed the ThreadLocalRandom class because I cannot set a seed in that class and these random numbers should be reproducible in a different system. A: Choosing the standard deviation (or variance) for a bounded distribution can only be done subject to constraints that depend on the selected distribution and the bounds (min, max) of your interval. Some distributions may allow you to make the variance arbitrarily small (e.g. the Beta distribution), other distributions (like the Uniform distribution) don't allow any flexibility once the bounds (min, max) have been set. In any case, you'll never be able to make the variance arbitrarily large -- the bounds do prevent this (they'll always enter the expression for the distribution's variance). I'll illustrate this for a very simple example that can be implemented without requiring any 3rd party libraries. Let's assume you want a symmetric distribution on the interval (min, max), symmetry implying that the mean E(X) of the distribution is located in the middle of the interval: E(X) = (min + max)/2. Using Random's nextDouble as in x = a + (b - a) * rnd.nextDouble() will give you a uniformly distributed random variable in the interval a <= x < b that has a fixed variance Var(X) = (b - a)^2 / 12 (not what we want). OTH, simulating a symmetric triangular distribution on the same interval (a, b) would give us a random variate whith the same mean but with only half the variance: Var(X) = (b - a)^2 / 24 (also fixed, so also not what we want). A symmetric trapezoidal distribution with parameters (a < b < c < d) lies somewhere in the middle of a Uniform and a triangular distribution on the interval (a, d). The symmetry condition implies d - c = b - a, in the following I'll refer to the distance b - a as x or as "displacement" (I've made up that name, it's not a technical term). If you let x approach 0.0 from above, the trapezoidal will begin to look very similar to a uniform distribution and its variance will tend to the maximum possible value (d - a)^2 / 12. If you let x approach the maximum possible value (d - a)/2 from below, the trapezoidal will look very similar to a symmetric triangle distribution and its variance will approach the minimum possible value of (d - a)^2 / 24) (but note that we should stay away a little from these extreme values in order not to break the variance formula or our algorithm for the trapezoidal). So, the idea is to construct a trapezoidal distribution with a value for x that yields the standard deviation you want, given the condition that your targeted standard deviation must lie inside the open range (roughly) given by (0.2041(d - a), 0.2886(d - a)). For convenience let's assume that a = min = 2.0 and d = max = 10.0 which gives us this range of possible stddevs: (1.6328, 2.3088). Let's further assume that we want to construct a distribution with a stddev of 2.0 (which, of course, has to be in the admissible range). Solving this requires 3 steps: 1) we need to have a formula for the variance given min, max and an admissible value for the displacement x 2) we need to somehow "invert" this expression to give us the value of x for our target variance 3) once we know the value of x we must construct a random variable that has a symmetric trapezoidal distribution with the parameters (min, max, x) Step 1: /** * Variance of a symmetric trapezoidal distribution with parameters * {@code a < b < c < d} and the length of {@code d - c = b - a} * (by symmetry) identified by {@code x}. * * @param a support lower bound * @param d support upper bound * @param x length of {@code d - c = b - a}, constrained to lie in the open * interval {@code (0, (d-a)/2)} * @return variance of the symmetric trapezoidal distribution defined by * the triple {@code (a, d, x)} */ static double varSymTrapezoid(double a, double d, double x) { if (a <= 0.0 || d <= 0.0 || a >= d) { throw new IllegalArgumentException(); } if (x <= 0.0 || x >= (d - a) / 2) { throw new IllegalArgumentException(); } double b = a + x; double c = d - x; double b3 = pow(b, 3); double c3 = pow(c, 3); double ex2p1 = pow(b, 4) / 4 - a * b3 / 3 + pow(a, 4) / 12; double ex2p2 = (c3 / 3 - b3 / 3) * (d - c); double ex2p3 = pow(c, 4) / 4 - d * c3 / 3 + pow(d, 4) / 12; double ex2 = (ex2p1 + ex2p2 + ex2p3) / ((d - b) * (d - c)); return ex2 - pow((a + d) / 2, 2); } Note that this formula is only valid for symmetric trapezoidal distributions. As an example, if you call this method with a displacement of 2.5 (varSymTrapezoid(2.0, 10.0, 2.5)) it'd give you back a variance of approximately 3.0416 which is too low (we need 4.0), meaning that a displacement of 2.5 is too much (higher displacements give lower variances). The variance expression is a 4th order polynomial in x that I'd rather not want to solve analytically. However, for a target x in the admissible range this expression is monotonically decreasing, so we can construct a function that crosses zero for our target variance and solve this by simple bisection. This is Step 2: /** * Find the displacement {@code x} for the given {@code stddev} by simple * bisection. * @param min support lower bound * @param max support upper bound * @param stddev the standard deviation we want * @return the length {@code x} of {@code d - c = b - a} that yields a * standard deviation roughly equal to {@code stddev} */ static double bisect(double min, double max, double stddev) { final double eps = 1e-4; final double var = pow(stddev, 2); int iters = 0; double a = eps; double b = (max - min) / 2 - eps; double x = eps; double dx = b - a; while (abs(dx) > eps && iters < 150 && eval(min, max, x, var) != 0.0) { x = ((a + b) / 2); if ((eval(min, max, a, var) * eval(min, max, x, var)) < 0.0) { b = x; dx = b - a; } else { a = x; dx = b - a; } iters++; } if (abs(eval(min, max, x, var)) > eps) { throw new RuntimeException("failed to find solution"); } return x; } /** * Function whose root we want to find. */ static double eval(double min, double max, double x, double var) { return varSymTrapezoid(min, max, x) - var; } Calling the bisect method with the desired value 2.0 for the standard deviation (bisect(2.0, 10.0, 2.0)) gives us the needed displacement: ~ 1.1716. Now that the value for x is known, the final thing we have to do is to construct a suitably distributed random variable which is Step 3: It is a well-known fact of probability theory that the sum of two independent uniformly distributed random variables X1 ~ U[a1, b1] and X2 ~ U[a2, b2] is a symmetric trapezoidally distributed random variable on the interval [a1 + a2, b1 + b2] provided that either a1 + b2 < a2 + b1 (case 1) or a2 + b1 < a1 + b2 (case 2). We have to avoid the case a2 + b1 = a1 + b2 (case 3) since then the sum has a symmetric triangular distribution which we don't want. We'll choose case 1 (a1 + b2 < a2 + b1). In that case the length of b2 - a2 will be equal to the "displacement" x. So, all we have to do is to choose the interval boundaries a1, a2, b1 and b2 such that a1 + a2 = min, b1 + b2 = max, b2 - a2 = x and the above inequality is fullfilled: /** * Return a pseudorandom double for the symmetric trapezoidal distribution * defined by the triple {@code (min, max, x)} * @param min support lower bound * @param max support upper bound * @param x length of {@code max - c = b - min}, constrained to lie in the * open interval {@code (0, (max-min)/2)} */ public static double symTrapezoidRandom(double min, double max, double x) { final double a1 = 0.5 * min; final double a2 = a1; final double b1 = max - a2 - x; final double b2 = a2 + x; if ((a1 + b2) >= (a2 + b1)) { throw new IllegalArgumentException(); } double u = a1 + (b1 - a1) * rnd.nextDouble(); double v = a2 + (b2 - a2) * rnd.nextDouble(); return u + v; } Calling symTrapezoidRandom(2.0, 10.0, 1.1716) repeatedly gives you random variables that have the desired distribution. You could do very similar things with other, more sophisticated, distributions like the Beta. This would give you other (usually more flexible) bounds on the admissible variances but you'd need a 3rd party library like commons.math for that. abs, pow, sqrt in the code refer to the statically imported java.lang.Math methods and rnd is an instance of java.util.Random.
{ "pile_set_name": "StackExchange" }
Q: Derivative of $\tan(xy^3)$ Can somebody tell me if I'm right on this? The math looks right, yet it just feels so wrong due to the obscene steps I had to take to get it. I hope I transcribed all that correctly from my paper. $y=\tan(xy^3)$ $y'=\sec^2(xy^3)(y^3+3xy^2y')$ $\frac{y'}{\sec^2(xy^3)}=y^3+3xy^2y'$ $\frac{y'}{\sec^2(xy^3)}-3xy^2y'=y^3$ $y'(\cos^2(xy^3)-3xy^2)=y^3$ $y'=\frac{y^3}{\cos^2(xy^3)}$ Edited to substitute $\frac{1}{\sec^2(xy^3)}$ for $\cos^2(xy^3)$ A: Looks good, but I'd rewrite it after step $5$ using $$\frac1{\sec^2(xy^3)}=\cos^2(xy^3).$$ In response to OP's edit: Now you've goofed going from $5$ to $6$. Take another look.
{ "pile_set_name": "StackExchange" }
Q: Add markers from rails database I'm creating a map with Google Maps API to reference restaurants based on their location. Each restaurant in my database (sqlite3) has a title, a description and two coordinates (latitude, longitude). I can successfully create entries in my database but struggle to find a solution to call in JS each restaurant's coordinates from the database. Different solutions have been proposed on Stackoverflow of which this one, another and a last one, but none of the answers my question as I'm working exclusively with JS and Ruby (on rails). Would you have suggestions ? A: First, you need to read this example from Goolge Maps Javascript API and play with this code: <!DOCTYPE html> <html> <head> <style> #map { height: 400px; width: 100%; } </style> </head> <body> <h3>My Google Maps Demo</h3> <div id="map"></div> <script> function initMap() { var uluru = {lat: -25.363, lng: 131.044}; var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: uluru }); var marker = new google.maps.Marker({ position: uluru, map: map }); } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY&callback=initMap"> </script> </body> </html> As you can see here, you need to create your own GOOGLE_MAPS_API_KEY here create div with id; connect Google's javascript, which when will load, will load also js-function initMap() define initMap-function with map and marker settings. Next step: getting data from database and passing to JavaScript. I used gon gem for transferring data from backend to frontend: in controller: # app/controllers/application_controller.rb def root gon.locations = Location.all end in layout: <!-- app/views/layouts/application.html.erb --> <head> <%= include_gon %> <!-- ... --> </head> in view: <!-- app/views/application/root.html.erb --> <script> function initMap() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: { lat: gon.locations[0].lat, lng: gon.locations[0].lng } }); for(var i = 0; i < gon.locations.length; i++){ new google.maps.Marker({ position: { lat: gon.locations[i].lat, lng: gon.locations[i].lng }, title: gon.locations[i].name, map: map }); } } <script> But, if you don't want use gon gem for passing data from backend to frontend, you can do this by plain rails: # app/controllers/application_controller.rb def root @json_data = { locations: { # ... }, # ... }.to_json end <!-- views/posts/edit.html.erb --> <script> var json_data = JSON.parse('<%= raw(escape_javascript(@json_data)) %>'); </script> Also, I created rails demo application, you can play with it. This commit doing all job, to write 'ICE' word by markers on Antarctica. See these files for more details: app/controllers/application_controller.rb app/views/application/root.html.erb app/views/layouts/application.html.erb I used this online service to create coordinates for 'ICE' word A: One way you could try is by using json. For example in the controller. class RestaurantsController < ApplicationController def show @restaurant = Restaurant.find(params[:id]) respond_to do |format| format.html format.json {render json: @restaurant} end end end Then the restaurant can be accessed in javascript (I'll use JQuery) $.getJSON("show_page_url.json", function(data){ //data will contain the @restaurant object //so data.latitute should return the value } Maybe this helps. I used it for a simple project I did recently, but maybe there are better methods.
{ "pile_set_name": "StackExchange" }
Q: How to change until the next character (vim), (with the next character can be a set of many) With VIM you can change until an underscore for eg: ct_ But is there a way to select multiple characters? Say for example you may want to change until the first underscore or dash -. Is it possible to do this with vim? A: You will need search for that: c/[_-]<CR> " forward search c?[_-]<CR> " backward search
{ "pile_set_name": "StackExchange" }
Q: How to create query specific projections with Vertica Database Designer? How should the script be fed to Vertica's database designer when I want to create query-specific projections ? Can I write more then one SELECT statement inside the file that will be provided as input to the DB designer? A: Create a text file with the queries you want to optimize for. When prompted in the DBD process, point it to that file. When I was working on/discussing optimxation using Vertica Database Designer it seems like the recommended upper limit for queries in the file was 100. If you want to weigh a query more heavily, put that in multiple times.
{ "pile_set_name": "StackExchange" }
Q: trouble starting lift I'm running through setting up my first lift web-app from Lift in Action. When I run the jetty command after running sbt, I get the following: [root@localhost lift-app]# sbt [info] Building project lift-travel 1.0 against Scala 2.8.0 [info] using LiftProject with sbt 0.7.7 and Scala 2.7.7 > jetty [info] [info] == copy-resources == [info] == copy-resources == [info] [info] == compile == [info] Source analysis: 1 new/modified, 0 indirectly invalidated, 0 removed. [info] Compiling main sources... [error] /home/Ramy/lift-app/src/main/scala/bootstrap/liftweb/Boot.scala:5: value liftweb is not a member of package net [error] import net.liftweb._ [error] ^ [error] one error found [info] == compile == [error] Error running compile: Compilation failed [info] [info] Total time: 3 s, completed Jan 29, 2012 8:11:59 PM I can post my config if need be but i'm hoping this is enough. A: For some reason the specs library isn't in the repository anymore. Unless you absolutely need specs unit testing you can comment out the dependency. Simply go to this line val specs = "org.scala-tools.testing" %% "specs" % "1.6.6" % "test->default" : import sbt._ class LiftProject(info: ProjectInfo) extends DefaultWebProject(info) { val liftVersion = "2.1" /** * Application dependencies */ val webkit = "net.liftweb" %% "lift-webkit" % liftVersion % "compile->default" val logback = "ch.qos.logback" % "logback-classic" % "0.9.26" % "compile->default" val servlet = "javax.servlet" % "servlet-api" % "2.5" % "provided->default" val jetty6 = "org.mortbay.jetty" % "jetty" % "6.1.22" % "test->default" val junit = "junit" % "junit" % "4.5" % "test->default" //val specs = "org.scala-tools.testing" %% "specs" % "1.6.6" % "test->default" val mapper = "net.liftweb" %% "lift-mapper" % liftVersion /** * Maven repositories */ lazy val scalatoolsSnapshots = ScalaToolsSnapshots } And comment it out and sbt will hum along nicely. From David Pollak (from liftweb@goolegroups mailing list): Scala is very version fragile. That means that a version of a library must be compiled against the same version of Scala and any other dependent libraries. Specs bumps its version number for each Scala release. So, if you change the version of Scala, the particular version of Specs will not be found because it does not match the given version of Scala. You can find the correct version of Specs for the given version of Scala on the Specs home page: http://code.google.com/p/specs/
{ "pile_set_name": "StackExchange" }
Q: JSF form value disappears on submit When I try to submit a form, the input value is present in the validation-method, but gone in the submit-method. Why the input-property blank by the time the program reaches the submit-function? Input: asdf genres.xhtml <h:form> <h:inputText id="userGenre" value="#{genres.input}" validator="#{genres.validateLength}" required="true" size="3" /> <h:commandButton value="Add genre" action="#{genres.submit}" /> <h:message for="userGenre" /> </h:form> Genres.java @Named @SessionScoped public class Genres { static final Logger LOG = LoggerFactory.getLogger(Genres.class); private String input = ""; public void validateLength(FacesContext context, UIComponent toValidate, Object value) { LOG.info("Validating"); input = (String) value; LOG.info("name:"+input); // result: "name:asdf" int min = 3; int max = 15; int len = input.length(); if (len < min || len > max) { ((UIInput) toValidate).setValid(false); FacesMessage message = new FacesMessage("Must be at least 3 and at most 15 characters."); context.addMessage(toValidate.getClientId(context), message); return; } } public void submit() { LOG.info("Submitting"); LOG.info("name:"+input); // result: "name:" // process input } public String getInput() { return input; } public void setInput(String input) { this.input = input; } } faces-config.xml <managed-bean> <managed-bean-name>genres</managed-bean-name> <managed-bean-class>no.krystah.Genres</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> <managed-property> <property-name>input</property-name> <property-class>java.lang.String</property-class> <value/> </managed-property> </managed-bean> A: in the #{genres.submit} when you try to submit then JSF will generate a new instance of your Genres class so input is blank but if you use @ManagedBean annotation on the top of your Genres class I think the code should work well
{ "pile_set_name": "StackExchange" }
Q: Do i need to set up security rules in Firebase, if i only use it for analytics and crashes? Firstly: I am using currently Firebase only for analytics (users count) and crashes for mobile app. No usage of Firebase Storage, Realtime Database or Firestore (none of those were configured or set up). Question: Do I still need to define some security rules in the Firebase? A: When you create a Firebase project, neither of the databases nor a storage bucket are auto-created. So at that point there is no risk of them being abused by malicious users. If you create a database or storage bucket through the console, it will ask what security rules to apply. If you select the restrictive rules there (the ones that have false in them, the database or bucket will be inaccessible, so there's also no risk of abuse. If you (accidentally) pick the more permissive rules though, users can access your database or bucket, even when your application does not. In that case, you'll want to set the most restrictive rules: Realtime Database { "rules": { ".read": false, ".write": false } } source Firestore // Deny read/write access to all users under any conditions service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if false; } } } source Storage // Access to files through Firebase Storage is completely disallowed. service firebase.storage { match /b/{bucket}/o { match /{allPaths=**} { allow read, write: if false; } } } source
{ "pile_set_name": "StackExchange" }
Q: I need textarea to take the rest of space I am new in HTML. I am trying to have two text area: top and bottom. I need bottom to be at the bottom of its tab with 5 rows height. top must take the rest of space. In a wide screen it does not appear as it should. How can I implement it? <!DOCTYPE html> <html> <head> <title>Title</title> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </head> <body> <ul class="nav nav-tabs"> <li><a href="#tasks" data-toggle="tab">tasks</a></li> <li><a href="#save" data-toggle="tab">save</a></li> </ul> <div class="tab-content"> <div class="tab-pane active" id="tasks"> <div style="width:100%;height:100%"> <textarea id="top" style="width:100%; height:100%;"> TOP: Must be wide height </textarea> <textarea id="bottom" rows="5" style="width:100%;"> BOTTOM: size is ok. Position must be bottom </textarea> </div> </div> <div class="tab-pane" id="save"> </div> </div> </body> </html> A: I dont know a lot about bootstrap. but i know about css enough... take a look at code I wrote : body .tab-content{ height:calc(100% - 42px); position:absolute; top:42px; left:0; width:100%; } body .tab-pane{ height:100%; } textarea{ padding:0; margin:0; } <!DOCTYPE html> <html> <head> <title>Title</title> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </head> <body> <ul class="nav nav-tabs"> <li><a href="#tasks" data-toggle="tab">tasks</a></li> <li><a href="#save" data-toggle="tab">save</a></li> </ul> <div class="tab-content"> <div class="tab-pane active" id="tasks"> <textarea id="top" style="width:100%; height:calc(100% - 104px);"> TOP: Must be wide height </textarea> <textarea id="bottom" rows="5" style="width:100%;height:100px"> BOTTOM: size is ok. Position must be bottom </textarea> </div> <div class="tab-pane" id="save"> </div> </div> </body> </html> the ask for any questions...
{ "pile_set_name": "StackExchange" }
Q: Keep div on top when scrolling but keep margin title is a little bit stupid. I have a page, probably full of errors. Either way, there's a Navi and a text box. Navi left, text box right. Navi shall scroll up until it raches top of the window and then stay there. I got that to work so far. Copied and used codes I found, since I am a noob in Javascript. Something happens to the text box though, just at the moment when the Navi changes from relative to fixed position. The text box ignores the Navi and just writes over it. I had the Navi on fixed before I used the stick to top script and it all worked fine. Here's the page: http://test.pluskat.de/StuckWeit/ Ignore background image. What to do or what to change? I am totally confused myself by now with all the positioning. Please help. Remember I'm a noob in Javascript. I might be able to follow you, but please describe what is to be done, so others might be able to learn from it too. Thank You. You guys are my last hope. A: To fix this issue you could try adding below style at the end of the style.css file. #wrapper { width: 1024px; /*Add this if you have fixed width layout else ignore*/ position: relative; } #textbox { position: absolute; left: 220px; height: auto; }
{ "pile_set_name": "StackExchange" }
Q: 2 Tables - one customer, one transactions. How to handle a customer with no transaction? I have 2 tables-one customers, one transactions. One customer does not have any transactions. How do I handle that? As I'm trying to join my tables, the customer with no transaction does not show up as shown in code below. SELECT Orders.Customer_Id, Customers.AcctOpenDate, Customers.CustomerFirstName, Customers.CustomerLastName, Orders.TxnDate, Orders.Amount FROM Orders INNER JOIN Customers ON Orders.Customer_Id=Customers.Customer_Id; I need to be able to account for the customer with no transaction such as querying for least transaction amount. A: INNER Joins show only those records that are present in BOTH tables OUTER joins gets SQL to list all the records present in the designated table and shows NULLs for the fields in the other table that are not present LEFT OUTER JOIN (the first table) RIGHT OUTER JOIN (the second table) FULL OUTER JOIN (all records for both tables) Get up to speed on the join types and how to handle NULLS and that is 90% of writing SQL script. Below is the same query with a left join and using ISNULL to turn the amount column into 0 if it has no records present SELECT Orders.Customer_Id, Customers.AcctOpenDate, Customers.CustomerFirstName, Customers.CustomerLastName , Orders.TxnDate, ISNULL(Orders.Amount,0) FROM Customers LEFT OUTER JOIN Orders ON Orders.Customer_Id=Customers.Customer_Id;
{ "pile_set_name": "StackExchange" }
Q: Expand Graphics based on all elements How might I force the following Graphics element to expand to contain the Inset text? Graphics[{White, Rectangle[{0., 0.0}, {1, 1}], Yellow, Rectangle[{0., 0.0}, {.2, 1}], Black, Inset[ Style[ToString[Unevaluated@abcdefghijklmnopqr], FontSize -> Scaled[.4]] , ImageScaled[{0.2753623188405797, 0.48550724637681175}], {Left, Center}] }, ImagePadding -> 0, PlotRangePadding -> 0, PlotRangeClipping -> True] The following gives the desired output although it doesn't solve the issue because ultimately I am trying to nest the text inside another Graphics element: Row[{Graphics[{}, ImageSize -> {10, 23}, Background -> Yellow],Text["abcedefghijklmnopqr"]}]. Ultimately I have several nested Insets but unfortunately I can't seem to force the Insets to nest inside of each other and therefore show entirely on the screen. These plot range questions seems to be related. The first question titled "How to determine PlotRange to include all Graphics" is likely a duplicate, although I believe you must ImageSize and PlotRange to get correct values. A: The threat of nested Insets makes me quail. I find it hard to use, although occasionally I can get it right. Text in an Inset poses an additional problem because many options are automatically handled for you by the Front End, although not always the way you wanted. It seems knowledge of the plot range(s) and image size(s) is helpful in getting it right, as alluded to in the statement of the question. Here's a way, used in this question, to convert text to Graphics primitives. Inset may be avoided altogether. text = First /@ ImportString[ ExportString[ Style[ToString[Unevaluated@abcdefghijklmnopqr], FontFamily -> "Times New Roman"], "PDF"], "PDF"]; {bottomLeft, topRight} = Transpose[{Min[#], Max[#]} & /@ Transpose@Cases[text, {_Real, _Real}, Infinity]]; textheight = 1; Graphics[{White, Rectangle[{0., 0.0}, {1, 1}], Yellow, Rectangle[{0., 0.0}, {.2, 1}], Black, Translate[ (* translate and scale the text to fit *) Scale[text, textheight / Last[topRight - bottomLeft], bottomLeft], -bottomLeft + {0.3, 0}]}] Because the glyphs are represented as FilledCurves they are rescaled with the graphics when the image changes size.
{ "pile_set_name": "StackExchange" }
Q: How to get the rows in a Datagrid that are customized in c#? I have a Datagrid with n rows. And some of the rows of the datagrid have the backcolor as green. I also have a button. How can I disable the button when no rows of my Datgrid are in green. A: Get the count of green colored cells int greenColuredCells = (dgv.Rows.Cast<DataGridViewRow>() .Where(r => r.Cells[0].Style.BackColor == Color.Green) .Count(); and use this to hide show butten btn.enable = greenColuredCells>0;
{ "pile_set_name": "StackExchange" }
Q: Browser ignores table-layout:fixed I fail to implement a fixed table layout. If a table cell has more content than would fit into it, the table is relayouted as if the table layout was set to auto. Here is the HTML code <!DOCTYPE html> <html> <head> <title>Table test</title> <meta charset="UTF-8" /> <link rel="stylesheet" type="text/css" href="<path here>" /> </head> <body> <table> <thead> <tr> <th class="number">Number</th> <th class="name">Name</th> <th class="type">Type</th> <th class="comment">Comment</th> <th class="buttons"></th> </tr> </thead> <tbody> <tr> <td>42</td> <td>This name is really long and is supposed to be truncated</td> <td>Normal</td> <td>I don't know what to say</td> <td><button>Edit...</button></td> </tr> </tbody> </table> </body> </html> The CSS is table { border-collapse: collapse; table-layout: fixed; } th { font-weight: bold; text-align: left; } td { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } tr { border-top: 1px solid #000000; border-bottom: 1px solid #000000; } th.number { width: 6rem; } th.name { width: 15rem; } th.type { width: 17rem; } th.comment { width: 15rem; } th.buttons { width: 17rem; } Here is a fiddle. The problem is that the 2nd column ("name") is increased until the content fits. What am I doing wrong? A: You need to set width on the table element, because the definition of Fixed table layout says: “The table's width may be specified explicitly with the 'width' property. A value of 'auto' (for both 'display: table' and 'display: inline-table') means use the automatic table layout algorithm. However, if the table is a block-level table ('display: table') in normal flow, a UA may (but does not have to) use the algorithm of 10.3.3 to compute a width and apply fixed table layout even if the specified width is 'auto'.” (Note that auto is the default value.) This is awkward, but to get fixed layout, you need to add table { width: calc(40rem + 10px); } Here 40rem is the sum of the widths you are setting for the columns, and 10px accommodates the default padding in cells (1px on the left and right in each cell). Older browsers don’t support the calc construct, but you are already taking risks by using the rem unit.
{ "pile_set_name": "StackExchange" }
Q: Google apps script how to parse a link and extract the document ID? Given a document link, is there a simple method wich allow me to extract the ID from a google document? Or the only way is write a script that do something like this: var linkString = "https://docs.google.com/spreadsheet/ccc? key=0AmEr9uNtZwnNdFNkNklYc3pVUzZINUV4eUtWVWFSVEf&usp=drive_web#gid=1" var docID = ''; for (i=0; i<=linkString.length(); i++) { if (linkString[i] = '='){ while (linkString[i] !== '&') { docID =+ linkString[i]; i+=1 ; } return docID } } A: You could make it simple using the split method var url = "https://docs.google.com/spreadsheet/ccc? key=0AmEr9uNtZwnNdFNkNklYc3pVUzZINUV4eUtWVWFSVEf&usp=drive_web#gid=1" var id = url.split('key=')[1].split('&')[0]; Logger.log(id)
{ "pile_set_name": "StackExchange" }
Q: Detect Exchange version by Redemption does anybody know how to detect Exchange server version when connected by Redemption? rdoSession.ExchangeMailboxServerName returns the machine name rdoSession.ExchangeMailboxServerVersion returns something like "14.3.181.4006" what I need to find out is whether its 2007 or 2010, etc. A: You have enough information to determine the exact version of Exchange you are connected to. The ExchangeMailboxServerVersion is returning the build number of the server you are connecting to, and you can compare this number to a list of server versions. For example, I know that the build number you reference is Update Rollup 5 for Exchange Server 2010 SP3. For a list of the build numbers, product names, and release dates check out this article on TechNet: Exchange Server Build Numbers and Release Dates I hope this helps. If this does resolve your question, please mark this post as answered. Thanks, --- Bob ---
{ "pile_set_name": "StackExchange" }
Q: Isometric isomorphism between Hardy Space $h^p(\mathbb{D})$ and $L^p(\mathbb{T})$ I know the question below is a known result but, I would need some help to prove it! Well, I know that in the Poisson integral induces an isometric isomorphism between $L^p(\mathbb{T})$ and the Hardy space $h^p(\mathbb{D})$ for $p>1$. I'm reading Function Spaces and Partial Differential Equations: Classical analysis and this question is the remark 5.24 but it's not proved. Now how can I do to prove this? Thanks. EDIT: The definition of $h^p$ that I have is this: $h^p(\mathbb{D})=\{u\in Har{\mathbb{D}: ||u||_{h^p}=sup_{0<r<1}M_{p}(u,r)< \infty}$}, where the $Har\{\mathbb{D}\}$ are the group of harmonic functions while $M_{p}(u,r)=(\int_{-\pi}^{\pi}|u(re^{it})|^p\frac{dt}{2 \pi})^\frac{1}{p}$. A: It's a good thing I asked for the definition, because it turns out that what you mean by $h^p$ is not what I thought you meant! FYI the reason I was thrown off is that $h^p$ is not what's usually called a Hardy space; I could tolerate calling it a "harmonic Hardy space". Say $u=P[f]$ and define $$u_r(t)=u(re^{it}).$$Then $u_r=f*P_r$ (where the $*$ denotes convolution), so if $f\in L^p(\Bbb T)$ then $$||u_r||_{L^p(\Bbb T)}\le||P_r||_1||f||_p=||f_p||.$$ So $||u||_{h^p}=\sup_r||u_r||_p\le ||f||_p$. On the other hand, we know that $u_r\to f$ almost everywhere, so Fatou's Lemma shows that $$||f||_p\le\liminf_r||u_r||_p\le\sup_r||u_r||_p.$$
{ "pile_set_name": "StackExchange" }
Q: switch between layouts in flex4 i have the list shown below with 2 layouts between which i switch: <s:List id="list" width="100%" height="100%" dataProvider="{ recordingsShown }" itemRenderer.CoverflowState="components.VideoItemRenderer" itemRenderer.TileState="components.VideoItemRenderer2" selectedIndex="0"> <s:layout.CoverflowState> <Layouts:CoverflowLayout id="coverflow" selectedIndex="{ list.selectedIndex }" horizontalDistance="103" selectedItemProximity="75" depthDistance="1" elementRotation="-70" focalLength="300" perspectiveProjectionX="-1" perspectiveProjectionY="-1"/> </s:layout.CoverflowState> <s:layout.TileState> <s:TileLayout orientation="columns" columnAlign="justifyUsingWidth" rowAlign="justifyUsingHeight" requestedColumnCount="-1" requestedRowCount="-1" paddingBottom="5" paddingLeft="5" paddingRight="5" paddingTop="5" verticalGap="10" horizontalGap="10"/> </s:layout.TileState> </s:List> 1) The problem is that i get Error #1009: Cannot access a property or method of a null object reference. at Layouts::CoverflowLayout/animationTickHandler()[line:201] at flash.utils::Timer/_timerDispatch() at flash.utils::Timer/tick() when i switch from coverflow to tilelayout and i think its because the effect used in the coverflow has not ended and i switch to the other layout,any help?. Coverflow layout used 2) how can i use any transition effect between them so as to be more "sweet" the switch between them!? Thanks in advance! A: The problem might be that some parts inside the list aren't created yet. When you using states, by default, the components are created on the first switch to this state Try to play around with the creation policy adobe documentation
{ "pile_set_name": "StackExchange" }
Q: Global.asax template not available in Visual Studio When I attempt to "add new item" to my web project (by right-clicking, add new item) - there is no template for it. What might the problem be? I'm using VS2008. Additional Info: When I right click on the solution and "Add", "New Web Site" - I have zero tempates to choose from. I have tried running devenv /installvstemplates and this template box is still empty. I have only three templates in the following directory. Is there somewhere I can just copy the other templates from manually? C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\Web\CSharp\1033 A: Unfortunately, the answer for me was re-installing VS. Not exactly sure what the issue was, but that fixed it.
{ "pile_set_name": "StackExchange" }
Q: Constants in multivariable integration I'm reviewing multivariable integrals, and the constants are confusing me. If I have: $$ f(x, y) = \int \frac{\partial f(x,y)}{\partial x} dx $$ $$ f(x, y) = \int 2xy \,dx $$ factor out $y$ which is treated as a constant. $$ f(x, y) = y \int 2x \,dx $$ But, I expected $$ f(x, y) = 2y \int x \,dx $$ Since $2$ is also a constant. The question is, why factor out $y$ and not $2$ as well. What am I missing? A: It is perfectly correct to pull out the $2$. But $$ \int 2x\,dx= x^2+\text{constant} $$ and $$ 2\int x\,dx = 2\left( \frac {x^2}{2}\right)+\text{constant} = x^2+\text{constant} $$ so the first way is a bit simpler.
{ "pile_set_name": "StackExchange" }
Q: ¿Cómo se puede usar las dos columnas de resultado de un SELECT en un UPDATE en SQL? Basicamente mi problema es que tengo una consulta bastante compleja para poder obtener la suma de productos que vendio cada empleado, la cual es la siguiente: SELECT SUM(Quantity)AS productosven, EmployeeID FROM(SELECT Orders.OrderID,Orders.EmployeeID,[Order Details].Quantity FROM Orders INNER JOIN DimEmployee ON Orders.EmployeeID=DimEmployee.EmployeeID INNER JOIN [Order Details] ON [Order Details].OrderID=Orders.OrderID)AS X GROUP BY EmployeeId El resultado de la consulta anterior es: Y es necesaria que sea así de compleja, ya que en la tabla Orders tengo el OrderID y el EmployeeID y en la tabla [Order Detail] tengo el OrderID y la cantidad de producto. Lo que hace es obtenerme dos columnas en las cuales de un lado tengo todos los productos que ese empleado vendió y del otro obtengo el id de ese empleado, y ahora intento meter eso en un update, de la siguiente manera: UPDATE DimEmployee SET N_Productos =(SELECT SUM(Quantity)AS productosven, EmployeeID FROM(SELECT Orders.OrderID,Orders.EmployeeID,[Order Details].Quantity FROM Orders INNER JOIN DimEmployee ON Orders.EmployeeID=DimEmployee.EmployeeID INNER JOIN [Order Details] ON [Order Details].OrderID=Orders.OrderID)AS X GROUP BY EmployeeId) WHERE EmployeeID=(SELECT EmployeeID FROM(SELECT Orders.OrderID,Orders.EmployeeID,[Order Details].Quantity FROM Orders INNER JOIN DimEmployee ON Orders.EmployeeID=DimEmployee.EmployeeID INNER JOIN [Order Details] ON [Order Details].OrderID=Orders.OrderID)AS X GROUP BY EmployeeId) Pero me dice que no es posible ya que devuelve varios resultados, me imagino que es por que uso la misma consulta dos veces, una en el set y otra en el where, pero no se. UPDATE DimEmployee SET N_Productos =(SELECT SUM(Quantity)AS productosven, EmployeeID FROM(SELECT Orders.OrderID,Orders.EmployeeID,[Order Details].Quantity FROM Orders INNER JOIN DimEmployee ON Orders.EmployeeID=DimEmployee.EmployeeID INNER JOIN [Order Details] ON [Order Details].OrderID=Orders.OrderID)AS X GROUP BY EmployeeId) Y de esta forma me aparece este error: Mens. 116, Nivel 16, Estado 1, Línea 7 Sólo se puede especificar una expresión en la lista de selección cuando la subconsulta no se especifica con EXISTS. A: En SQLServer puedes hacer una consulta de actualización, algo bastante útil, conceptualmente es algo así: UPDATE Tabla1 SET Columna = T2.OtraColumna FROM Tabla1 T1 INNER JOIN Tabla2 T2 ON T1.AlgunId = T2.AlgunId Si te fijas bien es casi una consulta habitual a la que se le ha agregado las sentencias de UPDATE. Adaptando un poco tu consulta, podrías hacer algo así: UPDATE DimEmployee SET N_Productos = G.productosven FROM DimEmployee E INNER JOIN (SELECT SUM(Quantity) AS productosven, EmployeeID FROM (SELECT Orders.OrderID, Orders.EmployeeID, [Order Details].Quantity FROM Orders INNER JOIN DimEmployee ON Orders.EmployeeID=DimEmployee.EmployeeID INNER JOIN [Order Details] ON [Order Details].OrderID=Orders.OrderID ) X GROUP BY EmployeeId ) G ON E.EmployeeID = G.EmployeeID
{ "pile_set_name": "StackExchange" }
Q: vertex buffer object C++ doesn't appear I write the following simple code to learn how to use vbo, but doesn't appear anything: GLuint vbo=0; GLfloat data[] = {175.0, 25.0, 0.0, 1.0, 0.0, 0.0, 100.0, 325.0, 0.0, 0.0,1.0,0.0, 250.0, 25.0, 0.0, 0.0, 0.0, 1.0}; void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(data),data, GL_STATIC_DRAW); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, 0); glEnableClientState(GL_COLOR_ARRAY); glColorPointer(3, GL_FLOAT, 0, (void*)(3*sizeof(float)) ); glDrawArrays(GL_TRIANGLES, 0,3); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); glutSwapBuffers(); glFlush(); } void reshape(int w, int h){ glClearColor(0.5,0.2,0.5,1); glViewport(0, 0, (GLsizei) w, (GLsizei) h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, (GLsizei) w, 0, (GLsizei) h, -1,1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } int main(int argc, char** argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(350, 350); glutInitWindowPosition(100, 100); glutCreateWindow("VBO"); glutDisplayFunc(&display); glutReshapeFunc(reshape); glutMainLoop(); } Where are the errors? A: You're passing a stride of 0, which means the data should be tightly packed (all vertices together, all colours together etc). But your data array appears to be interleaved. Change the pointer calls to: glVertexPointer(3, GL_FLOAT, 6 * sizeof(GLfloat), 0); glColorPointer(3, GL_FLOAT, 6 * sizeof(GLfloat), (void*)(3 * sizeof(GLfloat))); As a side note, you definitely shouldn't be generating a brand new VBO in each call to display().
{ "pile_set_name": "StackExchange" }
Q: Prawn: anchor middle of the text to the given point Prawn has height_of_formatted method to determine, well, height of formatted text, so its top left coordinate could be calculated when one needs to vertically align the middle of it to some anchor. But there is no width_of_formatted method. I'm drawing graph, and I need the text (dot label) to be centered right above some point (dot itself). So I know that middle of the text has x-coordinate of the dot. How do I get x-coordinate of the beginning of the text (so I could provide it to draw_text and other rendering methods)? A: If you use bounding_box instead of draw_text you can specify the width of the bounding box for the text. Then if you centre-align the text you should be able to specify the exact x-coordinate of the middle. (it's the x-position of the box plus half the width) Let's say you had a point at x-coordinate 72 and you want to put the label "hello world!" so the centre of the word is the same x-coordinate. You don't know how wide the word "hello" is but you're sure it'll fit inside a box of width 500. 72 - (500/2) = -178 bounding_box([-178, 100], :width => 500) do text "hello world!", align => :center end
{ "pile_set_name": "StackExchange" }
Q: How to show list of files with cyrillic name only? How do I can see in my directory, list of files, that have a Cyrillic name by using terminal, awk, and other stuff? If I'm trying all Russian symbols in find, it's like make terminal broken or stuff. not sure what example I need to give. I need to see a list of files, that name is written via Cyrillic symbols. what I tried? I tried "find" and use all buttons on Russian keyboard like "й ц у к е н г ш щ з х ъ ф ы в а п р о д ж э я ч с м и т ь б ю" and when I wrote it like "й","ц" it doesn't work. But I don't think its a problem because I made it just because I don't know how to chose only Cyrillic symbols. And it doesn't matter if it will show also Ukranian names or Belarus, or any else Cyrillic, so I want to ask how to show a list of Cyrillic names of files in my directory. A: List all files in the current directory that contains Russian characters in their names: find . -type f -name "[А-Яа-яЁё]*"
{ "pile_set_name": "StackExchange" }
Q: pass TextBox value to variable within SUB I have a form (named DateForm) that contains a textbox (named txt_AsOfDate), which displays a date value. I have a separate SUB which has the following code: Sub Test() Dim AsOfDate As String AsOfDate = txt_AsOfDate.Text MsgBox (AsOfDate) End Sub When running it, I get the following error: Run-time error '424': Object required What is going on? I tried loading the DateForm at the beginning of the SUB, and also tried assigning the value by further defining the object schema like below, but no luck. What am I doing wrong? AsOfDate = DateForm.txt_AsOfDate.Value A: Try replacing txt_AsOfDate.Text with Form_DateForm.txt_AsOfDate.Text. Referring to a control directly in code by its name only works in the form, whereas I'm guessing this code is in a separate module. In order to catch things like this, add Option Explicit to the top of your code modules. This forces the compiler to notify you if there is a variable being used which wasn't first declared with Dim.
{ "pile_set_name": "StackExchange" }
Q: What makes Night Elves flip when jumping in World of Warcraft? Is there some timing associated with Night Elves jump-flipping? Or is it just random? A: About a 1/5 chance for them to do a flip. Completely random. Blood elves spin are about half the chance. A: It's just random. I've seen speculation of somewhere between a 10 and 20% chance.
{ "pile_set_name": "StackExchange" }
Q: Does the barking of a dog diminish the value of a priest? Does a barking of a dog diminish the value of a priest? The above is an Idiom from Indian languages.A dog stands metophorically for the inferior people.The priest stands for the people who are intellectually and spiritually great.The meaning of the idiom is that the profane people never diminish the greatness and holiness of great people simply by mocking at them What is the equal idiom in English apart from the saying of the Egyptians. "A profane person might be tempted to violate the tomb" Edit : My question is not a duplicate because the idiom is different from other idioms : it is the tendency of a dog to bark at a thief or at a priest . It can not distinguish between good and bad.Every new person seems to be a thief to a dog.So great people are great people even if the inferior people do not recognise them or mock at them.The distance between the great and the profane is always too long A: A contemporary idiom with a similar sense is haters gonna hate. (NB I originally thought it was haters gotta hate, and probably both have some currency). The phrase implies that criticism says more about the critic, or "hater," than the person being criticized, i.e., that they are making judgements out of jealousy or their own negativity. (Source: dictionary.com)
{ "pile_set_name": "StackExchange" }
Q: Clarification regarding methods being used outside a contract in interface in http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html may i now how it was possible to use the to toString Method despite not being stated in the contract? Was it because it was in public so any method that declared public could be used anyway?. A: In Java, every class inherits from Object, and toString() is part of the Object's contract. Thus, any Java object has a toString() method. Additionally, since toString() is non-final, any class can choose to provide its own implementation of the method.
{ "pile_set_name": "StackExchange" }