text
stringlengths
64
89.7k
meta
dict
Q: help with span/linearindepencence/basis Determine whether each given tuple (i) spans $P_2$, (ii) is linearly independent, (iii) is a basis of $P_2$. (a.) $(2−x, 1+3x−x^2 , −7x+2x^2 )$ (b.) $(1+x−x^2 , 3x+2x^2 , −1+x+4x^2 )$ I can't figure this one out. Thanks for the help!! A: Since $dim(P_2)=3$, any three linearly independent vectors would span the whole set. All it remains is to show that which of the following is a linearly independent set. For (i) if $c_1(2-x)+c_2(1+3x-x^2)+c_3(-7x+2x^2)=0$, then $2c_1+c_2=0,-c_1+3c_2-7c_3=0,2c_3-c_2=0$. Now if you take $c_1=-\frac{1}{2},c_2=1, c_3=\frac{1}{2}$, you will see that there exists a nonzero linear combination of the three vectors which equals zero. Hence the set is not linearly independent and they don't form a basis. Similarly check for (ii).
{ "pile_set_name": "StackExchange" }
Q: Programmatically adding root view to view controller does not position correctly I am trying to add the root view and subviews to a viewcontroller programmatically, but the view is not filling to screen as expected: override func loadView() { self.view = UIView(frame: CGRect(x: 0.0, y: 0.0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)) self.view.backgroundColor = UIColor.blue } override func viewDidLoad() { let alertView = Bundle.main.loadNibNamed("CHRApptTakenAlertView", owner: self, options: nil)![0] as! CHRApptTakenAlertView self.view.translatesAutoresizingMaskIntoConstraints = false alertView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(alertView) self.view.addConstraint(NSLayoutConstraint(item: alertView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: alertView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)) alertView.addConstraint(NSLayoutConstraint(item: alertView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.width, multiplier: 1, constant: 350)) alertView.addConstraint(NSLayoutConstraint(item: alertView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.height, multiplier: 1, constant: 250)) alertView.closeBtn.addTarget(self, action: #selector(self.closeBtnTouch), for: UIControlEvents.touchUpInside) } A: Remove the line self.view.translatesAutoresizingMaskIntoConstraints = false, and call self.view.layoutIfNeeded() after the adding the constraints.
{ "pile_set_name": "StackExchange" }
Q: Should you "rebrand" the exception of the library you're using? Say your making a library Foo that depends on a 3rd-party library Bar. Bar throws a custom exception \OtherVendor\Bar\CustomException. Is it recommended to just throw that exact exception to your clients (devs using your lib) or should you catch it then convert it to your own exception? E.g., try { $bar->stuff(); } catch (\OtherVendor\Bar\CustomException $ex) { throw new \MyLib\Foo\MyCustomException(); } To explain further, is it better for your clients to know about that 3rd-party exception in your documentation? e.g., You can catch \OtherVendor\Bar\CustomException in case of x... or should you "rebrand" the exception so clients don't need to deal with another lib's namespace? E.g., You can catch \MyLub\Foo\MyCustomException in case of x... A: Generally speaking, it's fine to use a language's own exceptions, since these are commonly understood. I wouldn't use 3rd party exceptions, since using that 3rd party library isn't part of the API you're offering and you might swap it for another 3rd party library (or remove it altogether) in future versions. If a client of your library built some of their error handling based on the 3rd party exception, they will have to rewrite their code. By using your own exception ('rebranding it', as you call it), you'll have the option of keeping the interface identical to previous versions. (disclaimer: I use PHP only very sparingly, this recommendation is based on experience with half a dozen other languages) A: TL;DR: It's a waste of time to rebrand exceptions, in at least 99 percent of all situations. A valuable rule of thumb is to catch exceptions only: At application top level (telling the end user about the failure) or At places where you know and implement a strategy how to achieve your overall goal even in that specific failure case. In other words: if you receive an exception you don't fully understand, and don't have a generic "retry" or a "try-a-different-way" strategy, don't catch! Let your caller deal with the situation that his call failed. Both valid cases don't apply to you, but maybe to your caller. You're designing a library, not a top-level application. Your code shows that you don't want to recover from the exception (retrying or whatever), but just tell your caller about it. So the main question about your API design is "Will rebranding the exception make it easier for your caller to decide about and implement an error-recovery strategy?" There are a few situations to be considered now: Most probably your caller doesn't want to implement any recovery strategies, but just report an error to the user and restart from top level. In that case, the exception type doesn't matter at all. Maybe your caller seriously needs your API call to succeed, so he's ready to retry it a few times in case of failure. He'll write a retry-loop around your API call, and the only aspect where your rebranded exception can help him, is if it reliably tells him that retries won't change the outcome of your call. This "help" only shortens the time until he gives up... Maybe your caller has an alternative way of reaching his goal instead of your library call (that's a very rare situation). Then he'll most probably do that if he gets an exception, no matter what type of exception that is. So in general, to your caller's program flow it doesn't matter what type of exception he gets. But there's the error message to be presented to the user, and the information to be written into some kind of log. If your rebranded exception can provide a description that's presentable to the user, it might be worth the effort. Of course, you have to document that fact with your exception, otherwise your caller will create his own messages anyway. And hopefully you know enough about the end user's problem domain and native language so you can really supply a useful message. Considering that, you most probably won't be able to supply a useful message. Make sure your rebranded exception contains all information relevant for a technical analysis of the problem, esp. the complete stack trace. So, if you create a rebranded exception, make sure to include the original one as its "previous". And maybe you have some context information you'd like to add to the logged problem description, then "rebrand" the exception and add the context to the message. So, there are very few situations where I see a benefit in rebranding an exception.
{ "pile_set_name": "StackExchange" }
Q: OpenCV Python: Blur image using trackbar I'd like to control the blur of an image by using a trackbar. The given MWE imports a picture with a trackbar that sets the aperture linear size (ksize) which has to be one or a positive odd number. Strangely getTrackbarPos returns a negative number which makes it necesarry to multiply ksize by -2 and subtract 1. Inside an infinite loop the image gets blurred and displayed. import cv2 # Callback function for trackbar def on_change(self): pass # Reads image with 0 as GRAY and 1 as BGR img = cv2.imread('example.JPG', 0) # Creates window cv2.namedWindow('Image') # Creates Trackbar with slider position and callback function low_k = 1 # slider start position high_k = 21 # maximal slider position cv2.createTrackbar('Blur', 'Image', low_k, high_k, on_change) # Infinite loop while(True): ksize = cv2.getTrackbarPos('ksize', 'Image') # returns trackbar position ksize = -2*ksize-1 # medianBlur allows only odd ksize values # Blures input image median = cv2.medianBlur(img, ksize) # source, kernel size cv2.imshow('Image', median) # displays image 'median' in window k = cv2.waitKey(1) & 0xFF if k == 27: break cv2.destroyAllWindows() By running this code a window opens with the desired trackbar on top of the input image. The slider start position is one as desired but by changing the silder's position there is no blur or any significant change to the displayed image. The main question is why the returned trackbar position does not have any influence on medianBlur(). My first thought suggests a mistake either inside the while loop or the callback function. Besides that I'd like to know why getTrackbarPos returns negativ numbers. I am using Python 3.6 with Anaconda 1.9.2. Thank you for any help! A: getTrackbarPos arguments expects the name of the trackbar and the name of the window. You are creating the trackbar with the name Blur and reading as ksize, change ksize = cv2.getTrackbarPos('Blur', 'Image') to ksize = cv2.getTrackbarPos('ksize', 'Image') or change the other way around (the createTrackbar method). Also, as mentioned in the comments, you can also update ksize on the on_change callback. As a side note, you also need to adjust the way you treat odd values, if the track bar position is 1, the ksize ends up as -3
{ "pile_set_name": "StackExchange" }
Q: C# Как создать и передать IDispatch в COM DLL На C# надо подключить DLL работающую по COM технологии. Подключение COM-DLL и вызов из нее функций я написал - документации море. Но вот в одной функции DLL требует чтобы ей в качестве параметра передали указатель на IDispatch. B в этом указателе на IDispatch было реализовано два стандартых COM интерфейса : IMsgBox и IPlatformInfo На C# такое можно сделать? Если да то можно которенький примерчик? Обновление Не подскажите: нужные мне интерфейсы унаследованы от IUnknown. Мне надо тоже реализовывать интерфейс IUnknown с его функциям (QueryInterface, AddRef...)? Получить мне надо вот такой интерфейс: MIDL_INTERFACE("55272A00-42CB-11CE-8135-00AA004BB851") IPropertyBag : public IUnknown { public: virtual /* [local] */ HRESULT STDMETHODCALLTYPE Read( /* [in] */ LPCOLESTR pszPropName, /* [out][in] */ VARIANT *pVar, /* [unique][in] */ IErrorLog *pErrorLog) = 0; virtual HRESULT STDMETHODCALLTYPE Write( /* [in] */ __RPC__in LPCOLESTR pszPropName, /* [in] */ __RPC__in VARIANT *pVar) = 0; }; A: Первое. Добавьте в ваш проект ссылку на COM-библиотеку типов в студии, либо другим образом получите интерфейсы IMsgBox и IPlatformInfo. Второе. Реализуйте эти интерфейсы в некотором классе. Оформлять этот класс специальным образом не нужно: class MyClass : IMsgBox, IPlatformInfo { // ... } Третье. Импортируйте функцию из DLL через P/Invoke, указав MarshallAs(IDispatch): [DllImport("bar")] static extern void Foo([MarshallAs(UnmanagedType.IDispatch)] object obj) По поводу обновления. Нет, вам не надо реализовывать IUnknown самостоятельно, так же как и IDispatch. Эти интерфейсы будут реализованы средой.
{ "pile_set_name": "StackExchange" }
Q: How do you give a date interval with diffuse dates? I'm interested in phrases such as From 2002 till my pension in October 2016 I worked at the company X1 as Y1. and From 2017 till now I am working at the company X2 as Y2. I'm interested in the correct translation of "From ... till ...". Concerning 1, is it "Seit 2002 bis zum Renteneintritt in Oktober 2016 ..." or "Von 2002 bis zum Renteneintritt in Oktober 2016 ..."? Concerning 2, is it "Seit September 2017 bis jetzt...". Or is it something else? A: For 1 It is (almost) your second guess: Von 2002 bis zum Renteneintritt im Oktober 2016 Note that it is im Oktober, not in. For 2 It is either Seit September 2017 The "seit" already automatically includes the information that it is still lasting. Alternatively you can say Von September 2017 bis jetzt The former version is preferrable. A: Von, seit and ab can be used to denote the beginning of something. The Duden on von: gibt einen zeitlichen Ausgangspunkt an The Duden on seit: gibt den Zeitpunkt an, zu dem ein bestimmter Zustand, Vorgang eingetreten ist The Duden on ab: von … an If you want to tell when it ended, you would usually use von with bis (Von Montag bis Freitag.). Seit is used when it's open ended and you maybe want to emphasize when it began. However, if it's open ended, you could also use von (Von da an fragte ich regelmäßig auf German Stack Exchange.). You can also change the above example to include ab (Ab da fragte ich regelmäßig auf German Stack Exchange.) From 2002 till my pension in October 2016 I worked at the company X1 as Y1. Von 2002 bis zu meinem Renteneintritt / Pensionierung im Oktober 2016 ... From 2017 till now I am working at the company X2 as Y2. Von 2017 bis jetzt ... Again, with bis, von sounds more natural. However, saying Seit 2017 arbeite ich ... conveys the same meaning here.
{ "pile_set_name": "StackExchange" }
Q: Equivalent criteria or HQL? I have below SQL query. what is the equivalent Criteria or HQL query? select max(id) from ( select max(id) id from TableA union select max(id) from TableB ) Thanks! A: There is no equivalent, because there is no UNION in HQL or Criteria. Some workarounds are: use native query build view and map it for read only purposes (if it for some reason really not possible to use native query) perform two queries and choose in Java code which value to use.
{ "pile_set_name": "StackExchange" }
Q: long integer as array index in C gives segmentation fault The following C Code gives a segmentation fault: #include <stdio.h> #include <stdint.h> int main(){ uint32_t *a; uint32_t idx=1233245613; a[idx]=1233; return 0; } How can I use uint32_t as index of an array in C? Or how can I use array like structure which can get uint32_t and 12 digit numbers as an index? I'd appreciate any kind of help. A: The variable "a" is just a pointer varaible. A pointer variable holds the address of a memory location. You need to point a to a memory location that has the space you need already allocated. Also you are trying to index pretty far in the array. You may not have enough memory available for this so be sure to check for NULL. #include <stdio.h> #include <stdint.h> #include <stdlib.h> int main(void){ uint32_t *a; uint32_t idx=1233245613; //This allows you to index from 0 to 1233245613 // don't try to index past that number a = malloc((idx+1) * sizeof *a); if(a == NULL) { printf("not enough memory"); return 1; } a[idx]=1233; free(a); return 0; } A: If you want to use a "12-digit number" as the index, that implies that you want need more than 1 billion items. With each item being an uint32_t, that implies that each takes four bytes of memory. Therefore, you're looking at around 4 GB in memory total for this array. Arrays are not usually made that big, for performance and other reasons. If you really need each of those billion items, look into disk-backed algorithms, perhaps Red-Black Trees, that are suitable for implementing this kind of giant array.
{ "pile_set_name": "StackExchange" }
Q: Stop macro from repeating when using Application.OnTime By using the below code RefreshData I run mg macro every 10 secs. I'm unable to stop stoprefresh which is assigned to a square shape. Sub RefreshData() Application.OnTime Now + TimeValue("00:00:10"), "mg", , True End Sub Sub stoprefresh() On Error Resume Next Application.OnTime Now + TimeValue("00:00:10"), "mg", , False End Sub Sub mg() ActiveSheet.Cells(ActiveSheet.Cells.Rows.Count, 1).End(xlUp).Offset(1) = "Running" Call RefreshData End Sub A: Try this code Option Explicit Dim iTimerSet As Double Sub RefreshData() iTimerSet = Now + TimeValue("00:00:10") Application.OnTime iTimerSet, "mg", , True End Sub Sub stoprefresh() 'On Error Resume Next Application.OnTime iTimerSet, "mg", , False End Sub Sub mg() ActiveSheet.Cells(ActiveSheet.Cells.Rows.Count, 1).End(xlUp).Offset(1) = "Running" Call RefreshData End Sub Cancelling a scheduled Procedure It is possible to cancel a procedure that has been scheduled to run but you need to know the exact date and time it was scheduled for. To cancel a scheduled procedure you must know the "EarliestTime" it was scheduled for. Exactly the same syntax except you set the schedule paramater to False. This tells the application to cancel the schedule.
{ "pile_set_name": "StackExchange" }
Q: Where can I access annual reports of the registrar-general for England after 1920? The annual reports of the registrar-general relating to births, marriage, and deaths in England and Wales were published every year since civil registration began, and are available at the Histpop website up to 1920. However, there are no reports after that date. Does anyone know where or how one could access later reports, such as for the 1920s and 1930s? I find these reports useful for a number of reasons, some of which are related to genealogy, as well as broader historical/epidemiological/health related interests. With relation to genealogy, it is interesting to examine trends of births and deaths in certain localities to put my ancestors in a better context. A: The British Library appear to have two collections, one covering 1838 to 1920 and a second covering 1921 to 1968 when they seem to have ceased according to the British Library catalog entry. The first of those groups appears to be what Histpop has - it seems that after that there was a change to the way they were published. At least some years seem to be available at the National Archives although sometimes in odd places, for example 1971 is in the papers of the Sizewell B inquiry! Not sure how that squares with them ending in 1968 either. In any case the title seems to have changed after 1920 to "Registrar General: Statistical review of England and Wales NNNN" which may be why you have been having trouble finding them.
{ "pile_set_name": "StackExchange" }
Q: List and tuple behave differently I'm well aware that there are differences between lists and tuples and that tuples aren't just constant lists, but there are few examples where the two are actually treated differently by the code (as opposed to by a coding convention), so I (sloppily) have used them interchangeably. Then I came across a case where they give totally different behavior: >>> import numpy as np >>> a = np.arange(9).reshape(3,3) >>> a array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> idx = (1,1) >>> a[idx] 4 >>> idx = [1,1] >>> a[idx] array([[3, 4, 5], [3, 4, 5]]) can someone explain what's going on here? More importantly, where else does this pitfall appear in scipy? A: You are getting a different behavior because, in numpy, three types of indexing are supported Basic Slicing Advanced Indexing Record Access Using tuple for indexing is just equivalent to a parameter list, which suffixes as a Basic Slicing, where-as using a non-tuple like list results in Advanced Indexing. Also remember, from the documentation Advanced indexing is triggered when the selection object, obj, is a non-tuple sequence object, an ndarray (of data type integer or bool), or a tuple with at least one sequence object or ndarray (of data type integer or bool). There are two types of advanced indexing: integer and Boolean. Advanced indexing always returns a copy of the data (contrast with basic slicing that returns a view). And moreover, from the same documentation In Python, x[(exp1, exp2, ..., expN)] is equivalent to x[exp1, exp2, ..., expN]; the latter is just syntactic sugar for the former.
{ "pile_set_name": "StackExchange" }
Q: jQuery autocomplete UI Widget- Perform jQuery select event on dynamically created table row element I have a working jQuery autocomplete being performed on the text input of a table data element, txtRow1. The text data is remote, from a mysql database, and is returned by JSON as 'value' for the text input. The returned data includes another piece of text, which, via a select event within the autocomplete, is populated to the adjacent table data element tickerRow1. With help from the SO community, the autocomplete is now live and working on all text input elements of a dynamically created table (so txtRow1 to txtRowN). There is javascript code to create and name the table elements txtRoxN + 1 and tickerRowN + 1. However, I have a problem with the select event for the id of tickerRowN. Because it changes every time I add a row, I don't know how to call the select event for the specific id of the table data in question. I have done a lot of searching around but as I am new to this, the only functions I have been able to find manipulate the element data when you know the id already. This id is dynamically created and so I don't know how to build the syntax. Thankyou for your time. UPDATE: with huge thanks to JK, the following example works. I now know about jsFiddle and will try to use this for all further questions. The following code works for my dynamic example, but I don't know why. Sigh. jsFiddle working example A: function getRowId(acInput){ //set prefix, get row number var rowPrefix = 'txtRow'; var rowNum = acInput.attr("id").substring((rowPrefix.length)); return rowNum; } $("#txtRow1").autocomplete({ source: states, minLength: 2, select: function(event, ui) { var tickerRow = "#tickerRow" + getRowId($(this)); //set ticker input $(tickerRow).val(ui.item.label); } }); http://jsfiddle.net/jensbits/BjqNz/
{ "pile_set_name": "StackExchange" }
Q: CSS for making simple graph I have to make a graph using simple CSS. In this graph, a background color of grey is displayed and on top of it, varying a background color of blue is displayed of varying width showing the number of items loaded. Please refer to my jsfiddle for this example. It is located at http://jsfiddle.net/mzCdb/1/ . The problem with my code is that I want the "4/10" overlapping between teh blue and the grey portion when the width of the blue portion is 50% unlike the second graph in my fiddle. The following is my html code :- <div class="graph"> <div class="graph-within"> </div> <div style="text-align:center;float:left;color:#888;font-weight:bold; font-family:Tahoma;font-size:15px;">4/10</div> </div> Please view the CSS code from the fiddle. Any help will be appreciated. Thanks in advance. A: You could absolutely position the text within the graph: .graph .text { position: absolute; z-index: 1; top: 0; height: 25px; text-align: center; width: 100px; } DEMO
{ "pile_set_name": "StackExchange" }
Q: Combining multiple parameters for creating SVM vector New to scikit-learn and I am working with some data like the following. data[0] = {"string": "some arbitrary text", "label1": "orange", "value1" : False } data[0] = {"string": "some other arbitrary text", "label1": "red", "value1" : True } For single lines of text there is CountVectorizer and DictVectorizer in the pipeline before TfidfTransformer. The output of these could be concatenated, I'm hoping with the following caveat: The arbitrary text I don't want to be equal in importance to the specific, limited and well-defined parameters. Finally, some other questions, possibly related might this data structure indicate which SVM kernel is best? Or would a Random Forest/Decision Tree, DBN, or Bayes classifier possibly do better in this case? Or an Ensemble method? (The output is multi-class) I see there is an upcoming feature for feature union, but this is to run different methods over the same data and combine them. Should I be using feature selection? See also: Implementing Bag-of-Words Naive-Bayes classifier in NLTK Combining feature extraction classes in scikit-learn http://scikit-learn.org/dev/modules/label_propagation.html A: All classifiers in scikit-learn(*) expect a flat feature representation for samples, so you'll probably want to turn your string feature into a vector. First, let get some incorrect assumptions out of the way: DictVectorizer is not for handling "lines of text", but for arbitrary symbolic features. CountVectorizer is also not for handling lines, but for entire text documents. Whether features are "equal in importance" is mostly up to the learning algorithm, though with a kernelized SVM, you can assign artificially small weights to features to make its dot products come out differently. I'm not saying that's a good idea, though. There are two ways of handling this kind of data: Build a FeatureUnion consisting of a CountVectorizer (or TfidfVectorizer) for your textual data and a DictVectorizer for the additional features. Manually split the textual data into words, then use each word as a feature in a DictVectorizer, e.g. {"string:some": True, "string:arbitrary": True, "string:text": True, "label1": "orange", "value1" : False } Then the related questions: might this data structure indicate which SVM kernel is best? Since you're handling textual data, try a LinearSVC first and a polynomial kernel of degree 2 if it doesn't work. RBF kernels are a bad match for textual data, and cubic or higher-order poly kernels tend to overfit badly. As an alternative to kernels, you can manually construct products of individual features and train a LinearSVC on that; sometimes, that works better than a kernel. It also gets rid of the feature importances issue as a LinearSVC learns per-feature weights. Or would a Random Forest/Decision Tree, DBN, or Bayes classifier possibly do better in this case? That's impossible to tell without trying. scikit-learn's random forests and dtrees unfortunately don't handle sparse matrices, so they're rather hard to apply. DBNs are not implemented. Should I be using feature selection? Impossible to tell without seeing the data. (*) Except SVMs if you implement custom kernels, which is such an advanced topic that I won't discuss it now.
{ "pile_set_name": "StackExchange" }
Q: How to play a Tank Destroyer in World of Tanks? I've played several Tank Destroyers, SPGs and Light Tanks so far and reached Tier V with each of them. (Panzer IV, M41, StuG III) My observation is that the overall difficulty level increases because you are faced with tanks which are more tough nuts to crack. In case of an SPG I had to learn how to properly aim at the weak spots and/or calculate with tank speed (I noticed that the higher the tier of the tank the opponent sits in the more aware they get of a possible SPG threat). I also get bigger guns (155mm howitzer in M41 for example) In my Light/Medium tanks I had to learn how to use cover so I don't die instantly and how I can use my speed to work myself around bigger threats. I do feel that the higher tier I get my tanks become more capable. In case of my tank destroyer StuG III I feel that this is not the case. I'm not as fast as a lighter tank, and I do not have the firepower of a heavy tank. (I can't shoot behind covers either). The StuG III has the same derp gun as the Hetzer but since it is a higher tier I often face Tigers and KV-1s. I also noticed that since the StuG III's armor is not as sloped as the Hetzer's I am more vulnerable. I don't feel the same progression with tiers as I do with other tank types. It seems to me that I did not learn something important about playing tank destroyers since the higher tier I get the less fun I have with them. Do you have some guidelines for a puzzled tank destroyer player? StuG III specific answers are also welcome A: Many tank destroyers, and particularly the Stug III have a great camo rating, which means that if you play carefully the enemy team will have great difficulty spotting you. While playing this particular tank, and other TDs like it, try to stay behind the rest of your team and lay down supporting fire form a sniping position. If you're not familiar with how camo and spotting works, I recommend this camouflage tutorial. Some general tips: Stay behind a bush, but remember that firing your gun will temporarily remove the additional camo value of the bush Equipping your TD with a camo net, and training the crew in camouflage will greatly increase your overall camo rating. Remember that moving your tank, even by slightly turning it lowers your camo value. With TDs and SPGs you can prevent accidentally turning your tank by locking it in place by using the (default) X key. The commander's sixth sense skill is great on TDs as it will help you know when you're spotted. The Stug III is responsible fast and mobile, if you are spotted or think you might be soon, relocate to a new position from which you can safely snipe. A: As an alternate answer to the excellent camo-oriented answer @Xenox provided, there are also tank destroyers that do not rely on camo: British TD starting from the AT range German TD starting from Jagdpanther 2/Ferdinand US TD starting from T28/T28 Prot Generally there are 3 types of tank destroyers: Camo-oriented: They are usually low profile, and turret-less Maneuverable: Either with turret, or very good turning speed Heavy armoured: slow, above average frontal armour The camo one, @Xenox has answered. For maneauvrable TDs (e.g. E-25, German turreted TD line...etc.) It's all about positioning, dishing out as much damage as you can, then withdraw and re-position, rinse and repeat. So learning how, and when to flank, learning paths to take so you can quickly retreat and move somewhere else, is the most important aspect for these kind of TDs. Heavy armoured TDs (JP-E100, T110E4, T95...etc) is about finding the spots that conceal your weakpoints, avoiding being flanked, whether by positioning, or knowing where your team mates are and how they can protect your flanks. Knowing when to push forward is also very important due to the slow movement speeds of these tanks, not being at the scene of an important skirmish can determine a match's outcome. As a heavily armoured TD you can also take the role of drawing attention, since your shots hurt alot people tend to want to take down TDs as quick as possible, so if you can utilise your armour well, you can, for example, draw attention away from your flanking team mates. There are numerous ways to play a TD, so it's not restricted to what I said above, e.g. a heavy TD can also play camo-oriented, if they can find bushes that are big enough.
{ "pile_set_name": "StackExchange" }
Q: htaccess MIME type css read as text/html Before you reference similar questions: I did actually do research yet no post solved my issue. I literally have the most basic code you can imagine yet one of the most basic things won't work. The CSS file is interpreted as text/html while I need it to be a read as a stylesheet. This is due to my .htaccess file even though I explicitly added the AddType thing. Here's my HTML: <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>EASY-Online</title> <link href="./css/bootstrap.min.css" type="text/css"/> </head> <body> <div class="alert alert-warning"> test </div> </body> </html> My htaccess: RewriteEngine On RewriteBase / AddType text/css .css RewriteCond %(REQUEST_FILENAME} !-d RewriteCond %(REQUEST_FILENAME} !-f RewriteCond %(REQUEST_FILENAME} !-l RewriteRule ^(.*)$ index.php?url=$1 [QSA,L,T=text/css] A: After some more research I found this to fix my issue: RewriteCond %{REQUEST_URI} !\.(?:css|js|jpe?g|gif|png)$ [NC] I added this directly above the RewriteRule. Apparently this allows the described extentions to be reachable by navigating to them instead of redirecting.
{ "pile_set_name": "StackExchange" }
Q: Spreading micromirrors evenly across surface of a helmet model (Particle effect, procedural, instancing) I am doing a pre-visualization of an art installation. It looks a bit qwirky ;) It is to remember the fall of the berlin-wall etc. etc. So it will be old helmets plated with small mirrors arranged in a very large ball / flower. BUT the question is, how do i get the tiny mirrors to spread evenly without clipping into each other on the mesh evenly? I wanted to do that effect for a long time already on a couple of projects. I thought i could instanciate the micro mirrors onto the surface with a particle emitter and use the normals of the surface etc. OR alternatively spawn at each vertices a mirror plate. Yet it would be very hard to make them even like a disco ball. Do you have any ideas? here is a video of the status quo (sorry for the quality) VIDEO of the status quo The first original helmet looks like this: i tried your question. Though i think from the method it is very much like extruding individual faces right? Not entirely sure how it does it ;D to be honest. here is the result, i believe because of the (rather unclean) mesh topology I can not go that route if I would have to make all faces evenly first. MAYBE: i could use something like cloth simulation? I could make a "fabric" (just joined mirrors as plane ) and stitch it to the surface? Does anyone has experience with it? A: You can use the Tissue addon. The addon will tesselate a given shape on a mesh. Select a tile, shift select your mesh, and use 'tesselate': From that, if you want to modify the original mesh, you can come back to the tesselation and refresh it. A: If the models geometry allows it, you can try that : In Edit mode, select every face you want a mirror on. In the Face menu, select Exrtude Individual Faces, and move your mouse to give the mirrors some depth. Give them a nice shiny material and you're done. A: This is a partial shader-only solution, which may be good enough for your visualization. It depends on a 'Tile UV' node group, available in the download. 'Tile UV' splits a given UV space into square cells, tile size given by the 'Scale' input. Its outputs are: Cell UV, UV coordinates within each cell, -0.5 to 0.5 in X and Y Dist. Center, the distance of the shading point from the center of its cell Dist. Edge, the same for the edges of the cell, here used to put the cracks between the tiles Min, Mid and Max Tile UVS, which return the locations of the Min. Mid. and Max. X and Y of the shading point's cell in the original, given, UV space. The steps to applying the shader to your object would be: UV unwrap the object. The shape/distribution of the tiles will depend on your seams, UV islands and how you straighten / distort them. You could do this while looking at just the Base Color branch of this material, to see how your squares/fragments are coming out. This example just uses the default unwrap of Suzanne, you can see the tiles swell in her mouth region. Having settled the map, bake an image of the object's object-space normals for it to use: one way.. with the object at the origin and aligned the world, plug the 'Normal' output of a Geometry node into an emission shader, and bake the 'Emit' from that into a floating-point image, with your UV map active, using Cycles, 1 sample. You can then use that normal map, as shown in the node tree, to look up the normal at the center of each tile, and use that for the normal of every shading point in the tile. 'Partial', because so far. this is only a Bump/Normal effect. Building the tree to create actual flat-per-tile displacements would be a bit more involved, and need you to bake a position map, too. I don't know how well it would come out - you'd either need very high-res geometry to displace the model, or use Cycles to get the renderer to do it, but If you wanted it, given time, I'd have a look at that.
{ "pile_set_name": "StackExchange" }
Q: como cambiar la imagen de un carrusel buenos dias estoy haciendo un proyecto con bootstrapy soy nuevo usándolo estoy tratando de crear un carrousel como se indica en la documentación pero no me funciona. Estoy buscando cual puede ser el motivo pero no lo encuentro agradecería de su colaboración <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- <link href= "../css/bootstrap.css" rel="stylesheet" type="text/css" style="display:none;visibility:hidden"https://www.googletagmanager.com/ns.html?id=GTM-MWD3VXM" height="0" width="0"></iframe></noscript>--> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link href="../cssMipagina/pantilla.css" rel="stylesheet" type="text/css" style="display:none;visibility:hidden" https://www.googletagmanager.com/ns.html?id=GTM-MWD3VXM " height="0 " width="0 "></iframe></noscript> <title>Red Distrital de Bibliotecas Públicas - Biblored</title> </head> <body> <header> h</div> </header> <div class ="container "> <div id="carouselExampleIndicators " class="carousel slide " data-ride="carousel "> <ol class="carousel-indicators "> <li data-target="#carouselExampleIndicators " data-slide-to="0 " class="active "></li> <li data-target="#carouselExampleIndicators " data-slide-to="1 "></li> <li data-target="#carouselExampleIndicators " data-slide-to="2 "></li> </ol> <div class="carousel-inner " role="listbox " > <div class="item active "> <img class="d-block w-100 " src="../recurso/50-regalos-de-la-internet-para-diseñadores9.jpg " alt=" "> </div> <div class="item "> <img class="d-block w-100 " src="../recurso/a.jpg " alt=" "> </div> <div class="item "> <img class="d-block w-100 " src="../recurso/descarga.jpg " alt=" "> </div> </div> <a class="left carousel-control-prev " href="#carouselExampleIndicators " role="button " data-slide="prev "> <span class="glyphicon glyphicon-chevron-left " aria-hidden="true "></span> <span class="sr-only ">Previous</span> </a> <a class="right carousel-control-next " href="#carouselExampleIndicators " role="button " data-slide="next "> <span class="glyphicon glyphicon-chevron-right " aria-hidden="true "></span> <span class="sr-only ">Next</span> </a> </div> </div> <script src="../js/jquery-3.2.1.slim.min.js "></script> <script src="../js/popper.min.js "></script> <script src="../js/bootstrap.min.js "></script> <!-- <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js " integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN " crossorigin="anonymous "></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js " integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q " crossorigin="anonymous "></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js " integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl " crossorigin="anonymous "></script> --> </body> </html> el carrusel no arranca solo mostrando la primera imagen y no funciona los botones de siguiente o anterior A: EL principal problema es que estás usando el css de Bootstrap3 y la librería javascrip de Bootstrap4, con lo que se genera un conflicto. También tienes una etiqueta iframe mal cerrada en el head. Aquí tienes el código funcionando con Bootstrap4. Por supuesto no he podido insertar tu CSS. <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <title>Red Distrital de Bibliotecas Públicas - Biblored</title> </head> <body> <header> </header> <div class ="container "> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner" role="listbox"> <div class="carousel-item active"> <img class="d-block img-fluid" src="http://lorempixel.com/800/400" alt="First slide"> </div> <div class="carousel-item"> <img class="d-block img-fluid" src="http://lorempixel.com/800/400" alt="Second slide"> </div> <div class="carousel-item"> <img class="d-block img-fluid" src="http://lorempixel.com/800/400" alt="Third slide"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script></body> </html>
{ "pile_set_name": "StackExchange" }
Q: Nmap module issues in python I have installed nmap.exe and the nmap module. I am not sure how to configure the nmap path though. The block of code where you enter the nmap path is as follows class PortScanner(object): """ PortScanner class allows to use nmap from python """ def __init__(self, nmap_search_path=('nmap','/usr/bin/nmap','/usr/local/bin/nmap','/sw/bin/nmap','/opt/local/bin/nmap') ): """ Initialize PortScanner module * detects nmap on the system and nmap version * may raise PortScannerError exception if nmap is not found in the path :param nmap_search_path: tupple of string where to search for nmap executable. Change this if you want to use a specific version of nmap. :returns: nothing """ self._nmap_path = 'C:/Program Files (x86)/Nmap/' # nmap path self._scan_result = {} self._nmap_version_number = 0 # nmap version number self._nmap_subversion_number = 0 # nmap subversion number self._nmap_last_output = '' # last full ascii nmap output is_nmap_found = False # true if we have found nmap self.__process = None # regex used to detect nmap regex = re.compile('Nmap version [0-9]*\.[0-9]*[^ ]* \( http://.* \)') # launch 'nmap -V', we wait after 'Nmap version 5.0 ( http://nmap.org )' # This is for Mac OSX. When idle3 is launched from the finder, PATH is not set so nmap was not found for nmap_path in nmap_search_path: try: p = subprocess.Popen([nmap_path, '-V'], bufsize=10000, stdout=subprocess.PIPE) except OSError: pass else: self._nmap_path = nmap_path # save path break else: raise PortScannerError('nmap program was not found in path. PATH is : {0}'.format(os.getenv('PATH'))) I placed the path in the self._nmap_path variable. However, it does not seem to work. Could anyone with experience in nmap help me? How do I get started in nmap? I have researched this for hours but have still not come up with an answer. The error I receive is Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> nmap.PortScanner() File "C:\Python33\Lib\site-packages\nmap\nmap.py", line 192, in __init__ raise PortScannerError('nmap program was not found in path') nmap.PortScannerError: 'nmap program was not found in path' A: It looks like your environment path is not setup correctly. If you open the C:\Python33\Lib\site-packages\nmap\nmap.py file for editing and look at line 192. Where is it looking? It might be worth simply reinstalling with the self installer, the installer should set the path variables for you. http://nmap.org/book/inst-windows.html
{ "pile_set_name": "StackExchange" }
Q: Flutter TypeAhead Issue I am trying to implement the Flutter Typeahead based on the following link: Flutter TypeAhead class _CallAddState extends State<CallAdd> { final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); final TextEditingController _typeAheadController = TextEditingController(); var SerVerConfig = [ { "name":"Mike", "id":"1" }, { "name":"Bill", "id":"2" }, { "name":"Juan", "id":"3" }, ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Form( key: this._formKey, child: Padding( padding: EdgeInsets.all(32.0), child: Column( children: <Widget>[ TypeAheadField( textFieldConfiguration: TextFieldConfiguration( autofocus: true, style: DefaultTextStyle.of(context) .style .copyWith(fontStyle: FontStyle.italic), decoration: InputDecoration(border: OutlineInputBorder())), suggestionsCallback: (pattern) async { return SerVerConfig; }, itemBuilder: (context, suggestion) { print("item builder " + suggestion); return ListTile( leading: Icon(Icons.shopping_cart), title: Text(suggestion['name']), // subtitle: Text('\$${suggestion['id']}'), ); }, onSuggestionSelected: (suggestion) { Navigator.of(context).push(MaterialPageRoute( // builder: (context) => ProductPage(product: suggestion) )); }, ) ], ), ), )); } } Unfortunately, I am getting an error with the following message in the suggestionsCallback function. "type '_InternalLinkedHashMap' is not a subtype of type 'String' Any help or advice is much appreciated. Thanks. A: SerVerConfig use List, you can compare difference You can see full code and demo picture (Example 2: Form) code snippet List SerVerConfig = [ {"name": "Mike", "id": "1"}, {"name": "Bill", "id": "2"}, {"name": "Juan", "id": "3"}, ]; TypeAheadField( textFieldConfiguration: TextFieldConfiguration( autofocus: true, style: DefaultTextStyle.of(context) .style .copyWith(fontStyle: FontStyle.italic), decoration: InputDecoration(border: OutlineInputBorder())), suggestionsCallback: (pattern) async { return SerVerConfig; }, itemBuilder: (context, suggestion) { return ListTile( leading: Icon(Icons.shopping_cart), title: Text(suggestion['name']), // subtitle: Text('\$${suggestion['id']}'), ); }, onSuggestionSelected: (suggestion) { Navigator.of(context).push(MaterialPageRoute( builder: (context) => ProductPage(product: suggestion))); }, ), full code import 'package:flutter/material.dart'; import 'package:flutter_typeahead/flutter_typeahead.dart'; import 'package:example/data.dart'; class MyMaterialApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'flutter_typeahead demo', home: MyHomePage(), ); } } class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return DefaultTabController( length: 3, child: Scaffold( appBar: AppBar( title: TabBar(tabs: [ Tab(text: 'Example 1: Navigation'), Tab(text: 'Example 2: Form'), Tab(text: 'Example 3: Scroll') ]), ), body: TabBarView(children: [ NavigationExample(), FormExample(), ScrollExample(), ])), ); } } class NavigationExample extends StatelessWidget { @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.all(32.0), child: Column( children: <Widget>[ SizedBox( height: 10.0, ), TypeAheadField( textFieldConfiguration: TextFieldConfiguration( autofocus: true, style: DefaultTextStyle.of(context) .style .copyWith(fontStyle: FontStyle.italic), decoration: InputDecoration( border: OutlineInputBorder(), hintText: 'What are you looking for?'), ), suggestionsCallback: (pattern) async { var fruits = ['bananas', 'apples', 'oranges']; return await BackendService.getSuggestions(pattern); }, itemBuilder: (context, suggestion) { return ListTile( leading: Icon(Icons.shopping_cart), title: Text(suggestion['name']), subtitle: Text('\$${suggestion['price']}'), ); }, onSuggestionSelected: (suggestion) { Navigator.of(context).push(MaterialPageRoute( builder: (context) => ProductPage(product: suggestion))); }, ), ], ), ); } } class FormExample extends StatefulWidget { @override _FormExampleState createState() => _FormExampleState(); } class _FormExampleState extends State<FormExample> { final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); final TextEditingController _typeAheadController = TextEditingController(); String _selectedCity; List SerVerConfig = [ {"name": "Mike", "id": "1"}, {"name": "Bill", "id": "2"}, {"name": "Juan", "id": "3"}, ]; @override Widget build(BuildContext context) { return Form( key: this._formKey, child: Padding( padding: EdgeInsets.all(32.0), child: Column( children: <Widget>[ Text('What is your favorite city?'), TypeAheadFormField( textFieldConfiguration: TextFieldConfiguration( decoration: InputDecoration(labelText: 'City'), controller: this._typeAheadController, ), suggestionsCallback: (pattern) { //var fruits = ['bananas', 'apples', 'oranges']; return CitiesService.getSuggestions(pattern); }, itemBuilder: (context, suggestion) { return ListTile( title: Text(suggestion), ); }, transitionBuilder: (context, suggestionsBox, controller) { return suggestionsBox; }, onSuggestionSelected: (suggestion) { this._typeAheadController.text = suggestion; }, validator: (value) { if (value.isEmpty) { return 'Please select a city'; } }, onSaved: (value) => this._selectedCity = value, ), TypeAheadField( textFieldConfiguration: TextFieldConfiguration( autofocus: true, style: DefaultTextStyle.of(context) .style .copyWith(fontStyle: FontStyle.italic), decoration: InputDecoration(border: OutlineInputBorder())), suggestionsCallback: (pattern) async { return SerVerConfig; }, itemBuilder: (context, suggestion) { return ListTile( leading: Icon(Icons.shopping_cart), title: Text(suggestion['name']), // subtitle: Text('\$${suggestion['id']}'), ); }, onSuggestionSelected: (suggestion) { Navigator.of(context).push(MaterialPageRoute( builder: (context) => ProductPage(product: suggestion))); }, ), SizedBox( height: 10.0, ), RaisedButton( child: Text('Submit'), onPressed: () { if (this._formKey.currentState.validate()) { this._formKey.currentState.save(); Scaffold.of(context).showSnackBar(SnackBar( content: Text('Your Favorite City is ${this._selectedCity}'))); } }, ) ], ), ), ); } } class ScrollExample extends StatelessWidget { final List<String> items = List.generate(5, (index) => "Item $index"); @override Widget build(BuildContext context) { return ListView(children: [ Center( child: Padding( padding: const EdgeInsets.all(8.0), child: Text("Suggestion box will resize when scrolling"), )), SizedBox(height: 200), TypeAheadField<String>( getImmediateSuggestions: true, textFieldConfiguration: TextFieldConfiguration( decoration: InputDecoration( border: OutlineInputBorder(), hintText: 'What are you looking for?'), ), suggestionsCallback: (String pattern) async { return items .where((item) => item.toLowerCase().startsWith(pattern.toLowerCase())) .toList(); }, itemBuilder: (context, String suggestion) { return ListTile( title: Text(suggestion), ); }, onSuggestionSelected: (String suggestion) { print("Suggestion selected"); }, ), SizedBox(height: 500), ]); } } class ProductPage extends StatelessWidget { final Map<String, dynamic> product; ProductPage({this.product}); @override Widget build(BuildContext context) { return Scaffold( body: Padding( padding: const EdgeInsets.all(50.0), child: Column( children: [ Text( this.product['name'], style: Theme.of(context).textTheme.headline, ), Text( this.product['price'].toString() + ' USD', style: Theme.of(context).textTheme.subhead, ) ], ), ), ); } }
{ "pile_set_name": "StackExchange" }
Q: HTML/CSS: Vertical aligning span with vertical-align and line-height Sorry to beat a dead horse, but I cannot for the life of me understand why the below does not work. Set line-height: 50px Set vertical-align: top To my understanding, this should make the line-box 50px tall, and then vertical-align should, according to MDN, be able to move the inline element around inside it. Specifically: The following values vertically align the element relative to the entire line: bottom Aligns the bottom of the element and its descendants with the bottom of the entire line. I tried both this: <span style="line-height: 50px; border: 1px solid red; vertical-align: bottom">Some text</span> And this: <div style="line-height: 50px; border: 1px solid yellow"> <span style="border: 1px solid red; vertical-align: bottom">Some text</span> </div> It is the last version above that I would expect to position the span at the bottom. It says the line-box should be 50px, then vertical-align is used on the child span. PS: Please don't just say "use flexbox" or similar. I would like to understand the inner workings / conceptually why the above did not position the span at the bottom of the line. A: Everything you said is right but you simply forget something which is inheritance. The span element is having the same line-height defined on the div that's why bottom has no effect in your case. Reset the value to initial and it will work. <div style="line-height: 50px; border: 1px solid yellow"> <span style="border: 1px solid red; vertical-align: bottom;line-height:initial;">Some text</span> </div>
{ "pile_set_name": "StackExchange" }
Q: Muenchian? XSLT to denormalize/pivot/flatten xml file? Given an input xml file with following structure: <root> <record row="1" col="1" val="1" /> <record row="1" col="2" val="2" /> <record row="1" col="3" val="3" /> <record row="1" col="n" val="4" /> <record row="2" col="1" val="5" /> <record row="2" col="3" val="6" /> <record row="2" col="n" val="7" /> <record row="n" col="2" val="8" /> <record row="n" col="3" val="9" /> <record row="n" col="n" val="10" /> </root> How can I output the following structure using XSLT? <root> <row id="1"> <col id="1">1</col> <col id="2">2</col> <col id="3">3</col> <col id="n">4</col> </row> <row id="2"> <col id="1">5</col> <col id="2"></col> <col id="3">6</col> <col id="n">7</col> </row> <row id="n"> <col id="1"></col> <col id="2">8</col> <col id="3">9</col> <col id="n">10</col> </row> </root> [Note how all columns are output even if there is no related element in input] EDIT: I may have caused confusion through the use of numbers and letters in my example. The solution I am looking for needs to handle row and column attributes that are non-numeric. A: The answers to this question show possible ways to approach the problem: xslt: How could I use xslt to create a table with multiple columns and rows? EDIT: A solution that incorporates the techniques seen in the linked question follows. I am assuming: your @row and @col attributes are incrementing numbers that define the position of the record in the table, and they cannot really contain the string "n". As such they are not unique throughout the document, which makes them unsuitable as HTML @id attributes. I substituted them by @title attributes in my output. there are no implicit empty rows (gaps in @row continuity will not produce empty rows), only implicit empty cells. every @row and @col combination is unique. This XSLT 1.0 transformation: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > <!-- prepare some keys for later use --> <xsl:key name="kRecordsByRow" match="record" use="@row" /> <xsl:key name="kRecordsByPos" match="record" use="concat(@row, ',', @col)" /> <!-- find out the highest @col number --> <xsl:variable name="vMaxCol"> <xsl:for-each select="/root/record"> <xsl:sort select="@col" data-type="number" order="descending" /> <xsl:if test="position() = 1"> <xsl:value-of select="@col" /> </xsl:if> </xsl:for-each> </xsl:variable> <!-- select the <record>s that are the first in their rows --> <xsl:variable name="vRows" select=" /root/record[ generate-id() = generate-id(key('kRecordsByRow', @row)[1]) ] " /> <!-- output basic table structure --> <xsl:template match="/root"> <table> <xsl:for-each select="$vRows"> <xsl:sort select="@row" data-type="number" /> <tr title="{@row}"> <xsl:call-template name="td" /> </tr> </xsl:for-each> </table> </xsl:template> <!-- output the right number of <td>s in each row, empty or not --> <xsl:template name="td"> <xsl:param name="col" select="1" /> <td title="{$col}"> <xsl:value-of select="key('kRecordsByPos', concat(@row, ',', $col))/@val" /> </td> <xsl:if test="$col &lt; $vMaxCol"> <xsl:call-template name="td"> <xsl:with-param name="col" select="$col + 1" /> </xsl:call-template> </xsl:if> </xsl:template> </xsl:stylesheet> …when applied to this (slightly modified) input: <root> <record row="1" col="1" val="1" /> <record row="1" col="2" val="2" /> <record row="1" col="3" val="3" /> <record row="1" col="4" val="4" /> <record row="2" col="1" val="5" /> <record row="2" col="3" val="6" /> <record row="2" col="4" val="7" /> <record row="3" col="2" val="8" /> <record row="3" col="3" val="9" /> <record row="3" col="4" val="10" /> </root> …produces: <table> <tr title="1"> <td title="1">1</td> <td title="2">2</td> <td title="3">3</td> <td title="4">4</td> </tr> <tr title="2"> <td title="1">5</td> <td title="2"></td> <td title="3">6</td> <td title="4">7</td> </tr> <tr title="3"> <td title="1"></td> <td title="2">8</td> <td title="3">9</td> <td title="4">10</td> </tr> </table> Muenchian grouping is used to select the first <record>s of each @row group an <xsl:key> is used to pinpoint a record by it's position recursion is used to produce a consistent set of <td>s, independent of the actual existence of a <record> at the named position
{ "pile_set_name": "StackExchange" }
Q: Rails production 404,500 etc error pages with same layout as rest webpages How could i render my error pages in production mode, so that they are in same layout as rest pages? For example, not 404 as standart <h1>The page you were looking for doesn't exist.</h1> <p>You may have mistyped the address or the page may have moved.</p> without any layout, but this message in my layout (called application.html.haml)? Is it real? And what and where i need to write? I google'd but for own layout didn't find good one.... i use rails 3.2.8, ruby 1.9.3 A: One solution would be this: # In config/application.rb config.exceptions_app = self.routes # In routes match "/404", to: "errors#not_found" match "/500", to: "errors#server_error" # app/controllers/errors_controller.rb class ErrorsController < ApplicationController # Inherits layout from ApplicationController def not_found end def server_error end end # app/views/errors/not_found.haml %h1 Didn't find nothing! # app/views/errors/server_error.haml %h1 FUBAR!
{ "pile_set_name": "StackExchange" }
Q: Creating a fifo queue in SQS using boto3 Can anyone help me with creating a fifo queue in sqs using boto3. Tried this but this doesn’t work sqs.create_queue(QueueName='test', Attributes={'FifoQueue':'true’}) A: Your queue name has to end in .fifo and you have to be using either us-west-2 or us-east-2 region as those are the only regions that currently support the FIFO feature. A: This is a complete working example of creating a FIFO queue on SQS: import boto3 import pprint import time sqs = boto3.resource('sqs', region_name='us-west-2') queue = \ sqs.create_queue(QueueName='test.fifo', Attributes={'FifoQueue': 'true'}) pprint.pprint(queue)
{ "pile_set_name": "StackExchange" }
Q: Auto-number table rows? I have the following HTML table: <table border="1"> <tr> <td>blue</td> </tr> <tr> <td>red</td> </tr> <tr> <td>black</td> </tr> </table> I would like each row in this table have a number automatically assigned to each item. How could he do? A: The following CSS enumerates table rows (demo): table { counter-reset: rowNumber; } table tr::before { display: table-cell; counter-increment: rowNumber; content: counter(rowNumber) "."; padding-right: 0.3em; text-align: right; } <table cellpadding="0"> <tr><td>blue</td></tr> <tr><td>red</td></tr> <tr><td>yellow</td></tr> <tr><td>green</td></tr> <tr><td>purple</td></tr> <tr><td>orange</td></tr> <tr><td>maroon</td></tr> <tr><td>mauve</td></tr> <tr><td>lavender</td></tr> <tr><td>pink</td></tr> <tr><td>brown</td></tr> </table> If the CSS cannot be used, try the following JavaScript code (demo): var table = document.getElementsByTagName('table')[0], rows = table.getElementsByTagName('tr'), text = 'textContent' in document ? 'textContent' : 'innerText'; for (var i = 0, len = rows.length; i < len; i++) { rows[i].children[0][text] = i + ': ' + rows[i].children[0][text]; } <table border="1"> <tr> <td>blue</td> </tr> <tr> <td>red</td> </tr> <tr> <td>black</td> </tr> </table> A: And if you would use headers as well the following is the thing you need: http://jsfiddle.net/davidThomas/7RyGX/ table { counter-reset: rowNumber; } table tr:not(:first-child) { counter-increment: rowNumber; } table tr td:first-child::before { content: counter(rowNumber); min-width: 1em; margin-right: 0.5em; } note the: ":not(:first-child)" in there. A: Here is a modification of David Thomas' CSS solution that works with or without a header row in the table. It increments the counter on the first td cell of each row (thereby skipping the row with only th cells): table { counter-reset: rowNumber; } table tr > td:first-child { counter-increment: rowNumber; } table tr td:first-child::before { content: counter(rowNumber); min-width: 1em; margin-right: 0.5em; } You can see the behavior in this jsfiddle.
{ "pile_set_name": "StackExchange" }
Q: How is it possible to viewpager swiping being enable while an overlay is shown I have this xml layout <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/root_view" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white" > <com.duolingo.open.rtlviewpager.RtlViewPager android:id="@+id/book_reader_viewpager_portrait" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:background="@color/white" tools:visibility="visible" android:visibility="gone" /> <ImageView android:id="@+id/icon_pause" android:layout_width="@dimen/book_reader_pause" android:layout_height="@dimen/book_reader_pause" android:layout_alignParentEnd="true" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:src="@drawable/icon_pause" /> <include layout="@layout/loading_screen" /> <include layout="@layout/layout_offline_no_data" /> <include layout="@layout/layout_error_no_data" /> <include layout="@layout/layout_book_reader_overlay" /> <include layout="@layout/layout_book_reader_continue_or_startover" /> </RelativeLayout> I have this issue that when this overlay is shown (layout_book_reader_overlay) I can swipe or scroll page horizontally .. which shouldn't be happening as I understand A: Touch and click events are passed to the highest View that accepts them. If you do not want the ViewPager to swipe when the overlay is shown, set android:clickable="true" on the root View of the overlay layout. That way, it will take click events away from the ViewPager, even if it does not respond to them. Note that for this to really work, your overlay must fully cover the ViewPager, otherwise the parts that are not covered will still be swipeable. If the overlay is not meant to be full-screen, then you can make the outermost View of the overlay full-screen and transparent, make that clickable, then put the actual overlay inside it. <FrameLayout xmlns:android="..." android:layout_width="match_parent" android:layout_height="match_parent" android:clickable="true"> <!-- put your overlay layout in here --> </FrameLayout>
{ "pile_set_name": "StackExchange" }
Q: Creating a list based on a list definition template I have a list definition in my solution, and i want programmatically be able to create a list based on that list definition, could anyone tell me how to do that? <ListTemplate Name="Mylise" Type="10778" BaseType="0" OnQuickLaunch="TRUE" SecurityBits="11" Sequence="410" DisplayName="My new List" Description="My own list" Image="/_layouts/images/itgen.png"/> A: Call var customTemplate = yourSPWeb.ListTemplates["Mylise"]; to get the list template object, then yourSPWeb.Lists.Add("List title", "List description", customTemplate); to create the list. A: try { SPList list = null; using (SPSite site = new SPSite("http://yoursite/")) { using (SPWeb web = site.RootWeb) { //List Will be Created Based on this ListDefinition - OOB Custom List Definition //00BFEA71-DE22-43B2-A848-C05709900100 foreach (SPList _list in web.Lists) { if (_list.Title.Equals("TestList")) { list = _list; } } if (list == null) { web.AllowUnsafeUpdates = true; Guid listID = web.Lists.Add("TestList", //List Title "This is Test List", //List Description "Lists/TestList", //List Url "00BFEA71-DE22-43B2-A848-C05709900100", //Feature Id of List definition Provisioning Feature – CustomList Feature Id 10778, //List Template Type "101"); //Document Template Type .. 101 is for None web.Update(); web.AllowUnsafeUpdates = false; } } } } catch (Exception ex) { } Hope This is Helpful For you :)
{ "pile_set_name": "StackExchange" }
Q: MySQL - Return from a string the leftmost characters from 2 different characters I have a database with some codes seperated by / or -, I want to show the left side only, this is an example of the data: 45/84 12/753 68-53 15742-845 2/556 So, i want to get this: 45 12 68 15742 2 I tried using LEFT(), but this search for 1 character only, and returns a warning if the character is not found, this is what LEFT(field,'/') returns. 45 12 (WARNING) (WARNING) 2 So, what about a REGEXP? an IF? any way to ignore from the first non numeric character? I dont' have more ideas... Thank you! A: Try this: SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(col, '-', 1), '/', 1) FROM mytable Demo here
{ "pile_set_name": "StackExchange" }
Q: Unable to populate NSMutableArray from JSON file I have this following code that I am using to populate an NSMutableArray from a JSON file to use it late as a datasource for a CollectionView: NSString *filePath = [[NSBundle mainBundle] pathForResource:@"governorates" ofType:@"json"]; NSData *content = [[NSData alloc] initWithContentsOfFile:filePath]; NSDictionary *governorateJson = [NSJSONSerialization JSONObjectWithData:content options:kNilOptions error:nil]; NSArray *govNSArray = [governorateJson objectForKey:@"gouvernorats"]; if ([govNSArray isKindOfClass:[NSArray class]]){ for (NSDictionary *dictionary in govNSArray) { Governorate *govModel = [Governorate new] ; govModel.govID = [dictionary objectForKey:@"id"]; govModel.govNameAr = [[dictionary objectForKey:@"nom"] objectForKey:@"ar"]; govModel.govNameFr = [[dictionary objectForKey:@"nom"] objectForKey:@"fr"]; [self.governoratesArray addObject:govModel]; [self.governoratesString addObject:govModel.govNameAr]; NSLog(@"Count: %lu", (unsigned long) self.governoratesString.count); } NSLog(@"Total Count: %lu", (unsigned long) self.governoratesString.count); } The problem is the NSMutableArray always seems to be empty, and I am using the exact same code in another place with the same JSON file and it's working fine. A: Once check that mutable array is being alloc init or not before using it.
{ "pile_set_name": "StackExchange" }
Q: Restricting access to php file I'm currently writing an Android app at the moment, that accesses a PHP file on my server and displays JSON data provided by my MYSQL database. Everything works great and I love the simplicity of it, but I'm not too comfortable with the fact that someone could just type in the URL of this PHP file and be presented with a page full of potentially sensitive data. What advice would you give me to prevent access to this PHP file from anyone except those using my android app? Thanks very much for any information. A: The keyword is authentication. HTTP-Authentication is designed just for that purpose! There are 2 forms of HTTP-auth: Basic: easy to setup, less secure Digest: harder to setup, more secure Here is the php manual. And this is what you can do in your android app.
{ "pile_set_name": "StackExchange" }
Q: wrong number of arguments (0 for 1) (ArgumentError) when git push heroku master Background: Try to push spree to heroku. It work ok in localhost:3000 but no luck in heroku. After push heroku master, it's was no error. But when open heroku it's display Application Error. Can anyone help get rid the "wrong number of arguments" When heroku open Application Error An error occurred in the application and your page could not be served. Please try again in a few moments. If you are the application owner, check your logs for details. In the heroku logs, there is timeout as follow Starting process with command `bundle exec unicorn -p 56138 -c ./config/unicorn.rb` 2016-08-18T05:52:21.426098+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/unicorn- 5.1.0/lib/unicorn/configurator.rb:196:in `timeout': wrong number of arguments (0 for 1) (ArgumentError) A: Error happened from follow someone blog code here worker_processes Integer(ENV["WEB_CONCURRENCY"] || 3) timeout timeout 15 preload_app true before_fork do |server, worker| Signal.trap 'TERM' do puts 'Unicorn master intercepting TERM and sending myself QUIT instead' Process.kill 'QUIT', Process.pid end defined?(ActiveRecord::Base) and ActiveRecord::Base.connection.disconnect! end after_fork do |server, worker| Signal.trap 'TERM' do puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to send QUIT' end defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection end Which has error from second line timeout removed that timeout then it worked.
{ "pile_set_name": "StackExchange" }
Q: Como filtrar objetos JSON pelos campos de um array? Como posso pesquisar objetos JSON pelas tags atribuídas a ele? Tipo eu quero pegar todos os objetos que tenham a tag "algodao". Estou criando o modelo como está aí em baixo por enquanto, mas não sei se é a melhor forma, alguém me dá uma luz? { "ofertas": [ { "id": 1, "categoria": "masculino", "titulo": "Blusa Clássica", "descricao_oferta": "Camisa confeccionada em tecido leve de algodão com poliéster.", "anunciante": "riachuelo", "valor": 59.90, "destaque": true, "data" : "1970-01-01 00:00:00", "tags": [ {"tag": "algodao"}, {"tag": "blusa"}, {"tag": "azul"}, {"tag": "classica"} ], "imagens": [ { "url": "/assets/ofertas/camisa-social/camisa-classica-01.jpg" }, { "url": "/assets/ofertas/camisa-social/camisa-classica-02.jpg" }, { "url": "/assets/ofertas/camisa-social/camisa-classica-03.jpg" }, { "url": "/assets/ofertas/camisa-social/camisa-classica-04.jpg" } ] }, ... } pode ser pelo navegador localmente, eu só quero saber o caminho que tenho que seguir pra conseguir esse objeto. E se a forma que estruturei é a mais prática. Eu estava tentando isso: http://localhost:3000/ofertas?tags?tag=algodao mas não obtive sucesso. A: Você pode utilizar alguma ferramenta que ofereça leitura por meio de expressões JSONPath, como este site por exemplo. Com seu JSON, você pode aplicar expressões como $.ofertas..imagens, que irá selecionar todas os nodes de imagens abaixo de ofertas: [ [ { "url": "/assets/ofertas/camisa-social/camisa-classica-01.jpg" }, { "url": "/assets/ofertas/camisa-social/camisa-classica-02.jpg" }, { "url": "/assets/ofertas/camisa-social/camisa-classica-03.jpg" }, { "url": "/assets/ofertas/camisa-social/camisa-classica-04.jpg" } ] ] É possível também filtrar por índice do array, utilizando $.ofertas..imagens[0]: [ { "url": "/assets/ofertas/camisa-social/camisa-classica-01.jpg" } ] É possível fazer vários filtros sobre propriedades também, mas recomendo você estudar por conta própria no link que deixei no começo da resposta :)
{ "pile_set_name": "StackExchange" }
Q: Swift ios relational picker views and apple dev guidelines Right now I have a picker view that shows up when you press a label, and after you have selected anything from the picker view and hit done it will hide and the label will change to the value you selected. But I want to implement another picker view, and that picker view will only display based on the value you selected in the first picker view. So more or less like a relational dropdown that you can find on almost every website. I want to be able to select category and subcategory. But its only about 10% of the categories that has an subcategory thats why I want to build it this way. So my question now is if this will be against apples dev/design guidelines? Or does anybody else have a good solution on how to display a category/subcategory selector for a search form in an iOS app? Thanks in advance, A: Just a rough sketch: Say you pick a category from you PickerView. Your PickerView should then notify you parent ViewController that the user has picked a Category. The most convenient way to do this is to have a Delegate method, like: self.delegate.userPickedCategory(pickedCategory: Category) Now, I assume you Category object contains an array of subcategories: class Category: NSObject { var title: NSString! var subCategories: NSMutableArray! //some variable containing categories content } Say you named the button to your Sub Category Menu subCategoryButton. You should always set hidden = true or at least userInteractionEnabled = false, because you don't know whether the picked category has a sub. If your parent ViewController receives the delegate method that your user picked a category, you might do: func userPickedCategory(pickedCategory: Category) { if pickedCategory.subcategories != nil || pickedCategory.subCategories.count != 0 { //you now know the picked category has a subCategory //so allow the user to pick that subCategory by enabling this button self.subCategoryButton.hidden = false self.subCategoryButton.userInteractionEnabled = true } Then, you need to make sure the subCategoryButton shows another picker view containing the subCategories of your picked Category
{ "pile_set_name": "StackExchange" }
Q: Como puedo colocar un nombre a cada fila resultante de UNION en Sql Server La idea es que luego de hacer una UNION en SQL server poder identificar con un nombre cada fila, para poder identificar de que tabla viene la data A: Solo agrega un campo más a cada fila con el nombre de la tabla select dato1, dato2, 'nombre tabla' as nombreTabla from tabla1 union all select dato1, dato2, 'nombre tabla 2' from tabla2
{ "pile_set_name": "StackExchange" }
Q: how to solve a nonlinear parabolic equations? I have derived two nonlinear parabolic equation as $$\begin{align*} \frac{\partial S}{\partial t}&=a\exp\left(\frac{x-b}{c}\right)^2\frac{\partial^2 S}{\partial x^2} \tag{1}\\ \frac{\partial S}{\partial t}&=a\exp\left(\frac{x-b}{c}\right)^2\frac{\partial}{\partial x}\left(S\frac{\partial S}{\partial x}\right) \tag{2}\\ \end{align*}$$ I wonder if anyone can give a detail analysis for exact solution. Thank you! A: For (1), note that it is a linear PDE. First have a "warm-up" by using separation of variables: Let $ S(x,t)=X(x)T(t) $, Then $$X(x)T'(t)=ae^{\left(\frac{x-b}{c}\right)^2}X''(x)T(t)$$ $$\dfrac{T'(t)}{T(t)}=\dfrac{ae^{\left(\frac{x-b}{c}\right)^2}X''(x)}{X(x)}=f(s)$$ $$ \begin{cases}\dfrac{T'(t)}{T(t)}=f(s) \\ae^{\left(\frac{x-b}{c}\right)^2}X''(x)-f(s)X(x)=0 \end{cases} $$ Therefore $$ae^{\left(\frac{x-b}{c}\right)^2}\dfrac{\partial^2K(x,s)}{\partial x^2}-s K(x,s)=0 $$ For complying the conditions $S(0,t)=0$ and $\dfrac{\partial S}{\partial x}(L,t)=0$ , You should take the solution as $S(x,t)=\sum\limits_sC_1(s)e^{tf(s)}X_1(x,s)$, where $X_1(x,s)$ is some or all solutions of $ae^{\left(\frac{x-b}{c}\right)^2}X''(x)-f(s)X(x)=0$ that satisfies $X(0)=0$ and $X'(L)=0$ . But to solve $ae^{\left(\frac{x-b}{c}\right)^2}X''(x)-f(s)X(x)=0$ is just like to solve second-order linear ODE with general variable coefficients and is very complicated. I provide this article to you to have deep investigation on this issue. For (2), I have no idea.
{ "pile_set_name": "StackExchange" }
Q: Conditional logic in Dockerfile, using --build-arg Say I have this: ARG my_user="root" # my_user => default is "root" USER $my_user ENV USER=$my_user All good so far, but now we get here: ENV HOME="/root" is there a way to do something like this: ENV HOME $my_user === "root"? "/root" : "/home/$my_user" Obviously, that's the wrong syntax. The only solution I can think of is to just use two --build-args, something like this: docker build -t zoom \ --build-arg my_user="foo" \ --build-arg my_home="/home/foo" \ . A: Unfortunately you can't do this directly https://forums.docker.com/t/how-do-i-send-runs-output-to-env-in-dockerfile/16106/3 So you have two alternatives Use a shell script at start You can use a shell script at the start CMD /start.sh And in your start.sh you can have that logic if [ $X == "Y" ]; then export X=Y else export X=Z fi Create a profile environment variable FROM alpine RUN echo "export NAME=TARUN" > /etc/profile.d/myenv.sh SHELL ["/bin/sh", "-lc"] CMD env And then you when you run it $ docker run test HOSTNAME=d98d44fa1dc9 SHLVL=1 HOME=/root PAGER=less PS1=\h:\w\$ NAME=TARUN PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PWD=/ CHARSET=UTF-8 Note: The SHELL ["/bin/sh", "-lc"] is quite important here, else the profile will not be loaded Note2: Instead of RUN echo "export NAME=TARUN" > /etc/profile.d/myenv.sh you can also do a COPY myevn.sh /etc/profile.d/myenv.sh and have the file be present in your build context
{ "pile_set_name": "StackExchange" }
Q: For which values of $x$ does these series converge absolutely, converge conditionally or diverge I have these (math) problems where I am first supposed to find out if a given series converge or diverge, and then, by using that result, multiplying the same series by $x^n$ and find out for which values of $x$ the series converge absolutely, conditionally or diverge. I think I am starting to get a certain idea of which converge/divergence tests to use for different types of series, but the "by using that result"-part is confusing me a little bit. First series I concluded $\sum_{n=2}^{\infty}\frac{n^2 + 1}{n^2 - 1}$ diverges by applying the divergence test: $\lim_{n \to \infty}\frac{n^2 + 1}{n^2 - 1} = 1 \neq 0$. However, when I try to find out for which values of $x$ the series $\sum_{n=2}^{\infty}\frac{n^2 + 1}{n^2 - 1}x^n$ converge absolutely, conditionally or diverge, I dont know how to directly use the result I found previously. My book says the way to find out the radius of converge is by using the ratio test: $ \frac{1}{R} = L = \lim_{n \to \infty}\left|\frac{a_{n + 1}}{a_n}\right| = \lim_{n \to \infty}\frac{((n+1)^2 +1)(n^2 - 1)}{((n+1)^2 - 1)(n^2 + 1)} = 1$ (by multiplying by $\frac{1}{n^2}$) So because radius of convergence is $1$, I concluded the series converges absolutely for $x \in (-1 , 1)$ and diverge for $(-\infty, -1]\cup[1, \infty)$. Here I knew already that the series diverges for $x = 1$ and thus can not converge absolutely for $x \leq -1$. It does also not converge conditionally as $\lim_{n \to \infty}\frac{n^2 + 1}{n^2 - 1}(-1)^n \neq 0$. So, in other words, assuming I am on the right track here, I need a little advice how to do this more direct if possible. I do one more example to see if I have thought about it in the right way.. Second series I used the comparison test to conclude that $\sum_{n=0}^{\infty}\frac{2^n}{4^n + 1}$ converges since $\frac{2^n}{4^n + 1} \lt \frac{1}{2^n}$ for $n = 0, 1, 2, \dots$ Now, trying to do the same as previously for $\sum_{n=0}^{\infty}\frac{2^n}{4^n + 1}x^n$, I don't see a way to use what I just found directly, so I do the ratio test again to find the radius of converge with center of converge at $x = 0$: $\frac{1}{R} = L = \lim_{n \to \infty}|\frac{a_{n + 1}}{a_n}| = \lim_{n \to \infty}\frac{2^{n + 1}(4^n + 1)}{2^n(4^{n + 1} + 1)} = \lim_{n \to \infty}\frac{2*4^n}{4*4^n + 1} + \lim_{n \to \infty}\frac{2}{4*4^n + 1} = \frac{2}{4} \Rightarrow R = 2$. So I concluded the series converges (absolutely) for $x \in (-2, 2)$ which actually makes sense when I look at it, as $x = 2$ would make the numerator $4^n$ and the series would diverge like $\sum_{n=0}^{\infty}1$. Again I do not see any way to make the series converge conditionally and thus diverges everywhere else but $x \in (-2, 2)$ Summary I need advice how I can use the information about whether a series converges or diverges to decide for which values of the same series multiplied by $x^n$ converges absolutely, converges conditionally or diverges. Any help appreciated, sorry if the math things are a little bit tiny. A: I don't think there's really a better way to do either of these. A slightly less direct but nicer way would be to use the limit comparison test to compare it with $$\sum_{n=2}^{\infty} x^n$$ (for the first series) or $$\sum_{n=2}^{\infty} (x/2)^n$$(for the second), but it's essentially the same idea. Generally speaking, if you can determine how your original series converges, you can find the radius convergence of it multiplied by $x^n$ in this manner. (Also, a note: If you put double-dollar-signs around expressions they center and become bigger - that's called displaymath mode and it's generally used for expressions with large operators.)
{ "pile_set_name": "StackExchange" }
Q: Overwrite local branch with remote tracking branch (branches have diverged) I have create a new branch named my-4.3.y using the following command (note: my-4.3.y is set up to track remote branch 4.3.y from origin): git checkout -b my-4.3.y origin/4.3.y I haven't worked on the my-4.3.y branch after checking it out. Now, several days later, when I run: git status It tells me that my-4.3.y and origin/4.3.y have diverged. I don't care where and why the branches have diverged, I don't want to merge the remote branch into my. I just want my branch to be equal to the remote branch again. So, what I am doing is: (1) checkout some other branch (2) delete my-4.3.y and (3) check it out again: git checkout some_other_branch git branch -D my-4.3.y git checkout -b my-4.3.y origin/4.3.y Is there an easier way to that? A: You can use git reset --hard to force your currently checked out branch to any arbitrary point you would like. Note: using --hard is not working directory safe, and will throw out any changes you have. For the specific case of updating to your tracking branch you can use @{u} to specify your upstream git reset --hard @{u} Generally, you can pass in any branch reference or anything else Git resolves to a commit e.g. git reset --hard origin/4.3.y
{ "pile_set_name": "StackExchange" }
Q: ListView sorts added members as if they were another sorted list that comes after the original list I'm getting some odd behavior when I try to sort a javafx ListView object that starts with some elements in it after adding new elements to it. The code used to sort is movieList.getItems().add(newMovie); if(mainController.getListingOrder().equals("title")) { movieList.getItems().sort(Movie.getTitleComparator()); } else { movieList.getItems().sort(Movie.getYearComparator()); } The getTitleComparator() method is as follows public static Comparator<Movie> getTitleComparator() { return new Comparator<Movie>() { @Override public int compare(Movie movie1, Movie movie2) { return movie1.getTitle().compareTo(movie2.getTitle()); } }; } The three following pictures should hopefully illustrate the problem I'm having. Before any elements added: After 1 element added: After adding three elements: As you can see, the added elements are being sorted alphabetically with each other, but not with the elements that are already in the list. Is there any way to make it so all the elements sort in alphabetical order instead of acting as if they were two separate sorted arrays put next to each other? A: You compare strings in case-sensitive order. Instead of a.compareTo(b) do: String.CASE_INSENSITIVE_ORDER.compare(a, b)
{ "pile_set_name": "StackExchange" }
Q: Prevent closing by back button in xamarin forms on android I want to prevent closing the app by pressing the hardware back button in xamarin forms on android. I want, that you can navigate with the hardware back button in the app (what is working), but do not want to exit, when the first page in navigation stack is reached. I tried to use the OnSleep event in xamarin forms, but here I can not cancel the exit. I also tried catching the back button in android: public override void OnBackPressed() { //base.OnBackPressed(); } But when using xamarin forms, I do not know which page is currently showing. So I do not know if the navigation back is allowed or not A: It works with evaluating the NavigationStack (when you use NavigationPage). In my Activity, I override the OnBackPressed public override void OnBackPressed() { if(App.Instance.DoBack) { base.OnBackPressed(); } } In my xamarin forms app (App.Instance (it is a singleton)), I will evaluate the NavigationStack of the current Page like this. public bool DoBack { get { NavigationPage mainPage = MainPage as NavigationPage; if (mainPage != null) { return mainPage.Navigation.NavigationStack.Count > 1; } return true; } } When there is only one page left in the NavigationStack I will not call base.OnBackPressed, so that I will not close the App. ![test] A: And here's what the code could look like for a Xamarin Forms MasterDetail page scenario... public bool DoBack { get { MasterDetailPage mainPage = App.Current.MainPage as MasterDetailPage; if (mainPage != null) { bool canDoBack = mainPage.Detail.Navigation.NavigationStack.Count > 1 || mainPage.IsPresented; // we are on a top level page and the Master menu is NOT showing if (!canDoBack) { // don't exit the app just show the Master menu page mainPage.IsPresented = true; return false; } else { return true; } } return true; } } A: Just give a blank call in the page where do you wanna prevent, like protected override bool OnBackButtonPressed() { return true; } This will prevent the back button in XF-Droid.
{ "pile_set_name": "StackExchange" }
Q: How to assign a label to go.layout.Shape(type="line"...)? I produce the following figure. The figure has a number of add_trace applied to it with go.Scatter as arguments. A list of 4 go.layout.Shape, type="line", with fixed color attributes, is created and the figure layout is updated with that list: fig.update_layout(..., shapes=...) The traces have labels assigned to them that we can see to the extreme right. Is there a way to add labels to assign to the lines as well? A: You would like your lines to appear in the legend of the figure (https://plot.ly/python/legend/). However, only traces can appear in the legend, not shapes which are a kind of annotation. What you could do is to create the lines using go.Scatter(..., mode='lines'), and then they would appear in the legend. You just need to give the starting and end points in go.Scatter (see https://plot.ly/python/line-and-scatter/).
{ "pile_set_name": "StackExchange" }
Q: Describe a policy in AWS using the CLI It might seems a silly question but I'm not able and I haven't find any command to show in the aws CLI the policy body. I have a managed policy attached to a role. I can simply display the ID and other information but not the body. Am I missing anything? I run aws iam get-policy --policy-arn <arn> and get something like: { "Policy": { "PolicyName": "developer_allow", "CreateDate": "2017-03-28T12:57:11Z", "AttachmentCount": 1, "IsAttachable": true, "PolicyId": "XXXXXXXXXXXXXXXXXXXXX", "DefaultVersionId": "v1", "Path": "/", "Arn": "arn:aws:iam::xxxxxxxxxxx:policy/developer_allow", "UpdateDate": "2017-03-28T12:57:11Z" } } A: It was slightly more complicated but here the command: aws iam get-policy-version --policy-arn arn:aws:iam::XXXXXXXXXXXXXXX:policy/developer_allow --version-id v1 You need to specify the version
{ "pile_set_name": "StackExchange" }
Q: Окна в Терминале Здравствуйте! Подскажите пожалуйста, существует ли библиотека для реализации окон в терминале? Например как в Far, Midnight Commander, NC, ImpulseTracker для DOS и т.п. Помню очень давно была библиотека для Турбо Паскаль вроде, но забыл как называлась. Может быть есть современная реализация Окон В Терминале, для .NET например или Jаva? A: Charva
{ "pile_set_name": "StackExchange" }
Q: Does Cloud Computing COST a premium? (or is it competitive with shared/managed/co-location) Since cloud solutions (Google AppEngine, Amazon, etc.) do more for you, at the end of the day do they cost significantly more than doing it "yourself" with co-location hosting, etc. Not just starting out, but when the website is mature and getting many page views a day. A: They cost significantly more than do yourself - their advantage is not price per unit when used full month, it is price per unit for a short time PLUS significant scalaiblity. No many month contract. THis means if you have a site growing fast, you can easily get new nodes online without long term commitment. Any significant large static load is better served through other means, purely from a financial point of view. Colocation at the end being most competitive - if you OWN the hardware, there is no overhead for leasing, handling etc. A: Cloud computing, is always more expensive than doing it yourself. The attraction of cloud computing from a finance perspective is that instead of having to show N thousands of dollars of debt from a capital expense, all you show is a monthly bill (of course over the same 3 year period you could have purchased a datacenter bu that's never stopped a CFO from choosing less expensive now over less expensive in total). One of the myths of cloud computing is that you somehow gain infinite scalability. Before we called it cloud computing we called it "just throw more hardware at it". The secret of cloud computing is that your scalability is determined by your application, what technologies it's using and its architecture. Yes, you can probably get more performance or concurrent users out of throwing more hardware at it this time, but sooner or later more memory or faster CPUs isn’t going to do anything useful. I can guarantee you that “the cloud” isn’t going to advise you on how to restructure your storage so it will horizontally scale to a petabyte of data. Since cloud solutions (Google AppEngine, Amazon, etc.) do more for you Really, what is the "more" they are doing for you other than providing the hardware required to run your OS of choice? They aren't doing backups, they aren't providing OS licenses.Keep in mind, that with many of the "free" services like goog app engine, there is no SLA involved, so they can't even guarantee that the platform will be up. So here's what the cloud does offer: quick startup time inexpensive entry costs convienient 1 stop shopping (eg no looking for datacenters, comparing hardware etc) That certainly might be worthwhile to you but it's going to add to the expense sheet.
{ "pile_set_name": "StackExchange" }
Q: How can I dock the button to jQueryUI dialog bottom as the dialog inner content increases? UPDATE: Sorry I make this question to complex. What I want to ask is that how can I "fix" the buttons' position to the bottom of the jQueryUI dialog as the dialog height grow's larger. I have a jQueryUI dialog as follow: <head> $(function(){ $("#ChooseStoryCategory").dialog({ autoOpen: false, title: "Upload", height: 600, width: 500, modal: true }); }); </head> And I add two buttons in the dialog and I always want to put them at the bottom of the dialog. Here is the code: <body> <div id= "ChooseStoryCategory"> <div id="storyCategory"></div> <div><button id="ChooseCategory"><img src= "../pic/chooseOk.png"/></button></div> <div><button id="CategoryCancel"><img src= "../pic/close.png"/></button></div> </div> </body> css setting: #ChooseCategory{ position: absolute; left: 30%; top: 85%; bottom: 0; } #CategoryCancel{ position: absolute; left: 70%; top: 85%; bottom: 0; } But I will always increase element inside the dialog like this: for(multiple times)://pseudocode var categoryName= "PressNum1"; var value= 3; var $btn= $('<button/>').text(categoryName).width(400).height(80); $btn.bind('click', function(){console.log(value)}); $("#storyCategory").append($btn); As the added buttons increase, their position will exceed the two buttons(ChooseCategory and CategoryCancel). How can I dock the two buttons to the bottom of the jQueryUI dialog? I have tried to get the initial top position of the two buttons. As each button is added to the dialog, I just change the position of the two buttons. $("#CategoryCancel").css("height") = $("#ChooseStoryCategory").css("height") * 0.85 + $btn.css("height"); But $("#ChooseStoryCategory").css("height") * 0.85 + $btn.css("height"); didn't add the px, it just combines the number and string... Is there any simple alternative approach to dock the two buttons at the bottom of the jqueryUI dialog? A: Why dont you use the buttons option? $( "#ChooseStoryCategory" ).dialog({ autoOpen: false, title: "Upload", height: 600, width: 500, modal: true buttons: { "Choose category": function() { // Do something $( this ).dialog( "close" ); }, Cancel: function() { $( this ).dialog( "close" ); } } }); Check out the examples within jquery-ui's page: http://jqueryui.com/dialog/ or check out the API documentation: http://api.jqueryui.com/dialog/#option-buttons Here's the jsFeedle: http://jsfiddle.net/6gb4v/ (Took @rusln fiddle and started from there).
{ "pile_set_name": "StackExchange" }
Q: Convert time fields to strings in Excel I have an excel sheet full of times. They are formatted so that they look like: 1:00:15 However if I change the format on the cells to text, they change to the underlying numeric representation of the time: 0.041840278 How can I convert the cells to be text cells but still have the time in them ? A: This kind of this is always a pain in Excel, you have to convert the values using a function because once Excel converts the cells to Time they are stored internally as numbers. Here is the best way I know how to do it: I'll assume that your times are in column A starting at row 1. In cell B1 enter this formula: =TEXT(A1,"hh:mm:ss AM/PM") , drag the formula down column B to the end of your data in column A. Select the values from column B, copy, go to column C and select "Paste Special", then select "Values". Select the cells you just copied into column C and format the cells as "Text". A: copy the column paste it into notepad copy it again paste special as Text A: If you want to show those number values as a time then change the format of the cell to Time. And if you want to transform it to a text in another cell: =TEXT(A1,"hh:mm:ss")
{ "pile_set_name": "StackExchange" }
Q: Le « sabre laser » : de quoi s'agit-il en fait et comment s'appelle-t-il ainsi ? La Fédération française d'escrime adopte le sabre laser. (titre d'article dans La Presse) Sans blague : Le sabre définit l’objet d’où sort une ou plusieurs lames énergétiques. Il comporte plusieurs parties : un émetteur, une poignée, un activateur et un pommeau et éventuellement une garde. La lame définit le tube en polycarbonate éclairé par une LED qui va de la sortie de l’émetteur du sabre jusqu’à l’extrémité de l’embout. L’embout est la partie en polycarbonate ou MMA situé à l’extrémité de la lame. Il doit être rond. La poignée du sabre laser doit être composée d’un alliage métallique, sans excroissance. Le sabre laser définit l’objet composé du sabre et de la lame. La longueur totale du sabre laser est mesurée de l’extrémité du pommeau à la pointe de la lame et doit être comprise entre 100 cm (inclus) à 110 cm (exclus). [ Extrait du règlement national pour les combats sportifs au sabre laser de l'Académie de Sabre Laser, entité de la Fédération Française d'Escrime étant la seule organisation officielle ayant compétence pour enseigner et organiser la pratique du sabre laser sur le territoire conformément aux directives et missions du ministère des sports. ] Quel est le terme technique (réel) qui désigne cet objet (le « sabre laser »1) ? Comment appelle-t-on la figure de style ou le procédé qui fait qu'on puisse l'appeler sabre laser ? 1 Je suis parfaitement conscient du fait que ce soit une traduction du lightsaber : « Un pari ambitieux quand on connaît les différences fondamentales entre l’escrime traditionnelle et l’univers fantastique du sabre laser. » FFE, directement tiré du lien sous la deuxième citation ; « Maître Yoda, dépoussiérer son français, il le doit. » directement tiré de l'article de La Presse lié à la fin de la première citation. J'espère qu'on aura compris que le sabre laser n'existe pas et donc qu'il n'y a pas de laser ici : « Un sabre laser est une arme fictive de la saga cinématographique Star Wars. » (Wikipédia). Enfin je n'ai pas posé la question, qui se veut plus qu'un simple titre, sur Movies & TV. A: C'est juste l'expression officielle consacrée dès les premières traductions de la saga Star Wars, La guerre des étoiles, avec toutes les licenses artistiques que ce genre d'activité autorise. On retrouve cette juxtaposition de noms dans d'autres expressions: disque vinyle, bas nylon, stylo encre, ... En réponse à l'affirmation que le sabre laser n'en est pas un: Je ne suis pas assez versé dans les sciences de la Force pour affirmer sans doute aucun qu'il ne s'agit pas de laser. Il est même possible que la lumière observée ne soit qu'un sous-produit de la véritable lame sous-jacente. De toute façon, on peut affirmer qu'il ne s'agit pas d'un sabre. Le sabre est généralement courbe contrairement à l'épée. Il ne s'agit pas d'un fleuret ni d'un glaive qui sont des armes d'estoc et pas de taille, alors que le sabre laser convient aux deux situations. Discriminer sur le nombre de tranchants est assez difficile à la simple observation des combats. J'opterais donc pour épée à lame éclairante rétractable. (Par conséquent, la figure de style qui fait qu'on puisse l'appeler sabre laser s'appelle un mensonge, de la catégorie marketing)
{ "pile_set_name": "StackExchange" }
Q: how to make horizontal scroll like metro? I need make something similar to Windows 8's Metro style horizontal scrolling. For example, when the user moves the mouse in corner, the scrollers move with it. I tried this code: $(document).ready(function() { document.documentElement.onmousewheel = function (event) { $('body').scrollLeft($('body').scrollLeft() - event.wheelDelta); }; }); But the horizontal scrolling is not quite working as I'd expect it to. How should I make a Windows 8 style horizontal scroll? A: I found the answer: To get horizontal scrolling the Mouse Wheel Plugin by Brandon Aaron (GitHub, Download) will be used to detect mouse wheel movements like a keypress and of course, jQuery itself will be used. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="js/jquery.mousewheel.js"></script> Javascript $(document).ready(function() { $('html, body, *').mousewheel(function(e, delta) { this.scrollLeft -= (delta * 40); e.preventDefault(); }); }) The JavaScript can just be added into the Head tag. Note that scrolling applies to html, body and * (everything) – this enables it to work across different browsers. The event.preventDefault() just disables vertical scrolling.
{ "pile_set_name": "StackExchange" }
Q: Not able to send email in iOS I am trying to send mail in iOS but it doesn't work. Below is the code, using to send mail. MFMailComposeViewController *mailCtrl = [[MFMailComposeViewController alloc] init]; mailCtrl.mailComposeDelegate = self; [mailCtrl setSubject:@"Definition from CDE iPhone App"]; NSString *body = [self flattenHTML:[mydef renderHTML:NO landscape:NO]]; [mailCtrl setMessageBody:body isHTML:YES]; [self presentModalViewController:mailCtrl animated:YES]; //[mailCtrl navigationBar].tintColor = [UIColor blackColor]; [mailCtrl navigationBar].tintColor = [UIColor grayColor]; [mailCtrl release]; above code sets the html code in the body. everything it sets properly but when tapped on the send it doesn't send the mail to the emailid provided ion To box. Please help.... A: iOS simulator doesn't allow you to send email. You'll need a physical device to test this functionality.
{ "pile_set_name": "StackExchange" }
Q: Collatz Conjecture (3n+1) variant Let's consider the following variant of Collatz (3n+1) : if $n$ is odd then $n \to 3n+1$ if $n$ is even then you can choose : $n \to n/2$ or $n \to 3n+1$ With this definition, is it possible to construct a cycle other than the trivial one, i.e., $1\to 4 \to 2 \to 1$? Best regards A: Yes! With the standard Collatz conjecture, every number must eventually end up at the cycle $4 \to 2 \to 1 \to 4 \cdots$ . This has been verified for all numbers up to $2^{60}$. With your altered definition, you can start at $2$, apply $3n+1$ instead of $n/2$, and then continue like the standard Collatz again. $$2 \xrightarrow{3n+1} 7 \to 22 \to 11 \to \cdots ,$$ you'll eventually end at $2$ again, since this is one of the verified cases. A: $$7\to 22$$ $$22\to11$$ $$11\to34$$ $$34\to17$$ $$17\to52$$ $$52\to26\to13$$ $$13\to40$$ $$40\to20\to10\to5$$ $$5\to16$$ $$16\to8\to4\to2$$ $$2\to 3\cdot2+1=7$$ A: $4\to13\to40\to20\to10\to5\to16\to8\to4$
{ "pile_set_name": "StackExchange" }
Q: Are there any ActionScript 3 components/UI optimised for use in Adobe AIR touch/mobile applications? I have been searching for about a week now and found such pure AS3 UI/components: What I'm trying to create is (Adobe AIR mobile) options/settings menu for game and depending on the size/pixel density of a particular screen may require scrolling down options, mimicking the scrolling lists of Android with visual indicator of list location and the visual clue when reaching the end of the list with the inertia too MinimalComps (minimalcomps.com) Razorberry (razorberry.com/blog/components/) But they are all optimised for mouse clicks and use scrollbars as the interaction area for example (uses minimalcomps, try to use it in browser on mobile touchscreen, very fiddly to use, in fact had to zoom in just to get past the conditions screen(!!)) I've had no luck finding any information or tutorial to create menu system in Adobe AIR mobile in pure AS3 (it usually just links to Flex or AIR desktop applications) I only found one example of game pure AS3 with source to show, http://blogs.adobe.com/cantrell/archives/2010/05/my_presentation_on_multiscreen_development.html but it doesn't show you how to implement basic touch menus/UI or interface, A: I've been meaning to give mad components a try, they look very promising. Not sure if they'll solve your particular problem, but they do seem to outperform a similarly equipped Flex app (based on other developer's comments ;) A: Look at foxhole components : source and example And You can also look at this project i working on , its extension for MinimalComps that works like Flex display system and have databinding . With little style work and extend few components You can use it on touchscreens. source: https://github.com/turbosqel/Extended-MinimalComps example: http://turbosqel.pl/ExMinimalComps/simple/
{ "pile_set_name": "StackExchange" }
Q: What mobs are one block tall The title explains all. I'm asking for mobs that are one block tall (exactly one block). Can I use commands to change Slime's height so that it's a 1 block tall mob? A: Only a pig and a spider are about one block tall. All else are listed here if you need to determine other sizes.
{ "pile_set_name": "StackExchange" }
Q: javascript: generate 2 random but distinct numbers from range quick question: What is the best way for implementing this line of python code (generates two random but distinct numbers from a given range)... random.sample(xrange(10), 2) ...in Javascript? Thanks in advance! Martin A: Here is my attempt using splice: var a = [1,2,3,4,5,6,7,8,9,10];var sample = []; sample.push(a.splice(Math.random()*a.length,1)); sample.push(a.splice(Math.random()*a.length,1)); Wrapped in a function: function sample_range(range, n) { var sample = []; for(var i=0; i<n; i++) { sample.push(range.splice(Math.random()*range.length,1)); } return sample; } var sample = sample_range([1,2,3,4,5,6,7,8,9,10], 2); We could also stick the function into Array.prototype to have something like dot notation syntax: Array.prototype.sample_range = function(n) { var sample = []; for(var i=0;i<n;i++) { sample.push(this.splice(Math.random()*this.length,1)); } return sample; }; var sample = [1,2,3,4,5,6,7,8,9,10].sample_range(2); A: If you want to generate random numbers between 0 and n, one way is to randomly pick number r1 in 0..n then pick r2 from 0..n-1 and add 1 to r2 if r2 >= r1.
{ "pile_set_name": "StackExchange" }
Q: How can i add my data properly in csv format? My code to write my data in a .txt file: with open(file_path, 'w') as f: id = 1 for line in value: line = re.sub('[^A-Za-z0-9-,]+', '', str(line)) ymax, xmax, xmin, ymin=line.split(',') f.write(('{{\'yMax\': u\'{}\', \'xMax\': u\'{}\', \'xMin\': u\'{}\',\'yMin\': u\'{}\', \'id\': \'{}\', \'name\': \'\'}}'.format(ymax, xmax, xmin, ymin,id))) id = id + 1 outcome : {'yMax': u'156', 'xMax': u'4802', 'xMin': u'4770','yMin': u'141', 'id': '1', 'name': ''} {'yMax': u'157', 'xMax': u'4895', 'xMin': u'4810','yMin': u'141', 'id': '2', 'name': ''} However i want my data in a table like format of .csv: image id name xMin xMax yMin yMax 1-0.png 1 4770 4802 141 156 1-0.png 2 4810 4895 141 157 How can i adjust my code to go from the .txt format i already have to the .csv format i want? The excess column which is image is simply the filename of the txt but .png instead of txt so easy enough using re i can adjust later my main issue is the table shape. A: This should help. use csv.DictWriter with open(file_path, 'w') as f: writer = csv.DictWriter(f, delimiter='\t', fieldnames=['yMax', 'xMax', 'xMin', 'yMin', 'id', 'name']) #Tab seperated writer.writeheader() #Add header for i, line in enumerate(value, 1): #enumerate to get id line = re.sub('[^A-Za-z0-9-,]+', '', str(line)) ymax, xmax, xmin, ymin=line.split(',') d = {'yMax': ymax,'xMax': xmax, 'xMin': xmin,'yMin': ymin, 'id': i, 'name': ''} writer.writerow(d) Note: This is sample code.
{ "pile_set_name": "StackExchange" }
Q: How to read an XML file from the disk using Qt? I want to read an xml file as follow: QFile myFile("xmlfile"); and then continue with parsing the xml starting from : QXmlStreamReader xmlData(myFile); .. the error I get is: no matching function for call to 'QXmlStreamReader::QXmlStreamReader(QFile&)' so what is the problem and how to solve it ? question update: Based on the selected answer below, the code is now working without a syntax error . however, I can not read my xml. when parsing the xml, I use the following to read xml elements: QXmlStreamReader::TokenType token = xmlElements.readNext(); then this code for checking the startElements: while(!xmlElements.atEnd() && !xmlElements.hasError()){ // the breakpoint is here do ... } so, at this breakpoint, I notice in my debuger that token value is QXmlStreamReader::Invalid(1) so, what is going on .. is my QStreamReader does not read the file as xml, or it read it but there is an error with the xml itself ? A: The error message is telling you that there is no constructor for the class QXmlStreamReader with the signature you are trying to invoke, i.e. the one that would accept QFile parameter alone (either by value or by reference). Reading documentation is quite helpful. Relevant extract: QXmlStreamReader () QXmlStreamReader ( QIODevice * device ) QXmlStreamReader ( const QByteArray & data ) QXmlStreamReader ( const QString & data ) QXmlStreamReader ( const char * data ) Now, if you know that QFile actually inherits QIODevice (what you can find out in the documentation too), then you can immediately understand that the invocation should be changed as follows: QXmlStreamReader xmlData(&myFile); Furthermore, it seems like you don't know how to utilize QXmlStreamReader at all, therefore what you are looking for is a tutorial. I don't feel like rewriting great Qt tutorials here. So to intercept all your further questions, I'd refer you to the official tutorial.
{ "pile_set_name": "StackExchange" }
Q: Route::controller route names How can I get route names for Route::controller to use with route() helper ? For example: Route::controller('admin', 'AdminController'); Is possible to use 'admin' as a prefix, for example route('admin.users') and so on ? I've tried issuing artisan route:list but doesn't show anything for these routes. A: You can use 'as' to specify names for your routes, Route::get('/admin/users', [ 'as' => 'admin.users', 'uses' => 'AdminController@users' ]); Now if you see the output of artisan route:list You should see the name of the route /admin/users is set to admin.users
{ "pile_set_name": "StackExchange" }
Q: How to detect if the A,S,D or/and W button is pressed in cocos2d-mac? I want to move my ccsprite/b2body with the W,A,S,D keys in cocos2d for mac. How can I detect if one of these buttons are pressed? Can the user press multiplie keys at simultaneous? Can cocos2d for mac handle multiplie keys when they are pressed? Thank you very much A: Check this out: Cocos2d handling events (it detects none, one, or several keys pressed at the same time) Find Key Codes For Your Mac Keyboard
{ "pile_set_name": "StackExchange" }
Q: How to plot three sets of comparative data in R I have this dataframe called mydf where I have column Gene_symbol and three different columns (cancers), AML,CLL,MDS. I want to plot the percentage of each gene in these cancers. What would be the good way to represent this in plot? mydf <- structure(list(GENE_SYMBOL = c("NPM1", "DNMT3A", "TET2", "IDH1", "IDH2"), AML = c("28.00%", "24.00%", "8.00%", "9.00%", "10.00%" ), CLL = c("0.00%", "8.00%", "0.00%", "3.00%", "1.00%"), MDS = c("7.00%", "28.00%", "7.00%", "10.00%", "3.00%")), .Names = c("GENE_SYMBOL", "AML", "CLL", "MDS"), row.names = c(NA, 5L), class = "data.frame") A: We can try with barplot from base R after removing the % from the percent columns by looping through the columns, using sub to remove the %, and converting to numeric. mydf[-1] <- lapply(mydf[-1], function(x) as.numeric(sub("[%]", "", x)) ) barplot(`row.names<-`(as.matrix(mydf[-1]), mydf$GENE_SYMBOL), beside=TRUE, legend = TRUE, col = c("red", "green", "blue", "yellow")) If we want 'GENE_SYMBOL' in the x-axis barplot(t(`row.names<-`(mydf[-1], mydf$GENE_SYMBOL)), beside=TRUE, legend = TRUE, col = c("red", "green", "blue")) If we are using ggplot library(dplyr) library(tidyr) library(ggplot2) gather(mydf, Var, Val, -GENE_SYMBOL) %>% mutate(Val = as.numeric(sub("[%]", "", Val))) %>% ggplot(., aes(x= GENE_SYMBOL, y = Val)) + geom_bar(aes(fill = Var), position = "dodge", stat="identity")
{ "pile_set_name": "StackExchange" }
Q: Removing a parent element in xml while keeping it's children using xslt I want to transform the following xml, <pets> <Pet> <category> <id>4</id> <name>Lions</name> </category> <id>9</id> <name>Lion 3</name> <photoUrls> <photoUrl>url1</photoUrl> <photoUrl>url2</photoUrl> </photoUrls> <status>available</status> <tags> <tag> <id>1</id> <name>tag3</name> </tag> <tag> <id>2</id> <name>tag4</name> </tag> </tags> </Pet> </pets> in to this xml format. <pets> <Pet> <category> <id>4</id> <name>Lions</name> </category> <id>9</id> <name>Lion 3</name> <photoUrl>url1</photoUrl> <photoUrl>url2</photoUrl> <status>available</status> <tag> <id>1</id> <name>tag3</name> </tag> <tag> <id>2</id> <name>tag4</name> </tag> </Pet> </pets> I tried to write a template as follows, but it removes the parent element with it's children. <xsl:template match="photoUrls"/> How can this be done in xslt. Any help is appreciated. A: The following xslt does the job, <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output indent="yes" method="xml" /> <!-- Identity Transform --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()" /> </xsl:copy> </xsl:template> <xsl:template match="photoUrls"> <xsl:copy-of select="photoUrl" /> </xsl:template> <xsl:template match="tags"> <xsl:copy-of select="tag" /> </xsl:template> </xsl:stylesheet> But if you have any other way of doing this please don't hesitate to post your answer here. A: I would do it this way : <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output indent="yes" method="xml" /> <xsl:template match="photoUrls|tags"> <!-- Apply identity transform on child elements of photoUrls/tags--> <xsl:apply-templates select="*"/> </xsl:template> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()" /> </xsl:copy> </xsl:template> </xsl:stylesheet>
{ "pile_set_name": "StackExchange" }
Q: Simplifying Javascript if statement undefined if (typeof $scope.input.gps === 'undefined') { $scope.msgBody = 'Location not found.'; } else { $scope.msgBody = $scope.input.gps+' not found.'; } flash.pop({title: 'Error', body: $scope.msgBody, type: 'error'}); Would there be an easier way to do this if statement and include it inside the flash.pop A: There's nothing wrong with clear, easily maintained code even if it's a few characters more to type initially, it might save a lot of time and effort later. Seems you need to set the value of $scope.msgBody, I don't think it's a good idea to do that in the assignment. Consider: $scope.msgBody = typeof $scope.input.gps === 'undefined'? 'Location not found.' : $scope.input.gps + ' not found.' However, I don't think that's "easier". A: You may use $scope.msgBody = ($scope.input.gps || 'Location') + ' not found.';. But note that Location will be used not only if $scope.input.gps is undefined, but also if null, "", 0, NaN and false. Those values are covered by the falsy concept, see http://www.sitepoint.com/javascript-truthy-falsy/.
{ "pile_set_name": "StackExchange" }
Q: Convert a decimalized number into a fraction of eighths Fairly sure this is a simple problem, but I'm having issues wrapping my head around it. Suppose I have a decimalized number: 1.25 1.5 2.75 2.45 How do I convert the decimal part to be shown as a fraction of eighths? e.g. 1 2/8 1 4/8 2 6/8 2 3/8 // I need to round down rather than up when its not a simple conversion. Many thanks! A: This is a simple function to calculate the fractions using only Math (no split) in vanilla Javascript. document.addEventListener("DOMContentLoaded", function(event) { document.getElementById("number").addEventListener("change", function(event) { var f = parseFloat(document.getElementById("number").value); // float var a = Math.abs(f); // absolute value var w = Math.floor(a); // whole number var r = a - w; // remainder var d = Math.floor(r / .125); // denominator document.getElementById("results").innerHTML = f + " as a fraction: " + (f < 0 ? '-' : '') + w + ' ' + (d > 0 ? d + '/8' : '') + '<br>' + document.getElementById("results").innerHTML; })}); Enter a number to convert to fractions of 1/8s.<br> <input type="text" id="number" name="number" /> <div id="results"></div>
{ "pile_set_name": "StackExchange" }
Q: gitlab create new user via api yields 404 I'm able to do get requests to the gitlab api but I now want to programmatically create my first user. But every time I do a post request in Ruby: uri = URI.parse("http://ip-address/api/v3/users") http = Net::HTTP::new(uri.host, uri.port) request = Net::HTTP::Post.new(uri.request_uri) request.set_form_data({"username" => "username", "email" => "[email protected]", "password" => "password", "name" => "name"}) request["PRIVATE-TOKEN"] = "private-token" response = http.request(request) It shouldn't make a difference but i've tried this with a standard curl request, and with the gitlab ruby wrapper. For all of them my get requests work, but I get a 404 when trying to create a new user. Any ideas? A: As commented in issue 6878: 404 is the default result so far for password isn't acceptable email isn't unique username isn't unique So make sure your POST isn't for a user with a password or email or name problem (like one mentioned in issue 4209).
{ "pile_set_name": "StackExchange" }
Q: AsyncTask check MainActivity for variable set before ending doInBackground I would like to check for a variable in MainActivity while an AsyncTask created from it is running in the background, then end the AsyncTask when this variable is set to a certain value let's say to true; MainActivity @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); new MyTask(this).execute(); } MyTask public class MyTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... ignore) { //check for MainActivity variable then exit or PostExecute when this variable is set to true? } } A: Assuming Android is similar to normal Java threads and runnables in this regard, I would assume that you could just create an atomic variable in your main thread (MainActivity.java) and then check it in your AsyncTask. e.x. private final AtomicInteger myInt = new AtomicInteger(whatever value you need); public int getMyInt() { return myInt.get(); } Then just get the value and do what you want with it. You can also write methods to modify it or whatever else you want to do. https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html Otherwise if you need to pass objects, you'll have to look into synchronization, which you can find some good articles on by Googling. edit: To implement you could make the AtomicInteger static and the method as well, then just call the method to get the value of the integer. e.x. private final static AtomicInteger myInt = new AtomicInteger(whatever value you need); public static int getMyInt() { return myInt.get(); } then in your AsyncTask: public void doInBackground() { if(MainActivity.getMyInt() == some value) { //do something with it } }
{ "pile_set_name": "StackExchange" }
Q: MVVM light - how to access property in other view model I'm using mvvm light to build a Silverlight application. Is there a code snippet that shows how to access a view model's property or command from within another view model or user control's code behind? I guess it's simple, but I somehow missed something. Ueli A: You could use the Messenger to do this: Send the user in the UserViewModel: Messenger.Send<User>(userInstance); would just send the user to anyone interested. And register a recipient in your CardViewModel: Messenger.Register<User>(this, delegate(User curUser){_curUser = curUser;}); or you can also send a request from your CardViewModel for shouting the user: Messenger.Send<String, UserViewModel>("Gimme user"); And react on that in the UserViewModel: Messenger.Register<String>(this, delegate(String msg) { if(msg == "Gimme user") Messenger.Send<User>(userInstance); }); (You better use an enum and not a string in a real scenario :) ) Perhabs you can even response directly but I can't check it at the moment. Just check this out: Mvvm light Messenger A: Another way is to use the overload of RaisePropertyChanged that also broadcasts the change. You would do this: RaisePropertyChanged(() => MyProperty, oldValue, newValue, true); Then in the subscriber: Messenger.Default.Register<PropertyChangedMessage<T>>(this, Handler); where T is the type of MyProperty. Cheers Laurent
{ "pile_set_name": "StackExchange" }
Q: http://localhost:8000/broadcasting/auth 404 (Not Found) I am trying to make my app app connect to pusher on a private channel. But I am getting the following error: pusher.js?b3eb:593 POST http://localhost:8000/broadcasting/auth 404 (Not Found) What maybe the cause of the error and how to resolve it. A: Look in config/app.php if you have uncommented App\Providers\BroadcastServiceProvider::class, A: There are two Service Providers with Same name but different namespace in config/app.php Illuminate\Broadcasting\BroadcastServiceProvider::class, App\Providers\BroadcastServiceProvider::class, So uncomment both of them. It will work. A: Hope your base url is wrong try to hardcore your base url like below window.Echo = new Echo({ authEndpoint : 'http://*******/public/broadcasting/auth', broadcaster: 'pusher', key: '********', cluster: '***', encrypted: true });
{ "pile_set_name": "StackExchange" }
Q: Make a generic UITableViewCell Swift This is a broad question i know, and i basically ask this because i don't know how i would go about doing this. The task i have at hand is to make one generic tableViewCell that fit multiple purposes all at once and the layout of that cell will change accordingly to input. First of all, all cell must be able to have the following: A header, a body of text, a single image or multiple images, collection of data(displayed in UICollectionView inside UITableViewCell). The idea is that the user can create sections, these sections is of no type, so the task is to make the correct cell from this one generic UITableViewCell. And example could be. A user create two sections- 1.Section the user creates a header and a body and nothing more. 2. Section the user create a body and multiple images. For section 1 the cell would only need to consist of a header and a body and ignore the rest. For section 2, i would have a body and some images. How would you guys go about creating this behavior? I tried using storyboard with constraints, but even though i hide the header the UIElement is still present and the body which is beneath the header constraints are still attached to the UIElement in case of section 2 where there is no header the body should have constraints to the top of the cell instead. Please ask me to rephrase if this is to broad or the idea is not visualize clearly enough. A: Try to look on stackview. Or if you do not want to use it, I do a simple trick. Create one constraint to the top with priority 1. Add also one constraint for subtitle top to header bottom with priority 500. Create outlet for constraint with priority 1. Then whenever header title is set check if it is empty. If so set priority of constraint to 999 otherwise 1. It is okay to use it for one element but in case of multiple elements it is better to use stackview.
{ "pile_set_name": "StackExchange" }
Q: Bayesian belief network A child inherits a gene X with probability 50%. A disease will develop if child inherited gene from both parents. The disease will not develop if child got gene from just one of parents. Jain and Max have 0.25 probability of having that gene. They are parents of two children Mark and Eva. What is probability that Eva is healthy? What probability that Eva is healthy given Mark is healthy? A: Let's start with the first question. $$P(\text{Eva healthy}) = 1 - P(\text{Eva unhealthy})$$ Here we'll use law of total probability $$P(\text{Eva unhealthy}) = P(\text{Both parents pass gene onto Eva}|\text{Both parents have the gene}).P(\text{Both parents have the gene})$$ $$P(\text{Eva healthy}) =1- 0.5^{2}0.25^{2}=\frac{63}{64}$$ Now for the second question we have more information. The conditional will remain unchanged $$P(\text{Both parents pass gene onto Eva}|\text{Both parents have the gene}) = 0.5^{2}$$ However, now that we know that Mark is healthy, our belief of the parents having the gene decreases. So now, $$P(\text{Eva unhealthy}) = P(\text{Both parents pass gene onto Eva}|\text{Both parents have the gene}).P(\text{Both parents have the gene}|\text{Mark is healthy})$$ $$P(\text{Both parents have the gene}|\text{Mark is healthy}) = \frac{3*0.25^{2}*0.5^{2}}{3*0.25^{2}*0.5^{2} + 2*0.25*0.75 + 0.75^{2}}$$ $$P(\text{Both parents have the gene}|\text{Mark is healthy}) = \frac{1}{21}$$ Consequently, $$P(\text{Eva healthy}|\text{Mark healthy}) =1- 0.5^{2}\frac{1}{21}=\frac{83}{84}$$
{ "pile_set_name": "StackExchange" }
Q: Show that given function is identically zero Let $D \subset \mathbb{R}^{2}$ be and open and bounded set and $u \in C^{2}(D)\cup C^{0}(\overline{D})$ be a solution of $$ -\bigtriangleup u + u^{3} + uu_{x}^{3} + u_{y}^{2} = 0 $$ in D and $$u \equiv 0$$ in $\partial D$ Prove that u is identically 0 in $\overline{D}$. As a first attempt I used the divergence theorem: $$\int_{D}\bigtriangleup u =\int_{\partial D}<\bigtriangledown u, n>$$ where n is the normal vector. From this we have that $$ \int_{D} u^{3} + uu_{x}^{3} + u_{y}^{2} = 0 $$ because if $u(x) = 0, \forall x \in \partial D$ then $\bigtriangledown u$ must be $0$. I have absolutely no clue how to proceed from here with this question. Does anyone have any clues? A: To solve this explore the consequences of having a critical point inside the domain. The following observations are all you need: If $u\not\equiv 0$ then there has to be a critical point inside the domain where $\nabla u = 0$. At this point the PDE reads $\Delta u = u^3$. At a local maximum (minimum) we have $\Delta u \leq 0$ ($\Delta u \geq 0$). This kind of argument is similar to what is often used to prove maximum principles for certain PDEs. Another method that often works with PDEs involving the Laplacian is to multiply by $u$ and integrate over $D$ using integration by parts (instead of just integrating the PDE directly as you tried). This does not work on this PDE, however if the PDE was slightly different it would. For example if $-\Delta u + u^3 + uu_x^2 + u u_y^2 = 0$ then this would lead to $$\int_D (\nabla u)^2 + u^4 + (uu_x)^2 + (uu_y)^2{\rm d}x = 0$$ And since all the terms in the integrand is positive they each have to be identical to zero which gives you $u\equiv 0$. As I said this does not work here, but it's a very useful method to know about.
{ "pile_set_name": "StackExchange" }
Q: ionic2 - Photo Viewer not working .html <img *ngIf=new.Preview_image1 src="{{new.Preview_image1}}" (click)="zoomImage(new)"/> ionic document(ionic documentation) show me, src="path", but I get the data form my service, but if I use src="{{new.Preview_image1}}" error showing. .ts zoomImage(imageData) { this.photoViewer.show(imageData); } I try use this, but when I build it in my ios device when I click the image, loading only no responing. A: Change (click)="zoomImage(new)" to (click)="zoomImage(new.Preview_image1)". <img *ngIf=new.Preview_image1 [src]="new.Preview_image1" (click)="zoomImage(new.Preview_image1)"/>
{ "pile_set_name": "StackExchange" }
Q: On number of pairs of integers with lower bound on greatest common divisor Given $N\gg0$, small $\epsilon>0$ and $\alpha\in(\frac12,\frac34)$ how many pairs $$(a,b)\in[-N^{\alpha+\epsilon},N^{\alpha+\epsilon}]\times[-N^{\alpha+\epsilon},N^{\alpha+\epsilon}]$$ of integers of size $N^{\alpha+\epsilon}$ have $$gcd(|a|,|b|)>N^{1/3}?$$ Probability that $d|a$ and $d|b$ is $\frac1{d^2\zeta(2)}$ and so probability that every $d$ that divides $a$ and that divides $b$ is $\leq N^{1/3}$ is $$\int_{1}^{N^{1/3}}\frac1{x^2\zeta(2)}dx=\frac1{\zeta(2)}\Bigg(1-\frac1{N^{1/3}}\Bigg)$$ and so probability that there is at least one divisor $>N^{1/3}$ is $$1-\frac1{\zeta(2)}\Bigg(1-\frac1{N^{1/3}}\Bigg)=1-\frac6{\pi^2}+\frac1{\zeta(2)N^{1/3}}\underbrace{\approx}_{N\rightarrow\infty}0.3920728981459733713367232207\dots.$$ Is this correct estimation? A: No, your estimation is not correct. The integral you are computing is the probability that some $d \le N^{1/3}$ divides $a$ and $b$, since you are adding the probabilities for each $d \le N^{1/3}$. What we want is the probability that all $d$ which divide $a$ and $b$ are $\le N^{1/3}$. Conversely, we want no $d > N^{1/3}$ dividing $a$ and $b$, which means we will multiply the probabilities of each individual $d > N^{1/3}$ dividing $a$ and $b$. This means the probability we want is: $$ \prod_{d = N^{1/3}}^{N^{\alpha + \epsilon}} \left( 1 - \frac{1}{\zeta(2)d^2} \right) $$ Let this product be called $S$. Then: $$ \ln S = \sum_{d = N^{1/3}}^{N^{\alpha + \epsilon}} \ln \left( 1 - \frac{1}{\zeta(2)d^2} \right) $$ Since the function inside the sum is monotone increasing, it is asymptotically equal to: $$ \int_{N^{1/3}}^{N^{\alpha + \epsilon} + 1} \ln \left( 1 - \frac{1}{\zeta(2)x^2} \right) \mathrm{d}x $$ To make the formulas simpler, let $\beta = N^{\alpha + \epsilon} + 1$ and $\eta = N^{1/3}$. Then the integral above evaluates too: $$ \beta \ln \left( 1 - \frac{1}{\zeta(2)\beta^2} \right) - \eta \ln \left( 1 - \frac{1}{\zeta(2)\eta^2} \right) + \frac{2}{\sqrt{\zeta(2)}} \tanh^{-1}\left(\sqrt{\zeta(2)}\beta\right) - \frac{2}{\sqrt{\zeta(2)}} \tanh^{-1} \left(\sqrt{\zeta(2)} \eta \right) $$ This is asymptotically equal to $\ln S$, so $S$ is asymptotically: $$ \frac{\left(1 - \frac{1}{\zeta(2)\beta^2}\right)^\beta}{\left(1 - \frac{1}{\zeta(2)\eta^2}\right)^\eta} \cdot \left( \frac{1 - \zeta(2)\beta^2}{1 - \zeta(2)\eta^2} \right)^{1/\sqrt{\zeta(2)}} $$ This is (asymptotically) the probability that $gcd(a,b) \le N^{1/3}$. Therefore, the probability we actually want is one minus this. However, as $N \to \infty$, the above goes to $\infty$ (as far as I am able to determine), and so the probability that $gcd(a,b) > N^{1/3}$ appears to approach $0$.
{ "pile_set_name": "StackExchange" }
Q: How to use getIntent and startActivity in Fragment? The code like the following is in Activity , it will call setAppLocale function. After call the setAppLocale function , it will finish(); and restart by startActivity(intent); The code in Activity setAppLocale(mLocales[i]) ; Intent intent = getIntent() ; finish() ; startActivity(intent) ; And now , I want to do the same thing in Fragment by using the Button like the following code. And I have define Activity activity = getActivity(); in this Fragment. public void onClick(View v) { // TODO Auto-generated method stub MainActivity.setAppLocale(mLocales[1]); Intent intent = activity.getIntent(); activity.finish(); activity.startActivity(intent); } But it crash and the error log is like the following: D/AndroidRuntime(19694): Shutting down VM W/dalvikvm(19694): threadid=1: thread exiting with uncaught exception (group=0x416cc450) --------- beginning of /dev/log/system E/AndroidRuntime(19694): FATAL EXCEPTION: main E/AndroidRuntime(19694): java.lang.NullPointerException E/AndroidRuntime(19694): at tw.com.a_i_t.IPCamViewer.Control.LanguageSettings$3.onClick(LanguageSettings.java:85) E/AndroidRuntime(19694): at android.view.View.performClick(View.java:4147) E/AndroidRuntime(19694): at android.view.View$PerformClick.run(View.java:17161) E/AndroidRuntime(19694): at android.os.Handler.handleCallback(Handler.java:615) E/AndroidRuntime(19694): at android.os.Handler.dispatchMessage(Handler.java:92) E/AndroidRuntime(19694): at android.os.Looper.loop(Looper.java:213) E/AndroidRuntime(19694): at android.app.ActivityThread.main(ActivityThread.java:4786) E/AndroidRuntime(19694): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime(19694): at java.lang.reflect.Method.invoke(Method.java:511) E/AndroidRuntime(19694): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) E/AndroidRuntime(19694): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556) E/AndroidRuntime(19694): at dalvik.system.NativeStart.main(Native Method) W/ActivityManager( 568): Force finishing activity tw.com.a_i_t.IPCamViewer/.MainActivity The code at LanguageSettings.java:85 is Intent intent = activity.getIntent(); How to solve this problem? A: do this in onActivityCreated Activity activity = getActivity(); The reference to the activity is only available after the call of onActivityCreated so calling getActivity() after the call of this function will not return null.
{ "pile_set_name": "StackExchange" }
Q: SQL - fetch images with count likes, and count my likes on them I'm stuck in a query to fetch images, with count likes on them, but also my likes on each images, my actual query is : SELECT images.idimage, count( likes.idlike ) likes, count( likes2.idlike ) mylikes FROM images LEFT JOIN likes ON images.idimage = likes.idimage LEFT JOIN likes likes2 ON images.idimage = likes2.idimage AND likes2.iduser =3 GROUP BY images.idimage But it seems not working, column mylikes return me total likes of image, not only mine. Any help on that? Thanks A: You can do also this way SELECT images.idimage, count( * ), sum(case when iduser=3 then 1 else 0 end) as mylikes FROM images LEFT JOIN likes ON images.idimage = likes.idimage GROUP BY images.idimage
{ "pile_set_name": "StackExchange" }
Q: Variant of parabolic maximum principle: $\partial_t u\ge \Delta_x u + b\cdot\nabla_x u-u \;\Rightarrow\; u\ge e^{-t}\inf_y u(0,y)$ Let $b\colon[0,\infty)\times\Bbb R^d\to\Bbb R^d$ some smooth bounded function and $u\colon[0,\infty)\times\Bbb R^d\to\Bbb R$ a smooth function with $$ \partial_t u\ge \Delta_x u + b\cdot\nabla_x u-u. \label{1}\tag{1}$$ A paper I've been reading recently then quotes the maximum principle as $$ u(t,x)\ge e^{-t}\inf_{y\in\Bbb R^d}u(0,y) \quad \text{for all $(t,x)\in[0,\infty)\times\Bbb R^d$.} \label{2}\tag{2}$$ No reference is provided. I thought I was familiar with the parabolic maximum principle, but I have never seen this variant before. Can anyone give me a hint where I could find it in the literature? Would it need an additional growth condition on $u$? I'm a bit puzzled by the fact that \eqref{2} is similar to what Gronwall's inequality would imply if one omitted the terms in \eqref{1} with derivatives with respect to $x$. A: Note that it suffices to show the inequality on $[0, C] \times \mathbb R^d$ for any $C>0$. Part I: Changing $u$ to $w$: Write $U = \inf_y u(0,y)$ and let $w = u - e^{-t} U$. Then $\inf_y w(0,y) = 0$ and \begin{align} \partial_t w &= \partial_t u + e^{-t} U \\ &\ge \Delta u + b \cdot \nabla u - u + e^{-t} U \\ &= \Delta w + b \cdot \nabla w - w. \end{align} Thus we have $$\tag{3} \partial_t w \ge \Delta w + b \cdot \nabla w - w$$ and we need to show that $w\ge 0$ given $\inf_y w(0,y) = 0$ and (3). Part II: apply Parabolic Maximum Principle to $w$ (Heuristic): We argue by contradiction. Assume the contrary that $w<0$ somewhere. For the moment assume that the infimum $$\inf w = \inf_{(t, y) \in [0,C] \times \mathbb R^d} w (t, y)$$ is attained at some $(t_0, y_0)$. Then $t_0>0$ and thus we have at $(t_0, y_0)$, $$\tag{4} (\partial_t-\Delta) w \le 0, \ \ \nabla w=0.$$ Then (3) implies that $w(t_0, y_0)\ge 0$, which is a contradiction. Part III: Apply Non-compact Parabolic Maximum Principle: In general, due to the non-compactness of $\mathbb R^d$ such a point $(t_0, y_0)$ might not exist. There are several ways to deal with this. One of them is the Parabolic version of Omori-Yau maximum principle: Parabolic Omori Yau Maximum Principle: Let $w : [0, C]\times \mathbb R^d \to \mathbb R$ be a $C^2$ function so that $\inf_y w(0,y) = 0$, $\inf w <0$, and (Sublinear growth) $|w(t, y)|\le C o(|y|)$. Then there exists a sequence $(t_n, y_n)$ so that \begin{align} \lim_{n\to \infty} w(t_n, y_n) &=\inf w,\\ \tag{5}\lim_{n\to \infty} |\nabla w( t_n, y_n)|&= 0,\\ \limsup_{n\to \infty}\left(\partial_t - \Delta\right) w (t_n, y_n) &\le 0. \end{align} (5) should be compared to (4). Using the above Theorem (i.e. we assume that sublinear growth of $w$), we argue similarly as in part II. Assume the contrary that $\inf w<0$. Then the Theorem implies the existence of a sequence $(t_n, y_n)$ which satisfies (5). Plug $(t_n, y_n)$ into (3) and let $n\to \infty$ (boundedness of $b$ used), we obtain $\inf w \ge 0$, which is a contradiction. The Omori-Yau Maximum Principle is well known, in particular if you are working in Riemannian Geometry/Ricci-flow. One of the reference is this, which is in the context of Mean Curvature Flow. I will add more accessible references later. One could assume, instead of the sublinear growth condition, some bound on the $L^p$-norm of $u$ to obtain different version of non-compact Parabolic Maximum Principle (I will add more references later). Without any growth assumption, maximum principle is false even for heat equation: the classical nontrivial solution $T(t, y)$ to the heat equation constructed by Tychonov satisfies $T(0, y) = 0$ for all $y$, but $T$ attains some negative values for all $t\neq 0$.
{ "pile_set_name": "StackExchange" }
Q: Can NOT pass java int to jni function I have a simple jni function in test.cpp: #include <jni.h> #include <stdio.h> extern "C" { JNIEXPORT jint JNICALL Java_dri_put(JNIEnv* env, jstring js, jint ji){ printf("%d \n", ji); int t = ji; printf("%d \n", t); int k = -3412; return k; } } my java class javatest.java: public class javatest { public static void main(String args[]) { System.loadLibrary("test"); int t = 134; int k = dri.put("a", 5641); System.out.println(k); } } the output just prints some random number of the passing integer: 1075968840 1075968840 -3412 however if i change jint to jdouble and pass java double variable, it works fine, appreciate any help here. The dri java class is: public class dri { public final static native int put(String jarg1, int jarg2); } sizof(int) results in 4 bytes on my machine (red-hat) A: Your signature is incorrect (did you use javah?). The second argument to a JNI function will be the object (for object methods) or the class (for static class methods). Your declaration should look like this instead: JNIEXPORT jint JNICALL Java_dri_put(JNIEnv* env, jclass cls, jstring js, jint ji);
{ "pile_set_name": "StackExchange" }
Q: How to host more than 65536 services, each requiring a distinct port? I want to host web services (say a simple nodejs api service) There is a limitation on the number of services that I can host on a single host, since the number of ports available on a host is only 65536. I can think of having a virtual sub-network that is visible only within the host and then have a proxy server that sits on the host and routes the APIs to the appropriate web-service. Is it possible to do this with dockers - where each service is deployed in a container, a proxy server routing the APIs to the appropriate container? Is there any off the shelf solution for this (preferably free of cost). A: First of all, I doubt you can run 65536 processes per host, unless it's huge. Anyway, I would not recommend that because of availability and performance. Too many processes will be competing for the same resources, leading to a lot of context switches. That said, it's doable. If your services are HTTP you can use a reverse proxy, like nginx or traefik. If not, you can use HAProxy for TCP services. Traefik is a better option because it performs service discovery, so you won't need to configure the endpoints manually. In this setup the networking should be bridge, which is the default in Docker. Every container will have its own IP address, so you won't have any problem regarding port exhaustion.
{ "pile_set_name": "StackExchange" }
Q: Why do I get an email the next day? I already accepted an answer and upvoted it, yet I continue to get annoying emails a day or two later that say "1 Question Has 1 Answer"... no shit I already accepted it two days ago! Please make emails more aware. A: It seems to be slightly better now. I still wonder why sometimes I get notification emails and sometimes I don't, though.
{ "pile_set_name": "StackExchange" }
Q: C + WINAPI: How To handle Files? OK, I have read about CreateFile, ReadFile and WriteFile and I know how to use these. But I could not find any tutorial or guide with an example to use them properly. How do I handle files? I want to learn about: Read strings from file. Write strings to file. How does one do that? A: Here is an example: http://www.gamedev.net/page/resources/_/reference/programming/platform-specific/windows/file-io-in-visual-c-r707
{ "pile_set_name": "StackExchange" }
Q: How to do a Rapid Descent in a jet with inoperative spoilers? So, let us assume you are in a simulator for your favorite jet plane, and the instructor gives you a LOFT (Line-Oriented Flight Training) scenario that goes as follows: A normal takeoff and climb to cruise altitude, and perhaps thirty minutes of normal cruise flight The non-recoverable loss of speedbrake (flight spoiler) functionality due to a mechanical jam, or some other malfunction such as the loss of all SECs in a FBW Airbus. Another 30 minutes of time to deal with the first malfunction: run the checklists, plan and initiate a diversion if needed. You lose normal cabin pressure for some reason, and have to conduct a rapid descent to get back to 10,000' and complete your diversion. How do you execute the descent, considering that the rapid descent procedures for most jets rely on using the speedbrakes to achieve a high descent rate without overspeeding the aircraft? To use the 737 QRH checklist for Emergency Descent as an example: EMERGENCY DESCENT . . . . . . . . . . . . . . . . . . . . . .Announce The captain will advise the cabin crew, on the PA system, of impending rapid descent. The first officer will advise ATC and obtain the area altimeter setting. ENGINE START switches . . . . . . . . . . . . . . . . . . . . . . . . CONT THRUST levers . . . . . . . . . . . . . . . . . . . . . . . . . . . . CLOSE Reduce thrust to minimum or as needed for anti-ice. SPEED BRAKE . . . . . . . . . . . . . . . . . . . . . . . . . FLIGHT DETENT DESCENT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Initiate Target speed . . . . . . . . . . . . . . . . . . . . . . . . . . . Mmo/Vmo If structural integrity is in doubt, limit speed as much as possible and avoid high maneuvering loads. Level-off altitude . . . . . . . . . . . . . . . . . . . Lowest safe altitude or 10,000 feet, whichever is higher A: The answer is actually quite simple. FOLLOW THE MANUFACTURES PROCEDURES. In some aircraft (I don't have a 737 flight manual handy) there is an altitude limitation if the spoilers are inop for just this scenario. When the aircraft was certified, they needed to demonstrate an emergency descent (in the allowable time) without them, and that might not be possible from the certified ceiling. If that's the case in the 737, then descend to the max altitude with spoilers inop (assuming that you started above it). If there is no altitude limitation and no special spoiler-inoperative emergency descent procedure (I have never seen one of those, but there's nothing to say that a manufacturer couldn't have one) then you simply fly the regular procedure without spoilers. The manufacturer had to demonstrate this during certification and it must have been acceptable at the time. As rbp says, most of the time you fly Mmo/Vmo at idle power after you don the oxygen mask. IF the flight manual/checklist says that you can put the gear down (some do) then you may, but I wouldn't otherwise. I certainly wouldn't slow to gear speed (unless the manufacturer says to.... Unlikely in a jet like this) because you are decreasing the drag by slowing, and taking time at altitude to do so. A: Go to the top right corner of the envelope and stay there (point D in the sample below. Sorry, I don't have the 737 envelope at hand). Engines idle, speed and load factor as high as allowed. If airframe integrity is not critical, lower the gear to increase drag, but expect to lose the gear doors. A: Whenever trying to rapidly descend, you always want to think drag! Throttle to idle, lots of s-turns, (aileron drag), get down to gear speed, drop the gear, and lower flaps if practical. A limited crabbing-like manuever (intentional side-slipping) would greatly slow the aircraft as well! I'm sure that Terry will be here to recant us with a tale soon!
{ "pile_set_name": "StackExchange" }
Q: How to generate temporary operators with dynamic properties? During the development of an add-on I had to generate an operator based on the information in a dictionary. As I didn't find anything on that topic, I thought it might be useful to add my solution for others to use... This might come in useful, when you have a dictionary of data, a user needs to fill in, before some operator logic is executed, but you don't want to create an operator for every possible dictionary combination. A: As operators are not editable after creation, I achieved this by using a CollectionProperty with is hidden to the user. Instead, the temporary operator just shows the elements as single Properties of the type specified in the dictionary. The preset values for the Properties is taken from the dictionary, too. That way, we can create operators "on the fly", which are created in the function createOperator and discarded, when the next temporary operator is created. The Property type is handled in the calling operator by adding a type substring (such as 'b_' for boolean) to the name of the Property, which will show up in the GUI. Additional Properties could be added the same way. WARNING: It might be dangerous to use these operators with Blenders undo functionality. Therefore, I disabled it for these generic operators. Also, the usage of eval is dangerous in terms of security as written here. So make sure, your dictionary does not contain user input or digest the operatorName properly. I hope this is of use to anyone. Happy coding, Mr. Anderson! P.S.: New to the forum, so feedback is VERY appreciated! :) Just for reference: I took some inspiration from this question on dynamic operator generation and this old thread at blenderartists on generating dynamic properties in operators. Especially, this trick by sambler helped alot. Generating Blender operators in a function comes from an older Blender Dev entry. bl_info = { 'version': (1, 0), 'blender': (2, 79, 0), 'author': 'Mr. Anderson', 'name': 'Temporary Operator Showcase', 'location': 'blender', 'description': 'Creates operators when executing another operator, based on the contents of a dictionary.' , 'warning': 'This is a test only!', 'category': 'test', } import bpy custom_dict = { 'spoon': {'bent': True, 'dynamic': False}, 'smiths': {'amount': 55, 'angry': True}, 'matrix': {'greenness': 0.5, 'speed': 6.5} } class PropertyEntry(bpy.types.PropertyGroup): name = bpy.props.StringProperty() intProp = bpy.props.IntProperty() boolProp = bpy.props.BoolProperty() stringProp = bpy.props.StringProperty() floatProp = bpy.props.FloatProperty() def registerTempOperator(name): # check for previous temporary Operator and unregister it try: bpy.utils.unregister_class(TempOperator) except UnboundLocalError: pass blender_id_name = 'object.add_' + name # create the temporary operator class class TempOperator(bpy.types.Operator): """Temporary operator""" bl_idname = blender_id_name bl_label = 'Add a ' + name + ' object.' bl_description ='Adds a ' + name + ' object to the scene.' bl_options = {'REGISTER'} operator_data = bpy.props.CollectionProperty(type=PropertyEntry) operator_name = name def draw(self, context): layout = self.layout # expose all properties in the collection to the user for i in range(len(self.operator_data)): propname = self.operator_data[i].name[2:] # choose the right Property type depending on name identifier if self.operator_data[i].name[0] == 'i': layout.prop(self.operator_data[i], 'intProp', text=propname) elif self.operator_data[i].name[0] == 'b': layout.prop(self.operator_data[i], 'boolProp', text=propname) elif self.operator_data[i].name[0] == 's': layout.prop(self.operator_data[i], 'stringProp', text=propname) elif self.operator_data[i].name[0] == 'f': layout.prop(self.operator_data[i], 'floatProp', text=propname) def invoke(self, context, event): data = custom_dict[self.operator_name] for key in data.keys(): item = self.operator_data.add() prefix = '' if type(data[key]) is int: item.intProp = data[key] prefix = 'i' elif type(data[key]) is bool: item.boolProp = data[key] prefix = 'b' elif type(data[key]) is str: item.stringProp = data[key] prefix = 's' elif type(data[key]) is float: item.floatProp = data[key] prefix = 'f' # add the identifier to specify the data type item.name = prefix + '_' + key # show operator as popup window return context.window_manager.invoke_props_dialog(self) def execute(self, context): # TODO write the contents of operator_data somewhere here # or do something awesome print('Data is in here:') print(self.operator_data) print([i.name for i in self.operator_data]) return {'FINISHED'} # register the temporary class and return the operatorBlId bpy.utils.register_class(TempOperator) return blender_id_name def operatorList(self, context): items = [] for item in custom_dict: items.append((item,) * 3) return items class CallingOperator(bpy.types.Operator): """Operator which calls the temporary operator""" bl_idname = 'object.calling_operator' bl_label = 'Call operator' bl_description ='Call the temporary operators specified in custom_dict' bl_options = {'REGISTER'} op_list = bpy.props.EnumProperty(items=operatorList) def draw(self, context): layout = self.layout layout.prop(self, 'op_list', expand=True) def invoke(self, context, event): return context.window_manager.invoke_props_dialog(self) def execute(self, context): operator_name = registerTempOperator(self.op_list) # invoke the other operator, based on its bl_idname operator = eval('bpy.ops.' + operator_name + "('INVOKE_DEFAULT')") return {'FINISHED'} # just a basic panel to add the test operator to the 3D toolbar class TestPanel(bpy.types.Panel): """Contains the operator to test.""" bl_idname = "TOOLS_PT_TEST_TOOLS" bl_label = "TEST" bl_space_type = 'VIEW_3D' bl_region_type = 'TOOLS' bl_category = 'Tools' def draw(self, context): layout = self.layout layout.operator('object.calling_operator') def register(): bpy.utils.register_class(PropertyEntry) bpy.utils.register_class(CallingOperator) bpy.utils.register_class(TestPanel) def unregister(): bpy.utils.register_class(PropertyEntry) bpy.utils.register_class(CallingOperator) bpy.utils.unregister_class(TestPanel) if __name__ == '__main__': register()
{ "pile_set_name": "StackExchange" }
Q: How to call/bind a jquery datepicker to a label or div instead of an input field I'm working with the jqueryui datepicker on this page - http://jqueryui.com/demos/datepicker/ How do I call it on a label instead of an input field? Is this possible? A: I haven't looked at the code but I suspect that it assumes that it's attached to a <input type="text"> element. So assume that you must have that element. You can hide the <input> and interact with the datepicker via calls to its methods from your label events. $(labelselector).click(function() { $(inputselector).datepicker('show'); }); A: re: The positioning problem The above suggestions didn't work for me to get a clean ui. I have my datepicker control activated when people click a label, and I didn't want the textbox shown at all (the above css attempt was close, but still the textbox got focus amongst other issues). The solution for me was to make the textbox that the datepicker is attached to a < input type="hidden" .... /> This solved all the issues for me (I put the hidden input control just prior to the label so that the offset from the input control was right for my label). Notably, setting a normal input controls style to display: none, or visibility: hidden, etc. did not work. The reason this solution worked is due to the clauses in the source of the datepicker control that only perform certain functions if "type != "hidden". A: Are you trying to bind it so that it shows on click or so that the results populate a Label or Div? You could bind it to a hidden text box then bind your desired effects to the change() event of that hidden field. $(function() { $("#datepicker").datepicker(); $("#alternate").click(function() { $("#datepicker").focus(); }); $("#datepicker").change(function() { $("#alternate").html($("#datepicker").val()); }); }); <input id="datepicker" style="display:none" /><label id="alternate">change me</label> This worked fine for me in FireFox 3.5
{ "pile_set_name": "StackExchange" }
Q: Windows PowerShell Script to convert a folder of Word Docs to PDF So I already have the basic code to do this. i.e. convert a folder of word docs to pdf. # Acquire a list of DOCX files in a folder $Files=GET-CHILDITEM ‘C:\Users\Ashley\downloads\articles\*.DOC’ $Word=NEW-OBJECT –COMOBJECT WORD.APPLICATION Foreach ($File in $Files) { # open a Word document, filename from the directory $Doc=$Word.Documents.Open($File.fullname) # Swap out DOCX with PDF in the Filename $Name=($Doc.Fullname).replace(“doc”,”pdf”) # Save this File as a PDF in Word 2010/2013 $Doc.saveas([ref] $Name, [ref] 17) $Doc.close() } But as it stands if I have docx files. I need to re run the code replacing doc with docx. Is their any way I can make the replace function replace doc and docx for pdf? Thus eliminating the need to re run it twice? Thank you! A: This should help. Notice get-childitem looks for doc*, and the regex in the replace. $Files=GET-CHILDITEM 'C:\Users\Ashley\downloads\articles\*.DOC*' $Word=NEW-OBJECT –COMOBJECT WORD.APPLICATION Foreach ($File in $Files) { # open a Word document, filename from the directory $Doc=$Word.Documents.Open($File.fullname) # Swap out DOCX with PDF in the Filename $Name=$Doc.Fullname -replace('doc([x]{0,1})',"pdf") # Save this File as a PDF in Word 2010/2013 $Doc.saveas([ref] $Name, [ref] 17) $Doc.close() }
{ "pile_set_name": "StackExchange" }
Q: \setcounter{section} numbering not working Here is what I am working with: \documentclass{amsart} \newcounter{mysection} \let\realsection=\section \renewcommand\section[1]{\refstepcounter{mysection}% \subsection*{\themysection.\space #1} } \begin{document} \setcounter{section}{4} \section{} abc \setcounter{section}{7} \section{} def \end{document} However, the sections still display in proper numerical order, e.g. 1, 2, etc. instead of displaying 4 and then 7. A: Either follow Barbara Beeton's advice or patch the \centering command out of the definition (see amsart.cls) \documentclass{amsart} \usepackage{xpatch} \xpatchcmd{\section}{% \normalfont\scshape\centering}{% \normalfont\scshape}{\typeout{Success}}{\typeout{Failure}}% \begin{document} \setcounter{section}{4} \section{A section} abc \setcounter{section}{7} \section{Another text} def \end{document}
{ "pile_set_name": "StackExchange" }
Q: Is there a better way to change a UIBarButtonItem from Refresh to Stop in a UIWebView other than my implementation? The way I've been doing it for a few years is to simply create two toolbars, and set one or the other to hidden while the UIWebView loads. All of my toolbars and barbutton items are created in IB. I would like to make my implementation smaller if I can without this sort of "hack" I appreciate any help offered. Here is the code I'm using: #import "Web.h" @interface Web() @property (nonatomic, strong) IBOutlet UIWebView *webView; @property (nonatomic, strong) IBOutlet UIBarButtonItem *refreshButton; @property (nonatomic, strong) IBOutlet UIBarButtonItem *stopButton; @property (nonatomic, strong) IBOutlet UIBarButtonItem *backButtonRefreshToolbar; @property (nonatomic, strong) IBOutlet UIBarButtonItem *forwardButtonRefreshToolbar; @property (nonatomic, strong) IBOutlet UIBarButtonItem *backButtonStopToolbar; @property (nonatomic, strong) IBOutlet UIBarButtonItem *forwardButtonStopToolbar; @property (nonatomic, strong) IBOutlet UIToolbar *toolbarStop; @property (nonatomic, strong) IBOutlet UIToolbar *toolbarRefresh; @end @implementation Web - (void)webViewDidStartLoad:(UIWebView *)webView { [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; self.toolbarStop.hidden = NO; self.toolbarRefresh.hidden = YES; } - (void)webViewDidFinishLoad:(UIWebView *)webView { [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; self.toolbarStop.hidden = YES; self.toolbarRefresh.hidden = NO; [self actualizeButtons]; } - (void)actualizeButtons { self.backButtonRefreshToolbar.enabled = [self.webView canGoBack]; self.forwardButtonRefreshToolbar.enabled = [self.webView canGoForward]; self.backButtonStopToolbar.enabled = [self.webView canGoBack]; self.forwardButtonStopToolbar.enabled = [self.webView canGoForward]; } A: This is what I came up with based on the above help: @property (nonatomic, strong) IBOutlet UIToolbar *webToolbar; @property (nonatomic, strong) UIBarButtonItem *backButton; @property (nonatomic, strong) UIBarButtonItem *forwardButton; @property (nonatomic, strong) UIBarButtonItem *refreshButton; @property (nonatomic, strong) UIBarButtonItem *stopButton; @property (nonatomic, strong) UIBarButtonItem *flexibleItem; - (void)toolbarButtons { self.backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"UIButtonBarArrowLeft.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(goBack)]; self.forwardButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"UIButtonBarArrowRight.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(goForward)]; self.backButton.enabled = [self.webView canGoBack]; self.forwardButton.enabled = [self.webView canGoForward]; self.flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; self.refreshButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshWebView)]; self.refreshButton.style = UIBarButtonItemStyleBordered; self.stopButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemStop target:self action:@selector(stop)]; self.stopButton.style = UIBarButtonItemStyleBordered; if(self.webView.loading) { NSArray *items = [NSArray arrayWithObjects: self.backButton, self.forwardButton, self.flexibleItem, self.stopButton, nil]; [self.webToolbar setItems:items animated:NO]; } else { NSArray *items = [NSArray arrayWithObjects: self.backButton, self.forwardButton, self.flexibleItem, self.refreshButton, nil]; [self.webToolbar setItems:items animated:NO]; } }
{ "pile_set_name": "StackExchange" }
Q: What's the best way to sort function inputs based on type in Javascript? I've got a function with several inputs, which I would like to be optional in calling the function. Each input is of a different type, such as string, array, or number. With code like this: function doStuff(str, arr, num){ if typeof(str) != 'undefined' { $('#stringDiv').text(str)} if typeof(arr) != 'undefined' { for(var i=0; i < arr.length; i++){ $('<li>').text(arr[i]).appendTo('#arrayUl') } } if typeof(num) != 'undefined' { $('#numberDiv').text(num)} } jQuery(document).ready(function() { doStuff("i'm a string", [1,2,3,4,5], 7) }) I can account for the fact that my arguments might be optional, but not for the fact that, if I am missing arr, then my numeric argument (num) will come second, not third. To get around this, I can also dump my inputs into an array, and then sort through the array and look for this of each type, like I do in this fiddle. This seems sloppy, and, based on the number of libraries that I've seen that do this in their functions, it seems like there's probably a better way. Is there a better way to do this? Or is looping through arguments and hunting for types my best bet? A: You could leave off all parameters and use the arguments list to see what was passed. But, a better approach would be to create an object like this: { str: "i'm a string", arr: [1, 2, 3, 4], num: 3.14 } And then inspect the object for those keys: function doStuff(args): if ('str' in args) { $('#stringDiv').text(args.str); }
{ "pile_set_name": "StackExchange" }
Q: What type of IProducerConsumerCollection to use for my task? I have exactly 100 Sensors each "measuring" own data. I have exactly one DataSender which should send information from "sensors". The most recent information should be sent. Bandwidth of the channel may be less than data produced by 100 sensors. In this case some data can be skipped - but we should be "roughly fair". For example, we could skip every second measurement from each sensor. I don't know how often each sensor generates data, but in general they generate data pretty often. After my other posts: how to create singleton which always running in separate thread? Modified Producer/Consumer example, any problems with it? I have decided that I have classical Producer/Consumer problem, with: 100 Producers, and 1 Consumer I've been suggested to use BlockingCollection for this. The only problem with BlockingCollection - once you have added item, you cannot replace it. But in my application, if sensor produces a new value, and previous value was not processed by the Consumer, the value should be replaced. Should I use use a ConcurentDictionary or ConcurentBag for that task? Conceptually, all I need is an array of 100 elements. Sensor #33 should replace it's value into array[33]: | Sensor | Value | |--------|-------| | 1 | | | 2 | | | 3 | | /......../......./ | 32 | | | 33 | 101.9 | | 34 | | /......../......./ | 98 | | | 99 | | | 100 | | Consumer should take value from array[33] and if not null, then send it and set array[33] to null. Consumer should react on any not null values in array asap. A: I think you should implement your own IProducerConsumerCollection<T>. That's why it's an interface: so that you could easily make your own. You could do it using Dictionary<K,V> and Queue<T> to make sure receiving the data is fair, i.e. if you have just one device that produces data very fast, you won't send data just from this one. public class DeviceDataQueue<TDevice, TData> : IProducerConsumerCollection<Tuple<TDevice, TData>> { private readonly object m_lockObject = new object(); private readonly Dictionary<TDevice, TData> m_data = new Dictionary<TDevice, TData>(); private readonly Queue<TDevice> m_queue = new Queue<TDevice>(); //some obviously implemented methods elided, just make sure they are thread-safe public int Count { get { return m_queue.Count; } } public object SyncRoot { get { return m_lockObject; } } public bool IsSynchronized { get { return true; } } public bool TryAdd(Tuple<TDevice, TData> item) { var device = item.Item1; var data = item.Item2; lock (m_lockObject) { if (!m_data.ContainsKey(device)) m_queue.Enqueue(device); m_data[device] = data; } return true; } public bool TryTake(out Tuple<TDevice, TData> item) { lock (m_lockObject) { if (m_queue.Count == 0) { item = null; return false; } var device = m_queue.Dequeue(); var data = m_data[device]; m_data.Remove(device); item = Tuple.Create(device, data); return true; } } } When used along these lines: Queue = new BlockingCollection<Tuple<IDevice, Data>>( new DeviceDataQueue<IDevice, Data>()); Device1 = new Device(1, TimeSpan.FromSeconds(3), Queue); Device2 = new Device(2, TimeSpan.FromSeconds(5), Queue); while (true) { var tuple = Queue.Take(); var device = tuple.Item1; var data = tuple.Item2; Console.WriteLine("{0}: Device {1} produced data at {2}.", DateTime.Now, device.Id, data.Created); Thread.Sleep(TimeSpan.FromSeconds(2)); } it produces the following output: 30.4.2011 20:40:43: Device 1 produced data at 30.4.2011 20:40:43. 30.4.2011 20:40:45: Device 2 produced data at 30.4.2011 20:40:44. 30.4.2011 20:40:47: Device 1 produced data at 30.4.2011 20:40:47. 30.4.2011 20:40:49: Device 2 produced data at 30.4.2011 20:40:49. 30.4.2011 20:40:51: Device 1 produced data at 30.4.2011 20:40:51. 30.4.2011 20:40:54: Device 2 produced data at 30.4.2011 20:40:54.
{ "pile_set_name": "StackExchange" }
Q: c# string char 0x85 (ellipsis?) my c# program receives string data (via windows message queue) which sometimes includes a char-133 in a string. Is this a valid value in c#? For example, if I do this: string x = "a" + (char)133 + "b"; // 133 = 0x85 I can see the string x has length 3, but in the Visual Studio debugger I can only see x = "ab". If I do the following, I get the "ellipsis" character (which I think the 133 is also supposed to be from the program which delivers it): string y = "a" + (char)8230 + "b"; // 8230 = 0x2026 Thanks for any pointers. A: in a string there is no "invalid" value for a char. There are "invalid Unicode code points", but a string can contain them without problems, because string is a "stupid container" (but note that some string methods are "more intelligent" and don't like very much invalid code points... Normally they skip them/replace them with some substitution character) Now... "visualizers" (modules/functions/methods that have to "show" a string) often have limitations and can't show all the characters (even perfectly valid ones)... A classsical example is Zalgo and Zalgo. This is your problem, but this is another problem :-) To make an example, in Windows there are at least 4 "official" API to write text to the screen: GDI, GDI+, Uniscribe, DirectWrite. And many programs (games primarily) then use the FreeType library as an alternative... Each one of these libraries is compatible with some parts of Unicode. I'll add that the character that creates problems to you (0x85) is called NEL or Next Line. It is a control character, so not something that should be "shown" and it has a complex and funny story, that could explain why it is sometimes shown as ellipsis: the code for NEL has been used as the ellipsis ('…') character in Windows-1252. For instance: YAML[8] no longer recognizes them as special, in order to be compatible with JSON. ECMAScript[9] accepts LS and PS as line breaks, but considers U+0085 (NEL) white space, not a line break. Microsoft Windows 2000 does not treat any of NEL, LS or PS as line-break in the default text editor Notepad On Linux, a popular editor, gedit, treats LS and PS as newlines but does not for NEL.
{ "pile_set_name": "StackExchange" }
Q: Is there a good data structure that performs find, union, and de-union? I am looking for a data structure that can support union, find, and de-union fairly efficiently (everything at least O(log n) or better) as a standard disjoint set structure doesn't support de-unioning. As a background, I am writing a Go AI with MCTS [http://en.wikipedia.org/wiki/Monte_Carlo_tree_search], and this would be used in keeping track of groups of stones as they connect and are disconnected during backtracking. I think this might make it easier as de-union is not on some arbitrary object in the set, but is always an "undo" of the latest union. I have read through the following paper and, while I could do the proposed data structure, it seems a bit over kill and would take a while to implement http://docs.lib.purdue.edu/cgi/viewcontent.cgi?article=1773&context=cstech While O( a(n)) would be great, of course, I'm pretty sure path compression won't work with de-union, and I'd be happy with O(log n). My gut tells me a solution might be heap related, but I haven't been able to figure anything out. A: What you're describing is sometimes called the union-find-split problem, but most modern data structures for it (or at least, the ones that I know of) usually view this problem differently. Think about every element as being a node in a forest. You then want to be able to maintain the forest under the operations link(x, y), which adds the edge (x, y), find(x), which returns a representative node for the tree containing x, and cut(x, y), which cuts the edge from x to y. These data structures are often called dynamic trees or link-cut trees. To the best of my knowledge, there are no efficient data structures that match the implementation simplicity of the standard union-find data structure. Two data structures that might be helpful for your case are the link/cut tree (also called the Sleator-Tarjan tree or ST-tree) and the Euler-tour tree (also called the ET-tree), both of which can perform all of the above operations in time O(log n) each. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: Using arrays inside a custom data object (WPF C#) Assume I have a custom data object names MyDataObject, defined as such: public class MyDataObject { public string Caption { get; set; } public int inx { get; set; } public string[] inputArr = new string[6]; } I now can add MyDataObject to a list of objects. As shown below: public void PopuList() { var items = new ObservableCollection<MyDataObject>(); items.Add(new MyDataObject() { Caption = "foo", Checked = false, inx = 0 }); listBox.ItemsSource = items; } The problem I am having is that I cannot seem to add an array (inputArr as seen in the code above) to MyDataObject. inputArr is to have a length of 6, of which will be customized for each item. Some elements will be left blank. My attempt at getting arrays to add to the MyDataObject is as follows: items.Add(new MyDataObject() { Caption = "foo", Checked = false, inx = 0, inputArr[0] = "bar" }); For some reason this gives me an error across the entire inputArr[0] = "bar". The error states The name inputArr does not exist in the current context. I have also tried items.Add(new MyDataObject() { Caption = "foo", Checked = false, inx = 0, inputArr = { "a","b","c","d","e","f" } }); This however gives me an error on each of the six strings. The error is: string[] does not contain a definition for 'add' Any clues on adding arrays to custom data objects? A: You can use an array initializer: items.Add(new MyDataObject() { Caption = "foo", Checked = false, inx = 0, inputArr = new [] { "a","b","c","d","e","f" } }); Note In the definition of MyDataObject, I don't see a property whose name is Checked. If this isn't a property of MyDataObject, you have to remove it from the above object initializer.
{ "pile_set_name": "StackExchange" }
Q: Repeating threads with loops vs repeating runnable with scheduleAtFixedRate() final Runnable refresh = new Refresh(params...); service = Executors.newScheduledThreadPool(1); service.scheduleAtFixedRate(refresh, 0, 2000, TimeUnit.MILLISECONDS); // OR final Thread refresh = new Refresh(params...); refresh.start(); // In the run() method there is a loop with a sleep of 2000 ms Which of the above methods to repeat a piece of code are preferred and why? A: It is functionally equivalent but the former is more flexible and better separate responsibilities (SRP): a task should not be responsible for how or when it's run...
{ "pile_set_name": "StackExchange" }
Q: Can the Senate block House Subpoenas? Does the Senate have the ability to block a subpoena submitted by the house of representatives? A: No. A congressional subpoena is issued by the House of Representatives or the Senate on its own authority (for example, a recent subpoena (pdf)): SUBPOENA By Authority of the House of Representatives of the Congress of the United States of America To ... The subpoena could be challenged in court by someone with standing to do so. This would normally be the person to whom the subpoena is addressed. Neither the senate nor any senator would be likely to have standing.
{ "pile_set_name": "StackExchange" }
Q: RedBeanPHP - нет соединения с БД Оба сайта на одном лок. хостинге - на одном RedBeanPHP соед. с БД, а на другом - нет - выдает ошибку: http://joxi.ru/v294gWxf3ngZpm.jpg В чем, кроме путей, может быть причина?? A: Как ни странно, в сообщении об ошибке про БД не сказано ровным счетом ничего. Оно у вас гласит Fatal Error: Cannot redeclare class ReadBeanPHP\RedException Что в переводе на русский обозначениет, что пхп не может повторно определить класс RedException, поскольку он уже был определен ранее. Из стека видно, что используются конструкции include и require, из чего следует, что файл, в котором определен данный класс исключений, подключается как минимум два раза. Дабы избежать подобной сиутации, используйте include_once и require_once.
{ "pile_set_name": "StackExchange" }
Q: get_template_part() isn't loading author information Using get_template_part() I parted some of my theme's common post templates. My post template is content-general.php. Without parting thing is going fine. But just after parting the template — using WP_DEBUG, true — I discovered it's showing some errors in loading author information: Notice: Undefined variable: authordata Along with: Notice: Trying to get property of non-object I have the following code, where I have $authordata: <a class="url fn n" href="<?php echo get_author_posts_url( false, $authordata->ID, $authordata->user_nicename ); ?>" title="<?php printf( __( 'View all posts by %s', 'your-theme' ), $authordata->display_name ); ?>"> <?php the_author(); ?> </a> I followed this WPSE thread and tried globalizing $post inside the template file (content-general.php) like: <?php global $post; ?> and the template is called within a default WordPress loop. But the problem is not solved. A: With this answer with good practices, by Chip Bennett, in mind just do a simple global thing — add global $authordata to your template file: <?php global $authordata; ?> Follow the Codex's Global Variables article for details about the global practice. Quoting the portion specific to the Question: $authordata (object) Returns an object with information about the author, set alongside the last $post.
{ "pile_set_name": "StackExchange" }
Q: Is right this chromatic polynomial for this Bridge Graph? I have the following graph: Bridge Graph with N = 8 And I need to find its chromatic polynomial. Based in my notes, I have reached the following result: $$Pg(x) = \frac{((x-1)^4 + (x-1))^2}{x(x-1)} $$. It is because I have applied this formula: $$Pg(x) = \frac{Pg1(x) Pg2(x)}{Pkr(x)} $$. Taking the Bridge Graph and the previous formula, I have replaced with: $$ Pg1(x) = Pg2(x) = Pc4(x)= (x-1)^4+(x-1) $$ Because both sub-graphs are cycles. On the other hand, the Pkr(x) in this case is equals to Pk2(x). So, the chromatic polynomial for a complete graph with n = 2, could be expressed as : $$x(x-1)$$ So, my main doubt is if this reasoning is right. Because I'm not sure about my resolution and I think that Ia have missing something in the final response. Thanks a lot! A: The formula $$ P_G(x) = \frac{P_{G_1}(x) \cdot P_{G_2}(x)}{P_{K_r}(x)} $$ that you are using is appropriate when $G$ is the clique sum of the graphs $G_1$ and $G_2$ along a copy of $K_r$. The graph you give, is not a clique sum of two cycles. Instead, it is a clique sum (along a $K_2$) of the graph induced by vertices $\{a,b,c,d,e\}$ and the graph induced by vertices $\{d,e,f,g,h\}$. Both of these are not cycles, but cycles with an extra leaf vertex. Here is how we deal with that extra vertex. If the cycle has chromatic number $(x-1)^4+(x-1)$, then there are always $x-1$ ways to color the leaf vertex with a color different from its only neighbor, so in this case we have $P_{G_1}(x) = P_{G_2}(x) = (x-1)^5 + (x-1)^2$. Applying the formula, we get $$ P_G(x) = \frac{[(x-1)^5 + (x-1)^2]^2}{x(x-1)} = x^8-9 x^7+36 x^6-82 x^5+114 x^4-96 x^3+45 x^2-9 x. $$ (A quick sanity check which this result passes and yours does not is that the degree of $P_G(x)$ must be the number of vertices in $G$.)
{ "pile_set_name": "StackExchange" }
Q: Are there reactions where the stirring direction would make a difference? I'm not a chemist. I don't really do anything with chemistry, so I know little of the subject. I know a bit about chiral molecules. For example, I know that homochirality can affect light polarity. I'm just curious: Are there chemical reactions where the direction of the stirring (clockwise vs. anti-clockwise) would make a difference? A simple explanation would be appreciated. A: No, for three reasons: Firstly, you need a relatively large molecule and/or a high viscosity and/or a strong shear/extensional flow, before the molecule even notices that it´s in a nonuniform environment. The molecule, if it has an elongated form, will then align perpendicular to the normal vector of that flow field. That only occurs for sufficiently concentrated solutions of polymers, or liquid crystals. Secondly, you need three vectors to be able to differentiate a left and right hand. You only have the normal vector of the flow field, and the preferred direction of your molecule. Or in other words, your reaction will be indifferent to you watching it from the top of the beaker or through the bottom. ;) Thirdly, to get a third vector into your system, you need the normal of the flow field to change significantly, in a specific direction (using, say, a propellor instead of a stirring bar), on the lenght scale of your molecules. That is impossible with a macroscopic stirrer. A: In short: if the direction of stirring were a both reproducible and highly significant parameter for the synthesis of chiral molecules, the manufacturers would offer a back- and forward direction of stirring by default all across their stirrers. But no, I'm not aware that there is such an effect. Note, however, beside the stirring plate in the (small scale) lab driving a magnet in the beaker (reference) larger scale mixing uses overhead mixers. These look similar to a drilling machine and a replaceable, axle-mounted propeller: (reference) These occasionally have the option to alter the direction of stirring, but only because the mounting of the stirring blades may be chiral, screw-like (examples). Side note: At best of my knowledge, there isn't a significant and reproducible influence of the geographic position (latitude), either. Thus, the synthesis of and with chiral molecules is independent if performed in Boston (northern hemisphere), Perth (southern hemisphere), or Quito (almost equatorial). A: These two intriguing papers conclude chiral environments can be induced by directional stirring, where the direction of the chirality depends on the direction of stirring. And other work has shown that chiral environments steer the direction of chiral synthesis.* So: If [direction of stirring] -> [direction of chirality of environment] -> [direction of chirality of synthesis], then the direction of stirring could affect chiral synthesis. https://chemistry-europe.onlinelibrary.wiley.com/doi/full/10.1002/cphc.201200003 "Recently, several reports have suggested that the vortex flow of a solution of an achiral molecule gives rise to a CD signal, which is dependent on the stirring direction. This article introduces types of molecular architecture and material designs that show stir‐induced chirality....Supramolecular assemblies can be deformed to a chiral structure in a vortex flow which shows a CD signal even if the assemblies are achiral. ...Recently, we have shown that the stirring‐induced chirality caused by the host can be transferred to an achiral guest alignment. If such a transfer of chiral information could be realized on a molecular level from the vortex flow through a supramolecular aggregate to individual molecules, the consequences will be useful to a broad field in science and industry."[1] [1] Okano, Kunihiko, and Takashi Yamashita. "Formation of chiral environments by a mechanical induced vortex flow." ChemPhysChem 13.9 (2012): 2263-2271. https://chemistry-europe.onlinelibrary.wiley.com/doi/full/10.1002/chem.201100713 "This article introduces types of molecular architecture and material designs that show stir‐induced chirality.....Here we report that a solution of an achiral cationic gelator can vicariously transfer the macroscopic chirality of the vortex stirring towards an achiral molecule (in fact, a molecule showing racemic conformations)." [2] [2] Okano, Kunihiko, et al. "Emergence of chiral environments by effect of flows: The case of an ionic oligomer and Congo red dye." Chemistry–A European Journal 17.34 (2011): 9288-9292. *See for instance the following, which shows an example of how a chiral environment, created by a chiral solvent, "steers chiral synthesis": https://cen.acs.org/synthesis/catalysis/Solvent-steers-chiral-synthesis/97/web/2019/07
{ "pile_set_name": "StackExchange" }
Q: How to get the current heap size that an android application is using? I found that it can be easily done using java from this answer but couldn't find yet how to do it if my applicating is written using C#.NET and xamarin libraries. How to get those same datas (current heap size, maximum heap size) using this framework? Thanks in advance. A: I suppose you are looking for something like this: long memory = GC.GetTotalMemory(true); It retrieves the number of bytes currently thought to be allocated. There is also another option: Process currentProc = Process.GetCurrentProcess(); long memoryUsed = currentProc.PrivateMemorySize64; You determine memory usage by reading the PrivateMemorySize64 property. You need using System.Diagnostics; reference to support this action.
{ "pile_set_name": "StackExchange" }
Q: Can a sequential always block be triggered by a short pulse from a combi block Could a sequential always block be triggered by a short lived pulse coming from a combi block ? I have tried to trigger the always block, by assigning a value and set the value back to 0 in an attempt to trigger the sequential always block but to no avail, below is the pseudo code always_comb begin ...some code... pulse_trigger = 1; load_var= driver_var // assigning some values pulse_trigger = 0; ...some code... end always @(pulse_trigger)begin ...some code part 2... end I expect by assigning 1 to pulse_trigger the "always@(pulse_trigger)" block to get activated, but in my VCS simulation this does not seem to be the case. Maybe this is because the pulse trigger is assigned 1 and unassigned 1 in the same combi block, which takes 0 simulation time, so pulse_trigger might not appear to have changed values. Or this method should've triggered "always@(pulse_trigger)" and executed "...some code part 2..", because I am looking at the wrong values ? A: In verilog simulation only a single always block can be evaluated at a time. So, until your always_comb finishes, no other always block can be evaluated. Therefore, no pulse_trigger change will be detected by simulation (because all changes happen inside a single always block. You can do something like that by adding delays (assuming this is not a synthesizable code): always @* begin pulse_trigger = 1; load_var= driver_var // assigning some values #1 // << this will stop execution of the block for 1 time unit and allow others. pulse_trigger = 0; end However, the above code is not synthesizable but it can be a part of a test bench. Also, it is not allowed within always_comb.
{ "pile_set_name": "StackExchange" }
Q: WcfFacility missing I am looking for the WcfFacility which is supposed to be in Castle.Facilities.WcfIntegration. Have things changed? Where is it? I have the latest castle (version 3.1). The question is related to this link: castle wcf integration A: I assume you're asking where is it in the package you download? It's there. Or do you mean the nuget package
{ "pile_set_name": "StackExchange" }
Q: Asynchronous coding - waiting for all returns - performance I have code similar to the following pseudo code: static int counter; function GetCalculations() { for (x service calls) { service.BeginCalc(MyCallback); Interlocked.Increment(counter); } while(counter > 0) { //Wait for all results to return } return; } static function MyCallback() { try { ... process results } finally { Interlocked.Decrement(counter); } } My question is in relation to the wait in the above code (the while (counter > 0)). Is this going to be a performance issue? I know that the multiple calls that I am making (to remote web services) take at least a few seconds to return - would I be better introducing something like a Thread.Sleep() in the while loop so that I am only checking for all returned every quarter second or so? My gut instinct is that putting thread sleeps into my code smells a bit, but I'm just not well enough versed in this kind of code to say one way or the other. A: You could use task parallel library. It has easy to use mechanisms to wait on Tasks Below is an example from MSDN Task[] tasks = new Task[3] { Task.Factory.StartNew(() => MethodA()), Task.Factory.StartNew(() => MethodB()), Task.Factory.StartNew(() => MethodC()) }; //Block until all tasks complete. Task.WaitAll(tasks);
{ "pile_set_name": "StackExchange" }
Q: Динамическое создание и завершение потоков К, примеру, есть код: import threading from time import sleep class MyThread(threading.Thread): def __init__(self, key): super(MyThread, self).__init__() self.daemon = True self.key = key self.start() def run(self): while True: print('thread', self.key) sleep(1.5) threads = dict() def add_thread(key): key = int(key) if threads.get(key) is None: threads[key] = MyThread(key) def del_thread(key): key = int(key) if threads.get(key) is not None: thread = threads.pop(key, None) if thread is not None: # тут, что-то, что освободит поток print('остановка', key) i = 0 while True: add_thread(i) i += 1 if i >= 10: del_thread(i - 10) sleep(1) Код динамически добавляем потоки, но так же нужно динамически их и останавливать, как это сделать в данном примере? A: Замените while True: на while not self.stopped.wait(1.5):.. (уберите time.sleep(1.5)), где self.stopped = threading.Event(), тогда чтобы остановить поток, вызовите thread.stopped.set() (поток выйдет на wait() вызове, не дожидаясь пока 1.5 секунды закончатся). Код в вопросе можно упростить: чтобы запускать новый поток каждую секунду и останавливать его через десять итераций: #!/usr/bin/env python3 import collections import logging import time import threading def worker(stopped): while not stopped.wait(1.5): logging.info("heartbeat") logging.basicConfig(level=logging.INFO, format="%(relativeCreated)d %(threadName)s %(message)s") events = collections.deque(maxlen=10) while True: events.append(threading.Event()) threading.Thread(target=worker, args=[events[-1]], daemon=True).start() if len(events) == 10: events.popleft().set() # stop 10th thread from the end time.sleep(1 - time.monotonic() % 1) # every second Подробнее об этом time.sleep() вызове см. Как правильно сделать временный цикл?
{ "pile_set_name": "StackExchange" }
Q: How to build a VS2015 solution that has a VS2010 configuration using MSBuild? I want to build a Visual Studio 2015 C++ solution from the command line using MSBuild. The complication is that I want to build a particular configuration of the solution, which uses the Visual Studio 2010 toolset (necessary because I am linking to a 3rd party library). I have used MSBuild successfully in the past, but am unsure of which versions of MSBuild and vcvarsall.bat to use in this case. Currently I am running: "\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" "\Program Files (x86)\MSBuild\14.0\Bin\MSBuild" mysolution2015.sln /p:Configuration="2010_Config" /p:useenv=true but that gives error: LINK : fatal error LNK1117: syntax error in option 'manifest:embed' Any help would be appreciated. A: You should be using the vcvarsall.bat from VS2015 ("\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat") The chosen configuration will select the appropriate toolset (assuming you have both VS2015 and VS2010 installed). You can then simply use msbuild has it will have been added to the path...
{ "pile_set_name": "StackExchange" }