source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0016937157.txt" ]
Q: how to stop intellij incorrectly treating a normal directory as a package See in image I don;t want the webapp directory treated as package. And I don;t want to exclude from indexing - the indexing is great. A: Don't configure the directory (and any of its parents) as Sources in the Project Structure, module settings. IntelliJ IDEA interprets a directory as a package only for the the directories under the source roots.
[ "stackoverflow", "0015632960.txt" ]
Q: Knowing the direction vector of an image I'm a bit rusty in Math, but I have a problem. I have a 2D Image that is projected on a floor, which has two characters like [A1]. I use a Mobile phone camera that detects, decodes those two characters. Consider, for example a vehicle that has that camera passed through those two characters, one time forward, and one time backward over the the two characters [A1]. In both ways, to detect the characters each, I have to rotate it 180*, then do NCC with the characters template each frame which is computational consuming. Is there a better way or an optimized way to do that and save the rotation,..etc. ? Is there also a way to know from an Image that is projected on the floor, the directional vector ? A: there are other ways to detect "features" on a image, with matching descriptors (SURF-Speeded-Up Robust Feature or SIFT-Scale Invariant Feature Transform) that are scale and rotational invariant. at this link you can find some implementations for C#, Java (ImageJ) and C++ OpenCV has also several implementation of the algorithm. The idea is to extract descriptors from the template image and compare them with the target image without the need to rotate or scale it. hope it helps
[ "stackoverflow", "0053652520.txt" ]
Q: How to filter a list by multiple predicates in one pass? Suppose I filter a list by a few predicates, e.g. val xs = List(1, 0, -1, 2, 3, 4, 5, -6, 5, 0) val pred1: Int => Boolean = _ > 0 val pred2: Int => Boolean = _ < 0 val pred3: Int => Boolean = _ % 2 == 0 val xs1 = xs.filter(pred1) // List(1, 2, 3, 4, 5, 5) val xs2 = xs.filter(pred2) // List(-1, -6) val xs3 = xs.filter(pred3) // List(0, 2, 4, -6, 0) How to filter a list by all these predicates in one pass only ? def filterByFew(xs: List[Int], preds: List[Int => Boolean]): List[List[Int]] = ??? filterByFew(xs, List(pred1, pred2, pred3)) should return List(List(1, 2, 3, 4, 5, 5), List(-1, -6), List(0, 2, 4, -6, 0)) A: I believe Andrey Tyukin's answer does not address the "in one pass" aspect of the question. If the order of elements don't have to be preserved, then I think following implementation will be reasonably efficient: def filterByFew[A](xs: Traversable[A], preds: List[A => Boolean]): List[List[A]] = { xs.foldLeft(List.fill(preds.size)(List.empty[A]))((acc, el) => { acc.zip(preds).map({ case (l, p) => if (p(el)) el :: l else l }) }) } If the order has to be preserved the simple solution is reverse all the inner list at the end of filterByFew but if filters are not very selective it is effectively iterating over the whole collection multiple times. The other solution would be something like this: def filterByFew2[A](xs: Traversable[A], preds: List[A => Boolean]): List[Traversable[A]] = { val builders = xs.foldLeft(List.fill(preds.size)(xs.companion.newBuilder[A]))((acc, el) => { acc.zip(preds).foreach({ case (b, p) => if (p(el)) b += el }) acc }) builders.map(b => b.result()) } It is less FP but better for performance. Actually this is similar to how filter is implemented inside the standard library. A simple test to ensure that this works as claimed is something like this: def test(): Unit = { val xs0 = List(1, 0, -1, 2, 3, 4, 5, -6, 5, 0) val xs = xs0.view.map(x => { println(s"accessing $x") x }) val pred1: Int => Boolean = _ > 0 val pred2: Int => Boolean = _ < 0 val pred3: Int => Boolean = _ % 2 == 0 val preds = List(pred1, pred2, pred3) val res = preds.map(xs.filter) println(res) println("---------------") println(filterByFew(xs, preds)) println("---------------") println(filterByFew2(xs, preds)) } view is lazy method so we'll log every access to the underlying collection. It is easy to see that the Andrey's code access each element 3 times while my solutions do it only once.
[ "stackoverflow", "0040437983.txt" ]
Q: How to decide TabId and ModuleId in Globals.NavigateURL in DotnetNuke? I am damn confuse in TabId and ModuleId which need to pass as parameters in Globals.NavigateURL. I have created a project with 2 UserControl. Now I want to navigate in button click event of first UserControl. I have reviewed some reference. Most of them suggest to pass TabId, Key and ModuleId. I know Key but I don't know what is TabId and ModuleId and how to get it in my .cs file of usercontrol. Can anybody please suggest me? A: In answering your other question, I told you that the following two lines of code are equivalent: string miUrl = base.EditUrl("ModuleInfo"); string miUrl = DotNetNuke.Common.Globals.NavigateURL(base.TabId, "ModuleInfo", String.Format("mid={0}", base.ModuleId)); If you inherit from PortalModuleBase, you have access to TabId and ModuleId in the base class. If you only need to navigate to a module control (view) in the same module, base.EditUrl() works fine. You need to use NavigateUrl() if you need to navigate to another module or to another page (tab).
[ "scifi.stackexchange", "0000003067.txt" ]
Q: What is the story behind the Warp Gates in Cowboy Bebop? Was it ever explained who built the various gates in Cowboy Bebop? What companies, what are their construction, how many are there, how far do they reach, and how do they function? What are the specifics of the gate accident that shattered the moon? A: I don't think I've ever seen anything on the specifics of the gate accident cause. The technology was created by the character know as Chessmaster Hex and the company was just called generically the "Gate Corporation" The first set of experimental gates were between the moon and earth and as you know there was an accident and it blew up part of the moon. After the accident Earth wasn't very habitable (including rains of rock that killed over 4.5Bn people) so humans moved to colonize rest of the solar system. I'm not sure of exact gate numbers or gate paths but the series references colonies on Earth, Venus, Mars, Titan (moon of Saturn), Ganymede, Callisto and Io (3 moons of Jupiter), plus a few colonies (only Tijuana is referenced by name) on some large Asteroids between Mars and Jupiter. So you're looking at maybe dozen or so gates.
[ "academia.meta.stackexchange", "0000000180.txt" ]
Q: Are questions on opportunities in industry after a doctorate on-topic? In this question, the OP wants to know the opportunities in industrial R&D after a PhD in organic chemistry. In general, industry vacancies and requirements do not have anything to do with academia, so Charles has rightly cast his vote to close the question. But on a previous date, we have enthusiastically answered this question, which asks almost the same question for CS. How do we decide if a particular question asking about industrial R&D opportunities for PhD and post-doc scholars is on-topic or not? Asking about software jobs after MS is obviously out of scope, but aren't professors in academia better informed than most about research opportunities? Shouldn't we give a concession to questions about industrial R&D after PhD/post-doc alone? A: See my comment on this recent question. This question to me seems perfectly on-topic. The questioner is in academia, and has questions that relate to life as an academic, namely, what else can I do outside of working as a professor? Given that statistics (which I'm too lazy to look up now) suggest that most PhD students go on to careers outside of academia, this is actually a very relevant question. That being said, I agree with @Charles that this particular question was poorly phrased, and could have had a better reception if it was worded better. A: I agree with EnergyNumbers, I think that by default, question only about opportunity in industry are not on topic, but it's not a very strict rule. A question asking the difference between academia and industry might be more on topic. A question stating that the OP wants nothing to do with Academia is not really on topic on a website dedicated to academics ... That being said, the quality of the question is also a very important factor, and that was a main reason for closing that question: it was not really on topic, so I didn't see the point of leaving a low quality question open.
[ "rpg.stackexchange", "0000111066.txt" ]
Q: What class features work does a Runechild's Essence Runes feature apply to? I recently stared a game of D&D and I'm playing a sorcerer with the runechild subclass from the (third-party) Tal'Dorei Campaign Setting by Matt Mercer. I am trying to figure out how to use the runes. Part of the Essence Runes 1st-level feature of the subclass (Tal'Dorei Campaign Setting, p. 103) says: At the end of a turn where you spent any number of sorcery points for any of your class features, an equal number of essence runes glow with stored energy, becoming charged runes. I'm not sure what examples of class features would be because I understand that to be stuff like hit dice and proficiencies. What sort of "class features" does the Essence Runes feature refer to? A: There are 2 Class Features which all Sorcerers get which allow you to spend Sorcery Points (PHB 101): Creating Spell Slots (as a bonus action) Metamagic (as part of casting a spell) So as a Runechild, you have a number of Essense Runes equal to your Sorcerer class level. There are 3 ways to convert Essense Runes into charged runes (Tal'Dorei Campaign Setting 103): As a bonus action, spend any number of sorcery points to convert that number of Essense Runes into charged runes. As a bonus action, if you have 0 sorcery points, you may spend your Action to convert a single Essense Rune into a charged rune. At the end of your turn, and sorcery points used for the 2 Class Features above will convert that number of available Essense Runes into charged runes. The rules for Runechild then specify how charged runes affect you and how they can be used to activate Runechild features. Consider this example: A 5th level Sorcerer uses their bonus action to spend 2 sorcery points and create a 1st level spell slot. Then the Sorcerer spends 1 sorcery point to apply the Twinned Spell metamagic as they cast Chromatic Orb against 2 different enemies. The Sorcerer has 5 Essense Runes. If 3 of these Runes were already charged, then at the end of the Sorcerer's turn, there is enough power to charge 3 Runes, but only 2 are available and they are both charged, but the 3rd is "wasted." And now with 5 charged runes, the Sorcerer begins to glow (bright light for 5' and dim light for 5' beyond that). You are correct that Hit Points, Proficiencies, etc. are Class Features, but so are all of the other entries for Sorcerer on the next 2 pages. Also note, if you are not familiar, that the Runechild Sorcerous Origin is an alternative to the other Sorcerous Origins in the PHB. You get all of the Class Features of Sorcerer up until the section detailing the first 2 options for Sorcerous Origin: Draconic and Wild Magic.
[ "stackoverflow", "0062460806.txt" ]
Q: as.matrix on named list returning matrix with typeof "list" I'm trying to turn a named list in R into a column matrix with row names such as: my_matrix = as.matrix(list(Row1Name=1,Row2Name=2,Row3Name=3)) This seems straight forward enough and even appears to work (see output below). Unfortunately, despite appearances this is not a normal numeric matrix but rather a list matrix. Normally I wouldn't care but in this case I'd like to use apply to perform row based calculations. Is there an easy solution other than ugly code to manually convert my list to a matrix? A: If we need to construct from a list, unlist and then wrap with as.matrix my_matrix <- as.matrix(unlist(lst1)) Now, there won't be any errors apply(my_matrix, 1, sum) But, there are vectorized options rowSums(my_matrix) and also as there is a single column, probably this won't be needed (may be the example is a simple one) where lst1 <- list(Row1Name=1,Row2Name=2,Row3Name=3)
[ "stackoverflow", "0016660999.txt" ]
Q: Why does the color of my lines gradually change in html 5 canvas? I was wondering why the vertical lines(strokes) are slowing changing color almost like they are being gradiented towards the end Below is an example of what i mean, this is using HTML5 Canvas http://jsfiddle.net/YyhxV/ Thanks for your help Aiden A: The problem with the code is that you stroke each time you add a line to the path. Your line is a bit thin. Values below 1 are valid however - this will activate sub-pixeling (as does non-integer co-ordinates). The fading is a result of the previous lines being drawn on top of each other. As they are sub-pixel'ed it will give the "fading" effect as the older lines have more "mixed" information than the newer lines which makes them "stronger" in appearance. Try this modification: (http://jsfiddle.net/YyhxV/2/) //... context.lineWidth= 0.2; //0.1 is a bit too thin, try cranking it up a bit //... for(var interval = 0; interval < 24; interval++) { context.moveTo(interval*spacing+0.5,50); context.lineTo(interval*spacing+0.5,42); } //move stroke outside context.stroke();
[ "stackoverflow", "0060103377.txt" ]
Q: EC2 Instance Connect (browser-based SSH connection) doesn't work Trying to connect Amazon AWS EC2 instance fails. Platform: Amazon Linux Connection method: EC2 Instance Connect (browser-based SSH connection) Error: There was a problem setting up the instance connection Log in failed. If this instance has just started up, try again in a minute or two. Note: I am able to connect via Putty / SSH Client. But same instance can't connect via browser. When checked network logs in browser's developer tool, see a Status Code: 400 Bad Request for following URL: https://ec2-instance-connect.us-east-2.managed-ssh.aws.a2z.com/ls/api/tokens Has anyone ever successfully connected to Amazon Linux EC2 instance from browser. A: To test, I just did the following: Launched an Amazon Linux 2 EC2 instance with the default security group Clicked "Connect" in the EC2 management console Selected "EC2 Instance Connect" Clicked "Connect" A new browser tab opened and a few seconds later I had a working SSH connection. I then tried it again with an Amazon Linux (not Amazon Linux 2) instance and got the error: There was a problem setting up the instance connection Log in failed. If this instance has just started up, try again in a minute or two. This is because the EC2 Instance Connect client is only pre-installed on Amazon Linux 2 and Ubuntu 16.04 or later.
[ "mathoverflow", "0000359604.txt" ]
Q: What is the motivation of the $L^p$ differentiability? I was reading some papers and come up with the next definition : A function is differentiable in the $L^p$ sense at $x$ if there exists a real number $f'_p(x)$ such that $$\bigg(\frac{1}{h}∫_{-h}^{h}|f(x+s)−f(x)−f_p'(x)s|^pds\bigg)^{1/p}=o(h)$$ And he states that many $f_p'$ are equivalent to an ordinary derivative on an almost everywhere basis. I saw this kind of differentiability is studied in some papers, but I don't know where does it started, i.e. what was it's motivation to define such operation and function space. Ash, J. Marshall, An (L^p) differentiable non-differentiable function, Real Anal. Exch. 30(2004-2005), No. 2, 747-754 (2005). ZBL1107.26010. A: I don't know the literature, but it maybe helpful to understand exactly what this notion of differentiability gains for us. First, unlike the Sobolev notions, this does not handle functions which belong in Holder classes. For example, based on the definition the absolute value function is not $L^p$ differentiable for any $p$, but it is certainly (locally) in the Sobolev class $W^{1,p}$ for every $p\in [1,\infty]$. In fact, whenever $f$ is a function such that the one sided derivatives from the left and from the right independently exist, but do not agree, such a function is not $L^p$ differentiable in the sense defined in the paper. So what does $L^p$ differentiability gain for us? It gains when your function fails to be differentiable near $x$ due to it being oscillatory in a certain way. An example: Let the set $A = \cup_{k = 10}^\infty [ 1/k - 2^{-k}, 1/k + 2^{-k}]$, and let $f$ be the indicator function of $A$. This function is clearly not differentiable at $x = 0$. However, since $$ \int_{-h}^h |f(s)|^p ~ds \leq \sum_{k = \lfloor 1/h \rfloor }^\infty 2^{1-k} = 2^{2-\lfloor 1/h \rfloor } $$ we see that for any $p\in [1,\infty)$, $f$ is $L^p$ differentiable at the origin with derivative $0$. As to why measuring things with respect to $L^p$ means can be useful: there is a big hint in the paper of Calderon and Zygmund, concerning elliptic PDEs. They wrote [emphases mine]: It seems that the notion of differentiability which is most suited to the treatment of the problems that concern us, is not the classical one. It appears that it is more convenient to estimate the remainder of the Taylor series in the mean with various exponents. This type of differentiability is much more stable ... If you are familiar with some harmonic analysis, what this is screaming out is that a lot of analytic estimates (Sobolev regularity for elliptic PDEs, singular integrals, etc.) work generally for functions measured on the $L^p$ scale, but often fail (just by a little) at $L^\infty$ (and sometimes $L^1$). You can of course ask why did Calderon and Zygmund not use the Sobolev class: the key is that they want to understand pointwise estimates of differentiability. As mentioned above, Sobolev classes are not so sensitive to pointwise properties.
[ "stackoverflow", "0055892758.txt" ]
Q: No implementation found for int org.libsdl.app.SDLActivity.nativeSetupJNI() First of all want to confirm I browsed all similiar topics to this and found nothing that could solve my issue. When I want to run app on my phone it throws UnsatisfiedLinkError and No implementation found for int org.libsdl.app.SDLActivity.nativeSetupJNI(). 04-28 16:56:13.081 17793 17793 E art : No implementation found for int org.etlegacy.app.SDLActivity.nativeSetupJNI() (tried Java_org_etlegacy_app_SDLActivity_nativeSetupJNI and Java_org_etlegacy_app_SDLActivity_nativeSetupJNI__) 04-28 16:56:13.082 17793 17793 D AndroidRuntime: Shutting down VM 04-28 16:56:13.082 17793 17793 E AndroidRuntime: FATAL EXCEPTION: main 04-28 16:56:13.082 17793 17793 E AndroidRuntime: Process: org.etlegacy.app, PID: 17793 04-28 16:56:13.082 17793 17793 E AndroidRuntime: java.lang.UnsatisfiedLinkError: No implementation found for int org.etlegacy.app.SDLActivity.nativeSetupJNI() (tried Java_org_etlegacy_app_SDLActivity_nativeSetupJNI and Java_org_etlegacy_app_SDLActivity_nativeSetupJNI__) 04-28 16:56:13.082 17793 17793 E AndroidRuntime: at org.etlegacy.app.SDLActivity.nativeSetupJNI(Native Method) 04-28 16:56:13.082 17793 17793 E AndroidRuntime: at org.etlegacy.app.SDL.setupJNI(SDL.java:15) 04-28 16:56:13.082 17793 17793 E AndroidRuntime: at org.etlegacy.app.SDLActivity.onCreate(SDLActivity.java:234) 04-28 16:56:13.082 17793 17793 E AndroidRuntime: at android.app.Activity.performCreate(Activity.java:6857) 04-28 16:56:13.082 17793 17793 E AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119) 04-28 16:56:13.082 17793 17793 E AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2676) 04-28 16:56:13.082 17793 17793 E AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2784) 04-28 16:56:13.082 17793 17793 E AndroidRuntime: at android.app.ActivityThread.-wrap12(ActivityThread.java) 04-28 16:56:13.082 17793 17793 E AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1523) 04-28 16:56:13.082 17793 17793 E AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102) 04-28 16:56:13.082 17793 17793 E AndroidRuntime: at android.os.Looper.loop(Looper.java:163) 04-28 16:56:13.082 17793 17793 E AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:6238) 04-28 16:56:13.082 17793 17793 E AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method) 04-28 16:56:13.082 17793 17793 E AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) 04-28 16:56:13.082 17793 17793 E AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794) 04-28 16:56:13.091 3424 3645 D PowerKeeper.Event: notifyAMCrash packageName: 0, pid:17793 Been trying to add JNIEXPORT and JNICALL without no luck. I will provide some code from 3 different files. sys.android.c #include "jni.h" /******************************************************************************* Functions called by JNI *******************************************************************************/ /* Start up the ET Legacy app */ JNIEXPORT void JNICALL Java_org_etlegacy_app_SDLActivity_nativeInit(JNIEnv *env, jobject obj) { Android_JNI_SetupThread(); SDL_SetMainReady(); /* Run the application code! */ char *argv[2]; argv[0] = SDL_strdup("ET Legacy"); // send r_fullscreen 0 with argv[1] because on fullscreen can cause some issues see: https://github.com/rafal1137/android-project/commit/d960cc244b17d8cc0d084f9c8dad9c1af4b2ba72#diff-b9bd293cfb066fe80c10d3fcdd0fd6cbL439 argv[1] = 0; SDL_main(1, argv); } sys_main.c /** * @brief SDL_main * @param[in] argc * @param[in] argv * @return */ int main(int argc, char **argv) { char commandLine[MAX_STRING_CHARS] = { 0 }; Sys_PlatformInit(); // Set the initial time base Sys_Milliseconds(); #ifdef __APPLE__ // This is passed if we are launched by double-clicking if (argc >= 2 && Q_strncmp(argv[1], "-psn", 4) == 0) { argc = 1; } #endif Sys_ParseArgs(argc, argv); #if defined(__APPLE__) && !defined(DEDICATED) // argv[0] would be /Users/seth/etlegacy/etl.app/Contents/MacOS // But on OS X we want to pretend the binary path is the .app's parent // So that way the base folder is right next to the .app allowing { char parentdir[1024]; CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle()); if (!url) { Sys_Dialog(DT_ERROR, "A CFURL for the app bundle could not be found.", "Can't set Sys_SetBinaryPath"); Sys_Exit(EXIT_FAILURE); } CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url); if (!url2 || !CFURLGetFileSystemRepresentation(url2, 1, (UInt8 *)parentdir, 1024)) { Sys_Dialog(DT_ERROR, "CFURLGetFileSystemRepresentation returned an error when finding the app bundle's parent directory.", "Can't set Sys_SetBinaryPath"); Sys_Exit(EXIT_FAILURE); } Sys_SetBinaryPath(parentdir); CFRelease(url); CFRelease(url2); } #else Sys_SetBinaryPath(Sys_Dirname(argv[0])); #endif Sys_SetDefaultInstallPath(DEFAULT_BASEDIR); // Sys_BinaryPath() by default // Concatenate the command line for passing to Com_Init Sys_BuildCommandLine(argc, argv, commandLine, sizeof(commandLine)); Com_Init(commandLine); NET_Init(); Sys_SetUpConsoleAndSignals(); #ifdef _WIN32 #ifndef DEDICATED if (com_viewlog->integer) { Sys_ShowConsoleWindow(1, qfalse); } #endif Sys_Splash(qfalse); { char cwd[MAX_OSPATH]; _getcwd(cwd, sizeof(cwd)); Com_Printf("Working directory: %s\n", cwd); } // hide the early console since we've reached the point where we // have a working graphics subsystems #ifndef LEGACY_DEBUG if (!com_dedicated->integer && !com_viewlog->integer) { Sys_ShowConsoleWindow(0, qfalse); } #endif #endif Sys_GameLoop(); return EXIT_SUCCESS; } SDLActivity.java protected String[] getLibraries() { return new String[] { "SDL2", "hidapi", "etl" }; } Should I remove SDL_main(1, argv); from sys_android.c file so it can pick the right one from sys_main.c ? A: Issue seems to be typo in name of function correct one is Java_org_etlegacy_app_SDLActivity_nativeSetupJNI()
[ "stackoverflow", "0041248531.txt" ]
Q: Dictionary code just loops over and over again I have a text file I am designing for a mock store I named 'Bodn's Superstore'. I designed a .txt database as such. iPhone 28273139 5.50 Book 81413852 1.50 Charger 62863152 3.00 Plug 25537398 4.50 You can see it follows the format Name Code Price The code I have written is intended to conver the database to a dictionary, and the customer can choose the quantity of products they buy. They then enter the 8 digit code into the computer and the IDLE works to figure out the name of the product. The code is displayed below. It first validates the code to ensure it is 8 characters long. (Python 3.4.2) database = open("SODatabase.txt", "r") list = {} for line in database: key = line.strip() code = next(database).strip() price = next(database).strip() # next(database).strip() # if using python 3.x list[key]=code,price numberItems=int(input('State the quantity required. >> ')) with open('SODatabase.txt','r') as searchfile: for line in searchfile: while True: userCode=input('What product would you like? Enter the product code >> ') try: if len(str(userCode))!=8: raise ValueError() userCode=int(userCode) except ValueError: print('The code must be 8 characters long.') else: for key, value in list.items(): if userCode==value: print (key) Now, the validation of the code works. Say for example, I want to buy 1 iPhone. This is what appears in the main window. State the quantity required. >> 1 What product would you like? Enter the product code >> 2827313 The code must be 8 characters long. What product would you like? Enter the product code >> 28273139 What product would you like? Enter the product code >> 28273139 What product would you like? Enter the product code >> And so on and so forth. The code simply won't work backwards to find the key of the dictionary and print it, which is "iPhone". I want to receive the name "iPhone" after I've stated my quantity and the product code, but my Python File won't work back through the dictionary to find the key that corresponds to the product code (value) I have given it. A: I don't see why for line in searchfile is required; seems like a copy mistake. Anyway, userCode never equals value because value is a tuple; it can however equal value[0], where you saved the codes. How about that? while True: userCode = input('What product would you like? Enter the product code >> ') try: if len(str(userCode))!=8: raise ValueError() userCode = int(userCode) except ValueError: print('The code must be 8 characters long.') else: for key, value in list.items(): if userCode == value[0]: print (key)
[ "scifi.stackexchange", "0000124377.txt" ]
Q: Was the Trippies show a commentary on modern children's entertainment? In the prequel When The Tripods Came, humans are first hypnotized and brought under control via those who watch the Trippies cartoon. In The City of Gold and Lead, Will's Master explains that they had initially gained control via television signals, so the idea has long been established already. But John Christopher deliberately created a bright and saccharine sweet cartoon series that drew in the children and many adults and allowed them to be brainwashed. Was this just an idea he had for how it worked, or was this deliberate commentary on the state of television and specifically children's entertainment? A: John Christopher (Pseudonym of Sam Youd) was a British Army Signalman during the Second World War so he would have been familiar with the power of radio and television signals. As with many in his generation, he may well have regarded television as a propaganda tool and idiotic distraction (cf Roald Dahl) and his prolific science fiction and other writing demonstrates an enthusiasm for literature and he regularly returns to themes of disaster, self-sufficiency, self-discipline and resistance to authority both benevolent and oppressive. 'The Lotus Caves' (1969) has the main theme as 'the development of a young person's will and independence, and the conflict between benevolent authority and individual conscience.' (Wikipedia) Since 'When the Tripods Came' was written after the original book and the TV adaptation - which had only two seasons and did not conclude the story and included changes which Christopher/Youd disapproved of - the introduction of an all female family to provide love-interests (interview on wordcandy.net) it is conceivable that he had little love for modern British Children's TV - by the 80's it featured a lot of cartoons, American imports and toy brand tie ins.
[ "stackoverflow", "0034159696.txt" ]
Q: Resume activity from a android tv recommendation I have some troubles with the management of recommendations (notifications) on an Android TV with the Leanback Launcher. I use the google sample here to implement my own : https://github.com/googlesamples/androidtv-Leanback Expected result : I'm on my activity "MainActivity" (with a webview) I press HOME, so I'm on the Leanback launcher with recommendation include mines. I press on one of them Resume activity "MainActivity" without recreate it with a new Intent with a new extra. Actually, The resume of the activity without reload the activity works fine, below the creation of the PendingIntent : private PendingIntent buildPendingIntent(Parcelable media, int id) { Intent detailsIntent = new Intent(this, MainActivity.class); detailsIntent.putExtra("media", media); detailsIntent.putExtra("id", id); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(MainActivity.class); stackBuilder.addNextIntent(detailsIntent); return stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); } Current result : I'm on my activity "MainActivity" (with a webview) I press HOME, so I'm on the Leanback launcher with recommendation include mines. I press on one of them My activity receive "onNewIntent" event by in the extrat intent values I have always the same media. This solution doesn't work, because Google said in a comment of the sample code : // Ensure a unique PendingIntents, otherwise all recommendations end up with the same // PendingIntent detailsIntent.setAction(movie.getId()); So to differentiate all recommandations, I have to set Action with an ID, else, it will be always the last pendingintent sent to my activity. It's my current behavior, I receive in "onNewIntent" always the same "media" and "id" in the intent (the last one), whatever on which recommendation I click, I always get the same Intent. But if I set the action with an "id", the activity "MainActivity" is recreated, so the resume failed, and the context of my webview is cleared my webview is reloaded :( but I get the good intent with the good media in the extra intent values. Have you a solution to help me to have the behavior I want ? To simplify my question, how can I resume my Activity B from a recommendation with the good pendingintent without reload my activity ? Thank you in advance for your help. A: I found a solution. I don't think it's the good one but it works for my case. PendingIntent pIntent = PendingIntent.getActivity(this, id, detailsIntent, PendingIntent.FLAG_UPDATE_CURRENT); return pIntent; So, If I set the "resquetCode" with the id, so Android think it's a different Activity and resume it without recreate a new one.
[ "stackoverflow", "0002207393.txt" ]
Q: Indexing table with duplicates MySQL/SQL Server with millions of records I need help in indexing in MySQL. I have a table in MySQL with following rows: ID Store_ID Feature_ID Order_ID Viewed_Date Deal_ID IsTrial The ID is auto generated. Store_ID goes from 1 - 8. Feature_ID from 1 - let's say 100. Viewed Date is Date and time on which the data is inserted. IsTrial is either 0 or 1. You can ignore Order_ID and Deal_ID from this discussion. There are millions of data in the table and we have a reporting backend that needs to view the number of views in a certain period or overall where trial is 0 for a particular store id and for a particular feature. The query takes the form of: select count(viewed_date) from theTable where viewed_date between '2009-12-01' and '2010-12-31' and store_id = '2' and feature_id = '12' and Istrial = 0 In SQL Server you can have a filtered index to use for Istrial. Is there anything similar to this in MySQL? Also, Store_ID and Feature_ID have a lot of duplicate data. I created an index using Store_ID and Feature_ID. Although this seems to have decreased the search period, I need better improvement than this. Right now I have more than 4 million rows. To search for a particular query like the one above, it looks at 3.5 million rows in order to give me the count of 500k rows. PS. I forgot to add view_date filter in the query. Now I have done this. A: The best way I found in tackling this problem is to skip DTA's recommendation and do it on my own in the following way: Use Profiler to find the costliest queries in terms of CPU usage (probably blocking queries) and apply indexes to tables based on those queries. If the query execution plan can be changed to decrease the Read, Writes and overall execution time, then first do that. If not, in which case the query is what it is, then apply clustered/non-clustered index combination to best suit. This depends on the nature of the existing table indexes, the bytes total of columns participating in index, etc. Run queries in the SSMS to find the most frequently executing queries and do the same as above. Create a defragmentation schedule in order to either Reorganize or Rebuild indexes depending on how much fragmented they are. I am pretty sure others can suggest good ideas. Doing these gave me good results. I hope someone can use this help. I think DTA does not really make things faster in terms of indexing because you really need to go through what all indexes it is going to create. This is more true for a database that gets hit a lot.
[ "superuser", "0001117023.txt" ]
Q: How to import data in Excel from the clipboard as if it was in a text file? Using Excel you can import data from a text file with a wizard available at -> Data -> From text. Is there a way of using the same wizard to import data coming from the clipboard without having to create an empty text file, pasting the contents there and then using the wizard? A: Text to columns (in data tab) have almost the same functionality than your "import from text file has". You can split the text to columns by fixed length or at separators, select data type for each column... A: Alternatively, if you have the text data on your clipboard, you can Use Text Import Wizard...  (I've confirmed that this works for Excel 2010+; not sure about older versions.)
[ "stackoverflow", "0025818853.txt" ]
Q: How to use different contour levels for different functions I need to contour plot 3 different functions with gnuplot, but for 2 of them, I just need the contour level 0, for the other, I need the levels 10, 12 and 14. This is what I got so far: f(x,y) = 10 + x + y g1(x, y) = 5 - x - 2*y g2(x, y) = (1/x) + (1/y) - 2 set contour base set isosample 250, 250 set cntrparam cubicspline unset surface set size square set view map set yrange[-1:5] set xrange[-1:5] set cntrparam levels discrete 0 splot f(x,y), g2(x,y), g1(x,y) The problem is that I can either use: set cntrparam levels discrete 0 or set cntrparam levels discrete 10, 12, 14 for all the functions, but I don't know how to use the former for g1(x,y) and g2(x,y) only, while using the later for f(x,y). How to do it? A: In general you cannot define different contour settings for different functions which are to be plotted together. In your case there is a workaround, since the contour levels are well separated from each other. You must define your functions to be 1/0 where the unwanted levels are. Here I choose 5 as limit, which is in the middle: f(x,y) = 10 + x + y g1(x, y) = 5 - x - 2*y g2(x, y) = (1/x) + (1/y) - 2 set contour base set isosample 250, 250 set cntrparam cubicspline unset surface set size square set view map set yrange[-1:5] set xrange[-1:5] set cntrparam levels discrete 0, 10, 12, 14 splot (f(x,y) > 5 ? f(x,y) : 1/0) t 'f(x,y)', \ (g2(x,y) < 5 ? g2(x,y) : 1/0) t 'g2(x,y)', \ (g1(x,y) < 5 ? g1(x,y) : 1/0) t 'g1(x,y)' The result with 4.6.5 is:
[ "stackoverflow", "0000851323.txt" ]
Q: Reflection in C++ I've been working for years with Java. During those years, I've made extensive (or maybe just frequent) use of reflection, and found it useful and enjoyable. But 8 months ago I changed my job, and now Java is just a memory, and I'm getting my hands on C++. So now I'm wondering if there is any reflection mechanism in C++. I've read about RTTI but I feel it's by no means the power of Java (or other languages) reflecion. I'm beggining to think that there's no way to do this in C++. Am I wrong? A: Since C++ standard does not cover such concept as "metadata", there's no portable (across different compilers and platforms, for that matter) method of run-time reflection other than RTTI you already mentioned. In C++, there's also a possibility of compile-time reflection (think boost::type_traits and boost::type_of), but it's limited as well compared to, say, Nemerle or LISP. Most major frameworks (MFC, Qt, etc.) allow you to extract metainformation at run-time, but they require all kinds of special annotations for it to work (see RUNTIME_CLASS et al as an example). A: If you are looking for a totally general way to manipulate objects at runtime when you don't know their types at compile time in C++, you essentially need to: Define an interface (abstract base class with all pure virtual methods and no members) for each capability that a class might support. Each class must inherit virtually from all interfaces that it wants to implement (possibly among other classes). Now, suppose pFoo holds an interface pointer of type IFoo* to some object x (you don't need to know x's concrete type). You can see whether this object supports interface IBar by saying: if (IBar* pBar = dynamic_cast<IBar*>(pFoo)) { // Do stuff using pBar here pBar->endWorldHunger(); } else { // Object doesn't support the interface: degrade gracefully pFoo->grinStupidly(); } This approach assumes you know all relevant interfaces at compile time -- if you don't, you won't be able to use normal C++ syntax for calling methods anyway. But it's hard to imagine a situation where the calling program doesn't know what interfaces it needs -- about the only case I can think of would be if you want to expose C++ objects via an interactive interpreter. Even then, you can devise an (ugly, maintenance-intensive) way of shoehorning this into the above paradigm, so that methods can be called by specifying their names and arguments as strings. The other aspect to consider is object creation. To accomplish this without knowing concrete types, you'll need a factory function, plus unique identifiers for classes to specify which concrete class you want. It's possible to arrange for classes to register themselves with a global factory upon startup, as described here by C++ expert Herb Sutter -- this avoids maintaining a gigantic switch statement, considerably easing maintenance. It's possible to use a single factory, though this implies that there is a single interface that every object in your system must implement (the factory will return a pointer or reference to this interface type). At the end of the day, what you wind up with is basically (isomorphic to) COM -- dynamic_cast<IFoo*> does the same job as QueryInterface(IID_IFoo), and the base interface implemented by all objects is equivalent to IUnknown. A: Have a look at my answer to a similar question. Both solutions (XRTTI and OpenC++) proposed are based on external tools that generate the reflection meta-data for you during the build process.
[ "stackoverflow", "0055748553.txt" ]
Q: How to test for encoding type Python 2.7? I am trying to troubleshoot a problem I am having regarding foreign characters (any and all alphabets). My script (2.7 python) receives the characters (mix of english alphabet and other foreign characters) as unicode json, and it is sent to a database insert function for insertion into some tables using psycopg2. This works perfect as a script, but once not so much as a service (foreign chars get inserted as nonsense). This unicoding/encoding/decoding stuff is so confusing! I am trying to follow along with this ( https://www.pythoncentral.io/python-unicode-encode-decode-strings-python-2x/ ) in the hopes of understanding what I am receiving exactly and then sending to the database, but it seems to me that I need to know what the encoding is at various stages. How do you GET what the encoding type is? Sorry, this must be so simple, but I am not finding how to get that info, and other's questions on this matter haven't exactly been answered, in my opinion. This can't be that elusive. Please help. Add-on info as requested... -Yes, would love to move to 3.x, but cannot for now. -Currently it is mostly me testing, it's not live for users yet. I am testing and developing from a Windows 2012 Server AWS machine, and the service is hosted on a similar machine. So yes - how do you find the locale info? Have done some testing with the frontend dev (js) and he states the json input is coming to me as url encoded... when I type it, it just says unicode. Thoughts?? A: Don't rely on what the default system encoding is. Instead, always set it yourself: # read in a string (a bunch of bytes the encoding of which you should know) str = sys.stdin.read(); # decode the bytes into a unicode string u = unicode.decode(str, encoding='ISO-8859-1', errors=replace); # do stuff with the string # ... # always operate on unicode stuff inside your program. # make a 'unicode sandwhich'. # ... # encode the bytes in preparation for writing them out out = unicode.encode(u, encoding='UTF-8') # great, now you have bytes you can just write out with open('myfile.txt', 'wb') as f: rb.write(out) Notice, I hard-coded the encoding throughout. But what if you don't know the encoding of the input? Well, that's a problem. You need to know that. But I also understand unicode can be painful and there's this guy from the python community who tells you how to stop the pain (video). Note, one of the BIG changes in python 3 is better unicode support. Instead of using the unicode package and the confusing py2 str type, in python 3 str type is just what python 2's unicode type was, and you can specify encodings in more convenient places: with open('myfile.txt', 'w', encoding=UTF-8, errors='ignore') as f: # ...
[ "stackoverflow", "0023705019.txt" ]
Q: Purpose of "name" and "defaults" in config.Routes.MapHttpRoute In the global.asax file, I have something like this: void Application_Start(object sender, EventArgs e) { GlobalConfiguration.Configure(WebApiConfig.Register); } I have another file that has this code: using System.Web.Http; namespace WebConfig { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}", defaults: new { id = System.Web.Http.RouteParameter.Optional }); } } } The doc is not very descriptive. What's the purpose of the name property? Where else is it used? And same for the defaults property: what does it do? Thanks. A: The name assigns a name to the route by which route can be identified in the list of routes. This name is used in functions like ApiController.Url.Link to generate links to route, among others. defaults allows you to provide default values for things such as controller to map request to (if template doesn't specify {controller} segment), action to call if not following convention naming nor {action} segment in template, default values for parameters, etc.
[ "stackoverflow", "0023140944.txt" ]
Q: How can I output System.currentTimeMillis() to an ADF page? I'm using this and it doesn't work as expected. I'm trying to cache bust a css file as it changes a lot and we can't always expect users to thoroughly clear their cache. <c:set var="buster" value="{System.currentTimeMillis()}" /> <af:resource type="css" source="/oracle/webcenter/portalapp/shared/css/maaui.css?r=${buster}"/> Unfortunately that renders <link rel="stylesheet" type="text/css" afrres="true" href="/myAccount/oracle/webcenter/portalapp/shared/css/maaui.css?r=%7BSystem.currentTimeMillis()%7D"> It doesn't execute the method. I tried ${} and #{} as well and neither seem to work for me. Can anyone help me to achieve the desired result? Basically a random string that will change each time a user visits a page. I can easily do this in .NET but I am very new to Oracle ADF. A: Try <c:set var="buster" value="{myBean.time}" /> <af:resource type="css" source="/oracle/webcenter/portalapp/shared/css/maaui.css?r=#{buster}"/> And in MyBean managed backing bean public long getTime() { return System.getCurrentTimeMillis(); }
[ "stackoverflow", "0061540587.txt" ]
Q: Run Matlab script with python subprocess and timeout command I'm trying to run a batch of Matlab scripts and somehow it is not working. The code just stays idle and does nothing until timeout. This is the minimal code import subproces as sub cod = 'timeout -k 300 400 matlab -nodisplay -nosplash -r test'.split() proc = sub.run(cod, stdout=sub.PIPE, stderr=sub.PIPE) These lines of code just run until reaching the timeout condition, with no values in stdout and stderr. If I copy these lines inside the terminal, it works perfectly. (the script itself ends up with «exit», therefore after completion it returns to the terminal) I have already done this similar process with Octave instead, and it works flawlessly. I have tried to use matlab's python module, but the one I currently have is not compatible with my current Python version, an alternative could be to downgrade Python, but I'm reluctant to do it. The timeout condition is required because some of these scripts can loop infinitely. I am checking students codes. Edit: after discussion here, the main culprit appears to be the timeout command, if taken away, the script works. A: You can use the timeout argument of subprocess.run: import subproces as sub cod = 'matlab -nodisplay -nosplash -r test'.split() proc = sub.run(cod, stdout=sub.PIPE, stderr=sub.PIPE, timeout=300)
[ "stackoverflow", "0059715758.txt" ]
Q: what is the format specifier for string I use the following code myFunc(code:String) {        let t1f = NSLocalizedString("uiDlg Title code %s", comment: "uiDlg Title");       let t1 = String.localizedStringWithFormat(t1f, code); The string is declared in Localizable.strings file as "uiDlg Title code %s" = "code [%s]"; if I call myFunc("112233") the result string on the screen contains strange characters as code [Ä&:#] if I use let t1 = String.localizedStringWithFormat(t1f, code) + code; The second code is displayed properly as code [Ä&:#] 112233 Do I need to use %s as the format specifier for string? I could not find such sample code, all samples contains %d or %f for number formatting... A: %s is for a null terminated C string, the specifier for a standard Swift string is %@. You can find the list of format specifiers in the documentation
[ "stackoverflow", "0002732825.txt" ]
Q: Silverlight: Is it possible to use custom mouse cursors/pointers? I have just found this page indicating the support for Silverlight mouse cursors: http://msdn.microsoft.com/en-us/library/system.windows.input.cursor(VS.95).aspx Is that it!!! :-| what are they thinking, at least there is stylish looking Eraser! Is there aany other way to use custom cursors? How efficient/usable would it be to hide the cursor and show a png instead? A: I found an example here: http://nokola.com/blog/post/2009/12/13/Adorners-in-Silverlight-Move-Size-Rotate-Custom-Mouse-Cursor.aspx
[ "stackoverflow", "0013959018.txt" ]
Q: Thousands of Cities and Users relationship, what's the right way? In one application, user are allowed to select their desired locations/cities. The city list will be in a tree structure with checkbox like: [x]Country -[x]State 1 --[x]City 1 --[x]City 2 --[x]City 100 -[X]State 2 --[x]City 1 --[x]City 2 --[x]City 100 [x]Country 2 ...... Now, if user select country then all he'll have all state and cities. If selects one ore more states and those state, cities and country too be be stored for that user. User can select one or more country. Also user can uncheck any one desired city or state. How would you suggest to store and retrieve data. I'm using MySql and Php. Will a look-up table be ideal? OR can I grand all locations id kand store in json format in a text type column? Thanks! A: How would you suggest to store and retrieve data. I'm using MySql and Php. Will a look-up table be ideal? To store country, state and cities you should use normalized database schema. Country has states. States has cities. You need Junction tables. OR can I grand all locations id kand store in json format in a text type column? No. that would not be a normal form. And it'll create a lot of problem. You can not perform CRUD operations easily. Database schema create table countires(name varchar(100) primary key); create table sates(name varchar(100) primary key, country varchar(100), foreign key `country` references `countries`(`name`)); create table cities(name varchar(100) primary key, state varchar(100), foreign key `state` references `states`(`name`)); Now you can run any different type of queries on these tables. Say user have selected city (city1, city2), country cntry1 and a state stt2. Queries Find all the cities that users have selected. SELECT ct.name FROM cities AS ct JOIN states AS st ON ( st.name = city.state ) JOIN countries AS cn ON ( cn.name = st.country ) WHERE ct.name IN ( 'city1', 'city2' ) OR cn.name = 'cntry1' OR st.name = 'stt2'; Find all the states that users have selected. SELECT st.name FROM states AS st JOIN countries AS cn ON ( cn.name = st.country ) WHERE OR cn.name = 'cntry1' OR st.name = 'stt2'; Update 1 how to maintain its relation with user? You need Junction tables. Just create 3 of them. create table users(name varchar(100) primary key); CREATE TABLE user_countries ( user VARCHAR(100), country VARCHAR(100), PRIMARY KEY (`user`, `country`), FOREIGN KEY (`user`) REFERENCES `users`(`name`) FOREIGN KEY (`counry`) REFERENCES `countries`(`name`) ); CREATE TABLE user_states ( user VARCHAR(100), state VARCHAR(100), PRIMARY KEY (`user`, `state`), FOREIGN KEY (`user`) REFERENCES `users`(`name`) FOREIGN KEY (`state`) REFERENCES `states`(`name`) ); CREATE TABLE user_cities ( user VARCHAR(100), city VARCHAR(100), PRIMARY KEY (`user`, `city`), FOREIGN KEY (`user`) REFERENCES `users`(`name`) FOREIGN KEY (`city`) REFERENCES `cities`(`name`) );
[ "stackoverflow", "0013906679.txt" ]
Q: Storing large python object in RAM for later use Is it possible to store python (or C++) data in RAM for latter use and how can this be achieved? Background: I have written a program that finds which lines in the input table match the given regular expression. I can find all the lines in roughly one second or less. However the problem is that i process the input table into a python object every time i start this program. This process takes about 30minutes. This program will eventually run on a machine with over 128GB of RAM. The python object takes about 2GB of RAM. The input table changes rarely and therefore the python object (that i'm currently recalculating every time) actually changes rarely. Is there a way that i can create this python object once, store it in RAM 24/7 (recreate if input table changes or server restarts) and then use it every time when needed? NOTE: The python object will not be modified after creation. However i need to be able to recreate this object if needed. EDIT: Only solution i can think of is just to keep the program running 24/7 (as a daemon??) and then issuing commands to it as needed. A: To store anything in RAM you need an running process. Therefore the easiest solution is to implement what you wrote in your edit. You could also create a new process that always runs and let the old process connect to the new one to get the data. How you connect is up to you. You could use shared memory or a TCP/IP socket. TCP/IP has the advantage of allowing the data to be network accessible, but please make it secure. --edit-- Most operating systems also allow you to mount a pace of RAM as a drive. A RAM drive. You could write (like Neil suggested) the objects to that.
[ "serverfault", "0000263393.txt" ]
Q: What are "denied hosts"? An absolutely noob question I'm sure but I get an email from my web host everyday with a list of a few denied hosts and wondered exactly what this meant. I'm guessing that its a connection refused by the host because of an identification problem but what exactly could cause this issue? Additionally, I receive the following message and wondered if someone could explain it to me: reverse mapping - checking getaddrinfo for blah.blah.com [190.xxx.xxx.xx] failed - POSSIBLE BREAK-IN ATTEMPT! : 9 time(s) A: "Denied hosts" refers to brute force attacks on your services (usually ssh). Most likely you have a software like denyhosts or fail2ban or similar that looks into the failure log and when a host reaches a predefined number of failed logins it bans it (semi-)permanently. A brute force dictionary attack usually looks like this: hacker launches some tool that checks for public services(be that ssh for simplicity) running on machines in some IP range. When such a service is discovered the tool tries very common (hence dictionary) combinations of username/passwords. Things like "root/test123" or "guest/guest" should come to mind. You don't need to do anything besides making sure that your passwords are strong enough and you don't run any unsecured services on your box. http://en.wikipedia.org/wiki/Password_policy might be of some help in choosing strong passwords.
[ "diy.stackexchange", "0000069473.txt" ]
Q: Is it necessary to use GFCI receptacle with AFCI/GFCI combo breaker? I was just reading about the dual GFCI and AFCI breakers. Is it then necessary to use a GFCI receptacle with these breakers, or is that redundant? Also, rather than just pushing a button in your bathroom to reset or test, do you need to go to your panel each time? A: If you have a circuit where you need both AFCI and GFCI protection for some reason, yes, these breakers are fine to use, and no, you do not need additional GFI receptacles. That would be redundant and waste $$$. Yes, you definitely would need to go to the breaker panel to reset a tripped breaker. There is no such thing as a "remote reset". You also should test them once a month or so.
[ "stackoverflow", "0003466522.txt" ]
Q: Enter fires the form submit I have a div (nice gif dislayed as-if it's a button), on that div is a piece of javascript that handles the ENTER as-if it's a click ($(this).click()). The click does its own thing. In FireFox, it all works perfectly: the user presses the enter on the button and the click is fired. In IE, the form is submitted not the click() HELP!! A: this is a handy dandy jQuery function i use to get around this. $(formSelector).find('input, select').keypress(function (event) { if (event.keyCode == 13) { event.preventDefault(); $(buttonSelector).click().focus(); return false; } }); formselector is just a variable holding the '#FormId', and buttonSelector is a variable holding the button i want clicked. so in your case it would be: '#IdOfYourDivToClick'.
[ "stackoverflow", "0039079087.txt" ]
Q: how to find a list of users running a particular process I have to send a msg to a plurality of users who perform a specific process: How can I find a list of usernames, performing, for example the image "chrome.exe", and then send msg to these users. All the activities described above, must be in a bat-file Thank you in advance! A: Based on the comments to xmcp's answer, I expanded the code a bit: @echo off setlocal enabledelayedexpansion for /f "delims=" %%x in ('tasklist /fi "imagename eq firefox.exe" /fo csv /nh /v') do ( set line=%%x set line=!line:","="@"! for /f "tokens=7 delims=@" %%a in (!line!) do echo %%~a ) It replaces the field separators (","), without touching the comma within the numbers (in some localizations) and parses the resulting string with a different separator. Donwside: it slows things down (theroetical, I don't think anyone will notice it)
[ "gaming.stackexchange", "0000319107.txt" ]
Q: How do I obtain Fine Alcrysts? I want to craft more Magic Keys, but although the other ingredient (Screamroot) is available from several quests as a potential drop, there is no location given for farming fine alcrysts. Is the only choice to get them thru King Mog events etc., or are they farmable after advancing the story past a certain point? (or any other way, such as the Vortex missions) A: According to this page, aside from King Mog event, you can obtain Fine Alcrysts by Crafting 20% chance to obtain one after crafting any ability (source). Trophies Silver for Fabled Smith, Divine Technician, and Peerless Chemist. Reward (Event) Lunar New Year - Nian Beast Challenges! - INT (Day 5)
[ "stackoverflow", "0055515219.txt" ]
Q: Microsoft Graph API: Create events for users that are not me I'm currently developing a small managing app that should create events within a specific Microsoft calendar but I'm only able to do this for me as the authorized user. Is there an option to create events for everyone in this calendar with only knowing the userPrincipalName? { "subject": "test", "body": { "contentType": "HTML", "content": "Sample Text" }, "start": { "dateTime": "2019-04-04T12:00:00", "timeZone": "Pacific Standard Time" }, "end": { "dateTime": "2019-04-04T14:00:00", "timeZone": "Pacific Standard Time" }, "location":{ "displayName":"Testlocation" } } https://graph.microsoft.com/v1.0/users/myPricipalName/calendar/events works but only for me. The whole documentation is a bit overwhelming A: The answer is yes, but you're right about the documentation... You'll have to take the following steps: Create an application documentation Add the following permission Read and write calendars in all mailboxes for the Microsoft Graph API. Grant the permission for your tenant (the easiest way is through https://portal.azure.com -> Azure AD -> App Registrations -> Your App -> Settings -> Required permissions -> Button Grant Access. Request a token with the client id and secret, this is called the Client credentials flow documentation (optional) Inspect the token on https://jwt.ms to see if the token is correct. Create an event documentation Celebrate your accomplishment with some refreshments.
[ "stackoverflow", "0001108123.txt" ]
Q: How to detect if I can run executables compiled for gcc4 on a box? On a production Linux box without development tools installed (e.g. no headers, no gcc) how do you figure out if it will be able to execute stuff: compiled under gcc4.1.2 as opposed to gcc3.3.3 (there was a change in ELF between version 3 and 4 I think) compiled for 64 bit as opposed to 32 bit executables We have some legacy libraries so we still use gcc3.3.3 but are moving to gcc4.1.2 and colleague was trying to figure out how to detect on new remote box if we can execute stuff compiled with gcc4. Can I check for specific version of libraries or ld-linux.so or something like that instead of actually compiling test app with gcc4 and then try to run it on the new box? A: Seems like there isn't a simple way of looking at version of some of the libraries to determine if gcc4 binaries will run without any problems. I personally have no issues with executing any of the checks mentioned in the other responses, but I was looking for a static way of determining this, so that someone else in my team can check the linux box without giving me 30 minutes presentation about how linux should work ...
[ "stackoverflow", "0053252792.txt" ]
Q: What are differences between JobIntentService and IntentService? I do not understand what difference between those two APIs. I mean when to use the first one. Why is there JobIntentService ? Thanks in advance A: I would recommend to read this article explaining about the difference between intent service and job intent service. When we look for the first time at these terms Service, IntentService, JobIntentService they would look almost similar - in one way or other they would perform some operations in background (which user does not notice). But there is few difference in the way they operate, Service - This runs on the same main thread which invokes this service and performs some background operation. For any long running operation happening on the main thread it is recommended to create a new thread and do the job (eg; Handler) by not impacting the main thread's performance. Drawback : Runs on main thread IntentService - Intent service also helps in doing some long running (indefinite) background task. The only difference is that it creates a new thread to perform this task and does not run on the main thread. Does the given job on it's onHandleIntent. Drawback: The job given to the IntentService would get lost when the application is killed JobIntentService - Job intent service is very similar to IntentService but with few benefits like the application can kill this job at any time and it can start the job from the beginning once the application gets recreated/up. But from Oreo, if the app is running in background it's not allowed to start the service in background. Android asks us to start the service explicitly by content.startForegroundService instead of context.startService and when the service is started within 5 seconds it must be tied to the notification to have a UI element associated with it. Reference : https://developer.android.com/about/versions/oreo/background.html A: Both work same but the only difference with JobIntentService is that JobIntentService gets restarted if the application gets killed while the service was executing. OnHandleWork() get's restarted after the application get's killed.
[ "stackoverflow", "0003905146.txt" ]
Q: Viewstate, have I understood this correctly? Say I have 5 buttons on a page, numbered 1-5. When one is clicked, a value with a viewtate getter/setter assigns this the value of the button clicked. If I am checking for a value in Page_Init() / OnInit(), after the postback has occured, the value will always be empty/null. Is this correct? If so, is there anything else I can do that doesnt require an architectural change? Or something similar I can use to persist changes across post backs (Session[] no good unfortunately). A: ViewState stores the state of the page (page and control settings + custom values stored in ViewState) between post backs. It is just hidden field with serialized (and encrypted) state data. When you set something to ViewState in code behind it is transfered with page markup to the client and posted back to the sever in the next Postback. The page life cycle (between InitComplete and PreLoad) deserializes state from ViewState. That is the reason why you can't access data from ViewState in OnInit.
[ "math.stackexchange", "0000704860.txt" ]
Q: Critical points of multivariable function Im trying to find the critical points a function, but when setting the partial derivatives equal to zero, i cant figure out how to solve them, for this particular function: $\ f(x,y)= -(x^2-1)^2-(x^2y-x-1)^2 $ $\nabla f(x,y)=(-4x^3(y^2+1)+6x^2y+2x(2y-3)-2,-2x^4y+2x^3+2x^2) $ When plugging $\ -4x^3(y^2+1)+6x^2y+2x(2y-3)-2=0 $ into my calculator and trying to solve for $\ x $ i get $\ x(2x^2(y^2+1)-3xy-2y+3)=-1 $ as a result which i don't know what to with. A: From the second equation, we can divide out a $-2x^2$ and it reduces to: $$x^2 y - x - 1 = 0 \implies y = \dfrac{x+1}{x^2}$$ Substitute this into the first and it reduces nicely to: $$-4x(x^2-1) = 0 \implies x = 0, \pm ~ 1$$ We toss out $x = 0$, due to division by zero. Now, solve for the two $y$ values. $$(x,y)=~(−1,0),~(1,2)$$
[ "datascience.stackexchange", "0000000410.txt" ]
Q: Choosing a learning rate I'm currently working on implementing Stochastic Gradient Descent, SGD, for neural nets using back-propagation, and while I understand its purpose I have some questions about how to choose values for the learning rate. Is the learning rate related to the shape of the error gradient, as it dictates the rate of descent? If so, how do you use this information to inform your decision about a value? If it's not what sort of values should I choose, and how should I choose them? It seems like you would want small values to avoid overshooting, but how do you choose one such that you don't get stuck in local minima or take to long to descend? Does it make sense to have a constant learning rate, or should I use some metric to alter its value as I get nearer a minimum in the gradient? In short: How do I choose the learning rate for SGD? A: Is the learning rate related to the shape of the error gradient, as it dictates the rate of descent? In plain SGD, the answer is no. A global learning rate is used which is indifferent to the error gradient. However, the intuition you are getting at has inspired various modifications of the SGD update rule. If so, how do you use this information to inform your decision about a value? Adagrad is the most widely known of these and scales a global learning rate η on each dimension based on l2 norm of the history of the error gradient gt on each dimension: Adadelta is another such training algorithm which uses both the error gradient history like adagrad and the weight update history and has the advantage of not having to set a learning rate at all. If it's not what sort of values should I choose, and how should I choose them? Setting learning rates for plain SGD in neural nets is usually a process of starting with a sane value such as 0.01 and then doing cross-validation to find an optimal value. Typical values range over a few orders of magnitude from 0.0001 up to 1. It seems like you would want small values to avoid overshooting, but how do you choose one such that you don't get stuck in local minima or take too long to descend? Does it make sense to have a constant learning rate, or should I use some metric to alter its value as I get nearer a minimum in the gradient? Usually, the value that's best is near the highest stable learning rate and learning rate decay/annealing (either linear or exponentially) is used over the course of training. The reason behind this is that early on there is a clear learning signal so aggressive updates encourage exploration while later on the smaller learning rates allow for more delicate exploitation of local error surface. A: Below is a very good note (page 12) on learning rate in Neural Nets (Back Propagation) by Andrew Ng. You will find details relating to learning rate. http://web.stanford.edu/class/cs294a/sparseAutoencoder_2011new.pdf For your 4th point, you're right that normally one has to choose a "balanced" learning rate, that should neither overshoot nor converge too slowly. One can plot the learning rate w.r.t. the descent of the cost function to diagnose/fine tune. In practice, Andrew normally uses the L-BFGS algorithm (mentioned in page 12) to get a "good enough" learning rate. A: Selecting a learning rate is an example of a "meta-problem" known as hyperparameter optimization. The best learning rate depends on the problem at hand, as well as on the architecture of the model being optimized, and even on the state of the model in the current optimization process! There are even software packages devoted to hyperparameter optimization such as spearmint and hyperopt (just a couple of examples, there are many others!). Apart from full-scale hyperparameter optimization, I wanted to mention one technique that's quite common for selecting learning rates that hasn't been mentioned so far. Simulated annealing is a technique for optimizing a model whereby one starts with a large learning rate and gradually reduces the learning rate as optimization progresses. Generally you optimize your model with a large learning rate (0.1 or so), and then progressively reduce this rate, often by an order of magnitude (so to 0.01, then 0.001, 0.0001, etc.). This can be combined with early stopping to optimize the model with one learning rate as long as progress is being made, then switch to a smaller learning rate once progress appears to slow. The larger learning rates appear to help the model locate regions of general, large-scale optima, while smaller rates help the model focus on one particular local optimum.
[ "drupal.stackexchange", "0000147159.txt" ]
Q: Practical solution to get an overview of input formats in use I'd like to clean up unused text formats on some D7 sites. So I need to know which formats are not used. I tried using VBO for this, but there is no field Content: Text format I can add there. What's a good way to get an overview of formats in use? I'd be ok with using drush for this and I can settle with just knowing the nodes and blocks that use a specific format (ignoring other places like views headers). I'm not looking for a generic answer like "it's stored in these and these database tables". I'm looking for a practical solution that I can use on many Drupal sites. A: This is stored on a per-field basis. Take a look at your database, any field_data_* table. In those tables, the field_X_format column will contain the input format. A: Use this module: https://www.drupal.org/project/text_formats_report The module pages says don't use this on production.
[ "stackoverflow", "0003022002.txt" ]
Q: JUnit 4 test suite problems I have a problem with some JUnit 4 tests that I run with a test suite. If I run the tests individually they work with no problems but when run in a suite most of them, 90% of the test methods, fail with errors. What i noticed is that always the first tests works fine but the rest are failing. Another thing is that a few of the tests the methods are not executed in the right order (the reflection does not work as expected or it does because the retrieval of the methods is not necessarily in the created order). This usually happens if there is more than one test with methods that have the same name. I tried to debug some of the tests and it seems that from a line to the next the value of some attributes becomes null. Does anyone know what is the problem, or if the behavior is "normal"? Thanks in advance. P.S.: OK, the tests do not depend on each other, none of them do and they all have the @BeforeClass, @Before, @After, @AfterClass so between tests everything is cleared up. The tests work with a database but the database is cleared before each test in the @BeforeClass so this should not be the problem. Simplefied example: TEST SUITE: import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; importy testclasses...; @RunWith(Suite.class) @Suite.SuiteClasses({ Test1.class, Test2.class }) public class TestSuiteX { @BeforeClass public static void setupSuite() { System.out.println("Tests started"); } @AfterClass public static void setupSuite() { System.out.println("Tests started"); } } TESTS: The tests are testing the functionalily on a server application running on Glassfish. Now the tests extend a base class that has the @BeforeClass - method that clears the database and login's and the @AfterClass that only makes a logoff. This is not the source of the problems because the same thing happened before introducing this class. The class has some public static attributes that are not used in the other tests and implements the 2 controll methods. The rest of the classes, for this example the two extends the base class and does not owerride the inherited controll methods. Example of the test classes: imports.... public class Test1 extends AbstractTestClass { protected static Log log = LogFactory.getLog( Test1.class.getName() ); @Test public void test1_A() throws CustomException1, CustomException2 { System.out.println("text"); creates some entities with the server api. deletes a couple of entities with the server api. //tests if the extities exists in the database Assert.assertNull( serverapi.isEntity(..) ); } } and the second : public class Test1 extends AbstractTestClass { protected static Log log = LogFactory.getLog( Test1.class.getName() ); private static String keyEntity; private static EntityDO entity; @Test public void test1_B() throws CustomException1, CustomException2 { System.out.println("text"); creates some entities with the server api, adds one entities key to the static attribute and one entity DO to the static attribute for the use in the next method. deletes a couple of entities with the server api. //tests if the extities exists in the database Assert.assertNull( serverapi.isEntity(..) ); } @Test public void test2_B() throws CustomException1, CustomException2 { System.out.println("text"); deletes the 2 entities, the one retrieved by the key and the one associated with the static DO attribute //tests if the deelted entities exists in the database Assert.assertNull( serverapi.isEntity(..) ); } This is a basic example, the actual tests are more complex but i tried with simplified tests and still it does not work. Thank you. A: The situation you describe sounds like a side-effecting problem. You mention that tests work fine in isolation but are dependent on order of operations: that's usually a critical symptom. Part of the challenge of setting up a whole suite of test cases is the problem of ensuring that each test starts from a clean state, performs its testing and then cleans up after itself, putting everything back in the clean state. Keep in mind that there are situations where the standard cleanup routines (e.g., @Before and @After) aren't sufficient. One problem I had some time ago was in a set of databases tests: I was adding records to the database as a part of the test and needed to specifically remove the records that I'd just added. So, there are times when you need to add specific cleanup code to get back to your original state.
[ "stackoverflow", "0045634778.txt" ]
Q: Control character in a variable for use with grep I'm looking for a way to use a variable inside a grep command to look for ctrl-character 'start of text' (x02). I know that is works with this command. grep $'\x02' $FILE Can anyone explain how I can put the "x02"-part in a variable? A: pattern=$'\x02' grep "$pattern" "$file"
[ "stackoverflow", "0021280314.txt" ]
Q: How do I echo SQL data from database table into a form? I wonder if anyone can help. I am trying to echo some SQL data into a <select> form with each <option> as a different row from the table. For example if my table has two columns 'username' and 'category' and there are two rows for the same username, with the data: "username: test, category: test1." & second row as: "username: test, category: test2." How could I echo 'test1' and 'test2' as two options in a select form? The table name is 'testtable' so my current $sql query is ("SELECT 'category' FROM 'testtable' WHERE 'username = \'$user\'") $user is currently set to the $_SESSION['username'] Code examples would be really helpful and much appreciated. I just cant seem to get them to echo in examples I have found on forums. A: try this <select name="your_select_name" id="your_select_id"> <option value="">Select</option> <?php $username = $_SESSION['username']; $res = mysql_query("SELECT `category` FROM `testtable` WHERE `username` = '$username' ") or die(mysql_error()); while($row = mysql_fetch_assoc($res)) { echo '<option value="'.$row['category'].'">'.$row['category'].'</option>'; } ?> </select> UPDATE 2: For distinct category use this $res = mysql_query("SELECT DISTINCT(`category`) as category FROM `testtable` WHERE `username` = '$username' ") or die(mysql_error()); OR $res = mysql_query("SELECT `category` FROM `testtable` WHERE `username` = '$username' GROUP BY category ") or die(mysql_error());
[ "math.stackexchange", "0002640138.txt" ]
Q: Names for levels of calculus Differentiation can be said to take an expression to a higher order derivative. It seems that different variables inhabit different 'levels' of calculus, some from different areas seem analogous to each other in a way that I am searching for a word for. For example between electrical and mechanical: 1) Charge and displacement 2) Current and velocity 3) Potential difference and force What is the name for the numbers on the left of the list: 'order', 'level'? I haven't found the subject addressed directly anywhere. A: When we deal with derivatives and others releted topic as for example differential equations or Taylor's expansion we use the term "order".
[ "security.stackexchange", "0000000689.txt" ]
Q: I am looking for feedback on Secure Development Lifecycle for Scrum that has been tested? This question is indeed targeting SDL but for Scrum. The A-SDL from Microsoft is nice, but honestly I am not even daring testing it in reality as it seems too academic. I mean what they request for, requires an army of developers! or a dedicated Scrum for Threat Modelling --in case the models are sound! So, I would be thankful if you can share feedback on any SDL approach you have used for Scrum (including A-SDL as you may prove me wrong!) A: Very good question... SDL and Agile are often seen to be at loggerheads, though they dont need to be. In fact, I recently gave a talk at OWASP about this (Agile in general, not necessarily SCRUM), and met with some skepticism at first... but eventually most were convinced of the possibility, at least. I agree about MS's SDL, while I think its one of the best models for large companies, it is "heavy" (as I said in another lightweight SDL question), and has quite a lot of overhead. (though I dont think its academic, it just doesnt apply to most of us). Without setting up a complete SDL here, and without context of knowing your org, I would say these are some of the important elements: Training (which is already a big part of most Agile practices) Map SDL requirements to Agile tasks, and allow the team to complete these themselves. It's not about passing your checkpoints... Non-functional stories added to backlog Completion criteria (sprint / release) Product security requirements -> "ab user" stories Frequency based "Wedges" (not wedgies) Some tasks are one-time requirements, simply need to be completed like any other requirement Some tasks are for every sprint - these are designated "Sprint Completion Criteria" Some are only for public releases (some methodologies seperate the two, some treat every sprint as a public release) - "Release Completion Criteria" Sometimes you might want to do a "Security Spike" - a whole sprint focused on different security aspects MS idea of "Bucket" requirements seems nice, though I've never implemented it and would depend greatly on the culture/needs of the org. (Set up a group of req's with the same classification, or "bucket", and each time you need to choose one from each bucket). This is just the general outline... Let me know if you want more detail. Of course, what goes into each wedge, and what activities must be performed when/how, really depends on knowing your organization, culture, needs, risk profile, etc etc. I find the overriding change in concept from "Classic" SDL (or "Waterfall" SDL) that needs to be accepted is: "Classic” SDL was about control. Agile SDL is about visibility
[ "stackoverflow", "0054934153.txt" ]
Q: Angular Material data Table Data source Im trying to connect backend data to my dataSource and I keep getting an error saying: ERROR Error: Provided data source did not match an array, Observable, or DataSource export class AdminComponent implements OnInit { dataSource: Object; this.data.getUsers().subscribe(data => { this.dataSource = data; }); A: datesource type is wrong. don't specify Object. make sure its either : array, Observable, or DataSource. example: import {Component} from '@angular/core'; export interface PeriodicElement { name: string; position: number; weight: number; symbol: string; } const ELEMENT_DATA: PeriodicElement[] = [ {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'}, {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'}, {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'}, {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'}, {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'}, {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'}, {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'}, {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'}, {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'}, {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'}, ]; /** * @title Basic use of `<table mat-table>` */ @Component({ selector: 'table-basic-example', styleUrls: ['table-basic-example.css'], templateUrl: 'table-basic-example.html', }) export class TableBasicExample { displayedColumns: string[] = ['position', 'name', 'weight', 'symbol']; dataSource = ELEMENT_DATA; }
[ "stackoverflow", "0015593882.txt" ]
Q: need a little change with str_replace I have 2 links like this: http://www.site.com/report/4fbb14 http://www.site.com/4fbb14 so $_SERVER['REQUEST_URI'] for them is like: /report/4fbb14 /4fbb14 I just need to get 4fbb14 I have used $r_url = str_replace("/","",$_SERVER['REQUEST_URI']); But I need it to work for both links, is something like this acceptable? $r_url = str_replace("(/ or report)","",$_SERVER['REQUEST_URI']); A: Much simpler would be $r_url = end(explode('/', $_SERVER['REQUEST_URI'])); That gives you whatever was after the last forward slash
[ "math.stackexchange", "0002667212.txt" ]
Q: counting with constraints I have to count all the chains of $1$ and $2$ of length $n$ where every $1$ is followed by at list $d$ $2$'s. I started by the simpler case where $d=1$ and the number of $1$'s is maximum (i.e it can not be another 1 because it will be less than $d$ from the next or the previous one). I realized in this case the maximum number of 1's is $\lfloor\frac{n}{2}\rfloor$ and in general it is $\lfloor\frac{n}{d+1}\rfloor$. Also when the $n=(d+1)q+1$ the number of chains with maximum number of $1$'s is $1$ for general $n$ and $d$. But I'm stuck in other cases... Naturally, I can count all the chains with $k$ ones, but how I discard those which don't satisfy the restriction? Thanks in advance! A: We interprete the problem as follows: Given is the alphabet $V=\{1,2\}$. Find the number of strings consisting of characters of $V$ of length $n\geq 0$ so that each occurrence of $1$ is followed by at least $d$ characters $2$. We do so by encoding the problem using generating functions. Each of the admissible strings starts with zero or more $2$'s. This can be encoded as \begin{align*} 1+z+z^2+\cdots=\frac{1}{1-z}\tag{1} \end{align*} Each so created string can be followed by zero or more $1$'s, whereby each occurrence of $1$ is replaced by $1$ followed by at least $d$ $2$'s. This can be encoded as \begin{align*} 1+z(z^d+z^{d+1}+\cdots)+z^2(z^d+z^{d+1}+\cdots)^2+\cdots&=\frac{1}{1-z\left(z^d+z^{d+1}\cdots\right)}\\ &=\frac{1}{1-\frac{z^{d+1}}{1-z}}\tag{2} \end{align*} Multiplying (1) and (2) together we get a generating function $A(z)$ where $[z^n]$, i.e. the coefficient of $z^n$, contains the number of admissible strings of length $n$. We obtain \begin{align*} \color{blue}{[z^n]A(z)}&=[z^n]\left(\frac{1}{1-z}\cdot\frac{1}{1-\frac{z^{d+1}}{1-z}}\right)=[z^n]\frac{1}{1-z(1+z^d)}\\ &=[z^n]\sum_{j=0}^\infty z^j(1+z^d)^j\tag{3}\\ &=\sum_{j=0}^n [z^{n-j}](1+z^d)^j\tag{4}\\ &=\sum_{j=0}^n [z^j](1+z^d)^{n-j}\tag{5}\\ &=\sum_{j=0}^n[z^j]\sum_{k=0}^{n-j}\binom{n-j}{k}z^{dk}\tag{6}\\ &=\sum_{j=0}^{\left\lfloor\frac{n}{d}\right\rfloor}[z^{dj}]\sum_{k=0}^{n-dj}\binom{n-dj}{k}z^{dk}\tag{7}\\ &\,\,\color{blue}{=\sum_{j=0}^{\left\lfloor\frac{n}{d}\right\rfloor}\binom{n-dj}{j}}\tag{8} \end{align*} Comment: In (3) we apply the geometric series expansion. In (4) we use the linearity of the coefficient of operator and apply the rule $[z^{p-q}]A(z)=[z^p]z^qA(z)$. We also set the upper limit of the series to $n$ since the exponent of $z$ is non-negative. In (5) we change the order of summation $j\to n-j$. In (6) we apply the binomial theorem. In (7) we observe that we need only multiples of $d$ as exponent. In (8) we select the coefficient accordingly. A: Supposing "chain" means string, i.e. word, then we are dealing with binary words of lenght $n$, where a) all the ones (including the last) shall be followd by at least $d$ two's In this case we can figure out that each one be followed by a "bumper" string of $d$ two's. Assuming that the word contains $q$ ones, that is the same as deleting $qd$ two's from the total length and distributing the $q$ ones into $n-qd$ places. That can be done in $$ \bbox[lightyellow] { N\left( {n,d,q} \right) = \left( \matrix{ n - qd \cr q \cr} \right) = \left( \matrix{ n - qd \cr n - q\left( {d + 1} \right) \cr} \right) } \tag{a.1} $$ where the second writing shall be preferred, because it ensures that $N(n,d,q)$ be null when $n<q(d+1)$, taking for the binomial the definition through falling factorial. Then the answer to your question is $$ \bbox[lightyellow] { N\left( {n,d} \right) = \sum\limits_{\left( {0\, \le } \right)\,q\,\left( { \le \left\lfloor {n/\left( {d + 1} \right)} \right\rfloor \, \le \,n} \right)\;} {\left( \matrix{ n - qd \cr n - q\left( {d + 1} \right) \cr} \right)} \quad \left| {\;0 \le n,d \in Z} \right. } \tag{a.2} $$ where the bounds for $q$ can be generally extended to $0,\,cdots,\, n$, since the actual bounds are intrinsic to the binomial. In the hypothesis (user's comment) that the first one is not preceded by any two, then the position of the first $d+1$ block of letters would be fixed, and the number of ways of obtaining such a configuration would just become $N(n-(d+1),\, d,\, q-1)$. b) all the ones (except the last) shall be followed by at least $d$ two's, i.e. the ones are separated by at least $d$ two's. In this alternative interpretation, it also means that each $1$ occupies $d+1$ consecutive places, except the last, which can be followed by whichever number of $2$'s. Let's place the last one at position $j$, with $1 \le j \le n$. Then we are left with $j-1$ positions where to place $q-1$ ones occupying $d+1$ places. That is the same as telling that we are disposing $q-1$ identical objects into a total of $j-1-(q-1)d$ cells. So the total number of ways of arranging $q$ ones will be $$ \eqalign{ & N\left( {n,d,q} \right) = \sum\limits_{1\, \le \,j\, \le \,n} {\left( \matrix{ j - 1 - \left( {q - 1} \right)d \cr q - 1 \cr} \right)} = \sum\limits_{0\, \le \,k\, \le \,n - 1} {\left( \matrix{ k - \left( {q - 1} \right)d \cr k - \left( {q - 1} \right)\left( {d + 1} \right) \cr} \right)} = \cr & = \sum\limits_{(0\, \le) \,k\, (\le \,n - 1)} {\left( \matrix{ n - 1 - k \cr n - 1 - k \cr} \right)\left( \matrix{ k - \left( {q - 1} \right)d \cr k - \left( {q - 1} \right)\left( {d + 1} \right) \cr} \right)} = \left( \matrix{ n - \left( {q - 1} \right)d \cr n - 1 - \left( {q - 1} \right)\left( {d + 1} \right) \cr} \right) \cr} $$ where the steps are: -1) change index range -2) bring index range inside the sum, as an additional binomial, so as to let $k$ free of bounds -3) apply the "double convolution" formula $$ \eqalign{ & \sum\limits_k {\left( \matrix{ a - k \cr m - k \cr} \right)\left( \matrix{ b + k \cr n + k \cr} \right)} = \sum\limits_k {\left( { - 1} \right)^{\,m - k} \left( \matrix{ m - a - 1 \cr m - k \cr} \right)\left( { - 1} \right)^{\,n + k} \left( \matrix{ n - b - 1 \cr n + k \cr} \right)} = \cr & = \left( { - 1} \right)^{\,m + n} \left( \matrix{ m + n - a - b - 2 \cr n + m \cr} \right) = \left( \matrix{ a + b + 1 \cr n + m \cr} \right) \cr} $$ Now let's check the validity of the above for low values of $q,\, n,\, d$ : - $0$ ones can be placed in $1$ way, checks with ${{n+d} \choose {n+d}}$; - $1$ one can be placed in $n$ ways, checks with ${{n} \choose {n-1}}$; - $2$ ones can be placed in ${{n-d} \choose {2}}$, checks with ${{n-d} \choose {n-2-d}}$; - for $n=q=0$ we get $1$, the empty string; - for $d=0$ we get ${{n} \choose {n-q}}$ as it shall be. Thus we can conclude that $$ \bbox[lightyellow] { N\left( {n,d,q} \right) = \left( \matrix{ n - \left( {q - 1} \right)d \cr n - 1 - \left( {q - 1} \right)\left( {d + 1} \right) \cr} \right)\quad \left| {\;0 \le n,q,d \in \mathbb Z} \right. } \tag{b.1} $$ and of course the answer to your question will be the sum of $N(n,d,q)$ over $q$ $$ \bbox[lightyellow] { N\left( {n,d} \right) = \sum\limits_{\left( {0\, \le } \right)\,q\,\left( { \le \,n} \right)} {\left( \matrix{ n - \left( {q - 1} \right)d \cr n - 1 - \left( {q - 1} \right)\left( {d + 1} \right) \cr} \right)} \quad \left| {\;0 \le n,d \in \mathbb Z} \right. } \tag{b.2} $$ where the bounds for $q$ can be generally extended to $0,\,\cdots,\, n$, since the actual ones are intrinsic to the binomial. Example $n=5,\; d=2,\; q=2 \quad \Rightarrow \quad N(n,d,q)=3$ $$(1,\, 0,\, 0,\, 1,\, 0) ,\; (1,\, 0,\, 0,\, 0,\, 1) ,\; (0,\, 1,\, 0,\, 0,\, 1) $$ $n=6,\; d=2,\; q=2 \quad \Rightarrow \quad N(n,d,q)=6$ $$(1,\, 0,\, 0,\, 1,\, 0,\, 0) ,\; (1,\, 0,\, 0,\, 0,\, 1,\, 0) ,\; (1,\, 0,\, 0,\, 0,\, 0,\, 1) ,\; (0,\, 1,\, 0,\, 0,\, 1,\, 0) ,\; (0,\, 1,\, 0,\, 0,\, 0,\, 1) ,\; (0,\, 0,\, 1,\, 0,\, 0,\, 1) $$
[ "stackoverflow", "0050398334.txt" ]
Q: What is the relationship between Environment and Parameters in Jenkinsfile Parameterized Builds? I recently ran into something of a puzzler while working on some Jenkins builds with a coworker. He's been using params.VARIABLE and env.VARIABLE interchangably and having no issues with it. Meanwhile, I started getting null object errors on one of his calls to a parameter object through the environment on this line of code: if(!deploy_environments.contains(env.ENVIRONMENT_NAME.trim()) || params.INVOKE_PARAMETERS ) { ENVIRONMENT_NAME here is a parameter. I started getting this error: java.lang.NullPointerException: Cannot invoke method trim() on null object This build is executing as a child of another build. The ENVIRONMENT_NAME parameter is passed down to the child from that parent build. He was not seeing this error at all on a different Jenkins master. When I changed the reference above from env.ENVIRONMENT_NAME to params.ENVIRONMENT_NAME the issue went away. I could find no reference to params == env in the Jenkins documentation, so I created a build to try to clarify their relationship. pipeline { agent { label 'jenkins-ecs-slave' } environment { ENV_VARIABLE = 'Environment' } parameters { string(description: 'Parameter', name: 'PARAMETER_VARIABLE', defaultValue: 'Parameter') } stages { stage('Output Parameters'){ steps { script { echo "Environment: ${env.ENV_VARIABLE}" echo "Parameter: ${params.PARAMETER_VARIABLE}" echo "Environment from params: ${params.ENV_VARIABLE}" echo "Parameter from Env: ${env.PARAMETER_VARIABLE}" echo "Inspecific reference ENV_VARIABLE: $ENV_VARIABLE" echo "Inspecific reference PARAMETER_VARIABLE: $PARAMETER_VARIABLE" sh 'echo "Shell environment: $ENV_VARIABLE"' sh 'echo "Shell parameter: $PARAMETER_VARIABLE"' } } } } } The first time I ran this on my Jenkins master, it only included the first four lines (echo env.ENV, echo param.PARAM, echo env.PARAM, echo param.ENV) it succeeded with the following output: [Pipeline] { [Pipeline] withEnv [Pipeline] { [Pipeline] stage [Pipeline] { (Output Parameters) [Pipeline] script [Pipeline] { [Pipeline] echo Environment: Environment [Pipeline] echo Parameter: Parameter [Pipeline] echo Environment from params: null [Pipeline] echo Parameter from Env: null [Pipeline] } [Pipeline] // script [Pipeline] } [Pipeline] // stage [Pipeline] } [Pipeline] // withEnv [Pipeline] } [Pipeline] // node [Pipeline] End of Pipeline Finished: SUCCESS And I thought, "Aha!" Problem solved. They're not the same. However, that box promptly froze up on me afterwards and refused to queue anymore builds. I haven't finished debugging it, but it's not out of line to wonder if that master is just messed up. So I went and ran it on a third Jenkins master we have hanging around. It's at this point I added the additional lines you see in the script above to further clarify. The first time I ran this script on that box, it failed on the "Inspecific reference to $PARAMETER_VARIABLE line" with the following output: [Pipeline] { [Pipeline] withEnv [Pipeline] { [Pipeline] stage [Pipeline] { (Output Parameters) [Pipeline] script [Pipeline] { [Pipeline] echo Environment: Environment [Pipeline] echo Parameter: Parameter [Pipeline] echo Environment from params: null [Pipeline] echo Parameter from Env: null [Pipeline] echo Inspecific reference ENV_VARIABLE: Environment [Pipeline] } [Pipeline] // script [Pipeline] } [Pipeline] // stage [Pipeline] } [Pipeline] // withEnv [Pipeline] } [Pipeline] // node [Pipeline] End of Pipeline groovy.lang.MissingPropertyException: No such property: PARAMETER_VARIABLE for class: groovy.lang.Binding Okay, so far so good. This makes sense. They aren't the same. You can reference Environment variables in echos and shells with out specifically referencing the environment object, but can't do the same with parameters. Consistent, reasonable, I'm good with this. So then I removed the two lines doing the "inspecific reference" and the script succeeded with the following output: [Pipeline] { [Pipeline] withEnv [Pipeline] { [Pipeline] stage [Pipeline] { (Output Parameters) [Pipeline] script [Pipeline] { [Pipeline] echo Environment: Environment [Pipeline] echo Parameter: Parameter [Pipeline] echo Environment from params: null [Pipeline] echo Parameter from Env: Parameter [Pipeline] sh [Environment Testing] Running shell script + echo 'Shell environment: Environment' Shell environment: Environment [Pipeline] sh [Environment Testing] Running shell script + echo 'Shell parameter: Parameter' Shell parameter: Parameter [Pipeline] } [Pipeline] // script [Pipeline] } [Pipeline] // stage [Pipeline] } [Pipeline] // withEnv [Pipeline] } [Pipeline] // node [Pipeline] End of Pipeline Finished: SUCCESS And now I'm completely confuddled. What the hell? I ran it a couple of times just to be sure, and got the same successful output as above, consistently. Granted, none of the previous builds that showed env.PARAM as null had really succeeded in a clean environment (the one that succeeded was in an environment the promptly imploded on me afterwards). So maybe if there's an error in the Jenkins pipeline, it short circuits the loading of parameters into the environment or something? I tried adding echo "$I_SHOULD_FAIL" to the script to force an error in an attempt to reproduce what was I seeing. No dice: [Pipeline] { [Pipeline] withEnv [Pipeline] { [Pipeline] stage [Pipeline] { (Output Parameters) [Pipeline] script [Pipeline] { [Pipeline] echo Environment: Environment [Pipeline] echo Parameter: Parameter [Pipeline] echo Environment from params: null [Pipeline] echo Parameter from Env: Parameter [Pipeline] sh [Environment Testing] Running shell script + echo 'Shell environment: Environment' Shell environment: Environment [Pipeline] sh [Environment Testing] Running shell script + echo 'Shell parameter: Parameter' Shell parameter: Parameter [Pipeline] } [Pipeline] // script [Pipeline] } [Pipeline] // stage [Pipeline] } [Pipeline] // withEnv [Pipeline] } [Pipeline] // node [Pipeline] End of Pipeline groovy.lang.MissingPropertyException: No such property: I_SHOULD_FAIL for class: groovy.lang.Binding So what's going on here? What's the relationship between environment and parameters in Jenkins pipelines? What is that relationship supposed to be and why does it seem to be inconsistent? A: Basically this works as follows env contains all environment variables Jenkins pipeline automatically creates a global variable for each environment variable params contains all build parameters Jenkins also automatically creates an environment variable for each build parameter (and as a consequence of second point a global variable). Environment variables can be overridden or unset but params is an immutable Map and cannot be changed. Best practice is to always use params when you need to get a build parameter.
[ "mathoverflow", "0000077650.txt" ]
Q: A Volterra-type equation Consider the following integral equation $\phi(x) = f(x) + \frac{1}{x}\int_0^x N(x,y)\phi(y)\;dy$, where $f$ and $N$ are continuous and bounded functions. Are solutions $\phi$ of the above equation unique? If so, can one get an estimate of the form $\sup_{(0,x)} |\phi| \leq C \sup_{(0,x)}|f|$ ? Additional info: Assume that $\phi(0)=\phi(1)=f(0)=0$ and that $\|N\|_\infty\geq 1$. I am only interested in a solution (or lack thereof) on the interval $[0,1]$. As a note, without the $\frac{1}{x}$ multiplier, this is a Volterra equation of the second kind and existence/uniqueness of a solution $\phi$ is well-known and the above estimate is indeed satisfied. A: Not in general, since if $N(x,y)=a>1$ then the equation with $f=0$ has the solution $\phi(x)=x^{a-1}$. If, however, $N(0,0)<1$ (assuming as in the question that $N$ is continuous) then one can use the Banach fixed-point theorem (on short intervals) to get a unique solution.
[ "stackoverflow", "0052561739.txt" ]
Q: C# convert RecognizedAudio to text I want my program to convert my RecognizedAudio to text, this is what I have tried RecognizedAudio nameAudio = result.GetAudioForWordRange(result.Words[2], result.Words[result.Words.Count - 1]); MessageBox.Show(nameAudio.ToString()); It outputs this message: System.Speech.Recognition.RecognizedAudio Would anybody be able to help me with this issue? I'd really appreciate it! Thanks in advance A: ToString() is simply the default ToString() method of the class, and calling it actually converts it to string and it is not the method you are looking for. From SpeechRecognizer: You must have add a handler for your class: static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { Console.WriteLine("Speech recognized: " + e.Result.Text); Console.WriteLine(); Console.WriteLine("Semantic results:"); Console.WriteLine(" The flight origin is " + e.Result.Semantics["origin"].Value); Console.WriteLine(" The flight destination is " + e.Result.Semantics["destination"].Value); } The code above is the last lines of code in the page from Microsoft I have refereed.
[ "stackoverflow", "0058096175.txt" ]
Q: Cannot change hidden column state from true to false on setState I'm using devexpress React table and you can hide and show columns via state. I would like to change the state for hidden from true to false but I get an Uncaught Invariant Violation error. I've tried to use setState but doesn't work. class ResultsTable extends Component { constructor(props) { super(props); this.state = { columns: [ { name: 'agent', title: 'Agent' }, { name: 'alertGroup', title: 'Alert Group', hidden:true }, { name: 'manager', title: 'Manager', hidden:true } ], }; } componentDidMount() { this.testAlert(); } testAlert = () => { if (this.props.alertgroupColumn()) { this.setState({ columns: [{ name: 'alertGroup', title: 'Alert Group', hidden:false }] }) } } Hidden should change from true to false. A: I have another alternative to update your state class ResultsTable extends Component { constructor(props) { super(props); this.state = { columns: [ { name: 'agent', title: 'Agent' }, { name: 'alertGroup', title: 'Alert Group', hidden:true }, { name: 'manager', title: 'Manager', hidden:true } ], }; } componentDidMount() { this.testAlert(); } testAlert = () => { if (this.props.alertgroupColumn()) { //---- get the columns from state let columns = JSON.parse(JSON.stringify(this.state.columns)) columns[1].hidden = false this.setState({ columns:columns }) this.setState({ columns: [{ name: 'alertGroup', title: 'Alert Group', hidden:false }] }) } }
[ "stackoverflow", "0008137900.txt" ]
Q: How to change the mouse pointer? I need to change the mouse pointer to the wait cursor. I tried document.body.style.cursor = 'wait'; In my fiddle, my mouse cursor does not change (nor does it change in my main app). I tried a couple methods, but nothing seems to work (IE7 and FF7 tested). How do I change the cursor? I am open to using CSS instead of JavaScript if that works better. For what it is worth...In the final program, I need to change the pointer at the start of an AJAX call and then change it back to the default in the callback. But, this is a simplified example and still does not work. A: I'd create a CSS class: .busy { cursor: wait !important; } and then assign this class to body or whatever element you want to mark as busy: $('body').addClass('busy'); // or, if you do not use jQuery: document.body.className += ' busy'; http://jsfiddle.net/ThiefMaster/S7wza/ If you need it on the whole page, see Wait cursor over entire html page for a solution A: Since there is no text you don't really have a body (in terms of "it has no height"). Try adding some content and then hovering the text: http://jsfiddle.net/kX4Es/4/. You can just use CSS. Or, add it to the <html> element to bypass this <body> constraint: http://jsfiddle.net/kX4Es/3/. html { cursor: wait; }
[ "stackoverflow", "0039745203.txt" ]
Q: The byte equivalent to cut the socket link Normally when I use r = new BufferedReader(new InputStreamReader(receivedSocketConn1.getInputStream())); then I use int nextChar = 0; while ((nextChar=r.read()) != -1) { } Now I am going to use byte level r = new DataInputStream(new BufferedInputStream(receivedSocketConn1.getInputStream())); so the first byte I read is this try { while(true){ if (r.readByte() != 0x7E) // start byte { // ah oh, something went wrong!! receivedSocketConn1.close(); return; } int bodyLen = r.readUnsignedShort(); // message body nature (body length) byte serialNum1 = r.readByte();// message serial number byte[] messageBody = new byte[20]; // message body r.readFully(messageBody); if (r.readByte() != 0x7E) // end byte { // ah oh, something went wrong!! receivedSocketConn1.close(); return; } } } catch (SocketTimeoutException ex) { System.out.println("SocketTimeoutException has been caught"); ex.printStackTrace(); } catch (IOException ex) { System.out.println("IOException has been caught"); ex.printStackTrace(); } finally { try { if ( w != null ) { w.close(); r.close(); receivedSocketConn1.close(); } else { System.out.println("MyError:w is null in finally close"); } } } You see it always goes into the finally block after I do the 7e, thereafter it cuts the link. I would like to keep the link for some time. But before that, I want to run a for loop for the look for the -1 in this scenario. How to I implement that? A: You don't need to handle -1 in this situation. If you read the documentation, it says: InputStream::read() Returns: the next byte of data, or -1 if the end of the stream is reached. DataInputStream::readByte() Throws: EOFException - if this input stream has reached the end. IOException - the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs. The same goes for all of the DataInputStream reading methods. So, all you have to do is read values from the DataInputStream normally and let it throw an exception if the socket gets closed by the peer. You are already doing exactly that (EOFException extends IOException and will be caught in your catch (IOException ex) block). You are over-thinking the problem. That being said, if reading the 0x7E byte is throwing an exception (which readByte() call is failing? Which exception is being thrown?), then you are doing something wrong. For instance, this question is based on code I gave you yesterday for another question, but the code you have shown in this question is incomplete based on the earlier code. That omission would easily cause the second if (r.readByte() != 0x7E) to evaluate as false and close the connection. Try something more like this instead: w = new DataOutputStream(new BufferedOutputStream(receivedSocketConn1.getOutputStream())); r = new DataInputStream(new BufferedInputStream(receivedSocketConn1.getInputStream())); try { while(true) { if (r.readByte() != 0x7E) // start byte throw new RuntimeException("Incorrect start byte detected"); int messageID = r.readUnsignedShort(); // message ID int bodyLen = r.readUnsignedShort(); // message body nature (body length) byte[] phoneNum = new byte[6]; r.readFully(phoneNum); // device phone number int serialNum = r.readUnsignedShort(); // message serial number byte[] messageBody = new byte[bodyLen]; // message body r.readFully(messageBody); byte checkCode = r.readByte(); // check code if (r.readByte() != 0x7E) // end byte throw new RuntimeException("Incorrect end byte detected"); // TODO: validate checkCode if needed... // ... // if (checkCode is not valid) // throw new RuntimeException("Bad checkCode value"); // process message data as needed... } } catch (SocketTimeoutException ex) { System.out.println("SocketTimeoutException has been caught"); ex.printStackTrace(); } catch (EOFException ex) { System.out.println("Socket has been closed"); } catch (IOException ex) { System.out.println("IOException has been caught"); ex.printStackTrace(); } catch (RuntimeException ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } finally { w.close(); r.close(); receivedSocketConn1.close(); }
[ "stackoverflow", "0028761820.txt" ]
Q: android how have the value of edittext auto format itself and calculate-able at the same time I have 2 edittexts and 1 textview. 1 edittext for input the price another one the percentage and the textview will display the result of them both (the price * percentage/100) and i want to make the 1st edittext input(for the price) will change the format of the input and display it on the same edittext with decimal format. For example : edittext1 100 the user type 100 it will just display 100 ,but when the user type one or more number(S) it will add "," every 3 number edittext1 1,000 edittext1 10,000 edittext1 100,000 edittext1 1,000,000 and so on i have the functions, one will autocalculate the value for textview1 , another will convert automatically the input of edittext. However they cant work together because the format for calculation function, it uses int/long/double and for the converter it uses decimalformat . If i use them both the app will crash with javanumberformatexception unable to parse int "1,000"(if we put 1000 into edittext) my function for autocalculate public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.simulasikredit); ethint1 = (EditText) findViewById(R.id.ethint); etpersen2 = (EditText) findViewById(R.id.etpersen); textvDP1 = (TextView) findViewById(R.id.textvDP); etpersen2.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String text1 = ethint1.getText().toString(); String text2 = etpersen2.getText().toString(); long input1 = 0; long input2 = 0; if(text1.length()>0) input1 = Long.valueOf(text1); if(text2.length()>0) input2 = Long.valueOf(text2); if (text1.length() != 0) { long output = (input1 * input2) / 100; textvDP1.setText(""+output); } else if(text2.length() == 0){ textvDP1.setText(""); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); } et stands for edittext, tv stands for textview and makedecimal function public void makedecimal(View v) { ethint1.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); DigitsKeyListener dkl = new DigitsKeyListener(true,true); ethint1.setKeyListener(dkl); ethint1.addTextChangedListener(new TextWatcher(){ private String current = ""; @Override public void afterTextChanged(Editable s) { String userInput=s.toString(); if(!userInput.toString().equals(current)){ ethint1.removeTextChangedListener(this); String cleanString = userInput.replaceAll("[,]", ""); if(cleanString.length()>0){ double parsed = Double.parseDouble(cleanString); String formated = DecimalFormat.getNumberInstance().format(parsed); current = formated; ethint1.setText(formated); ethint1.setSelection(formated.length()); }else{ ethint1.setText(cleanString); ethint1.setSelection(cleanString.length()); } ethint1.addTextChangedListener(this); } this makedecimal is android:onClick from ethint , ethint is the id(these two come from 1 edittext) A: I need to fulfil a similar requirements before where we need to format the number in thousands and also support fractions. My approach is to register a TextWatcher format text every time input changed, and provide a public method to get numeric value by stripping separators, which is quite tricky. My solution also caters for locale-specific separator by utilizing DecimalFormatSymbols class. private final char GROUPING_SEPARATOR = DecimalFormatSymbols.getInstance().getGroupingSeparator(); private final char DECIMAL_SEPARATOR = DecimalFormatSymbols.getInstance().getDecimalSeparator(); ... /** * Return numeric value repesented by the text field * @return numeric value or {@link Double.NaN} if not a number */ public double getNumericValue() { String original = getText().toString().replaceAll(mNumberFilterRegex, ""); if (hasCustomDecimalSeparator) { // swap custom decimal separator with locale one to allow parsing original = StringUtils.replace(original, String.valueOf(mDecimalSeparator), String.valueOf(DECIMAL_SEPARATOR)); } try { return NumberFormat.getInstance().parse(original).doubleValue(); } catch (ParseException e) { return Double.NaN; } } /** * Add grouping separators to string * @param original original string, may already contains incorrect grouping separators * @return string with correct grouping separators */ private String format(final String original) { final String[] parts = original.split("\\" + mDecimalSeparator, -1); String number = parts[0] // since we split with limit -1 there will always be at least 1 part .replaceAll(mNumberFilterRegex, "") .replaceFirst(LEADING_ZERO_FILTER_REGEX, ""); // only add grouping separators for non custom decimal separator if (!hasCustomDecimalSeparator) { // add grouping separators, need to reverse back and forth since Java regex does not support // right to left matching number = StringUtils.reverse( StringUtils.reverse(number).replaceAll("(.{3})", "$1" + GROUPING_SEPARATOR)); // remove leading grouping separator if any number = StringUtils.removeStart(number, String.valueOf(GROUPING_SEPARATOR)); } // add fraction part if any if (parts.length > 1) { number += mDecimalSeparator + parts[1]; } return number; } It's quite tedious to elaborate here so I'll only give a link for your own reading: https://gist.github.com/hidroh/77ca470bbb8b5b556901
[ "stackoverflow", "0005348514.txt" ]
Q: Is it possible to host a ASP.NET website in a wireless adhoc network? I need to set up a server for testing a project. So is it possible to host it on a wireless adhoc network? So how to implement it? A: ASP.NET works on top of HTTP which works on top of TCP. The underlying transport infrastructure does not matter. The only requirement is the client must be able to connect to the TCP port 80 (or any of your choice) on the server.
[ "stackoverflow", "0009230512.txt" ]
Q: Use of expando objects in views? Edit: Seems numerous people think this is a dumb idea, so I would appreciate an explanation of why it's bad? I was trying to make one partial view that could handle a list of any models to display in table format. I was planning on extending it then to allow also take config options to say what columns to display and add extra ones after I figured out the basics. Is there a better way to do this? How does one use a list of expando objects in views? I am trying to make a view that can display a table format of a list of any of my models, and it looks like expando object is a good fit for this, but I can't figure out how to get the iterations properly. I tried using these links: Dynamic Anonymous type in Razor causes RuntimeBinderException, ExpandoObject, anonymous types and Razor but they seem either incomplete or not what what I am doing. Here is my view: @using System.Reflection @model IList<dynamic> <h2>ExpandoTest</h2> @if(Model.Count > 0) { <table> @foreach (dynamic item in Model) { foreach(var props in typeof(item).GetProperties(BindingFlags.Public | BindingFlags.Static)) { <tr> <td> @props.Name : @props.GetValue(item, null) </td> </tr> } } </table> } My controller: public ActionResult ExpandoTest() { IList<dynamic> list = EntityServiceFactory.GetService<UserService>().GetList(null, x => x.LastName).ToExpando().ToList(); return View(list); } Extension method: public static IEnumerable<dynamic> ToExpando(this IEnumerable<object> anonymousObject) { IList<dynamic> list = new List<dynamic>(); foreach(var item in anonymousObject) { IDictionary<string, object> anonymousDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(item); IDictionary<string, object> expando = new ExpandoObject(); foreach (var nestedItem in anonymousDictionary) expando.Add(nestedItem); list.Add(expando); } return list.AsEnumerable(); } The list of expando items are being properly created I can see through debugging, but in the view it says item can not be resolved in the typeof(item) statement and throws the error saying type item cannot be found. If I try item.GetType().GetProperties() that returns nothing. Now I understand that these don't work because the type is dynamic, but how can I dynamically display the properties and values then? A: You can cast a ExpandoObject to an IDictionary, and do something like this: foreach(var prop in item as IDictionary<string, object>) { <tr> <td> @prop.Key @prop.Value </td> </tr> }
[ "askubuntu", "0000763202.txt" ]
Q: Matlab problem on ubuntu 16.04 I have been facing problem in starting up the Matlab. I am getting the following error: MATLAB crash file:/home/user/matlab_crash_dump.4765-1: ------------------------------------------------------------------------ Segmentation violation detected at Tue Apr 26 20:24:15 2016 ------------------------------------------------------------------------ Configuration: Crash Decoding : Disabled Crash Mode : continue (default) Current Graphics Driver: Unknown hardware Current Visual : 0x20 (class 4, depth 24) Default Encoding : UTF-8 GNU C Library : 2.23 stable Host Name : chaos MATLAB Architecture : glnxa64 MATLAB Root : /usr/local/MATLAB/MATLAB_Production_Server/R2015a MATLAB Version : 8.5.0.197613 (R2015a) OpenGL : hardware Operating System : Linux 4.4.0-21-generic #37-Ubuntu SMP Mon Apr 18 18:33:37 UTC 2016 x86_64 Processor ID : x86 Family 6 Model 69 Stepping 1, GenuineIntel Virtual Machine : Java 1.7.0_60-b19 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode Window System : The X.Org Foundation (11803000), display :0 Fault Count: 1 Abnormal termination: Segmentation violation Register State (from fault): RAX = 0000000000000000 RBX = 00007f36d8a660e8 RCX = 00007f36f827ec60 RDX = 0000000000000006 RSP = 00007f3773929e50 RBP = 00007f3773929f70 RSI = 0000000000000000 RDI = 00007f36d8a3c8a8 R8 = 0000000000000030 R9 = 0000000000000004 R10 = 00007f36d8dbcef0 R11 = 00007f36d8a39000 R12 = 00007f370c53e810 R13 = 0000006900000006 R14 = 0000000000000006 R15 = 00007f36d8a3d280 RIP = 00007f378b88056c EFL = 0000000000010206 CS = 0033 FS = 0000 GS = 0000 Stack Trace (from fault): [ 0] 0x00007f378b88056c /lib64/ld-linux-x86-64.so.2+00050540 [ 1] 0x00007f378b889681 /lib64/ld-linux-x86-64.so.2+00087681 [ 2] 0x00007f378b884394 /lib64/ld-linux-x86-64.so.2+00066452 [ 3] 0x00007f378b888bd9 /lib64/ld-linux-x86-64.so.2+00084953 [ 4] 0x00007f3788032f09 /lib/x86_64-linux-gnu/libdl.so.2+00003849 [ 5] 0x00007f378b884394 /lib64/ld-linux-x86-64.so.2+00066452 [ 6] 0x00007f3788033571 /lib/x86_64-linux-gnu/libdl.so.2+00005489 [ 7] 0x00007f3788032fa1 /lib/x86_64-linux-gnu/libdl.so.2+00004001 dlopen+00000049 [ 8] 0x00007f378b60046a /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libut.so+00308330 [ 9] 0x00007f377dc01c25 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_dispatcher.so+00560165 [ 10] 0x00007f377dbf4faa /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_dispatcher.so+00507818 _ZN13Mlm_MATLAB_fn8try_loadEv+00000042 [ 11] 0x00007f377e908de5 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmex.so+00146917 _ZN13Mlm_MATLAB_fn4loadEv+00000037 [ 12] 0x00007f377dbe8685 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_dispatcher.so+00456325 _ZN13Mfh_MATLAB_fn11dispatch_fhEiPP11mxArray_tagiS2_+00000053 [ 13] 0x00007f377cfd1fee /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+05378030 [ 14] 0x00007f377cf00a71 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+04520561 [ 15] 0x00007f377cf017ee /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+04524014 [ 16] 0x00007f377cf0d619 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+04572697 [ 17] 0x00007f377cf0d783 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+04573059 [ 18] 0x00007f377d044b54 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+05847892 [ 19] 0x00007f377ce6386a /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03876970 [ 20] 0x00007f377ced92ce /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+04358862 [ 21] 0x00007f377dc3faea /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_dispatcher.so+00813802 _ZN8Mfh_file16dispatch_fh_implEMS_FviPP11mxArray_tagiS2_EiS2_iS2_+00000762 [ 22] 0x00007f377dc3ffb0 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_dispatcher.so+00815024 _ZN8Mfh_file11dispatch_fhEiPP11mxArray_tagiS2_+00000032 [ 23] 0x00007f377ceafd20 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+04189472 [ 24] 0x00007f377ce5f432 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03859506 [ 25] 0x00007f377ce61612 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03868178 [ 26] 0x00007f377ce67597 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03892631 [ 27] 0x00007f377ce62cff /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03874047 [ 28] 0x00007f377ce63934 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03877172 [ 29] 0x00007f377ced92ce /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+04358862 [ 30] 0x00007f377dc3faea /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_dispatcher.so+00813802 _ZN8Mfh_file16dispatch_fh_implEMS_FviPP11mxArray_tagiS2_EiS2_iS2_+00000762 [ 31] 0x00007f377dc3ffb0 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_dispatcher.so+00815024 _ZN8Mfh_file11dispatch_fhEiPP11mxArray_tagiS2_+00000032 [ 32] 0x00007f3771492edd /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02473693 [ 33] 0x00007f3771493152 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02474322 [ 34] 0x00007f3771427edb /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02035419 [ 35] 0x00007f377142854e /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02037070 [ 36] 0x00007f3771429ddf /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02043359 [ 37] 0x00007f377142f8e0 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02066656 [ 38] 0x00007f377142ad20 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02047264 [ 39] 0x00007f377142ae39 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02047545 [ 40] 0x00007f377142b43c /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02049084 [ 41] 0x00007f377142b608 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02049544 [ 42] 0x00007f377149ce27 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02514471 [ 43] 0x00007f377151eccb /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+03046603 [ 44] 0x00007f377dbe8744 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_dispatcher.so+00456516 _ZN13Mfh_MATLAB_fn11dispatch_fhEiPP11mxArray_tagiS2_+00000244 [ 45] 0x00007f377151c451 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+03036241 [ 46] 0x00007f377ceafd20 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+04189472 [ 47] 0x00007f377ce5f432 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03859506 [ 48] 0x00007f377ce61612 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03868178 [ 49] 0x00007f377ce67597 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03892631 [ 50] 0x00007f377ce62cff /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03874047 [ 51] 0x00007f377ce63934 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03877172 [ 52] 0x00007f377ced92ce /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+04358862 [ 53] 0x00007f377dc3faea /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_dispatcher.so+00813802 _ZN8Mfh_file16dispatch_fh_implEMS_FviPP11mxArray_tagiS2_EiS2_iS2_+00000762 [ 54] 0x00007f377dc3ffb0 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_dispatcher.so+00815024 _ZN8Mfh_file11dispatch_fhEiPP11mxArray_tagiS2_+00000032 [ 55] 0x00007f3771492edd /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02473693 [ 56] 0x00007f37714285c2 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02037186 [ 57] 0x00007f3771429ddf /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02043359 [ 58] 0x00007f377142f8e0 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02066656 [ 59] 0x00007f377142b053 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02048083 [ 60] 0x00007f3771499bb6 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02501558 [ 61] 0x00007f377ce8d6cb /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+04048587 [ 62] 0x00007f377dc01305 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_dispatcher.so+00557829 [ 63] 0x00007f377dbe8744 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_dispatcher.so+00456516 _ZN13Mfh_MATLAB_fn11dispatch_fhEiPP11mxArray_tagiS2_+00000244 [ 64] 0x00007f377ceafd20 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+04189472 [ 65] 0x00007f377ce5f432 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03859506 [ 66] 0x00007f377ce61612 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03868178 [ 67] 0x00007f377ce67597 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03892631 [ 68] 0x00007f377ce62cff /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03874047 [ 69] 0x00007f377ce63934 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03877172 [ 70] 0x00007f377ced92ce /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+04358862 [ 71] 0x00007f377dc3faea /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_dispatcher.so+00813802 _ZN8Mfh_file16dispatch_fh_implEMS_FviPP11mxArray_tagiS2_EiS2_iS2_+00000762 [ 72] 0x00007f377dc3ffb0 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_dispatcher.so+00815024 _ZN8Mfh_file11dispatch_fhEiPP11mxArray_tagiS2_+00000032 [ 73] 0x00007f3771492edd /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02473693 [ 74] 0x00007f37714285c2 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02037186 [ 75] 0x00007f3771429ddf /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02043359 [ 76] 0x00007f377142f8e0 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02066656 [ 77] 0x00007f377142b053 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02048083 [ 78] 0x00007f377151eef0 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+03047152 [ 79] 0x00007f377dbe8744 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_dispatcher.so+00456516 _ZN13Mfh_MATLAB_fn11dispatch_fhEiPP11mxArray_tagiS2_+00000244 [ 80] 0x00007f377151c451 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+03036241 [ 81] 0x00007f377ceaf98f /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+04188559 [ 82] 0x00007f377cec4ca4 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+04275364 [ 83] 0x00007f377cec5b0f /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+04279055 [ 84] 0x00007f377cec6df0 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+04283888 [ 85] 0x00007f377ce41e06 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03739142 [ 86] 0x00007f377ce32005 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03674117 [ 87] 0x00007f377ce606c2 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03864258 [ 88] 0x00007f377ce67597 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03892631 [ 89] 0x00007f377ce62cff /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03874047 [ 90] 0x00007f377ce63934 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03877172 [ 91] 0x00007f377ced92ce /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+04358862 [ 92] 0x00007f377dc3faea /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_dispatcher.so+00813802 _ZN8Mfh_file16dispatch_fh_implEMS_FviPP11mxArray_tagiS2_EiS2_iS2_+00000762 [ 93] 0x00007f377dc3ffb0 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_dispatcher.so+00815024 _ZN8Mfh_file11dispatch_fhEiPP11mxArray_tagiS2_+00000032 [ 94] 0x00007f3771492edd /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02473693 [ 95] 0x00007f37714285c2 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02037186 [ 96] 0x00007f3771429ddf /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02043359 [ 97] 0x00007f377142f8e0 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02066656 [ 98] 0x00007f377142b053 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02048083 [ 99] 0x00007f3771499bb6 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+02501558 [100] 0x00007f377151e71b /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+03045147 [101] 0x00007f377dbe8744 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_dispatcher.so+00456516 _ZN13Mfh_MATLAB_fn11dispatch_fhEiPP11mxArray_tagiS2_+00000244 [102] 0x00007f377151c451 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmcos_impl.so+03036241 [103] 0x00007f377ce8ce60 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+04046432 [104] 0x00007f377ce8c729 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+04044585 [105] 0x00007f377cdce986 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03266950 inCallFcnWithTrap+00000086 [106] 0x00007f377ce5350b /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03810571 [107] 0x00007f377cdcff70 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwm_interpreter.so+03272560 _Z44inCallFcnWithTrapInDesiredWSAndPublishEventsiPP11mxArray_tagiS1_PKcbP15inWorkSpace_tag+00000096 [108] 0x00007f377ee4ab44 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwiqm.so+00908100 _ZN3iqm15BaseFEvalPlugin7executeEP15inWorkSpace_tagRN5boost10shared_ptrIN14cmddistributor17IIPCompletedEventEEE+00000356 [109] 0x00007f3757d9f763 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libnativejmi.so+00870243 _ZN9nativejmi14JmiFEvalPlugin7executeEP15inWorkSpace_tagRN5boost10shared_ptrIN14cmddistributor17IIPCompletedEventEEE+00000307 [110] 0x00007f3757dc5e15 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libnativejmi.so+01027605 _ZN3mcr3mvm27McrSwappingIqmPluginAdapterIN9nativejmi14JmiFEvalPluginEE7executeEP15inWorkSpace_tagRN5boost10shared_ptrIN14cmddistributor17IIPCompletedEventEEE+00000437 [111] 0x00007f377ee45e16 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwiqm.so+00888342 [112] 0x00007f377ee2c484 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwiqm.so+00783492 [113] 0x00007f377ee2fa20 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwiqm.so+00797216 _ZN3iqm3Iqm7deliverERKN10foundation7msg_svc8exchange7RoutingEN5boost10shared_ptrIN14cmddistributor3IIPEEERKN6mlutil10contextmgr5McrIDERKNS7_8optionalINSD_5MvmIDEEENS8_INS2_8eventmgr8EventMgrEEENSC_14cmddistributor13WhenToDequeue13WhenToDequeueEb+00000144 [114] 0x00007f378320af4b /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmlutil.so+03600203 _ZNK14cmddistributor17IIPEnqueueMessage7deliverERKN10foundation7msg_svc8exchange7RoutingE+00000171 [115] 0x00007f378272902c /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwms.so+02924588 _ZN10foundation7msg_svc8exchange12MessageQueue7deliverERKN5boost10shared_ptrIKNS1_8EnvelopeEEE+00000172 [116] 0x00007f3782729ee6 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwms.so+02928358 [117] 0x00007f378270c129 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwms.so+02806057 [118] 0x00007f378270efb9 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwms.so+02817977 [119] 0x00007f378270baad /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwms.so+02804397 [120] 0x00007f3783190ee0 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmlutil.so+03100384 [121] 0x00007f3783191804 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libmwmlutil.so+03102724 [122] 0x00007f3757dba456 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libnativejmi.so+00980054 _ZN14cmddistributor14CmdDistributor21enqueueWithFutureImplIN9nativejmi15FEvalCmdRequestEEEN5boost13unique_futureINS_16CmdRequestTraitsIT_E10ResultTypeEEERKNS4_10shared_ptrIS7_EENS0_14IqmEnqueueTypeEN6mlutil14cmddistributor13WhenToDequeue13WhenToDequeueE+00000262 [123] 0x00007f3757dba682 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libnativejmi.so+00980610 _ZN14cmddistributor14CmdDistributor10executeNowIN9nativejmi15FEvalCmdRequestEEEN5boost10disable_ifINS4_7is_sameIvNS_16CmdRequestTraitsIT_E10ResultTypeEEESA_E4typeERKNS4_10shared_ptrIS8_EE+00000034 [124] 0x00007f3757da6e06 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libnativejmi.so+00900614 _Z17mtMessageDispatchP7JNIEnv_P8_jobject+00000310 [125] 0x00007f3757da7145 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/libnativejmi.so+00901445 _Z17SendMatlabMessageP7JNIEnv_P8_jobjectS2_+00000085 [126] 0x00007f37681bdd98 <unknown-module>+00000000 [127] 0x00007f37681b1233 <unknown-module>+00000000 If this problem is reproducible, please submit a Service Request via: http://www.mathworks.com/support/contact_us/ A technical support engineer might contact you with further information. Thank you for your help. Please help me out. Many thanks in advance. A: Try to install matlab-support,but first you'll need to check whether multiverse is already included or not. sudo gedit /etc/apt/sources.list If not included yet, then add this line deb http://us.archive.ubuntu.com/ubuntu xenial main multiverse Update your system and install the package sudo apt-get update sudo apt-get install matlab-support Then follow the instruction. It works for me. Source : http://installion.co.uk/ubuntu/xenial/multiverse/m/matlab-support/install/index.html
[ "stackoverflow", "0052534591.txt" ]
Q: Gitlab Omnibus: how to rewrite URLs with bundled nginx Current configuration I migrated my GitLab to a new server. As part of the migration, some repositories were reorganized. We have a website that links directly to raw and blob files on GitLab. I'd like to redirect all HTTPS requests from the old URLs to the new ones, for these raw and blob files. I use Gitlab Omnibus package, with the bundled nginx install. I based myself on the accepted answer to this question: Gitlab Omnibus: how to redirect all requests to another domain, which in turn refers to the official GitLab documentation: https://docs.gitlab.com/omnibus/settings/nginx.html#inserting-custom-settings-into-the-nginx-config. Create nginx config directory, because it did not yet exist: sudo mkdir -p /etc/nginx/conf.d/ Create /etc/nginx/conf.d/redirect.conf: . server { server_name gitlab.itextsupport.com; rewrite ^\/itext7\/samples\/(blob|raw)\/master\/(?!samples\/)(.*)$ https://$server_name/itext7/samples/$1/master/samples/$2 permanent; } Edit the configuration file at /etc/gitlab/gitlab.rb to add the following line: nginx['custom_nginx_config'] = "include /etc/nginx/conf.d/redirect.conf;" Rewrite the nginx configuration: sudo gitlab-ctl reconfigure Restart the bundled nginx: sudo gitlab-ctl restart nginx Verify that the bundled nginx includes the redirect file: sudo grep 'redirect.conf' /var/opt/gitlab/nginx/conf/nginx.conf Testing the configuration curl -I https://gitlab.itextsupport.com/itext/tutorial/blob/master/signatures/src/main/java/signatures/chapter4/C4_05_SignWithBEID.java Expected result /samples gets inserted after /blob/master. I expect to see a 301 rewrite to https://gitlab.itextsupport.com/itext/tutorial/blob/master/samples/signatures/src/main/java/signatures/chapter4/C4_05_SignWithBEID.java Actual result 200 OK on the unmodified URL. Ugly hack Add this line to /var/opt/gitlab/nginx/conf/gitlab-http.conf and restart the bundled nginx: rewrite ^\/itext7\/samples\/(blob|raw)\/master\/(?!samples\/)(.*)$ https://$server_name/itext7/samples/$1/master/samples/$2 permanent; By doing it this way, I have verified that my actual rewrite rule itself is correct. Drawback: this line will be lost every time gitlab-ctl reconfigure is run. Question What do I need to change to make the URL rewrite work as expected? Without the ugly hack? Additional information When I run sudo /opt/gitlab/embedded/sbin/nginx -p /var/opt/gitlab/nginx -T, I see two server { } blocks. My working theory so far is that nginx is picking up only the first server block, and ignoring the second one. If I could find a way to merge both server blocks, in a way that is compatible with the configuration file /etc/gitlab/gitlab.rb, then my problem is most likely solved. A: Well, it looks like the answer was staring me in the face in gitlab.rb. One line above nginx['custom_nginx_config'], there is nginx['custom_gitlab_server_config']. I put the include statement there, and removed the server {} brackets around the rewrite rules. This is also described in the GitLab documentation at https://docs.gitlab.com/omnibus/settings/nginx.html#inserting-custom-nginx-settings-into-the-gitlab-server-block: This inserts the defined string into the end of the server block of /var/opt/gitlab/nginx/conf/gitlab-http.conf. So this is what I did: In /etc/gitlab/gitlab.rb, comment out the nginx['custom_nginx_config'] line and add: nginx['custom_gitlab_server_config'] = "include /etc/nginx/conf.d/redirect.conf;" In /etc/nginx/conf.d/redirect.conf, only keep the rewrite line on its own: rewrite ^\/itext7\/samples\/(blob|raw)\/master\/(?!samples\/)(.*)$ https://$server_name/itext7/samples/$1/master/samples/$2 permanent; Reconfigure GitLab: sudo gitlab-ctl reconfigure Restart nginx: sudo gitlab-ctl restart nginx Verify the nginx configuration: sudo /opt/gitlab/embedded/sbin/nginx -p /var/opt/gitlab/nginx -T | tail -n 20 . nginx: the configuration file /var/opt/gitlab/nginx/conf/nginx.conf syntax is ok nginx: configuration file /var/opt/gitlab/nginx/conf/nginx.conf test is successful include /etc/nginx/conf.d/redirect.conf; } # configuration file /etc/nginx/conf.d/redirect.conf: rewrite ^\/itext7\/samples\/(blob|raw)\/master\/(?!samples\/)(.*)$ https://$server_name/itext7/samples/$1/master/samples/$2 permanent; # configuration file /var/opt/gitlab/nginx/conf/nginx-status.conf: server { listen 127.0.0.1:8060; server_name localhost; location /nginx_status { stub_status on; server_tokens off; access_log off; allow 127.0.0.1; deny all; } } Verify the URL rewrite: curl -I https://gitlab.itextsupport.com/itext/tutorial/blob/master/signatures/src/main/java/signatures/chapter4/C4_05_SignWithBEID.java . HTTP/1.1 301 Moved Permanently Server: nginx Date: Thu, 27 Sep 2018 11:32:23 GMT Content-Type: text/html Content-Length: 178 Connection: keep-alive Location: https://gitlab.itextsupport.com/itext/tutorial/blob/master/samples/signatures/src/main/java/signatures/chapter4/C4_05_SignWithBEID.java Strict-Transport-Security: max-age=31536000 One thing I am still curious about: The rewrite line ended up outside the server{} block. The rewrite line uses the $server_name variable. The $server_name variable is defined inside the server{} block. Is that visually confusing because of how the weird way included statements are displayed by nginx -T? Is the rewrite line really inside the server{} block even if it appears to be outside? Why are things oft not as they appear to be, and why is GitLab documentation written in a hermetic language? Alas, these ponderings may forever remain unanswered.
[ "stackoverflow", "0058012369.txt" ]
Q: Set window title from an external thread I want to change the Window Title of my mainwindoThread. In debug mode it works but not when I start the program normal. I think i have to use Qmutex but I am very new in these topic. I tried it with Qmute but I dont know right how to lock and what I have to lock. In my Mainwindow I execute this line: self.menuprojects = class_menuprojects(self) The class will be successfully creaed and on click_insertproject I will execute this: def click_insertproject(self): thread = generate_insert_frame(self.MainWindow) thread.start() And now I want to change my mainthrea mainwindow title to "test" class generate_insert_frame(QThread): def __init__(self, MainWindow): QThread.__init__(self) self.mutex = QMutex() self.MainWindow = MainWindow def run(self): self.mutex.lock() self.MainWindow.setWindowTitle("Test") self.mutex.unlock() A: Data is transferred from the external thread to the GUI using signals. from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtGui import * class generate_insert_frame(QThread): threadSignal = pyqtSignal(str) # <<--- def __init__(self, num=1): super().__init__() self.num = num def run(self): self.threadSignal.emit("Test {}".format(self.num)) # <<--- self.msleep(100) self.stop() def stop(self): self.quit() class MyWindow(QWidget): def __init__ (self): super().__init__ () self.setWindowTitle("MyWindow") button = QPushButton("Start Thread") button.clicked.connect(self.click_insertproject) grid = QGridLayout(self) grid.addWidget(button) self.num = 1 def click_insertproject(self): self.thread = generate_insert_frame(self.num) self.thread.threadSignal.connect(self.setWindowTitle) # <<--- self.thread.start() self.num += 1 if __name__ == "__main__": import sys app = QApplication(sys.argv) window = MyWindow() window.resize(400, 200) window.show() sys.exit(app.exec_())
[ "stackoverflow", "0061792131.txt" ]
Q: How to configure Stackify prefix with tomcat in windows server 2016? I have downloaded stackify prefix on windows x64 server. Installed it with Run as Administrator My java agent file location is C:\Program Files (x86)\StackifyPrefix\java\lib\stackify-java-apm.jar I navigated to my tomcat installation directory, opened C:\Program Files\Apache Software Foundation\Tomcat 9.0_Tomcat91\bin\catalina.bat file and inserted set CATALINA_OPTS=%CATALINA_OPTS% -javaagent:"C:\\Program Files (x86)\\StackifyPrefix\\java\\lib\\stackify-java-apm.jar" just after first set local line. Restarted tomcat server windows service Enabled Prefix .NET Profiler Opened localhost:2012 Can not view tomcat requests. But I can view my IIS requests. What I am missing here? My tomcat version is 9, JDK 1.8, Windows 2016 A: All the steps you followed are ok except one thing. When you attach this java agent with tomcat which is installed as windows service, it does not work. Follow the steps below:- Download tomcat zip version go to catelina.bat file and include set JAVA_HOME=C:\Program Files\Java\jre1.8.0_251 set CATALINA_OPTS=%CATALINA_OPTS% -javaagent:"C:\\Program Files (x86)\\StackifyPrefix\\java\\lib\\stackify-java-apm.jar" configure your server.xml and users run startup.bat voila ! it will work now on localhost:2012
[ "stackoverflow", "0012820275.txt" ]
Q: AWS: Difference between User data and Metadata tags when creating EC2 instance Amazon EC2 instances can be created with 'User Data' (a long string), or metadata tags (a number of key/value pairs). What is the difference between these? Why do these two systems exist in parallel? In particular, I wish to pass certain pieces of custom data (i.e. a connection string and two resource URLs) to an EC2 machine on startup so it can configure itself. Presumably these are best sent as three key/value pairs? A: According to this documentation page, Metadata provided by Amazon and User Data specified by the user: Amazon EC2 instances can access instance-specific metadata as well as data supplied when launching the instances. You can use this data to build more generic AMIs that can be modified by configuration files supplied at launch time. For example, if you run web servers for various small businesses, they can all use the same AMI and retrieve their content from the Amazon S3 bucket you specify at launch. To add a new customer at any time, simply create a bucket for the customer, add their content, and launch your AMI.
[ "stackoverflow", "0038910530.txt" ]
Q: angular2 pseudo selector styling Can I style Pseudo Selector using Angular2. <section class="inner_content person_content backdrop poster" *ngIf="personAllMoviesArray.length > 0"> <div class="personFavouritePoster"></div> <div class="single_column_medium"> {{id}} </div> </section> CSS is section.inner_content.backdrop:before { background-image: url('https://image.tmdb.org/t/p/w1440_and_h405_bestv2/fBFPLjqiLTDW3GWgWIRkhHTwAcb.jpg');} A: you can define a css-class like .has-before:before { background-image: url('https://image.tmdb.org/t/p/w1440_and_h405_bestv2/fBFPLjqiLTDW3GWgWIRkhHTwAcb.jpg'); } and add toggle the class via some toggle variable <section [class.has-before]="toggleVariable" class="inner_content person_content backdrop poster" *ngIf="personAllMoviesArray.length > 0"> <div class="personFavouritePoster"></div> div class="single_column_medium"> {{id}} </div> </section>
[ "stackoverflow", "0028743647.txt" ]
Q: import someModule, instead of clr.AddReferenceToFile("someModule")? I am a python beginner (python 2.7 and ironpython 2.7) and not a programmer. From time to time, I find a code which starts like so: import clr clr.AddReferenceToFile("nameOfmodule") from nameOfmodule import someMethod What is the point of this? Can't we just use: from nameOfmodule import someMethod ? I tried googling but have not really understand the explanation. Thank you for the reply. EDIT: the confusion is not between "from nameOfmodule import someMethod" and "import nameOfmodule.someMethod". I edited the code, so that now it makes more sense. A: You don't need to import clr and AddReferenceToFile with recent versions of Python for .NET, but it still works for backwards compatibility so the examples you're looking at might still use it so they work for a larger number of people. With recent versions, you can treat CLR assemblies as normal Python modules: from nameOfModule import someMethod clr is the Common Language Runtime, provided by Microsoft's .NET framework. So, in your example, the script uses clr so that it can refer to a component written in C# or Visual Basic and made into a library for use with something else. http://pythonnet.github.io/ has some more information.
[ "stackoverflow", "0055255973.txt" ]
Q: Job in rails is being executed :inline despite setting queue_adapter to :sidekiq I was exploring different tutorials on how to set-up and use sidekiq to execute process in the background. I decided to follow this tutorial and follow everything exactly. However, when I start trying to execute the job, nothing is being added in my sidekiq queue and the job executes inline. Like in the tutorial, I was expecting that every time I try to execute the job, it should reflect in my sidekiq however when I do that, it stays like this: while my rails server executes the job itself Here are the codes in the necessary files needed as shown in the tutorial: My Gemfile: # Gemfile.rb source 'https://rubygems.org' git_source(:github) { |repo| "https://github.com/#{repo}.git" } ruby '2.6.0' gem 'rails', '~> 5.2.2' gem 'sqlite3' gem 'puma', '~> 3.11' gem 'sass-rails', '~> 5.0' gem 'uglifier', '>= 1.3.0' gem 'coffee-rails', '~> 4.2' gem 'turbolinks', '~> 5' gem 'jbuilder', '~> 2.5' gem 'semantic-ui-sass', github: 'doabit/semantic-ui-sass' gem 'slim-rails' gem 'chartkick' gem 'groupdate' gem 'faker', :git => 'https://github.com/stympy/faker.git', :branch => 'master' gem 'rest-client' gem 'devise', '~> 4.6', '>= 4.6.1' gem 'sidekiq' gem 'bootsnap', '>= 1.1.0', require: false group :development, :test do gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] end group :development do gem 'web-console', '>= 3.3.0' gem 'listen', '>= 3.0.5', '< 3.2' gem 'spring' gem 'spring-watcher-listen', '~> 2.0.0' end group :test do gem 'capybara', '>= 2.15' gem 'selenium-webdriver' gem 'chromedriver-helper' end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] My job: #generate_random_vehicle_job.rb class GenerateRandomVehicleJob < ApplicationJob queue_as :default def perform(*args) detected_vehicle = DetectedVehicle.new detected_vehicle.detection_time = Faker::Date.between(30.days.ago, Date.today) detected_vehicle.license_plate_text = Faker::Vehicle.license_plate detected_vehicle.camera_id = rand(1..Camera.count) #detected_vehicle = DetectedVehicle.create(detection_time: date, camera_id: camera_id, license_plate_text: license_plate) detected_vehicle.license_plate_image.attach(io: File.open(Rails.root.join('public', 'sample_plate.png')), filename: 'sample_plate.png', content_type: 'image/png') detected_vehicle.vehicle_image.attach(io: File.open(Rails.root.join('public', 'sample_vehicle.jpg')), filename: 'sample_vehicle.jpg', content_type: 'image/jpeg') detected_vehicle.video_footage_snippet.attach(io: File.open(Rails.root.join('public', 'sample_video.mp4')), filename: 'sample_video.mp4', content_type: 'video/mp4') sleep 2 end end My application.rb: # config/application.rb require_relative 'boot' require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module CatchAllApp class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.2 config.active_job.queue_adapter = :sidekiq # No need to run sidekiq and redis server in development #config.active_job.queue_adapter = Rails.env.production? ? :sidekiq : :async # Settings in config/environments/* take precedence over those specified here. # Application configuration can go into files in config/initializers # -- all .rb files in that directory are automatically loaded after loading # the framework and any gems in your application. end end My sidekiq.rb # config/initializers/sidekiq.rb Sidekiq.configure_server do |config| config.redis = { url: 'redis://localhost:6379/0' } end Sidekiq.configure_client do |config| config.redis = { url: 'redis://localhost:6379/0' } end And finally, my controller: def create_random_vehicle GenerateRandomVehicleJob.perform_later redirect_to root_path end I am sure that my redis-server, rails server, and sidekiq are all up and running properly. A: It turned out that my active_job.queue_adapter has been overridden by my config/environment/development.rb as pointed out above by @max pleaner. I just removed the active_job.queue_adapter = :inline and it fixed my problem! :)
[ "stackoverflow", "0020786146.txt" ]
Q: Add log4j maven dependency to war without having it in compile time Our application uses slf4j, but has dependency to slf4j api slf4j over log4j log4j The problem is that very often IDE imports classes from log4j and not from slf4j. Ideally, i want to have only slf4j api as a maven dependency for my application and pack slf4j binding with log4j only at the time i building a war. I found several solutions so far: Add libs to WEB-INF/lib folder. This is bad, because i have no maven dependency control and have to store binary in my repo which is not the best thing to do. Use maven-war plugin with overlays. But as i understand adding dependency to overlay will require to declare dependency (at least as compile) Is it ok to have only dependency for slf4j api? How to package other dependencies to war without declaring them as project dependencies? Thanks! A: Please simply specify dependency to slf4j-log4j in runtime scope. So during compile and test time class from runtime scope will not be available. Also in IDE it shouldn't be visible - I checked it in IntelliJ. Of course all artifacts with runtime scope will be put in WEB-INF/lib directory. Example: ... <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.5</version> <scope>runtime</scope> </dependency> ...
[ "stackoverflow", "0019653018.txt" ]
Q: Get user accessToken with Java login for Facebook I need to get my user_accessToken with Java login. Have i to use the FacebookOAuthResult? If yes, how? I write an Applet for login to Facebook. It works, but i can't get the token. ... String GraphURL = "https://graph.facebook.com/me/friends?&access_token=" + token; URL newURL = URL(GraphURL); HttpsURLConnection https = (HttpsURLConnection)newURL.openConnection(); https.setRequestMethod("HEAD"); https.setUseCache(false); ... //open a connection window like: if(Desktop.isDesktopSupported()) { Desktop.getDesktop().browse(new URI(GraphURL)); } else if(... here to get token. it is right? String getTokenUrl = "https://www.facebook.com/dialog/oauth?client_id=MY_APP_ID&redirect_uri=https%3A%2F%2Fwww.facebook.com%2Fconnect%2Flogin_success.html&response_type=token&display=popup&scope=user_about_me%2Cread_stream%2C%20share_item"; Desktop desktop = Desktop.getDesktop(); desktop.browse(new URL(getTokenUrl).toURI()); URL tokenURL = new URL(getTokenUrl); URLConnection connect = tokenURL.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connect.getInputStream())); String inputLine; StringBuffer bufferr = new StringBuffer(); while ((inputLine = in.readLine()) != null) bufferr.append(inputLine + "\n"); in.close(); token = bufferr.toString(); HttpURLConnection myWebClient = (HttpURLConnection)url.openConnection(); myWebClient.setRequestMethod("HEAD"); myWebClient.setUseCaches(false); //webClient.. try { String gAntwort = myWebClient.getResponseMessage(); if (myWebClient.getResponseCode() != HttpURLConnection.HTTP_OK) { //Not OK //JOptionPane.showMessageDialog(null, conn.getResponseMessage(), "URL Response", JOptionPane.INFORMATION_MESSAGE); } init(); } catch (Exception d){ } A: I do not think there is a way to get a user access token programmatically. Facebook requires the user's consent where the previously logged in user needs to press the "Okay" button in order to get a new access_token. However, there is a way to get an application access token if this is what you intended. public static void main(String[] args) { try { String myAppId = "XXX"; String myAppSecret = "XXX"; String redirectURI = "http://localhost:8080/"; String uri = "https://graph.facebook.com/oauth/access_token?client_id=" + myAppId + "&client_secret=" + myAppSecret + "&grant_type=client_credentials" + "&redirect_uri=" + redirectURI + "&scope=user_about_me"; URL newURL = new URL(uri); ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream is = newURL.openStream(); int r; while ((r = is.read()) != -1) { baos.write(r); } String response = new String(baos.toByteArray()); is.close(); baos.close(); String TOKEN_INDEX = "accesss_token="; String token = response.substring(TOKEN_INDEX.length()-1); //API Call using the application access token String graph = "https://graph.facebook.com/v2.2/" + myAppId + "?access_token=" + token; URL graphURL = new URL(graph); HttpURLConnection myWebClient = (HttpURLConnection) graphURL.openConnection(); String responseMessage = myWebClient.getResponseMessage(); if (myWebClient.getResponseCode() != HttpURLConnection.HTTP_OK) { System.out.println(myWebClient.getResponseCode() + " " + responseMessage); } else { System.out.println(responseMessage); } myWebClient.disconnect(); } catch (Exception e) { System.err.println(e); } } Note that because this request uses your app secret, it must never be made in client-side code or in an app binary that could be decompiled. It is important that your app secret is never shared with anyone. Therefore, this API call should only be made using server-side code. Read here: https://developers.facebook.com/docs/facebook-login/access-tokens#pagetokens BTW, we, at Stormpath support really simple social login integration (Google, Github, Facebook, LinkedIn)
[ "stackoverflow", "0003166154.txt" ]
Q: ASP.NET server-side cache lifetime? I have written a small ASHX handler that uses a small state object that I'd like to persist through the lifetime of a series of requests. I have the handler putting the object in the server-side cache (HttpContext.Current.Cache) and retrieving it at the start of ProcessRequest. How long can I expect that object to remain in the cache? I expect handler instances to come and go, so I wanted something to persist across all of them (until no longer needed as determined by the requests themselves). However, if I have the handler write to the application log when it has to create a new state object due to it not being in the cache, I'm seeing it create it 2-3 times. A: You can specify the lifetime and priority when you add the item to the cache. An item isn't guaranteed to stay in the cache for the entire requested lifetime. For example, if there's memory pressure then the cache might be purged, but setting a higher priority for your item makes it more likely that it will remain in the cache.
[ "stackoverflow", "0043979498.txt" ]
Q: How to create custom basic auth or use two middleware in Laravel I'm using laravel 5.2.45 and I have the following routes Route::group([ 'namespace' => 'Api', 'prefix' => "api", 'middleware' => 'service' ], function() { Route::get('student/{msisdn}/status', 'StudentController@status'); }); my middleware is service so here is my config/service.php <?php return [ 'password' => //password here, 'ip' => //my server ip here, 'url' => [ 'check_status' => 'http://%s/student/api/checkUser?password=%s&msisdn=%s', ] ]; This code works fine according to my requirements, but what i want now is to apply basic authentication without database. I just want a hardcorded username and password (its my requirements, otherwise i would use db). As my middleware is service and how will i apply another middleware basic.auth on it, is it possible to use two middleware ? or combine both service and basic.auth middle ware and create new middleware? any suggestion, tutorial or example code on how can i do that? A: You can add any number of middleware to a route or group of routes. Route::group([ 'namespace' => 'Api', 'prefix' => "api", 'middleware' => ['service', 'auth.basic'] ], function() { Route::get('student/{msisdn}/status', 'StudentController@status'); }); As for authentication without a database, you can create a custom middleware and hardcode the login information there. Apply this middleware to all the routes to enforce the auth. This should get you started. Though you need to convert the filter to a middleware, the code here is pretty straightforward. https://stackoverflow.com/a/28322507/5892849
[ "english.stackexchange", "0000096223.txt" ]
Q: Antecedents of indefinite pronouns Consider the sentence, "Most of the apples are fresh." Is it incorrect to say that apples is the antecedent of the indefinite pronoun most? A: When Donatus listed the Latin Parts of Speech in his Ars Minor, he didn't mention "Quantifier". partes orationis quot sunt? octo. quae? nomen pronomen uerbum aduerbium participium coniunctio praepositio interiectio. How many parts of speech are there? Eight. What are they? Noun Pronoun Verb Adverb Participle Conjunction Preposition Interjection. He didn't mention "Adjective" either, and "Participle" slipped off the Approved List, but that's another story. Of course, this was the 4th century AD, so one shouldn't expect much. However, as it happens, this list (with "Adjective" replacing "Participle" since around the 14th century) is still what's taught in Anglophone schools as the English Parts of Speech. 4th-century science, applied to a language that didn't exist then. There have, however, been some discoveries since the 4th century. One of them is that not all languages are like Latin. In particular, English isn't much like Latin, though it's borrowed about half its vocabulary from Latin, one way or another; however, parts of speech (POS, or Grammatical Categories, as they're called in syntax) are about grammar, not vocabulary, so where the words come from doesn't matter. It's how they're used that counts. One of the grammatical categories that is very prominent in English is the Determiner. Articles are determiners, and so are quantifiers. In an English noun phrase, determiners are placed before prenominal adjectives: [quite a few of the] [big red expensive] houses The first bracketed chunk above is composed of determiners and the second of adjectives; the last word, houses, is the head noun. Quantifiers include numbers (three of the), indefinites (many of the), and universals (each/any/all of the). They don't all use prepositions, they have very complex syntax, and logically, they are related to Modals and Negatives in that they are Operators, elements with a focus on some other element in a clause. This focussed element is said to be "bound" by a quantifier, and is usually stressed in speech. Binding is not quite the same thing as modification, a term usually applied to adjectives, adverbs, and articles; this is semantics, not really syntax. A quantifier can bind a word located quite far away from it, and can be moved around without changing the meaning, something that modifiers can't do easily. All of the boys passed the test = The boys all passed the test. And it's not quite the same thing as pronoun antecedents (Latin for 'coming before'), either. They have their own unique syntax. Executive Summary: Don't depend on Latin when you want to know about English. A: No, apples is not the antecedent of most. Most of is a quantifying pronoun.
[ "apple.stackexchange", "0000381091.txt" ]
Q: Create gigabit bond from 2x100Mbps ethernet I followed the instructions from: Combine Ethernet ports into a virtual port on Mac to create a bind between two 100Mbps Ethernet interfaces. However the bond itself is only a 100Mbps interface. It there a way to make a Gigabit bonded interface to get 200Mbps out of the two interfaces at once? A: This is called link aggregation. First off, to bond two Ethernet ports together, your switch must also support this and have the ports configured to do so. From your description of things, it appears this part was overlooked because you still only have a 100MB connection. Secondly, you can’t get a gigabit link (1Gb) from two 100MB connections. 1Gb = 1000Mb. Two 100Mb links aggregated is 200Mb.
[ "stackoverflow", "0052003215.txt" ]
Q: My fragment doesn't play video/audio links package com.mixlr.www.oco; import android.annotation.SuppressLint; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.media.MediaPlayer; import android.widget.MediaController; import android.widget.VideoView; import static com.mixlr.www.beachradioco.R.layout.fragment_listen; public class ListenFragment extends Fragment { @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(fragment_listen, container, false); VideoView videoView = VideoView.findViewById(R.id.videoView); videoView.setVideoPath("http://edge.mixlr.com/channel/wtrpf"); videoView.start(); return inflater.inflate(fragment_listen, null); } } I am trying to play clip from the link. My fragment in android studio isn't play video/audio link.this s fragmet code please help, its xml file only have video view A: Change your code From View rootView = inflater.inflate(fragment_listen, container, false); VideoView videoView = VideoView.findViewById(R.id.videoView); videoView.setVideoPath("http://edge.mixlr.com/channel/wtrpf"); videoView.start(); return inflater.inflate(fragment_listen, null); To View rootView = inflater.inflate(fragment_listen, container, false); VideoView videoView = rootView.findViewById(R.id.videoView); videoView.setVideoPath("http://edge.mixlr.com/channel/wtrpf"); videoView.start(); return rootView; Update: Make sure you add internet permission in AndroidManifest.xml file <uses-permission android:name="android.permission.INTERNET"/> Bonus: You can add a MediaController which allow you control the playback. These controls should include a seekbar, volume control and a play/pause button. View rootView = inflater.inflate(fragment_listen, container, false); VideoView videoView = rootView.findViewById(R.id.videoView); videoView.setVideoPath("http://edge.mixlr.com/channel/wtrpf"); MediaController mediaController = new MediaController(this); mediaController.setAnchorView(videoView); videoView.setMediaController(mediaController); videoView.start(); return rootView;
[ "wordpress.stackexchange", "0000010544.txt" ]
Q: Post from front-end with post types, categories and taxonomies I am now developing a wordpress site that will be something like a directory. People will be able to submit walkthroughs, advanced reviews, as well as cheat codes for games. We were going to make a different form for each page, but now we've decided that one form with a drop down will be just fine. There doesn't seem to be a good plug in out there, that I can find, which accommodates the fact that each submission needs to be pushed through as a "pending post" but also to a certain post type. For example, the form that we'll use will be set up like this: Game name: <post title> Platform: <Taxonomy> Category: <Category> (role playing, FPS, adventure, etc..) This is a: () Review () Tutorial () Cheat list <this is the post type> Content: <post body> Tags: <tags> [Submit] Upon submission, I need for the review, cheat, or tutorial to be set as a pending post, in the post type chosen from the radio boxes. I'm currently using WP User Front End, but I could probably use any post from front-end form that is suggested for easiest modification. Adding the new fields to the form is easy, making them do stuff is hard! I'd appreciate any help I can get with this, our website sort of revolves around these feature. A: It looks like Gravity Forms can do this. I just did a quick search on the support forums and found this, an answer to someone asking almost exactly the same question as you: Gravity Forms can be used to create custom post types as well as custom taxonomies, however it doesn't do so out of the box. It requires the use of available hooks to tell Gravity Forms to use a custom post type or custom taxonomy instead of the default. By default it uses standard WordPress Posts, Categories and Tags. So yes it is possible, but it does take some custom code. When you are ready to implement this you can search the forums for code examples as many people have done this, or you can post a new post describing what you are trying to do and request some assistance and we can assist you with basic code snippets to get you started. We do plan on creating an Add-On in the future that will make it much easier to create custom post types and use custom taxonomies. A: there are some free plugins that let you submit posts from frontend: TDO mini forms Post From Site One Quick Post and a better paid one would be: Gravity Forms But none of them will give you the flexibility as a custom coding to your needs, and really a post from front end is a matter of displaying a form and processing it ,so following your use case your form would be something like this: <!-- New game Post Form --> <div id="postbox"> <form id="new_post" name="new_post" method="post" action=""> <!-- game name --> <p><label for="title">Game name</label><br /> <input type="text" id="title" value="" tabindex="1" size="20" name="title" /> </p> <!-- game platform assuming that the taxonomy is named platform --> <p><label for="Platform">Platform:</label><br /> <p><?php wp_dropdown_categories( 'show_option_none=Platform&tab_index=4&taxonomy=platform' ); ?></p> <!-- game Category --> <p><label for="Category">Category:</label><br /> <p><?php wp_dropdown_categories( 'show_option_none=Category&tab_index=4&taxonomy=category' ); ?></p> <!-- game post type assuming that the post types are named: review,tutorial,cheat_list--> <p><label for="post_type">This is a:</label><br /> <p><select name="post_type" id="post_type"> <option value="review">Review</option> <option value="tutorial">Tutorial</option> <option value="cheat_list"> Cheat list</option> </select></p> <!-- game Content --> <p><label for="description">Content</label><br /> <textarea id="description" tabindex="3" name="description" cols="50" rows="6"></textarea> </p> <!-- game tags --> <p><label for="post_tags">Tags:</label> <input type="text" value="" tabindex="5" size="16" name="post_tags" id="post_tags" /></p> <p align="right"><input type="submit" value="Publish" tabindex="6" id="submit" name="submit" /></p> <input type="hidden" name="action" value="new_game_post" /> <?php wp_nonce_field( 'new-post' ); ?> </form> </div> and your form processing would be: if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == "new_game_post") { // Do some minor form validation to make sure there is content if (isset ($_POST['title'])) { $title = $_POST['title']; } else { echo 'Please enter a game title'; } if (isset ($_POST['description'])) { $description = $_POST['description']; } else { echo 'Please enter the content'; } $tags = $_POST['post_tags']; // Add the content of the form to $post as an array $new_post = array( 'post_title' => $title, 'post_content' => $description, 'post_category' => array($_POST['cat']), // Usable for custom taxonomies too 'tags_input' => array($tags), 'post_status' => 'publish', // Choose: publish, preview, future, draft, etc. 'post_type' => $_POST['post_type'] // Use a custom post type if you want to ); //save the new post $pid = wp_insert_post($new_post); //insert taxonomies wp_set_post_terms($pid,array($_POST['Platform']),'platform',true); } its not perfect but its a start and you should get the idea. Hope this helps
[ "stackoverflow", "0053173089.txt" ]
Q: Calculating a percentage of 2 columns in my SQL I'm trying to get a percentage of two columns in SQL, but for some reason the division part of the equation is not happening? I'm very new to this, but excited to learn. Thank you for your help! SELECT Jaar, SUM(Bedrag) AS 'Totaal te innen contributie', (SELECT SUM(Bedrag) FROM Betaling WHERE Jaar = Contributie.Jaar) AS 'Totaal geïnde contributie', CAST((SUM(Bedrag) / (SELECT SUM(Bedrag) FROM Betaling WHERE Jaar = Contributie.Jaar) * 100) AS numeric(7,2)) AS 'percentage beta' FROM Contributie GROUP BY Jaar A: We can approach this using a join: SELECT c.Jaar, SUM(c.Bedrag) AS 'Totaal te innen contributie', b.bedrag_sum AS 'Totaal geïnde contributie', 100.0 * SUM(c.Bedrag) / b.bedrag_sum AS 'percentage beta' FROM Contributie c LEFT JOIN ( SELECT Jaar, SUM(Bedrag) AS bedrag_sum FROM Betaling GROUP BY Jaar ) b ON c.Jaar = b.Jaar GROUP BY c.Jaar; The subquery aliased as b replaces the correlated subqueries you had in the select clause.
[ "stackoverflow", "0048882650.txt" ]
Q: Allowing both moving and copying a returned class member I'm trying to write a class that contains a function returning one of the class members, and I want to allow the caller to either move or copy the returned value. I wrote some dummy structs to test this; and after trying different variations, this seems to give me what I want. #include <iostream> using namespace std; struct S { int x; S() : x(10) { cout << "ctor called\n"; } S(const S& s) : x(s.x) { cout << "copy ctor called\n"; } S(S&& s) : x(s.x) { cout << "move ctor called\n"; } // I'm implementing move and copy the same way since x is an int. // I just want to know which one gets called. }; struct T { S s; T() : s() {} S&& Test() && { return move(s); } const S& Test() & { return s; } }; int main() { T t; auto v = move(t).Test(); cout << v.x << "\n"; T t2; auto w = t2.Test(); cout << w.x << "\n"; return 0; } The code prints out (with clang++-5.0 c++14): ctor called move ctor called 10 ctor called copy ctor called 10 Is this an acceptable way to implement what I want? I have a few questions: In the first Test function, I tried both S&& and S for the return type and it doesn't change the output. Does && mean anything for the (non-template) returned type? Is it guaranteed that auto v = move(t).Test() would only invalidate the "moved" member? If struct T had other member variables, can I assume this call wouldn't invalidate them? A: In the first Test function, I tried both S&& and S for the return type and it doesn't change the output. Does && mean anything for the (non-template) returned type? There are little differences: S&& is a (r-value) reference, so object is not yet moved. returning S would move-construct S, so member is moved once the method is called. For move(t).Test();, return ingS&& does nothing whereas returning S would move the member. Is it guaranteed that auto v = move(t).Test() would only invalidate the "moved" member? If struct T had other member variables, can I assume this call wouldn't invalidate them? Yes, only T::s is moved. std::move is just a cast to rvalue.
[ "stackoverflow", "0003773814.txt" ]
Q: CUDA Project Structure The template and cppIntegration examples in the CUDA SDK (version 3.1) use Externs to link function calls from the host code to the device code. However, Tom's comment here indicates that the usage of extern is deprecated. If this the case, what's the correct structure for a CUDA project such as the template example or cppIntegration example? A: Depends what your host code is. If you end up mixing C and C++ you still need the externs. For details see this guide. Update: the content from the above link has been moved [here] (https://isocpp.org/wiki/faq/mixing-c-and-cpp).
[ "stackoverflow", "0007102359.txt" ]
Q: Generate two same random alpha-numeric strings in different java programs I am looking to see if there is a possibility to generate two same alpha-numeric strings in two different java codes. This is for the purpose of secured communication between client and server. Or is there an alternative way to do this? I looked at the usual ways of public private key encryption and related stuff. For my requirement, I do not need such a mechanism as its kind of too much of standard stuff. I am kind of looking for a simple alternative like this. Thanks, Abishek A: I think what you're looking for is akin to a time-synchronized one-time password. A simplistic way to do this is to use the system time, rounded to the nearest, say, 6-second 'pulse' as a seed for a cryptographically secure random number generator (Java provides SecureRandom FWIW). Then, along with a pre-shared 'secret' put that through a one-way cryptographic hash (say, SHA256) to generate your alpha-numeric (hex or base64) string. If you don't need to display/pass along the actual string, then I suppose you can skip the hash step and just use the shared secret and the synchronized time as the IV + key for a cipher applied to the communications stream on both ends. The obvious risk or complication with this approach is keeping the two system clocks in sync. If you use NTP or some other time synchronization protocol, then you have to secure that as well (otherwise you're potentially open to a replay attack). Standard computer clocks are prone to drift (hence the 6-second window) and you have to secure them from tampering as well. (Disclaimer: I am not a security specialist so don't think for a moment that what I've outlined about is completely secure/safe as is.)
[ "stackoverflow", "0060024288.txt" ]
Q: C# IDisposable, Dispose(), lock (this) I am new to programming. I am studying chapter 14 of John Sharp's Microsoft Visual C # Step by Step 9ed. And I do not understand a number of points. The author writes: ...it (finalizer) can run anytime after the last reference to an object has disappeared. So it is possible that the finalizer might actually be invoked by the garbage collector on its own thread while the Dispose method is being run, especially if the Dispose method has to do a significant amount of work. 1) Here I have a first question, how is this possible? After all, GC CLR destroys the object as correctly noticed when there are no more links to it. But if there are no references, how then can simultaneously still work the method of an object (Dispose()) to which nothing else refers? Yes, there are no links, but the method is not completed and GC CLR will try to delete the method object that still works? Further, the author proposes to use lock (this) to circumvent this problem (parallel calls to Dispose ()) and clarifies that this can be detrimental to performance by immediately suggesting another strategy described earlier in the chapter. class Example : IDisposable { private Resource scarce; // scarce resource to manage and dispose private bool disposed = false; // flag to indicate whether the resource // has already been disposed ... ~Example() { this.Dispose(false); } public virtual void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { // release large, managed resource here ... } // release unmanaged resources here ... this.disposed = true; } } //other methods } 2) I understand how it works and why it is needed, but I have problems with mentioning exactly the parallel execution of this.Dispose(true) and this.Dispose(false). Which in the proposed last solution will not allow GC CLR to call the this.Dispose(false) method in its thread in parallel through the destructor in the same way as before while this.Dispose(true) will still be executed previously launched explicitly? At first glance, this is a GC.SuppressFinalize (this) construct, but it should work only after the end of this.Dispose (true), and by condition it is executed long enough for GC CLR in its thread to start the deconstructor and this.Dispose(false). As I understand it, nothing prevents and we get only a repeat of discarding unmanaged resources (files, connections to databases, and so on), but we don’t get a repeat of discarding managed resources (for example, a large multidimensional array). It turns out that it is permissible to repeatedly drop unmanaged resources and it is unacceptable to repeatedly discard managed resources? And this is better than using the lock (this) construct? A: 1) Here I have a first question, how is this possible? After all, GC CLR destroys the object as correctly noticed when there are no more links to it. But if there are no references, how then can simultaneously still work the method of an object (Dispose()) to which nothing else refers? Yes, there are no links, but the method is not completed and GC CLR will try to delete the method object that still works? Imagine that you have a method like: void SomeMethod() { var unmanagedPtr = this.MyPointer; while (/* some long loop */) { // lots of code that *just* uses unmanagedPtr } } Now; this here is arg0, so does exist in the stack, but the GC is allowed to look at when locals are read, and arg0 is not read past the first few instructions; so from the perspective of GC, it can ignore arg0 if the thread is in the while loop. Now; imagine that somehow the reference to this object only exists in arg0 - perhaps because it was only ever transient on the stack, i.e. new MyType(...).SomeMethod(); At this point, yes, the object can be collected even though a method is executing on it. In most scenarios, we would never notice any side effect from this, but: finalizers and unmanaged data is a bit of a special case, beause if your finalizer invalidates the unmanagedPtr that the while loop is depending on: bad things. The most appropriate fix here, is probably to just add GC.KeepAlive(this) to the end of SomeMethod. Importantly, note that GC.KeepAlive does literally nothing - it is an opaque, no-op, non-inlineable method, nothing else. All we're actually doing by adding GC.KeepAlive(this) is adding a read against arg0, which means that the GC needs to look at arg0, so it notices that the object is still reachable, and doesn't get collected. 2) Which in the proposed last solution will not allow GC CLR to call the this.Dispose(false) method in its thread in parallel through the destructor in the same way as before while this.Dispose(true) will still be executed previously launched explicitly? For us to be able to call Dispose(), we clearly have a reference, so that's good. So we know it was reachable at least until Dispose, and we're only talking about Dispose(true) competing with Dispose(false). In this scenario, the GC.SuppressFinalize(this) serves two purposes: the mere existence of GC.SuppressFinalize(this) acts the same as GC.KeepAlive and marks the object as reachable; it can't possibly be collected until that point is reached and once it has been reached, it won't get finalized at all
[ "physics.stackexchange", "0000092933.txt" ]
Q: Time dependence of Lagrangian and Hamiltonian? I am reading a online tutorial about Lagrangian mechanics. In one section, it states that if the kinetic term in Lagrangian has no explicit time dependence, the Hamiltonian does not explicitly depends on time, so $H=T+V$. I just wonder if it is always true that $H=T+V$, why require it has no explicit time dependence? A: I think I cannot completely agree with Torsten Hĕrculĕ Cärlemän's answer (or maybe I did not understand it). However the situation is more complicated. I try to present a more general picture below. A Lagrangian function is a sufficiently regular function $L(t,q, \dot{q})$ (where henceforth $q$ means the $R^n$ column vector $(q^1,\ldots,q^n)^t$ and so on for other similar vaiables). In particular I will focus on Lagrangians with the form: $$L(t,q,\dot{q}) = \frac{1}{2}\dot{q}^t A(t,q) \dot{q} + F(t,q) \cdot \dot{q} - U(t,q) \qquad (1)$$ where $A$ is a non-singular real $n\times n$ symmetric matrix, $F$ is a vector-valued function, and $G$ is a scalar field. The dot in the RHS after $F$ $\cdot$ indicates the $R^n$ scalar product. The form (1), essentially, is the most general case considered in mechanics, where $A$ is also positively defined. That expression even includes the case of non static constraints, or interactions with non-conservative forces (e.g., a given electromagnetic field or inertial forces). In the simplest case: a physical system such that (a) *the system is the statically constrained $^1$ in the inertial reference frame $K$, and (b) it subjected to conservative interactions in $K$, one has: $F=0$ and $A=A(q)$, $U=U(q)$ (absence of $t$), so that: $$L(t,q,\dot{q}) = \frac{1}{2}\dot{q}^t A(t) \dot{q} - U(q) \qquad (1)'$$ In this case the Kinetic energy computed in $K$ is completely defined by $A$, while $U$ describes the potential energy. In the more general case (1), the Kinetic energy may get contributions also from $F$ and $U$, depending on the nature of the chosen coordinates and the chos The Hamiltonian associated with a generic Lagrangian, $L$ is, by definition, the Legendre transform of $L$: $$H(r,q, \dot{q}):= \dot{q} \cdot \nabla_{\dot{q}} L - L(t,q,\dot{q}) \quad (2)$$ (I stick to the Lagrangian formulation without introducing Hamiltonian variables since it is not relevant for this reasoning.) For a Lagrangian of the form (1), $H$ results to be (even if $F\neq 0$!): $$H(t,q, \dot{q}) := \frac{1}{2}\dot{q}^t A(t,q) \dot{q} + U(t,q) \qquad (3)\:.$$ When the Lagrangian has the particular form as in (1)' (and is computed in the reference frame $K$), $H$ coincides to the total mechanical energy of the physical system in K, otherwise its physical meaning has to be investigated case by case. Jacobi's theorem states that, for a generic Lagrangian function (so as in (1) but even more complicated): $$\frac{d }{dt}\left( \left. H\right|_{solutions\: eq. \:of \:motion} \right)= - \frac{\partial L}{\partial t}\:.$$ You see that, computing $H$ along a solution of Eulero-Lagrange's equations, one finds a constant whenever $L$ does not depend explicitly on time. In this case $H$ is called Jacobi's constant of motion. However it does not coincide, in general, with the total mechanical energy of the system. It happens when all forces are conservative and the coordinates hare suitably chosen so that (1)' holds true. Here is an instructive example. Consider a reference frame $K$ rotating with uniform angular velocity directed along $z$ with respect to an inertial frame $K_0$. Let $\Omega$ be the magnitude of that angular velocity. Suppose that a point $p$ with mass $m>0$ is constrained to stay on a smooth vertical ring, with radius $R$, at rest with $K$ in the plane $xz$ and centred on the origin of $K$. There are no forces acting on $p$, barring the irrelevant reaction due to the smooth constraint. We exploit the angle $q:= \theta$ ($\theta =0$ is the $x$ axis in $K$) to describe the position of $p$. Moreover we use the Lagrangian evaluated with respect to $K_0$ (in order to disregard the inertial forces that instead appear in $K$). With some elementary trigonometry, we have: $$L(t, q, \dot{q}) = (Kin.\: Energy \: in\: K) = \frac{mR^2}{2}\dot{q}^2 + \frac{mR^2\Omega^2}{2}\cos^2 q\:.$$ This Lagrangian verifies the hypotheses of Jacobi's theorem, so the Hamiltonian function: $$H(t,q, \dot{q}) = \frac{mR^2}{2}\dot{q}^2 - \frac{mR^2\Omega^2}{2}\cos^2 q\qquad (4)$$ is conserved in time along any dynamical evolution of the point $p$. What is the meaning of $H$? It is not the mechanical energy in $K_0$, that is $L$ itself and $L\neq K$. Moreover that energy cannot be conserved for physical reasons: Because one has to supply energy to the system to maintain the uniform rotation in $K_0$ independently on the motion of $p$ along the ring. The meaning of that $H$ constructed out of the Lagrangian evaluated in $K_0$, but using coordinates at rest with $K$, is the mechanical energy in $K$. Indeed: The second term in the RHS of (4) is nothing but the potential energy of the centrifugal force. in $K$, Coriolis' force can be neglected as it is normal the the ring so its work vanishes. There are no further inertial forces in $K$ and, as already noticed, the reaction due to the ring dissipates no energy as it is normal to the ring itself like Coriolis' force. The first term in (4) is just the kinetic energy of $p$ in $K$. Footnotes: (1) for "statically constrained in the reference frame $K$" I mean that the Lagrangian coordinates $q^1,\ldots, q^n$ are chosen as follows. The position vector $\vec{x}_i$,in the rest space of the reference frame $K$, of the generic $i$th point of mass of the system, can be written as $\vec{x}_i= \vec{x}_i(q^1,\ldots,q^n)$ without any explicit dependence on time. In general, in fact one could have a time dependence $\vec{x}_i= \vec{x}_i(q^1,\ldots,q^n)$, if in $K$ the constraints depend on time. For instance a point $p$ requested to belong to a smooth curve with an assigned motion in $K$. A: The Hamiltonian has the very legal definition that it is the Legendre transform of the Lagrangian function. So, in any physical case to find the Hamiltonian of a system, you have to take $L = T - V$ and then perform the ritualistic Legendre transform process shifting coordinates from $q,q'$ to $q,p$. The time symmetry of the system leads to the conservation of the so called Jacobian function and NOT the Hamiltonian . the Hamiltonian will however be the total mechanical energy if thesystem is conservative and in this case the Jacobian function also equals the total mechanical energy. The Jacobian is the mechanical one and not the mathematical one. Ref Goldstein.
[ "math.stackexchange", "0002263853.txt" ]
Q: Parametrization of two surfaces $\frac{x^2}{a^2}-\frac{y^2}{b^2}-\frac{z^2}{c^2}=1$ and $\frac{x^2}{p}+\frac{y^2}{q}=2z$. Can someone please help me to parametrize the following surfaces in terms of hyperbolic(for second it might not be possible but i need some more convenient set of parametric equation than mine ) and trigonometric functions $$\frac{x^2}{a^2}-\frac{y^2}{b^2}-\frac{z^2}{c^2}=1 $$ and $$\frac{x^2}{p}+\frac{y^2}{q}=2z$$ I have tried to do but the set of parametric equations I got were too complicated as I have to use those in some further calculation which makes the result very ugly. For first equation the set of parametric equations is: $$x=a\sqrt{1+\frac{u^2}{c^2}}\cos v, \ \ y=b\sqrt{1+\frac{u^2}{c^2}}\sin v \ \ z=u$$ and for second: $$x=\sqrt{2pu} \cos v ,\ \ y=\sqrt{2qu} \sin v, \ \ z=u $$ A: $$ \frac{x^2}{a^2} - \frac{y^2}{b^2} - \frac{z^2}{c^2} = 1 $$ Try \begin{align} x &=& a\cosh u \\ y &=& b\sinh u \cos v \\ z &=& c\sinh u \sin v \end{align} Then \begin{eqnarray} \frac{x^2}{a^2} - \frac{y^2}{b^2} - \frac{z^2}{c^2} &=& \cosh^2 u -(\sinh^2u\cos^2v + \sinh^2u\sin^2v) \\ &=& \cosh^2 u - \sinh^2 u \\ &=& 1 \end{eqnarray} $$ \frac{x^2}{p} + \frac{\color{red}{y}^2}{q} = 2z $$ Try \begin{align} x &=& \sqrt{2up}\cos v \\ y &=& \sqrt{2uq}\sin v \\ z &=& u \end{align} In this case \begin{eqnarray} \frac{x^2}{p} + \frac{y^2}{q} &=& \frac{2 u p}{p}\cos^2v + \frac{2 u q}{q}\sin^2 u = 2u \\ &=& 2z \end{eqnarray}
[ "stackoverflow", "0052688432.txt" ]
Q: Thyme, Spring: stuck on creating a single item view I have successfully implemented adding a visit and showing a list of all visits, but now I'm stuck on creating a view for a single visit. My findById function works: logger.info("Visit id 2 -> {}", repository.findById(2)); Visit id 2 -> DentistVisitDTO[id='0', dentistName='Mait Kuusevaik', visitTime='2018-10-12T12:15'] And when I click on a list item it sucessfully redirects to a url using ID (i.e "/results/1" and so on. Is there a way I can use the ID from the URL and somehow render the item on the page using findById()? I'm new to Spring and Thyme. public DentistVisitDTO findById(long id) { return jdbcTemplate.queryForObject("SELECT * FROM DENTIST_VISIT where id=?", new Object[] { id }, new BeanPropertyRowMapper<DentistVisitDTO>(DentistVisitDTO.class)); } A: You can use the @RequestMapping annotation of SpringMVC/SpringWeb to get the id attribute from the URL: import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping(value="/results/{id}", method=RequestMethod.GET) public String detail(@PathVariable(value="id") String id, Model model) { DentistVisitDTO dentistVisit = repository.findById(id); System.out.println("GET /results [" + id + "]"); model.addAttribute("dentistVisit", dentistVisit); return "details"; }
[ "stackoverflow", "0007285941.txt" ]
Q: classic asp site randomly hangs IIS6 We have a classic ASP site that connects to a SOAP server. We have not been able to figure out what causes the website to hang. When we see that the website is hanging we simply restart the soap server and the website works fine(until the next time it hangs). I want to mention that when the website hangs I can get to any page on the server that has .html or .htm extension, but any page that has an .asp extension will simply clock. A: Fire up performance monitor, select Active Server Pages category and watch the Requests Executing counter. You will likely see that over time this increases. You have threads hanging waiting for incomplete calls to the SOAP Server. Eventually ASP runs out of threads (usually 25 threads per CPU). After that subsequent requests to ASP get queued waiting for a thread to come free, which it never does.
[ "money.stackexchange", "0000110329.txt" ]
Q: Does Internal Revenue Code section 1031 enable perpetual depreciation to offset income? I've recently come across Internal Revenue Code section 1031, which as I understand it allows me to postpone paying taxes on income from the sale of an investment property, so long as I purchase a similar investment property of equal or greater value within 180 days. From wikipedia, this specific section stuck out to me (emphasis mine): This would result in a gain of $50,000, on which the investor would typically have to pay three types of taxes: a federal capital gains tax, a state capital gains tax and a depreciation recapture tax based on the depreciation he or she has taken on the property since the investor purchased the property. If the investor invests the proceeds from the $250,000 sale into another property or properties (without touching the proceeds and using a Qualified Intermediary), then he would not have to pay any taxes on the gain at that time. But when I purchase a new investment property with the money from the sale of the old investment property, wouldn't that new property begin its depreciation schedule anew, allowing me to once-again depreciate that property against my income for the next 27.5 years? If so, that means that I'm getting the benefit of depreciation again. Would that mean I could then sell (exchange) the second property for a third, once-again resetting the depreciation schedule on a new property? If not, can someone explain the reason why not? I'm expecting that this isn't possible as it seems too good to be true, but I can't find any details explaining why it's not possible. A: As you say, you do get to "restart" your depreciation schedule on the new property, however, your depreciable basis from the first property follows you to the next. I'm not an accountant, so caveat emptor, but my understanding is as follows: If you buy property 1 for $50,000, own it for a few years, and during that time you deducted $10,000 of depreciation, your new taxable basis on the property is $40,000 (50k-10k). If you sell it for $75k without doing a 1031 exchange, you owe taxes on your gain - the difference between your sale price, and the adjusted tax basis. So your taxable gain would be $75k-$40k -> $35k. Assuming a 15% capital gains rate, you'd owe $5,250 in gains taxes. If instead you do a 1031 exchange and buy a new property, you pay no taxes immediately, but your tax basis on the new property starts at your previous property's tax basis of $40k. So when you eventually sell outside of a 1031 exchange, your tax bill will account for all of the gains from the entire chain of properties. You don't avoid the taxes, but can defer them, possibly for a very long time.
[ "stackoverflow", "0001561108.txt" ]
Q: How to deploy a hotfix in a ClickOnce application? I recently discoverd that there is a bug in the dutch .Net assembly that effectively breaks NavigationWindows on dutch vista SP1 or higher. See for details this link A hotfix is available, but how can I distribute this with my ClickOnce application? I am appalled that this situation, that seems to be known since february, has not been remedied. I am also puzzled: any dutch vista computer running SP1 or higher will crash on a wpf Navigation apllication, so there should be more outcry about it. Is no one writing Navigation Programs? A: I don't think there is any way to deploy a hotfix as part of a ClickOnce application as it would violate the entire idea of click once. That is to be a zero impact installation environment. What you could do though, is add a section to your program which checks for the particular flaw and then pops up a message box / form, requesting the user to deploy a particular hot fix. Including a link should make the process pretty straight forward. Not an ideal solution but it should help to alleviate your particular problem.
[ "meta.stackexchange", "0000248496.txt" ]
Q: Does it make sense for the required number of close votes to be a static number? Right now engineering.SE is early in its beta phase. We have received many questions which are unquestionably bad and for which the best response would be swift closure (examples: here, here, and here). All of the questions have now been closed but in some cases the process took more than 2 days due to the low number of high rep users. Contrast this to a more developed site like physics.SE where 5 high rep users represent ~1% of the users with more than 1,000 reputation and ~0.01% of the total number of users. This group of 5 people gets to speak for the entire community in terms of what questions are appropriate on the site. Would it make more sense to have the required number of close votes scale by the total number of users? The scaling doesn't have to be linear, perhaps 2-3 more people for every order of magnitude of growth in the active userbase. A: The number of questions coming in also grows with the number of users. If this is multiplied by increasing number of close votes per question, the growth would become superlinear. On some large sites with many questions coming in (Stack Overflow and Ask Ubuntu come to mind) there are already not enough closevoters to handle the questions. To complicate things further, the number of users who actively close questions is not nearly as large as the number of users (even those with the privilege to close). A major factor in close backlog at Engineering was that you did not have moderators back then. But now you do. This group of 5 people gets to speak for the entire community in terms of what questions are appropriate on the site. No, they speak for themselves. Their names are right there in the closure banner. If others disagree, they will reopen. A: I guess my one question is, why? I see the reasoning in theory, but in practice I have no complaints about how things work. Let's go over the numbers, right quick. Problem Statement I'd like to know how the time it takes for questions to get closed varies based on the size of a site in the Stack Exchange network. Setup I ran a query to test the amount of time it takes for questions to be closed across five network sites. As is always the case when people try to run queries like this, there are some significant biases in the data that need to be accounted for: Deleted questions (the result of "truly successful" closures) do not count Questions that are closed then reopened count once Questions that are closed, reopened, then closed again count twice Data is cached and only updated weekly (not really a big deal for this) That said, I don't believe any of those to be a major hindrance in comparing the sizes of sites to the time it takes to close them. The five sites a chose were, in no particular order: Stack Overflow Startups The Workplace Code Review Super User Approach In order to find an answer to my problem statement, I ran a query to find, for each close (given the aforementioned limitations), how many hours it took between posting the question and having that close be successful. I grouped on those results, and created a table of each number of hours, and the associated number of closures on each site. Finally, I then found for each hour x, the percentage of all closed questions which were closed in x or fewer hours. Data I reviewed all data since Startups (I'm a mod there, information bias) went to public beta, on August 18th of 2014. These were the total counts of recognized closed questions. Startups Stack Overflow The Workplace Code Review Super User 45 52,752 825 435 2,190 I don't know why the last three are the same, and would appreciate clarification. Maybe all of this is nonsense, if my query was. For the first day (24 hours), these were the data. I've marked each site with two asterisks when they crossed over 50%. Hours Startups Stack Overflow The Workplace Code Review Super User 0 12% 30% 1% 36% 10% 1 21% 46% 6% ** 59% 18% 2 33% ** 53% 10% 68% 21% 3 37% 59% 14% 73% 24% 4 37% 63% 16% 77% 26% 5 37% 67% 20% 80% 27% 6 40% 70% 23% 82% 29% 7 40% 72% 25% 83% 30% 8 44% 74% 28% 84% 31% 9 49% 76% 30% 85% 32% 10 ** 53% 78% 32% 86% 34% 11 56% 79% 34% 87% 35% 12 56% 81% 36% 88% 36% 13 58% 82% 37% 89% 37% 14 58% 83% 40% 89% 38% 15 58% 83% 41% 89% 40% 16 60% 84% 43% 90% 41% 17 60% 85% 45% 91% 42% 18 63% 85% 48% 92% 43% 19 65% 86% 49% 92% 44% 20 65% 86% ** 51% 92% 46% 21 70% 87% 53% 92% 47% 22 70% 87% 54% 93% 48% 23 72% 87% 56% 93% 49% 24 72% 87% 57% 93% ** 50% Also, of course, very important is the number of users who can vote to close. I also retrieved this data from SEDE. Asterisks indicate betas, with lowered reputation thresholds. *Startups Stack Overflow The Workplace *Code Review Super User 24 26,256 98 483 515 Discussion I think the number at the 24-hour mark is the most relevant, because that's the time by which all users will have had some opportunity to see the question. I would expect slower closes for questions in the middle of the night (timezones permitting). Given these data, I don't see any viable correlation between the number of users on a site and questions getting closed too slowly or quickly. That seems to be a factor dependent more on the culture of the site than its sheer mass of users. I hypothesize that this might be the result of the natural increase in post quantity. In other words, where there are more users, there are more posts to moderate, and vice-versa. Because of that, I think scaling the number of required votes would fix a problem that is already intrinsically fixed by definition. As Famous Blue Raincoat mentioned, the assistance of moderators to pick up the slack on smaller sites tends to make up for the lack of users with privileges. By the time there are enough posts to overwhelm the moderators, in theory, there are enough users with moderation privileges.
[ "softwareengineering.stackexchange", "0000096478.txt" ]
Q: Dealing with coworkers when developing, need advice I developed our current project architecture and started developing it on my own (reaching something like, revision 40). We're developing a simple subway routing framework and my design seemed to be done extremely well - several main models, corresponding views, main logic and data structures were modeled "as they should be" and fully separated from rendering, algorithmic part was also implemented apart from the main models and had a minor number of intersection points. I would call that design scalable, customizable, easy-to-implement, interacting mostly based on the "black box interaction" and, well, very nice. Now, what was done: I started some implementations of the corresponding interfaces, ported some convenient libraries and wrote implementation stubs for some application parts. I had the document describing coding style and examples of that coding style usage (my own written code). I forced the usage of more or less modern C++ development techniques, including no-delete code (wrapped via smart pointers) and etc. I documented the purpose of concrete interface implementations and how they should be used. Unit tests (mostly, integration tests, because there wasn't a lot of "actual" code) and a set of mocks for all the core abstractions. I was absent for 12 days. What do we have now (the project was developed by 4 other members of the team): 3 different coding styles all over the project (I guess, two of them agreed to use the same style :), same applies to the naming of our abstractions (e.g CommonPathData.h, SubwaySchemeStructures.h), which are basically headers declaring some data structures. Absolute lack of documentation for the recently implemented parts. What I could recently call a single-purpose-abstraction now handles at least 2 different types of events, has tight coupling with other parts and so on. Half of the used interfaces now contain member variables (sic!). Raw pointer usage almost everywhere. Unit tests disabled, because "(Rev.57) They are unnecessary for this project". ... (that's probably not everything). Commit history shows that my design was interpreted as an overkill and people started combining it with personal bicycles and reimplemented wheels and then had problems integrating code chunks. Now - the project still does only a small amount of what it has to do, we have severe integration problems, I assume some memory leaks. Is there anything possible to do in this case? I do realize that all my efforts didn't have any benefit, but the deadline is pretty soon and we have to do something. Did someone have a similar situation? Basically I thought that a good (well, I did everything that I could) start for the project would probably lead to something nice, however, I understand that I'm wrong. A: Refactor mercilessly to get out of the mess! Take the coding style that accounts for the most part of the usable style and use it for this project. Worst thing is, that you have to roll back to revision 40, and your programmers had a 12 day training session, that gave them a better understanding of the subject. If your programmers have that much to learn about clean coding, the twelve days are the least of the delays you will have. A: Paraphrasing your question - "I went away for a couple of weeks and disagree with what my team did when I was gone, how do I make them do what I want when I am not here?" I put it to you that this is not a technical problem, it's a management problem. My take (Please forgive me if I am wrong) is that you dictate the technical solution to an army of minions, who for some reason either cannot or do not agree with or understand your solution. If 12 Days is all it took to do so much damage to your design, there must be a reason. Is the design fragile? s it over engineered? or did the team just do it out of spite? What are your deadlines and deliveries like? Tight? were they just trying to meet one? One case I have seen this the technical lead was so far ahead of the game that the average developer (me) could not keep up. The technical lead failed to design commercially viable code, as he was the only one who could maintain it. If a grad developer cannot maintain it, it's too complex for the commercial world. All others cases, it was just plain lack of people management skills on the management side. The team dynamics are broken. You can (as suggested by others) spend time refactoring the mess and have to do it all again next time you take leave. You may need to up-skill your team members, but I believe you need to fix the team dynamics first, as they appear to have enough skills to get work done, no matter how ugly you believe it is. A: Pair. What you're describing is a lot of doing it right, technically, solo. Yes, you tried to document, tried to impose standards - but you (apparently) failed to communicate. Well, your team has just communicated to you, rather resoundingly. They said, "Hey, Yippie - you're not communicating!" The most powerful form of communication I know is pairing. Pair. Until they get it, or until they persuade you to do it different.
[ "stackoverflow", "0029291997.txt" ]
Q: Filter of two values for same parameter In AngularJS I want to know if it is possible to filter data of a view column using two possible values. So...if I pass a value of a parameter to a page's controller, I want to limit the data to particular values..... Data: Product Status Item 1 Active Item 2 Planned Item 3 Completed Item 4 Cancelled if I want only one value, I can pass routeParams such as filterCol, filterVal like so the following would only show items that are Active: /programs/status/Active/ app.controller('AllItemsController', function($scope,$http,$rootScope,$routeParams){ $scope.tableFilter = {}; if($routeParams.filterCol && $routeParams.filterVal){ $scope.tableFilter[$routeParams.filterCol] = $routeParams.filterVal; } }); My XML looks similar to: <table class="table table-bordered table-condensed table-hover" ts-wrapper <thead> <tr> <th ts-criteria="itmName | lowercase">Item Name</th> <th ts-criteria="status">Status</th> </tr> <tr> <th><input type="text" class="form-control input-sm" ng-model="tableFilter.itmName"></th> <th><input type="text" class="form-control input-sm" ng-model="tableFilter.status"></th> </tr> </thead> <tbody> <tr ng-repeat="it in allItemData | filter: tableFilter" ts-repeat "> <td>{{it.itmName}}</td> <td>{{it.status}}</td> </tr> </body> </table> Now, how can I change the controller if I want to send a value such as 'ActPlan' and to show all items that are Active or Planned? (such as: /programs/status/ActPlan/) I think I somehow have to change how $scope.tableFilter is set (by checking the value of $routeParams.filterVal), but I can't figure how to set the tablefilter and couldn't find an example to help me. I tried setting it equal to ['Active, Planned'], but that didn't bring anything up. A: If you have several condition, you can just use a filter function, like this thread.
[ "stackoverflow", "0048085454.txt" ]
Q: Plotting quadrants with axvspan I am trying to plot four colored quadrants on a plot with a range of [-0.2,1.4] and [-0.2,1.4]. The issue is I'm having trouble trying to line up the y axis coordinates of the quadrants using plt.axvspan: roc_t = 0.43652219 roc_v = 0.82251961 plt.figure() plt.figure(figsize=(15,12)) plt.xlim(-0.2,1.4) plt.ylim(-0.2,1.4) plt.scatter([nTPredict], [nVPredict], color = 'red', marker='X', s=500) plt.plot([T_Cutoff,T_Cutoff],[-0.2,1.4],color = 'black',linestyle='dashed',lw=2) plt.plot([1.4,-0.2],[(V_Cutoff),(V_Cutoff)],color = 'black',linestyle='dashed',lw=2) plt.axvspan(-0.2, roc_t, 0, roc_v, alpha=0.3, color='#1F98D0')#blue plt.axvspan(roc_t, 1.4, 0, roc_v, alpha=0.3, color='#F9D307')#yellow plt.axvspan(-0.2, roc_t, roc_v, 1, alpha=0.3, color='#F38D25')#orange plt.axvspan(roc_t, 1.4, roc_v, 1, alpha=0.3, color='#DA383D')#red plt.show() plt.close() Which produced this: So the top and bottom rows should end/start at roc_v (indicated by the horizontal dotted line). I understand that in plt.axvspan the ymin and ymax are a relative scale of [0,1] but I can't figure out how to get the quadrants to line up with the horizontal dotted line. How do I figure out the value of roc_v for the ymin and ymax. I've tried (roc_v*1.6) which I though was the logical answer, but this still doesn't line it up. Otherwise, is there another way I can plot these background quadrants? A: Although it's probably doable messing around with transforms, I think you'll probably have more luck using something else than axvspan. I would suggest fill_between, where the limits are simply provided in Data coordinates. PS: for your dashed line, you might want to have a look at axvline() and axhline(), which were specially made for this purpose. roc_t = 0.43652219 roc_v = 0.82251961 T_Cutoff = roc_t V_Cutoff = roc_v fig,ax = plt.subplots(figsize=(15,12)) ax.set_xlim(-0.2,1.4) ax.set_ylim(-0.2,1.4) ax.axvline(T_Cutoff,color = 'black',linestyle='dashed',lw=2) ax.axhline(V_Cutoff,color = 'black',linestyle='dashed',lw=2) ax.fill_between([-0.2, roc_t],-0.2,roc_v,alpha=0.3, color='#1F98D0') # blue ax.fill_between([roc_t, 1.4], -0.2, roc_v, alpha=0.3, color='#F9D307') # yellow ax.fill_between([-0.2, roc_t], roc_v, 1.4, alpha=0.3, color='#F38D25') # orange ax.fill_between([roc_t, 1.4], roc_v, 1.4, alpha=0.3, color='#DA383D') # red plt.show()
[ "stackoverflow", "0011651499.txt" ]
Q: Comparing two files using perl I have 2 files: A.txt and B.txt. In file A.txt, first filed having number series with 5 digit, in B.txt file whole number is given. If that first 5 digit of File A.txt is not match with second file B.txt, then need to print those numbers in separate file.i.e. numbers in B.txt has to print in another file. A.txt 81270,UEDP35 81274,UEDP35 87562,UEDP35 89537,UEDP35 90050,UEDP35 99358,UEDP35 99369,UEDP35 99560,UEDP35 99561,UEDP35 B.txt 8127047667 8756209276 9956176149 8127463873 8953713146 9935805068 9005080751 9956088702 9936916718 A: use warnings; use strict; open AIN, "<A.TXT" or die("A.TXT"); open BIN, "<B.TXT" or die("B.TXT"); my %seen; while (<AIN>) { my $v = (split(/,/))[0]; $seen{$v}++; } while (<BIN>) { my $v=(split)[0]; print "$v\n" if not $seen{substr($v, 0, 5)}; } close AIN; close BIN;
[ "math.stackexchange", "0000928155.txt" ]
Q: Let$\ PA_n $ be the$\ n $-th odd primitive abundant number (whose divisors are deficient). An upper bound for $\ {\sigma(PA_n) \over PA_n} $? Very clearly,$$\ \lim_{n\to\infty}{\sigma(PA_n) \over PA_n}=2. $$ I need whatever $\ m $ such that for every$\ n $, $\ {\sigma(PA_n) \over PA_n} < m $. I've tried with no success, but I think it should be reasonably easy, especially with some tool that I probably lack, or maybe an intuition I failed to have up to now. Here is a table that leaves neither doubt of the limit, nor of the existence of$\ m $, which in fact is most likely just$\ 3 $ (but I'm not necessarily demanding the best upper bound): $$ \begin{array}{c|lcr} n & \text{$\ PA_n$} & \text{$\ \sigma(PA_n)$} & \text{$\ {\sigma(PA_n) \over PA_n}$} \\ \hline 1 & 945 & 1920 & \frac{128}{63}\approx 2.03175 \\ 2 & 1575 & 3224 & \frac{3224}{1578}\approx 2.04698 \\ 3 & 2205 & 4446 & \frac{494}{245}\approx 2.01633 \\ 4 & 3465 & 7488 & \frac{832}{285}\approx 2.16104 \\ 5 & 4095 & 8736 & \frac{32}{15}\approx 2.13333 \\ 6 & 5355 & 11232 & \frac{1248}{595}\approx 2.09748 \\ 7 & 5775 & 11904 & \frac{3968}{1925}\approx 2.0613 \\ 8 & 5985 & 12480 & \frac{832}{399} \approx 2.08521 \\ 9 & 6435 & 13104 & \frac{112}{55}\approx 2.03636 \\ 10 & 6825 & 13888 & \frac{1984}{975}\approx 2.03487 \\ \vdots & \vdots & \vdots & \vdots \\ 10000 & 159210675 & 318595680 & \frac{554608}{272155}\approx 2.00109 \\ \vdots & \vdots & \vdots & \vdots \\ \end{array} $$ You can find the first 10000 odd primitive abundant numbers here. Any ideas as to the bound? A: Lemma: Let $n>1$ be an integer, and let $p$ be the largest prime dividing $n$. Then $$ \frac{\sigma(n)}n \le \bigg(1+\frac1p\bigg) \frac{\sigma(n/p)}{n/p}. $$ Proof: Write $n=p^rm$ where $p\nmid m$. Then $$ \frac{\sigma(n)/n}{\sigma(n/p)/(n/p)} = \frac{\sigma(p^rm)}{p\sigma(p^{r-1}m)} = \frac{\sigma(p^r)\sigma(m)}{p\sigma(p^{r-1})\sigma(m)} = \frac{\sigma(p^r)}{p\sigma(p^{r-1})}. $$ Since $\sigma(p^r) = \frac{p^{r+1}-1}{p-1}$, this gives $$ \frac{\sigma(n)/n}{\sigma(n/p)/(n/p)} = \frac{p^{r+1}-1}{p(p^r-1)} \le \frac{p+1}p = 1+\frac1p. $$ As a consequence, if $n$ is a primitive abundant number whose largest prime factor is $p$, then $$ \frac{\sigma(n)}n \le 2\bigg(1+\frac1p\bigg). $$ Odd primitive abundant numbers have to be divisible by at least three distinct primes; this immediately gives an upper bound of $m=2(1+\frac17) = \frac{16}7 \approx 2.286$. One can do better with a little computation. For example, the only odd primitive abundant numbers not divisible by a prime exceeding $7$ are $945$, $1575$, and $2205$. A calculation gives $\frac{\sigma(n)}n \le 2.05$ for these, and the above argument gives an upper bound of $m=2(1+\frac1{11}) = \frac{24}{11} \approx 2.182$ for the rest. Probably the best possible upper bound is $m+\frac{32}{15} = 2.1333\dots$, which is achieved by $n=4095$. Since $2(1+\frac1{17}) = \frac{35}{17} < \frac{32}{15}$, this would follow from an exhaustive calculation of all primitive abundant numbers of the form $3^a5^b7^c11^d13^e$ and checking that their $\frac{\sigma(n)}n$ values never exceed $\frac{32}{15}$. (Once one shows that there are only finitely many primitive abundant numbers with prime factors bounded by any given $B$, this argument then does show that the limit equals $2$, as asserted.)
[ "stackoverflow", "0058738664.txt" ]
Q: Jquery Datatable not displaying using MVC I am trying to display data from a SQL query using Jquery datatable. my problem is the datatable in the view is not displaying properly as shown by the image attached. cannot see what I am doing wrong I took some part of the code out. The data is retrieved from the database without any problem Html Code <table id="tblPatientHealthRecord" class="table table-bordered table-striped" style="width: 100% !important;"> <thead> <tr> <th>Record ID</th> </tr> </thead> </table> C# Code public class HealthRecordController : Controller { // GET: HealthRecord public ActionResult Index(int id) { ViewBag.patientid = id; List<HealthRecordata> HealthRecordList = new List<HealthRecordata>(); // Oracle connection to table health record using (OracleConnection conn = new OracleConnection(WebConfigurationManager.ConnectionStrings["HealthRecord"].ConnectionString)) { conn.Open(); OracleCommand cmd = new OracleCommand(); cmd.Connection = conn; cmd.CommandText = @"SELECT hr.record FROM health_records hr LEFT JOIN health_record_types hrt ON hr.record_type = hrt.code LEFT JOIN media_types mt ON hr.media_type = mt.code Where hr.patient=:PatientId"; cmd.CommandType = CommandType.Text; cmd.Parameters.Add("PatientId", id); OracleDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { var healthrecord = new HealthRecordata(); HealthRecordList.Add(healthrecord); } } return Json(new { data = HealthRecordList }, JsonRequestBehavior.AllowGet); } Javascript Code @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @Styles.Render("~/bundles/datatablecss") @Scripts.Render("~/bundles/table") <script type="text/javascript"> $(document).ready(function () { $('#tblPatientHealthRecord').DataTable({ ajax: { "url": "/HealthRecord/Index", "type": "GET", "dataType": "json", }, columns: [ { "data": "Record" }, ] }); }); </script> A: Maybe try this instead: $(document).ready(function () { $.get("/HealthRecord/Index", function (data) { var jsonData = data; $('#tblPatientHealthRecord').DataTable({ data: jsonData, columns: [ { data: "Record" }, ] }); }); }); https://dotnetfiddle.net/05jCka
[ "stackoverflow", "0035804553.txt" ]
Q: Two Queries in One with Active Record Rails 4 I got those two queries in rails console, but I want to make just one query with the same result. How I can do that? Table name: companies id :integer not null, primary key name :string phone :string email :string Table name: users id :integer not null, primary key role :integer tier :integer company_id :integer name :string email :string Table name: responsibles id :integer not null, primary key company_id :integer user_id :integer These queries: user_ids = Responsible.where(company_id: 1).pluck(:user_id) User.where(id: user_ids).agent_or_admin.tier1.pluck(:email) (edit: formatted code block) A: Assuming Responsible is a join table for User and Company, you could do something like: User.joins(:responsibilities).where(responsible: {company_id: 1}).agent_or_admin.tier1.pluck(:email) But without knowing how things are structured in your code, I can't really do much else.
[ "stackoverflow", "0037483708.txt" ]
Q: Find all char excluding group at the end with regexp I have this string: this is a test at the end of this string I have a space and the new line. I want to extract (for counting) all space group in the string witout the last space. With my simple regex /\s+/g I obtain these groups: this(1)is(2)a(3)test(4) I want to exclude from group the forth space because i want to get only 3 groups if the string end with space. What is the correct regexp? A: Depending on the regex flavor, you can use two approaches. If atomic groups/possessive quantifiers are not supported, use a lookahead solution like this: (?:\s(?!\s*$))+ See the regex demo The main point is that we only match a whitespace that is not followed with 0+ other whitespace symbols followed with an end of string (the check if performed with the (?!\s*$) lookahead). Else, use \s++(?!$) See another demo. An equivalent expression with an atomic groups is (?>\s+)(?!$). Here, we check for the end of string position ONLY after grabbing all whitespaces without backtracking into the \s++ pattern (so, if after the last space there is an end of string, the whole match is failed). Also, it is possible to emulate an atomic group in JavaScript with the help of capturing inside the positive lookahead and then using a backreference like (?=(\s+))\1(?!$) However, this pattern is costly in terms of performance.
[ "superuser", "0000722771.txt" ]
Q: DD-WRT limited connection on WPA2/AES I installed DD-WRT on a TP-Link TL-WR740N router with the dynamic DHCP WAN setting enabled. Wireless settings are as below: Basic Settings wireless mode : AP wireless network mode : mixed or 802.n only (which is better) channel width : full wireless channel : auto Wireless security Security mode : WPA2 Personal Encryption : AES Using Ethernet, I can access the Internet and everything works fine. When I'm setting security mode none (no security) everything is working but on the laptop's WiFi, it displays "limited connectivity". The laptop can't get an IP from the router. Where does the problem lie? A: Working fine after re-installing dd-wrt. May be some bug in the version.
[ "stackoverflow", "0043188208.txt" ]
Q: Fix Message ER Rejected No Route Defined I'm trying to send a new order single message but I'm getting an ER Rejected message that says that the order reject reason is UNKNOWN ORDER, and No Route Defined but I couldn't find any explanation for this error. If anyone knows what "No Route Defined" means I would be grateful, thanks. A: Typically this means the FIX engine and transaction infrastructure at the other end (it's usually a broker you are connecting to with FIX) does not know what to with the order you are sending to them. Specifically it does not know which exchange or other handling venue to route it to. Hence 'no route'. This may be because it does not recognize the instrument in your order or some combination of parameters on your order are invalid. Although typically you would get a more informative error message if this were the cause. Other causes include the broker's connection to a down stream handling system (e.g. exchange, trading desk) has been interrupted. Sometimes this is a transient situation - service interuption or time-of-day issue outside regular trading hours (RTH). In any case the message indicates that a valid servicing destination for your the order can not be found at this moment.
[ "stackoverflow", "0006723324.txt" ]
Q: MySQL Query is not processing whereas PHP Email code is? I have a form setup in html php and javascript. I set the form to run a process() function upon the click of the submit button. In this process function, I send myself an email and insert the data from the form into a mysql query and sendout that query. However the email code works, and I receive an email, but the query code doesn't and therefore I receive no new rows in my database. I also receive no mysql_error() output either. Please can you tell me where I am going wrong? function process() { mysql_connect("localhost", "username", "password"); mysql_select_db("db"); $device = mysql_real_escape_string($_POST['Device_Type']); $name = mysql_real_escape_string($_POST['Name']); $job = mysql_real_escape_string($_POST['DD']); $username = mysql_real_escape_string($_POST['Username']); $email = mysql_real_escape_string($_POST['Email']); $website = mysql_real_escape_string($_POST['Website']); $UDID = mysql_real_escape_string($_POST['UDID']); mysql_query("INSERT INTO Beta_Testers (`Name`, `Username`, `Email Address`, `Website`, `Job`, `Device_Type`, `UDID`) VALUES ('$name','$username','$email','$website','$job','$device','$UDID'))") or die(mysql_error()); $msg = "Form Contents: \n\n"; foreach($this->fields as $key => $field) $msg .= "$key : $field \n"; $to = '[email protected]'; $subject = 'Beta Form Submission'; $from = 'Beta Sign up'; mail($to, $subject, $msg, "From: $from\r\nReply-To: $from\r\nReturn-Path: $from\r\n"); } A: Since mysql_query() is a boolean function in the context you're using it in, you can do the following: function process() { mysql_connect("localhost", "username", "password"); mysql_select_db("db"); $device = mysql_real_escape_string($_POST['Device_Type']); $name = mysql_real_escape_string($_POST['Name']); $job = mysql_real_escape_string($_POST['DD']); $username = mysql_real_escape_string($_POST['Username']); $email = mysql_real_escape_string($_POST['Email']); $website = mysql_real_escape_string($_POST['Website']); $UDID = mysql_real_escape_string($_POST['UDID']); $query = "INSERT INTO Beta_Testers (`Name`, `Username`, `Email Address`, `Website`, `Job`, `Device_Type`, `UDID`) VALUES ('$name','$username','$email','$website','$job','$device','$UDID'))"; if (mysql_query($query)) { $msg = "Form Contents: \n\n"; foreach($this->fields as $key => $field) $msg .= "$key : $field \n"; $to = '[email protected]'; $subject = 'Beta Form Submission'; $from = 'Beta Sign up'; mail($to, $subject, $msg, "From: $from\r\nReply-To: $from\r\nReturn-Path: $from\r\n"); } else { echo $query; } } But looking your code, is your email address column called "Email Address" or "Email_Address"?
[ "stackoverflow", "0053053289.txt" ]
Q: Changing screens in Python without Screen Manager Class I'm using gestures in all of my screens, and I cannot use a screen manager class to manage my screens, or so I believe. I can navigate the .kv file by using manger.current = 'some_screeen' but cannot in the .py file. I've been trying Runner().ids.manager.current = 'some_screen' in the .py file but it doesn't work. There isn't even an error thrown. The screen doesn't change at all. Essential Code (for the sake of brevity): class Runner(gesture.GestureBox): pass MyApp(App): def build(self): return Runner() Then in the KV file, I'm creating the screen manager. <Runner>: ScreenManager: id: manager Screen: name: 'main_screen' Button: on_press: manager.current = 'screen1' Screen: name: 'screen1' Button: on_press: manager.current = 'home_screen' A: I've been trying Runner().ids.manager.current = 'some_screen' in the .py file but it doesn't work. There isn't even an error thrown. The screen doesn't change at all. It works fine, it just doesn't do what you believe. When you write Runner() you get a new instance of the Runner class, with its own children including its own ScreenManager. This one has nothing to do with the one you're displaying in your gui. When you set its current property the ScreenManager will dutifully change the screen, it's just you have no way to see that. What you actually want is to change the current property of the widget that you are displaying in your gui. The best way to do this depends on the context, which you have omitted (always try to provide a full runnable example, it isn't clear what your failing code looked like). However, in this case the Runner instance is your root widget which is accessible with App.get_running_app().root, so you can write App.get_running_app().root.ids.manager.current = 'some_screen'. Again, there might be neater ways to do it depending on how you structure your code, but this is always an option.
[ "stackoverflow", "0024193898.txt" ]
Q: How do I convert Foreach statement into linq expression? how to convert below foreach into linq expression? var list = new List<Book>(); foreach (var id in ids) { list.Add(new Book{Id=id}); } A: It's pretty straight forward: var list = ids.Select(id => new Book { Id = id }).ToList(); Or if you prefer query syntax: var list = (from id in ids select new Book { Id = id }).ToList(); Also note that the ToList() is only necessary if you really need List<Book>. Otherwise, it's generally better to take advantage of Linq's lazy evaluation abilities, and allow the Book objects objects to only be created on demand.
[ "stackoverflow", "0029522245.txt" ]
Q: Adding Jquery Cycle to Twitter Feed I have found a working script that pulls the feed from twitter. What I want to do is now use Jquery Cycle to vertically scroll this feed 1 tweet at a time. When I try to do this the "normal" way Jquery Cycle works, it does not cycle the tweets as they are not there yet. How can I add some code into this script to then cycle the tweets 1 at a time? Here is the script: /********************************************************************* * #### Twitter Post Fetcher v13.0 #### * Coded by Jason Mayes 2015. A present to all the developers out there. * www.jasonmayes.com * Please keep this disclaimer with my code if you use it. Thanks. :-) * Got feedback or questions, ask here: * http://www.jasonmayes.com/projects/twitterApi/ * Github: https://github.com/jasonmayes/Twitter-Post-Fetcher * Updates will be posted to this site. *********************************************************************/ (function(v,n){"function"===typeof define&&define.amd?define([],n):"object"===typeof exports?module.exports=n():n()})(this,function(){function v(a){return a.replace(/<b[^>]*>(.*?)<\/b>/gi,function(a,f){return f}).replace(/class=".*?"|data-query-source=".*?"|dir=".*?"|rel=".*?"/gi,"")}function n(a){a=a.getElementsByTagName("a");for(var c=a.length-1;0<=c;c--)a[c].setAttribute("target","_blank")}function m(a,c){for(var f=[],g=new RegExp("(^| )"+c+"( |$)"),h=a.getElementsByTagName("*"),b=0,k=h.length;b< k;b++)g.test(h[b].className)&&f.push(h[b]);return f}var A="",k=20,B=!0,t=[],w=!1,u=!0,q=!0,x=null,y=!0,C=!0,z=null,D=!0,E=!1,r=!0,F={fetch:function(a){void 0===a.maxTweets&&(a.maxTweets=20);void 0===a.enableLinks&&(a.enableLinks=!0);void 0===a.showUser&&(a.showUser=!0);void 0===a.showTime&&(a.showTime=!0);void 0===a.dateFunction&&(a.dateFunction="default");void 0===a.showRetweet&&(a.showRetweet=!0);void 0===a.customCallback&&(a.customCallback=null);void 0===a.showInteraction&&(a.showInteraction=!0); void 0===a.showImages&&(a.showImages=!1);void 0===a.linksInNewWindow&&(a.linksInNewWindow=!0);if(w)t.push(a);else{w=!0;A=a.domId;k=a.maxTweets;B=a.enableLinks;q=a.showUser;u=a.showTime;C=a.showRetweet;x=a.dateFunction;z=a.customCallback;D=a.showInteraction;E=a.showImages;r=a.linksInNewWindow;var c=document.createElement("script");c.type="text/javascript";c.src="//cdn.syndication.twimg.com/widgets/timelines/"+a.id+"?&lang="+(a.lang||"en")+"&callback=twitterFetcher.callback&suppress_response_codes=true&rnd="+ Math.random();document.getElementsByTagName("head")[0].appendChild(c)}},callback:function(a){var c=document.createElement("div");c.innerHTML=a.body;"undefined"===typeof c.getElementsByClassName&&(y=!1);a=[];var f=[],g=[],h=[],b=[],p=[],e=0;if(y)for(c=c.getElementsByClassName("tweet");e<c.length;){0<c[e].getElementsByClassName("retweet-credit").length?b.push(!0):b.push(!1);if(!b[e]||b[e]&&C)a.push(c[e].getElementsByClassName("e-entry-title")[0]),p.push(c[e].getAttribute("data-tweet-id")),f.push(c[e].getElementsByClassName("p-author")[0]), g.push(c[e].getElementsByClassName("dt-updated")[0]),void 0!==c[e].getElementsByClassName("inline-media")[0]?h.push(c[e].getElementsByClassName("inline-media")[0]):h.push(void 0);e++}else for(c=m(c,"tweet");e<c.length;)a.push(m(c[e],"e-entry-title")[0]),p.push(c[e].getAttribute("data-tweet-id")),f.push(m(c[e],"p-author")[0]),g.push(m(c[e],"dt-updated")[0]),void 0!==m(c[e],"inline-media")[0]?h.push(m(c[e],"inline-media")[0]):h.push(void 0),0<m(c[e],"retweet-credit").length?b.push(!0):b.push(!1),e++; a.length>k&&(a.splice(k,a.length-k),f.splice(k,f.length-k),g.splice(k,g.length-k),b.splice(k,b.length-k),h.splice(k,h.length-k));c=[];e=a.length;for(b=0;b<e;){if("string"!==typeof x){var d=g[b].getAttribute("datetime"),l=new Date(g[b].getAttribute("datetime").replace(/-/g,"/").replace("T"," ").split("+")[0]),d=x(l,d);g[b].setAttribute("aria-label",d);if(a[b].innerText)if(y)g[b].innerText=d;else{var l=document.createElement("p"),G=document.createTextNode(d);l.appendChild(G);l.setAttribute("aria-label", d);g[b]=l}else g[b].textContent=d}d="";B?(r&&(n(a[b]),q&&n(f[b])),q&&(d+='<div class="user">'+v(f[b].innerHTML)+"</div>"),d+='<p class="tweet">'+v(a[b].innerHTML)+"</p>",u&&(d+='<p class="timePosted">'+g[b].getAttribute("aria-label")+"</p>")):a[b].innerText?(q&&(d+='<p class="user">'+f[b].innerText+"</p>"),d+='<p class="tweet">'+a[b].innerText+"</p>",u&&(d+='<p class="timePosted">'+g[b].innerText+"</p>")):(q&&(d+='<p class="user">'+f[b].textContent+"</p>"),d+='<p class="tweet">'+a[b].textContent+ "</p>",u&&(d+='<p class="timePosted">'+g[b].textContent+"</p>"));D&&(d+='<p class="interact"><a href="https://twitter.com/intent/tweet?in_reply_to='+p[b]+'" class="twitter_reply_icon"'+(r?' target="_blank">':">")+'Reply</a><a href="https://twitter.com/intent/retweet?tweet_id='+p[b]+'" class="twitter_retweet_icon"'+(r?' target="_blank">':">")+'Retweet</a><a href="https://twitter.com/intent/favorite?tweet_id='+p[b]+'" class="twitter_fav_icon"'+(r?' target="_blank">':">")+"Favorite</a></p>");E&&void 0!== h[b]&&(l=h[b],void 0!==l?(l=l.innerHTML.match(/data-srcset="([A-z0-9%_\.-]+)/i)[0],l=decodeURIComponent(l).split('"')[1]):l=void 0,d+='<div class="media"><img src="'+l+'" alt="Image from tweet" /></div>');c.push(d);b++}if(null===z){a=c.length;f=0;g=document.getElementById(A);for(h="<ul id='tweets'>";f<a;)h+="<li>"+c[f]+"</li>",f++;g.innerHTML=h+"</ul>"}else z(c);w=!1;0<t.length&&(F.fetch(t[0]),t.splice(0,1))}};return window.twitterFetcher=F}); /** * ### HOW TO CREATE A VALID ID TO USE: ### * Go to www.twitter.com and sign in as normal, go to your settings page. * Go to "Widgets" on the left hand side. * Create a new widget for what you need eg "user time line" or "search" etc. * Feel free to check "exclude replies" if you don't want replies in results. * Now go back to settings page, and then go back to widgets page and * you should see the widget you just created. Click edit. * Look at the URL in your web browser, you will see a long number like this: * 345735908357048478 * Use this as your ID below instead! */ /** * How to use TwitterFetcher's fetch function: * * @function fetch(object) Fetches the Twitter content according to * the parameters specified in object. * * @param object {Object} An object containing case sensitive key-value pairs * of properties below. * * You may specify at minimum the following two required properties: * * @param object.id {string} The ID of the Twitter widget you wish * to grab data from (see above for how to generate this number). * @param object.domId {string} The ID of the DOM element you want * to write results to. * * You may also specify one or more of the following optional properties * if you desire: * * @param object.maxTweets [int] The maximum number of tweets you want * to return. Must be a number between 1 and 20. Default value is 20. * @param object.enableLinks [boolean] Set false if you don't want * urls and hashtags to be hyperlinked. * @param object.showUser [boolean] Set false if you don't want user * photo / name for tweet to show. * @param object.showTime [boolean] Set false if you don't want time of tweet * to show. * @param object.dateFunction [function] A function you can specify * to format date/time of tweet however you like. This function takes * a JavaScript date as a parameter and returns a String representation * of that date. * @param object.showRetweet [boolean] Set false if you don't want retweets * to show. * @param object.customCallback [function] A function you can specify * to call when data are ready. It also passes data to this function * to manipulate them yourself before outputting. If you specify * this parameter you must output data yourself! * @param object.showInteraction [boolean] Set false if you don't want links * for reply, retweet and favourite to show. * @param object.showImages [boolean] Set true if you want images from tweet * to show. * @param object.lang [string] The abbreviation of the language you want to use * for Twitter phrases like "posted on" or "time ago". Default value * is "en" (English). */ // ##### Simple example 1 ##### // A simple example to get my latest tweet and write to a HTML element with // id "example1". Also automatically hyperlinks URLS and user mentions and // hashtags. var config1 = { "id": '585817037076725762', "domId": 'twitterfeed', "maxTweets": 10, "enableLinks": true }; twitterFetcher.fetch(config1); A: You'll have to precache a fixed number of tweets and then scroll through them. The API offers no way to 'skip' over tweets you've already seen. var config1 = { "id": '585817037076725762', "domId": 'twitterfeed', "maxTweets": 1000, "enableLinks": true, "customCallback": gotTweets }; twitterFetcher.fetch(config1); var tweets = []; var i = 0; function gotTweets(data){ tweets = data; }; function showNextTweet() { document.getElementById("twitterfeed").innerHTML = tweets[i]; i++; console.log("Showing tweet " + (i+1)); } setInterval(showNextTweet, 1000);
[ "travel.stackexchange", "0000106663.txt" ]
Q: Seoul-Toronto-Montreal, skipping last leg, what happens to my luggage? Earlier this year I booked return tickets from Montreal to Seoul. The return flight is from Incheon to Toronto via Korean Air and Toronto to Montreal via WestJet. The problem is I've now moved to Toronto and don't need the last flight to Montreal. Expedia said no need to cancel this portion of tickets, I can simply not show up. But then what happens to my luggage? Can I book it to Toronto instead of Montreal? I heard airlines don't like throwaway tickets. What should I do? A: This is called short-checking. You can always ask but they do not always accept, particularly if your connection is short on time. However in this case it does not matter. Even if they tag your luggage to YUL, you must take it through customs yourself when you enter Canada which is in Toronto for you. At that point you will just be able to exit the airport with your luggage as you would do if you had a stopover in Toronto. A: I believe you will have to claim your luggage in Toronto anyway to go through customs so it should not be a problem. To be double sure just glance at your luggage tag in Seoul and make sure that the tag says YYZ.
[ "math.stackexchange", "0002225850.txt" ]
Q: Below is a diagram of the dotted cube with edges of length 4 Below is a diagram of the dotted cube with edges of length 4 my attempt: t=-u+v=(-4,4,0) t-2r=(-4,4,0)-2(-4,4,4)=(4,-4,-8) u+v+w+r+s+t=(4,0,0)+(0,4,0)+(0,0,4)+(-4,4,4)+(4,-4,4)+(-4,4,4)=(0,8,16) is i am right can any one give me right direction A: $$t-2r=(-4,4,0)-2(4,4,4)=(-12,-4,-8)$$ $$u+v+w+r+s+t=u+v+w+u+v+w+u+w+v-u=$$ $$=2u+3v+3w=(8,12,12)$$