source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0055394504.txt" ]
Q: Get records "Jone Deo" or "Deo Jone" in mysql How can we get the result of "Jone Deo" or "Deo Jone" in mysql? Example. Table Name students ID------Name 1-------Jone Deo 2-------Bill Gates Now, if someone enter Deo Jone or Jone Deo then Jone Deo records will be search out in mysql I've search box in my website. If someone search "Jone Deo" or "Deo Jone", I will need only result from above tables. I don't want to use PHP loop or explode function. A: You might want to try Full-text search: SELECT * FROM People WHERE MATCH (full_name) AGAINST ('+Doe +John' IN BOOLEAN MODE); http://sqlfiddle.com/#!9/d21d4e/5 Full-text search explained: https://www.w3resource.com/mysql/mysql-full-text-search-functions.php "Full-text searching is performed using MATCH() ... AGAINST syntax. MATCH() takes a comma-separated list that names the columns to be searched. AGAINST takes a string to search for, and an optional modifier that indicates what type of search to perform. The search string must be a string value that is constant during query evaluation. This rules out, for example, a table column because that can differ for each row." So in short, to answer your question you should see an improvement in query execution times by implementing a full text index on wide VARCHAR columns. Providing you are using a compatible storage engine ( InnoDB or MyISAM)
[ "quant.stackexchange", "0000048964.txt" ]
Q: Calculate the price at time t=0 Assume the risk-free bond Bt and the stock St follow the dynamics of the Black & Scholes model (with interest rate r, stock drift $\mu$ and volatility $\sigma$). Calculate the price at time $t = 0$ of a derivative with maturity T and payoff $(S^3_t-K)^+$. I know I need to use the Black Scholes formula for price of a call to find the price of the derivative but the formula also contains $N(d_1)$ and $N(d_2)$ so how would this get affected? A: I don't understand the question but I can try. I think the problem is to find the price of a contingent claim that has payoff $(S_T^3 - K)^+$. The well-known pricing formula is: \begin{equation} \pi(t)=\mathbb{E}^\mathbb{Q}[e^{-r(T-t)}(S_T^3 - K)^+|\mathcal{F}_t] \end{equation} Now put $Y=S^3$, by using Ito's Lemma \begin{equation} dY(t)=dS^3(t)=3S^2(t)dS(t) + \frac126S(t)\sigma^2S^2(t)dt \end{equation} In Black-Scholes model \begin{equation} dS(t)=\mu S(t) dt + \sigma S(t) dW(t) \end{equation} So we have: \begin{equation} dY(t)=3\mu S^3dt + 3\sigma^2S^3dt + 3\sigma S^3dW=(3\mu + 3\sigma^2)Ydt + 3\sigma YdW \end{equation} Now we define \begin{align} \tilde{\mu}&=3\mu + 3\sigma^2 \\ \tilde{\sigma}&=3\sigma \end{align} Now suppose $Y$ is a new stock with drift $\tilde{\mu}$ and volatility $\tilde{\sigma}$ and just substitute in the Black-Scholes formula for an european option with underlying $Y$ and strike $K$.
[ "stackoverflow", "0050452085.txt" ]
Q: ScrollView is not Scrolling down I know its a very basic issue. I still can't resolve it. I have a Scrollview below a title view and the Scrollview is not at all scrolling. I will post my codes below. Please have a look. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/page_background" android:clickable="true" android:orientation="vertical" > <RelativeLayout android:layout_width="match_parent" android:layout_height="?android:attr/actionBarSize" android:gravity="center_vertical" android:layout_weight="0" android:clickable="true" android:background="@color/button_colour"> </RelativeLayout> <ScrollView android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:fillViewport="true" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:weightSum="14" android:padding="2dp" android:clickable="true" android:orientation="vertical"> </LinearLayout> </ScrollView> </LinearLayout> A: There is no use of android:layout_weight in this case . And also you do not have to use android:layout_weight inside ScrollView. If you use Views will be wrap inside the ViewGroup and won't scroll. And fill_parent is depricated Use match_parent. Use the layout below: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linearLayout" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent"> <RelativeLayout android:layout_width="match_parent" android:layout_height="?android:attr/actionBarSize" android:background="@color/colorPrimary" android:clickable="true" android:gravity="center_vertical"> </RelativeLayout> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/colorAccent" android:orientation="vertical" android:padding="2dp" > <!--Other views goes here without weight--> </LinearLayout> </ScrollView> </LinearLayout>
[ "travel.stackexchange", "0000069282.txt" ]
Q: Leaving belongings in a capsule hotel I am considering staying at Hotel Asakusa & Capsule for a few days. I know I have to leave the hotel during the day for cleaning, I don't mind this as I will be going around town anyways. However, I would much rather not have to carry my main backpack everywhere I go and only carry a small bag for daily needs. Is it possible to leave my belongings in the including locker since I would be staying there for 3-4 days in a row, or do I have to carry all my belongings every day? A: As a rule, capsule hotels are not set up for multi-day stays. However, this one appears to be an exception, and you can keep your locker during the day - with the major caveat of not being able to enter the hotel (and access your belongings) between 9:30AM and 4PM. Beware that capsule hotel lockers may be quite small and a full-size backpack may not fit. That said, while capsule hotels are a fun "only in Japan" novelty and worth trying once, I would not recommend multiple nights in one. Your privacy and space is quite limited, they're noisy with drunk people coming and going all night long, and not being able to use the room during the day can be quite a disadvantage when you're jet lagged. You can likely get a "normal" hotel for a similar price if you book in advance: I've stayed in the same chain's Tsukuba Hotel in Ueno, and it was fine and the Japanese-style room (with shared bathroom) only costs ¥3800/night.
[ "stackoverflow", "0037971833.txt" ]
Q: Need to draw cursor in Linux framebuffer I need to draw a cursor (mouse pointer) on the screen under Linux without X11. This is for use in an embedded system where all of the other drawing happens directly in a framebuffer (/dev/fb0). The GUI library that I'm currently looking at doesn't provide any cursor support. I could do the blitting myself, but I'm concerned about appearance and performance, in part because I don't seem to be able to synchronize with vsync (FBIO_WAITFORVSYNC). I know that nearly every graphics chip out there supports hardware cursors, but DirectFB is dead, libdrm needs X11, and likewise for Mesa. In What is hardware cursor and how does it work?, the OP claims to have achieved this with ioctl calls, stating that it was simple, but declining to provide further details because his code is proprietary. I am aware of FBIO_CURSOR, but it seems to be non-standard and always returns EINVAL on my 3.10.0 kernel. What is the right way to draw a framebuffer cursor in the absence of X11? A: I ended up rolling my own cursor support, since it appeared that the kernel support was dependent on whatever the particular video driver supported. The performance ended up great for my purposes. Here's what I did: Open the /dev/fb0 framebuffer, adjust vinfo as needed, mmap the framebuffer, and malloc two buffers the same size as the framebuffer. One of the buffers is my back buffer where all the drawing happens. The other one is my "cursor" buffer where the cursor is drawn. Open the appropriate /dev/input/eventX in preparation for reading mouse events. Define a "refresh" function to call whenever something is drawn into the back buffer, or whenever there is mouse activity. poll for mouse events with a reasonable timeout. I used a 500 ms timeout and put this inside a pthread so that it had very little performance overhead. The "refresh" function memcpy'ies the back buffer into the cursor buffer, and draws the cursor on top of it. (I erase the mask bits under the cursor and draw the cursor bits, as per the images here.) The cursor buffer is then memcpy'ed into the framebuffer. (I protect the refresh functionality with two mutex locks for better performance. I acquire the first before copying the back buffer to the cursor buffer and release it after drawing the cursor. I acquire the second before drawing the cursor and release it after copying the cursor buffer to the framebuffer. This improves performance noticeably when doing lots of really fast drawing.) A few reasons for some of my decisions: Writing into the framebuffer is reasonably fast, but reading from it is much slower, hence the use of regular malloc'ed memory for the back and cursor buffers. memcpy is much faster than anything I can write and is thread-safe. Concurrent access to the framebuffer is slow, presumably because memcpy locks regions and blocks when trying to access a region currently in use. This is why I used two mutexes to protect copies from the back buffer to the cursor buffer, and from the cursor buffer to the framebuffer. poll with a 0 timeout is equivalent to a tight loop that uses a lot of CPU cycles, hence the use of a non-zero timeout. But poll returns as soon as there is activity on the input, so the responsiveness is great. On my hardware, I didn't find a usable way to synchronize with the vertical blanking (some of the ioctl's are apparently no-ops), but the approach described above exhibited no particular tearing. Yes, this approach uses two offscreen buffers, each of which require 4 MB on my 1920 x 1080 16-bit/pixel screen, but it's very simple and sufficient for my needs.
[ "stackoverflow", "0001651297.txt" ]
Q: JQGrid - ccur is undefined I've done quite a bit of googling on this error but have had no luck. I'm basically sending a JSON result to the jqGrid and getting this error. A: Setting jsonReader : { repeatitems: false } in my jqGrid declaration got around this issue.
[ "stackoverflow", "0018897593.txt" ]
Q: regex to parse out preceding backslash In JavaScript, I am trying to split a string by ';' if not preceded (escaped) by '\'. The string might look like: asd;123;&auml\;;33; So the above string should be split into: asd 123 &auml\; 33 I thought [^\]; would do the trick but this selects the preceding character of ';' as well if it is not a '\'. I want only the ';' though without its preceding character. A: Instead of splitting, you can match: /(\\.?|[^;])+/g
[ "stackoverflow", "0004446270.txt" ]
Q: ASP.NET AJAX: How to access object properties? My web method returns object 'User' that has a lot of properties. In my 'OnComplete' function I am receiving those object. function OnComplete(args) { var res = $get('WsResult'); debugger; res.innerHTML = args['Nick']; } Question: How can I get values of object properties? The code above provides me with '[object Object]' text instead of real object value. Thanks a lot! A: You can get these properties the same way you get any other properties: alert(args.Nick.FullName);
[ "stackoverflow", "0035637305.txt" ]
Q: Multiple execSQL() in one function I wrote a scheduler app which adds schedule data to a database when the user updates the schedule from the internet using this: sqLiteDatabase.execSQL("INSERT OR IGNORE INTO `subject` (`id`, `date`, `start`, `end`, `name`, `room`, `teacher`, `class_id`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", new String[]{id, date, start, end, name, room, teacher, classId}); This is working fine. However there could be a scenario, that the online schedule will change it's content. Therefore I would write the function like this: sqLiteDatabase.execSQL("DELETE FROM `subject` WHERE `date` = ? AND `class_id` = ?", new String[] {date, classId}); sqLiteDatabase.execSQL("INSERT OR IGNORE INTO `subject` (`id`, `date`, `start`, `end`, `name`, `room`, `teacher`, `class_id`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", new String[]{id, date, start, end, name, room, teacher, classId}); The data is deleted fine, but now not all the content (only one row) is added back in the database. So what I think: The delete query is still running while the second insert query is executed too So, my question is. How can I wait until the deletion is finished to add the new data back properly? A: That is not how execSQL calls work; they are always properly serialized. To update or insert a record, try the update first, and insert only if that record was not found: ContentValues cv = new ContentValues(); cv.put(...); if (sqLiteDatabase.update("subject", cv, "Date = ? AND ClassID = ?", new String[]{ date, classId }) < 1) sqLiteDatabase.insertOrThrow("subject", null, cv);
[ "stackoverflow", "0060728593.txt" ]
Q: Aggregate and count disctinct values with a join This question is a mix of those duplicates: Get unique values using STRING_AGG in SQL Server SQL/mysql - Select distinct/UNIQUE but return all columns? I just can't manage to make it work all at once. I have two tables : TABLE A IntervalId Starts Ends ------------------------- 1 0 10 2 10 25 3 25 32 4 32 40 TABLE B Id ErrorType Starts Ends ---------------------------------------- 1 666 0 25 2 666 10 32 3 777 0 32 4 666 25 40 5 777 10 25 Starting from the time intervals in table B, I'm trying to count and list, in each interval, the error types that might have happened during that interval. And remove duplicates. Please note that there isn't any Start or End in table B that does not exist in Table A (Table A is generated from them). the result with duplicates would be this : Starts Ends ErrorsCount Errors ----------------------------------------------- 0 10 2 666, 777 10 25 4 666, 666, 777, 777 25 32 3 666, 777, 666 32 40 1 666 The result I'm looking for is without duplicates: Starts Ends DistinctErrorsCnt DistinctErrors ----------------------------------------------- 0 10 2 666, 777 10 25 2 666, 777 25 32 2 666, 777 32 40 1 666 Here is my attemot, but I can't understand how to get ErrorType out of the bit that does the "distinct" without SQL server complaining that it's not in an aggregate or group by. Or, as soon as I put it into a Group by, then all the different Error Types are wiped by the first one that comes around. I end up with only 666 everywhere. SELECT IntervalId, Starts, Ends, COUNT([TableB].ErrorType) as DistinctErrorsCnt, DistinctErrors= STRING_AGG([TableB].ErrorType, ',') FROM ( SELECT DISTINCT [TableA].IntervalId, FROM TableB LEFT JOIN TableA ON ( [TableA].Starts= [TableB].Starts OR [TableA].Ends = [TableB].Ends OR ([TableA].Starts >= [TableB].Starts AND [TableA].Ends <= [TableB].Ends) ) GROUP BY [TableA].IntervalId, [TableA].Starts, [TableA].Ends, ) NoDuplicates GROUP BY NoDuplicates.IntervalId, NoDuplicates.Starts, NoDuplicates.Starts Again: This is not syntactically correct, for the reason I explained above. A: You can use aggregation: select a.starts, a.ends, count(distinct b.errorType) DistinctErrorsCnt, string_agg(b.errorType, ', ') within group(order by b.starts) DistinctErrors from tablea a inner join tableb b on b.starts >= a.ends and b.ends <= a.start group by a.intervalId, a.start, a.end If you want to avoid duplicates, you could use a subquery, or better yet, cross apply: select a.starts, a.ends, count(*) DistinctErrorsCnt, string_agg(b.errorType, ', ') within group(order by b.starts) DistinctErrors from tablea a cross apply ( select distinct errorType from tableb b where b.starts >= a.ends and b.ends <= a.start ) b group by a.intervalId, a.start, a.end
[ "movies.stackexchange", "0000049645.txt" ]
Q: What is the longest running TV role for a child actor? What is the longest running TV role for an actor who started in the role as a child (regardless of their age at the end of their role)? I'm especially interested in those that were part of the main cast and/or appeared in the majority of episodes rather than an occasional recurring role. A: Adam Woodyatt was part of the original cast of Eastenders. He was born in June 1968 and Eastenders started in February 1985 when he would have been 16. It's still running and he's still in it, so 31 years and counting... A: Jack P Shepard has been playing David Platt on Coronation Street since 2000. He would thus have been 12 when he started and it's been 16 years so far. He has appeared in 1348 episodes in those 16 years.
[ "stackoverflow", "0018257868.txt" ]
Q: ModelLayer(Context appContext) Singleton Constructor in Android...what does the following code with comments exactly do? In the model layer of the Android project I am learning from the Big nerd Ranch Android Programming book, there is a specific singleton - model layer class, which goes like this: public class ModelLayerClass { private static ModelLayerClass class_instance; //its a clear singleton here ! private Context context_instance; private ModelLayerClass(Context appContext) //why this parameter is being passed? { context_instance = appContext; //how this helps here ? } public static ModelLayerClass get(Context c) { if(class_instance=null) { class_instance = new ModelLayerClass(c.getApplicationContext()); } return class_instance; } } When I went through the book, it was saying that, it is common practice in Android to have a Context parameter which allows the singleton to "start activities", access project resources, find your apps private storage and more.....doesnt the classes in our project have a default access to all of these (except for starting activities). Can anyone direct me to proper online resources or could give me a good explanation about this...thnx :) A: From your activity, you do have access to everything within your application, but generally through the use of context. Here's the Android documentation for Context. For example, when you write startActivity(new Intent(MainActivity.this, NewActivity.class)); You only have access to the startActivity method because your Activity class is extends Activity. If you want to start an activity from a singleton or from another class or anything like that, you need to have a Context to start an activity. For example, if you wanted to start the same activity above, but from outside of your Activity class, you must have a context: context.startActivity(new Intent(context, NewActivity.class)); Same goes for any number of other things you might want to do outside of your Activity class. Accessing resources: Bitmap imageFromRes = BitmapFactory.decodeResource(context.getResources(), R.drawable.image); Creating new Android views: ImageView iv = new ImageView(context); Basically, Context is a good "catch-all" parameter that allows your non-Android classes to still utilize methods that you would use in Android classes (like Activity, Service, Dialog, etc).
[ "codereview.stackexchange", "0000123445.txt" ]
Q: Computing logits for a vector and for all vectors in a set I've had to write two different functions (shown below), but I want to combine the two functions into one. Is there a way to do this? softmax_a_set() takes a list of numpy arrays, applies softmax() to each individual numpy array, and then returns a list of processed numpy arrays. def softmax(a_vector): """Compute a logit for a vector.""" denom = sum(numpy.exp(a_vector)) logit = numpy.exp(a_vector)/denom return logit def softmax_a_set(a_set): """computes logits for all vectors in a set""" softmax_set = numpy.zeros(a_set.shape) for x in range(0, len(a_set)): softmax_set[x] = softmax(a_set[x]) return softmax_set A: Why do you want to combine them into two functions? It’s possible, but I don’t think it would be an improvement. They’re two fairly distinct functions, and cramming the code for both into a single function would make the code less readable. If you really need a single function that handles both, you could do something like: def softmax(a): if isinstance(a, vector): return softmax_a_vector(a) elif isinstance(a, set): return softmax_a_set(a) which gets what you want, but you keep the nice separation of code into distinct functions. One other minor thing: you can improve the for loop in softmax_a_set with enumerate: for idx, a_vector in enumerate(a_set): softmax_set[idx] = softmax(a_vector)
[ "stackoverflow", "0047751923.txt" ]
Q: Using multiple setTimeout in the same async function / Timer reset When trying to understand async/await, I tried this block of code that didn't behave the way I expected it to. let test = async function () { let result = new Promise((resolve, reject) => { setTimeout(() => resolve('done1'), 2000) }) let result2 = new Promise((resolve, reject) => { setTimeout(() => resolve('done2'), 2500) }) let x1 = await result console.log(x1) let x2 = await result2 console.log(x2) } test() I was expecting the console to display done1 after 2seconds, then display done2 2.5 seconds after done1. Instead, It displayed done1 in 2seconds and done2 0.5seconds after that. Why does it behave like this, since I await the second setTimeout after displaying the first one? A: When you create a new Promise, it starts to run it's code. When you have setTimeout inside it, actually the timer is going. When you use await before the Promise call, it waits until the promise will be resolved or rejected and then work. You need to create each promise and after that wait for it. let test = async function () { let result = new Promise((resolve, reject) => { setTimeout(() => resolve('done1'), 2000); }); let x1 = await result; console.log(x1); let result2 = new Promise((resolve, reject) => { setTimeout(() => resolve('done2'), 2500); }); let x2 = await result2; console.log(x2); } test()
[ "stackoverflow", "0028210248.txt" ]
Q: How to assign variable value to constant in perl? I have following code #!/usr/bin/perl -w use warnings; use constant ARRAY => "XCC320G"; print ARRAY; print "Enter ur choice\n"; chomp($choice = <STDIN>); ARRAY=>$choice; print ARRAY; Currently my code is with respect to constant. Now I want to make it generic so I have to give variable value to the constant. Is there any way to do this in perl? A: The definition of a constant includes the fact that you cannot assign a different value to it later on. If you wish to be able to assign to it then it should not have been a constant.
[ "stackoverflow", "0059850562.txt" ]
Q: how to install sympy in jupyter note book I have installed anaconda and I am using jupyter notebook. I ran a code in jupyter notebook and faced with this error: ModuleNotFoundError: No module named 'SymPy' I installed sympy with conda install -c anaconda sympy but It still gives the above error. what can I do know? A: Python imports are case sensitive: from sympy import * should work
[ "stackoverflow", "0011884859.txt" ]
Q: Monotouch Automated Incremental Build Number with version number Regarding Monotouch IOS development with C#: I'm trying to implement an auto incrementing build version number into my Monotouch IOS project. Something like [Major].[Minor].[Build] would be fine with the [Build] part auto incrementing on every build. I found this post below but it seems to be using Objective C and I can't figure out how to get this working using Monotouch C#. http://monotouch.2284126.n4.nabble.com/How-to-increment-the-iPhone-Application-Version-number-on-every-build-td4425363.html In Monotouch, I have access to "System.Reflection.AssemblyVersionAttribute", but I don't know how to use it. I tried simple things like: System.Reflection.AssemblyVersionAttribute tempvar = new System.Reflection.AssemblyVersionAttribute ("1.2.*"); Console.WriteLine("tempvar = " + tempvar.Version); But the print output is literally: "1.2.*" and doesn't auto increment. Anyone experienced with this? Thanks in advance A: System.Reflection.AssemblyVersionAttribute is meant to be used as an attribute. The compiler will replace the * with a number. E.g. [assembly: System.Reflection.AssemblyVersionAttribute ("1.2.*")] You might also want to look at this email for how the use your application bundle version.
[ "math.stackexchange", "0000575036.txt" ]
Q: Limit of a harmonic subseries minus "its" logarithm $\displaystyle \lim_{n \to \infty} \sum_{k=1}^n \frac{1}{3k-1} - \frac{1}{3}\ln(n)$ I think that inserting the other terms and then subtracting them would not help. I need just the ideea. Thank you. A: It is not very difficult to show that, for natural values of a, $\displaystyle{\sum_{k=1}^n}\frac1{n+a}=H_{n+a}-H_a$ , where $H_n$ is the $n^{th}$ harmonic number. But in our case, $a=-\frac13$ , so we have to extend the formula or definition of $H_n$ so as to encompass non-natural arguments as well. Luckily for us, Euler has already done it some $250$ years ago: $\displaystyle{H_n=\int_0^1\frac{1-x^n}{1-x}dx}$ . Using this, we can now compute the value of $H_{-\frac13}$ to be $\displaystyle{\frac12\bigg(\frac\pi{\sqrt3}-3\ln3\bigg)}$. Now use the fact that $\displaystyle{\lim_{n\to\infty}H_n-\ln n}=\gamma$. See here for more details on how to handle the integral in question.
[ "stackoverflow", "0005707363.txt" ]
Q: Same Origin Policy and external scripts I've been tasked with integrating ad code from AdBrite. This is the snippet I've been given, sanitized to remove our identifiers: <script type="text/javascript"> var AdBrite_Title_Color = '3D81EE'; var AdBrite_Text_Color = '000000'; var AdBrite_Background_Color = 'FFFFFF'; var AdBrite_Border_Color = 'CCCCCC'; var AdBrite_URL_Color = '008000'; try{var AdBrite_Iframe=window.top!=window.self?2:1;var AdBrite_Referrer=document.referrer==''?document.location:document.referrer;AdBrite_Referrer=encodeURIComponent(AdBrite_Referrer);}catch(e){var AdBrite_Iframe='';var AdBrite_Referrer='';} </script> <script type="text/javascript">document.write(String.fromCharCode(60,83,67,82,73,80,84));document.write(' src="http://ads.adbrite.com/mb/text_group.php?sid=sanitized&zs=sanitized&ifr='+AdBrite_Iframe+'&ref='+AdBrite_Referrer+'" type="text/javascript">');document.write(String.fromCharCode(60,47,83,67,82,73,80,84,62));</script> <div><a target="_top" href="http://www.adbrite.com/mb/commerce/purchase_form.php?opid=sanitized&afsid=1" style="font-weight:bold;font-family:Arial;font-size:13px;">Your Ad Here</a></div> It's loading a remote script from the Adbrite servers by writing to the DOM. The String.fromCharCode cleverly writes out the ASCII chars for <script> in order to reference the remote Javascript file. My question is: why does this work? Don't browsers recognize this as a violation of the Same Origin Policy? BTW, what prompted my investigation of this was the fact that I'm having trouble getting the URL params to be properly escaped and then un-escaped in GWT's UIBinder. Thanks A: Same origin policy applies to AJAX requests. Loading remote scripts is not governed by this rule, hence solutions like JSONP might exists.
[ "hardwarerecs.stackexchange", "0000006265.txt" ]
Q: i7 4770 Cheap Deal vs i7 6700 I got an offer to buy a used Core i7-4770 with Asus Motherboard and 16 Gigs of DDR3 RAM for 200 Euros. This offer comes to pass very good because I am thinking about upgrading my computer. Currently, I use an AMD FX-6300 on an MSI Board which recently started having issues on boot. GPU is the Sapphire R9 270X, but I will upgrade to an GTX 1070 soon. My question now is, should I take that deal for 200 Euros or should I save some more money to take a new i7-6700 with DDR4 instead. How is the Performance to Value comparison? I compared the two CPUs using CPUBenchmark.net and the Benchmark Points are different by just 200, which does not seem much compared to the difference from my FX-6300 to the i7's (which is about 3k Points difference). In case you need some information about my main usage of the PC, I play a lot of games like Rainbow Six Siege, The Division, Overwatch, Paragon (guess that's the cpu-heaviest game of those) and I also do a lot of rendering to MP4 (live and non-live). A: You should seriously consider the newer chip for rendering. I shall weigh up the + / - as if we refer to upgrading to the newer CPU. - It has been shown on TOM's hardware many times that there is little difference for gaming, due to the CPU clock-speed being a big factor in games still. Consider this a small minus as CPU has VERY little effect on game performance (it's all about GPU, baby!) - You will need to buy new RAM as you stated, and it's not really much better in performance for games... Video it is, but only a little bit. + Power usage / thermal control is a LOT better on the 6000's, so it will distract your gaming a lot less with quieter fans. + Video encoding MUCH faster on the new i7's if the software is optimised for it (it will be). + (this is the one that got me) Upgrading Mobo means you get all the sweet new features such as USB3.1 and type-C connectors. Future-you will thank you for this investment. Also, EUR200 is too much for that old CPU. I mean, performance-per-dollar it's OK, but if you really look hard for second-hand machines you will find one (probably with case and PSU) for half that price.
[ "english.stackexchange", "0000007049.txt" ]
Q: Does "bend over backwards" have bad meaning? If my boss asks me if I can help him to do something, I reply: I'll bend over backwards to do it. Does this reply literally have a meaning of flattery? A: I think it sounds a little weird to tell your boss you will bend over backwards. I think it sounds better when your boss uses it to explain your work. A: In my mind, it's a very extreme form of commitment reserved for out of the ordinary scenarios. Not something I would recommend telling a boss on a regular basis, as it robs the term of its degree of commitment. You might bend over backwards to win a key client from a competitor, but you wouldn't bend over backwards to get the weekly report in on time. Even then, to use the phrase is indicative that you really need something to happen and that the consequences for your job/reputation/well being might be extreme if you couldn't. One typically bends over backwards not just for someone in a higher position than oneself, but also when the person you're doing it for shows little regard for you, because they know they're in control due to their station. People who bend over backwards often assume a submissive role, which is not to be mistaken with there mere seniority that a boss would have over you at work. A: I'm not sure I agree with some of the current answers implying some negative overtones. The thing is, in most circumstances, one would use this term about someone else, not oneself. And in that case, it would more likely somewhere between compliment and outright admiration. "The plane was delayed by 3 hours, but the crew bent over backwards to make it as painless as possible" Another roughly-equivalent expression would be "going beyond the call of duty".
[ "stackoverflow", "0017973180.txt" ]
Q: os.chroot Operation not permitted I'm trying to write a python script to generate a debian package. I'm generating required folder structure in a temporary folder. In order to change uid and gid of /usr and subfolders to root I thought of using chroot. However, on this line os.chroot(tmpdir) I get: OSError: [Errno 1] Operation not permitted: '/tmp/tmpVnTqW7/myproj' I've also tried this mini-tutorial with same results: http://www.tutorialspoint.com/python/os_chroot.htm Why would that be? Thanks A: chroot() can be done only by root. do one of these: Run the script with sudo Make the script setuid root, and do the setuid(geteuid()) equivalent python magic
[ "softwareengineering.stackexchange", "0000019326.txt" ]
Q: Is it possible to adopt agile methodologies for outsourced projects? I've had experience as a developer or team lead on several projects that have been outsourced and have seen less than stellar results in all cases. Most of these projects have employed a waterfall philosophy, with large kickoff meetings, months-long requirements gathering phases, plenty of conference calls, and innumerable emails. One thing that's always frustrated me is an absence of early access to the code. The contracts are setup in a way where the offshore team is responsible for meeting functional requirements, which is what the executives are concerned with. This means, however, that architecture decisions, implementation details, pattern usage, and things that concern other developers are so deeply settled by the time the product is delivered that we're unable to offer feedback or request any real changes. Has anybody here managed an offshore project that hasn't experienced these problems? Specifically, I'm wondering if there's any way to structure the contracts to compel offshore teams to work in shorter cycles and re-factor or re-design based on feedback from on-shore developers. I haven't had too much experience with agile methodologies (I agree with the general principles, but work in a conservative shop that has it's entrenched methodologies), but wonder whether these could somehow be adapted to help manage offshore development. Overall, I'm looking to minimize the surprises and maintenance nightmares that inevitably arise when a development team is left to work in isolation for months at a time. A: I have done it and I prefer it. The contract will have to be on a time and materials basis, rather than a fixed bid. The fixed bid theoretically moves some risk to the vendor and may be more competitively priced but in reality it generates a need for so much more work like you describe, not to mention fights over change control definitions etc. So we just hire x number of bodies and work a lot more dynamically with them, assigning work on a task basis. They do not participate in Scrums though - there are onshore leads that will represent them. Essentially the onshore looks like he is doing the work of three people, but he is parceling out tasks to offshore. The onshore/offshore model does cost you some higher rates with the onshore person obviously.
[ "stackoverflow", "0014728262.txt" ]
Q: Event handling in SAPUI5 - Tree controls I am trying to build an application using SAPUI5. Right now I have a page with nodes listed as a tree, and a navigation frame at the center. I want to load various pages in the navigation frame based on the node selected in the tree. I tried to handle the JS event the following way, it doesn't seem to be working. function Tree_Click(oControlEvent){ alert(oControlEvent.getParameters.node); } //create the Tree control for the MENU block var MenuTree = new sap.ui.commons.Tree("MenuTree", {select : Tree_Click}); MenuTree.setTitle("Home"); MenuTree.setWidth("100%"); MenuTree.setHeight("auto"); MenuTree.setShowHeaderIcons(true); MenuTree.setShowHorizontalScrollbar(false); //create Tree Nodes var Node1 = new sap.ui.commons.TreeNode("Node_fruit", { text : "Fruit", expanded : true }); var Node2 = new sap.ui.commons.TreeNode("Node_veg", { text : "Vegetables", expanded : true }); var Node1_1 = new sap.ui.commons.TreeNode("Node_app", { text : "Apple", }); var Node2_1 = new sap.ui.commons.TreeNode("Node_carr", { text : "Carrot", }); Node2.addNode(Node2_1); Node1.addNode(Node1_1); //add Tree Node root to the Tree MenuTree.addNode(Node1); MenuTree.addNode(Node2); MenuTree.placeAt("menu_tree"); The alert seems to be returning 'undefined'. What am I doing wrong here? Thanks. A: Try: alert(oControlEvent.getParameter("node")); I've written up the snippet on Github. A: Or oControlEvent.getParameters().node. oControlEvent.getParameters without parentheses is a function pointer, not the return value of the function call...
[ "meta.stackexchange", "0000069346.txt" ]
Q: Save questions to visit later, but not exactly 'favourite' them Most of the time I find questions that I would want to log in later to answer. These wouldn't exactly be my favorite questions since that's not the intent. Would it be possible to create such a feature. This is not a duplicate of Any way to save a question (like in Reddit). Currently I would need to "favorite" a question and then remember to un-"favorite" it later. This 'visit-later' list can be autopurged after 10-20 questions or so. I do know that most questions would've been answered on SO by the time I come back home and login, but still.. A: This actually is one of the accepted uses of the "favorites" feature. With respect, your interpretation takes the name "favorites" a bit too literally; it's really more like "SO internal server-side bookmarks." I suspect that having a second queue of "temporary favorites" would lead to more confusion than it's worth. A: Favourites are by design immutable. And from an UI perspective no one would associate a star with add to answer later list. Answer Later or Save For Later whatever the name I need a tick-or-mark-this-question-because-I-can't-answer-it-right-now option. In the meantime I am using temporary comment reminders to track them.
[ "math.stackexchange", "0002053965.txt" ]
Q: Fixed point iteration-finding $g(x)$ I have an equation $f(x)= x^4 +2x^3 -5x^2 -7x-5=0 $ and I want to solve it (numerically) at [1.5,3] using the fixed point iteration-method, so I want to find a function g(x) such that $f(x)=0$ is equivalent to $g(x)=x$. However I've tried many different $g(x)$'s but can't seem to find one that converges to the solution (which is about 2.19). First of all, anyone has any idea which $g(x)$ I could use? Second is there a trick to finding it? Thanks in advance :) A: To get the solution to converge, besides $g(x)=x$ you need $|g'(x)| \lt 1$ at the root. The distance from the root is multiplied by about $|g'(x)|$ every iteration, so if that is less than $1$ it will converge. Powers change quickly and roots slowly, so a natural try is to write $$x^4 +2x^3 -5x^2 -7x-5=0\\x^4=-2x^3+5x^2+7x+5\\ x=\sqrt[4]{-2x^3+5x^2+7x+5}$$ It converges nicely starting at $0, 1$ and $3.5$ but fails starting from $4$ because the piece under the root goes negative. Another try, which I have not tested, would be to write $$x^4 +2x^3 -5x^2 -7x-5=0\\x^4=-2x^3+5x^2+7x+5\\ x=(-2x^3+5x^2+7x+5)/x^3$$ It is a bit of an art. If you don't know the root, you can't evaluate the derivative of your proposed $g(x)$ at it.
[ "stackoverflow", "0032815206.txt" ]
Q: Use MEF in ServiceStack services I'm trying to use MEF as ContainerAdapter in ServiceStack (https://github.com/ServiceStack/ServiceStack/wiki/The-IoC-container). I've made ContainerAdapter: internal class MefIocAdapter : IContainerAdapter { private readonly CompositionContainer _container; internal MefIocAdapter(CompositionContainer container) { _container = container; } public T TryResolve<T>() { return _container.GetExportedValue<T>(); } public T Resolve<T>() { return _container.GetExportedValueOrDefault<T>(); } } and registered it like so: public override void Configure(Container container) { container.Adapter = new MefIocAdapter(_mefContainer); } After registering service by RegisterService(System.Type, String) function, I'm getting MEF's exception. It can't find exports: ContractName ServiceStack.Auth.IAuthSession RequiredTypeIdentity ServiceStack.Auth.IAuthSession Am i misunderstood something? Why does Funq asks adapter container to resolve internal ServiceStack's dependency? Will funq use MEF to instantiate my services? (if not, is there something like service factory?) P.S. When I delete container.Adapter assignment it works (but ofc my MEF dependencies are null). A: When you register a Container Adapter you're telling ServiceStack to resolve all dependencies with the Adapter, it only searches ServiceStack's IOC if the dependency isn't found in your Adapter first. The issue here is that IAuthSession is an optional property dependency where your Adapter should return null if the dependency doesn't exist so ServiceStack can then check the dependency in Funq. In your adapter you've got it the wrong way round where Resolve<T> (used for resolving Constructor dependencies) returns the default value and TryResolve<T> throws an exception when it doesn't exist when it should return the default value. So I'd change your Adapter implementation to: public T TryResolve<T>() { return _container.GetExportedValueOrDefault<T>(); } public T Resolve<T>() { return _container.GetExportedValue<T>(); }
[ "stackoverflow", "0032206055.txt" ]
Q: Rebase using github’s api I have a original_repo with branch master that I forked to fork_repo. Using github’s API, I can create a branch in fork_repo but I would like that this branch is up to date with original_repo:master. It doesn’t seem possible to create a reference from an other repository (that would be quite strange), and I can’t find an endpoint to achieve what I want. A: I have the following work-arround, not very satisfying, but at least it fulfils my need: Create a pull request from original_repo:master to the fork_repo Accept the pull request Reset the head to remove the merge commit
[ "stackoverflow", "0003615968.txt" ]
Q: viewWillAppear not getting called for detailView of UISplitViewController I am experimenting with the splitViewController, introduced for iPads and am stuck at a point. I have a button on my detail view of the splitViewController, clicking on which a modal view opens. Now I want to change the positoning of UI controls on the detail view when the modal view gets dissmissed. A pretty obvious way of doing this would be to catch the view transition in the ViewWillAppear method of the detailView. But it's not being called in this case. I remember facing the same problem in tabBarController where [tabBarController viewWillAppear:animated] was needed to be set before viewWillAppear of views in each tab item got called. I tried doing this with the splitViewController as well, but this doesn't seem to to work. Any Ideas?? A: If the positioning is required due to an action that occurred in the modal view, you should use an explicit delegate callback. That will allow you to clearly specify the control flow and resulting behaviour of your app. You should then define a protocol that has specific methods that carry pertinent information about the action taken. When the action occurs in the modal, perform the protocol method on the delegate, and it can react to that event (for you it seems to be a re-layout of button positioning). To get an idea of the methods that are abstract enough to handle generic modal behaviour, look at UIAlertViewDelegate protocol. Here the delegate will get an alertViewCancel: message when the user decides to take no action, or alertView:didDismissWithButtonIndex: when they selected one of the options presented to them. That is a good start for how to define the protocol. If you need a many view controllers to react to the action taken in the modal, say a Sign In modal, then a better mechanism is notifications.
[ "stackoverflow", "0062029064.txt" ]
Q: Assemble and analyze a list of lists from dataframe in python I've got a .csv file that looks a bit like this: COL_A COL_B COL_C 1 2020-05-26T00:01:01 99999 2 2020-05-26T00:01:02 99999 3 2020-05-26T00:01:03 99999 4 2020-05-26T00:01:04 2.3 5 2020-05-26T00:01:05 2.3 6 2020-05-26T00:01:06 2.3 7 2020-05-26T00:01:07 99999 8 2020-05-26T00:01:08 99999 9 2020-05-26T00:01:09 3.4 10 2020-05-26T00:01:10 3.4 11 2020-05-26T00:01:11 99999 12 2020-05-26T00:01:12 99999 I'd like to be able to identify the longest continuous span of rows where COL_C is < 5 and return that list of rows. The desired output would be something like: [ [4 2020-05-26T00:01:04 2.3, 5 2020-05-26T00:01:05 2.3, 6 2020-05-26T00:01:06 2.3] ], 3 The way I have approached this in theory is building a list of lists that meet the criteria, and then using max over the lists with len as the key. I've attempted this: import pandas as pd def max_c(csv_file): row_list = [] df = pd.read_csv(csv_file) for i, row in df.iterrows(): while row[2] < 5: span = [*row] row_list.append(span) return max(row_list, key=len) I know enough to know that this isn't correct syntax for what I'm trying to do and I can even explain why, but do not know enough to get the desired output. A: I'll use cumsum() to identify blocks and do a groupby: s = df['COL_C'].lt(5) sizes = s.groupby([s,(~s).cumsum()]).transform('size') * s # max block 1 size # max_size == 0 means all values are >= 5 max_size = sizes.max() df[sizes==max_size] Output: COL_A COL_B COL_C 3 4 2020-05-26T00:01:04 2.3 4 5 2020-05-26T00:01:05 2.3 5 6 2020-05-26T00:01:06 2.3 Details: s is: 0 False 1 False 2 False 3 True 4 True 5 True 6 False 7 False 8 True 9 True 10 False 11 False Name: COL_C, dtype: bool if we just do s.cumsum() then the True obviously belong to different groups. Instead we do (~s).cumsum() we get: 0 1 1 2 2 3 3 3 4 3 5 3 6 4 7 5 8 5 9 5 10 6 11 7 Name: COL_C, dtype: int64 Almost there, but each group of True is now preceded by a row of False. That suggests we group by both s and the negated cumsum.
[ "stackoverflow", "0048590768.txt" ]
Q: Heroku Django app: ECONNRESET: read ECONNRESET I'm getting the below error when trying to run the command heroku run python manage.py migrate from the terminal. ECONNRESET: read ECONNRESET I followed the link in the heroku docs to check if there was a firewall issue, but I had a successful telnet connection. I haven't been able to find any other examples of anyone running into this issue unless they are having a proxy/firewall issue but according to the telnet test it doesn't seem like I have a problem right? I've also tried testing any other heroku run command I can think of and I get the same result. A: After reading the logs it showed that there was an Error Code R13. I was able to follow this thread to get what I needed to be fixed but was unable to run anything that needs to actually be attached (like an interactive shell). Tried filing something with Heroku support but they basically said that it's outside the scope of free support. Disappointing.
[ "stackoverflow", "0047031239.txt" ]
Q: Combining strings in an array upto certain length var chars = 100; var s = [ "when an unknown printer took a galley of type and scrambled it to make a type specimen book", //contains 91 chars "essentially unchanged. It was popularised in the 1960s with the release", //contains 71 chars "unchanged essentially. popularised It was in the 1960s with the release", //contains 71 chars "It is a long established", //contains 24 chars "search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years", //contains 121 chars "injected humour and the like" //contains 28 chars ] I want to join (by \n) the next sentence if the number of characters in the present sentence is LESS than the variable chars=100 if chars=100 then 1) s[0] is less than 100 so I will have to join s[1] and s[1] 2) s[2] is less than 100 so I will have to join s[3] but still after combining they are 95 hence I need to further join s[4] 3) display s[5] as the list is empty Expected Output: 1) when an unknown printer took a galley of type and scrambled it to make a type specimen book essentially unchanged. It was popularised in the 1960s with the release 2) unchanged essentially. popularised It was in the 1960s with the release It is a long established search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years 3) injected humour and the like How do I implement in JS with fastest code possible? var x = ""; var y = []; for (var i = 0; i < s.length; i++) { if(x.length<100) { x=x+s[i]; continue; } y.push(x) x=""; } y.push(x) console.log(y.join("\n\n")); A: One way of doing it by parsing the array only once but using another array for the result: var chars = 100; var s = [ "when an unknown printer took a galley of type and scrambled it to make a type specimen book", "essentially unchanged. It was popularised in the 1960s with the release", "unchanged essentially. popularised It was in the 1960s with the release", //contains 71 chars "It is a long established", //contains 24 chars "search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years", //contains 121 chars "injected humour and the like" //contains 28 chars ], out = [], tmp; s.forEach((str, index) => { tmp = tmp ? tmp + '\n' + str : str; if (tmp.length > chars || index == s.length - 1) { out.push(tmp); tmp = null; } }); console.log(out.join('\n\n'));
[ "stackoverflow", "0028838935.txt" ]
Q: Add FK field in table when there are already records on that table Let say FB didnt have gender_id before in their users table, and suddenly they decided to add it as required field. What would happen if they add this field as fk in the same table users, when all other records doesn't have a value of gender_id. in fact mysql doesnt let you do that until u have an gender_id value to add to other records too. Of course they cannot delete all users to do this, my question is, what is the best solution for this case? 1.I was thinking add this field in a new table and reference the user_id with gender_id, so for the incoming users to necessarily have gender_id. 2.Add new record to genders like 0=male,1=female,2=unsigned so by default add unsigned value (2) for all other users What is you opinion? A: That’s exactly what I would do. Add the FK field with a default of 0, I like to use 0 as the unknown case, then maybe 1=male, 2=female. I would NOT allow NULL in the field, and always default it to 0 if no value provided.
[ "superuser", "0000199463.txt" ]
Q: How to change directory sort order only in the current Finder window? I can't stand how in one Finder window you set the files to be sorted by name, and then open another Finder window and need to sort by size, well it changes all Finder windows to the same thing. So you have to change your original Finder window again back to sort by name. Is there a way to make it so that only the folders you're in at that time change when you sort? Instead of all Finder windows? A: The sort order is per directory. If multiple windows show the same directory, changing one sort order changes all. However, this does not affect other folders. Also, this has nothing to do with "file organization", it's the Finder's view preferences. And they cannot be changed the way you seem to want them.
[ "stackoverflow", "0062873828.txt" ]
Q: Need to read the variable in file and write in other file using python. File type is text I am new to python. trying to write a program to read a file1 and write in file2 Ex: file1 contents a=value1 b=value2 c=dddd.eeeee.fffff d=value4 need to fetch the value of variable c and write in file2 file2 contents (suiteName: "aaaa.bbbb.ccc") i need to replace the value of suiteNmae: "aaaa.bbbb.ccc" with c i.e, file 2 suitename should replace with c value suiteName: dddd.eeeee.fffff This should be done using python file2 other values should not be changed import os import sys import csv file_path = "C:/Users/file1" replace_file_path = "C:/Users/file2" def get_c(file_name): with open(file_name, 'r') as f: fileone = csv.reader(f,delimiter='=') for row in fileone: if row[0] == 'c': return row[1] def get_suiteName(file_name): with open(file_name, 'r') as f1: filetwo = csv.reader(f1,delimiter=':') for row in filetwo: if row[0] == 'suiteName': return row[1] After this I am confused and this is also giving error A: In [102]: with open("file1.txt") as f1, open("file2.txt") as f2: ...: f1_value = [i.strip().split("=")[1] for i in f1.readlines() if i.strip().split("=")[0] == "c"][0] ...: f2_value = re.sub(r"suiteName: \"(.*)\"", "suiteName: \"{}\"".format(f1_value), f2.read()) ...: print(f2_value) ...: with open("file2.txt","w") as f3: ...: f3.write(f2_value) ...: override func broadcastStarted(withSetupInfo setupInfo: [String : NSObject]?) { if let userDefaults = UserDefaults(suiteName: "dddd.eeeee.fffff")
[ "stackoverflow", "0025835727.txt" ]
Q: Replicating tests for related subclasses with JUnit effeciently I saw the answers here How to test abstract class in Java with jUnit? that says not to test the parent class for your subclasses, but test each of the concrete classes. However, the tests are the same for each subclass (beyond what subclass is being used/tested). What is the most efficient/elegant way to test all of these beyond copy pasting into new test classes and replacing the subclasses being tested? I could see doing a loop, but are there better options? A: Use Parameterized. Example, assuming that Foobar & Barbar both implement Baz interface @RunWith(Parameterized.class) public class BazTest { @Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { { new Foobar(), new Barbar(), } }); } private Baz baz; public BazTest(Baz baz) { this.baz= baz; } @Test public void test() { // assert something about baz } }
[ "stackoverflow", "0060676903.txt" ]
Q: Having a problem adding a throws clause to a toString method header can someone help? I'm a CS student working on a project in java for class. We need to create a checked exception that's thrown in a LinkedQueue class. All that is fine. In my class above the LinkedQueue we need to acknowledge the exception and not handle it. So for each method in the class that calls the LinkedQueue method I added 'throws EmptyQueueException'. It works except for the toString method. When I add the throws clause I get an error that says "overrider java.lang.Object.toString" and Exception EmptyQueueException in not compatible with throws clause in Object.toString. Any ideas/help? thanks so much A: You can't. The contract of the Object#toString() method guarantees that it won't throw any checked exceptions, and since anything that's an Object (everything) has to meet this contract, you can't add a checked exception. toString() should never throw an exception of any kind anyway, because it's used in thousands of places all throughout applications and should be "safe" to call.
[ "stackoverflow", "0021279460.txt" ]
Q: Android: positioning items in ListView menu in java? I am really new into Android development, so I am sorry if this question may sound funny to some of you. I need to center the items of my ListView Menu just for the sake of aestheticism, but I really don't know how since the code is written only in java without the use of XML. package com.example.mysqltest; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; public class Menu extends ListActivity { String classes[] = {"ProductList", "example1", "example2", "example3", "example4", "example5"}; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, classes)); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { // TODO Auto-generated method stub super.onListItemClick(l, v, position, id); String local = classes[position]; try { Class ourClass = Class.forName("com.example.mysqltest." + local); Intent ourIntent = new Intent(Menu.this, ourClass); startActivity(ourIntent); } catch(ClassNotFoundException e){ e.printStackTrace(); } } } A: You need to create your own Adapter : public class MyAdapter extends BaseAdapter{ private LayoutInflater inflater; private List<String> data; public MyAdapter(Context context, List<String> data){ this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.data = data; } public int getSize(){ return data.getSize(); } public Object getItem(int position){ return data.get(position); } public View getView(View convertView, int position, ViewGroup parent){ View v = convertView; ViewHolder h; if(v == null){ v = inflater.inflate(R.layout.my_adapter, false); h = new ViewHolder(); t.tv = (TextView) v.findViewById(R.id.my_textview); v.setTag(); }else{ h = (ViewHolder) v.getTag(); } String s = (String) getItem(position); h.tv.setText(s); return v; } public class ViewHolder{ TextView tv; } } I don't really remember by heart because of the autocompletion in Eclipse, but it should look like this. Your my_adapter.xml is where you will place your TextView everywhere you want, you will be able to add more, like ImageViews and others TextViews. And to call it it's simple : MyAdapter adapter = new MyAdapter(context, myList); listView.setAdapter(adapter);
[ "math.stackexchange", "0001922832.txt" ]
Q: Alternating series: $\sum\limits_{n= 1}^{\infty} (-1)^{n-1} \frac{\ln(n)}{n}$ convergence? Determine whether the series converges absolutely, conditionally or diverges? $$\sum\limits_{n= 1}^{\infty} (-1)^{n-1} \frac{\ln(n)}{n}$$ I know that $\sum|a_{n}|$ diverges by using the comparison test: $$\frac{\ln(n)}{n} > \frac{1}{n}$$ and the smaller, r.h.s being the divergent harmonic series. So, should my conclusion for the alternating series be divergent or convergent conditionally*? * How to estimate whether the alternating series terms are cancelling? A: Let $f(x)=\frac{\ln x}{x}$ so $f'(x)=\frac{1-\ln x}{x^2}\le 0$ for $x\ge e$ and so the sequence $\left(\frac{\ln n}{n}\right)_{n\ge3}$ is decreasing to $0$. Apply now the alternating series criteria to conclude the convergence of the series. A: Since $\frac{\log n}{n}$ is a decreasing function on $n\geq 3$ and $\{(-1)^n\}_{n\geq 1}$ is a sequence with bounded partial sums, the series is convergent by Dirichlet's test. Moreover, by exploiting the integral representation for $\log(n)$ provided by Frullani's theorem, we have: $$ S=\sum_{n\geq 1}\frac{(-1)^{n-1}\log(n)}{n}=\int_{0}^{+\infty}\frac{e^{-x}\log(2)-\log(1+e^{-x})}{x}\,dx\tag{1}$$ and by the integral representation for the Euler-Mascheroni constant we have: $$ \sum_{n\geq 1}\frac{(-1)^{n-1}\log(n)}{n} = \color{red}{\frac{\log^2(2)}{2}-\gamma\log(2)}\approx -0.1598689 .\tag{2}$$
[ "stackoverflow", "0048435671.txt" ]
Q: join two lists with columns showing values from each table without duplicates I have two tables. Each table has two columns. The first column of each table is the matching/mapping column. I have no idea how to explain what I am trying to do so I'll use an example. table 1 | col1 | col2 | |------|-------| | a | one | | a | two | | b | three | | c | four | table 2 | col1 | col2 | |------|-------| | a | five | | b | six | | b | seven | | d | eight | desired output | col1 | table1 | table2 | |------|--------|--------| | a | one | five | | a | two | | | b | three | six | | b | | seven | | c | four | | | d | | eight | (the empty cells are null) Basically I am looking for a summary table that shows all the col2 options for that col1 from each table. I hope this makes sense... A: You need FULL OUTER JOIN and ROW_NUMBER SELECT COALESCE(a.col1, b.col2), COALESCE(a.col2, ''), COALESCE(b.col, '') FROM (SELECT *, Rn = Row_number()OVER(partition BY col1 ORDER BY @@SPID) FROM table1) a FULL JOIN (SELECT *, Rn = Row_number()OVER(partition BY col1 ORDER BY @@SPID) FROM table2) b ON a.col1 = b.col1 AND a.Rn = b.Rn
[ "stackoverflow", "0013385984.txt" ]
Q: Insert sql statement in php Error: No database selected So I'm attempting to make a registration form. I've made a php MySQL class which uses the constructor to make the connection with new MySQLi() for verifyLogin function and mysql_connect() for my addElement function. The error is with my addElement function, the SQL statement writes out properly but it doesn't seem to connect to the database. I've checked that all the names are correct. Any ideas? <?php class MySQL { private $connection; private $conn; private $databaseName; function __construct($dbServer, $dbUser, $dbPassword, $dbName) { $this->connection = new MySQLi($dbServer, $dbUser, $dbPassword, $dbName) or die('PROBLEM CONNECTING TO DATABASE'); $this->conn = mysql_connect($dbServer, $dbUser, $dbPassword); echo $this->conn; $databaseName = $dbName; } function verifyLogin($table, $email, $password) { $query = "SELECT * FROM ? WHERE email = ? AND password = ? LIMIT 1"; if($statement = $this->connection->prepare($query)) { $statement->bind_param('sss', $table, $email, $password); $statement->execute(); if($statement->fetch()) { $statement->close(); return true; } else { return false; } } } function addElement($table, $firstName, $lastName, $email, $mobile, $password, $faculty, $campus) { $query = "INSERT INTO $table (first_name, last_name, email, mobile, password, faculty, campus_location) VALUES('$firstName', '$lastName','$email','$mobile', '$password','$faculty','$campus');"; echo $query; mysql_select_db($this->databaseName, $this->conn); if(!mysql_query($query)) { die('Error: ' . mysql_error()); } mysql_close($this->connection); } } ?> A: To select a database in MySQLi, you need to select it like so: $db = new mysqli("localhost", "my_user", "my_password", "database_name"); or $db = new mysqli("localhost", "my_user", "my_password"); $db->select_db('database_name'); as opposed to MySQL: $db = mysql_connect('localhost', 'my_user', 'my_password'); $db_selected = mysql_select_db('database_name', $db); MySQLi : http://www.php.net/manual/en/mysqli.select-db.php MySQL : http://www.php.net/manual/en/function.mysql-select-db.php
[ "stackoverflow", "0033602478.txt" ]
Q: How to handle OpenSSL.SSL.Error while using twisted.web.client.Agent on Facebook graph api? I am running the ff. code from a virtualenv on Mac OS X (Yosemite): # testfb.py from twisted.internet import reactor from twisted.python import log from twisted.web.client import Agent GRAPH_API = "https://graph.facebook.com/v2.5" def stop(_): reactor.stop() def get_me(access_token): agent = Agent(reactor) uri = "{}/me?access_token={}".format(GRAPH_API, access_token) log.msg("uri:" + uri) return agent.request("GET", uri) if __name__ == "__main__": import sys access_token = sys.argv[1] d = get_me(access_token) d.addErrback(log.err) d.addCallback(stop) reactor.run() And I get: Failure: twisted.web._newclient.ResponseNeverReceived: [<twisted.python.failure.Failure OpenSSL.SSL.Error: [('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE', 'certificate verify failed')]>] I don't have this issue when I call the uri in curl. BTW, I also installed service_identity using pip on the virtualenv. A: You probably don't have any OpenSSL trust roots configured. This used to happen automatically by accident because Cryptography linked against the built-in version of OpenSSL from OS X. Since the headers for that version were removed in El Capitan, Cryptography now ships wheels with their own built-in version of pyOpenSSL. This is a bug in Twisted, and we know about it; you can read more about it here: https://twistedmatrix.com/trac/ticket/6372. It's been open for a while; because it worked by accident for a long time, it hasn't been a high priority. Thanks to bug reports from folks like you, this is changing... In the meanwhile, though, you have two possible options. One is that you can install OpenSSL from Homebrew, which will automatically put some certificate authority certificates in the default location that Cryptography's OpenSSL is already looking for them, with brew install openssl. (You can see these certificate authority certificates in /usr/local/etc/openssl/cert.pem after installing it) Another is that you can get some certificates from Certifi, and then set the (undocumented) environment variable that tells OpenSSL to look for them, by doing, for example, export SSL_CERT_FILE="$(python -m certifi)" in your shell before invoking your Python program. Sorry for the, and I hope this answers your question!
[ "stackoverflow", "0043020998.txt" ]
Q: App stop working after button click so I´m making an app with fragments and I want a sound on button click. Everything works except when I click on the button the app stop working. I put an onclick method named playAnother on the button. I think the problem might be there in .java file: I dont know what to do I´m total beginner. Have a nice day! A: The method playAnother(View view) must be in your Activity, not in fragment. OR If you want to handle the button click in your fragment you can give your button an id: <Button android:id="@+id/button" . . And then in your fragment's onCreateView() public View onCreateView(...) { // First we save the reference to the views of your fragment View view = inflater.inflate(R.layout.fragment_three, container, false); // Then we need to find the button-view Button button = (Button) view.findViewById(R.id.button); // And finally we can register OnClickListener for the button button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Handle your button click here } }); return view; }
[ "stackoverflow", "0061649781.txt" ]
Q: Spark with Hive, Unable to instantiate SparkSession with Hive support because Hive classes are not found The spark app is to load data from Hive: SparkSession spark = SparkSession.builder() .appName(topics) .config("hive.metastore.uris", "thrift://device1:9083") .enableHiveSupport() .getOrCreate(); I start the spark by: spark-submit --master local[*] --class zhihu.SparkConsumer target/original-kafka-consumer-0.1-SNAPSHOT.jar --jars spark-hive_2.11-2.4.4.jar maven pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.zhihu</groupId> <artifactId>kafka-consumer</artifactId> <packaging>jar</packaging> <version>0.1-SNAPSHOT</version> <name>kafkadev</name> <url>http://maven.apache.org</url> <repositories> <repository> <!-- Proper URL for Cloudera maven artifactory --> <id>cloudera</id> <url>https://repository.cloudera.com/artifactory/cloudera-repos/</url> </repository> </repositories> <dependencies> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core --> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.8.2</version> </dependency> <dependency> <!-- Spark dependency --> <groupId>org.apache.spark</groupId> <artifactId>spark-sql_2.11</artifactId> <version>2.4.4</version> <scope>compile</scope> </dependency> <dependency> <!-- Spark dependency --> <groupId>org.apache.spark</groupId> <artifactId>spark-hive_2.11</artifactId> <version>2.4.4</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-streaming_2.11</artifactId> <version>2.4.4</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-streaming-kafka-0-10_2.11</artifactId> <version>2.4.4</version> </dependency> <dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka-clients</artifactId> <version>2.1.0</version> <exclusions> <exclusion> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> </exclusion> <exclusion> <groupId>org.apache.log4j</groupId> <artifactId>log4j-core</artifactId> </exclusion> <exclusion> <groupId>log4j</groupId> <artifactId>log4j</artifactId> </exclusion> </exclusions> <scope>compile</scope> </dependency> <!-- gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.hive</groupId> <artifactId>hive-metastore</artifactId> <version>2.1.1-cdh6.2.0</version> </dependency> <dependency> <groupId>org.apache.hive</groupId> <artifactId>hive-service</artifactId> <version>2.1.1-cdh6.2.0</version> </dependency> <!-- runtime Hive --> <dependency> <groupId>org.apache.hive</groupId> <artifactId>hive-common</artifactId> <version>2.1.1-cdh6.2.0</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.apache.hive</groupId> <artifactId>hive-beeline</artifactId> <version>2.1.1-cdh6.2.0</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.apache.hive</groupId> <artifactId>hive-jdbc</artifactId> <version>2.1.1-cdh6.2.0</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.apache.hive</groupId> <artifactId>hive-shims</artifactId> <version>2.1.1-cdh6.2.0</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.apache.hive</groupId> <artifactId>hive-exec</artifactId> <version>2.1.1-cdh6.2.0</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.apache.hive</groupId> <artifactId>hive-serde</artifactId> <version>2.1.1-cdh6.2.0</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.apache.hive</groupId> <artifactId>hive-contrib</artifactId> <version>2.1.1-cdh6.2.0</version> <scope>runtime</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.2.1</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <filters> <filter> <artifact>*:*</artifact> <excludes> <exclude>**/Log4j2Plugins.dat</exclude> </excludes> </filter> <filter> <artifact>*:*</artifact> <excludes> <exclude>META-INF/*.SF</exclude> <exclude>META-INF/*.DSA</exclude> <exclude>META-INF/*.RSA</exclude> </excludes> </filter> </filters> <artifactSet> <excludes> <exclude>classworlds:classworlds</exclude> <exclude>junit:junit</exclude> <exclude>jmock:*</exclude> <exclude>*:xml-apis</exclude> <exclude>org.apache.maven:lib:tests</exclude> </excludes> </artifactSet> <skip>true</skip> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> it looks no problem, but it always raised: 20/05/07 12:03:17 INFO spark.SparkContext: Added JAR file:/data/projects/zhihu_scraper/consumers/target/original-kafka-consumer-0.1-SNAPSHOT.jar at spark://device2:42395/jars/original-kafka-consumer-0.1-SNAPSHOT.jar with timestamp 1588824197724 20/05/07 12:03:17 INFO executor.Executor: Starting executor ID driver on host localhost 20/05/07 12:03:17 INFO util.Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 33849. 20/05/07 12:03:17 INFO netty.NettyBlockTransferService: Server created on device2:33849 20/05/07 12:03:17 INFO storage.BlockManager: Using org.apache.spark.storage.RandomBlockReplicationPolicy for block replication policy 20/05/07 12:03:17 INFO storage.BlockManagerMaster: Registering BlockManager BlockManagerId(driver, device2, 33849, None) 20/05/07 12:03:17 INFO storage.BlockManagerMasterEndpoint: Registering block manager device2:33849 with 366.3 MB RAM, BlockManagerId(driver, device2, 33849, None) 20/05/07 12:03:17 INFO storage.BlockManagerMaster: Registered BlockManager BlockManagerId(driver, device2, 33849, None) 20/05/07 12:03:17 INFO storage.BlockManager: Initialized BlockManager: BlockManagerId(driver, device2, 33849, None) 20/05/07 12:03:17 INFO handler.ContextHandler: Started o.s.j.s.ServletContextHandler@63e5e5b4{/metrics/json,null,AVAILABLE,@Spark} Exception in thread "main" java.lang.IllegalArgumentException: Unable to instantiate SparkSession with Hive support because Hive classes are not found. at org.apache.spark.sql.SparkSession$Builder.enableHiveSupport(SparkSession.scala:869) at zhihu.SparkConsumer.main(SparkConsumer.java:72) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.spark.deploy.JavaMainApplication.start(SparkApplication.scala:52) at org.apache.spark.deploy.SparkSubmit.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:845) at org.apache.spark.deploy.SparkSubmit.doRunMain$1(SparkSubmit.scala:161) at org.apache.spark.deploy.SparkSubmit.submit(SparkSubmit.scala:184) at org.apache.spark.deploy.SparkSubmit.doSubmit(SparkSubmit.scala:86) at org.apache.spark.deploy.SparkSubmit$$anon$2.doSubmit(SparkSubmit.scala:920) at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:929) at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala) 20/05/07 12:03:18 INFO spark.SparkContext: Invoking stop() from shutdown hook I have tried all answers in this post How to create SparkSession with Hive support. But, none of them work for me. A: <dependency> <!-- Spark dependency --> <groupId>org.apache.spark</groupId> <artifactId>spark-hive_2.11</artifactId> <version>2.4.4</version> <scope>compile</scope> </dependency> I dont know why compile is the scope it should be runtime. Since You are using maven shade plugin you can package uber jar(with target/original-kafka-consumer-0.1-SNAPSHOT.jar) with all dependencies in one umbrella/archive and it will be in the classpath so that nothing is missed try this. Also hive-site.xml should be in classpath. then there is no need to seperately configure metastoreuris. in programatic way. Further reading
[ "stackoverflow", "0035261524.txt" ]
Q: website shows unavailable while taking DB backup? My website is created using Drupal 7 on one instance of amazon & database is on amazon RDS . whenever i am taking backup of database using Mysql with root user & simultaneously when a developer try to clear the cache on the website that time website goes offline untill backup gets over say for around 30 min this happens everytime . what is the solution to avoid this problem. A: Try to use this parameter when taking backup with mysqldump . --lock-tables for MyISAM storage engine. --single-transaction for Innodb storage engine. --lock-tables Lock all tables before dumping them. The tables are locked with READ LOCAL to allow concurrent inserts in the case of MyISAM tables. For transactional tables such as InnoDB and BDB, --single-transaction is a much better option, because it does not need to lock the tables at all.--single-transaction produces a checkpoint that allows the dump to capture all data prior to the checkpoint while receiving incoming changes. Those incoming changes do not become part of the dump. That ensures the same point-in-time for all tables.
[ "stackoverflow", "0012881964.txt" ]
Q: How to get the List of Facebook Applications for a user using Graph API How can i get the list of applications created by the User. I would like to fetch this list using the Facebook Graph API. Could you please advice on which API on the Facebook Graph API to use and how to use it. A: Take a look at /me/accounts. I believe what you are looking or is at that endpoint. Description of the endpoint - The Facebook apps and pages owned by the current user. Permissions needed - manage_pages yields access_tokens that can be used to query the Graph API on behalf of the app/page Take a look at the user endpoint documentation, there will be more information there. Remember that ownership of an application doesn't necessarily mean that it was that user who created it, it just means that the user is an administrator of the application.
[ "physics.stackexchange", "0000292948.txt" ]
Q: When will the block lift up the front wheel? Here is my problem: the luggage is being pulled with force $T$ at an angle $\theta$. I'd like to know when the front wheel will lift up. How do I even start? Before lifting it up, all I know is that with a force $T$ the luggage is going at a constant velocity. Therefore I used the conditions for equilibrium: \begin{equation} \sum_i{F_i} \,\,\,\,\text{and}\,\,\,\,\sum_i{r_i\times F_i} \end{equation} However I want to find $T$ and $\theta$, as functions of $\mu$ friction coefficient, $g$ gravitational acceleration and for which the front wheel will lift up. I'm using $F_i = -\mu |R_i|\vec{i}$ Thanks How can I find it? A: As this is a homework & exercises type question, I'll only point you in the right direction. First add some dimensions and a coordinate system: Before lifting it up, all I know is that with a force $T$ the luggage is going at a constant velocity By Newton this means that there's no net force and no net torque acting on the suitcase: $$\Sigma_i \vec{F}_i=0$$ $$\Sigma \vec{\tau}_i=0$$ First look at all forces in the $y$-direction: $T\sin\theta+R_1+R_2-W=0\tag{1}$ The forces in the $x$-direction: $T\cos\theta-\mu R_1-\mu R_2=0\tag{2}$ Finally a torque balance. We can make this balance about any point, so it's desirable to choose the point carefully. We choose the point where $\vec{T}$ acts on the luggage because that way the torque exerted by $\vec{T}$ and $\vec{R_2}$ is $0$. The balance then becomes: $R_1\times L-W\times \frac{L}{2}=0\tag{3}$ You now have three equations and three unknowns. Solve the system of equations for these unknowns. This will give you an expression of $T$ inthe knowns only: $$T=f(\mu,W)$$ Increasing $T$ above that value will cause net torque and thus lift.
[ "stackoverflow", "0050935534.txt" ]
Q: Implementing a class with a dynamic datatype attribute C# i want to implement a class that one of the attribute is dynamic but i can't seem to figure out how to do that... public class myClass { public datetime timeStamp { get; set; } public object variable { get; set; } public string name { get; set; } } I need to read a archive that has the type of the "variable" inside as a integer, for example This is just an exaple of a json or something that i will use, the "variable" attribute of the clas (in this example) will be a string, but there are sometimes that this attribute should be a integer(example2) Ex1: {"name" : "Variable1" , "variable" : "string" : "myString" , "timeStamp" : "852852852" } Ex2: {"name" : "Variable2" , "variable" : "int32" : "125125" , "timeStamp" : "852852852" } A: You could make OPC_UA a generic class: class OPC_UA<T> { public DateTime TimeStamp { get; set; } public T Variable { get; set; } public string Name { get; set; } } And then you can instantiate the type using reflection methods: Type type = Type.GetType("System.Int32"); Type genericizedType = typeof(OPC_UA<>).MakeGenericType(type); dynamic opc_ua = Activator.CreateInstance(genericType); opc_ua.Variable = 5; // For example
[ "stackoverflow", "0054638108.txt" ]
Q: Is this JSON data parsed into Python dict correctly? Cannot extract components of data parsed from JSON to Python dictionary. I attempted to print the value corresponding with a dictionary entry but get an error. import urllib, json, requests url = "https://storage.googleapis.com/osbuddy-exchange/summary.json" response = urllib.urlopen(url) data = json.loads(response.read()) print type(data) for key, value in data.iteritems(): print value print '' print "data['entry']: ", data['99'] print "name: ", data['name']``` I was hoping I could get attributes of an entry. Say the 'buy_average' given a specific key. Instead I get an error when referencing specific components. <type 'dict'> 22467 {u'sell_average': 3001, u'buy_average': 0, u'name': u'Bastion potion(2)', u'overall_average': 3001, u'sp': 180, u'overall_quantity': 2, u'members': True, u'sell_quantity': 2, u'buy_quantity': 0, u'id': 22467} 22464 {u'sell_average': 4014, u'buy_average': 0, u'name': u'Bastion potion(3)', u'overall_average': 4014, u'sp': 270, u'overall_quantity': 612, u'members': True, u'sell_quantity': 612, u'buy_quantity': 0, u'id': 22464} 5745 {u'sell_average': 0, u'buy_average': 0, u'name': u'Dragon bitter(m)', u'overall_average': 0, u'sp': 2, u'overall_quantity': 0, u'members': True, u'sell_quantity': 0, u'buy_quantity': 0, u'id': 5745} ... data['entry']: {u'sell_average': 7843, u'buy_average': 7845, u'name': u'Ranarr potion (unf)', u'overall_average': 7844, u'sp': 25, u'overall_quantity': 23838, u'members': True, u'sell_quantity': 15090, u'buy_quantity': 8748, u'id': 99} name: Traceback (most recent call last): File "C:/Users/Michael/PycharmProjects/osrsGE/osrsGE.py", line 16, in <module> print "name: ", data['name'] KeyError: 'name' Process finished with exit code 1 A: There is no key named 'name' in the dict named 'data'. The first level keys are numbers like: "6", "2", "8",etc The seconds level object has a key named 'name' so code like: print(data['2']['name']) # Cannonball should work
[ "stackoverflow", "0016465230.txt" ]
Q: Select Statement based on user defined variable I am trying to do a simple select statement based on the input of the user (SSRS). Help! select * from Table1 WHERE Case when @x = 'Yes' then (select * from Table1 where [Column1] < 0) end; case when @x = 'No' then (select * from Table1 where [Column1] > 0) end; Thank you in advance KJ A: It should be as simple as select * from Table1 WHERE (@x = 'Yes' AND [Column1] < 0) OR (@x = 'No' AND [Column1] > 0); By the way, SELECT * is really bad coding, you really should specify each column you are returning.
[ "stackoverflow", "0060630415.txt" ]
Q: Distance converter keeps navigating to PHP page I'm working on a basic distance converter and clicking the form to submit keeps redirecting to the somephpfile.php (which doesn't exist as this is an exercise) instead of posting the converted number in kilometers (mi > km) to the div "container bottom." Here is what I've got so far, any help would be much appreciated: <!doctype html> <html> <head> <meta charset="UTF-8"> <title>Miles to Kilometers Converter</title> <!--/ /-------- Normalize CSS --------/ /--> <link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" rel="stylesheet"> <!--/ /-------- Google Fonts --------/ /--> <link href="https://fonts.googleapis.com/css?family=Oswald|PT+Sans&display=swap" rel="stylesheet"> <!--/ /-------- My Styles --------/ /--> <link href="styles.css" rel="stylesheet"> </head> <body> <h1>Miles to Kilometers Converter</h1> <div class="container top"> <p>Type in a number of miles and click the button to convert the distance to kilometers.</p> <form method="post" action="somephpfile.php" id="convert"> <input type="number" name="distance" id="distance" placeholder="distance"> <input type="submit" name="convertdist" value="Convert Distance"> </form> </div> <div class="container bottom" id="answer"> <h2 class="invisible">Answer goes here</h2> </div> <script> var miles = parseInt(document.getElementById("distance").value); var kilometers = (miles * 1.609344); var answer = document.createElement("P"); answer.innerHTML = `"${miles} miles converts to ${kilometers} kilometers"`; document.getElementsByName("convertdist").addEventListener("click", function(event){ event.preventDefault(); document.getElementById("answer").appendChild(); }); </script> </body> </html> A: <form method="post" action="somephpfile.php" id="convert"> <input type="number" name="distance" id="distance" placeholder="distance"> <input type="submit" name="convertdist" value="Convert Distance"> </form> This form will be submitted when you click on the submit button. Make the form as follows. <form id="convert"> <!-- Taken out the attributes method and action --> <input type="number" name="distance" id="distance" placeholder="distance"> <input type="button" name="convertdist" value="Convert Distance" onclick="convert()"> <!-- Changed the button type submit->button --> </form> For JavaScript, you have to enclose the JS logic in a function or so, and call it during onclick of the submit button, like: <script> function convert(){ var miles = parseInt(document.getElementById("distance").value); var kilometers = (miles * 1.609344); var answer = document.createElement("P"); answer.innerHTML = `"${miles} miles converts to ${kilometers} kilometers"`; document.getElementById("answer").appendChild(answer); } </script> Things you got wrong are: Conversion + Appending the answer should be callable, meaning it should be a function. The conversion function should be invoked whenever the button is clicked. So, it should be bound to the onclick event of the convert button. Any HTML form with a button of type submit will be submitted to the target specified by action attribute no matter what, unless you block that with event.preventDefault() in your JS. You did that, but not where it should have been done. The following in your code makes no sense from where you have put it. document.getElementsByName("convertdist").addEventListener("click", function(event){ event.preventDefault(); document.getElementById("answer").appendChild(); }); Put the working version in this fiddle. Find time to check out.
[ "stackoverflow", "0012586180.txt" ]
Q: cropping IplImage most effectively I wonder what is the most effective way of cropping an IplImage in opencv. I currently do the following, but it seems too complicated and I'm sure there's a better way of doing things. // set ROI on original image, create 'tmp' image and copy data over. cvSetImageROI(orig_image, cvRect(55, 170, 530, 230)); IplImage *tmp = cvCreateImage(cvGetSize(orig_image), orig_image->depth, orig_image->nChannels); cvCopy(m_depth_run_avg, tmp, NULL); cvResetImageROI(orig_image); // copy temporary image back to original image. IplImage *orig_image= cvCreateImage(cvGetSize(tmp), tmp->depth, tmp->nChannels); cvCopy(tmp, orig_image, NULL); is there a better way to crop a image? A: Yes, there is. You seem to be recreating the original image at the end. That is not necessary, as the following code demonstrates: IplImage* orig = cvLoadImage("test.jpg"); if (!orig) { return -1; } printf("Orig dimensions: %dx%d\n", orig->width, orig->height); cvSetImageROI(orig, cvRect(0, 250, 350, 350)); IplImage *tmp = cvCreateImage(cvGetSize(orig), orig->depth, orig->nChannels); cvCopy(orig, tmp, NULL); cvResetImageROI(orig); orig = cvCloneImage(tmp); printf("Orig dimensions after crop: %dx%d\n", orig->width, orig->height); cvNamedWindow( "result", CV_WINDOW_AUTOSIZE ); cvShowImage( "result", orig); cvWaitKey( 0 ); cvDestroyWindow( "result" ); Unfortunately, it's imperative that you create a temporary image to store the result of cvCopy().
[ "apple.stackexchange", "0000107553.txt" ]
Q: OSX 10.9 Mavericks Update Causes Non-Stop Kernel Panics I have a 2009 iMac that I just upgraded to 10.9 OSX Mavericks and after migrating my old software over, my computer is having random kernel panics within 5 minutes of being booted up. Can anyone find any clues in the panic log below? Tue Oct 29 18:56:03 2013 panic(cpu 0 caller 0xffffff80066ddd0f): "tcp_lock: so=0xffffff801355b7e8 NO PCB! lr=0xffffff800682fecf lrh= 0xffffff800681a7d6:0xffffff80068309f6 0xffffff8006811d13:0xffffff80068309f6 0xffffff800681a2c4:0xffffff80068309f6 0xffffff800681a2c4:0xffffff80066d6816 \n"@/SourceCache/xnu/xnu-2422.1.72/bsd/netinet/tcp_subr.c:2454 Backtrace (CPU 0), Frame : Return Address 0xffffff80861dbce0 : 0xffffff8006422f69 0xffffff80861dbd60 : 0xffffff80066ddd0f 0xffffff80861dbda0 : 0xffffff800682fecf 0xffffff80861dbdc0 : 0xffffff7f88980225 0xffffff80861dbde0 : 0xffffff80068308df 0xffffff80861dbe10 : 0xffffff800681192d 0xffffff80861dbe30 : 0xffffff80066dffa5 0xffffff80861dbe90 : 0xffffff80066dfd5d 0xffffff80861dbec0 : 0xffffff80066b5771 0xffffff80861dbf20 : 0xffffff800644a15a 0xffffff80861dbfb0 : 0xffffff80064d6aa7 Kernel Extensions in backtrace: com.apple.nke.applicationfirewall(153.0)[050FCA37-3ACE-343F-93DE-A42A92EF1AD9]@0xffffff7f8897d000->0xffffff7f88984fff BSD process name corresponding to current thread: kernel_task Mac OS version: 13A603 Kernel version: Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE_X86_64 Kernel UUID: 1D9369E3-D0A5-31B6-8D16-BFFBBB390393 Kernel slide: 0x0000000006200000 Kernel text base: 0xffffff8006400000 System model name: iMac12,1 (Mac-942B5BF58194151B) System uptime in nanoseconds: 118627507779 last loaded kext at 33935262213: com.apple.driver.AppleHWSensor 1.9.5d0 (addr 0xffffff7f87e33000, size 36864) loaded kexts: com.seagate.driver.PowSecLeafDriver_10_5 5.2.3 com.speedbit.driver.vadriver 1.0.8 com.seagate.driver.PowSecDriverCore 5.2.3 com.apple.driver.AppleHWSensor 1.9.5d0 com.apple.driver.AudioAUUC 1.60 com.apple.driver.AppleTyMCEDriver 1.0.2d2 com.apple.driver.AGPM 100.14.11 com.apple.driver.AppleBluetoothMultitouch 80.14 com.apple.filesystems.autofs 3.0 com.apple.iokit.IOBluetoothSerialManager 4.2.0f6 com.apple.driver.AppleMikeyHIDDriver 124 com.apple.driver.AppleHDAHardwareConfigDriver 2.5.2fc2 com.apple.driver.AppleHDA 2.5.2fc2 com.apple.driver.AppleUpstreamUserClient 3.5.13 com.apple.kext.AMDFramebuffer 1.1.4 com.apple.driver.ApplePolicyControl 3.4.12 com.apple.iokit.IOUserEthernet 1.0.0d1 com.apple.AMDRadeonX3000 1.1.4 com.apple.iokit.IOBluetoothUSBDFU 4.2.0f6 com.apple.driver.AppleIntelHD3000Graphics 8.1.8 com.apple.driver.AppleMikeyDriver 2.5.2fc2 com.apple.iokit.BroadcomBluetoothHostControllerUSBTransport 4.2.0f6 com.apple.Dont_Steal_Mac_OS_X 7.0.0 com.apple.driver.AppleThunderboltIP 1.0.10 com.apple.driver.AppleSMCLMU 2.0.4d1 com.apple.kext.AMD6000Controller 1.1.4 com.apple.driver.AppleLPC 1.7.0 com.apple.driver.AppleHWAccess 1 com.apple.driver.AppleSMCPDRC 1.0.0 com.apple.driver.ACPI_SMC_PlatformPlugin 1.0.0 com.apple.driver.AppleMuxControl 3.4.12 com.apple.driver.AppleBacklight 170.3.5 com.apple.driver.AppleMCCSControl 1.1.12 com.apple.driver.AppleIntelSNBGraphicsFB 8.1.8 com.apple.driver.AppleIRController 325.7 com.apple.iokit.SCSITaskUserClient 3.6.0 com.apple.driver.AppleUSBCardReader 3.3.5 com.apple.driver.AppleFileSystemDriver 3.0.1 com.apple.AppleFSCompression.AppleFSCompressionTypeDataless 1.0.0d1 com.apple.AppleFSCompression.AppleFSCompressionTypeZlib 1.0.0d1 com.apple.BootCache 35 com.apple.driver.XsanFilter 404 com.apple.iokit.IOAHCIBlockStorage 2.4.0 com.apple.driver.AppleUSBHub 650.4.4 com.apple.iokit.AppleBCM5701Ethernet 3.6.9b9 com.apple.driver.AirPort.Atheros40 700.74.5 com.apple.driver.AppleAHCIPort 2.9.5 com.apple.driver.AppleFWOHCI 4.9.9 com.apple.driver.AppleUSBEHCI 650.4.1 com.apple.driver.AppleUSBUHCI 650.4.0 com.apple.driver.AppleACPIButtons 2.0 com.apple.driver.AppleRTC 2.0 com.apple.driver.AppleHPET 1.8 com.apple.driver.AppleSMBIOS 2.0 com.apple.driver.AppleACPIEC 2.0 com.apple.driver.AppleAPIC 1.7 com.apple.driver.AppleIntelCPUPowerManagementClient 216.0.0 com.apple.nke.applicationfirewall 153 com.apple.security.quarantine 3 com.apple.driver.AppleIntelCPUPowerManagement 216.0.0 com.apple.driver.AppleMultitouchDriver 245.13 com.apple.driver.AppleBluetoothHIDKeyboard 170.15 com.apple.driver.IOBluetoothHIDDriver 4.2.0f6 com.apple.driver.AppleHIDKeyboard 170.15 com.apple.kext.triggers 1.0 com.apple.iokit.IOSerialFamily 10.0.7 com.apple.driver.DspFuncLib 2.5.2fc2 com.apple.vecLib.kext 1.0.0 com.apple.iokit.IOAudioFamily 1.9.4fc11 com.apple.kext.OSvKernDSPLib 1.14 com.apple.iokit.IOSurface 91 com.apple.iokit.IOAcceleratorFamily 98.7.1 com.apple.iokit.IOBluetoothHostControllerUSBTransport 4.2.0f6 com.apple.iokit.IOBluetoothFamily 4.2.0f6 com.apple.kext.AMDSupport 1.1.4 com.apple.AppleGraphicsDeviceControl 3.4.12 com.apple.driver.AppleHDAController 2.5.2fc2 com.apple.iokit.IOHDAFamily 2.5.2fc2 com.apple.iokit.IOFireWireIP 2.2.5 com.apple.driver.AppleSMBusPCI 1.0.12d1 com.apple.driver.AppleSMC 3.1.6d1 com.apple.driver.IOPlatformPluginLegacy 1.0.0 com.apple.driver.IOPlatformPluginFamily 5.5.1d27 com.apple.driver.AppleThunderboltEDMSink 1.2.1 com.apple.driver.AppleGraphicsControl 3.4.12 com.apple.driver.AppleBacklightExpert 1.0.4 com.apple.iokit.IONDRVSupport 2.3.6 com.apple.driver.AppleSMBusController 1.0.11d1 com.apple.iokit.IOGraphicsFamily 2.3.6 com.apple.iokit.IOSCSIMultimediaCommandsDevice 3.6.0 com.apple.iokit.IOBDStorageFamily 1.7 com.apple.iokit.IODVDStorageFamily 1.7.1 com.apple.iokit.IOCDStorageFamily 1.7.1 com.apple.iokit.IOAHCISerialATAPI 2.6.0 com.apple.driver.AppleThunderboltDPOutAdapter 2.5.0 com.apple.driver.AppleThunderboltDPInAdapter 2.5.0 com.apple.driver.AppleThunderboltDPAdapterFamily 2.5.0 com.apple.driver.AppleThunderboltPCIDownAdapter 1.4.0 com.apple.iokit.IOUSBHIDDriver 650.4.4 com.apple.iokit.IOUSBMassStorageClass 3.6.0 com.apple.driver.AppleUSBMergeNub 650.4.0 com.apple.driver.AppleUSBComposite 650.4.0 com.apple.iokit.IOFireWireSBP2 4.2.5 com.apple.iokit.IOSCSIBlockCommandsDevice 3.6.0 com.apple.iokit.IOSCSIArchitectureModelFamily 3.6.0 com.apple.driver.AppleThunderboltNHI 1.9.2 com.apple.iokit.IOThunderboltFamily 2.8.5 com.apple.iokit.IOUSBUserClient 650.4.4 com.apple.iokit.IOEthernetAVBController 1.0.3b3 com.apple.driver.mDNSOffloadUserClient 1.0.1b4 com.apple.iokit.IO80211Family 600.34 com.apple.iokit.IONetworkingFamily 3.2 com.apple.iokit.IOAHCIFamily 2.6.0 com.apple.iokit.IOFireWireFamily 4.5.5 com.apple.iokit.IOUSBFamily 650.4.4 com.apple.driver.AppleEFINVRAM 2.0 com.apple.driver.AppleEFIRuntime 2.0 com.apple.iokit.IOHIDFamily 2.0.0 com.apple.iokit.IOSMBusFamily 1.1 com.apple.security.sandbox 278.10 com.apple.kext.AppleMatch 1.0.0d1 com.apple.security.TMSafetyNet 7 com.apple.driver.AppleKeyStore 2 com.apple.driver.DiskImages 371.1 com.apple.iokit.IOStorageFamily 1.9 com.apple.iokit.IOReportFamily 21 com.apple.driver.AppleFDEKeyStore 28.30 com.apple.driver.AppleACPIPlatform 2.0 com.apple.iokit.IOPCIFamily 2.8 com.apple.iokit.IOACPIFamily 1.4 com.apple.kec.pthread 1 com.apple.kec.corecrypto 1.0 Model: iMac12,1, BootROM IM121.0047.B1F, 4 processors, Intel Core i5, 2.5 GHz, 4 GB, SMC 1.71f21 Graphics: AMD Radeon HD 6750M, AMD Radeon HD 6750M, PCIe, 512 MB Memory Module: BANK 0/DIMM0, 2 GB, DDR3, 1333 MHz, 0x80CE, 0x4D34373142353637334648302D4348392020 Memory Module: BANK 1/DIMM0, 2 GB, DDR3, 1333 MHz, 0x80CE, 0x4D34373142353637334648302D4348392020 AirPort: spairport_wireless_card_type_airport_extreme (0x168C, 0x9A), Atheros 9380: 4.0.74.0-P2P Bluetooth: Version 4.2.0f6 12982, 3 services, 23 devices, 0 incoming serial ports Network Service: AirPort, AirPort, en1 Serial ATA Device: WDC WD5000AAKS-402AA0, 500.11 GB Serial ATA Device: HL-DT-STDVDRW GA32N USB Device: Hub USB Device: IR Receiver USB Device: Internal Memory Card Reader USB Device: FaceTime HD Camera (Built-in) USB Device: Hub USB Device: BRCM2046 Hub USB Device: Bluetooth USB Host Controller Thunderbolt Bus: iMac, Apple Inc., 22.1 UPDATE: Just a quick update for anyone else who has this problem. The iMac was taken to the Apple store where they misdiagnosed the problem as a hard drive issue. After the hard drive was replaced, when I got home, the machine continued to crash just as it had before. I'm now going back to the Apple store. PROBLEM SOLVED: It was simply some 3rd party software that was conflicting with OSX Mavericks, even though my mac was still crashing in Safe Mode. See the answer below for more information. Since the Mac still crashed in Safe Mode, within seconds of it starting up, I was unable to uninstall the 3rd party software. So, I had to take the machine to the Apple store, where they used some special equipment to keep it the Mac alive while they uninstalled the software, and it worked!!! A: This is hardly a hard disk issue; From the kernel panic, it seems the TCP stack is to blame, with no packet control block. The suspect is the firewall module, so what you might want to do is tell the Apple Store folk to disable the built in firewall NKE (Network Kernel Extension) A: First, try starting the machine in Safe Mode to re-confirm that this is a third party software issue and not related to hardware: Shut down your Mac and wait 10 seconds. Press the power button. Immediately after you hear the startup tone, hold down the Shift key. You should press the Shift key as soon as possible after you hear the startup tone, but not before. Release the Shift key when you see the gray Apple logo and progress indicator (spinning gear). To leave safe mode, restart the computer normally without holding down any keys during startup. If it works fine in Safe Mode without issues, then you could try uninstalling some potential culprits seen in the log. The backtrace in your log shows the application firewall crashing. The key suspects in this case, based on what was loaded most recently, are the following: com.speedbit.driver.vadriver 1.0.8 Uninstall the Speedbit Video Accelerator for Mac from your system and see if it helps. com.seagate.driver.PowSecLeafDriver_10_5 5.2.3 and com.seagate.driver.PowSecDriverCore 5.2.3 Uninstall any Seagate Diagnostics Tool that you may have and see if it helps.
[ "stackoverflow", "0012259389.txt" ]
Q: Entity with a limited number of fields of the same class type instead of a collection. Is it possible? Suppose you have a class like the following: public class Container { Element topElement; Element rightElement; Element leftElement; ..... A possible DB mapping is done with a table Containers and another table Elements, linked by a foreign key like Container_ID. The table Elements will have a composite primary key made with Container_ID, the unique identifier of a Container object in the DB, and a flag indicating the element position (top, left, right, etc). I use EclipseLink as ORM persistence provider, but I'm not an expert, so I usually start from the database design and let Netbeans build my entities from database with the wizard. That way inside the Container entity I would get a Collection of Element, while I would like to have different fields (topElement, rightElement, etc) of the same type (Element). Is there a way to achieve that goal ? Thanks Filippo A: You have a few options, Just have the Collection variable, but provide get/set methods in your class that return the appropriate Element. (probably the best solution). Provide a get/set method for setting the Collection and internally set the fields. Use 4 separate OneToOne relationships instead of a OneToMany. You could customizer the mapping to query the type, or change the data-model to match your object model.
[ "stackoverflow", "0000328851.txt" ]
Q: Printing all instances of a class With a class in Python, how do I define a function to print every single instance of the class in a format defined in the function? A: I see two options in this case: Garbage collector import gc for obj in gc.get_objects(): if isinstance(obj, some_class): dome_something(obj) This has the disadvantage of being very slow when you have a lot of objects, but works with types over which you have no control. Use a mixin and weakrefs from collections import defaultdict import weakref class KeepRefs(object): __refs__ = defaultdict(list) def __init__(self): self.__refs__[self.__class__].append(weakref.ref(self)) @classmethod def get_instances(cls): for inst_ref in cls.__refs__[cls]: inst = inst_ref() if inst is not None: yield inst class X(KeepRefs): def __init__(self, name): super(X, self).__init__() self.name = name x = X("x") y = X("y") for r in X.get_instances(): print r.name del y for r in X.get_instances(): print r.name In this case, all the references get stored as a weak reference in a list. If you create and delete a lot of instances frequently, you should clean up the list of weakrefs after iteration, otherwise there's going to be a lot of cruft. Another problem in this case is that you have to make sure to call the base class constructor. You could also override __new__, but only the __new__ method of the first base class is used on instantiation. This also works only on types that are under your control. Edit: The method for printing all instances according to a specific format is left as an exercise, but it's basically just a variation on the for-loops. A: You'll want to create a static list on your class, and add a weakref to each instance so the garbage collector can clean up your instances when they're no longer needed. import weakref class A: instances = [] def __init__(self, name=None): self.__class__.instances.append(weakref.proxy(self)) self.name = name a1 = A('a1') a2 = A('a2') a3 = A('a3') a4 = A('a4') for instance in A.instances: print(instance.name) A: You don't need to import ANYTHING! Just use "self". Here's how you do this class A: instances = [] def __init__(self): self.__class__.instances.append(self) @classmethod def printInstances(cls): for instance in cls.instances: print(instance) A.printInstances() It's this simple. No modules or libraries imported
[ "stackoverflow", "0022823807.txt" ]
Q: Iterating through JSON I have a following JSON: sales = { "February 20, 2014": { "services": 0, "total": 160, "repairs": 0 }, "February 18, 2014": { "services": 360, "total": 1109.95, "repairs": 410 } }; Now, this JSON has the data I want to graph. I already implemented nice d3.js chart, but I have issues getting data from that JSON to the chart. I need to somehow iterate through the JSON, and construct three arrays for services, total, repairs, and have them contain key value pairs, {x: date, y: value}. So, the process would be something like this (pseudocode): for date in sales services.push({x: date, y: services_value}) total.push({x: date, y: total_value}) repairs.push({x: date, y: repairs_value}) endfor And the result for, lets say services, based on the sample json above, would be like this: total = [{x: "February 20, 2014", y: "160.0"}, {x: "February 18, 2014", y: "1109.95.0"}] As I am rendering this on the website, I need this implementation in Javascript. A: Simple as it is (tuples of values): var services = []; var total = []; var repairs = []; for(i in sales) { services.push([i, sales[i].services]); total.push([i, sales[i].total]); repairs.push([i, sales[i].repairs]); } fiddle: http://jsfiddle.net/f3CKQ/1/ and if you need the exact structure as you have mentioned then: var services = []; var total = []; var repairs = []; for(i in sales) { var obj = {x: "", y: ""}; obj.x = i; obj.y = sales[i].services; services.push(obj); obj.y = sales[i].total; total.push(obj); obj.y = sales[i].repairs; repairs.push(obj); }
[ "mathoverflow", "0000058327.txt" ]
Q: Jordan measurability of the level sets Let $A$ be a compact subset of $R^n$ and $d_S(\bullet, A)$ be the signed distance function of $A$. Namely, $d_S(p,A) = d\left({p,\partial A} \right)$ for p in A, and $d_S(p,A) = -d\left({p,\partial A} \right)$ for p not in A. Here $d$ denotes the usual Euclidean distance from a point to a set. . Question 1: Let $r \in R$, and consider the set $A_r$ = {$p : d_S(p,A) \geq r$}. Is the set $A_r$ necessarily Jordan measurable (has boundary of zero Lebesgue measure). If this doesn't hold strictly, then maybe under what conditions on $A$? Question 2: Let A,B be compact subsets of $R^n$ and $d_S(\bullet, A)$, $d_S(\bullet, B)$ defined as above. For some $t \in R$, consider the set {$p : td_S(p,A) + (1-t)d_S(p,B) \geq 0$}. Is this set Jordan measurable? Many thanks ahead, Shay A: I was not able to determine if this is a homework problem or not. In any case, here are some observations: For the first question there are to cases: When $r = 0$ the set $A_r = A$ and the question then is if the boundary of $A$ has Lebesgue measure zero. When $r \ne 0$ the boundary of the set $A_r$ even has finite $n-1$-dimensional Hausdorff measure. This can be seen by considering for each $x \in \partial A_r$ a point $y \in A$ for which $d(x,y) = d(x,A) = |r|$. The open ball $B(y,|r|)$ is contained either in the set $A_r$ (if $r < 0$) or in $\mathbb{R}^n \setminus A_r$ (if $r > 0$). Therefore, starting from each point in $\partial A_r$ you have some cone with a fixed opening angle and radius $|r|$ which does not contain any other points of $\partial A_r$. So, the set $\partial A_r$ is contained in finitely many graphs of Lipschitz functions. For the second question consider the case $A = B$ and you notice that we are in the situation of the first question with $r=0$.
[ "parenting.stackexchange", "0000001654.txt" ]
Q: Can I use a stroller for my infant in Chicago's public transportation? My family will be visiting Chicago next month and we'll be using the metro and buses. My question is, how do infants (son is a 7 month old baby) usually travel in public transporation? Does one have to set-up a car seat on either of those? Or is it always on arms? Also, if we carry a lightweight stroller, are there ramps on every station to be able to move around in it? How about when going through the turnstiles? Can the baby go through it on the stroller? Or does one have to fold the stroller, carry the baby on arms, and then unfold the stroller again when boarding? Thanks for the help. A: In most cities you can easily drive a stroller onboard local trains and metros, and you are typically allowed to do so. If the stations has elevators or escalators varies wildly from city to city. Buses and trams are different, and there you'll typically find that if the buses/trams are modern strollers work well, and there are often an area for strollers although you will need to be two persons to carry the stroller up and down. Commuter trains are usually not stroller friendly. In the cases of non-stroller friendly transportation a car seat works for longer journeys, but for the typical 10-20 minute journey of local transportation you'll probably find that a baby carrier is more practical. Because of this, your strategy will be different in different cities. In Paris you would typically have to carry the stroller up and down stairs to take the Metro, while all buses have stroller-parking (that is often full, though), so for a family with a baby or a toddler a bus is definitely easier. In Stockholm both buses and subway is extremely family friendly, partly because of an almost obsessive handicap-friendliness. In Krakow we find that it's easiest to walk. I remember both local trains and buses in Chicago as being stroller friendly even if we didn't have a stroller with us, but I do not remember if there was escalators or elevators everywhere. A: I live in Chicago, have taken both my kids on public transport (bus and train). Most stations are now ADA compliant so you can take the stroller through where a wheelchair rider would. There are elevators too. Check out their site for a list of accessible stations: http://www.transitchicago.com/maps/ It can get crowded at rush hour, but in my experience other riders are conscious of people with kids/strollers and generally accommodating. It's not uncommon to see people give up their seat for someone riding with young children. As far as germs go, I don't think it is any more or less germy than any public place. I suspect you already have hand sanitizer if you have a kid in diapers. Just use common sense.
[ "stackoverflow", "0013127380.txt" ]
Q: Cross browser AJAX and setTimeout() works in IE but fails in Chrome/Firefox Ok. This has been frustrating me for a few days now. I'm sure I'm an idiot and there is a solution right in front of my face but here's my question. I have a series of AJAX calls that process and save data from a web page when the Save button is pressed. This has worked in IE for years (Was setup before I was hired) and have had no problems. We now have a requirement to support multiple browsers, namely IE, Firefox, Chrome and Safari. What I see when I try to press the save button in Firebug is that I get to the first AJAX call, I get the 200OK response and the time it took in ms, however it keeps spinning: The 17 seconds is because I stepped through the server side code. The AJAX success handler method is never called and the whole thing falls apart. I have tried several different methods I've found searching but none of them seems to make much of a difference. Here is the original code. EDIT 5: Here is the updated code. I simplified it and took out the Step() method and all the timeouts. It's just the AJAX call that is causing the problem. function SubmitForm() { $.blockUI({ message: waitMessage, css: { padding: 5} }); var settingsXml = GetSettingsXml(); ajaxParameters = "customerId:'" + customerId + "', connectionId:" + connectionId + ", settingsXml:'" + settingsXml + "', securityToken:'" + securityToken + "'"; AjaxCall("EmailMarketingSettings.aspx", "Validate", ajaxParameters, function (result) { alert("It works!") }, function (result) { alert("It's broken!"); }); } Validate() will make it to the return statement but the code never returns to the client side success method. What am I missing? EDIT: Here is the requested AjaxCall method. function AjaxCall(pageName, methodName, parameters, onSuccessCallback, onFailureCallback) { $.ajax({ type: "POST", url: pageName + "/" + methodName, data: "{" + parameters + "}", contentType: "application/json; charset=utf-8", dataType: "json", timeout: 120000, success: function (resp) { result = resp.d; if (result.Success) { if (onSuccessCallback != null && typeof (onSuccessCallback) == "function") { onSuccessCallback(result); } else { $.unblockUI(); } } else if (onFailureCallback != null && typeof (onFailureCallback) == "function") { onFailureCallback(result.Message); } else { alert(result.Message); $.unblockUI(); } }, error: function (req, errorType, errorThrown) { var errorMessage = ""; if (errorType == "timeout") { errorMessage = "A timeout has occured" } else if (req.responseText.length > 0) { errorMessage = (req.responseText.substring(0, 1) == "{" ? eval("(" + req.responseText + ")").Message : req.responseText); } else { errorMessage = req.status; } if (onFailureCallback != null && typeof (onFailureCallback) == "function") { onFailureCallback(errorMessage); } else { alert("An error has occured: " + errorMessage); $.unblockUI(); } } }); } EDIT 2: As soon as the request is sent I hit the error handler before my server side code returns anything at all. The AJAX call isn't waiting for anything to be returned it's just erroring out with an errorType of "error" and an empty string for errorThrown. EDIT 3: Raw data from Fiddler FireFox: HTTP/1.1 200 OK Cache-Control: private, max-age=0 Content-Type: application/json; charset=utf-8 Server: Microsoft-IIS/7.5 X-Powered-By: ASP.NET Date: Wed, 31 Oct 2012 15:30:01 GMT Content-Length: 178 {"d":{"__type":"CoreMotives.Web.MethodResult","Success":true,"Comments":"","Message":"","ElapsedMilliseconds":0,"SubTests":null,"NextStepAdditionalParameters":null,"Value":null}} IE: HTTP/1.1 200 OK Cache-Control: private, max-age=0 Content-Type: application/json; charset=utf-8 Server: Microsoft-IIS/7.5 X-Powered-By: ASP.NET Date: Wed, 31 Oct 2012 15:29:53 GMT Content-Length: 178 {"d":{"__type":"CoreMotives.Web.MethodResult","Success":true,"Comments":"","Message":"","ElapsedMilliseconds":0,"SubTests":null,"NextStepAdditionalParameters":null,"Value":null}} Again though. The AJAX call hits the error handler before the server side code returns anything at all. Edit 4: Link to the .saz file from Fiddler. http://tinyurl.com/ckmatsk There should be only 2 entries in there. A: Wow... All this effort for something so stupid... I figured out what my problem was thanks to this thread: JQuery Ajax Firefox Error The SubmitForm() method was not returning false so the browsers default behavior was taking over. As soon as I changed the onclick to: onclick="return SubmitForm();" from: onclick="SubmitForm();" And made SubmitForm() return false. It started working in both Chrome and Firefox. Thanks to anyone who was looking into it. Hopefully this helps someone in the future though I doubt there are many as dumb as me...
[ "sharepoint.stackexchange", "0000116981.txt" ]
Q: Javascript Error inplview.js IE only We're experiencing an issue where Internet Explorer 8 is reporting an Expected ';' in the minified inplview.js file. It doesn't affect any functionality it seems, but we have no idea what's causing it. Perhaps other scripts we are using such as repond, modernizr, angular, scripts which extend the array.prototype are the culprits. A: This was exactly our issue. We had extended the Array.prototype and for whatever reason it caused the SP scripts to start failing. We already had another prototype extension that caused no issues. We ended up just moving it into a utility function instead.
[ "stackoverflow", "0057835206.txt" ]
Q: How to use the states of changed store right after dispatching an action in a component method? I use Redux for state management of React JS but I have a event handler relevant to a button in my class component like below: handleStartBtn = e => { const name = document.getElementById("nameInput").value; const error = "You must set a value in this field"; this.props.createPoll(name); if (!this.props.currentPoll) return; cookies.set("assignments", `EHS_${this.props.currentPoll.uuid}`, { path: "/" }); this.props.history.push("/polling"); }; The createPoll function is in my actions file. after creating a poll I dispatched a success function and it hits the store then it changes the currentPoll property. but it seems like it will leave null after calling createPoll dispatched I must clicked on startBtn twice till the store to be updated. how can I use the value of store after dispatch method call? A: You can try using componentDidUpdate() life cycle method for this issue. handleStartBtn = e => { const name = document.getElementById("nameInput").value; const error = "You must set a value in this field"; this.props.createPoll(name); }; componentDidUpdate(prevProps,prevState){ if(prevProps.currentPoll !== this.props.currentPoll){ cookies.set("assignments", `EHS_${this.props.currentPoll.uuid}`, { path: "/" }); this.props.history.push("/polling"); } } when you dispatch the action through this.props.createPoll(name); you redux state of currentPoll will be changed and then this change takes place the componentDidUpdate will be triggered and in here you can check it (though a proper condition) and continue what needs to be done after that.
[ "scifi.meta.stackexchange", "0000000683.txt" ]
Q: Are children's literature and cartoons for children on-topic? Books and movies intended for children very often contain fantasy elements. They are typically not considered part of the fantasy genre, but rather part of the specific “for children” genre. Does this make them on-topic or off-topic for this site? Where do we draw the line, if any? This meta question was triggered by this question about a children's cartoon, which was eventually closed as off-topic by community vote and is now deleted. Its title was “Which Tiny Toons episode has the characters producing their own serious film?”, with some reasonable story identification elements. Here's the relevant limit in the ISFDB scope as a guideline (which isn't an obligation, we can go our own way): they exclude animal books for very young children, i.e. books for preschoolers which depict simple scenes from animal life featuring anthropomorphized animals (quoted here as a possibility that we don't have to follow) A: I'm going to say that unless the show was seriously sci-fi/fantasy (Dungeons and Dragons comes to mind), then it should not be on topic. If it's merely creative creatures, even if they exhibit unusual abilities, it shouldn't be on topic. As far as the other concern that will no doubt be raised, of comic-themed cartoons, I think those should be allowed, for now. It's not the best fit, but as almost all comic book heros are either mutants, genetically engineered, aliens, robots, or people with some futuristic technology, all of which would easily be covered in this site, I say it's on topic, at least until such time that there is a better place for it. A: I think the line is pretty straightforward: would a serious fan of the science fiction or fantasy genres consider spending any amount of effort digging into the details of a children's cartoon? If the answer is yes, it's on-topic. If the answer is no, it's off-topic. I'm willing to bet the farm, in the case of Tiny Toons, the answer is no. One should take care to not compare this to potentially on-topic animated features, like anime or licensed films based on comic book characters: both enjoy a following within the respective communities and in many cases are designed to appeal to more than just children, but to adults invested in the genres the animated features are set in. But putting aside the genre question for a moment: how is "what episode had X?" interesting? Isn't that covered by any episode list and shouldn't it be closed as general reference? A: I suppose my response would be that childrens SF/F is valid, as long as it is actual SF/F, in a way that is recognisable to SF/F fans. But where the essence of the story is not really fantasy, even if the setting is "fantastical" as a lot of childrens material is, then it does not count. The challenge is distinguishing between situations where the fantasy aspect is core to the story, and where it is merely a good setting for telling the stories. The other test might be whether a particular series would appeal to younger people who will enjoy SF/F when they are older, or may enjoy it at their current age. Are Smurfs - or Tiny Toons - fans good SF/F material? The answer is probably no. Are Sarah Jane Adventures fans good SF/F material? Probably yes. The other test for this site is Are there liable to be people who use this site who have a clue about this series? If the answer is no, then, however much you might want to argue that it is SF, the questions are not going to get good answers.
[ "stackoverflow", "0063541549.txt" ]
Q: Can Two Load balancers have same ssl endpoint and certificate One of my application is running behind a Load balancer on a server in east region. I have created a replica of the same application and deployed it on a server in west region My question is, that can I achieve High availability using two load balancers? Something Like Application running in EAST region behind load balancer LB-1 (Primary) If we shut down the above, then Application running in WEST region should become active which is running behind LB-2. My thoughts: Replication Of Code on deployment: Write Jenkins script which will trigger a deploy command to deploy APP TO west REGION, whenever a deployment is done on east region. CHecking the health of primary Server/application: Write cron, which will check if the server on east region is down If it is down, then a. Using Load Balancer PATCH API, remove the mapping of load balancer in EAST region. b. Using Load Balancer PATCH API, update the mapping of load balancer in WEST region [To match with the previous east region mappings] Are these feasible? A: Note that each Dedicated Load Balancer has a unique DNS host name in CloudHub. And the certificate subject's common name attribute must match the host name to avoid SSL/TLS validation errors in the clients. If you are intending to failover transparently for the clients, meaning that the next requests go through LB-2, then you should have a DNS CNAME record that matches LB-1 and you need to point to LB-2. If you don't have a DNS CNAME record to point to the other dedicated load balancer, then you need to change the clients URL to point to LB-2, and need to be sure that the certificate has a Subject Alternative Name with LB-2 host name, so it is valid for both.
[ "stackoverflow", "0014386616.txt" ]
Q: Is it bad form to intentionally throw an exception? Is it bad form to do something you know will throw an exception (assuming you handle it properly)? For example: JSONArray stuff = new JSONArray(); JSONArray otherStuff = new JSONArray(); try{ for(i = 0; i < stuff.length(); i++){ JSONObject a = stuff.getJSONObject(i); otherStuff.add(a); } } catch (JSONException e){ Log.e("FAIL", e.toString()); } //more code adding things to array later on In this case the first time you ran the sequence the array would be empty and getJSONObject would throw an excpetion because there would be nothing at index i. However, later on, if things were added to the array, it would not throw an exception. Granted this code is just a hypothetical (I'm sure there are better examples - someone may have one) but as a matter of form/style is it ok to intentionally throw an exception? Or should you just avoid throwing them all together? A: In my experience it's generally considered bad practice to use Exceptions as flow control. They should be reserved for Exceptional situations.
[ "stackoverflow", "0028713851.txt" ]
Q: position absolute div and centered positioning of its elements While editing the css theme of news boxes at this site: http://pureenergy.nazwa.pl/fwwm/wordpress/?page_id=364 I have encountered two problems, both of them I cannot resolve for a long time. I am hoping that by asking a question here, you will be able to help me with sloving these issues :). Two bugs concern the .category1 div and .info .aut element. Firstly, when it comes to categories, I wish them to be centered and not to occupy the whole width of the box, but only the width which they have by default. The full width of the box, I can remove by deleting width:100% instruction from .category1 div. But unfortunately, caregories still stick to the left, even though I remove the float:left instruction. I am also unable to make negative px/% margins because the width of the category is not fixed (generates itself on the basis of category name). What should I do to have the categories centered and not occupy the whole width of the box? Secondly, I have similar issue in .info .aut element. I wish elements of this div to be centered, regardless of their width, generated automatically on the basis of autor's name. Now it is centered because it is given an artificial width of 180px, and unfortunately it does not look good in all cases. What should I do to have this div elements centered properly? I am looking forward to your help! Thanks in advance :) ! A: remove the floats from the elements which you want to be centered and add display: inline-block; width: auto; also add text-align: center; to parent element.
[ "stackoverflow", "0057230118.txt" ]
Q: Can we group in Java 8 the Data based on Month and Year only Here in this example , it is grouping the data based on the entire date . Can we group the Data based on Month and Year only package com; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import com.google.gson.Gson; public class GroupData { public static void main(String args[]) throws Exception { try { List<Person> personList = new ArrayList<Person>(); // Date Format is MM/DD/YYYY personList.add(new Person("Mike", "London", 35, "01/01/1981")); personList.add(new Person("John", "London", 21, "01/02/1981")); personList.add(new Person("John", "Bristol",41, "01/06/1981")); personList.add(new Person("Steve", "Paris",34, "03/07/2019")); Map<LocalDate, List<Person>> personByMap = new HashMap<>(); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/yyyy"); personByMap = personList.stream() .collect(Collectors.groupingBy(p -> LocalDate.parse(p.getDateOfBirth(), dtf))); System.out.println(personByMap.size()); } catch (Exception e) { e.printStackTrace(); } } } class Person { private String name; private String city; private int age; private String dateOfBirth; public String getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(String dateOfBirth) { this.dateOfBirth = dateOfBirth; } public Person(String name, String city, int age, String dateOfBirth) { this.name = name; this.city = city; this.age = age; this.dateOfBirth = dateOfBirth; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } A: Instead of using a LocalDate, use YearMonth: personByMap = personList.stream() .collect(Collectors.groupingBy(p -> YearMonth.parse(p.getDateOfBirth(), dtf))); I also suggest you to directly store the date of birth as a LocalDate: class Person { private String name; private String city; private int age; private LocalDate dateOfBirth; // ... } And then you can do: personByMap = personList.stream() .collect(Collectors.groupingBy(p -> YearMonth.from(p.getDateOfBirth())));
[ "stackoverflow", "0056429621.txt" ]
Q: Import from Github : How to fix ImportError I want to use the open source person re-identification library in Python on Ubuntu 19.04 with Anaconda no CUDA in the terminal PyCharm (or not) Python version 3.7.3 PyTorch version 1.1.0 For that I have to follow instruction like on their deposite git : git clone https://github.com/Cysu/open-reid.git cd open-reid python setup.py install python examples/softmax_loss.py -d viper -b 64 -j 2 -a resnet50 --logs-dir logs/softmax-loss/viper-resnet50 I receive the following error: from sklearn.utils.extmath import pinvh ImportError: cannot import name 'pinvh' I have tried to create virtual environments with previous versions of PyTorch (0.4.1, 0.4.0 and 1.0.1) but I always got: File "examples/softmax_loss.py", line 12, in <module> from reid import datasets ModuleNotFoundError: No module named 'reid' I do not know how to fix it. EDIT : Hi thanks for the answer, the problem is that the import are like : from reid import datasets from reid import models from reid.dist_metric import DistanceMetric from reid.trainers import Trainer from reid.evaluators import Evaluator from reid.utils.data import transforms as T from reid.utils.data.preprocessor import Preprocessor from reid.utils.logging import Logger from reid.utils.serialization import load_checkpoint, save_checkpoint I tried : from ../reid import datasets But I got a File "examples/softmax_loss.py", line 12 from ../reid import datasets ^ SyntaxError: invalid syntax EDIT 2 : After re-installing Python 3.7.3 and pytorch 1.1.0 the problem persist with pinvh... I still got this message : ImportError: cannot import name 'pinvh' from 'sklearn.utils.extmath' If you can tell me how to fix it or try to tell me if it works please A: Since the directory structure is as below: /(root)-->| | |-->reid |--> (contents inside reid) | | |-->examples | -->softmax_loss.py | |-->(Other contents in root directory) It can be observed that reid is not in the same directory as softmax_loss.py, but instead in the parent directory. So, in the file softmax_loss.py, at line number 12 and below, replace reid with ../reid, this looks for the directory reid in the parent directory. The other method is to use: import ../reid as R or any other variable; Then use from R import datasets, and so on
[ "stackoverflow", "0024555326.txt" ]
Q: Dynamic modifications at runtime - Web Dynpro ABAP tutorial I am studding by my about Web Dympro and I would like to do some tutorials about the Dynamic modifications at runtime in Web Dynpro... but I have not seen one available on the Internet. Can anyone provide me some links whith some tutorial about this subject? A: Here you go: Dynamic Programming in Web Dynpro ABAP - Introduction and Part I: Understanding UI Elements Web Dynpro ABAP - Dynamic Programming Search for "SAP ABAP Web Dynpro dynamic" for more...
[ "stackoverflow", "0042620821.txt" ]
Q: How to get data as Ionic's list from Firebase's JSON I would like to display a list of items, retrieved from Firebase realtime database, on my page. My problem is that I need to parse JSON that I receive from Firebase and put it into an object so that I can call it from page. export class Item { name: string, price: number } Page code: export class ItemsPage { private itemsList; private userId; private userFirebaseToken; constructor(public navCtrl: NavController, private userService: UserService) {} this.userService.getItemsList(this.userId, this.userFirebaseToken) .subscribe( items => this.itemsList = items, error => console.log(error), () => console.log('OK') ); } Service code: getItemsList(userId: string, userToken: string) { return this.http.get(this.userServiceUrl + userId + '/items.json?auth='+ userToken) .map((response: Response) => response); EDIT: Change the object into Array that can be called in ngFor directives. Now I have been getting [object Object] A: You can do it in your map function.It will send the parsed json to your subscribe Try: .map((response: Response) => response.json());
[ "stackoverflow", "0019793272.txt" ]
Q: GMP convert char array to float I am using GMP and MPI to calculate precision PI. Currently I have calculated PI in a worker process and need to send it back to the farmer process, to do this I have converted to a char array as so mp_exp_t exp; pi_str = mpf_get_str(pi_str, &exp, 10, (size_t)PRECISION, pi); char send_str[3026]= {0}; strcpy(send_str,pi_str); MPI_Send(&send_str, len, MPI_CHAR, 0, 1, MPI_COMM_WORLD); This works fine, now I receive the char array and I need to perform other calcualtions so the char array needs converting back to a float. char recv_str[3026] = {0}; for(i=1; i<size ; i++) { printf("farmer**%d\n",size); MPI_Recv(&recv_str,3026, MPI_CHAR, i, 1,MPI_COMM_WORLD, &status); printf("pi after send %s", recv_str); mpf_set_str(pi_ret, recv_str, 10); gmp_printf("setting from string to float %.Ff\n", pi_ret, 20); This gives me a memory allocation fault, but I can not see another way of converting back to a float unless I am missing something. A: You need to initialize pi_ret before assigning a value to it. The easiesst way to do this would be with the mpf_init_set_str() function, which simultaneously initializes a floating point number and assigns its value from a string of chars.