text
stringlengths
64
89.7k
meta
dict
Q: Any solid textbook recommendations to begin studying linguistics? I need an introductory book that covers the cutting-edge research of the linguistics and most of its big branches. It must be written in a textbook format. The answerer must be well-versed in linguistics (well-versed = engages with the contemporary literature on linguistics on academic level/contributes to it or strives to contribute to it in future), and s/he also must have read more than one introductory book to linguistics (so that the end-review is not skewed). There are a number of well-reviewed introductory linguistics books on Amazon, but I wanted a more systematic answer to my question, and hence the reason I'm posting it here. A: You are asking for impossible things. A textbook, by definition, covers material that is fairly well-established in the field,[*] and note that the degree of difficulty of the material is not a good indicator of how well-established the conclusions are. If you want to know about cutting-edge research, you need to be reading journals and attending conferences. That said, this is what I tend to recommend to my syntax-semantics students (in no particular order). Syntax Radford, Andrew. 2009. Minimalist syntax: exploring the structure of English. Cambridge University Press. Adger, David. 2003. Core syntax. Blackwell. Carnie, Andrew. 2012. Syntax: a generative introduction. Blackwell. Haegeman, Liliane. 1994. Introduction to Government and Binding theory. Blackwell (a bit dated, but useful to understand the background of certain current ideas). Larson, Richard, and Kimiko Ryokai. 2009. Grammar as science. MIT Press (possibly the most basic textbook in this list) Lasnik, Howard, and Juan Uriagereka. 1988. A course in GB syntax. MIT Press (same comments as Haegeman 94 apply). Lasnik, Howard, and Juan Uriagereka. 2005. A course in Minimalist syntax. Blackwell (updated version of Lasnik & Uriagereka 88). Uriagereka, Juan. 1998. Rhyme and reason. MIT Press (written as a Socratic dialogue, which some people dislike, but it highlights why certain issues are important, rather than just explaining how to go about solving them). Pollard, Carl, and Ivan Sag. 1994. Head-Driven Phrase Structure Grammar. University of Chicago Press (about same status as Haegeman 94). Sag, Ivan, Thomas Wasow, and Emily Bender. 2003. Syntactic Theory: a formal introduction. CSLI. Bresnan, Joan. 2001. Lexical-functional grammar. Blackwell. Semantics Heim, Irene, and Angelika Kratzer. 1998. Semantics in Generative Grammar. Blackwell. Iatridou, Sabine, and Kai von Fintel. 2010. Intensional semantics. Available from KvF's website. Chierchia, Gennaro, and Louise McNally. 2000. Meaning and grammar: an introduction to semantics. MIT Press. Larson, Richard, and Gabriel Segal. 1995. Knowledge of meaning: an introduction to semantic theory. MIT Press. [*] or at least in the relevant subfield. For example, you tend to see textbooks with titles like "Introduction to [name of theoretical framework]". What you find in those are things that are well-established within the framework in question, even though there might be competing frameworks that propose pretty different ways of doing things.
{ "pile_set_name": "StackExchange" }
Q: Why must 'if' clause in Perl come with either curly brackets or nothing? This is ok: if ($some_var==$some_value) {} This is ok too: print "hello" if ($some_var==$some_value); But this raises an error: if ($some_var==$some_value) print "some_message"; Why must 'if' clause in Perl come with either curly brackets or nothing? A: To avoid the well-known problem in compiler construction known as a "dangling else". See http://en.wikipedia.org/wiki/Dangling_else A: Perl has a rather complex syntax and is rather difficult to parse. I gather that curly brackets were made mandatory following an if clause so as to remove an ambiguity and make Perl code easier to parse. A: That's how the perl syntax is defined. The if (expr) BLOCK syntax requires a block, not a statement. See perlsyn ("Compound statements" section). Excerpt: The if statement is straightforward. Because BLOCKs are always bounded by curly brackets, there is never any ambiguity about which if an else goes with.
{ "pile_set_name": "StackExchange" }
Q: How should we understand the plain form when used in novels set in the past? I am trying to understand how the plain form is used in novels set in the past through the explanations in the paper referenced below. I wonder if someone could explain how we should understand the Japanese version of the following examples: Example 24: (1) 広田さんは髭の下から歯を出して笑った。 (2) わりあいきれいな歯を持っている/??持っていた。 (1) hirota-san wa hige no sita kara ha o dasite warat-TA. (2) wariai kireina ha o motte-i-RU/??motte-i-TA. (1) Mr. Hirota SMILED showing his teeth below his moustache. (2) He’D GOT good-looking teeth. Example 25:   (1) 「お出になりませんか」と聞くと、先生は少し笑いながら、無言のまま首を横に振った。 (2) 子どものような所作をする/??した。 (1) “odeni narimasen ka” to kiku to, sensei wa sukosi warai nagara, mugon no mama kubi o yoko ni hut-TA. (2) kodomo no yoona syosa o su-RU/??si-TA. (1) “Wouldn’t you like to go out?” asked Sanshiro, and then Sensei smiled faintly and SHOOK his head without saying a word. (2) That WAS a childlike gesture. Example 29: (1) 「おしだ。」と信吾はつぶやいた。 (2) ぎゃあっと言った蝉とはちがう。 (1) “osida,” to singo wa tubuyai-TA. (2) gyatto itta semi to wa tiga-U. (1) “This one’s mute,” Shingo MUTTERED. (2) It WAS different from the one that had sung so loudly. My limited understanding is that: ta-form are main sentences about the foreground, plain form are about the background. In each case the English translation places the plain form sentence in the past tense and makes it part of the author's narrative but, as the paper explains, this is wrong. You lose the perspective of being there, conveyed by the plain form. In sentence 2 of example 24 the past tense does not work, but I am not sure why. Again in example 2 of example 25 past tense does not work, but I am not sure why. Sanshiro seems to be "thinking" sentence 2 of example 25 but I am not really sure. English translations do always help. Sometimes they feel unnatural. For example, in the second sentence of "Example 25", I am not sure why the author has used "That" instead of "It". "It" (as used in sentence 2 of "Example 29") would have been more natural if the sentence was written from the author's perspective. "That" would fit if sentence was from Sanshiro's perspective, but if it his unspoken observation or the narrative has switched, how are we supposed to tell?, what is the convention? There is a bit more to it than just: background, plain form = time of utterance. In example 29 we are told that sentence two is the "voice" of Shingo's: Are these his actual thoughts or observations, or even just what he could observe? I am confused. My guess is that: Possibly this writing can be likened to the frames in a US-Comic book(?) where: - The authors narrative appears in the rectangular boxes?, - the ta-form sentences represent the words appearing in speech bubbles? - The plain form sentences refer to the images/pictures and the thoughts appearing in the "thought bubbles"? But, I don't really know if this works. I have struggled with explanations in the paper (link below) but if somebody could explain in simple terms how to interpret the plain form sentences above I should be grateful. Paper: TENSE-ASPECT CONTROVERSY REVISITED: THE -TA AND -RU FORMS IN JAPANESE Yoko Hasegawa; Link to paper: http://hasegawa.berkeley.edu/Papers/Hasegawa99.pdf A: To my understanding as a native speaker, in all of the three examples, sentence (1) is written from the author's perspective, and sentence (2) is written from the perspective of a character in the story. The switching of the perspectives is in fact, in these examples, is signalled by the change of the tenses. The sentences in Example 24 could be written in the following way without losing the meaning: (1) 広田さんは髭の下から歯を出して笑った。 (2) わりあいきれいな歯を持っている、とXは思った。 where X is the person who was in front of Hirota. However, without 'とXは思った', readers understand that it is X who thought 'わりあいきれいな歯を持っている'. By not stating 'とXは思った' explicitly, the sentence (2) is somehow, I think, high-lighted as X's impression. Besides, concise composition is preferred in Japanese text; Japanese readers are supposed to be always glad to bear the responsibility to understand the context. Alternatively, these sentences could be written in the following way, too, without losing the meaning: (1) 広田さんは髭の下から歯を出して笑った。 (2) わりあいきれいな歯を持っていた。 In this case, as you said, the sentence (2) is written from the author's perspective. Therefore, the two sentences give information to the readers on the same level, i.e., the author does not intend to highlight how shiny teeth Hirota had for the readers. The three examples you raised have the rather clear effect, i.e., implicit switching of the perspective and highlighting the impression made in a character's mind. However, it is not unusual to mix past tense and present tense (or maybe it is better to say -ta form and -ru form because past and present are not distinguished literally by these forms in the example below), without much reason in Japanese story-telling. If sentences after sentences all end with -ta, I think readers feel the text boring. As long as it is clear that things in the past are described in the context, it is acceptable and probably natural to end a few sentences in the block of the description with -ru. For example, it would be difficult for anyone to explain why some sentences end with -ru and the others end with -ta in the following paragraph from "1Q84" by Haruki Murakami: 青豆というのは彼女の本名である。父方の祖父は福島県の出身で、その山の中の小さな町だか村だかには、青豆という姓をもった人々が実際に何人かいるということだった。しかし彼女自身はまだそこに行ったことがない。青豆が生まれる前から、父親は実家と絶縁していた。母方も同じだ。だから青豆は祖父母に一度も会ったことがない。彼女はほとんど旅行をしないが、それでもたまにそういう機会があれば、ホテルに備え付けられた電話帳を開いて、青豆という姓を持った人がいないか調べることを習慣にしていた。しかし青豆という名前を持つ人物は、これまでに彼女が訪れたどこの都市にも、どこの町にも、一人として見あたらなかった。そのたびに彼女は、大海原に単身投げ出された孤独な漂流者のような気持ちになった。 (IQ84 BOOK 1 <4月-6月> 前編, 新潮文庫 む-5-27, p.13, 村上春樹 2009) Finally, I would like to stress that my comments above applies mostly to novels. For technical reports and research papers, there should be different standards and styles to tell facts accurately and precisely without any chance of confusion.
{ "pile_set_name": "StackExchange" }
Q: Chain jQuery AJAX promises with custom ones I have a particular website where I cannot rely on HTTP status codes, as I normally do, to trigger a success or failure after an AJAX call. A workaround I've come into, is to build the response as a JSON object that has a "type" property that is valued to "success" or "error". I've a helper function: function myAjaxCall(data) { return $.ajax({method: 'post', url: myUrl, data: data}); } What I want to accomplish is to make this possible: myAjaxCall(data).then(successFunction, failFunction); I've tried to interpose this function: function myPromise(response) { var d = $.Deferred(); response.type == 'success' ? d.resolve() : d.reject(); return d; } But I just can't imagine a clean way to insert my promise in the code. A: Just chain it with then: function myAjaxCall(data) { return $.ajax({method: 'post', url: myUrl, data: data}).then(myPromise); } Your myPromise function will receive the response as its argument, and the then does return a promise for the result of the call (the promise you return). Btw, you probably should pass some parts of the response to resolve/reject, so that that your successFunction and failFunction can access it. Not sure how your responses exactly look like, but as an example: function myPromise(response) { var d = $.Deferred(); response.type == 'success' ? d.resolve(response.data) : d.reject(response.error); return d; }
{ "pile_set_name": "StackExchange" }
Q: Does Heartbleed vulnerability affect other libraries (like BouncyCastle, .NET's SslStream, etc.)? pretty much the title, how to know if the Heartbleed vulnerability (for OpenSSL) affects other libraries like .NET's SSLStream or BouncyCastle. (Sorry for ignorance, but have found no info on how to exploit, to see if is related to bufferoverruns and other things that shouldn't happen in Java/.NET). A: The so-called "heartbleed" exploit is a buffer overrun. A read overrun, to be specific: the attacked system is induced into reading and sending back bytes from a buffer which is much shorter than the read length, thus reading whatever bytes reside in RAM past the buffer. Since the bytes are sent back to the peer, this gives a window to peek into the target system RAM. It is unlikely that any other implementation of SSL shares the same exact bug. It is plausible that other SSL libraries have buffer overruns of some sort (nobody really knows how to write bug-free code), but not exactly that one. Or, said otherwise, if another SSL implementation has the same heartbeat-related bug, then it probably is a spin-off of OpenSSL. Moreover, for implementations written in a language where array accesses are systematically checked for bounds (typically Java or C# or Python or Scheme or OCaml or just about any language which is not awfully low-level like C), the consequences of a buffer overrun are different, and usually preferable: instead of reading the extra bytes and sending them back, the offending code traps, triggering an exception which implies termination of the thread or process or connection. The bug is still there, not the far-ranging exploit; the leakage of secret data has turned into a basic potential denial-of-service, which will often be limited to closing the affected connection, therefore not denying much service after all.
{ "pile_set_name": "StackExchange" }
Q: html-select drop down issue with cordova on IOS 11 Beta I currently build an IOS application using AngularJS and Cordova. I find a bug when I tried my app on IOS 11 Beta. To select some data in a form, we use select dropDown. When we select a value, the drop down list disappears but it appear again some seconds after. When I have multiple select on my form, when a tap on a second select the first is selected. Then after selected the value the good list of option appear. I try with basic sample and this is the same behaviour. In a web explorer or with IOS 10, there is no bug. <select ng-model="elements" ng-options="serie.nom for serie in elements"></select> I try to add label, Update Cordova and IOS plugins. But nothing works. Thank you by advance. A: I had reported this issue for Cordova below: https://issues.apache.org/jira/browse/CB-13287 It appears the bug in Apple's UIWebView that cordova uses for IOS. I worked with one of our IOS developers to create a sample native IOS app using just Swift (no Cordova). The issue with the dropdown was present there too. Apple seems to have another view called WKWebView, which seems to be preferred one starting from IOS 8.0. Below is the quote taken from Apple's WKWebView documentation. I have verified there is no issue with the dropdown under WKWebView. Important Starting in iOS 8.0 and OS X 10.10, use WKWebView to add web content to your app. Do not use UIWebView or WebView. Good thing is Cordova has support for WKWebView too. You have to install the plugin: cordova-plugin-wkwebview-engine The plugin is not foolproof yet. You can try if that plugin works for your entire application. As of yet, WKWebView is not the default view that Cordova uses. Hopefully, Cordova will make WKWebView as default view soon. They are tracking all the known issues with WKWebView here. Update: Nov 3, 2017 I had reported this issue to apple too. But unfortunately, it was flagged as a duplicate of some other issue reported to them. For security and privacy reasons, apple didn't provide me the details about the other issue. The status of that issue is CLOSED now (it was OPEN before). So, hopefully the fix will be shipped into the upcoming IOS updates. Update: Feb 1, 2018 I just noticed that Apple has fixed this issue for UIWebView too under Xcode 9.2.
{ "pile_set_name": "StackExchange" }
Q: PostSharp: How to decorate returning IEnumerable? How to get it work? public override void OnExit(MethodExecutionArgs args) { var enumerable = (IEnumerable) args.ReturnValue; return Log( enumerable, // How to cast to unknown generic type? () => logger.LogRequestEntry(), stopwatch => logger.LogRequestExit( stopwatch ), ex => logger.LogRequestError( ex ) ); } private static IEnumerable<T> Log<T>(IEnumerable<T> enumerable, Func<Stopwatch> logEntry, Action<Stopwatch> logExit, Action<Exception> logError) { var stopwatch = logEntry(); try { using (var enumerator = enumerable.GetEnumerator()) { while (MoveNext( enumerator, logError )) yield return enumerator.Current; } } finally { logExit( stopwatch ); } } private static bool MoveNext<T>(IEnumerator<T> enumerator, Action<Exception> logError) { try { return enumerator.MoveNext(); } catch (Exception ex) { logError( ex ); throw; } } A: You need to use reflection to construct the return value of the correct generic type. However, you can move all the reflection code to the build-time logic and improve the run-time performance. You can construct a generic instance of the aspect at build-time as shown below. [PSerializable] public class LogEnumerableRequestAttribute : MethodLevelAspect, IAspectProvider { public IEnumerable<AspectInstance> ProvideAspects( object targetElement ) { var @interface = ( (MethodInfo) targetElement ).ReturnParameter.ParameterType; if (!IsGenericIEnumerable(@interface)) { @interface = @interface.GetInterfaces().First( IsGenericIEnumerable ); } var generic = @interface.GetGenericArguments().First(); var aspectGenericType = typeof( LogEnumerableRequestImpl<> ).MakeGenericType( generic ); yield return new AspectInstance( targetElement, (IAspect) Activator.CreateInstance( aspectGenericType ) ); } private static bool IsGenericIEnumerable( Type t ) { return t.IsGenericType && t.GetGenericTypeDefinition() == typeof( IEnumerable<> ); } } [PSerializable] public class LogEnumerableRequestImpl<T> : IMethodLevelAspect { [OnMethodExitAdvice(SemanticallyAdvisedMethodKinds = SemanticallyAdvisedMethodKinds.None)] [SelfPointcut] public void OnMethodExit( MethodExecutionArgs args ) { args.ReturnValue = Log_( (IEnumerable<T>) args.ReturnValue ); } public void RuntimeInitialize( MethodBase method ) { } private static IEnumerable<T> Log_<T>( IEnumerable<T> enumerable, Func<Stopwatch> logEntry, Action<Stopwatch> logExit, Action<Exception> logError ) { // ... } private static bool MoveNext<T>( IEnumerator<T> enumerator, Action<Exception> logError ) { // ... } }
{ "pile_set_name": "StackExchange" }
Q: create / edit file in bash with root privileges I am creating then writing to a file in bash4, in a directory with root privileges. I looked at these results from stackoverflow: https://unix.stackexchange.com/questions/37875/how-to-add-a-line-to-a-file-which-has-only-root-write-permission-and-to-continue But not helping me. Below $fName contains path to file. First I touch the file: sudo touch $fName; I am writing a key value pair (YAML) and this works: echo " "$key": "$value But when I try to write to the file $fName as in: sudo sh -c 'echo " "$key": "$value >> $fName'; or even: sudo sh -c 'echo \" "$key": "$value\ >> $fName'; does not work. Get various errors: Bad substitution, command not found etc. I was also trying to write to memory or /tmp and then move it to the directory. Would that be a better idea? Somehow that did not work either. Thank you for your help. A: all things including variables will be regard as string but not variable! Does this work? sudo sh -c "echo \" $key: $value \" >> $fName"
{ "pile_set_name": "StackExchange" }
Q: Java - Class.forName, how to get a Field from Class i'm trying to get a String from android.os.Build class using Class.forName but i'm getting the error NoSuchFieldException. Here is my code: public String getValue() { String field = ""; try { Class b = Class.forName("android.os.Build"); Class build = b.getClass(); Field myField = build.getDeclaredField("UNKNOWN"); field = myField.toString(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } return field; } The string I want to get is actually "SDK_INT" wich is inside VERSION, but I thought I'll try getting a field from the main class first. Here is the Build Class that also contain the Version class: package android.os; public class Build { public static final String UNKNOWN = "unknown"; public static final String ID = null; public static final String DISPLAY = null; public static final String PRODUCT = null; public static final String DEVICE = null; public static final String BOARD = null; public static final String CPU_ABI = null; public static final String CPU_ABI2 = null; public static final String MANUFACTURER = null; public static final String BRAND = null; public static final String MODEL = null; public static final String BOOTLOADER = null; /** @deprecated */ @Deprecated public static final String RADIO = null; public static final String HARDWARE = null; public static final String SERIAL = null; public static final String TYPE = null; public static final String TAGS = null; public static final String FINGERPRINT = null; public static final long TIME = 0L; public static final String USER = null; public static final String HOST = null; public Build() { throw new RuntimeException("Stub!"); } public static String getRadioVersion() { throw new RuntimeException("Stub!"); } public static class VERSION_CODES { public static final int CUR_DEVELOPMENT = 10000; public static final int BASE = 1; public static final int BASE_1_1 = 2; public static final int CUPCAKE = 3; public static final int DONUT = 4; public static final int ECLAIR = 5; public static final int ECLAIR_0_1 = 6; public static final int ECLAIR_MR1 = 7; public static final int FROYO = 8; public static final int GINGERBREAD = 9; public static final int GINGERBREAD_MR1 = 10; public static final int HONEYCOMB = 11; public static final int HONEYCOMB_MR1 = 12; public static final int HONEYCOMB_MR2 = 13; public static final int ICE_CREAM_SANDWICH = 14; public static final int ICE_CREAM_SANDWICH_MR1 = 15; public static final int JELLY_BEAN = 16; public static final int JELLY_BEAN_MR1 = 17; public static final int JELLY_BEAN_MR2 = 18; public static final int KITKAT = 19; public VERSION_CODES() { throw new RuntimeException("Stub!"); } } public static class VERSION { public static final String INCREMENTAL = null; public static final String RELEASE = null; /** @deprecated */ @Deprecated public static final String SDK = null; public static final int SDK_INT = 0; public static final String CODENAME = null; public VERSION() { throw new RuntimeException("Stub!"); } } } A: Remove the following line: Class build = b.getClass(); and get the field of Class variable b instead of build: Field myField = b.getDeclaredField("UNKNOWN"); Otherwise you're looking up a field in the class java.lang.Class not android.os.Build.
{ "pile_set_name": "StackExchange" }
Q: How to fix TypeError: 'float' object is not subscriptable and an .append that isn't working This is the module that will input a two-dimensional array containing employee names and their corresponding salaries. Here the program is only taking one input and moving on instead of adding more inputs until the user types in "*". How do I fix this? salary = [] names = [] def floatInput(): done = False while not done: nameIn = input("Please enter the employee name or * to finish: ") salaryIn = input("Please enter the salary in thousands for " + nameIn + ": ") try: salaryIn = float(salaryIn) except: print("Program was expecting a positive integer or floating point number!") if nameIn == "*": done = True else: salary.append(salaryIn) names.append(nameIn) return salary return names Calling the float Input function floatInput() here I use a for loop to print and iterate through the list of names and salaries. for i in range(len(names)): print(names[i] + ", " + str(salary[i])) Here I find the mean of the salaries. def salaryMean(): mean = sum(salary) / float(len(salary)) print("The mean of the salaries is: " + str(mean)) return mean Calling the salary mean Function salaryMean() here I convert the salary to thousands. for i in range(len(names)): salary = salary[i] * 1000 print(salary) Here I display all emplpyees who earn within a range of $5,000 from the mean This is where I am getting the "TypeError: 'float' object is not subscriptable" and it points to the line "if salary[x] >= (mean - 5000) and salary[x] <= (mean + 500):" .... How do I fix this? def displayNames(): done = False x = 0 while not done: if done: break if salary[x] >= (mean - 5000) and salary[x] <= (mean + 5000): print(salary[x]) x += 1 if x > len(salary): done = True Calling the display name Function. displayNames() A: To fix your .append issue (also your second return statement is never going to execute, see below on how to return both lists): Your loop isn't continuing is because you're returning inside the loop, thus terminating the function. Move your return statement outside of the loop (single unindent). while not done: # do stuff return salary, names To fix your TypeError I think the problem is here: for i in range(len(names)): salary = salary[i] * 1000 # Up to this point salary is a list, here it turns into the ith value of the list multiplied by 1000 print(salary) Instead, replace that entire for loop with: salary = [s*1000 for s in salary] for s in salary: print(s) # This should now print the multiplied salaries. Some other issues - you have two return statements followed by one another - the function will finish executing after the first return, and never execute the return below that one; if you want to return both salary and names use return names, salary (and maybe rename salary to salaries so that people can easily tell that it's a bunch of salaries, not just one).
{ "pile_set_name": "StackExchange" }
Q: What would I have to track during each point to get detailed tennis match statistics I am looking to keep stats for upcoming tennis tournament and I am wondering what would I have to track play by play to get good match statistics. For example should I track every shot in the rally or maybe note down just where serve landed and where it was returned and at the end of the play note if it was winner, forced error or unforced error. For example http://tennisabstract.com/ tracks every shot with additional modifiers like slice, drop-shot etc, along with other data. This is too much data for one person to track during a live match...so I am looking for most important metrics that would yield good match stats but would be feasible for a single person to manage during a match. A: The most important stats to track are serves, returns, break points and double faults. Depending on how far you want to go you can go into more or less details: Serves: Aces 1st serve (succeeded + points won / percentage) 2nd serve (dito) service points won in total / percentage Same for Returns: 1st serve returns won 2nd serve returns won return points won in total Break points: break points won break points saved Double Faults are easy to track as well: total percentage per set Other stats that might be handy: total games played / won (percentage) total points won Those stats should be easy to track by one person.. Watch the service, wait for the outcome, write it down, repeat. After the match you can do the math (e.g. calculate the serve and return ratings) and go on with the next one.
{ "pile_set_name": "StackExchange" }
Q: Need heuristic function for Reversi(Othello) ideas I have just studied about heuristic functions but I cant find an idea for heuristic function for reversi(Othello), I just need a good idea for grading some state of the board I thought about : count the number of moves count the number of discs and count the number of discs that are in corner and give them better score, I dont know if it is good. A: No, it is not good enough. The number of disks is particularly useless - although it is the goal of the game to collect as many as possible, the count on any move except for the last one is rather meaningless. Here are a few more things that you should take into consideration: Counting the number of moves gives you a measure of immediate mobility; everything else being equal, situations when you can make a move that opens up more other moves should be favored. You need to measure the potential mobility as well - the number of opponent's disks next to an open space. X squares - B2, B7, G2, and G7. Placing your disk there early almost certainly gives away the adjacent corner, so your heuristic should give them high negative weight, at least in the first 40 moves C squares - A2, A7, B1, G1, H2, H7, B8, and G8. They offer the opponent access to corners, so their value should be different from that of other squares, at least when the edge has fewer than five disks You can read a relatively short description of the strategy used in building a relatively strong (in the sense of its ability to beat human novices) reversi applet here. A: A good heuristic function for othello/reversi needs to capture more aspects of the positions, including: Coin parity Mobility (No. of possible moves) Corner captivity (corners are stable/cannot be turned and have special importance) Stability (measure of discs being immune from being turned) I've discussed these aspects and provided implementation of a good heuristic function here: http://kartikkukreja.wordpress.com/2013/03/30/heuristic-function-for-reversiothello/
{ "pile_set_name": "StackExchange" }
Q: Are there any long term RC4 bias based exploits? The RC4 cipher possibly exhibits low level bias in it's long run PRNG keystream. I'm specifically excluding short term bias attacks which I'm defining as outputs < 1024 bytes. Are there any real world attacks that exploit this feature? A: I'm happy to have a crack at this one, providing I've understood your question correctly. Firstly I wouldn't say the cipher possibly exhibits low level bias at any point. It experiences plenty of bias and I'll attempt to explain how we can use it to launch practical attacks. As I'd imagine you know, the strongest bias is found right at the start of the KSA, in fact there are numerous biases in the KSA, but the KSA only represents the first 256 bytes, assuming we don't drop any. The problem is, there's plenty of evidence (not just speculation) of the biases extending to any point in the key stream (asin the PRNG or PRGA part). See this again. Your question asked for real world attacks? Well contrary to some prior belief that because BEAST did not effect RC4 TLS, that RC4 was suitable for TLS, I'd recommend reading this as suggestion otherwise or alternatively this. The Bar Mitzvah Crypto attack, discovered and demonstrated by Itsik Mantin in 2015, should be the best proof that the IETF were onto something when they introduced the idea to ban RC4 altogether in TLS the year before. I know you were probably looking for something more in an answer but considering the question, this is about all there is to be said. How practical you think The Bar Mitzvah Crypto attack is, may be a question for debate.... but if we accept that NSA gathering of information, constantly with the same patterns in it (do I really need citations for this?), then it absolutely is the case that long key streams show significant enough bias and having enough of them allows data recovery and even in the circumstances of especially weak keys, key recovery all together. If we have a heavily biased round (the KSA) and a knowingly biased round (the PRGA) plus a handful of real world exploits, we can assume the attacks will only keep getting worse, but yeah: it's already practical to use bias to attack RC4, even in RC4-drop-768. EDIT It's probably worth reading this too Mathy Vanhoef and Frank Piessens, go into huge detail on biases
{ "pile_set_name": "StackExchange" }
Q: Aggregating numbers based on a column I have a table : A | B | C| D 2 4 5 01 3 3 1 02 12 1 13 03 I want the logic A + B - C to be grouped by column D. However, i want the value of A+B-C to be carried on to the next grouping. so, output table: D | Total 01 1 02 6 03 6 Logic for 01 : 2 + 4 - 5 = 1 02 : 1(from 01) + 3+3 -1 = 6 03 : 6 + 12 + 1 -13 = 6 I was trying to find the result of the logic grouping on D. But i am stuck on how to use the last groupings result. A: You want a cumulative sum: select t.*, sum(a + b - c) over (order by d) as total from t; I think d is determining the ordering of the results. Here is a db<>fiddle.
{ "pile_set_name": "StackExchange" }
Q: Gauss sum possible typo Let $ψ: \mathbb{F_p} \to Z_p$ with the property $ψ(a+b)=ψ(a)ψ(b)$ where $Z_p$ denotes the p-adic integers. Assume further that $ψ$ is not trivial. I'm trying to follow my professor's work, but I believe he may have made a typo. For each $0 \leq k \leq p-2$, define the Gauss sum $g_k= \sum _{x \in \mathbb{F_p}}t^{p-1-k}ψ(x)$. Let $\sum _k G(k)t^k$ be a polynomial of degree $p-1$ such that $ψ(\overline{t})= \sum _{k=0} ^{p-1}G(k)t^k$ for all $t\in \mathbb{F_p}$ Then, he claims that $G(0)=1$ (which is easy for me to see) but also $G(p-1)=-p/(p-1)$ (which I'm not sure how to prove.) He also claims that, for $1 \leq k \leq p-2$, $G(k)=g_k/(p-1).$ I believe that this is inconsistent with his previous definition of $g_k$ (after all, shouldn't G(k) be a coefficient instead of a polynomial?) which is why I think he made a typo. Can anyone see an easy way to correct it? A: Try $g_k:= \sum _{x \in \mathbb{F}_p}T(x)^{p-1-k}ψ(x)$
{ "pile_set_name": "StackExchange" }
Q: How to show date with previous post link in Wordpress When viewing a post, I want to show the date of the previous post underneath the previous/next post links but $post is not available in previous_post_link(). How can I carry forward the post date from the previous post as well as get the date for the next link? A: Did a bit of searching on the web, but no result. Then I opened the file wp-include/link-tempalte.php. On line 1327 you will find next_post_link which calls adjacent_post_link function. This function again calls get_adjacent_post function to retrieve previous post data. Looking at the source, you should be able to do the following: $in_same_cat = false; $excluded_categories = ''; $previous = true; $post = get_adjacent_post($in_same_cat, $excluded_categories, $previous); echo $post->post_date; This is not tested, but I think it hould work.
{ "pile_set_name": "StackExchange" }
Q: Remove Equal Sign "=" from GET request I have the following code which gets the URL parameter after the ? and displays it. <?php $qt = http_build_query($_GET); echo $qt; ?> But the problem i am having is that, whenever the URL is as follows: http://example.net/blog?123 The output is as follows: 123= How can i get rid of that "=" sign? I am parsing this into a mysql db, so the equal sign is not necessary. Thank you! P.S: I know that i need to sanitize the requests for security reasons, and i have that covered. A: Use str_replace: $qt = str_replace("=", "", http_build_query($_GET));
{ "pile_set_name": "StackExchange" }
Q: Why does flutter throw invalid argument(s) when grabbing children based on index? Ok, so I'm currently using a PageBuilder and what I'm doing works, but I don't really like the sliding physics. I'd rather just have them tap the bottomappbar to navigate. WORKING CODE: class Home extends StatefulWidget { @override State<StatefulWidget> createState() { return _HomeState(); } } class _HomeState extends State<Home> { int selectedIndex = 0; PageController controller = PageController(); List<GButton> tabs = new List(); final List<Widget> _children = [ Settings(), ListFamily(), CameraScreen(), SplashAccount(), Questions() ]; @override void initState() { super.initState(); var padding = EdgeInsets.symmetric(horizontal: 18, vertical: 5); double gap = 10; tabs.add(GButton( gap: gap, iconActiveColor: maincolor, iconColor: Colors.grey, textColor: maincolor, iconSize: 24, padding: padding, icon: Icons.settings, // textStyle: t.textStyle, text: 'Settings', )); tabs.add(GButton( gap: gap, iconActiveColor: maincolor, iconColor: Colors.grey, textColor: maincolor, iconSize: 24, padding: padding, icon: Icons.wc, // textStyle: t.textStyle, text: 'Relations', )); tabs.add(GButton( gap: gap, iconActiveColor: maincolor, iconColor: Colors.grey, textColor: maincolor, iconSize: 24, padding: padding, icon: Icons.camera_alt, // textStyle: t.textStyle, text: 'Camera', )); tabs.add(GButton( gap: gap, iconActiveColor: maincolor, iconColor: Colors.grey, textColor: maincolor, iconSize: 24, padding: padding, icon: Icons.video_library, // textStyle: t.textStyle, text: 'Videos', )); tabs.add(GButton( gap: gap, iconActiveColor: maincolor, iconColor: Colors.grey, textColor: maincolor, iconSize: 24, padding: padding, icon: Icons.question_answer, // textStyle: t.textStyle, text: 'Questions', )); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( extendBody: true, body: PageView.builder( onPageChanged: (page) { setState(() { selectedIndex = page; }); }, controller: controller, itemBuilder: (context, position) { return Column( children: <Widget>[ Expanded(child: _children[position]), Container( width: MediaQuery.of(context).size.width, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.only( topLeft: Radius.circular(12), topRight: Radius.circular(12), bottomLeft: Radius.zero, bottomRight: Radius.zero), boxShadow: [ BoxShadow( spreadRadius: -10, blurRadius: 60, color: Colors.black.withOpacity(.20), offset: Offset(0, 15)) ]), child: Padding( padding: const EdgeInsets.symmetric(vertical: 20), child: GNav( tabs: tabs, selectedIndex: selectedIndex, onTabChange: (index) { print(index); setState(() { selectedIndex = index; }); }), ), ), ], ); }, itemCount: tabs.length, // Can be null ), ), ); } } Invalid argument(s) code: class Home extends StatefulWidget { @override State<StatefulWidget> createState() { return _HomeState(); } } class _HomeState extends State<Home> { int selectedIndex = 0; PageController controller = PageController(); List<GButton> tabs = new List(); final List<Widget> _children = [ Settings(), Container(), Container(), Container(), Container() ]; @override void initState() { super.initState(); var padding = EdgeInsets.symmetric(horizontal: 18, vertical: 5); double gap = 10; tabs.add(GButton( gap: gap, iconActiveColor: maincolor, iconColor: Colors.grey, textColor: maincolor, iconSize: 24, padding: padding, icon: Icons.settings, // textStyle: t.textStyle, text: 'Settings', )); tabs.add(GButton( gap: gap, iconActiveColor: maincolor, iconColor: Colors.grey, textColor: maincolor, iconSize: 24, padding: padding, icon: Icons.wc, // textStyle: t.textStyle, text: 'Relations', )); tabs.add(GButton( gap: gap, iconActiveColor: maincolor, iconColor: Colors.grey, textColor: maincolor, iconSize: 24, padding: padding, icon: Icons.camera_alt, // textStyle: t.textStyle, text: 'Camera', )); tabs.add(GButton( gap: gap, iconActiveColor: maincolor, iconColor: Colors.grey, textColor: maincolor, iconSize: 24, padding: padding, icon: Icons.video_library, // textStyle: t.textStyle, text: 'Videos', )); tabs.add(GButton( gap: gap, iconActiveColor: maincolor, iconColor: Colors.grey, textColor: maincolor, iconSize: 24, padding: padding, icon: Icons.question_answer, // textStyle: t.textStyle, text: 'Questions', )); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( extendBody: true, body: Column( children: <Widget>[ // _children[selectedIndex] will cause the Invalid Argument(s) error here. Expanded(child: _children[selectedIndex]), Container( width: MediaQuery.of(context).size.width, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.only( topLeft: Radius.circular(12), topRight: Radius.circular(12), bottomLeft: Radius.zero, bottomRight: Radius.zero), boxShadow: [ BoxShadow( spreadRadius: -10, blurRadius: 60, color: Colors.black.withOpacity(.20), offset: Offset(0, 15)) ]), child: Padding( padding: const EdgeInsets.symmetric(vertical: 20), child: GNav( tabs: tabs, selectedIndex: selectedIndex, onTabChange: (index) { print(index); setState(() { selectedIndex = index; }); }), ), ), ], ))); } } I'm currently only using Flutter's Material library and this plugin: https://github.com/sooxt98/google_nav_bar Also, I've tried this with other bottom navigation bars as well, I'm just stumped as to why this happens The children in the working code are my other pages. The settings page code is below: class Settings extends StatefulWidget { @override _SettingsPageState createState() => _SettingsPageState(); } class _SettingsPageState extends State<Settings> { @override Widget build(BuildContext context) { return Scaffold( body: Container( child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ // Logo + Container Container( color: thirdcolor, child: Center( child: SafeArea( child: Container( decoration: BoxDecoration( image: DecorationImage( image: AssetImage( "assets/mvvdesign/Solid/White/horizontal/logo.png"), fit: BoxFit.fitWidth)), ), ), ), ), // Container for Questions bar Container( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( "SETTINGS", style: TextStyle( color: Colors.white, fontSize: fontsize, fontFamily: fontfamily, fontWeight: FontWeight.w300), ), Container( margin: const EdgeInsets.only(top: 10.0), color: Colors.white, child: Divider( height: 5.0, thickness: 3.0, endIndent: 100.0, indent: 100.0, color: Colors.white, ), ), ], ), ), ], ), ), Container( margin: const EdgeInsets.only(top: 20.0), child: Column( children: <Widget>[ Container( height: 60, width: MediaQuery.of(context).size.width - 50, decoration: BoxDecoration( borderRadius: BorderRadius.circular(15.0), border: Border.all(color: Colors.white, width: 2.0)), child: Center( child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( "Hey, ", style: TextStyle( fontSize: 24.0, color: Colors.white, ), ), Text( "Alyssa Thurman", style: TextStyle( fontSize: 24.0, color: Colors.green, fontWeight: FontWeight.bold), ), ], ), ), ), margin: const EdgeInsets.only(bottom: 10.0), ), ], ), ), Expanded( child: SingleChildScrollView( child: Column( children: <Widget>[ Container( width: 360.0, height: 56.0, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.0), color: Colors.white), margin: const EdgeInsets.only(top: 20.0), child: Center( child: Text( "Update Account Information", style: TextStyle(fontSize: 24.0, color: maincolor), )), ), Container( width: 360.0, height: 56.0, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.0), color: Colors.white), margin: const EdgeInsets.only(top: 40.0), child: Center( child: Text( "Terms and Conditions", style: TextStyle(fontSize: 24.0, color: maincolor), )), ), Container( width: 360.0, height: 56.0, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.0), color: Colors.white), margin: const EdgeInsets.only(top: 40.0), child: Center( child: Text( "Privacy Policy", style: TextStyle(fontSize: 24.0, color: maincolor), )), ), Container( width: 360.0, height: 56.0, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.0), color: Colors.white), margin: const EdgeInsets.only(top: 40.0), child: Center( child: Text( "Manage Membership", style: TextStyle(fontSize: 24.0, color: maincolor), )), ), Container( width: 360.0, height: 56.0, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.0), color: Colors.red), margin: const EdgeInsets.only(top: 40.0, bottom: 40.0), child: InkWell( onTap: () async { await OneSignal.shared.logoutEmail(); SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.remove('accesstoken'); prefs.remove('refreshtoken'); prefs.remove('email'); Navigator.push( context, MaterialPageRoute(builder: (context) => First()), ); }, child: Center( child: Text( "LOGOUT", style: TextStyle(fontSize: 24.0, color: Colors.white), )), ), ), ], ), ), ) ], ), ), ), resizeToAvoidBottomPadding: false, backgroundColor: thirdcolor, ); } } Error log: https://pastebin.com/raw/Regkgcqk A: EDIT: I figured out why it wasn't working (fairly sure). I have a function that grabs a saved index value from persistent storage and sets selectedIndex to this value upon initialization of the state. However, when the saved index is grabbed, it returns a null (because it has not been set yet) value. Therefore it passes this null value to selectedIndex and subsequently the builder as well; leading to an invalid argument(s) error because the index cannot be null. The function in question is not included in the above incorrect code, so both code snippets should work. The reason it wasn't working for me is likely because the index was cached and it was considering the index to be null every time the state was reloaded. Alternative solution: Use a pageview builder and set the properties to your preferences. My preference: Inside of PageView.builder() physics: NeverScrollableScrollPhysics()
{ "pile_set_name": "StackExchange" }
Q: 0 + integer is weird in JS Go to your browser's JS console and try these: -14 // -14 -014 // -12 -24 // -24 -024 // -20 -0024 // -20 012 // 10 Why is this 0-integer construct giving me results that are 2 smaller in absolute value? A: "Never write a number with a leading zero (like 07). Some JavaScript versions interpret numbers as octal if they are written with a leading zero." (see: http://www.w3schools.com/js/js_numbers.asp)
{ "pile_set_name": "StackExchange" }
Q: Trouble returning a valid result while integrating Stripe API into my Meteor app Here's the rundown: I'm trying to run Stripe API on my Meteor app asynchronously Long story short, everything works (i.e. subscription and charge is/are created normally and shows up in my Stripe dashboard) When errors occur, the errors throw normally and show on client via user friendly alerts I have a problem when there is a success and customer subscription is created, the result is not present in client and instead always returns as an error, despite it being a successful process Here's what my method looks like on the server: createCustomer: function(token, email, plan){ try{ let createCustomer = Meteor.wrapAsync(stripe.customers.create); let result = createCustomer({ source: token, email: email, plan: plan }); let subscription = { customer: result.id, sub: result.subscriptions.data[0].id, plan: result.subscriptions.data[0].plan.name }; Meteor.users.update({_id: Meteor.userId()}, {$set: subscription}); } catch(error){ if(error.code === "incorrect_cvc"){ throw new Meteor.Error("incorrect_cvc", error.message); } // More of such errors follows } } Here's what it looks like on the client: Stripe.card.createToken({ number: number, cvc: cvc, exp_month: exp, exp_year: exp_year, address_zip: zip, address_country: country }, function(status, response){ if(response.error){ console.log("Make sure all fields are filled before submitting order."); } else{ let token = response.id; Meteor.call("createCustomer", token, email, plan, function(error, result){ if(result){ console.log("Congratulations, everything worked!"); } else{ if(error.error === "incorrect_cvc"){ console.log("oops, the CSV is incorrect"); } // More of such errors follow.. } }) } }); So, everything works in terms of when there is a real error, it throws fine on server + client. When user uses card, the charges are created and subscription is always created. HOWEVER, when there is a success and everything clicking fine, I still receive an error on client via callback and the result is never true or triggered. No idea why. A: Not 100% up on Meteor, but it looks to me like your createCustomer method doesn't actually return anything, so the result from your (err, result) might never have anything in it? As was mentioned in the comments, you might want to separate out the steps and wrap each in its own try-catch set so you can better isolate the issue. Also, I feel like you could probably generalize your server-side error code to something like: throw new Meteor.Error(error.error, error.message); And I might even be tempted to do something like this, at least during testing/development - that way you can actually console.log() the original error in the browser: throw new Meteor.Error(error.error, error.message, JSON.stringify(error));
{ "pile_set_name": "StackExchange" }
Q: Not reading number properly? I'm trying to read from file line by line. It takes the first number of the line and the rest it connects it using a char of linked list. But when I run it, i get the connection as -38 (which is wrong) and it only prints it once and does not go through the rest of the line. but it reads first element perfectly. #include <stdio.h> #include <stdlib.h> struct node{ int data; struct node* next; }; int main(void) { FILE * fp; char * line = NULL; char * storage; size_t len = 0; ssize_t read; struct node *G[1000]; for (int i = 1; i < 1000; i++) { G[i]= malloc(sizeof(struct node)); G[i]->data = i; G[i]->next = NULL; } fp = fopen("idk2.txt", "r"); if (fp == NULL) exit(EXIT_FAILURE); while ((read = getline(&line, &len, fp)) != -1) { int vertexGettingConntected = line[0]; struct node* newItem; printf("Retrieved line of length %zu :", read); int i = 0; while(line[i] != '\0'){ if ( line[i] == ' '){ i++; } else if (i == 0){ newItem = malloc(sizeof(struct node)); int itemStorage = line[0] - '0'; newItem->next = NULL; newItem->data = itemStorage; G[itemStorage] = newItem; printf("This is first Number:%d\n", itemStorage); } else if (line[i] != ' '){ struct node* addingItem = newItem; while(addingItem->next != NULL){ addingItem = addingItem->next; } int itemStorage = line[i] - '0'; struct node* newConnection = malloc(sizeof(struct node)); addingItem->next = newConnection; newConnection->data = itemStorage; newConnection->next = NULL; printf("This is character:%c\n", line[i]); printf("This is connection:%i\n", itemStorage); } i++; } } fclose(fp); if (line) free(line); exit(EXIT_SUCCESS); for(int printer = 1; printer<20; printer++){ printf("%d\n",G[printer]->data); } } EDIT: Just wanted to include file im reading from: 1 3 4 2 4 3 1 4 4 2 1 3 A: I am not sure why you want to have an array of pointers to node which you all allocate memory for at the beginning of your program without knowing how many nodes will be needed. Then you allocate memory again while reading from the file. Given the constraints of not being allowed to use functions, thats how i'd read the file and build a list: #include <stdlib.h> #include <stdio.h> typedef struct node_tag { int value; struct node_tag *next; } node_t; int main(void) { char const *filename = "test.txt"; FILE *input_file = fopen(filename, "r"); if (!input_file) { fprintf(stderr, "Couldn't open \"%s\" for reading :(\n\n", filename); return EXIT_FAILURE; } // read from file and build a list: node_t *head = NULL; node_t *tail = NULL; int value; int result = EXIT_SUCCESS; while (fscanf(input_file, "%d", &value) == 1) { node_t *new_node = calloc(1, sizeof *new_node); if (!new_node) { fputs("Not enough memory :(\n\n", stderr); result = EXIT_FAILURE; goto glean_up; } new_node->value = value; if (!head) { // there is no head yet so new_node becomes the head head = tail = new_node; // which is also the lists tail continue; } tail->next = new_node; tail = new_node; } // print the list: for (node_t *current_node = head; current_node; current_node = current_node->next) printf("%d ", current_node->value); putchar('\n'); clean_up: fclose(input_file); for (node_t *current_node = head, *temp; current_node; current_node = temp) { temp = current_node->next; free(current_node); } return result; } Ideally you'd write functions to manage the list: #include <stdbool.h> #include <stdlib.h> #include <stdio.h> typedef struct node_tag { int value; struct node_tag *next; } node_t; typedef struct list_tag { node_t *head; node_t *tail; } list_t; void list_create(list_t *list) { list->head = list->tail = NULL; } bool list_push_back(list_t *list, int value) { node_t *new_node = calloc(1, sizeof *new_node); if (!new_node) return false; new_node->value = value; if (!list->head) { list->head = list->tail = new_node; return true; } list->tail->next = new_node; list->tail = new_node; return true; } void list_print(list_t *list) { for (node_t *current_node = list->head; current_node; current_node = current_node->next) printf("%d ", current_node->value); } void list_free(list_t *list) { for (node_t *current_node = list->head, *temp; current_node; current_node = temp) { temp = current_node->next; free(current_node); } } bool read_int(FILE *input_file, int *value) { return fscanf(input_file, "%d", value) == 1; } int main(void) { char const *filename = "test.txt"; FILE *input_file = fopen(filename, "r"); if (!input_file) { fprintf(stderr, "Couldn't open \"%s\" for reading :(\n\n", filename); return EXIT_FAILURE; } // read from file and build a list: list_t list; list_create(&list); int value; while (read_int(input_file, &value)) { if (!list_push_back(&list, value)) { fputs("Not enough memory :(\n\n", stderr); // clean up: fclose(input_file); list_free(&list); return EXIT_FAILURE; } } // print the list: list_print(&list); putchar('\n'); // clean up: fclose(input_file); list_free(&list); } Output: 1 3 4 2 4 3 1 4 4 2 1 3
{ "pile_set_name": "StackExchange" }
Q: Prove $ \int_{C}fdr=\int_{S}dS\times\nabla f$ Prove $\displaystyle \int_{C}fdr=\int_{S}dS\times\nabla f$. where $C=\partial S$ and the usual relationship between orientations hold. Apply Stokes's theorem to $F=af$ where $a$ is an arbitrary constant vector. From this identity and because $\nabla \times \mathbf{a = 0 }, $ thus $ \nabla\times F=0 + \nabla f \times a$. Thus $(\nabla\times F)\cdot d\mathbf{ S }= (\nabla f \times a) \cdot d\mathbf{ S } = (d\mathbf{ S }\times \nabla f) \cdot a $, thanks to the answer below. Then Stokes's theorem for arbitrary a implies $ \int_{C}f \mathbf{ a } \; d\mathbf{ r } = \iint_S (d\mathbf{ S }\times \nabla f) \cdot a $. My concern: How do I proceed from here? Please explain steps in detail? A: Apply the Kelvin-Stokes theorem to the vector field $fa$: $$\oint fa \cdot dr = \int (\nabla \times [af]) \cdot dS$$ Use vector calculus identities to write $$\nabla \times [af] = f \nabla \times a + \nabla f \times a$$ Since $\nabla \times a = 0$, we get $$\oint f a \cdot dr = \int (\nabla f \times a) \cdot dS$$ The triple product can be cyclically permuted, yielding $$\oint fa \cdot dr = \int (dS \times \nabla f) \cdot a$$ Since $a$ is constant, it can be moved out of both integrals, the way you would move a constant scalar out of an integral: $$a \cdot \oint f \, dr = a \cdot \int dS \times \nabla f$$ $a$ was chosen arbitrarily; this is true for all $a$ and thus we can "cancel" $a$. If one must think of it more rigorously, look at this expression above as a linear function of $a$. Take a gradient of that function with respect to $a$. The resulting gradients are equal on both sides. The result is $$\oint f \, dr = \int dS \times \nabla f$$
{ "pile_set_name": "StackExchange" }
Q: Orientation reversing diffeomorphism Why each sphere admits an orientation reversing diffeomorphism onto itself? (For even dimensional ones can we take conjugation map?) And why complex projective spaces do not admit? Is there a geometric way to see this without using characteristic classes? A: The reason complex projective space $\mathbb{CP}^{2k}$ has no orientation-reversing homeomorphism is because the top dimensional cohomology is generated by an even power of the generator, $x$, of $H^2(\mathbb{CP}^{2k})$. So any self-homeomorphism will send $x$ to $\lambda x$ ($\lambda\neq 0$), and the top cohomology will have $x^{2k}\mapsto \lambda^{2k} x^{2k}$. Since $\lambda^{2k}>0$, this preserves orientation. As Georges pointed out, this argument doesn't work for $\mathbb{CP}^{2k+1}$. A: Complex spaces of the form $\mathbb{C}P^{2n+1}$ do admit orientation reversing diffeomorphisms. In fact, the map sending $[z_0:z_1:...:z_{2n}:z_{2n+1}]$ to $[-\overline{z_1}:\overline{z_0}:...:-\overline{z_{2n+1}}:\overline{z_{2n}}]$ is orientation reversing (and gives a free action of $\mathbb{Z}/2\mathbb{Z}$ on $\mathbb{C}P^{2n+1}$). One can check that when $n=0$, this map is the usual antipodal map of $\mathbb{C}P^1 = S^2$. Also, Jim's idea works for showing that the manifolds $\mathbb{H}P^{2n}$ and $\mathbb{O}P^2$ do not admit orientation reversing diffeomorphisms. But more is true. The manifolds $\mathbb{H}P^{2n+1}$ also do not admit orientation reversing diffeomorphisms (unless $n=0$). (The map I wrote above isn't well defined when considering $\mathbb{H}P^n$). The only argument for this I'm familiar with involves characteristic classes, but I'm vaguely aware of one using Steenrod squares. Finally, I just wanted to point out that when one says "all sphere's admit orientation reversing diffeomorphisms", one must be careful to throw out most exotic spheres. An exotic sphere is a manifold which is homeomorphic to $S^n$ but not diffeomorphic to it (and such things are known to exist, starting in dimension $7$). It's a fact that for each fixed dimension the set of diffeomorphism classes of smooth manifolds homeomorphic to $S^n$ forms a group under connect sum. The inverse to an exotic sphere is the same sphere with reveresed orientation. Hence, exotic spheres admitting orientation reversing diffeomorphisms correspond to order $2$ elements in this group. Then, for example, in dimension $7$, the group is known to be cyclic of order $28$, so only $1$ of the 13 unoriented types of exotic spheres admits orientation reversing diffeomorphisms (though, being homeomorphic to $S^n$, it admits orientation reversing homeomorphisms!) A: The $n$-sphere $S^n$ is $\{(x_0, x_1,\ldots ,x_n):\sum {x_i}^2 = 1\}$ The map $f:S^n \to S^n$ sending $(x_0,x_1,\ldots , x_n)$ to $(-x_0,x_1,\ldots , x_n)$ is an oreintation-reversing diffeomorphism. Sorry I don't have an answer for complex projective spaces.
{ "pile_set_name": "StackExchange" }
Q: GCP - Windows Activation I'm using a GCP-VM instance with Windows Server 2019 Datacenter Edition installed normally, suddenly Windows is not activated more and i can't do it. I tried to active windows in control panel, but i had the message below: In my revenue i have a fee for windows license, so i don't know what is happening. A: According to GCP documents click here and click here , you need to recheck configure routes and firewall rules in your VPC network to allow access to kms.windows.googlecloud.com (35.190.247.13). Furthermore I attached this document click here , as I think it will be useful regarding your request and you will be able to troubleshoot the issue.
{ "pile_set_name": "StackExchange" }
Q: Search all smart contracts I would like to search the code (binary grep) of all deployed contracts. The goal is to search for vulnerabilities and other research. How can I do this with geth, Parity or the like? And is this feasible, like will it take years to do a search? A: You can query contract bytecode in this public BigQuery dataset https://medium.com/@medvedev1088/more-blockchain-analysis-on-bigquery-92a863137f01 Previous answer It's not possible via JSON RPC or web3 API. Scanning the Patricia trie wouldn't work either because the addresses are hashed there. To list all contracts you'd need to do: list all transactions where to address is 0x0 - these are contract-creating transactions execute all transactions and intercept CREATE opcodes - opcode for creating a contact alternatively transaction traces can be inspected For each address collected above then call eth_getCode or the corresponding web3 API to get the bytecode. An alternative is to try to scrape contract code from Etherscan. I've scraped some using this Scrapy script https://github.com/medvedev1088/ethereum-scraper About 7k contracts with bytecode and Solidity code can be found here http://ipfs.io/ipfs/QmU7pxFykAwemy8vGcAp78pUnHuye4gjjCiBsDsqV1raeF https://drive.google.com/open?id=1YWMUhXd97OEC24gyG_kKvo6xfwZ3K8xB
{ "pile_set_name": "StackExchange" }
Q: Ionic Notification/Push message I need to send a JSON containing the category and the message all users who have my application installed, like this: {category:"shoes", message:"New pair of shoes available"} then I need to display a alert/notification only to users which checked a specific option which matches the category in the JSON. I'm using Ionic, NodeJS and Express. How could I do that? A: Hello Shadow00, Then first of all you have to install FOUR Plugins for that. 1)cordova plugin add https://github.com/phonegap-build/PushPlugin // For notification 2)cordova plugin add cordova-plugin-device // For on Device Ready to call 3)cordova plugin add cordova-plugin-dialogs // For notification Dialog 4)cordova plugin add cordova-plugin-media // For Notification Sound and generate API key and SenderId throw developer console.and senderid past in bellow code. And e.regid pass to on server. <script type="text/javascript" src="PushNotification.js"></script> <script type="text/javascript"> var pushNotification; function onDeviceReady() { $("#app-status-ul").append('<li>deviceready event received</li>'); document.addEventListener("backbutton", function(e) { $("#app-status-ul").append('<li>backbutton event received</li>'); if( $("#home").length > 0) { // call this to get a new token each time. don't call it to reuse existing token. //pushNotification.unregister(successHandler, errorHandler); e.preventDefault(); navigator.app.exitApp(); } else { navigator.app.backHistory(); } }, false); try { pushNotification = window.plugins.pushNotification; $("#app-status-ul").append('<li>registering ' + device.platform + '</li>'); if (device.platform == 'android' || device.platform == 'Android' || device.platform == 'amazon-fireos' ) { pushNotification.register(successHandler, errorHandler, {"senderID":"661780372179","ecb":"onNotification"}); // required! } else { pushNotification.register(tokenHandler, errorHandler, {"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"}); // required! } } catch(err) { txt="There was an error on this page.\n\n"; txt+="Error description: " + err.message + "\n\n"; alert(txt); } } // handle APNS notifications for iOS function onNotificationAPN(e) { if (e.alert) { $("#app-status-ul").append('<li>push-notification: ' + e.alert + '</li>'); // showing an alert also requires the org.apache.cordova.dialogs plugin navigator.notification.alert(e.alert); } if (e.sound) { // playing a sound also requires the org.apache.cordova.media plugin var snd = new Media(e.sound); snd.play(); } if (e.badge) { pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge); } } // handle GCM notifications for Android function onNotification(e) { $("#app-status-ul").append('<li>EVENT -> RECEIVED:' + e.event + '</li>'); switch( e.event ) { case 'registered': if ( e.regid.length > 0 ) { $("#app-status-ul").append('<li>REGISTERED -> REGID:' + e.regid + "</li>"); // Your GCM push server needs to know the regID before it can push to this device // here is where you might want to send it the regID for later use. console.log("regID = " + e.regid); } break; case 'message': // if this flag is set, this notification happened while we were in the foreground. // you might want to play a sound to get the user's attention, throw up a dialog, etc. if (e.foreground) { $("#app-status-ul").append('<li>--INLINE NOTIFICATION--' + '</li>'); // on Android soundname is outside the payload. // On Amazon FireOS all custom attributes are contained within payload var soundfile = e.soundname || e.payload.sound; // if the notification contains a soundname, play it. // playing a sound also requires the org.apache.cordova.media plugin var my_media = new Media("/android_asset/www/"+ soundfile); my_media.play(); } else { // otherwise we were launched because the user touched a notification in the notification tray. if (e.coldstart) $("#app-status-ul").append('<li>--COLDSTART NOTIFICATION--' + '</li>'); else $("#app-status-ul").append('<li>--BACKGROUND NOTIFICATION--' + '</li>'); } $("#app-status-ul").append('<li>MESSAGE -> MSG: ' + e.payload.message + '</li>'); //android only $("#app-status-ul").append('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>'); //amazon-fireos only $("#app-status-ul").append('<li>MESSAGE -> TIMESTAMP: ' + e.payload.timeStamp + '</li>'); break; case 'error': $("#app-status-ul").append('<li>ERROR -> MSG:' + e.msg + '</li>'); break; default: $("#app-status-ul").append('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>'); break; } } function tokenHandler (result) { $("#app-status-ul").append('<li>token: '+ result +'</li>'); // Your iOS push server needs to know the token before it can push to this device // here is where you might want to send it the token for later use. } function successHandler (result) { $("#app-status-ul").append('<li>success:'+ result +'</li>'); } function errorHandler (error) { $("#app-status-ul").append('<li>error:'+ error +'</li>'); } document.addEventListener('deviceready', onDeviceReady, true); </script> <div id="home"> <div id="app-status-div"> <ul id="app-status-ul"> <li>Cordova PushNotification Plugin Demo</li> </ul> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: How does a loglogN complexity loop look like? I have few questions here consider the following loops (let N = 8) for(int i=1;i<N/2;i++){ // this is O(logN) } N/2 = 4 but log(8) = 3 (considering base as 2) then why above loop considered as O(logN) and How does O(loglogN) loop look like? PS: Sorry for my poor mathematical concepts A: O(log n) loop: for (i = 1; i <= n; i *= 2) So you double i at each step. Basically: Increment => O(n) Doubling => O(log n) ??? => O(log log n) What comes after multiplication? Exponentiation. So this would be O(log log n): for (i = 2; i <= n; i *= i) // we are squaring i at each step Note: your loop is O(n), not O(log n). Keeping in line with the increment / double / exponentiate idea above, you can rewrite your loop using incrementation: for(int i = 1; i < n; i += 2) Even if you increment by more, it's still incrementation, and still O(n).
{ "pile_set_name": "StackExchange" }
Q: Does a Middle Ground Exist? (Unit Testing vs. Integration Testing) Consider an implementation of the Repository Pattern (or similar). I'll try to keep the example/illustration as succinct as possible: interface IRepository<T> { void Add(T entity); } public class Repository<T> : IRepository<T> { public void Add(T entity) { // Some logic to add the entity to the repository here. } } In this particular implementation, the Repository is defined by an interface IRepository to have one method which adds an entity to the repository, thus making Repository dependant upon the generic type T (also, the Repository must be implicitly dependant upon another type TDataAccessLayer, since the abstraction is the entire point of the Repository Pattern. This dependency, however, is not currently readily available). At this point, from what I understand so far, I have two options: Unit Testing and Integration Testing. Where Integration Testing may be assumed to have a greater number of moving parts, I would much rather initially Unit Test in order to as least verify a baseline functionality. However, without creating some sort of "entity" property (of generic type T), I can see no way of asserting that any logic is actually performed within the Add() method of the Repository implementation. Is there, perhaps, a middle ground somewhere between Unit Testing and Integration Testing which allows (through Reflection or some other means) to verify that specific points of execution have been reached within a tested unit? The only explanation I've come up with for this particular issue is to further abstract the Data Access Layer from the repository, resulting in the Add() method accepting not only an entity argument but also a Data Access argument. This seems to me like it might defeat the purpose of the Repository Pattern, however, since the consumer of the Repository must now know about the Data Access Layer. With regard to request for examples: (1) And in regard to Unit Testing, I'm not sure something like a Repository could actually be Unit Tested with my understanding of current testing techniques. Because a Repository is an abstraction (wrapper) around a specific Data Access Layer, it seems that the only method of verification would be an Integration Test? (Granted, a Repository Interface may not be tied to any specific DAL, but any implemented Repository must surely be tied to a specific DAL implementation, therefore the need to be able to test that the Add() method actually performs some work). (2) And in regard to Integration Testing, the test, as I understand the technique, would verify the Add() method performing work by actually calling the Add() method (which should add a record to the repository) and then check to see that the data was actually added to the repository (or perhaps database in a specific scenario). This may look something like: [TestMethod] public void Add() { Repository<Int32> repository = new Repository<Int32>(); Int32 testData = 10; repository.Add(testData); // Intended to illustrate the point succinctly. Perhaps the repository Get() method would not // be called (and a DBCommand unrelated to the repository issued instead). However, assuming the // Get() method to have been previously verified, this could work. Assert.IsTrue(testData == repository.Get(testData)); } So, in this instance, assuming the repository is a wrapper around some database logic layer, the database is actually hit twice during the test (once during insert, and once during retrieve). Now, what I could see being useful, would be a technique for verifying that a certain execution path is taken during runtime. An example could be that if a non-null reference is passed in, verify execution path A is taken, and if a null reference is passed in, verify execution path B is taken. Also, perhaps one could verify that particular LINQ query was to be executed. Therefore, the database is never actually hit during the test (allowing prototyping and development of an implementation without any actual DAL in place). A: It sounds like you're describing the testing of an implementation detail rather than fulfillment of the requirements of a pattern by an implementor of the pattern. It doesn't matter if "specific points of execution" have been reached within the tested unit, it only matters if the concrete implementor upholds the contract of the interface. It's perfectly acceptable for tests to create a T entity for testing purposes, that's what mocks are for.
{ "pile_set_name": "StackExchange" }
Q: Salvar arquivos com storeAs fora da pasta Storage Tenho em uma API em Laravel para armazenamento de arquivos $request->file("file$i")->storeAs('categories', $nameFile) Da forma que está este armazena os dados corretamente no endereço /var/www/html/apiapp/storage/app/public/categories Porém eu gostaria de salvar estes arquivos na pasta /var/archives Pois estes arquivos serão acessados por outra aplicação A: O terceiro argumento do storeAs diz em qual storage disk o arquivo deve ser salvo $path = $request->photo->storeAs('images', 'filename.jpg', 's3'); Assim, crie um novo disk em config/filesystem.php e aponte ele para /var/archives 'disks' => [ // ... 'archive' => [ 'driver' => 'local', 'root' => '/var/archives', ], // ... No código: $request->file("file$i")->storeAs('categories', $nameFile, 'archive') Garanta que o usuário que roda o webserver tenha permissão para salvar nessa pasta em disco também. Outra alternativa é compartilhar um storage externo, como o S3 da AWS por exemplo. A configuração para isso segue a mesma ideia.
{ "pile_set_name": "StackExchange" }
Q: Converting object contribution to menu contribution in eclipse I have a context menu written using org.eclipse.ui.popupMenus. Since it is deprecated now I want to use org.eclipse.ui.menus for the same. Earlier implementation looks like this <extension point="org.eclipse.ui.popupMenus"> <objectContribution adaptable="true" id="com.xyz.plm.analysis.func.gui.popupOnComponentForCA" objectClass="com.xyz.plm.componentmodel.IComponent"> <action class="com.xyz.plm.analysis.my.gui.MyAction" enablesFor="1" id="com.xyz.plm.analysis.my.gui.MyActionion2" label="Run My Action" menubarPath="com.xyz.plm.ide.ui.myToolsPopupMenu/myToolsGroup" tooltip="Run My Action"> </action> What I tried so far is below <extension point="org.eclipse.ui.commands"> <command id="com.xyz.plm.analysis.my.commandmygui" name="Run My Action"> </command> </extension> <extension point="org.eclipse.ui.handlers"> <handler class="com.xyz.plm.analysis.my.gui.MyAnalysisGui" commandId="com.xyz.plm.analysis.my.commandmygui"> <enabledWhen> <with variable="selection"> <iterate ifEmpty="false" operator="or"> <instanceof value="com.xyz.plm.componentmodel.IComponent"> </instanceof> </iterate> </with> </enabledWhen> </handler> </extension> <extension point="org.eclipse.ui.menus"> <menuContribution locationURI="popup:com.xyz.plm.ide.ui.myToolsPopupMenu"> <command commandId="com.xyz.plm.analysis.my.commandmygui" label="RunMyACtion" style="push"> </command> </menuContribution> </extension> But with this I am seeing MyAction subMenu under MyTools context menu. But MyAction is disabled. Also I am seeing MyACtion is appearing in projectExplorer window as well as in editor when I right click select MyTools. What I want is MyAction submenu should appear only under MyTools popupmenu and only when I right click on a object of type IComponent this menu should appear. A: You should use visibleWhen on the menu contribution and no enabledWhen for the handler. You should probably use adapt rather than instanceof. So something like: <extension point="org.eclipse.ui.handlers"> <handler class="com.xyz.plm.analysis.my.gui.MyAnalysisGui" commandId="com.xyz.plm.analysis.my.commandmygui"> </handler> </extension> <extension point="org.eclipse.ui.menus"> <menuContribution locationURI="popup:com.xyz.plm.ide.ui.myToolsPopupMenu"> <command commandId="com.xyz.plm.analysis.my.commandmygui" label="RunMyACtion" style="push"> <visibleWhen> <with variable="selection"> <iterate ifEmpty="false" operator="or"> <adapt value="com.xyz.plm.componentmodel.IComponent"> </adapt> </iterate> </with> </visibleWhen> </command> </menuContribution> </extension>
{ "pile_set_name": "StackExchange" }
Q: How do I breed a Malachite dragon? I have heard reports of the Malachite dragon not being in the shop but being a possible new dragon introduced with the Pollen Dragon. Is this a gem dragon? (isn't malachite technically a mineral??) A: You need to breed a plant dragon with a metal hybrid as the Wiki says. Apparently it is important that the metal dragon is the hybrid one, as there are several similar pairings between incompatible dragons where choosing which dragon is the hybrid determines which breeding result you can get. Note you can't directly breed a plant and metal dragon; alone they are incompatible.
{ "pile_set_name": "StackExchange" }
Q: TypeError: 'tuple' object is not callable when trying to subplot in python Currently trying to make some subplots in python. This exact code worked yesterday, and now I am getting "TypeError: 'tuple' object is not callable" The strange thing is it lets me run all these graphs separately in the command bar, but when I run the full code it only plots two of them before giving me this error. I have to restart the kernel to start plotting again or else anything I try to plot will give me that answer. here is what I am trying to code: plt.subplot(2,2,1) plt.plot(x_axis, avg_ANK_ang[:,0], color='red', linewidth=1, linestyle = '--') plt.fill_between(x_axis, avg_ANK_ang[:,0]-angANKnvf_err, avg_ANK_ang[:,0]+angANKnvf_err, alpha=0.5, facecolor='#FF9848') plt.plot(x_axis, avg_ANK_ang[:,1], color='blue', linewidth=1) plt.fill_between(x_axis, avg_ANK_ang[:,1]-angANKcvf_err, avg_ANK_ang[:,1]+angANKcvf_err, alpha=0.5, facecolor='#089FFF') plt.xticks([]) seaborn.despine(left=True, bottom=True, right=True) plt.ylabel("Ankle") plt.title("Angle (deg)") plt.subplot(2,2,3) plt.plot(x_axis, avg_MTP_ang[:,0], color='red', linewidth=1, linestyle = '--') plt.fill_between(x_axis, avg_MTP_ang[:,0]-angMTPnvf_err, avg_MTP_ang[:,0]+angMTPnvf_err, alpha=0.5, facecolor='#FF9848') plt.plot(x_axis, avg_MTP_ang[:,1], color='blue', linewidth=1) plt.fill_between(x_axis, avg_MTP_ang[:,1]-angMTPcvf_err, avg_MTP_ang[:,1]+angMTPcvf_err, alpha=0.5, facecolor='#089FFF') seaborn.despine(left=True, bottom=True, right=True) plt.plot = (x_axis, 0) plt.ylabel("MTP") plt.xlabel("% stance") plt.subplot(2,2,2) plt.plot(x_axis, avg_ANK_mom[:,0], color='red', linewidth=1, linestyle = '--') plt.fill_between(x_axis, avg_ANK_mom[:,0]-momANKnvf_err, avg_ANK_mom[:,0]+momANKnvf_err, alpha=0.5, facecolor='#FF9848') plt.plot(x_axis, avg_ANK_mom[:,1], color='blue', linewidth=1) plt.fill_between(x_axis, avg_ANK_mom[:,1]-momANKcvf_err, avg_ANK_mom[:,1]+momANKcvf_err, alpha=0.5, facecolor='#089FFF') plt.xticks([]) seaborn.despine(left=True, bottom=True, right=True) plt.title("Moment (NM)") plt.subplot(2,2,4) plt.plot(x_axis, avg_MTP_mom[:,0], color='red', linewidth=1, linestyle = '--') plt.fill_between(x_axis, avg_MTP_mom[:,0]-momMTPnvf_err, avg_MTP_mom[:,0]+momMTPnvf_err, alpha=0.5, facecolor='#FF9848') plt.plot(x_axis, avg_MTP_mom[:,1], color='blue', linewidth=1) plt.fill_between(x_axis, avg_MTP_mom[:,1]-momMTPcvf_err, avg_MTP_mom[:,1]+momMTPcvf_err, alpha=0.5, facecolor='#089FFF') seaborn.despine(left=True, bottom=True, right=True) plt.xlabel("% stance") the error: File "/Users/Laura/Box/NVF/Biomechanics data/Compile/compile.py", line 130, in <module> plt.plot(x_axis, avg_ANK_mom[:,0], color='red', linewidth=1, linestyle = '--') TypeError: 'tuple' object is not callable The other strange thing is it typically plots the first two plots before giving the error. (Unless I individually put them in the command window, then the first three will typically plot) A: plt.plot = (x_axis, 0) That line of code is the problem. You've reassigned plt.plot to be a tuple variable, and it's not a function anymore.
{ "pile_set_name": "StackExchange" }
Q: Accessing an instance variable from another class -- can I use a class method? I need to access to a NSMutableArray, in class1, from another class (class2). The solution I tried was to create a class method in class1 and call it from class2. Obviously, it is not possible because this is a restriction of class methods. I cannot figure out the solution. What can I do? A: Generally you expose needed instance variables through properties. This link covers properties. http://cocoacast.com/?q=node/103 Once the correct variables are exposed then simply pass a reference to the needed class to a given method.
{ "pile_set_name": "StackExchange" }
Q: BASE24 tutorial or learning material Does someone know where I can find a tutorial or material relating to Base24? I'm referring to Base24 the product by ACI. My understanding is that they use a programming language called 'TAL' which has similarities to Cobol and C. I've searched the net and I have only found job opportunities for Base24 developers but hardly any learning resources. Cheers A: TAL stands for "Transaction Application Language" and is supported by HP. There's a programmer's guide here and a reference manual here.
{ "pile_set_name": "StackExchange" }
Q: How half screen option is implemented I notice in an application like "whatsapp", if you click on "tell friend" it display half screen options buttons, I wonder how these half screen options view is implemented. A: Without an image, I'd say the half-view is a UIActionSheet.
{ "pile_set_name": "StackExchange" }
Q: Use function from a structure in class I am new to Swift and I have trouble using classes and structures. I have a Structure called Workspace: struct Workspace: Decodable { var guid: String var name: String func getUserWorkspace(base: String, completed: @escaping () -> ()){ //some code } } Here is my class User: public class User { var Wor = [Workspace]() var WorData:Workspace? = nil //+some other var & functions } So what I'm doing in my view controller is this: class SecondViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var listView: UITableView! var co = User() override func viewDidLoad() { super.viewDidLoad() co.WorData?.getUserWorkspace(base: co.Base) { print("success") self.listView.reloadData() self.updateVertically() } listView.delegate = self listView.dataSource = self } The problem is that the code never goes inside the function co.WorData?.getUserWorkspace(base: co.Base) Before I put it in the structure it was directly in the class but since I changed it it doesn't work anymore so I think I might be calling it the wrong way ? A: WorData is nil. Conditional unwrapping (co.WorData?.getUserWorkspace(base: co.Base) will check WorData has a value before trying to call the method. If it was nil and Swift didn't do this, it would crash. You either need to set it as new all the time var worData = Workspace() Set it after class init var user = User() user.worData = Workspace() // or pass a specific one in or require your User object to be initialised with a Workspace class User: NSObject { var wor = [Workspace]() var workspace: Workspace // use lower camel case for var names required init(workspace: Workspace) { self.workspace = workspace } }
{ "pile_set_name": "StackExchange" }
Q: ESP8266 WiFi module light switch Info So I've decided to hop on the ESP8266 WiFi module bandwagon and build a light switch with a couple of differences. 1) the light switch needs to go in the wall and be the same size as the existing panel light switches (deeper will be OK) 2) the circuit needs to pull power from the existing 250v power that runs through the switch 3) the light switch needs to contain a microphone so I can walk around the house issuing voice commands and each light switch will be able to hear the command and relay it to a central hub for processing. 4) the light switches will use the esp 8226's ability to be a wifi client and AP to create a mesh network so commands can be relayed around the house. 5) I need a design that an support up to 4 switches in one light switch panel. Questions 1) What should I use to pull 5v from the 250v power supplier. I've seen switching power supplys but these are all fairly bulky and contain transformers. I was hoping that there was a smaller solution. I only need 250mA to power the device. 2) Can the esp 8226 be used to forward raw audio from a digital microphone. I would estimate the device will need to handle about 100Kbps given I probably won't have sufficient room on the device to compress before I send the data. So there are two parts to this question a) is it possible to wire a microphone to the esp 8226 and capture the audio b) can it handle 100Kbps 3) If I 3d print the panel and a mount box in PLA is that considered electrically safe ? 4) How much of a challenge is reception going to be if the antenna is in the wall? Should I expose the antenna on the switch face plate? As i'm designing the light switches as a mesh network there should be another light switch just a few meters away in most cases. Sorry if the questions are dumb but I'm a programmer not an electrical engineer. A: "Only" 250mA is not the word I'd use when you want to drop up to 345V (if full wave rectified) - I'd like to hear you managed to dissipate 80+ Watt in a linear regulator. The 2 common options are a) full wave rectify, and use a buck converter to drop to 5V (addendum by bss36504: flyback converters do both) b) Use a transformer to drop the AC voltage first, then rectify and you may use either a linear regulator depending on the dropout voltage and the voltage ripple across the filtering capacitor of the rectifier. My advice to you is: c) don't reinvent the wheel, it's time consuming, expensive, and potentially dangerous. Use one of those 5V wall wart. They're bulky due to their transformer, but they work first try and they have been safety-checked. Otherwise you'll have to ask an electrician to check your system to cover your back in case anything goes wrong (I suspect insurance may not reimburse your home if it burns down because of something that you've done yourself and has not been checked...)! The ESP8266 will never be able to send uncompressed audio at 100kbps in real time. This source has tested it and measured 7kbps in TCP, and 19kbps in UDP. What you could do though is recognise commands, and send the command waveform at a slower rate. Assuming one command takes 1 second, it would take 15s to send the command over in TCP and 6s with UDP. Maybe you can compress on board first, reducing the time it takes to send the data, but I doubt you can do it with a ESP8266 alone (I've seen it done on Atmega328s). As for the microphone connection, you've got 2 GPIO's exposed on the connector of the common 8-pin ESP8266, and I THINK none of them are analog. Enough for a serial microphone module. The chip has 1 ADC though, so there are bigger boards with more signals routed and in particular 1 ADC which would allow you to use the more commonly available analog microphone modules such as this one. Seeing how voice recognition is barely good enough with a decent PC or smartphone microphone, I have no idea if the audio will be clear enough with cheap microphone modules, you need to test it. As long as you use a decent wall wart (or equivalent) to drop mains voltage to less than 25V, a PLA enclosure is absolutely fine and in fact it would be legal to leave the box open if the environment is dry. This should be valid in Europe only although I suspect it's similar elsewhere. I don't have my BS EN 7671 book with me, so you'd better check the details yourself for anything above 12V. I'm about to do the same here, and my advice to you is that you should probably trade some of this off: I'm personally going to use "OK google" on my phone, and send the commands to the correct ESP8266 in the house. After all, who wanders around without their phone nowadays?
{ "pile_set_name": "StackExchange" }
Q: Loss of references between service and controller data in Angular.js We encountered a problem when working with references between service and controller data // We have a service that we use to store id and some other data app.service('testService', function ($http, serverURL) { var self = this; self.data = { id: null, token: null, .... }; self.initMe = function () { return $http({ method: 'GET', url: serverURL + '/initMe/' + '?token=' + self.data.token }); }; return self; }); meModule.controller('MeCtrl', function (testService, ...) { $scope.me = testService.data; // we make a connection between the scope and the controller $rootScope.$on('initMe', function (e, data) { testService.initMe().success(function (data, status, headers, config) { // typeof(data.result) === 'object' // $scope.me = data.result; // Doesn't work // OR // testService.data = data.result; // Doesn't work testService.data = data.result; // $scope.me = testService.data; // It works, but we have to recover // the references between scope and service }); }); } Questions Why we loose the connection between scope and service in $scope.me = data.result or meService.data = data.result;? Maybe there are other, nicer ways to update the data in a sevice from an external API (Get requests)? A: That's just how JavaScript works. Consider the following example: > first = { data: null } { data: null } > second = { data: first.data } { data: null } > first.data = "something" 'something' > second.data null There is an incorrect assertion on this line: $scope.me = testService.data; // we make a connection ... There is no actual connection between the scope and the service; you're just copying the simple value over. However, if you store off a reference to an object, you can update that object in place and the "connection" will be kept. Consider this example: > first = { data: {} } { data: {} } > second = { data: first.data } { data: {} } > first.data['something'] = 'stuff' 'stuff' > second.data { something: 'stuff' }
{ "pile_set_name": "StackExchange" }
Q: average of RGB color of Image I'm trying to get average of RGB color of Image in php. by gd lib I program it $x = imagesx($im); $y = imagesy($im); for ($i = 0;$i < $x;$i++) for ($j = 0;$j < $y;$j++){ $rgb = imagecolorat($im,$i,$j); $sum['R'] += ($rgb >> 16) & 0xFF; $sum['G'] += ($rgb >> 8) & 0xFF; $sum['B'] += $rgb & 0xFF; } But it's not good way I think. It needs a lot of ram to process. Is there another way to do it? A: I would go with resampling: $tmp_img = ImageCreateTrueColor(1,1); ImageCopyResampled($tmp_img,$im,0,0,0,0,1,1,$x,$y); // or ImageCopyResized $rgb = ImageColorAt($tmp_img,0,0); A: One way to do this is to scale the picture to just one pixel and then use the colors of that pixel as a reference. <?php $image = new Imagick('800x480.jpg'); $image->scaleImage(1, 1, true); $pixel = $image->getImagePixelColor(0,0); $red = ($rgb >> 16) & 0xFF; $green = ($rgb >> 8) & 0xFF; $blue = $rgb & 0xFF; ?> That way you don't need to handle messy details. and you can use smarter scaling algorithms to achieve better precision. Edit: You can use Imagick::resizeImage instead if you need a more sophisticated algorithm. it can use different algorithms like Interpolation filter.
{ "pile_set_name": "StackExchange" }
Q: get and set css style into var I am just begginer. I am trying to get font size of the element into variable. After that I would like to set font size of another element using this variable. I have been looking for the solution for 12 hours and found nothing. I would be grateful for any tips. Thanks in advance. My code is below. jQuery(window).scroll(function() { var OldFont = jQuery('.mhmainnav').find('li').find('a').css("font-size"); var windowTop = jQuery(window).scrollTop(); if (windowTop > 280) { jQuery('.mh-main-nav').find('li').find('a').css("font-size", "12px"); } else { jQuery('.mh-main-nav').find('li').find('a').css("font-size", OldFont); } }); A: The only thing I would change is moving the old font to outside your scroll, otherwise when you change the font-size to 12px, OldFont will get overwritten next time you scroll. Maybe probably cache your anchor selector too for better performance Also check your mhmainnav selector - you change it to mh-main-nav var anchors = jQuery('.mhmainnav').find('a'), // if you are reusing this in the scroll, cache it here for better performance OldFont = anchors.css("font-size"); // set this before the scroll as it shouldn't change once set jQuery(window).scroll(function() { var windowTop = jQuery(this).scrollTop(); if (windowTop > 280) { anchors.css("font-size", "12px"); } else { anchors.css("font-size", OldFont); } });
{ "pile_set_name": "StackExchange" }
Q: Get current CSS property value during a transition in JavaScript I would like to be able to read the value of a CSS property in the middle of a transition before it is fully executed. Is that possible? So if during a transition from 0% to 100%, I were to check halfway through, could I see it at 50%? A: Is it possible to get the current css property during a transition in JavaScript? Yes var timer; function test(e) { var $this; $this = $(this); timer = setInterval(function () { console.log($this.height()); }, 500); } function untest(e) { clearInterval(timer); } $('div').mouseenter(test).mouseleave(untest); div { transition: height 10s; -moz-transition: height 10s; -webkit-transition: height 10s; width: 100px; height: 100px; background-color: #00F; } div:hover { height: 300px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div></div> So far I've only tested firefox & chrome, but it appears that you can get the current CSS height via JS. I can't think of a reason why the browser wouldn't report the change in styles to the DOM during a CSS transition. A: Yes, it's possible. The corresponding property on the object returned by getComputedStyle will change gradually over the course of a transition, as shown in this demo: const box = document.getElementById('box'), turnBlueButton = document.getElementById('turnblue'), turnPinkButton = document.getElementById('turnpink'), computedStyleValueSpan = document.getElementById('computedstylevalue'); turnBlueButton.onclick = () => { box.classList.add('blue'); box.classList.remove('pink'); } turnPinkButton.onclick = () => { box.classList.add('pink'); box.classList.remove('blue'); } const computedStyleObj = getComputedStyle(box); setInterval(() => { computedStyleValueSpan.textContent = computedStyleObj.backgroundColor; }, 50); #box { width:50px; height:50px; transition: background-color 10s; } .pink { background: pink; } .blue { background: blue; } <div id="box" class="pink"></div> <p> <code>getComputedStyle(box).backgroundColor:</code> <code><span id="computedstylevalue"></span></code> </p> <button id="turnblue">Turn blue</button> <button id="turnpink">Turn pink</button> This behaviour is required by spec. https://www.w3.org/TR/css-transitions-1/#transitions- states: The computed value of a property transitions over time from the old value to the new value. Therefore if a script queries the computed value of a property (or other data depending on it) as it is transitioning, it will see an intermediate value that represents the current animated value of the property. While the Mozilla docs seem to say that getComputedStyle would return either the start or the end value, they seem wrong, at least for WebKit. WebKit-based browsers' getComputedStyle implementation seems to return intermediate values. (Hat tip to https://stackoverflow.com/users/27862/user123444555621 for their comment pointing out the relevant spec passage.)
{ "pile_set_name": "StackExchange" }
Q: Is there a way to load string resources from database instead of the wicket properties file? I need to store the string key value pairs in the database. I want to load them with the Wicket ResourceModel, so no modifications have to be made in the gui part of the application. Is there a way to do that that avoids the overwriting of ComponentStringResourceLoader#loadStringResource() ? A: You need to implement IStringResourceLoader that reads from the DB and to register it with getResourceSettings().getStringResourceLoaders().add(new MyDbResourceLoader()) in MyApplication#init() method.
{ "pile_set_name": "StackExchange" }
Q: Proof of a equality-topology Consider he topological space $ (X,\tau)$ and $A \subseteq X$. I want to prove that these are equivalent: (i)$A\in \tau$ ($A$ is open)~ (ii) For any $B\subseteq X$, where $A\cap B=\emptyset$ then, $A\cap \overline B =\emptyset$ I have started in this way: (i) $\to$ (ii) $B\subseteq X$, where $A\cap B=\emptyset$ if and only if (As $A$ is open) $A^\circ\cap B = \emptyset $ if and only if $A^\circ\cap (B^\circ)^\circ = \emptyset$ if and only if $(A\cap B^\circ)^\circ = \emptyset$ if and only if $X-(A\cap B^\circ)^\circ =X$ if and only if $\overline{X-(A\cap B^\circ)} =X$..... But I don't get to any point Thank you for your time A: If $A$ is open, then $X -A $ is closed. If $A \cap B = \varnothing$, then $B \subset X-A$. Then $\overline{B} \subset \overline{X-A} = X-A$, so $A \cap \overline{B} = \varnothing$. Conversely, if all sets $B$ disjoint from $A$ are such that $A \cap \overline{B} = \varnothing$. Then $A \cap \overline{X-A} = \varnothing \implies \overline{X-A} \subset X-A$, or $X-A$ is closed, so $A$ is open.
{ "pile_set_name": "StackExchange" }
Q: Firebase Functions Deployment Failed I have been trying to deploy my firebase function called onFollowUser however, it has been constantly failing to launch. I have the Blaze plan currently and this is the error message: ⚠ functions[onFollowUser(us-central1)]: Deployment error. Failed to configure trigger providers/cloud.firestore/eventTypes/[email protected] (__gcf__.us-central1.onFollowUser) Functions deploy had errors with the following functions: onFollowUser To try redeploying those functions, run: firebase deploy --only functions:onFollowUser To continue deploying other features (such as database), run: firebase deploy --except functions Error: Functions did not deploy properly. Here is my complete index.js: const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.onFollowUser = functions .firestore .document('/Followers/{userID}/User Follower/{followerID}') .onCreate(async (snapshot, context) => { console.log(snapshot.data()); }); I have spotted the error... My database is located in Europe-central, however, for some reason, it is deploying to US-central... How can I change this? The ID of my project which it says it is deploying to is correct. Here is my package.json: { "name": "functions", "description": "Cloud Functions for Firebase", "scripts": { "lint": "eslint .", "serve": "firebase emulators:start --only functions", "shell": "firebase functions:shell", "start": "npm run shell", "deploy": "firebase deploy --only functions", "logs": "firebase functions:log" }, "engines": { "node": "10" }, "dependencies": { "firebase-admin": "^8.10.0", "firebase-functions": "^3.6.1" }, "devDependencies": { "eslint": "^5.12.0", "eslint-plugin-promise": "^4.0.1", "firebase-functions-test": "^0.2.0" }, "private": true } Edit: Even though I get this failing message, I can see the function on my console : A: This is a know issue, see: Error Deploying Firestore Function with a space in the name of a collection Rename the a collections so that they do not includes spaces, rather use camel case, dashes or underscores. const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); admin.firestore().settings({ timestampsInSnapshots: true }); exports.onFollowUser = functions .firestore .document('/Followers/{userID}/User-Follower/{followerID}') .onCreate(async (snapshot, context) => { console.log(snapshot.data()); return; });
{ "pile_set_name": "StackExchange" }
Q: As many have pointed out, comments are the problem then what is the solution? The first thing they teach you in art school is how to take and give criticism as a professional. Criticism is not just a statement to the contrary, it also must contain a reason for the criticism and must be accompanied a proposed alternative solution. Before leaving a comment basically stating. You are wrong! and nothing else, think about how productive that is in the whole. Without the proposed alternative, it is nothing more than a verbose -1. Think about how that proves my point about the comment system. Downvotes on meta mean "I disagree". Why post a comment that basically states "I disagree and some generic negative comment" and nothing else, is illustrating the point and just providing objective data to back up subjective feedback. Why not just down vote and move on, that is the current community mantra and party line. For the uninitiated that is almost just as unwelcoming, at least they do not see a comment that they can internalize a some kind of abuse directed as them personally. It is not a solution, that much is clear. On the main site, the down votes have real consequences and the comments are taken as criticism, with no positive alternative solution proposed. Problem: Comments The presumption of the argument is based on comments are the root cause as evidences in every case cited that people are complaining about. So comments no matter how neutral are causing feelings of unwelcoming and no comments are considered just as unwelcoming. Damned if you do, damned if you don't. I make no assertion that any of these feelings is legitimate. That is impossible because feelings are subjective. Jay Hanlon is the one that made the erroneous jump to: "When someone tells you how they feel, you can pack up your magnifying glass and clue kit, cuz that’s the answer. You’re done. And a lot of devs feel like Stack Overflow is an intimidating, unwelcoming place. We know because they tell us. I am doing nothing but proposing something to try and change what he thinks is wrong." The current comment system is the majority source of the feelings because of two polcies that exacerbate the inference and amplify things perceptions that are not there or completely unintended. comments are not for conversation: that means they are terse, one liners and people are loath to respond to lines of questioning to avoid conversing. Which typically devolves into arguing because of the terse one liners. vote and move one: this community policy is recommended because of the first problem. It causes its own problems and exacerbates the first one. No follow ups on down votes, close votes, etc. No comments are just as problematic for new community members as terse comments with no follow up. So we should just remove the ability to comment. That much has been expressed in the past ( which I actually disagree with that proposal, it does not go far enough and is what prompted this post ) and tries to address the root cause of most of the problems that Jay Hanlon's blog post tries to make a point about but gets lost in the clumsy way he blames the volunteer community members that contribute the content to the site that makes it what it is and also whatever financial commercial success it may have. This is my attempt to address the problem, nothing more. The in these cases where comments are taken as offense almost always have devolved into a back and forth between one or more people. Which just exacerbated it the problem. Someone feels like they are being ganged up on or ignore at some point. It is a damned if you do damned if you don't situation, has been for the at least last five years, from my experience. Chat rooms get suggested by some heuristic now, usually long after it should have been taken to chat and everyone is pissed and wants nothing to do with any more communication. Solution: Chat By definition comments are not for conversation and they are about the worst way to hold one if conversation was allowed in them. By definition chat is for conversation and real time interaction, which would go a long ways to changing the unwelcoming perception that the no conversation in comments commenting system evokes now. This by no means completely removes the problem that some people are just going to be assholes no matter what, it just removes some of unintended perception that people that are not intentionally being an asshole to a form of communication that is more suited to conversation instead of tossing terse one liners over a fence. The logical conclusion is that the ability to leave comments be removed. I suggest that that every question gets a chat room instead. You could make the OP the room owner and moderation would be from the community members with badges in the tags of the question. Lock the chat room when an answer is accepted or abandoned for some period of time. Make it vote to reopen or something, with previous participants getting higher weighted votes, or flagged for moderation just like comments would have been. Delete the room when the question is roomba'd, delete voted, has no activity for a period of time or by a moderator just like comments would have been. The technology is there, refactor it where it will scale to this requirement. A: The problem is not in comments. The problem is that some people lack any tact or patience at times, and that other people can't accept the slightest bit of criticism, however friendly it's worded. This causes people not to be nice to each other. You're not going to solve this problem by moving the place where these words are exchanged. They're still going to be jerks in chat. That just moves the problem, it doesn't eradicate it. A: I think my hubris in my feature request to rate limit comments, as well as others' hubris in excising them completely for certain rep levels, as well as the hubris in this suggestion is that, whether we like it or not, comments fill a role that the system simply...doesn't. I still agree with you that something needs to be done with comments and commentating on the main sites, but what's going ignored is the vacuum of what actually replaces comments. For simple things like suggesting dupes, you can experience this... ...but most of the time, you experience this instead. The solution may be simply having the close reason(s) better explain what's going on, as it seems to be the case that the community rushes in to fill the gap and void of the system simply not mentioning, "Oh hey, this post is going to be closed as 'unclear what you're asking'. Here's a few things you can do to fix that!..." Pushing this into chat would move the chimera from one part of the site to another, and chat has enough issues without adding this kind of weight to it. I plan to put together a better post to actually describe such a feature, when I find some energy... A: As others have indicated, it's unclear why you think that forcing people to either write answers or to take it up in chat would help anything. This would, however, have the effect of cutting off discussion. Chat is blocked on many corporate networks, for example, and it would be a pain to have to go to a separate window to see the discussion of an idea. A good percent of people simply wouldn't bother with the extra step and wouldn't bother to get involved in the discussion at all. If you think that someone is being rude, unnecessarily sarcastic, etc. in comments, just flag the comment.
{ "pile_set_name": "StackExchange" }
Q: Swift String to unsigned char [](CUnsignedChar) Hello i'm trying to use an old legacy C library that uses buffers (unsigned char []) to transform the data. The main issue here is that I couldn't find a way to transform a String to a CUnsignedChar and then be able to alloc that buffer to a UnsafeMutablePointer A: If you want to convert a Swift string to an immutable C string to pass to a C function, try this: let s: String = "hello, world!" s.nulTerminatedUTF8.withUnsafeBufferPointer { p -> Void in puts(UnsafePointer<Int8>(p.baseAddress)) Void() } You may need to use UnsafePointer<UInt8> if your function takes an unsigned char *.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to fade between two view background images? I would like to know if it's possible for some button to cause a fade from one background image to another? The following code I have results in an abrupt change from the current image, background-image-1, to the new image, background-image-2. func buttonPressed() { if let image = UIImage(named: "background-image-2") { UIView.animateWithDuration(2, delay: 0, options: .CurveEaseInOut, animations: {_ in self.view.backgroundColor = UIColor(patternImage: image) }, completion: nil) } Thanks EDIT Though the accepted answer does work, I was finding slight glitches when toggling quickly between images. A similar method using UIView.animateWithDuration solves this: func buttonPressed() { let oldImageView = UIImageView(image: UIImage(named: "background-image-1")) oldImageView.frame = view.frame let newImageView = UIImageView(image: UIImage(named:"background-image-2")) newImageView.frame = view.frame newImageView.alpha = 0 view.insertSubview(newImageView, aboveSubview: backgroundImageView) view.insertSubview(oldImageView, aboveSubview: newImageView) UIView.animateWithDuration(1.0, delay: 0.0, options: .CurveEaseInOut, animations: { oldImageView.alpha = 0 newImageView.alpha = 1 }, completion: { completed in self.backgroundImageView.image = newImage newImageView.removeFromSuperview() oldImageView.removeFromSuperview() }) } A: Say imageView is the UIImageView you are using for your animation. image1 is your original image. image2 is the new image. Try this: let crossFade: CABasicAnimation = CABasicAnimation(keyPath: "contents") crossFade.duration = 1 crossFade.fromValue = image1.CGImage crossFade.toValue = image2.CGImage self.imageView.image = image2 self.imageView.layer.addAnimation(crossFade, forKey: "animateContents") Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: Axon 4 - JpaEventStorageEngine protected constructor When trying to configure the Upcaster in Axon 4 based on the documentation available at : Axon 4 Framework Versioning Events I am getting the error: JpaEventStorageEngine() has protected access @Bean public JpaEventStorageEngine eventStorageEngine( Serializer serializer, DataSource dataSource, SingleEventUpcaster myUpcaster, EntityManagerProvider entityManagerProvider, PlatformTransactionManager transactionManager) { return new JpaEventStorageEngine(serializer, myUpcaster::upcast, dataSource, entityManagerProvider, transactionManager); } What am I missing? A: I think I can help you with this. You have, sadly, found an issue with the reference guide just now. As off Axon 4, all the main infrastructure components no longer get created through a constructor, but through a Builder pattern. Thus, the right approach to create it would be: @Bean public JpaEventStorageEngine eventStorageEngine(Serializer eventSerializer, Serializer snapshotSerializer, DataSource dataSource, SingleEventUpcaster myUpcaster, EntityManagerProvider entityManagerProvider, TransactionManager transactionManager) throws SQLException { return JpaEventStorageEngine.builder() .eventSerializer(eventSerializer) .snapshotSerializer(snapshotSerializer) .dataSource(dataSource) .entityManagerProvider(entityManagerProvider) .transactionManager(transactionManager) .upcasterChain(myUpcaster) .build(); } I've just adjusted the Reference Guide to reflect this accordingly; I'm terribly sorry for the inconvenience.
{ "pile_set_name": "StackExchange" }
Q: How to exit if statement and continue to else This is a long shot question, but is there a way in php to exit an "if" statement and continue on to the "else" statement if an error occurs inside the if block? example if ($condition == "good") { //do method one //error occurs during method one, need to exit and continue to else } else { //do method two } Of course it is possible to do a nested if inside the first if, but that seems hacky. TIA A: try { //do method one //error occurs during method one, need to exit and continue to else if ($condition != "good") { throw new Exception('foo'); } } catch (Exception $e) { //do method two } A: I would just use a function so you don't duplicate code: if ($condition == "good") { //do method one //error occurs during method one if($error == true) { elsefunction(); } } else { elsefunction(); } function elsefunction() { //else code here }
{ "pile_set_name": "StackExchange" }
Q: Custom adapter, listview getFilter method cannot be resolved im building an android app atm and it contains a page with information in a listview, the information is taken from a List and the items are from a class which has 2 strings in it. I want to use a filter to search through my items in the list. I used this to create an adapter and filter. After a day of searching around on here i still have the same problem, my adapter.getFilter(); method cannot be resolved. this is my custom adapter class with a filter class below import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Filter; import android.widget.Filterable; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class CustomAdapter extends BaseAdapter implements Filterable { private List<Facility> mListItems; private List<Facility> mFilteredListItems; private FacilityFilter facilityFilter = new FacilityFilter(); private LayoutInflater mLayoutInflater; public CustomAdapter(Context context, List<Facility> pDataList) { super(); this.mListItems = new ArrayList<>(); this.mFilteredListItems = new ArrayList<>(); mListItems.addAll(pDataList); mFilteredListItems.addAll(pDataList); mLayoutInflater = LayoutInflater.from(context); } public void resetData() { mFilteredListItems = mListItems; } static class ViewHolder { protected TextView customRowText; protected TextView mediumRowText; } @Override public int getCount() { return mFilteredListItems.size(); } @Override public Object getItem(int position) { return mFilteredListItems.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; ViewHolder viewHolder; Facility facility = mFilteredListItems.get(position); if (convertView == null) { view = mLayoutInflater.inflate(R.layout.custom_row, parent, false); viewHolder = new ViewHolder(); viewHolder.customRowText = (TextView) view.findViewById(R.id.customRowText); viewHolder.mediumRowText = (TextView) view.findViewById(R.id.mediumRowText); view.setTag(viewHolder); } else { view = convertView; viewHolder = ((ViewHolder) view.getTag()); } viewHolder.customRowText.setText(facility.title); viewHolder.mediumRowText.setText(facility.info); return convertView; } @Override public Filter getFilter() { return facilityFilter; } public class FacilityFilter extends Filter{ @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults Result = new FilterResults(); // if constraint is empty return the original names if(constraint.length() == 0 ){ Result.values = mListItems; Result.count = mListItems.size(); return Result; } String filterString = constraint.toString().toLowerCase(); Facility filterableString; for(int i = 0; i<mListItems.size(); i++){ filterableString = mListItems.get(i); if(filterableString.toString().toLowerCase().contains(filterString)){ mFilteredListItems.add(filterableString); } } Result.values = mFilteredListItems; Result.count = mFilteredListItems.size(); return Result; } @Override protected void publishResults(CharSequence constraint,FilterResults results) { mFilteredListItems = (ArrayList<Facility>) results.values; notifyDataSetChanged(); } } } And I use this in my activity: btw mFacilities is my List with items from the Facility class (the one with 2 strings). facilityAdapter = new CustomAdapter(getBaseContext(), mFacilities); facilityList = (ListView) findViewById(R.id.facilitiesList); searchInput = (EditText)findViewById(R.id.searchInput); facilityList.setAdapter(facilityAdapter); searchInput.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { facilityAdapter.getFilter(); } @Override public void afterTextChanged(Editable s) { } }); A: You have wrong type of your instance when you declare facilityAdapter. Change BaseAdapter facilityAdapter; to CustomAdapter facilityAdapter;. It should resolve your issue.
{ "pile_set_name": "StackExchange" }
Q: Show that $∏_{k=1}^{n}(2k)²/((2k-1)(2k+1))<π/2$ for all $n≥1$. We have $$π/2=∏_{k=1}^{∞}(2k)²/((2k-1)(2k+1))$$ Show that $$∏_{k=1}^{n}(2k)²/((2k-1)(2k+1))<π/2$$ for all $n≥1$. I have remarked that $(2k)²/((2k-1)(2k+1))>1$ for all $k$ A: Hint $$a_n\triangleq \prod_{k=1}^{n}{(2k)^2\over (2k-1)(2k+1)}$$therefore $$a_{n+1}>a_n>1$$
{ "pile_set_name": "StackExchange" }
Q: Did Huxley detail the Brave New World setting outside of the book? Besides the book Brave New World itself, are there any sources, interviews or quotes from the author himself —Aldous Huxley — explaining more about the world and characters of this book? I'm not asking about his interpretations or the views he wanted to expose in Brave New World, but about the setting itself, like the Letters of J.R.R Tolkien where he explains more about his legendarium or J.K.Rowling's Pottermore. So I want to know if there is some "Word of God" (warning: TVTropes) about the Brave New World universe, instead of interpretations and speculations by people other than the author. I tried to find it online, but with no success. I only found these videos, but for what I got (I'm not a native English speaker, so the videos without subtitles are hard) in these he is speaking about the themes of the book regarding the real world — but I'm a damned nerd, I want to learn more about Brave New World universe and not about the real-life implications of his writings. A: In short: No. Aldous Huxley made clear in several of his subsequent writings that he was not very interested in fleshing out the setting he had created in Brave New World. As time passed, he was much more interested in seeing how the real world had developed, contrary to his expectations; and in considering how he could have written Brave New World differently. Much of my discussion here will be based on Huxley's comments in his collection of essays, "Brave New World Revisited," from 1958, twenty-six years after the publication of Brave New World. The purpose of the collection was to given his then-current thinking about many of the issues that he had raised in the novel. In general, the essays are quite pessimistic about the future. When he wrote the Brave New World, Huxley thought that a sea change in the nature of human culture would be required in order for the dystopia he envisioned to take hold; but by 1958, he thought that dystopia could actually be a natural outgrowth of the changes that had overtaken the world in the twentieth century. (The whole thing makes for very interesting reading. While I disagree with Huxley on many points, he clearly has put a great deal of thought into the questions at hand.) One thing that is immediately evident from reading "Brave New World Revisited," is that Huxley was framing the essays entirely based on his personal recollection of the novel. Not only does he not always have a crystal clear idea of how things worked in the setting he had created, he does not care; in fact, he did not even bother to reread or consult Brave New World to get details of the setting accurate. In the very first essay ("Over-Population"), the author indicates that he does not remember how far in the future the novel takes place: I for­get the exact date of the events recorded in Brave New World; but it was somewhere in the sixth or seventh century A.F. (After Ford) He later gives other details that similarly indicate he is working purely from the memory of what he had written a couple decades earlier. In the Brave New World of my fable, the problem of human numbers in their relation to natural resources had been effectively solved. An optimum figure for world population had been calculated and numbers were maintained at this figure (a little under two bil­lions, if I remember rightly) generation after genera­tion. Careful world-building was not Huxley's way. In this 1960 interview with The Paris Review, he explains that he largely makes up his plots as he goes along (including the plot of Brave New World), without mapping things out extensively in advance. Moreover, he writes and edits one full chapter at a time, minimizing the need to go back and re-analyze what is already effectively finished. I work away a chapter at a time, finding my way as I go. I know very dimly when I start what’s going to happen. I just have a very general idea, and then the thing develops as I write. Sometimes—it’s happened to me more than once—I will write a great deal, then find it just doesn’t work, and have to throw the whole thing away. I like to have a chapter finished before I begin on the next one. But I’m never entirely certain what’s going to happen in the next chapter until I’ve worked it out. Things come to me in driblets, and when the driblets come I have to work hard to make them into something coherent. Finally, in the foreword to his final novel Island, Aldous Huxley indicated that, since the publication of Brave New World, he had decided he should have created a different setting instead: If I were now to rewrite the book, I would offer the Savage a third alternative. Between the Utopian and primitive horns of his dilemma would lie the possibility of sanity.... In this community economics would be decentralist and Henry-Georgian, politics Kropotkinesque and co-operative. Science and technology would be used as though, like the Sabbath, they had been made for man, not (as at present and still more so in the Brave New World) as though man were to be adapted and enslaved to them. Religion would be the conscious and intelligent pursuit of man's Final End, the unitive knowledge of immanent Tao or Logos, the transcendent Godhead or Brahman. And the prevailing philosophy of life would be a kind of Higher Utilitarianism, in which the Greatest Happiness principle would be secondary to the Final End principle -- the first question to be asked and answered in every contingency of life being: 'How will this thought or action contribute to, or interfere with, the achievement, by me and the greatest possible number of other individuals, of man's Final End?'
{ "pile_set_name": "StackExchange" }
Q: spring cloud stream kinesis Binder I am trying to implement a spring boot aws kinesis consumer that is capable of being auto-scaled in order to share the load (split processing shards) with the original instance. What I have been able to do: using the well defined read me and examples available hereKinesis binder docs I have been able to start up multiple consumers that actually divide the shards for processing by supplying these properties. on the producer, I supply partitionCount: 2 via an application property. and on the consumers, I supply both the instanceIndex and the instanceCount. on consumer 1 i have instanceIndex=0 and instantCount =2 , on consumer 2 i have instanceIndex=1 and instantCount=2 this works fine and I have two spring boot applications dealing with their specific shards. But in this case, I have to have a pre-configured properties file per boot application that needs to be available upon load for them to split the load. and if I only start up the first consumer(non auto-scaled) I only process shards specific to index 0, leaving other shards unprocessed. What I would like to do but not sure if it is possible is to have a single consumer deployed (that processes all shards). if I deploy another instance I would like that instance to relive the first consumer of some of the load, in other words, if I have 2 shards and one consumer it would process both, if I then deploy another app I would like that first consumer to now only processes from a single shard leaving the second shard to the second consumer. I have tried to do this by not specifying instanceIndex or instanceCount on the consumers and only supplying the group name, but that leaves the second consumer idle until the first is shut down. FYI I have also created my own metadata and locking table, preventing the binder from creating the default ones. Configurations: Producer ----------------- originator: KinesisProducer server: port: 8090 spring: cloud: stream: bindings: output: destination: <stream-name> content-type: application/json producer: headerMode: none partitionKeyExpression: headers.type consumers------------------------------------- originator: KinesisSink server: port: 8091 spring: cloud: stream: kinesis: bindings: input: consumer: listenerMode: batch recordsLimit: 10 shardIteratorType: TRIM_HORIZON binder: checkpoint: table: <checkpoint-table> locks: table: <locking-table bindings: input: destination: <stream-name> content-type: application/json consumer: concurrency: 1 listenerMode: batch useNativeDecoding: true recordsLimit: 10 idleBetweenPolls: 250 partitioned: true group: mygroup A: That’s correct. That’s how it works for now: if one consumer is there, it takes all the shards for processing. The second one will take an action only if the first one is broken somehow for at least one shard. The proper Kafka-like rebalancing is on our roadmap. We don’t have the solid vision yet, so issue on the matter and subsequent contribution are welcome!
{ "pile_set_name": "StackExchange" }
Q: Passing PHP variables in $wpdb query I've a table in my database named wp_q33uds_campaign. I have a query in my application as follows: $usr = $wpdb->get_var('SELECT user_id FROM wp_q33uds_campaign WHERE date1 = 1451546940'); Now, this query returns a user_id from the table which has the date1 column set as 1451546940. Now, somewhere in my application, I have a variable named $dd where $dd is set as 1451546940. However, when I modify my above query as follows: $usr = $wpdb->get_var('SELECT user_id FROM wp_q33uds_campaign WHERE date1 = $dd); it returns a NULL value. What seems to be wrong here? Is there no way to pass in PHP variables inside $wpdb query? A: You should use the $wpdb->prepare() method to properly escape variables to prevent syntax errors and most importantly to protect against SQL injection attacks - see Running General Queries in the WordPress documentation. You should also use the $wpdb->prefix property to ensure the proper table prefix in your queries. The value you see for your date is actually a Unix timestamp, you will need to convert this to a string using date(); // convert from timestamp to date string $dd = date( 'Y-m-d H:i:s', 1451546940 ); // your SQL statement with db table prefix and %s placeholder $sql = "SELECT user_id FROM {$wpdb->prefix}campaign WHERE date1 = %s"; // populate vars and run query $usr = $wpdb->get_var( $wpdb->prepare( $sql, $dd ) );
{ "pile_set_name": "StackExchange" }
Q: Why are interfaces called interfaces? From what I understand so far, an interface is a list of methods that need to be implemented by whoever wishes to use that interface. If so, would it make any difference to call it a specification instead of interface, or is it more sophisticated than a specification? A: The definition of interface on oxforddictionaries.com is A point where two systems, subjects, organizations, etc. meet and interact. In programming, the 'two systems' are the class that is using the interface (the client), and the class that is 'hidden behind' the interface, i.e. the class that implements the interface. In this way an interface is a point where two classes interact.
{ "pile_set_name": "StackExchange" }
Q: .htaccess in subfolder The main site runs WordPress with .htaccess <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> I'm going to create an CodeIgniter app in subdirectory site.com/online/ If simply add CI .hta file in subfolder it wouldn't work. CI .htaccess: RewriteEngine on RewriteCond $1 !^(index\.php|robots\.txt|img|styles|js) RewriteRule ^(.*)$ /index.php?/$1 [L] Is it possible to combine two .htaccess files or to do something with .htaccess in CI subfolder? Thank you. UPD. Thank you for answers, I've tried all variants, and eventually moved project to subdomain. A: First thing, your .htaccess should be like this: <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{THE_REQUEST} !^GET\s/+online/ [NC] RewriteRule . /index.php [L] </IfModule> #Then add this for CI handling in the same .htaccess RewriteCond %{REQUEST_FILENAME} !-f RewriteCond $1 !index\.php [NC] RewriteRule ^online/(.*)$ online/index.php?/$1 [L,NC] Then you can remove (or rename) .htaccess in the online subfolder.
{ "pile_set_name": "StackExchange" }
Q: What is the proper structure for Nested Case statement with Subquery Sql Statement? I have here a complicated query here where I have nested case with subquery. I am having trouble with getting the right structure of it. Here is my code: select AccountNo, Case when Datepart (month,TranDate) = 1 Then Case ISNULL(RemainingBalance,'NULLVALUE') When 'NULLVALUE' Then (select top 1 RemainingBalance From tempAccountBalance where DATEPART (YEAR,TranDate)=@FiscalYear-1 order by TranDate desc) else MIN(Case when Datepart (month,TranDate) <= 3 Then RemainingBalance END) End Q1 FROM tempAccountBalance WHERE Datepart (year,TranDate) = @FiscalYear and AccountNo=@AccountNo Group By AccountNo I get an error which says, Msg 102, Level 15, State 1, Line 11 Incorrect syntax near 'Q1'. A: If you indent your code, you'll spot errors like this more easily (below). Note however that your query still has grouping issues - you'll either need to add TranDate and RemainingBalance to the GROUP BY, or use aggregates on them. I've taken a guess below without any understanding of your query: select AccountNo, Case when Datepart(month,TranDate) = 1 Then Case ISNULL(Min(RemainingBalance), 'NULLVALUE') -- Added Min When 'NULLVALUE' Then (select top 1 RemainingBalance From tempAccountBalance where DATEPART (YEAR,TranDate)=@FiscalYear-1 order by TranDate desc) else MIN( Case when Datepart (month,TranDate) <= 3 Then RemainingBalance END) end -- Missing End Q1 FROM tempAccountBalance WHERE Datepart(year,TranDate) = @FiscalYear and AccountNo=@AccountNo Group By AccountNo, Datepart(month,TranDate); -- Added to Group By A: You need an END before the Q1 : select AccountNo, Case when Datepart (month,TranDate) = 1 Then Case ISNULL(RemainingBalance,'NULLVALUE') When 'NULLVALUE' Then (select top 1 RemainingBalance From tempAccountBalance where DATEPART (YEAR,TranDate)=@FiscalYear-1 order by TranDate desc) else MIN(Case when Datepart (month,TranDate) <= 3 Then RemainingBalance END) End End Q1 FROM tempAccountBalance WHERE Datepart (year,TranDate) = @FiscalYear and AccountNo=@AccountNo Group By AccountNo
{ "pile_set_name": "StackExchange" }
Q: PDF smart file diff I have a LibreOffice document that I converted to PDF at some point in time using the built-in capabilities. The timestamp on the PDF is later than on the word processing document, so that makes sense, but I am not absolutely sure that the word processing document produces exactly that PDF. The document is 20 pages long so it's not a good idea to check it manually. One possibility is to redo the PDF in a different folder and then do a binary diff of the two PDFs. Unfortunately the command line diff indicates that the "binary files are different". Is there a "smart binary diff" that will help me determine if the difference is merely in meta data or some such non-consequential difference? A: In general it is a good idea to check if command + file extension are what your are looking for. diff+pdf results in diffpdf. sudo apt-get install diffpdf DiffPDF is used to compare two PDF files. By default the comparison is of the text on each pair of pages, but comparing the appearance of pages is also supported (for example, if a diagram is changed or a paragraph reformatted). It is also possible to compare particular pages or page ranges. For example, if there are two versions of a PDF file, one with pages 1-12 and the other with pages 1-13 because of an extra page having been added as page 4, they can be compared by specifying two page ranges, 1-12 for the first and 1-3, 5-13 for the second. This will make DiffPDF compare pages in the pairs (1, 1), (2, 2), (3, 3), (4, 5), (5, 6), and so on, to (12, 13). Source: Ubuntugeek.com.
{ "pile_set_name": "StackExchange" }
Q: Predicate logic: Two variables - same value allowed? I have the following formula: $\exists y \forall x ((x \geq y) \wedge \neg(y \geq x))$ This essentially boils down to: $\exists y \forall x (x > y)$ I have to check whether this applies to certain universes. But my result depends on whether I can assume that x can also equal y, because in that case the condition will never be true (how could a number be smaller than and at the same time equal to another number?). Can you give me a hint? A: I'll put the answer here so the question can be marked as answered. "For every $x$" means for every $x$, period. So, yes, there are no restrictions on $x$ not being equal to $y$; any such restrictions would have to be given as predicates (a clause $x\neq y$). I'll note (as I did in the comments) that whether the transformation from $(x\geq y) \wedge \neg(y\geq x)$ is equivalent to $x\gt y$ (and whether $\gt$ is areflexive) depends on the interpretation of $\geq$ and $\gt$ on the universe in question. The specification of the universe should not be only the set, but also the meaning of the relational and functional symbols like $\geq$. Only if there is some working convention can you simply assume that the meaning will be "the usual one".
{ "pile_set_name": "StackExchange" }
Q: Post data from angularjs client to WEBAPI controller I am new in angular js and webapi Problem: I can't post data using json url: "NewRoute/firstCall" from view to WebAPI controller but I can post using url: "http://localhost:2730/NewRoute/firstCall", who can I post data without http://localhost:2730 thing is I got two projects in one solution. 1.AngularJS 2.WebAPI In view part <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="Scripts/angular.js"></script> <script> var TestCtrl = function ($scope, $http) { $scope.SendData = function (Data) { var GetAll = new Object(); GetAll.txt1 = Data.txt1; $http({ url: "NewRoute/firstCall", //url: "http://localhost:2730/NewRoute/firstCall", dataType: 'json', method: 'POST', data: GetAll, headers: { "Content-Type": "application/json" } }).success(function (response) { $scope.value = response; }) .error(function (error) { alert(error); }); } }; var myApp = angular.module("myApp", []); myApp.controller("TestCtrl", TestCtrl); </script> </head> <body ng-app="myApp"> <div ng-controller="TestCtrl"> <hr /> <div> Enter text <input type="text" placeholder="Enter your name" ng-model="details.txt1"> </div> <hr /> <input type="button" ng-click="SendData(details)" value="Submit" /> <hr /> <h4 style="color:blueviolet">{{value}}</h4> </div> <hr /> </body> </html> In Web Api controller using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace WebApplication1.Controllers { [RoutePrefix("NewRoute")] public class NewController : ApiController { public class GetAll { public string txt1 { get; set; } } [Route("firstCall")] [HttpPost] public string firstCall(HttpRequestMessage request, [FromBody] GetAll getAll) { return "Success"; } } } WebApi provider using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace WebApplication1 { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } protected void Application_BeginRequest() { if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS") { Response.Flush(); } } } } Global.asax <?xml version="1.0" encoding="utf-8"?> <!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=301879 --> <configuration> <appSettings> <add key="webpages:Version" value="3.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings> <system.web> <compilation debug="true" targetFramework="4.5.1" /> <httpRuntime targetFramework="4.5.1" /> </system.web> <system.webServer> <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <remove name="OPTIONSVerbHandler" /> <remove name="TRACEVerbHandler" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Content-Type" /> <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" /> </customHeaders> </httpProtocol> </system.webServer> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration> A: It could be the relative url that's the problem, since it's working when you got a full url. Try this: $http({ url: "/NewRoute/firstCall", dataType: 'json', method: 'POST', data: GetAll, headers: { "Content-Type": "application/json" } }).success(function (response) { $scope.value = response; }) .error(function (error) { alert(error); }); Note the leading / before the url. This will cause the browser to make a request with the url currentdomain.org/NewRoute/firstCall
{ "pile_set_name": "StackExchange" }
Q: How to simulate, with FIXTURES, a slow REST backend? I am trying to simulate a slow backend in a test application using FIXTURES. I am doing the following: App.SlowIndexRoute = Ember.Route.extend({ model: function() { return new Ember.RSVP.Promise(function(resolve) { Ember.run.later(function() { resolve(App.Node.find()); }, 2000); }); } }); I was expecting that this would behave similarly to a slow REST backend, namely: The request is sent Route is activated, and the template is rendered Reply arrives from backend Now the data is updated in the template Instead, this is roughly what is happening, as far as I can tell: The request is sent No rendering of the template is performed, the route is not yet activated. Once the reply "arrives" (resolve(App.Node.find());) the route is activated The template is rendered, and since the data is already available, it is also displayed How can I more accurately simulate a slow REST backend? How can I make sure that the router is activating the view/template before the reply arrives? A: DS.FixtureAdapter has a latency property that defaults to 50 milliseconds. You can change this by instantiating the adapter manually when you create your store. App.Store = DS.Store.extend({ adapter: DS.FixtureAdapter.create({ latency: 1000 }); }); As of Ember 1.0.0-rc.6, it is expected behavior for a route to wait for the model's promise to resolve before transitioning. If you don't want the route to wait, don't return a promise (something with a then method) from your model hook. Return a regular object, one that's already loaded, or a proxy. Then load the model later, in your setupController hook, for example.
{ "pile_set_name": "StackExchange" }
Q: dynamically toggle class with javascript I'm having trouble figuring out how to toggle a class depending on the anchor text that is clicked. <div> <a id="Menu1" href="#">Menu</a> <div id="subMenu1" class="subLevel"> <p>stuff</p> </div> <div> <a id="Menu2" href="#">Menu</a> <div id="subMenu2" class="subLevel"> <p>stuff</p> </div> <div> <a id="Menu3" href="#">Menu</a> <div id="subMenu3" class="subLevel"> <p>stuff</p> </div> <script> $(document).ready(function () { $("#Menu" + [i]).on('click', function (e) { e.preventDefault(); $("#subMenu" + [i]).toggleClass('dropDownShow'); }); }); </script> Having trouble figuring out where var i changes from number 1 - 3 depenidng on anchor link that is clicked A: Here is one way to do it: <div> <a id="Menu1" class="menu" href="#">Menu</a> <div id="subMenu1" class="subLevel"> <p>stuff</p> </div> <div> <a id="Menu2" class="menu" href="#">Menu</a> <div id="subMenu2" class="subLevel"> <p>stuff</p> </div> <div> <a id="Menu3" class="menu" href="#">Menu</a> <div id="subMenu3" class="subLevel"> <p>stuff</p> </div> <script> $(document).ready(function () { $(".menu").on('click', function (e) { e.preventDefault(); $(this).next().toggleClass('dropDownShow'); }); }); </script>
{ "pile_set_name": "StackExchange" }
Q: Error: Cannot alter or drop column 'x' because it is enabled for Full-Text Search I'm refactoring an old database and removing columns no longer in use. The DB used to have full text indexing, so, some column are marked for full text. How can I remove them? Notes: DB is MS SQL Server Express 2008 Full text search service is no longer installed Edit: I have tried ALTER FULLTEXT INDEX ON tableName DROP (ColumnName) But gets this error: Full-text crawl manager has not been initialized. Any crawl started before the crawl manager was fully initialized will need to be restarted. Please restart SQL Server and retry the command. You should also check the error log to fix any failures that might have caused the crawl manager to fail. A: Found the solution myself: -- You should call the DISABLE command ALTER FULLTEXT INDEX ON TableName DISABLE ALTER FULLTEXT INDEX ON TableName DROP (ColumnName) ALTER TABLE TableName DROP COLUMN ColumnName A: I know this is an old post,I got stuck up,where i had to alter a column in table rather than drop.below code worked for me... EXEC sp_fulltext_column //Drop your column from full text search here @tabname = '<table_name>' , @colname = '<column_name>' , @action = 'drop' ALTER TABLE ... //Alter your column here EXEC sp_fulltext_column //Add your column back to full text search @tabname = '<table_name>' , @colname = '<column_name>' , @action = 'add'
{ "pile_set_name": "StackExchange" }
Q: Questions with ignored tags are a little too transparent The questions tagged with ignored tags have opacity: 0.2 in the stylesheet. I think this is a little too transparent. Stack Overflow and Meta Stack Overflow (the only two I checked) use opacity: 0.5. If the user doesn't choose to hide ignored questions completely, then he should be able to read them. For me, anything below about 0.35 looks too transparent. A: I have decreased the transparency slightly to 0.35. The change will be in the next deployment.
{ "pile_set_name": "StackExchange" }
Q: Is there a coding convention for a "line rule" for Java I like to organize my Java files a little and would like to know if there is a standard way of doing this. For example: public class Example { private int exampleInt; private String exampleString; /*------------------------------------------------------------*/ /* I N N E R C L A S S E S */ /*------------------------------------------------------------*/ private someInnerClass { someInnerClass() { } } /*------------------------------------------------------------*/ /** * This method returns the example int. */ public int getExampleInt() { return exampleInt; } } I don't what to call the part where I have a sort of comment break /-----------------------------------------------------------------/ Is there any sort of convention for this sort of thing? Or is this something that I should just not be doing because most IDE's will display everything nicely to you in some sort of outline view? A: The code explains itself. There is no need to put these ugly long comment lines in. If you really have to, then make them short, like so: // ------------- // Inner Classes // ------------- This is less messy. When I come across these kind of comments that state the obvious, I usually remove them right there and then. A: Refactoring and source cleanup may cause your source files to be reorganized, including comments. I would suggest you do not do that since that comment may end up somewhere completely unrelated. Another thing you may want to try instead is to use your IDE to reformat your source. Eclipse allows for doing that every time you save a file. This will give all your code a consistent look allowing for easier reading.
{ "pile_set_name": "StackExchange" }
Q: New to Heroku - "No such type as web" I'm trying to deploy my first app using Python/Flask on Heroku. I don't really know what I'm doing and am just following the tutorial at https://devcenter.heroku.com/articles/python#prerequisites. When I type the command heroku ps:scale web=1 I'm getting the error message "No such type as web". My Procfile says web: python scrabble_cheater.py, which I believe is correct. Here's the log of my terminal: (venv)jason-olsens-macbook-pro:scrabble paulnichols$ heroku status === Heroku Status Development: No known issues at this time. Production: No known issues at this time. (venv)jason-olsens-macbook-pro:scrabble paulnichols$ heroku config === enigmatic-mountain-1395 Config Vars LANG: en_US.UTF-8 LD_LIBRARY_PATH: /app/.heroku/vendor/lib LIBRARY_PATH: /app/.heroku/vendor/lib PATH: /app/.heroku/venv/bin:/bin:/usr/local/bin:/usr/bin PYTHONHASHSEED: random PYTHONHOME: /app/.heroku/venv/ PYTHONPATH: /app/ PYTHONUNBUFFERED: true (venv)jason-olsens-macbook-pro:scrabble paulnichols$ heroku ps (venv)jason-olsens-macbook-pro:scrabble paulnichols$ git push heroku master Warning: Permanently added the RSA host key for IP address '50.19.85.154' to the list of known hosts. Everything up-to-date (venv)jason-olsens-macbook-pro:scrabble paulnichols$ heroku ps:scale web=1 Scaling web processes... failed ! No such type as web (venv)jason-olsens-macbook-pro:scrabble paulnichols$ Any help is greatly appreciated! A: Procfile was saved with a .txt extension by mistake--once I removed the extension it worked.
{ "pile_set_name": "StackExchange" }
Q: Ensuring settings and mapping are set on index in Elasticsearch In order to ensure that my Elasticsearch index has the right settings and mapping I have the following code: if (client.admin().indices().prepareExists(Index).execute().actionGet().exists()) { client.admin().indices().prepareClose(Index).execute().actionGet(); client.admin().indices().prepareUpdateSettings(Index).setSettings(settings.string()).execute().actionGet(); client.admin().indices().prepareOpen(Index).execute().actionGet(); client.admin().indices().prepareDeleteMapping(Index).setType(Type).execute().actionGet(); client.admin().indices().preparePutMapping(Index).setType(Type).setSource(mapping).execute().actionGet(); } else { client.admin().indices().prepareCreate(Index).addMapping(Type, mapping).setSettings(settings).execute().actionGet(); } It seems a bit silly to update the settings and mapping even if they are already fine. I do not know how to do stuff in a more clever way though. Any suggestions? Thanks a lot, Stine A: You can retrieve current settings and mappings and make sure that they are correct before trying to update them. ClusterStateResponse response = client.admin().cluster().prepareState() .setFilterAll() .setFilterMetaData(false) .setFilterIndices(index) .execute().actionGet(); IndexMetaData indexMetaData = response.state().metaData().index(index); Settings settings = indexMetaData.settings(); // Verify settings MappingMetaData mapping = indexMetaData.mappings().get(type); // Verify mapping
{ "pile_set_name": "StackExchange" }
Q: In a complete metric space with no isolated points, any countable intersection of open dense sets is uncountable? I was playing with Baire's Theorem, and seemed to deduce the following: In a complete metric space $X$ that has no isolated points, any countable intersection of open dense sets is uncountable. Proof: Let $S$ be the countable intersection of open dense sets $\{U_n\}$. By Baire's Theorem $S$ is dense thus $U_n$ are open and dense. This implies that $U_n^c$ are nowhere dense. $$X = S\cup S^c = S\cup (\bigcap_n U_n)^c = S\cup \bigcup_n U_n^c.$$ If $S$ were countable, then $X = \bigcup_{s\in S}\{s\} \cup \bigcup_n U_n^c$. Since $X$ has no isolated points, every singleton set is closed and has empty interior, thus nowhere dense. We have just written $X$ has a countable union of nowhere dense sets. A contradiction to Baire's corollary. As a corollary, any connected complete metric space, such as $\mathbb{R}$, must be uncountable (this gives a topological proof that $\mathbb{R}$ is uncountable). Also $\mathbb{Q}$ is not the intersection of open dense sets of $\mathbb{R}$. I am a little bit suspicious about my proof, is it correct? A: It seems like a more obvious proof is to avoid the corollary and use the theorem directly: If $x$ is not an isolated point, then $X\setminus\{x\}$ is dense and open in $X$. If $S=\{s_1,s_2,\dots\}$ is countable, define $V_n=X\setminus \{s_n\}$, which are dense and open since $X$ has no isolated points. Then $\emptyset = \bigcap V_n\cap\bigcap U_n$ is the the countable intersection of dense open sets. This is essentially the dual of your proof.
{ "pile_set_name": "StackExchange" }
Q: Install OSX on NTFS? Want windows compatibility with file sizes > 4gb I have a macbook pro, and I'm putting a nice new 500gb ssd in it. I'm going to reformat and do a complete reinstallation. I would like a filesystem that Windows computers can read/write (not OSX Journaled, HFS, HFS+). I also want support for file-sizes over 4gb (rules out MS-DOS). There's one other option that I can use in the recovery, but I forgot what it was and I'm pretty sure it was incompatible with Windows. So is there a way to install OSX on a drive that uses say ExFat? Or will I simply have to sacrifice cross-compatibility and stick with HFS or HFS+ ? Edit: ExFat was the other option, which is totally compatible with Windows. I've learned that although it does overcome the hurdles of the 4gb block, a lot of Mac functionality is lost. Backups, encryption, and also less usable space. I'll stick to HFS. A: You could partition the hard drive and install format one partition as NTFS and the other partition as HFS. I multi-booted my MacBook with Windows XP and I used OSX's Disk Settings to create the partitions, then used the Windows CD to format that new partition as NTFS. If that doesn't do it, you can start with the Windows partition then install OSX on a second partition, although you wouldn't be able to use bootcamp. A: Don't use NTFS for your OSX installation. Both OSes need to be installed on SEPARATE partitions/volumes. Install OSX first. Partition how much space you feel you'll need for OSX, leaving enough space left over for Windows. Format the OSX partition as HFS, and do not create a Windows partition yet. Once you have OSX installed, run the Bootcamp Assistant. It will allow you to partition the drive properly for both OSes to live in peace and harmony. It will walk you through installing Windows from the media. During the Windows Install, select the partition that Bootcamp Assistant told you to choose, and let Windows install. Once you have Windows installed, insert your OSX DVD, and install the Bootcamp Drivers for Windows. Part of the driver package includes read support for HFS. This will let you read data on the OSX side. Install something such as NTFS-3G for OSX to read and write NTFS data. If you want one central place to keep your data, then set a small amount for both OSes - I set 100GB each for OSX and Windows 7. Then, the remainder of the hard drive is partitions as exFAT, using diskpart under Windows. Both OSes can mount it, and read/write data on them. It also gets past the 4GB limit, by allowing up to 128 PB for a single file, if necessary.
{ "pile_set_name": "StackExchange" }
Q: python - extract a specific key / value from json file by a variable a bit new to python and json. i have this json file: { "hosts": { "example1.lab.com" : ["mysql", "apache"], "example2.lab.com" : ["sqlite", "nmap"], "example3.lab.com" : ["vim", "bind9"] } } what i want to do is use the hostname variable and extract the values of each hostname. its a bit hard to explain but im using saltstack, which already iterates over hosts and i want it to be able to extract each host's values from the json file using the hostname variable. hope im understood. thanks o. A: You could do something along these lines: import json j='''{ "hosts": { "example1.lab.com" : ["mysql", "apache"], "example2.lab.com" : ["sqlite", "nmap"], "example3.lab.com" : ["vim", "bind9"] } }''' specific_key='example2' found=False for key,di in json.loads(j).iteritems(): # items on Py 3k for k,v in di.items(): if k.startswith(specific_key): found=True print k,v break if found: break Or, you could do: def pairs(args): for arg in args: if arg[0].startswith(specific_key): k,v=arg print k,v json.loads(j,object_pairs_hook=pairs) Either case, prints: example2.lab.com [u'sqlite', u'nmap']
{ "pile_set_name": "StackExchange" }
Q: Why didn't the gangster shoot Lou? In Nightcrawler, the injured gangster shoots down Rick when he comes in front of him, but when the same gangster comes out of the car, he sees Lou standing right in front of him, filming. Yet he does not do anything and limps away. Why didn't he shoot Lou? A: The way I've seen it is, As soon as the bad guy's car crashed, Lou took his camera and started filming and Lou observed that the bad guy is injured and gaining senses and recovering, he wanted to use this situation and kill his partner. So, he backed off and asked his partner to come shoot with steady hands and zoom. Unlucky for the partner, when he reached in front of the car, the bad guy recovered and not thinking straight and shot Rick, at this point, gangster would have shot Lou if he was there. But after shooting Rick, when he saw Lou standing there filming without a budge, the bad guy was surprised for Lou's audacity and few moments later Police arrived and the gangster's main concern is to deal with the police who shot the gangster's partner down. A: I don't think it has any proper explanation or motive. The answer could be opinion based. Suppose gangster didn't shoot Rick, then we could ask 'why didn't he shoot the damn camera-man who was filming his accident after having a gun?' So I can come up with my own thinking. There is 2 strong reason to shoot Rick and to leave Louis. Rick was in the path from where gangster got out of his car, Louis wasn't. He was in a bit distance. Secondly, there was police siren when gangster was in eye-contact with Louis. He could think that he needs to escape first. Trapped, injured man can think in a million ways. Let us think like a gangster. Lying injured in a car just after the accident- "What the f? Who's filming me? Ahh! dhish dhish(shots fired) die idiot die. Now let's get out. Oh no! another one!! Why isn't he running!! Siren! Police! Aw, I need to run...." Maybe I would do the same thing :) A: Here's my take on it. Right after watching the scene, three more reasons came to mind: The guy's actions suggest he's a hardened criminal and quite probably a murderous psychopath. When he sees the weak, indecisive intern is in his way, he takes him out. But when he sees Lou, who is increasingly terrifying throughout this movie, he recognizes a fellow psychopathic mind and chooses to let him be. Lou's defiant stance and stare also indicate that Lou is not afraid to die. So killing him would just be redundant, an empty gesture and a waste of bullets which the criminal desperately needs. The guy is injured, the car is totalled and the police is seconds away. He suspects he's about to go down, so he goes out in a blaze of glory - and wants his last moments to be documented.
{ "pile_set_name": "StackExchange" }
Q: How can I downgrade My Surface Pro 3 from Windows 10 enterprise to Pro (using the built-in key) I have a Surface Pro which had Windows 10 enterprise installed but has become deactivated due to no longer being around/associated the organizational infrastructure (KMS?). I want to just downgrade it to the built-in Windows 10 Pro that it came with. How can I do that? Bonus for doing it without wiping it. A: So this worked for my surface and for another laptop we are working with. We ran an administrator command prompt, then ran wmic path softwareLicensingService get OA3xOriginalProductKey This output my original Windows Key. Then We copied that key into the "Change your product key" option in Settings --> About Done
{ "pile_set_name": "StackExchange" }
Q: Transaction Controller Usage in Jmeter I know that transaction controller is uage to logically group multiple samplers and it generate a sampler of itself. However I have a question on script performance optimization. How advisable it is to use Transaction Controller if I have only Sampler in it? Does it impact the memory badly if I have 10s of those in the a thread group. Any link to best practice regarding the same will be appreciated. A: Each element has its cost. Transaction Controller's cost is relatively low, it's just generating a virtual SampleResult plus adding metrics from each and every child to this virtual sampleresult plus sending the signal to the Listeners (if any) There is no sense of having a Transaction Controller with only one child Sampler because it's response time, throughput, etc. will be absolutely the same as for its only child. I wouldn't say that the number of Transaction Controllers in the Test Plan matter, it's more about the number of Samplers which are under the Transaction Controller (a little bit higher memory consumption, a little bit lower throughput), however if you properly configure JMeter you won't see any visible impact. The only way to see the side-effect of having Transaction Controllers in the Test Plan is running your test with and without them under profiler tool telemetry
{ "pile_set_name": "StackExchange" }
Q: program has exited with code -1073610751 (0xc0020001) I'm getting a strange error on a SharpDX program I made. The program contains one form MainForm, which inherits from SharpDX.Windows.RenderForm (I'm doing Direct3D 9). I have some logic that kills the program by calling MainForm.Close(), and it works perfectly. However, when I close the form with the X button, or by double clicking the top left corner of the screen, the program ends with code -1073610751 (0xc0020001). This is a relatively minor annoyance, because it only happens when the program is finishing, so it doesn't really matter if it exits with an error, because it is actually finishing. However, this error does not happen when I set a breakpoint at the last line of my Main(). If I do so, and then close the window as I explained, the breakpoint gets hit, and resuming ends the program with code 0. Apart from SharpDX and one pure C DLL I am calling to one-shot process some data, I am not doing mixed code, or any other weird stuff. I've looked around, but this code appears to be related to string bindings? other people seem to have this problem when doing weird mixed C++/CLI stuff, but I'm not doing anything like that. Any ideas? at least on how to get more concise information on this error code? A: It is a very low-level RPC error. Which is likely to be used in your program, it is the underlying protocol on top of which COM runs. There are plenty of candidates, SharpDX itself uses the COM interop layer to make DirectX calls. And DirectX itself is very likely to make such kind of calls to your video driver. It is also the kind of error code you'd expect to get triggered if there's a shutdown-order problem. Like using a COM interface after it was already released. Shutting down a program cleanly can be a difficult problem to solve, especially when there are lots of threads. There are in any DirectX app. It is also very easy to ignore such a problem, even if it is known and recorded in somebody's bug database. Because, as you noted, the program otherwise shuts down okay without any nasty exceptions. RPC already prevented it from blowing up, you are seeing the error code it generated. There's very little you can do yourself about this problem, this is code you did not write and you'll never find the programmer who did. If you see a first-chance exception notification in the Output window then you could enable the unmanaged debugger, use Debug + Exceptions and tick the Thrown checkbox for Win32 exception, enable the Microsoft Symbol server and you'll get a stack trace when the exception is thrown. Beware this will be in the bowels of native code with no source to look at. But it could pin-point the DLL that's causing the problem. Still nothing you can do to fix that DLL. I'd recommend a video driver update, the most common source of trouble. That's about as far as you can take it.
{ "pile_set_name": "StackExchange" }
Q: WordPress Theme Installer > Need some advice I've got a pretty popular WordPress theme that has a template switcher (basically just changes the stylesheet assigned to the theme for a completely different look and stores this as setting in the db). The way I do this is that I have a "styles" directory under my theme folder and inside of that, I have a single folder for every one of my templates that work with the theme. Inside each of these folders is a stylesheet, along with any images the template needs. I'd like to create an uploader in my theme options panel that allows one to select a zip file from their PC and install a new template to the theme. Basically, I suppose I'm just looking for an upload routine that can take a zip file, extract it and place it in my theme's style folder. If there is already a folder by the same name, I'd like the routine to prompt for overwrite or rename. Any ideas? This appears to be the most promising thus far. I just need some tips on how to get this integrated with an file > uploader widget. // create object $zip = new ZipArchive() ; // open archive if ($zip->open(‘archive. zip’) !== TRUE) { die (‘Could not open archive’); } // extract contents to destination directory $zip->extractTo(‘/ tmp/extracted/ ‘); // close archive // print success message $zip->close(); echo ‘Archive extracted to directory’; A: Might be worth checking out the PHP filesystem functions: http://www.php.net/manual/en/ref.filesystem.php If you've tried with some code, I might be able to help some more.
{ "pile_set_name": "StackExchange" }
Q: What is "embedded affine variety" I am a junior learner of algebraic geometry. And I just roughly go through the following lecture: https://math.berkeley.edu/~brandtm/talks/sonberkeley.pdf In the first page, Definition 2. says: If $X$ is an embedded affine variety, then its projective closure $\bar{X}$ is the smallest projective variety containing $X$. So my first question is what is "embedded affine variety". So far I cannot find its definition in my algebraic geometry textbook and the internet. Moreover, I also read the following discussion: algebraic/geometric interpretation of the projective closure of an affine variety It seems that in the above definition, the "embedded" term is not necessary. (Please see the answer of this discussion, the article did not mention "embedded"). I am confused about these issues. Please advise, thanks! A: "Embedded affine variety" means an affine variety with a chosen embedding into some affine space $\Bbb A^n$. Since the embedding $\Bbb A^n\hookrightarrow\Bbb P^n=\operatorname{Proj} R[x_0,\cdots,x_n]$ given by identifying $\Bbb A^n$ and $D(x_0)$ gives you a map from any variety $X\subset \Bbb A^n$ into $\Bbb P^n$, you can then talk about the closure of it's image, which is what is meant by "the smallest variety containing $X$". It should be noted that in the discussion you link, the variety comes equipped with a chosen embedding - the data of $I\subset k[x_1,\cdots,x_n]$ determines how the variety is embedded. An embedding of a variety $X=\operatorname{Spec} k[X]$ is equivalent to a choice of generators for $k[X]$ as a $k$-algebra, and it is not immediately obvious that different choices should produce the same projective closures (for example, I'm not even sure that this is true - it could be an interesting question to think about for a little bit).
{ "pile_set_name": "StackExchange" }
Q: Derivation of Blattner's conjecture in the Beilinson-Bernstein picture On the last page of Schmid's article "Discrete Series", he says "In the Beilinson-Bernstein picture, discrete series modules are attached to closed $K$-orbits in $X$... the $K_{\mathbb R}$-structure of discrete series modules [i.e. Blattner's conjecture, which Schmid proved] is almost obvious from this point of view." I do indeed see how to prove Blattner's conjecture from this point of view, though there is enough battle with $\rho$-shifts that I didn't find it "almost obvious". (Added: I posted this proof on the arXiv.) Is there a place where Blattner's conjecture is derived in this algebraic setting of $(\mathfrak g,K)$-modules, rather than Schmid's original analytic setting? (I did write Schmid, though I suspect if he knew of such a reference he would have referenced it. Of course one may have come out in the intervening time, and if he has an answer I will include it here.) ADDED: Schmid's derivation sounded (on the phone) pretty isomorphic to mine, except where I write out a page (being an outsider to the field, and not clear on which parts are considered easy and which hard) he often puts just a sentence. Nothing wrong with that, of course, if you know your audience and know what will suffice for them. Anyway that doesn't answer my reference-request. A: "Geometric Methods in Representation Theory", by Gregg Zuckerman p.283, in 'Representation Theory of Reductive Groups' ed. Peter C Trombi, Progress in Math. 290 Birkhauser(1983) Procedings of University of Utah conference may have what you are looking for.
{ "pile_set_name": "StackExchange" }
Q: How to use Python and .NET/C# to automatise Princeton Instruments LightField I want to use Python to control a proprietary spectroscopic software (Princeton Instruments LightField). I have a LightField automation example using Matlab. The example use .NET to control LightField using provided DLLs. I used pythonnet to load the DLLs into Python, but I failed to communicate with LightField. Here is a (non-)working example : import sys sys.path.append(r"C:\Program Files\Princeton Instruments\LightField") sys.path.append(r"C:\Program Files\Princeton Instruments\LightField\AddInViews") import clr clr.AddReference('PrincetonInstruments.LightFieldViewV4') clr.AddReference('PrincetonInstruments.LightField.AutomationV4') clr.AddReference('PrincetonInstruments.LightFieldAddInSupportServices') import PrincetonInstruments.LightField.AddIns as AddIns from PrincetonInstruments.LightField.Automation import Automation instance = Automation(True,[]) And here is the error message : File "D:/python/test_lightfield.py", line 21, in <module> instance = Automation(True,[]) TypeError: no constructor matches given arguments However, when I look at the beginning of help(Automation) : help(Automation) Help on class Automation in module PrincetonInstruments.LightField.Automation: class Automation(System.Object) | Void .ctor(Boolean, System.Collections.Generic.List`1[System.String]) | | Method resolution order: | Automation | System.Object | builtins.object | | Methods defined here: | | __call__(self, /, *args, **kwargs) | Call self as a function. or the relevant Matlab example file : out.automation = PrincetonInstruments.LightField.Automation.Automation(visible,[]); It looks like I instantiated the Automation class with valid arguments (a boolean and an empty string). I don't have much documentation apart my Matlab sample file. What am I doing wrong ? EDIT : This was a problem of type. Using a .NET type list instead a Python list works. from PrincetonInstruments.LightField.Automation import Automation from System.Collections.Generic import List from System import * l = List[String]() instance = Automation(True,l) A: Check for supported constructor signatures in __overloads__, e.g.: >>> import clr >>> from System import Decimal >>> Decimal.__overloads__ System.Decimal(Int32[]) System.Decimal(UInt64) System.Decimal(UInt32) System.Decimal(Int64) System.Decimal(Int32) System.Decimal(Single) System.Decimal(Double) System.Decimal(Int32, Int32, Int32, Boolean, Byte) EDIT: Convert your second argument to .NET type (System.Collections.Generic.List[System.String]) before passing it. Auto-conversion of containers is not supported in pythonnet yet. EDIT: Here is how to do this: In C#: using System; using System.Collections.Generic; namespace ListInConstr { public class ListInConstr { public ListInConstr(bool test1, List<String> test2) { } } } Compile this into DLL: csc.exe /target:library ListInConstr.cs In Python: >>> import clr >>> import sys >>> sys.path.append(r"C:\Debug") >>> clr.AddReference("ListInConstr") <System.Reflection.RuntimeAssembly object at 0x02849E50> >>> from ListInConstr import ListInConstr >>> ListInConstr.__overloads__ ListInConstr.ListInContr(Boolean, System.Collections.Generic.List`1[System.String]) >>> from System.Collections.Generic import List >>> from System import String >>> arg2=List[String]() #do not add elements here >>> ListInConstr(True,arg2) <ListInConstr.ListInConstr object at 0x0284E890> >>>
{ "pile_set_name": "StackExchange" }
Q: Python: Evaluating a board position using stockfish from the python-chess library I am trying to create an engine but my evaluation function is terrible so I decided to use stockfish to evaluate it for me. import chess import chess.engine def stockfish_evaluation(board, time_limit = 0.01): engine = chess.engine.SimpleEngine.popen_uci("stockfish/stockfish_10_x64") result = engine.play(board, chess.engine.Limit(time=time_limit)) return result.info["score"] board = chess.Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1") result = stockfish_evaluation(board) print(result) but it prints out: KeyError: 'score' A: I think you are using the wrong function, it should be engine.analyse not engine.play import chess import chess.engine def stockfish_evaluation(board, time_limit = 0.01): engine = chess.engine.SimpleEngine.popen_uci("stockfish_10_x64") result = engine.analyse(board, chess.engine.Limit(time=time_limit)) return result['score'] board = chess.Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1") result = stockfish_evaluation(board) print(result) #+58
{ "pile_set_name": "StackExchange" }
Q: Is there Facebook search box component? I would like to use exactly same search box in my app, (to search ppl and saw her profile picture). Is there any good example how to do it? A: do you mean something like... http://www.9lessons.info/2009/06/autosuggestion-with-jquery-ajax-and-php.html This guy has a lot of facebook examples.
{ "pile_set_name": "StackExchange" }
Q: Fluent Mapping - CsvHelper I'm using the CsvHelper library built by Josh Close. I thought the datasource where I'll be obtaining the .csv files had a way to mask or 'alias' the column headers with proper naming convention. Unfortunately that's not going to be the case so I'd like to use the Fluent Class Mapping but I'm unclear as to how to implement it. I built the below class(simplified for this post) public class PaymentType { public int PaymentTypeId { get; set; } public string BusinessUnit { get; set; } public string Region { get; set; } public string Status { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public decimal Amount { get; set; } public string Name { get; set; } } The below method in another class downloads and saves the file private string DownloadDS(string getURL, string fileName) { try { //CSV path string url = getURL; //Where to save and retrieve CSV file string path = AppDomain.CurrentDomain.BaseDirectory + "ImportedFiles\\" + fileName; //Download file and save it WebClient client = new WebClient(); client.DownloadFile(url, path); return path; } catch { return ""; } } This method then updates the db private void UpdateDB(string path, string fileName) { try { //read in file with CsvReader object and output to an enumerable object var csv = new CsvReader(new StreamReader(path)); var importedPaymentTypes = csv.GetRecords<ImportPaymentTypes>(); //Save each payment type record to the db. If record exhsists, update it, if not, add it. ... } catch { ... } } I stripped out some of the logging and db logic to shorten the code snippets. I read up on the Fluent Mapping but I'm confused on how to implement it? I understand that I have to build a class, but how do you reference/configure the use of the mapper class? Here's an example from Josh's site; http://joshclose.github.io/CsvHelper/#reading-reading-all-records A: Take a look at the mapping section. http://joshclose.github.io/CsvHelper/#mapping You register the mapping by doing: csv.Configuration.RegisterClassMap<PaymentTypeMap>();
{ "pile_set_name": "StackExchange" }
Q: Preventing thread from duplicate processing in java Problem statement I have a JMS listener running as a thread listening to a topic. As soon a message comes in, I spawn a new Thread to process the in-bounded message. So for each incoming message I spawn a new Thread. I have a scenario where duplicate message is also being processed when it is injected immediately in a sequential order. I need to prevent this from being processed. I tried using a ConcurrentHashMap to hold the process times where I add in the entry as soon as Thread is spawn and remove it from the map as soon Thread completes its execution. But it did not help when I tried with the scenario where I passed in same one after the another in concurrent fashion. General Outline of my issue before you plunge into the actual code base onMessage(){ processIncomingMessage(){ ExecutorService executorService = Executors.newFixedThreadPool(1000); //Map is used to make an entry before i spawn a new thread to process incoming message //Map contains "Key as the incoming message" and "value as boolean" //check map for duplicate check //The below check is failing and allowing duplicate messages to be processed in parallel if(entryisPresentInMap){ //return doing nothing }else{ //spawn a new thread for each incoming message //also ensure a duplicate message being processed when it in process by an active thread executorService.execute(new Runnable() { @Override public void run() { try { //actuall business logic }finally{ //remove entry from the map so after processing is done with the message } } } } Standalone example to mimic the scenario public class DuplicateCheck { private static Map<String,Boolean> duplicateCheckMap = new ConcurrentHashMap<String,Boolean>(1000); private static String name=null; private static String[] nameArray = new String[20]; public static void processMessage(String message){ System.out.println("Processed message =" +message); } public static void main(String args[]){ nameArray[0] = "Peter"; nameArray[1] = "Peter"; nameArray[2] = "Adam"; for(int i=0;i<=nameArray.length;i++){ name=nameArray[i]; if(duplicateCheckMap.get(name)!=null && duplicateCheckMap.get(name)){ System.out.println("Thread detected for processing your name ="+name); return; } addNameIntoMap(name); new Thread(new Runnable() { @Override public void run() { try { processMessage(name); } catch (Exception e) { System.out.println(e.getMessage()); } finally { freeNameFromMap(name); } } }).start(); } } private static synchronized void addNameIntoMap(String name) { if (name != null) { duplicateCheckMap.put(name, true); System.out.println("Thread processing the "+name+" is added to the status map"); } } private static synchronized void freeNameFromMap(String name) { if (name != null) { duplicateCheckMap.remove(name); System.out.println("Thread processing the "+name+" is released from the status map"); } } Snippet of the code is below public void processControlMessage(final Message message) { RDPWorkflowControlMessage rdpWorkflowControlMessage= unmarshallControlMessage(message); final String workflowName = rdpWorkflowControlMessage.getWorkflowName(); final String controlMessageEvent=rdpWorkflowControlMessage.getControlMessage().value(); if(controlMessageStateMap.get(workflowName)!=null && controlMessageStateMap.get(workflowName)){ log.info("Cache cleanup for the workflow :"+workflowName+" is already in progress"); return; }else { log.info("doing nothing"); } Semaphore controlMessageLock = new Semaphore(1); try{ controlMessageLock.acquire(); synchronized(this){ new Thread(new Runnable(){ @Override public void run() { try { lock.lock(); log.info("Processing Workflow Control Message for the workflow :"+workflowName); if (message instanceof TextMessage) { if ("REFRESH".equalsIgnoreCase(controlMessageEvent)) { clearControlMessageBuffer(); enableControlMessageStatus(workflowName); List<String> matchingValues=new ArrayList<String>(); matchingValues.add(workflowName); ConcreteSetDAO tasksSetDAO=taskEventListener.getConcreteSetDAO(); ConcreteSetDAO workflowSetDAO=workflowEventListener.getConcreteSetDAO(); tasksSetDAO.deleteMatchingRecords(matchingValues); workflowSetDAO.deleteMatchingRecords(matchingValues); fetchNewWorkflowItems(); addShutdownHook(workflowName); } } } catch (Exception e) { log.error("Error extracting item of type RDPWorkflowControlMessage from message " + message); } finally { disableControlMessageStatus(workflowName); lock.unlock(); } } }).start(); } } catch (InterruptedException ie) { log.info("Interrupted Exception during control message lock acquisition"+ie); }finally{ controlMessageLock.release(); } } private void addShutdownHook(final String workflowName) { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { disableControlMessageStatus(workflowName); } }); log.info("Shut Down Hook Attached for the thread processing the workflow :"+workflowName); } private RDPWorkflowControlMessage unmarshallControlMessage(Message message) { RDPWorkflowControlMessage rdpWorkflowControlMessage = null; try { TextMessage textMessage = (TextMessage) message; rdpWorkflowControlMessage = marshaller.unmarshalItem(textMessage.getText(), RDPWorkflowControlMessage.class); } catch (Exception e) { log.error("Error extracting item of type RDPWorkflowTask from message " + message); } return rdpWorkflowControlMessage; } private void fetchNewWorkflowItems() { initSSL(); List<RDPWorkflowTask> allTasks=initAllTasks(); taskEventListener.addRDPWorkflowTasks(allTasks); workflowEventListener.updateWorkflowStatus(allTasks); } private void clearControlMessageBuffer() { taskEventListener.getRecordsForUpdate().clear(); workflowEventListener.getRecordsForUpdate().clear(); } private synchronized void enableControlMessageStatus(String workflowName) { if (workflowName != null) { controlMessageStateMap.put(workflowName, true); log.info("Thread processing the "+workflowName+" is added to the status map"); } } private synchronized void disableControlMessageStatus(String workflowName) { if (workflowName != null) { controlMessageStateMap.remove(workflowName); log.info("Thread processing the "+workflowName+" is released from the status map"); } } I have modified my code to incorporate suggestions provided below but still it is not working public void processControlMessage(final Message message) { ExecutorService executorService = Executors.newFixedThreadPool(1000); try{ lock.lock(); RDPWorkflowControlMessage rdpWorkflowControlMessage= unmarshallControlMessage(message); final String workflowName = rdpWorkflowControlMessage.getWorkflowName(); final String controlMessageEvent=rdpWorkflowControlMessage.getControlMessage().value(); if(controlMessageStateMap.get(workflowName)!=null && controlMessageStateMap.get(workflowName)){ log.info("Cache cleanup for the workflow :"+workflowName+" is already in progress"); return; }else { log.info("doing nothing"); } enableControlMessageStatus(workflowName); executorService.execute(new Runnable() { @Override public void run() { try { //actual code fetchNewWorkflowItems(); addShutdownHook(workflowName); } } } catch (Exception e) { log.error("Error extracting item of type RDPWorkflowControlMessage from message " + message); } finally { disableControlMessageStatus(workflowName); } } }); } finally { executorService.shutdown(); lock.unlock(); } } private void addShutdownHook(final String workflowName) { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { disableControlMessageStatus(workflowName); } }); log.info("Shut Down Hook Attached for the thread processing the workflow :"+workflowName); } private synchronized void enableControlMessageStatus(String workflowName) { if (workflowName != null) { controlMessageStateMap.put(workflowName, true); log.info("Thread processing the "+workflowName+" is added to the status map"); } } private synchronized void disableControlMessageStatus(String workflowName) { if (workflowName != null) { controlMessageStateMap.remove(workflowName); log.info("Thread processing the "+workflowName+" is released from the status map"); } } A: The issue is fixed now. Many thanks to @awsome for the approach. It is avoiding the duplicates when a thread is already processing the incoming duplicate message. If no thread is processing then it gets picked up public void processControlMessage(final Message message) { try { lock.lock(); RDPWorkflowControlMessage rdpWorkflowControlMessage = unmarshallControlMessage(message); final String workflowName = rdpWorkflowControlMessage.getWorkflowName(); final String controlMessageEvent = rdpWorkflowControlMessage.getControlMessage().value(); new Thread(new Runnable() { @Override public void run() { try { if (message instanceof TextMessage) { if ("REFRESH".equalsIgnoreCase(controlMessageEvent)) { if (tryAddingWorkflowNameInStatusMap(workflowName)) { log.info("Processing Workflow Control Message for the workflow :"+ workflowName); addShutdownHook(workflowName); clearControlMessageBuffer(); List<String> matchingValues = new ArrayList<String>(); matchingValues.add(workflowName); ConcreteSetDAO tasksSetDAO = taskEventListener.getConcreteSetDAO(); ConcreteSetDAO workflowSetDAO = workflowEventListener.getConcreteSetDAO(); tasksSetDAO.deleteMatchingRecords(matchingValues); workflowSetDAO.deleteMatchingRecords(matchingValues); List<RDPWorkflowTask> allTasks=fetchNewWorkflowItems(workflowName); updateTasksAndWorkflowSet(allTasks); removeWorkflowNameFromProcessingMap(workflowName); } else { log.info("Cache clean up is already in progress for the workflow ="+ workflowName); return; } } } } catch (Exception e) { log.error("Error extracting item of type RDPWorkflowControlMessage from message " + message); } } }).start(); } finally { lock.unlock(); } } private boolean tryAddingWorkflowNameInStatusMap(final String workflowName) { if(controlMessageStateMap.get(workflowName)==null){ synchronized (this) { if(controlMessageStateMap.get(workflowName)==null){ log.info("Adding an entry in to the map for the workflow ="+workflowName); controlMessageStateMap.put(workflowName, true); return true; } } } return false; } private synchronized void removeWorkflowNameFromProcessingMap(String workflowName) { if (workflowName != null && (controlMessageStateMap.get(workflowName) != null && controlMessageStateMap .get(workflowName))) { controlMessageStateMap.remove(workflowName); log.info("Thread processing the " + workflowName+ " is released from the status map"); } }
{ "pile_set_name": "StackExchange" }
Q: How can I call images into the DOM without querying the server? Given a number of images (animation frames) I would like to prefetch them and then show them on a webpage as needed. I have tried several ways of prefetching, including a nifty plugin, but here's a dead simple method: <div class="animation-container"></div> <div class="holding-container" style="display:none"></div> <script> $('.holding-container').append('<img src="Image1.png" />'); $('.holding-container').append('<img src="Image2.png" />'); </script> In the Network tab of Firebug or developer tools, I see these calls result in queries to the server, and the images are fetched successfully. Now, I want to actually use the images. Here's some very simplified code: $('.animation-container').prepend('<img src="Image1.png"/>'); This is where things go off the rails. The network tabs show the browsers query the server again (receiving 304 NOT MODIFIED). This results in about a 200ms delay before the image is shown. Why does this happen and what can I do about it? A: You are creating a new DOM object instead of re-using the one that was pre-fetched. Add an id to each image to uniquely identify it - <div class="animation-container"></div> <div class="holding-container" style="display:none"></div> <script> $('.holding-container').append('<img src="Image1.png" id="img1" />'); $('.holding-container').append('<img src="Image2.png" id="img2" />'); </script> And then to grab the element using a selector, detach() it (like remove() but keeps the info, you can omit this if you you want to keep it in your holding container), and prependTo() it to your container: $('.holding-container #img1').detach().prependTo('.animation-container');
{ "pile_set_name": "StackExchange" }
Q: Who's the artist that drew the art on pages 148 and 220 of the PHB? Anyone know the name of the artist or artists that drew the art on page 148 and 220 in the Player's Handbook? I know there's a list of artists in the credits, but looking through it, I haven't been able to find that art specifically on any of their online portfolios. Also, does anyone know if there exist uncropped versions of said art, and where you might find them? A: The art on page 148 is "Shield bash" by John Stanko. The art on page 220 is "Burning Hands", also by John Stanko.
{ "pile_set_name": "StackExchange" }
Q: Is there a reliable online backup service? We currently have multiple remote servers backing up about 50GB of total data to Mozy Pro. unfortunately, we have had issues with Mozy not connecting or having a daily email alert generated. Are there any truly reliable online backup services out there? What might be great for personal use might not cut it here. Edit: Reliable meaning that the automated backup will run without fail on a nightly basis, and the automated reporting will function without fail. These are 2 things our existing service is not quite accomplishing. A: I use rsync.net, works like a charm with Mac book and Ubuntu. A: I have not used this myself, but I have been meaning to try after hearing good things about it from other co-workers. http://www4.crashplan.com/landing/index.html
{ "pile_set_name": "StackExchange" }
Q: How would I do a detailed walk-through of a factorial? def factorial(x): if x == 0: return 1 else: return x * factorial(x - 1) print(factorial(3)) How would I do a detailed walk-through with information on the stack at every call and show the data at every return? I know I have to draw 3 boxes to show what happens at every call, and the data at every return; I just don't know how the function actually works, and how to implement it. This does not require any coding, but an explanation? ***** Update **** So something like this? N = 3 4 * factorial (3): 24 N = 2 5 * factorial (4): 120 // and so on.... A: You can try to add some print lines to know what's happening inside a function call. Such as the following: def factorial(x): print("factorial({}) is called".format(x)) if x == 0: print("Reached base branch") return 1 else: print("Reached recursive branch") result = x * factorial(x - 1) print("Exitted recursive branch") return result print(factorial(3)) This should let you see how the call to factorial(3) eventually calls factorial(2), factorial(1), and factorial(0) and then goes up the recursive hierarchy when the based case is reached.
{ "pile_set_name": "StackExchange" }
Q: upload image files from IOS to web server What is the best way to upload image files to web server in java considering IOS9 and swift 2. Upon searching, I realised that similar question was asked and many different methods are available online to upload images. However I am not sure on what is the best method to follow. I tried the following approaches and noticed that it takes about a minute to upload an image. ****Approach 1:**** Using NSURLSession and invoking “POST” method of the java servlet Send as JSON as stated in this example Append image to httpbody itself as stated in this example ****Approach 2:**** Using NSURL and invoking a javascript method as in this example I also read about AFNetworking 2.0 (ex) and I am not sure if it can bring any performance increase to the uploading process. Our users might take around 100 of pictures everyday and the images needs to be uploaded to web server for further processing. Please review and suggest your views. Many thanks. A: Create base64 String out of your image and send it to web server. let imageData = UIImageJPEGRepresentation(imageURL.image!, 0.5) let base64String = imageData!.base64EncodedStringWithOptions([]) In your web server, read the input image string and parse it as follows. byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image); Then you can do whatever you like with the bytes like: BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));
{ "pile_set_name": "StackExchange" }
Q: adb: Find PID from the adb shell I am trying to get the PID of the process INSIDE adb shell. So, I am doing adb shell which gets me to the android shell. Now, if I were to get the PID using a regular shell I would use adb shell ps | grep android.process.acore | sed 's/\s\s*/ /g' | cut -d ' ' -f 2 OR adb shell ps | grep android.process.acore | awk '{ print $2 }' I get the PID (a numeric number - 2nd field of the ps | grep android.process.acore) output. However, if I run the above commands inside android shell(after doing adb shell), I get /system/bin/sh: sed: not found and /system/bin/sh: awk: not found errors respectively. Which means, these commands are not available inside adb shell. However, grep works. The output of the ps | grep android.process.acore inside adb shell is: XXX_x21 11826 441 502296 39028 ffffffff 4010ff6c S android.process.acore I am looking for the number 11826. How can I extract it inside adb shell? Also, please help if there is a direct way to get the PID inside the adb shell. Regards, Rumit A: Not sure if you can get the PID directly however you can try the following set `ps |grep android.process.acore` echo $2 This has the affect of setting the output of the ps command into variables $1, $2, $3 etc. The PID value is in $2 A: Android versions starting with 6.0 already include pidof utility: usage: pidof [-s] [-o omitpid[,omitpid...]] [NAME]... Print the PIDs of all processes with the given names. -s single shot, only return one pid. -o omit PID(s)
{ "pile_set_name": "StackExchange" }
Q: How to resize QML TableView column to its contents on app start? I am using Qt 5.9.4 on Ubuntu 18.04. When my application starts, I want to automatically adjust TableView's column size to its contents. A model have some data on start. I know about the resizeColumnToContents function, but I have no idea where to call it. onDataChange does not work in TableView: The QML engine says that this signal does not exist. But intellitype allows me to type it in the code. How to accomplish that? A: EDIT 18/09/18 If you use a StackView or else you can preload your TableView // main.qml Loader { id: tableViewLoader active: true sourceComponent: TableView { id: tableView } } StackView { id: stackView initialItem: listViewLoader function onContentReceived() { stackView.push(tableViewLoader); tableViewLoader.item.resizeColumnsToContents() } function onContentClosed() { swipeView.pop() } } EDIT 17/09/18 You are right Danil. There is specified in TableView.qml that Depending on how the model is populated, the model may not be ready when TableView Component.onCompleted is called. In that case you may need to delay the call to positionViewAtRow by using a \l {QtQml::Timer}{Timer} For me this is working Component.onCompleted: resizeColumnsToContentsTimer.start() Timer { id: resizeColumnsToContentsTimer interval: 50 running: false repeat: false onTriggered: parent.resizeColumnsToContents() } You can also see this discussion about it http://lists.qt-project.org/pipermail/interest/2016-June/023018.html Maybe, you can call it in onModelChanged which called when you set your model (your model must be populated before). onModelChanged: tableView.resizeColumnToContents() Otherwise, you can use signals/slots when your data ready. But beware with this function : if you have delegate you must specify implicitWidth in, or this is will not to work. headerDelegate: Rectangle { id: headerDelegate height: 36 implicitWidth: textItem.implicitWidth + textItem.padding * 2 color: Style.lightColor Text { id: textItem anchors.fill: parent verticalAlignment: Text.AlignVCenter horizontalAlignment: Text.AlignLeft padding: 10 text: styleData.value elide: Text.ElideRight color: Style.darkColor font.pixelSize: Style.bigFontPixelSize } }
{ "pile_set_name": "StackExchange" }
Q: program with recursive function I'm pretty stumped on this recursive function. I'm using it to highlight words in a text box, but it's giving me some strange output: should be: #define testing #define but instead it's: testing #define testing #define here's the code function replace_all( text, old_str, new_str ){ index_of = text.indexOf( old_str ); if( index_of != -1 ){ old_text = text.substring( 0, index_of ); new_text = text.substring( index_of + old_str.length ); new_text = replace_all( new_text, old_str, new_str ); text = old_text + new_str + new_text; } return text; } Any ideas on what's wrong with the function? It seems to be replacing all the old keywords with the last one found. A: You need to at least declare all your variables in the function as local variables by adding var in front of their first use. function replace_all( text, old_str, new_str ){ var index_of = text.indexOf( old_str ); if( index_of != -1 ){ var old_text = text.substring( 0, index_of ); var new_text = text.substring( index_of + old_str.length ); new_text = replace_all( new_text, old_str, new_str ); text = old_text + new_str + new_text; } return text; } By not using var, your variables are global and each invocation of replace_all will be sharing the same copies of variables which will mess up the recursion as recursive calls will mess up the state of the higher levels calls. If the variables are all local variables, then each function invocation has it's own set of variables and one recursive call does not mess up the others. Plus, it is generally always a good idea to limit the scope of your variables to as local a scope as practical and avoid globals whenever possible. Implicit globals variables like you have here are particular evil because they can easily lead to accidental misuse. As Kolink suggested, you might just want to do a single global .replace() operation using a regex search/replace. You would need to make sure that any regex special characters in the search string were properly escaped though.
{ "pile_set_name": "StackExchange" }
Q: How to use a textbox to input multiple HEX values into an array in c# I'm trying to use a textbox control so the user can input Hex values into it, press enter and it is stored in an array. Then enter another hex value press enter and it is stored in the array. I'm new to programming, so maybe there is a more suitable control than textbox to do this? This is the code I've come up with so far, I'm not sure how you would clear the textbox when the user presses enter though, maybe there is something more suitable to input the values? Any help would be appreciated! private void Test_TextChanged(object sender, EventArgs e) { string hexString = Test.Text; int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber); int[] arr = new int[20]; for (uint i = 0; i < 5; i++) { arr[i] = num; ReadValue.Text = num.ToString(); } } A: You can use the NumericUpDown control and set its Hexadecimal property to true. Than you can use his KeyDown event private List<int> hexValues = new List<int>(); private void numericUpDown1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { hexValues.Add(Convert.ToInt32(numericUpDown1.Value)); // Reset the value. numericUpDown1.Value = Decimal.Zero; } } Then if you need the array: int[] hexValuesArray = hexValues.ToArray();
{ "pile_set_name": "StackExchange" }
Q: Can't redirect to URI I have this URI I want to redirect to: redirect('search_results/result/$id'); I get this error: The URI you submitted has disallowed characters. Do you have any idea how I can fix this? A: If you want use variable within string use double quotation instead of single quotation. redirect("search_results/result/$id");
{ "pile_set_name": "StackExchange" }
Q: Changing schema using a stored procedure with FOR XML AUTO, ELEMENT Right now I'm getting schema in XML format like this <Header> <data1> </data1> <Line> <data> </data> <VLine> <data> </data> <LUI></LUI> </Vline> </Line> </Header> By using following stored procedure Select * from EDI834_5010_Header Header join EDI834_5010_2000 Line on Header.BGN02__TransactionSetIdentifierCode = Line.Id_BGN02__TransactionSetIdentifierCode left join EDI834_5010_2300_DTPLoop VLine on Line.REF02_MemberSupplementalIdentifier = VLine.Id_REF02__SubscriberIdentifier and Header.BGN02__TransactionSetIdentifierCode = VLine.Id_BGN02__TransactionSetIdentifierCode left join EDI834_5010_2300_LUILoop LUI on LUI.Id_BGN02__TransactionSetIdentifierCode=Header.BGN02__TransactionSetIdentifierCode and LUI.Id_REF02__SubscriberIdentifier=Line.REF02_MemberSupplementalIdentifier for xml auto,ELEMENTS END But I need to get the schema like this in xml <Header> <data1> </data1> <Line> <data> </data> <VLine> <data> </data> </Vline> <LUI> <data> </data> </LUI> </Line> </Header> How should I change my above stored procedure to get the schema like this? A: Try this, not tested by me so there may be any number of typos in there. select *, (select * from EDI834_5010_2300_DTPLoop VLine where Line.REF02_MemberSupplementalIdentifier = VLine.Id_REF02__SubscriberIdentifier and Header.BGN02__TransactionSetIdentifierCode = VLine.Id_BGN02__TransactionSetIdentifierCode for xml auto, elements, type), (select * from EDI834_5010_2300_LUILoop LUI where LUI.Id_BGN02__TransactionSetIdentifierCode=Header.BGN02__TransactionSetIdentifierCode and LUI.Id_REF02__SubscriberIdentifier=Line.REF02_MemberSupplementalIdentifier for xml auto, elements, type) from EDI834_5010_Header Header join EDI834_5010_2000 Line on Header.BGN02__TransactionSetIdentifierCode = Line.Id_BGN02__TransactionSetIdentifierCode for xml auto, elements Used this to test if the sub-queries work and it looks like they do. declare @t1 table (id int) declare @t2 table (id int) declare @t3 table (id int) insert into @t1 values (1),(2) insert into @t2 values (1),(2) insert into @t3 values (1),(2) select *, (select * from @t2 as t2 where t1.id = t2.id for xml auto, elements, type), (select * from @t3 as t3 where t1.id = t3.id for xml auto, elements, type) from @t1 as t1 for xml auto, elements Result: <t1> <id>1</id> <t2> <id>1</id> </t2> <t3> <id>1</id> </t3> </t1> <t1> <id>2</id> <t2> <id>2</id> </t2> <t3> <id>2</id> </t3> </t1>
{ "pile_set_name": "StackExchange" }
Q: Proving that an infinite set is uncountable. I've been doing some practice questions for my course and I found the following question quite difficult to understand. Prove that the following set is uncountable $B_\infty = \{ s \in B : s \text{ is an infinite binary sequence}\}$ To my knowledge, for a set to be countable it must be onto or one-to-one. Thus, I think to prove something to be uncountable, we can either prove that the set is not onto or one-to-one. Any help or hints are greatly appreciated! Thank you for your time. A: Proceed by contradiction. Let's say you can somehow map every binary sequence to a natural number. Can you construct a binary sequence that wasn't mapped? Lost's hint in the comments on Cantor's diagonalization argument is needed. Also, you should know that for a set to be (infinitely) countable, that means there exists an injection(one-to-one) from the set to the natural numbers.
{ "pile_set_name": "StackExchange" }
Q: Understanding Sign extension int main() { unsigned int b; signed int a; char z=-1; b=z; a=z; printf("%d %d",a,b); } gives -1 -1. why does no sign extension occur, ALSO, when does it occur? A: Sign extension DID occur, but you are printing the results incorrectly. In your printf you specified %d for b, but b is unsigned, you should have used %u to print b. printf does not know the type of its arguments and uses the format specifies to interpret them. printf("%d %u",a,b); A: Because printf looks at the raw memory, not the type. use %u to print the value as unsigned. See. http://ideone.com/Qpcbg
{ "pile_set_name": "StackExchange" }
Q: Is the camouflage texture of certain wildlife lens covers relevant? Camouflage texture on wildlife lens covers seem pretty popular. I get that the covers can be great to protect the lens from dents and scratches as well as to protect the hands of thephotographer from a cold barrel. However I'm not convinced that it helps at all in camouflaging the lens so that the photographer is less likely to be noticed by animals. In my very limited experience in wildlife photography, the animals don't seem to care about the lens barrel itself. They rather seem to react to reflections from the front element and general movement. Is there any benefit at all of having the camouflage texture or is this just a marketing trick taking advantage of the gulliblity among certain people that are attracted to anything that allude to military stuff. Looking for answers on the Internet seem to indicate (but not entirely conclusively) that the camouflage is rather useless: [1], [2], [3]. If you can I'd be happy if you provide a good source if you know the answer. A: Movement, scent, noise and shape are more likely to effect an animal's behaviour than the pattern of the camouflage used on a lens. However the pattern may help in that it breaks up the shape of the outline of the lens, which is alien to the animal's habitat and will most likely be seen a trap. As many animals are colour blind, the colour may not effect them, but if it looks obviously manmade to them, they will behave cautiously around it. Also, the placement of the animal's eyes can effect how the lens is viewed. For example, a bird with the eyes located at the sides of it's head, will possibly notice the circular pattern of the front element of the lens when facing to the side (in front of the camera's position) rather than facing towards the lens. The material used on the lens cover can also reflect infra red or ultra violet light, which would be invisible to us, but may also be seen by certain animals or birds.
{ "pile_set_name": "StackExchange" }
Q: Jekyll website not setting favicon First time working with Jekyll. I'm working localhost and trying to set a favicon to the website. I did generate the image.ico and put the code generated on my head.html file. It generates the image on my _site folder but it does not show on the tab icon. What am I doing wrong? I generated the favicon on: https://www.favicon-generator.org that told me to use this on my file: <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"> <link rel="icon" href="/favicon.ico" type="image/x-icon"> So I did on my head.html file and the image is on my root folder: <head> <title>{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %}</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="description" content="" /> <meta name="keywords" content="" /> <!--[if lte IE 8]><script src="js/html5shiv.js"></script><![endif]--> <script src="{{ site.baseurl }}/js/jquery.min.js"></script> <script src="{{ site.baseurl }}/js/skel.min.js"></script> <script src="{{ site.baseurl }}/js/skel-layers.min.js"></script> <script src="{{ site.baseurl }}/js/init.js"></script> <noscript> <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"> <link rel="icon" href="/favicon.ico" type="image/x-icon"> <link rel="stylesheet" href="{{ site.baseurl }}/css/skel.css" /> <link rel="stylesheet" href="{{ site.baseurl }}/css/style.css" /> <link rel="stylesheet" href="{{ site.baseurl }}/css/style-xlarge.css" /> </noscript> </head> I don't know if this is really necessary but just in case, this is my header.html file: <!-- Header --> <header id="header" class="skel-layers-fixed"> <h1><a href="{{ site.baseurl }}/" class="site-title" ><img class="image full" style="width: 35%; height: 85%; margin-top: 2px; margin-bottom: 5px; " src="images/logo.png"/></a></h1> <nav id="nav"> <ul> <li><a href="{{ site.baseurl }}/">Home</a></li> <li><a href="{{ site.baseurl }}/team.html">Item 1</a></li> <li><a href="{{ site.baseurl }}/amitis.html">Item 2</a></li> <li><a href="{{ site.baseurl }}/enactusTogether.html">Item 3</a></li> <li><a href="{{ site.baseurl }}/awards.html">Item 4</a></li> <!-- <li><a href="{{ site.baseurl }}/blog.html">Blog</a></li> --> {% for page in site.pages %} {% if page.title %} <li><a class="page-link" href="{{ page.url | prepend: site.baseurl }}">{{ page.title }}</a></li> {% endif %} {% endfor %} <!-- <li><a href="#" class="button special">Sign Up</a></li> --> </ul> </nav> </header> Is that right? Should I put the favicon code in somewhere else? Update: I did what you guys told me to do but it is still not working. <head> <title>{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %}</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="description" content="" /> <meta name="keywords" content="" /> <link rel="shortcut icon" href="{{ site.baseurl }}/favicon.ico" type="image/x-icon" /> <link rel="icon" href="{{ site.baseurl }}/favicon.ico" type="image/x-icon" /> <!--[if lte IE 8]><script src="js/html5shiv.js"></script><![endif]--> <script src="{{ site.baseurl }}/js/jquery.min.js"></script> <script src="{{ site.baseurl }}/js/skel.min.js"></script> <script src="{{ site.baseurl }}/js/skel-layers.min.js"></script> <script src="{{ site.baseurl }}/js/init.js"></script> <noscript> <link rel="stylesheet" href="{{ site.baseurl }}/css/skel.css" /> <link rel="stylesheet" href="{{ site.baseurl }}/css/style.css" /> <link rel="stylesheet" href="{{ site.baseurl }}/css/style-xlarge.css" /> </noscript> </head> It was like this? It's inside the head tag, outside the no script tag and using href="{{ site.baseurl }}/favicon.ico" A: Should put your icon code outside the <noscript> tag. Stuff inside <noscript> is only parsed if javascript is disabled. UPDATE Time to run in circles and try everything then: Clear your caches and whatnot. Try to navigate to /favicon.ico in your browser to make sure it's being served. Load your site in incognito/private mode, or on multiple browsers, or on a different device Get rid of the rel="shortcut icon" line. It's for IE8 and below, so nobody cares. Try using a plain png favicon. Save a PNG called favicon.png, and use <link rel="icon" href="{{ site.baseurl }}/favicon.png" type="image/png" />
{ "pile_set_name": "StackExchange" }
Q: Need to make a mask invoked over a dialog box ignore escape (ExtJS 5.1.2) Reason: We need to stop allowing dismissal of the U/I element while we are waiting for a reply from an external device/system. I've tried a number of different approaches (keymap, onEsc). There is already a working listener that dismisses the mask when the external system returns with data. Here is the code as I have it currently... onSaveRecord: function () { var me = this; . . . if (me.onRecordSaving(recordDetail, isNew)) { var myMask = new Ext.LoadMask({ msg: 'Processing', target: me.getView(), closable: true, onEsc: function () { my.myOnEsc(); } }); myMask.show(); //me.getView().mask('Processing'); // . . . }, myOnEsc: function () { debugger; // <--- never hits this Ext.emptyFn(); }, A: Wound up with this in the actualDialogBox.js... onSaveRecordClick: function () { var me = this; me.callSuper(); var win1 = me.getView(); . . . generic conditional code added . (not pertinent to the escape key disabling). . if (condition) { var win = Ext.WindowManager.getActive(); win.setDisableEscapeKey(true); } }, and in a super of the above dialog... disableEscapeKey: false, setDisableEscapeKey: function (value) { this.disableEscapeKey = value; }, onEsc: function () { var me = this; if (me.disableEscapeKey) { Ext.emptyFn(); } else { me.callParent(arguments); } }, Works perfectly for my application.
{ "pile_set_name": "StackExchange" }
Q: How to copy a div's content to clipboard without flash That's it :) I have a div with the id #toCopy, and a button with the id #copy. What's the best way to copy #toCopy content to clipboard when pressing #copy? A: You can copy to clipboard almost in any browser from input elements only (elements that has .value property), but you can't from elements like <div>, <p>, <span>... (elements that has .innerHTML property). But I use this trick to do so: Create a temporary input element, say <textarea> Copy innerHTML from <div> to the newly created <textarea> Copy .value of <textarea> to clipboard Remove the temporary <textarea> element we just created function CopyToClipboard (containerid) { // Create a new textarea element and give it id='temp_element' var textarea = document.createElement('textarea') textarea.id = 'temp_element' // Optional step to make less noise on the page, if any! textarea.style.height = 0 // Now append it to your page somewhere, I chose <body> document.body.appendChild(textarea) // Give our textarea a value of whatever inside the div of id=containerid textarea.value = document.getElementById(containerid).innerText // Now copy whatever inside the textarea to clipboard var selector = document.querySelector('#temp_element') selector.select() document.execCommand('copy') // Remove the textarea document.body.removeChild(textarea) } <div id="to-copy"> This text will be copied to your clipboard when you click the button! </div> <button onClick="CopyToClipboard('to-copy')">Copy</button> Little late but hope that helps! A: UPDATED ANSWER Javascript was restricted from using the clipboard, early on. but nowadays it supports copy/paste commands. See documentation of mozilla and caniuse.com. document.execCommand('paste') make sure that you support browsers that don't. https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand http://caniuse.com/#search=command Javascript is not allowed to use the clipboard, but other plugins like flash do have access. How do I copy to the clipboard in JavaScript?
{ "pile_set_name": "StackExchange" }
Q: Is a GPU always faster than a CPU for training neural networks? Currently, I am working on a few projects that use feedforward neural networks for regression and classification of simple tabular data. I have noticed that training a neural network using TensorFlow-GPU is often slower than training the same network using TensorFlow-CPU. Could something be wrong with my setup/code or is it possible that sometimes GPU is slower than CPU? A: This changes according to your data and complexity of your models. See following article by microsoft. Their conclusion is The results suggest that the throughput from GPU clusters is always better than CPU throughput for all models and frameworks proving that GPU is the economical choice for inference of deep learning models. ... It is important to note that, for standard machine learning models where number of parameters are not as high as deep learning models, CPUs should still be considered as more effective and cost efficient. Since you are training MLP, it can not be thought as standard machine learning model. See my preprint, The impact of using large training data set KDD99 on classification accuracy. I compare different machine learning algorithms using weka. As you can see from above image, MLP takes 722 minutes to train while Naive Bayes ~2 minutes. If your data is small and your models parameters are not high, you will see better performance on CPU.
{ "pile_set_name": "StackExchange" }