source
stringclasses
1 value
task_type
stringclasses
1 value
in_source_id
stringlengths
1
8
prompt
stringlengths
209
40.4k
gold_standard_solution
stringlengths
0
56.7k
verification_info
stringclasses
1 value
metadata
stringlengths
138
225
problem_id
stringlengths
9
10
stackexchange
llm_judgeable_groundtruth_similarity
47697139
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: #include<stdio.h>int main(){ switch(*(1+"AB" "CD"+1)) { case 'A':printf("A is here"); break; case 'B':printf("B is here"); break; case 'C':printf("C is here"); break; case 'D':printf("D is here"); break; }} The output is: C is here. Can anyone explain this to me its confusing me. Now provide the response and nothing else.
First of all, string literals only separated by white-space (and comments) are concatenated into single strings. This happens before expression parsing (see e.g. this translation phase reference for more information). This means that the expression *(1+"AB" "CD"+1) is really parsed as *(1+"ABCD"+1) . The second thing to remember is that string literals like "ABCD" are really read-only arrays , and as such one can use normal array-indexing with them, or letting them decay to pointers to their first element. The third thing is that for any array or pointer p and index i , the expression *(p + i) is equal to p[i] . That means *(1+"ABCD"+1) (which is really the same as *("ABCD"+2) ) is the same as "ABCD"[2] . Which gives you the third character in the string. And the third character in the string is 'C' .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47697139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8667423/']}
jdg_71541
stackexchange
llm_judgeable_groundtruth_similarity
593331
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Classical mechanics is famous for its supposed ability to theoretically calculate the state of a system at any given time provided all the necessary initial conditions. I believe this is the definition of determinism. But a simple system if 3 particles interacting gravitationally fails to admit such a description.Some people use the arguments that one can still determine the state up to a certain time for any given system, however this is only an approximate prediction leaving even in this limited time window some uncertainty about the system. EDIT : This is purely a methematical physics question. Can you formally prove classical mechanics is deterministic from classical mechanics. It's not a question about the universe but about the theory.. Now provide the response and nothing else.
But a simple system if 3 particles interacting gravitationally fails to admit such a description. No it doesn't. Given some set of initial conditions, the gravitational three-body problem can be solved for any time you like, to whatever degree of precision you like. It's true that the result can't be expressed in a neatly-packaged "closed form," but that's more a statement about how we write formulas down than it is a statement about the behavior of the system. More interesting is the fact that the gravitational three-body problem is generically chaotic, meaning (among other things) that nearby initial conditions diverge from each other exponentially. From a practical point of view, this limits how far in the future we can reliably predict the motion of an observed three-body system. Because our measurements have finite resolution, we can't precisely pin down the true initial state of the system, and two initial conditions which are both compatible with our measurements will eventually evolve to completely different final states. Even if exact measurement of initial conditions were possible, our calculations necessarily have finite precision, which would give us the same problem. However, this is not the same as non-deterministic evolution. Given exact initial conditions, the evolution of a chaotic system is completely deterministic - it's just that if the model is based on real-world observations, those predictions quickly become relatively meaningless because of uncertainty in the initial conditions and finite numerical precision.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/593331', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/225180/']}
jdg_71542
stackexchange
llm_judgeable_groundtruth_similarity
1052445
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The definition of a homomorphism $f$ from $G$ to $H$, given by Pinter, says that: If $G$ and $H$ are groups, a homomorphism from $G$ to $H$ is a function $f: G \rightarrow H$ such that for any two elements $a,b \in G$, $f(ab)=f(a)f(b)$. If there exists a homomorphism from $G$ onto $H$, we say that $H$ is a homomorphic image of $G$. So, I am wondering, is a homomorphism onto, or one-to-one? An explanation would be appreciated. It seems to me, that a homomorphism should be just one-to-one. Now provide the response and nothing else.
A homomorphism $f:G\to H$ need be neither 1-1 nor onto. It need merely satisfy the requirement that $f(ab)=f(a)f(b)$. Note that the product $ab$ is the product in the domain $G$, while the product $f(a)f(b)$ is the product in the range $H$. One always has that $f(G)\subset H$. If it is 1-1, it is called a monomorphism. If it is onto, it is called an epimorphism. This means $f(G)=H$. If it is both 1-1 and onto, it is called an isomorphism.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1052445', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/186378/']}
jdg_71543
stackexchange
llm_judgeable_groundtruth_similarity
3049834
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have 2 activities. In child activity i have put something like that in onPause(): if (isFinishing()) { final Intent intent = new Intent(); intent.putExtra(SOME_DATA, value); setResult(RESULT_OK, intent); Log.i("test", "Result set to RESULT_OK");} In parent activity i check resultCode when child activity is destroyed, and this is what i have noticed: If i destroy child activity by some action (in some condition i invoke finish()), then resultCode is RESULT_OK But when i destroy by pressing return key (i works only in emulator so its ESC) who kills activity, then resultCode read in parent onActivityResult method equals 0 (RESULT_CANCELD). "test" log read in each case is the same. Now provide the response and nothing else.
public string GetPath<T>(Expression<Func<T, object>> expr){ var stack = new Stack<string>(); MemberExpression me; switch (expr.Body.NodeType) { case ExpressionType.Convert: case ExpressionType.ConvertChecked: var ue = expr.Body as UnaryExpression; me = ((ue != null) ? ue.Operand : null) as MemberExpression; break; default: me = expr.Body as MemberExpression; break; } while (me != null) { stack.Push(me.Member.Name); me = me.Expression as MemberExpression; } return string.Join(".", stack.ToArray());}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3049834', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/367786/']}
jdg_71544
stackexchange
llm_judgeable_groundtruth_similarity
6943
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to create a new display type, especially for numbers or text, but potentially for arbitrary objects as well. I want a "drag box" where not all of the number (object) is visible, but dragging left and right on the object itself slides it left and right (or in a generalized form both x and y). No scroll bars should be visible, and it should be tightly integrated much like Framed so that it can be used in different places without difficulty. In Chat Szabolcs showed how to get the basic functionality. However, there are problems with this implementation as he notes: the N[Pi,100] shouldn't be recalculated constantly ... Dynamic doesn't work inside the ScrollPosition setting ... when the mouse leaves the region, it stops working, and for good usability it shouldn't I don't observe #3 on my system (Win7/mma7) but I do note another problem: Dragging the text left (looking at the least significant digits) it is possible to drag the object completely out of frame. Dragging it right does not move it out of frame but causes a memory of the drag such that it appears "stuck" when you start dragging left, though it eventually moves. How can this function be implemented most efficiently and flexibly? Can it be made to work inside a Text object the way Frame does? Now provide the response and nothing else.
Here's a more robust version of Rojo's answer: BeginPackage["DragPane`"];DragPane::usage = "implements a draggable Pane";BeginPackage["`Package`"];DragPaneDynamicModule::usage = "the dynamic module used by DragPane";EndPackage[];Begin["`Private`"];Options[DragPaneDynamicModule] = Join[ Options[Pane], { AutoAction -> False } ];DragPaneDynamicModule[ exp_, {width_, height_}, ops : OptionsPattern[] ] := With[ { boxSize = {#[[1]], 3 + Total@#[[2 ;;]]} &@First@ FrontEndExecute@ GetBoundingBoxSizePacket[ Cell[BoxData[ToBoxes[exp]], "Output", PageWidth -> \[Infinity], ShowCellBracket -> False, CellMargins -> {{0, 0}, {0, 0}} ] ] }, DynamicModule[ { scrollX = 0., scrollY = 0., maxWidth = If[! NumericQ@width, boxSize[[1]], Max@{boxSize[[1]], width} ], boxWidth = If[! NumericQ@width, Min@{boxSize[[1]], 360} , width], maxHeight = If[! NumericQ@height, boxSize[[2]], Max@{boxSize[[2]], height} ], boxHeight = If[! NumericQ@height, Min@{boxSize[[2]], 360} , height], setXScroll, setYScroll, getXScroll, getYScroll, scrolling = False, refWidth, refX, refHeight, refY }, Pane[ EventHandler[ Pane[ Pane[exp, 2*boxSize, Alignment -> {Left, Top}], Full, ScrollPosition :> Dynamic[ If[ TrueQ[scrolling], { setXScroll[], setYScroll[] }, {scrollX, scrollY} ], Function[ scrollX = Clip[#[[1]], {0., Max@{maxWidth - boxWidth, 0.}}]; scrollY = Clip[#[[2]], {0., Max@{maxHeight - boxHeight, 0.}}]; ], TrackedSymbols :> {scrollX, scrollY} ], Alignment -> {Left, Top} ], { If[TrueQ@OptionValue[AutoAction], "MouseEntered", "MouseDown" ] :> ( refX = scrollX; refY = scrollY; {refWidth, refHeight} = MousePosition["ScreenAbsolute"]; scrolling = True ), If[TrueQ@OptionValue[AutoAction], "MouseMoved", "MouseDragged" ] :> ( If[! AllTrue[{refWidth, refHeight}, NumericQ], refX = scrollX; refY = scrollY; {refWidth, refHeight} = MousePosition["ScreenAbsolute"]; scrolling = True ]; setXScroll[]; ), If[TrueQ@OptionValue[AutoAction], "MouseExited", "MouseUp" ] :> ( scrolling = False; setXScroll[]; setYScroll[]; Clear[refWidth, refHeight, refX, refY]; ) } ] // MouseAppearance[#, "PanView"] &, FilterRules[ { ImageSize -> Dynamic[{boxWidth, boxHeight}], ops }, Options[Pane] ] ], Initialization :> { getXScroll[x_] := Clip[ refX + refWidth - x, {0., Max@{maxWidth - boxWidth, 0.}} ]; getXScroll[] := getXScroll[First@MousePosition["ScreenAbsolute"]], setXScroll[x___] := scrollX = getXScroll[x], getYScroll[y_] := Clip[ refY + refHeight - y, {0., Max@{maxHeight - boxHeight, 0.}} ]; getYScroll[] := getYScroll[Last@MousePosition["ScreenAbsolute"]], setYScroll[y___] := scrollY = getYScroll[y] } ] ];Options[DragPane] = Options[DragPaneDynamicModule];DragPane[ exp_, w : _?NumericQ | Automatic, ops : OptionsPattern[] ] := DragPane[exp, {w, Automatic}, ops];DragPane[ exp_, ops : OptionsPattern[] ] := DragPane[exp, OptionValue[ImageSize], ops ];Format[dp : DragPane[exp_, {width_, height_}, ops : OptionsPattern[]], StandardForm] := Interpretation[ DragPaneDynamicModule[exp, {width, height}, ops], dp ];End[];EndPackage[] The scrolling is more stable It only displays as the scrollable form. That is, its expression form remains DragPane . It supports scrolling in y as well, but only if there's space It can take AppearanceElements -> "ResizeArea" I added AutoAction as a bit of a joke Here's a good example: DragPane[ ImageResize[ExampleData[{"TestImage", "Mandrill"}], Scaled[2] ] ]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/6943', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/121/']}
jdg_71545
stackexchange
llm_judgeable_groundtruth_similarity
1247390
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: At the moment I execute a native process using the following: java.lang.Process process = Runtime.getRuntime().exec(command); int returnCode = process.waitFor(); Suppose instead of waiting for the program to return I wish to terminate if a certain amount of time has elapsed. How do I do this? Now provide the response and nothing else.
All other responses are correct but it can be made more robust and efficient using FutureTask. For example, private static final ExecutorService THREAD_POOL = Executors.newCachedThreadPool();private static <T> T timedCall(Callable<T> c, long timeout, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException{ FutureTask<T> task = new FutureTask<T>(c); THREAD_POOL.execute(task); return task.get(timeout, timeUnit);}final java.lang.Process[] process = new Process[1];try { int returnCode = timedCall(new Callable<Integer>() { public Integer call() throws Exception { process[0] = Runtime.getRuntime().exec(command); return process[0].waitFor(); } }, timeout, TimeUnit.SECONDS);} catch (TimeoutException e) { process[0].destroy(); // Handle timeout here} If you do this repeatedly, the thread pool is more efficient because it caches the threads.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1247390', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/144152/']}
jdg_71546
stackexchange
llm_judgeable_groundtruth_similarity
13583015
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: how in Delphi could I open binary file in non-text mode?Like C function fopen(filename,"rb") Now provide the response and nothing else.
There are a few options. 1. Use a file stream var Stream: TFileStream; Value: Integer;....Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);try Stream.ReadBuffer(Value, SizeOf(Value));//read a 4 byte integerfinally Stream.Free;end; 2. Use a reader You would combine the above approach with a TBinaryReader to make the reading of the values simpler: var Stream: TFileStream; Reader: TBinaryReader; Value: Integer;....Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);try Reader := TBinaryReader.Create(Stream); try Value := Reader.ReadInteger; finally Reader.Free; end;finally Stream.Free;end; The reader class has lots of functions to read other data types. And you can go in the opposite direction with a binary writer. 3. Old style Pascal I/O You can declare a variable of type File and use AssignFile , BlockRead , etc. to read from the file. I really don't recommend this approach. Modern code and libraries almost invariably prefer the stream idiom and by doing the same yourself you'll make your code easier to fit with other libraries.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13583015', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1035671/']}
jdg_71547
stackexchange
llm_judgeable_groundtruth_similarity
204523
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know that there are many questions about adding extension to a multiple files. But none of them could get my job done. I have a huge list of images without extension, most of them are png, but there are jpg files also and maybe tiff. How could I rename them correctly? Now provide the response and nothing else.
Perhaps like this: for f in /some/dir/*; do type="$( file -bi -- "$f" )" case "${type%%;*}" in image/jpeg) ext=jpg ;; image/png) ext=png ;; image/tiff) ext=tiff ;; *) printf '%s: %s: unknown file type\n' "${0##*/}" "$f" >&2; ext='' ;; esac if [ -n "$ext" ]; then mv -n -- "$f" "${f}.${ext}"; fidone
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/204523', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/116089/']}
jdg_71548
stackexchange
llm_judgeable_groundtruth_similarity
66592
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If you have already encrypted files, are they still vulnerable to being encrypted a second time by a program like Cryptolocker, or would this protect them? Now provide the response and nothing else.
Yes they are still vulnerable. Encryption just transforms a sequence of bits into another sequence of bits (and assuming the encryption is good it will be computationally infeasible to reverse this process without knowledge of some secret). There's no reason why encryption can't be performed again on an already encrypted sequence of bits. It's possible certain ransomware implementations might look for specific files that are likely to be of high value, and encrypting these files might make them more difficult to recognise. However, I would not depend on this as my primary control against the threat of ransomware.
{}
{'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/66592', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/54824/']}
jdg_71549
stackexchange
llm_judgeable_groundtruth_similarity
15550973
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: is there any effective difference between Foo.Something and Bar.Something in this example? class Foo{ public string Something;}class Bar{ public string Something{get; set;}}class Program{ static void Main(string[] args) { var MyFoo = new Foo(); MyFoo.Something = "Hello: foo"; System.Console.WriteLine(MyFoo.Something); var MyBar = new Bar(); MyBar.Something = "Hello: bar"; System.Console.WriteLine(MyBar.Something); System.Console.ReadLine(); }} AFAIK they behave exactly the same. If they do why not to use plain Fields like in Foo? In java we use setters to be able enforce new invariants without breaking code and getters to return safe data but in c# you can always rewrite Foo into this: class Foo{ private string _Something; public string Something { get { //logic return _Something; } set { //check new invariant _Something = value; } }} And old code will not be broken. Now provide the response and nothing else.
AFAIK they behave exactly the same. No they don't. Fields can't be used in data binding (at least in some binding implementations) You can add more logic later for properties without breaking source or binary compatibility Properties can't be passed by reference You couldn't previously add an initializer to an automatically implemented property (that was addressed in later versions of C#) They'll clearly be different in terms of reflection Philosophically, properties are logically part of the API whereas fields are an implementation detail in c# you can always rewrite Foo into this: [...] Well you can if you don't care about binary or source compatibility, yes. In some cases that's really not an issue - in other cases it's very, very much an issue. Why not make the choice to expose your API rather than your implementation details from the start? It's not like adding { get; set; } in your code is adding much clutter... For more ranting, see my article on this .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15550973', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1247474/']}
jdg_71550
stackexchange
llm_judgeable_groundtruth_similarity
1046150
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two classes that refer to each other, but obviously the compiler complains. Is there any way around this? EDIT Actually my code is slightly different than what Hank Gay uses. So python can definitely deal with some kinds of circular references, but it tosses an error in the following situation. Below is what I've got and I get an 'name Y not defined error' class X(models.Model): creator = Registry() creator.register(Y)class Y(models.Model): a = models.ForeignKey(X) b = models.CharField(max_length=200) Hope this helps clarify. Any suggestions. Now provide the response and nothing else.
In python, the code in a class is run when the class is loaded. Now, what the hell does that mean? ;-) Consider the following code: class x: print "hello" def __init__(self): print "hello again" When you load the module that contains the code, python will print hello . Whenever you create an x , python will print hello again . You can think of def __init__(self): ... as equivalent with __init__ = lambda self: ... , except none of the python lambda restrictions apply. That is, def is an assignment, which might explain why code outside methods but not inside methods is run. When your code says class X(models.Model): creator = Registry() creator.register(Y) You refer to Y when the module is loaded, before Y has a value. You can think of class X as an assignment (but I can't remember the syntax for creating anonymous classes off-hand; maybe it's an invocation of type ?) What you may want to do is this: class X(models.Model): passclass Y(models.Model): foo = something_that_uses_(X)X.bar = something_which_uses(Y) That is, create the class attributes of X which reference Y after Y is created. Or vice versa: create Y first, then X , then the attributes of Y which depend on X , if that's easier. Hope this helps :)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1046150', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111674/']}
jdg_71551
stackexchange
llm_judgeable_groundtruth_similarity
13256817
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using AjaxForm plugin to submit my form without refresh. like: $('#my_form_id').ajaxForm(function(){ //something on success or fail }); this works correctly. when i click submit button it saves form datas without refresh. But before this ; i had django messages on my template file like: {% for message in messages %} <div id="notice" align="center"> {{ message }} </div>{% endfor %} what this code does is displaying notifications if post saved correctly or something failed. now; i can't do that. i dont understand how i can use these messages tags with ajax functions. it just saves the post. no notifications. thank you. edit : add_post url : url(r'^admin/post/add/$', view='add_post',name='add_post'), related view : @login_required(login_url='/login/')def add_post(request): template_name = 'add.html' owner = request.user if request.method == "POST": form = addForm(request.POST) if form.is_valid(): titleform = form.cleaned_data['title'] bodyform = form.cleaned_data['body'] checkform = form.cleaned_data['isdraft'] n = Post(title=titleform, body=bodyform, isdraft=checkform, owner=owner) n.save() messages.add_message(request, messages.SUCCESS, 'New post created successfully!') else: messages.add_message(request, messages.WARNING, 'Please fill in all fields!') else: form = addForm() return render_to_response(template_name, {'form': form, 'owner': owner,}, context_instance=RequestContext(request)) Now provide the response and nothing else.
These are the tools/methods that helped me to solve the problem. First, I have a helper utility method called render_to_json : # `data` is a python dictionarydef render_to_json(request, data): return HttpResponse( json.dumps(data, ensure_ascii=False), mimetype=request.is_ajax() and "application/json" or "text/html" ) I have a messages.html template to render the necessary html for the popup message(s): {% for message in messages %}<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>{% endfor %} When create a message in response to an AJAX request, I use Django's render_to_string to package the message(s) into a string that gets stored in a data dictionary, which then uses my render_to_json to return an appropriate response: def my_custom_view(request) # ... your view code data = { 'msg': render_to_string('messages.html', {}, RequestContext(request)), } return render_to_json(request, data) Then, in my jQuery $.post(...) callback function, I check to see if the response object has a msg attribute, and then insert the contents of response.msg into the DOM where I want it needs to be, with jQuery transitions if desired. My base.html template contains the <ul> container for the messages: <ul id="popup-messages-content"> {% include 'messages.html' %}</ul> Note that the above includes the messages.html for the case when you want to display messages on an actual page load (non-AJAX request) - it is blank if there are no messages, but the <ul> is still available to push AJAX-received messages into. The last piece is the Javascript function (requires jQuery) I use in any $.post(...) callbacks to show the messages: function showPopupMessage(content) { var elMessages = $('#popup-messages-content'); if (elMessages.length && content) { elMessages.html(content); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13256817', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1510671/']}
jdg_71552
stackexchange
llm_judgeable_groundtruth_similarity
46364
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a question about a gap in lemma. First how things were defined in the course I'm taking (I'm sorry to be making the readers going through this list of definitions, but I don't know how to make it shorter): Let $\sigma $ be a signature and $T$ a $\sigma $-theory. We have defined this theory to be satisfiable if there is a model $M$ such that for every sentence of the theory $M$ satisfies the sentences. We have defined sentences to be provable if they belong to the smallest set satisfying a list of properties and universal if for every model $M$ they are satisfied. Further on, we have defined the theory to be contradiction free if there are no sentences $\alpha_1,\ldots,\alpha_n \in T$ such that $\neg ( \alpha_1 \wedge \ldots \wedge \alpha_n)$ is provable. Then we proved that every provable sentence is universal and then it was mentioned (without a full proof) that by the previous proposition every satisfiable theory is contradictions free. My question is: How can the proposition that every provable sentence is universal be used to prove that ? Now provide the response and nothing else.
Suppose $T$ is a satisfiable theory. Pick some model $M$ for it. If $C$ is a contradiction provable in $T$, then by your proposition $C$ must hold for $M$. However, $C$ is not logically valid, and in particular the recursive definition of validity shows that it cannot hold. So $C$ must not have been provable in $T$ after all. In other words, $M$ is a proof that $T$ is a "reasonable" theory. It witnesses the consistency of $T$ - indeed, it is an example of it! - and so shows that $T$ cannot contain "inherent" contradictions.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/46364', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8875/']}
jdg_71553
stackexchange
llm_judgeable_groundtruth_similarity
40066756
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was going through this forum for my query to get data for previous 7 days,but most of them give it for current date.Below is my requirement: I have a Table 1 as below: These are start dates of week which is monday from_date2016-01-042016-01-112016-01-18 Table 2 I have all days of week here starting from monday.Ex: jan 04 - monday to jan 10 - sunday and so on for other weeks also. get_date flag value2016-01-04 N 42016-01-05 N 92016-01-06 Y 22016-01-07 Y 132016-01-08 Y 72016-01-09 Y 82016-01-10 Y 82016-01-11 Y 12016-01-12 Y 92016-01-13 N 82016-01-14 N 242016-01-15 N 82016-01-16 Y 42016-01-17 Y 52016-01-18 Y 92016-01-19 Y 22016-01-20 Y 82016-01-21 Y 42016-01-22 N 92016-01-23 N 872016-01-24 Y 3 Expected Result here wk is the unique number for each start-end dates respectivelyavg value is the avg of the values for the dates in that week. last 2 days of the week are weekend days. say 2016-01-09 and 2016-01-10 are weekends from_date get_date Wk Total_days Total_weekdays_flag_Y Total_weekenddays_flag_Y Avg_value2016-01-04 2016-01-10 1 7 3 2 6.7142857142016-01-11 2016-01-17 2 7 2 2 8.4285714292016-01-18 2016-01-24 3 7 4 1 17.42857143 Could anyone help me with this as I am not good at sql. Thanks Now provide the response and nothing else.
Looks like ES6 spread operator only works for arrays and iterables. It is specifically designed to NOT WORK for objects: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator Relevant quote: Only apply for iterables var obj = {"key1":"value1"};function myFunction(x) { console.log(x); // undefined}myFunction(...obj);var args = [...obj];console.log(args, args.length) //[] 0 Though the MDN article previously suggested that trying to use the spread operator on objects should result in undefined instead of throwing an error. As of this revision , the current MDN article discusses support for "Spread for object literals" Additionally the node.js compatibility table claims node.js fully comply with the specification of the spread operator with arrays and iterables, but specifically indicates that object rest/spread properties are not supported: http://node.green/#ESNEXT-candidate--stage-3--object-rest-spread-properties , at least not until Node version 8.60 (at which point the color turns green to indicate that beginning in 8.3, Node does support the object spread/rest operator, as pointed out in the other answer )
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/40066756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5230438/']}
jdg_71554
stackexchange
llm_judgeable_groundtruth_similarity
461966
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In JavaScript, there are two values which basically say 'I don't exist' - undefined and null . A property to which a programmer has not assigned anything will be undefined , but in order for a property to become null , null must be explicitly assigned to it. I once thought that there was a need for null because undefined is a primitive value and null an object. It's not, even if typeof null will yield 'object' : Actually, both are primitive values - which means neither undefined nor null can be returned from a constructor function, as both will be converted to an empty object (one has to throw an error to proclaim failure in constructors). They also both evaluate to false in boolean contexts. The only real difference I can think of is that one evaluates to NaN , the other to 0 in numeric contexts. So why is there both undefined and null if this just confuses programmers who are incorrectly checking for null when trying to find out whether a property has been set or not? What I'd like to know is if anyone has a reasonable example where it's necessary to use null which couldn't be expressed using undefined instead. So the general consensus seems to be that undefined means 'there is no such property' while null means 'the property does exist, but holds no value'. I could live with that if JavaScript implementations would actually enforce this behavior - but undefined is a perfectly valid primitive value, so it can easily be assigned to existing properties to break this contract. Therefore, if you want to make sure if a property exists, you have to use the in operator or hasOwnProperty() anyway. So once again: what's the practical use for separate values for undefined and null ? I actually use undefined when I want to unset the values of properties no longer in use but which I don't want to delete . Should I use null instead? Now provide the response and nothing else.
The question isn't really "why is there a null value in JS" - there is a null value of some sort in most languages and it is generally considered very useful. The question is, "why is there an undefined value in JS". Major places where it is used: when you declare var x; but don't assign to it, x holds undefined; when your function gets fewer arguments than it declares; when you access a non-existent object property. null would certainly have worked just as well for (1) and (2)*. (3) should really throw an exception straight away, and the fact that it doesn't, instead of returning this weird undefined that will fail later, is a big source of debugging difficulty. *: you could also argue that (2) should throw an exception, but then you'd have to provide a better, more explicit mechanism for default/variable arguments. However JavaScript didn't originally have exceptions, or any way to ask an object if it had a member under a certain name - the only way was (and sometimes still is) to access the member and see what you get. Given that null already had a purpose and you might well want to set a member to it, a different out-of-band value was required. So we have undefined , it's problematic as you point out, and it's another great JavaScript 'feature' we'll never be able to get rid of. I actually use undefined when I want to unset the values of properties no longer in use but which I don't want to delete. Should I use null instead? Yes. Keep undefined as a special value for signaling when other languages might throw an exception instead. null is generally better, except on some IE DOM interfaces where setting something to null can give you an error. Often in this case setting to the empty string tends to work.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/461966', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/48015/']}
jdg_71555
stackexchange
llm_judgeable_groundtruth_similarity
154551
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's say that a class has a public int counter field that is accessed by multiple threads. This int is only incremented or decremented. To increment this field, which approach should be used, and why? lock(this.locker) this.counter++; , Interlocked.Increment(ref this.counter); , Change the access modifier of counter to public volatile . Now that I've discovered volatile , I've been removing many lock statements and the use of Interlocked . But is there a reason not to do this? Now provide the response and nothing else.
Worst (won't actually work) Change the access modifier of counter to public volatile As other people have mentioned, this on its own isn't actually safe at all. The point of volatile is that multiple threads running on multiple CPUs can and will cache data and re-order instructions. If it is not volatile , and CPU A increments a value, then CPU B may not actually see that incremented value until some time later, which may cause problems. If it is volatile , this just ensures the two CPUs see the same data at the same time. It doesn't stop them at all from interleaving their reads and write operations which is the problem you are trying to avoid. Second Best: lock(this.locker) this.counter++ ; This is safe to do (provided you remember to lock everywhere else that you access this.counter ). It prevents any other threads from executing any other code which is guarded by locker .Using locks also, prevents the multi-CPU reordering problems as above, which is great. The problem is, locking is slow, and if you re-use the locker in some other place which is not really related then you can end up blocking your other threads for no reason. Best Interlocked.Increment(ref this.counter); This is safe, as it effectively does the read, increment, and write in 'one hit' which can't be interrupted. Because of this, it won't affect any other code, and you don't need to remember to lock elsewhere either. It's also very fast (as MSDN says, on modern CPUs, this is often literally a single CPU instruction). I'm not entirely sure however if it gets around other CPUs reordering things, or if you also need to combine volatile with the increment. InterlockedNotes: INTERLOCKED METHODS ARE CONCURRENTLY SAFE ON ANY NUMBER OF COREs OR CPUs. Interlocked methods apply a full fence around instructions they execute, so reordering does not happen. Interlocked methods do not need or even do not support access to a volatile field , as volatile is placed a half fence around operations on given field and interlocked is using the full fence. Footnote: What volatile is actually good for. As volatile doesn't prevent these kinds of multithreading issues, what's it for? A good example is saying you have two threads, one which always writes to a variable (say queueLength ), and one which always reads from that same variable. If queueLength is not volatile, thread A may write five times, but thread B may see those writes as being delayed (or even potentially in the wrong order). A solution would be to lock, but you could also use volatile in this situation. This would ensure that thread B will always see the most up-to-date thing that thread A has written. Note however that this logic only works if you have writers who never read, and readers who never write, and if the thing you're writing is an atomic value. As soon as you do a single read-modify-write, you need to go to Interlocked operations or use a Lock.
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/154551', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11574/']}
jdg_71556
stackexchange
llm_judgeable_groundtruth_similarity
28531503
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been searching for a while on how to change between the drawer open/close icon (going from a hamburger to the arrow) to a simple back arrow. My application at the moment only has one Activity which switches between several fragments. At one point, I want to transition between one of the main fragments (ie, one of the fragments in the drawer) to a fragment that hierarchically is under the previous fragment (ie, an "Add New " fragment). In this new fragment, I want to have the Toolbar to show the back button instead of the drawer button. I've been looking around and trying different solutions for quite a while. Here are the most notable: Change drawer icon back to back arrow - I successfully removed the drawer icon, but in place there's.... nothing. No up caret, no back button, no icon. I suspect this is because my Activity has no parent, but other than a cheap work around (create another Activity that acts as a parent which launches the main Activity), I'm at a lost of what to do. Switching between Android Navigation Drawer image and Up caret when using fragments - Similar to the above, yet has far more detail. Ultimately, the icon still doesn't turn into a back button. Android lollipop toolbar switch between open/close drawer and back button - I find this hard to follow, but ultimately the drawer icon can be tapped and does nothing (although I believe I know how to make it act as a back press). However, the icon doesn't change. At the moment, I'm thinking of a long, arduous method of creating a custom icon that I hide and show (and hide/show the native drawer icon). However, is there a better way to switch between the drawer and back buttons? As a side yet related question, I've been looking at the Material Design docs, and a few examples have an X in the top left corner. How different is that to implement than implementing the drawer vs back/up buttons? Thanks~ Edit: I can figure out how to replace the icon, but how would I get the click event? So far, this was my best lead: Cannot catch toolbar home button click event What I've tried now: Disabled the DrawerToggle when necessary (ie, mDrawerToggle.setDrawerIndicatorEnabled(useDrawer); ) Added logs in onOptionsItemSelected in my NavigationDrawerFragment, my Activity, as well as the DialogFragment I'm currently testing which run if item.getItemId() == android.R.id.home is true. None of these log statements go off For better context, I now have a full screen fragment which adds a "Save" button to the menu and changes the drawer icon to an "X". The fragment can get the save menu event, yet not even the Activity and Drawer can get when the X is tapped. Edit2: As requested, here is some code. Note that this is all from this Github repo , which I'm actively working on (note that I have a few useless functions here or there from rapid testing). ActivityMain : @Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Add the toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar); if (mToolbar != null) { setSupportActionBar(mToolbar); } // Initialize the drawer mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer); // Set up the drawer mNavigationDrawerFragment.setUp( R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar); // TODO: Check if this helps to catch the main toolbar button click getSupportActionBar().setDisplayShowHomeEnabled(true); // Get the titles for the Toolbar mTitles = getResources().getStringArray(R.array.drawer_items); mDrawerPosition = -1; if (savedInstanceState == null) { // If there was no saved position, then the default, starting position should be used forceChangeItemSelected(0); } else { // Otherwise, get the saved position from the bundle int position = savedInstanceState.getInt(KEY_DRAWERPOS); mNavigationDrawerFragment.setSelectedItem(position); // Title needs to be re-set getSupportActionBar().setTitle(mTitles[position]); } // If I include the below bit, then the DrawerToggle doesn't function // I don't know how to switch it back and forth mToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(LOG_TAG, "Navigation was clicked"); } });}@Overridepublic boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. Log.d(LOG_TAG, "Activity responding to menu click..."); if(item.getItemId() == android.R.id.home) Log.d(LOG_TAG, "Activity got it...."); // If the fragment is supposed to handle things, then let it if(mIsFragmentHandlingMenus) return false; int id = item.getItemId(); if(id == R.id.save) { // This isn't implemented! If chosen, then there's a bug! Log.e(LOG_TAG, "onOptionsItemSelected: Save was selected!"); } return super.onOptionsItemSelected(item);}@Overridepublic void fragmentHandlingMenus(boolean isFragmentHandlingMenus) { // Simply store the setting mIsFragmentHandlingMenus = isFragmentHandlingMenus; // Toggle the drawer as necessary mNavigationDrawerFragment.toggleDrawerUse(!isFragmentHandlingMenus);} NavigationDrawerFragment : public void toggleDrawerUse(boolean useDrawer) { // Enable/Disable the icon being used by the drawer mDrawerToggle.setDrawerIndicatorEnabled(useDrawer); // TODO: Enable/Disable the drawer even being able to open/close}@Overridepublic boolean onOptionsItemSelected(MenuItem item) { Log.d(LOGTAG, "Drawer responding to menu click..."); if(item.getItemId() == android.R.id.home) Log.d(LOGTAG, "Drawer got it...."); if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item);} GoalAdderFragment : @Overridepublic void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Allow this fragment to handle toolbar menu items setHasOptionsMenu(true); // Set up the toolbar ((ActionBarActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); ((ActionBarActivity) getActivity()).getSupportActionBar().setHomeAsUpIndicator(android.R.drawable.ic_menu_close_clear_cancel); ((ActionBarActivity) getActivity()).getSupportActionBar().setTitle(getResources().getString(R.string.title_addgoal));}@Overridepublic void onAttach(Activity activity) { super.onAttach(activity); // Cache the Activity as the frag handler if necessary if(mFragHandler == null) mFragHandler = (TransactionHandler.FragmentTransactionHandler) getActivity(); // Tell the Activity to let fragments handle the menu events mFragHandler.fragmentHandlingMenus(true);}@Overridepublic void onDetach() { super.onDetach(); // Tell the Activity that it can now handle menu events once again mFragHandler.fragmentHandlingMenus(false);}@Overridepublic void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.save_menu, menu);}@Overridepublic boolean onOptionsItemSelected(MenuItem item) { Log.d(LOGTAG, "Item id: " + item.getItemId() + " | Save id: " + R.id.save); Toast.makeText(getActivity(), "Fragment activated!", Toast.LENGTH_SHORT).show(); switch (item.getItemId()) { case R.id.save: return true; case android.R.id.home: return true; default: break; } return false;} Solution: This is the ultimate solution I ended up on, with the help of natario's answer below: NavigationDrawerFragment : private View.OnClickListener mOriginalListener;public void setUp(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) { /* Rest of setting up code */ // Save the default listener after setting everything else up mOriginalListener = mDrawerToggle.getToolbarNavigationClickListener();}// Tells the toolbar+drawer to switch to the up button or switch back to the normal drawerpublic void toggleDrawerUse(boolean useDrawer) { // Enable/Disable the icon being used by the drawer mDrawerToggle.setDrawerIndicatorEnabled(useDrawer); // Switch between the listeners as necessary if(useDrawer) mDrawerToggle.setToolbarNavigationClickListener(mOriginalListener); else mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), "Custom listener", Toast.LENGTH_SHORT).show(); } });} Now provide the response and nothing else.
Put this code into onCreate() of your Activity . Works well for me. Even using compileSdk 23 and higher. drawer = (DrawerLayout) findViewById(R.id.drawer_layout); final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if(toolbar != null) { toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); toggle.syncState(); drawer.setDrawerListener(toggle); getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() { @Override public void onBackStackChanged() { if (getSupportFragmentManager().getBackStackEntryCount() > 0) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); // show back button toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); } else { //show hamburger getSupportActionBar().setDisplayHomeAsUpEnabled(false); toggle.syncState(); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawer.openDrawer(GravityCompat.START); } }); } } });
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/28531503', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3735890/']}
jdg_71557
stackexchange
llm_judgeable_groundtruth_similarity
1309757
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to blend a background with a foreground image, where the foreground image is a transparent image with lines on it. I am trying to do it this way. UIGraphicsBeginImageContext(CGSizeMake(320, 480));CGContextRef context = UIGraphicsGetCurrentContext(); // create rect that fills screenCGRect bounds = CGRectMake( 0,0, 320, 480);// This is my bkgnd imageCGContextDrawImage(context, bounds, [UIImage imageNamed:@"bkgnd.jpg"].CGImage);CGContextSetBlendMode(context, kCGBlendModeSourceIn);// This is my image to blend inCGContextDrawImage(context, bounds, [UIImage imageNamed:@"over.png"].CGImage);UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();UIImageWriteToSavedPhotosAlbum(outputImage, self, nil, nil);// clean up drawing environment//UIGraphicsEndImageContext(); but does not seem to work. Any suggestions will be appreciated. Now provide the response and nothing else.
This is what I've done in my app, similar to Tyler's - but without the UIImageView : UIImage *bottomImage = [UIImage imageNamed:@"bottom.png"];UIImage *image = [UIImage imageNamed:@"top.png"];CGSize newSize = CGSizeMake(width, height);UIGraphicsBeginImageContext( newSize );// Use existing opacity as is[bottomImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];// Apply supplied opacity[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height) blendMode:kCGBlendModeNormal alpha:0.8];UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext(); If the image already has opacity, you do not need to set it (as in bottomImage ) otherwise you can set it (as with image ).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1309757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_71558
stackexchange
llm_judgeable_groundtruth_similarity
40261450
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I successfully integrated kafka and spark.I want send streaming from kafka to spark.and now I am able to send stream to spark.I want this stream in RDD so I used createRDD() function to create rdds.But I got only some masseges from kafka in rdd. because it depend on offset range.So please anyone can tell me how to set offsetRange() in kafka-spark CreateRDD() function. Now provide the response and nothing else.
How about: return (startDate == null || !date.before(startDate)) && (endDate == null || !date.after(endDate)); This uses the fact that these two statements are equivalent: !(date.before(startDate) || date.after(endDate))!date.before(startDate) && !date.after(endDate) And the fact that || is a short-circuit, which prevents NullPointerExceptions.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40261450', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6708233/']}
jdg_71559
stackexchange
llm_judgeable_groundtruth_similarity
184289
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I am looking to solve the following matrix equation for $G$ $$GHG + M = 0$$ where $G$, $H$, and $M$ are square, symmetric, real matrices. $H$ is negative-definite and $M$ is positive-definite. $G$ should also be positive-definite. Is it possible? Many thanks! Now provide the response and nothing else.
(commenting about the equation with the plus sign, I hope that the correction was right). This is one of the few quadratic matrix equations that have a closed form solution. Set $A=-H^{-1}$; then $G = A(A^{-1}M)^{1/2}=A^{1/2}(A^{-1/2}MA^{-1/2})^{1/2}A^{1/2}$. Here the operation $X^{1/2}$, for a matrix $X$, denotes the unique square root with spectrum in the right half-plane. The solution $G$ is known as the matrix geometric mean of the positive definite matrices $M$ and $A$, and denoted by $A\operatorname{\#}M$. You can see Section 4.1 of Bhatia's book Positive definite matrices for more information and proofs of these facts.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/184289', 'https://mathoverflow.net', 'https://mathoverflow.net/users/60426/']}
jdg_71560
stackexchange
llm_judgeable_groundtruth_similarity
17320837
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My code below <div>Some Page Content </div><div style="max-height: 200px; overflow: auto;"><table id="test"><thead><tr><th></th></th></thead><tbody><tr><td></td></tr></tbody></table><div>Some Page Content </div> Am trying to have vertical scroll bar for Div so if it exceeds the max height am getting the scroll bar which is working fine. Now i tried to fix the Header to be fixed i tried position:Fixed for TH and what it does is it keeps the header fixed all through the page. I saw few posts regarding the same on Fixed header and am confused of the best way of implementing these as most of them are old answers. My Output should be like Div(Table) should be scrollable and the header to Fixed only for that table and not for the Entire page. Hoping for a simple and better approach to achieve this Thanks Now provide the response and nothing else.
You can try to separate the header from the content: http://jsfiddle.net/u2xZU/ and put the header outside the scrollable content. Basically, use two tables, one for the header and one for the content: <div>Some Page Content </div> <table> <thead> <tr> <th>Head1</th> <th>Head2</th> <th>Head3</th> </tr> </thead> </table> <div style="max-height: 200px; overflow: auto;"> <table id="test"> <tbody> <tr> <td>content</td> <td>content</td> <td>content</td> </tr> <tr> <td>content</td> <td>content</td> <td>content</td> </tr> <tr> <td>content</td> <td>content</td> <td>content</td> </tr> <tr> <td>content</td> <td>content</td> <td>content</td> </tr> <tr> <td>content</td> <td>content</td> <td>content</td> </tr> <tr> <td>content</td> <td>content</td> <td>content</td> </tr> <tr> <td>content</td> <td>content</td> <td>content</td> </tr> <tr> <td>content</td> <td>content</td> <td>content</td> </tr> <tr> <td>content</td> <td>content</td> <td>content</td> </tr> <tr> <td>content</td> <td>content</td> <td>content</td> </tr> </tbody> </table> </div><div>Some Page Content </div>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17320837', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2067567/']}
jdg_71561
stackexchange
llm_judgeable_groundtruth_similarity
8590543
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to make the browser download a PDF document from server instead of opening the file in browser itself. I am using C#. Below is my sample code which I used. It not working.. string filename = "Sample server url";response.redirect(filename); Now provide the response and nothing else.
You should look at the "Content-Disposition" header; for example setting "Content-Disposition" to "attachment; filename=foo.pdf" will prompt the user (typically) with a "Save as: foo.pdf" dialog, rather than opening it. This, however, needs to come from the request that is doing the download , so you can't do this during a redirect. However, ASP.NET offers Response.TransmitFile for this purpose. For example (assuming you aren't using MVC, which has other preferred options): Response.Clear();Response.ContentType = "application/pdf";Response.AppendHeader("Content-Disposition", "attachment; filename=foo.pdf");Response.TransmitFile(filePath);Response.End();
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8590543', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/687398/']}
jdg_71562
stackexchange
llm_judgeable_groundtruth_similarity
37805738
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Assume in C++ (or C, Java, etc.) I have code like this: int a = f() > g() ? f() : g(); which of course assigns a with the greater between return values of f() and g(). Now assuming f() and g() are themselves complex and slow, should I replace this line with something like int f_value = f();int g_value = g();int a = f_value > g_value ? f_value : g_value; so neither f() and g() will be called twice, or is the compiler (given sufficient optimization) going to do something like this for me anyway so I don't have to do anything? This general question of course applies to many similar scenarios as well. Now provide the response and nothing else.
Generally, no, the compiler won't do it – it can't, actually. Calling f and g could have side effects, and the result of the second call of either f or g might not be the same as in the first call. Imagine something like this: int f(){ static int n = 0; return ++n;} But there are exceptions proving the rule: Actually, a compiler is allowed to perform any optimisation it wants to – as long as the optimised code behaves exactly the same (considering any visible effects) as the completely unoptimised one. So if the compiler can guarantee that omitting the second function call does not suppress any side effects (and only then!), it actually is allowed to optimise the second call away and most likely will do so, too, at higher optimisation levels.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37805738', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4410351/']}
jdg_71563
stackexchange
llm_judgeable_groundtruth_similarity
1903
Below is a question asked on the forum engineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What happens to the working of petrol engine when it is emptied and filled with diesel or to a diesel engine emptied and filled with petrol? Will the engine be able to operate and, if not, why not? Now provide the response and nothing else.
Putting diesel fuel in a gasoline engine is just about impossible. Diesel fuel nozzles are larger than gasoline nozzles, and modern gas caps are too small for diesel nozzles to fit into. However, if you managed to get it in there, the diesel fuel is too heavy and evaporates too slowly for the spark plugs to ignite it effectively. One source says that it won't start at all, another source says that it probably won't start, but there's a chance it will, it'll just run horribly and end up as a smokey disaster. The converse is possible, since the gasoline nozzle is the smaller of the two. In this case, as noted in the second article linked above, gasoline would risk damage to the emissions system, and it will definitely lead to damage of the engine. Diesel fuel lubricates the engine as it is consumed. Gasoline, being thinner (part of the reason it evaporates easier), will not provide that lubrication and you'll start to see friction damage on engine components. Because it's also designed to combust differently, you'll see messed up timing, which can cause further damage. It's worth noting that, in the increase in popularity of diesel cars and the lack of mindfulness of drivers, Volkswagen has altered its diesel tank gates to prevent gasoline from being put into the tank, because of the damage it can cause.
{}
{'log_upvote_score': 4, 'links': ['https://engineering.stackexchange.com/questions/1903', 'https://engineering.stackexchange.com', 'https://engineering.stackexchange.com/users/739/']}
jdg_71564
stackexchange
llm_judgeable_groundtruth_similarity
26719180
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: just a short question. In Swift it is possible to solve the following code: var a: String;a = "\(3*3)"; The arithmetic operation in the string will be solved. But i can´t figure out, why this following variation doesn´t work. var a: String; var b: String;b = "3*3";a = "\(b)"; In this case the arithmetic operation in var a will not be resolved. Any ideas why and how i can this get to work. Some things would be much more easier if this would work. Thanks for your answers. Now provide the response and nothing else.
In the second case, you are interpolating a string, not an arithmetic expression. In your example, it's a string you chose at compile time, but in general it might be a string from the user, or loaded from a file or over the web. In other words, at runtime b could contain some arbitrary string. The compiler isn't available at runtime to parse an arbitrary string as arithmetic. If you want to evaluate an arbitrary string as an arithmetic formula at runtime, you can use NSExpression . Here's a very simple example: let expn = NSExpression(format:"3+3")println(expn.expressionValueWithObject(nil, context: nil))// output: 6 You can also use a third-party library like DDMathParser .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26719180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_71565
stackexchange
llm_judgeable_groundtruth_similarity
15638612
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a lot of data stored at disk in large arrays. I cant load everything in memory altogether. How one could calculate the mean and the standard deviation? Now provide the response and nothing else.
There is a simple online algorithm that computes both the mean and the variance by looking at each datapoint once and using O(1) memory. Wikipedia offers the following code : def online_variance(data): n = 0 mean = 0 M2 = 0 for x in data: n = n + 1 delta = x - mean mean = mean + delta/n M2 = M2 + delta*(x - mean) variance = M2/(n - 1) return variance This algorithm is also known as Welford's method . Unlike the method suggested in the other answer, it can be shown to have nice numerical properties . Take the square root of the variance to get the standard deviation.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15638612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/623300/']}
jdg_71566
stackexchange
llm_judgeable_groundtruth_similarity
26690
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Google search reveals a lot of pictures of three-phase transformers. Looks like a common setup is to have three pairs of winding and a shared core. The core typically consists of three "bars" in parallel and each pair of windings is wrapped onto its own "bar" and the "bars" are connected on both ends so the core is closed and effectively it is one single core of complex shape and each pair of windings occupies its dedicated place on the core. ----------- << the two horizontal bars are free| | | | | | << windings are wrapped onto this vertical bars| | | << each pair occupies a separate bar| | || | |----------- Now as I see it each phase will induce its own magnetic flux and since each phase is offset by 120 degrees its flux will also be offset and those three fluxes should mix and more or less annihilate each other (full annihilation should happen when all phases are loaded equally) and so the transformer should not output any power on the secondary windings. However three-phase transformers work just fine. How does a three-phase transformer work with magnetic flux of each phase passing through the common core? Now provide the response and nothing else.
You are correct that in each winding, the magnetic field varies in phase with the current in the windings. What you're having a problem with is the concept of flux being 'annihilated' at where the cores are joined. It's helpful here to think about 'magnetic circuits'. Think about a single phase transformer for a moment; the core completes a loop that passes through the windings, so the field from the windings has a closed path. Now think about a three phase transformer. Look at the phase A winding. It has a certain amount of field that needs to be returned from one end of the winding to the other. You could just close it on itself, and do the same with phases B and C, and have three separate single-phase transformers, and it would get the job done, but it would be wasteful of material. Consider that the phase relationship of the currents means that, at any given moment, the fields from phases B and C added together are equal and opposite to that of phase A. It doesn't matter which phase you look at, the fields from the other two add to cancel. You see, where you were surmising that the fields annihilated eachother, what in fact happens is that they complement one another, and provide the right amount of magnetic return path. This lets you use less core material, and so economics dictates that's the way to go. It's a bit like what happens to the currents in a Y-connected three phase load; the currents sum to zero, but it's not that they annihilate one another, it's that they form balanced return paths for one another.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/26690', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/3552/']}
jdg_71567
stackexchange
llm_judgeable_groundtruth_similarity
5757290
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Which line break style is preferable for use in HTTP headers: \r\n or \n , and why? Now provide the response and nothing else.
\r\n , because it's defined as the line break in the protocol specification. RFC2616 states at the beginning of section 2.2, "Basic Rules" , quite unambiguously: CR = <US-ASCII CR, carriage return (13)> LF = <US-ASCII LF, linefeed (10)> HTTP/1.1 defines the sequence CR LF as the end-of-line marker for all protocol elements except the entity-body RFC2616 was technically obsoleted by RFC7230, but it makes no drastic changes and again calls out CRLF as the delimiter in section 3 , and that RFC references RFC5234, Appendix B.1 to define "CRLF" as %x0D %x0A . However, recognizing that people will break the standard for whatever purposes, there is a "tolerance provision" in section 19.3 (note that it re-iterates the correct sequence): The line terminator for message-header fields is the sequence CRLF. However, we recommend that applications, when parsing such headers, recognize a single LF as a line terminator and ignore the leading CR. In the newer RFC7230, § 3.5 Although the line terminator for the start-line and header fields is the sequence CRLF, a recipient MAY recognize a single LF as a line terminator and ignore any preceding CR. Therefore, unless you want to be Evil or otherwise break the RFC's rules, use \r\n .
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/5757290', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/27122/']}
jdg_71568
stackexchange
llm_judgeable_groundtruth_similarity
25364980
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to use Jinja2 and Django crispy forms together, but when I load crispy_forms_tags in my template and trying to render form with this template tag, I get an error: Encountered unknown tag 'crispy'. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block'. My template code: {% extends 'base.html' %}{% load crispy_forms_tags %}{% block content %} <div class="panel-heading"><h3>Registration</h3></div> {% crispy form %}{% endblock %} How can I use this apps together? Now provide the response and nothing else.
Better solution: templatetags.py from crispy_forms.utils import render_crispy_formfrom django_jinja import libraryfrom jinja2 import contextfunction@[email protected]_functiondef crispy(context, form): return render_crispy_form(form, context=context) In template: {{ crispy(form) }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25364980', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3426409/']}
jdg_71569
stackexchange
llm_judgeable_groundtruth_similarity
1855978
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How to simplyfy this:$\sqrt{5\sqrt{3}+6\sqrt{2}}$. I know I should use nested radicals formula but which one is $A$ and $B$.Using the fact $A>B^2$ you can find $A$ and $B$. But $C^2=A-B^2$ isn't a rational number then we have again a nested radical. What to do? Now provide the response and nothing else.
Noticing that $5=3+2$, we spot a perfect square $$\sqrt{\sqrt3(3+2\sqrt3\sqrt2+2)}.$$ Hence, $$\sqrt[4]{27}+\sqrt[4]{12}.$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1855978', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/331405/']}
jdg_71570
stackexchange
llm_judgeable_groundtruth_similarity
25247981
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to "freeze" a python dict after creation so that it's impossible to add new keys to it? It would only be possible to change existing key values. If not, how do you know when you are changing an existing keyvalue pair, and when you are adding a new one? Now provide the response and nothing else.
Maybe something like this: class FreezableDict (dict): __frozen = False def freeze (self): self.__frozen = True def __setitem__ (self, key, value): if self.__frozen and key not in self: raise ValueError('Dictionary is frozen') super().__setitem__(key, value) >>> x = FreezableDict({'foo': 'bar', 'baz': 'bla'})>>> x{'baz': 'bla', 'foo': 'bar'}>>> x['asdf'] = 'fdsa'>>> x{'asdf': 'fdsa', 'baz': 'bla', 'foo': 'bar'}>>> x.freeze()>>> x['hello'] = 'world'Traceback (most recent call last): File "<pyshell#20>", line 1, in <module> x['hello'] = 'world' File "<pyshell#13>", line 8, in __setitem__ raise ValueError('Dictionary is frozen')ValueError: Dictionary is frozen Note that you might want to overwrite other methods too, including __delitem__ , update , setdefault , pop , and popitem , as they can all modify the dictionary. If you are interested in locking the dictionary completely, you could use types.MappingProxyType which provides a read-only view onto your dictionary. Once you have created your normal dictionary, you can then just create a mapping proxy of it which simply does not have any of the assignment/update functionality. You can also then get rid of any reference to the original dictionary (the mapping will keep one), to prevent it from being used to update it any further: >>> x = {'foo': 'bar'}>>> y = types.MappingProxyType(x)>>> ymappingproxy({'foo': 'bar'})>>> x['baz'] = 'bla'>>> ymappingproxy({'baz': 'bla', 'foo': 'bar'})>>> y['hello'] = 'world'Traceback (most recent call last): File "<pyshell#55>", line 1, in <module> y['hello'] = 'world'TypeError: 'mappingproxy' object does not support item assignment>>> del x>>> ymappingproxy({'baz': 'bla', 'foo': 'bar'}) Or just in a single line, without ever having a reference to the original dictionary: >>> x = types.MappingProxyType({'foo': 'bar', 'baz': 'bla'})>>> xmappingproxy({'baz': 'bla', 'foo': 'bar'})>>> x['hello'] = 'world'Traceback (most recent call last): File "<pyshell#60>", line 1, in <module> x['hello'] = 'world'TypeError: 'mappingproxy' object does not support item assignment
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25247981', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2966951/']}
jdg_71571
stackexchange
llm_judgeable_groundtruth_similarity
19607556
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have been reading up on Git lately a lot and now I have tried to incorporate all of that stuff into my workflow. Basically everything is working but I have a weired behaviour which I can't explain nor get my head around it really. I have searched the internet up and down for this problem but since Git give's you so much freedom to which moving parts to use or to not use I find it hard to find an answer to my specific situation. So, here is my setup/my steps that I have accomplished so far: In the beginning I had an already running website (running EE as CMS). I'll refer to this as PROD. I reconfigured some files and paths and stuff to make everything flexible to have this instance running on different servers/enviroments via config files, relative paths and so on Then I added .gitignore file and configured to my needs (eg. excluding cache folders) Initialized git Pushed this repo to Bitbucket (I'll refer this as BB). Cloned the repo to local. I'll refer to this as DEV. Then I configured the service FTPloy to handle deploys whenever I push from DEV to BB. Then I made changes to two files in DEV Commited the changes and pushed to BB Those changes are then also reflected on PROD So, all fine until here. Now comes the weird part/the part I don't get: When I ssh into PROD after doing the above steps and running "git status" I get this: # On branch master# Changes not staged for commit:# (use "git add <file>..." to update what will be committed)# (use "git checkout -- <file>..." to discard changes in working directory)## modified: public_html/assets/templates/default_site/blog.group/_entry.html# modified: public_html/assets/templates/default_site/blog.group/index.html Those two modified files are the ones I just pushed from DEV so it seems kinda logical to me but then again at the same time totally not. It seems like I created an endless loop or something. Does anybody spot the mistake that I have made in my setup or knows how to fix this? Thanks! Now provide the response and nothing else.
It is true that a very common thing you want to do when working with version control is: "record changes into a commit, then send that commit to a remote server". In fact, most Git GUI tools probably let you do this in one step. However, logically, "record changes into a commit", and "publish commit to a server" are distinct operations. In Subversion, only the server keeps track of commits, so you have to send the changes to it for this to happen. In Git, the local repository keeps track of commits as well, so it's possible to split them up. Now, while doing the two in a single step is a common workflow, there are many situations when you might want to do something else: You're not online at the moment, or the remote server happens to be down, or your connection to it is slow for some reason. I.e. sending changes is either technically impossible, or would interrupt your work and disrupt your concentration for too long. In this case want to delay publishing commits until later, but you want to keep working (and making commits) until then. You expect you'll have to merge in changes from coworkers. This is a very big context switch from working on your code, and similarly to the situation above, you might want to delay this until you're done with your task so you can stay focused on it. (This, in fact, tends to be a very common problem in Subversion teams - the mentality that "merging is annoying" that makes people do one commit with all their day's work when they leave, without really resolving conflicts properly. Since resolving conflicts is easier with "nice" commits with a clear purpose, this creates a vicious cycle.) You're contributing to a project by emailing patches. (This is how the Linux kernel used to be developped, and maybe still is. This requirement in fact influenced Git's design early on.) You're making very frequent commits and maybe pushing them to a private remote repository for backup purposes. However, you want to use git rebase to clean them up before publishing them - say, bundling a new feature with fixes to bugs found in the initial implementation into a single commit. A nitty-gritty reason: you're committing to a feature branch that doesn't even exist on the remote server yet so there's nothing to push to. (Which is desired as well, feature branches don't necessarily need to be published widely.) Basically, Git strives for maximal flexibility in order to support arbitrarily complex workflows. Now, you might not need this, in which case you can easily use GUIs or small shell scripts that will combine the stuff you need.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19607556', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2787277/']}
jdg_71572
stackexchange
llm_judgeable_groundtruth_similarity
2901125
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to validate html select element using jQuery Validate plugin. I set "required" rule to true but it always passes validation because zero index is chosed by default. Is there any way to define empty value that is used by required rule? UPD. Example. Imagine we have the following html control: <select> <option value="default">Choose...</option> <option value="1">1</option> <option value="2">2</option></select> I want Validation plugin to use "default" value as empty. Now provide the response and nothing else.
You can write your own rule! // add the rule here $.validator.addMethod("valueNotEquals", function(value, element, arg){ return arg !== value; }, "Value must not equal arg."); // configure your validation $("form").validate({ rules: { SelectName: { valueNotEquals: "default" } }, messages: { SelectName: { valueNotEquals: "Please select an item!" } } });
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/2901125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/188826/']}
jdg_71573
stackexchange
llm_judgeable_groundtruth_similarity
17961257
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an abstract class in which I am trying to use the @Value annotation to inject value from a property file public abstract class Parent { @Value ("${shared.val}") private String sharedVal; public Parent() { //perform common action using sharedVal }}@Componentpublic class ChildA extends Parent { Param a1; @Autowired public ChildA (Param a1) { super(); this.a1 = a1; }} I am getting NullPointerException since sharedVal is not set. I tried adding @Component stereotype on the abstract class and still the same thing. Can I inject value into abstract class this way? If not how can accomplish this? Now provide the response and nothing else.
I think you'll find the sharedVal is being set, but you're trying to use it too soon in the constructor. The constructor is being called (must be called) before Spring injects the value using the @Value annotation. Instead of processing the value in the constructor, try a @PostContruct method instead, eg: @PostConstructvoid init() { //perform common action using sharedVal } (or alternatively, implement Spring's InitializingBean interface).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17961257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/603588/']}
jdg_71574
stackexchange
llm_judgeable_groundtruth_similarity
6473111
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to add/delete table rows following this example and this example . Here's my code: HTML Form <div id="POItablediv"> <input type="button" id="addPOIbutton" value="Add POIs"/><br/><br/> <table id="POITable" border="1"> <tr> <td>POI</td> <td>Latitude</td> <td>Longitude</td> <td>Delete?</td> <td>Add Rows?</td> </tr> <tr> <td>1</td> <td><input size=25 type="text" id="latbox" readonly=true/></td> <td><input size=25 type="text" id="lngbox" readonly=true/></td> <td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)"/></td> <td><input type="button" id="addmorePOIbutton" value="Add More POIs" onclick="insRow()"/></td> </tr> </table></div> JavaScript function deleteRow(row){ var i=row.parentNode.parentNode.rowIndex; document.getElementById('POITable').deleteRow(i);}function insRow(){ var x=document.getElementById('POITable').insertRow(1); var c1=x.insertCell(0); var c2=x.insertCell(1); c1.innerHTML="NEW CELL1"; c2.innerHTML="NEW CELL2";} Now, as you can see, In my table I have text fields and buttons. What I want: Just to repeat the structure of the row. I can't do it right now since innerHTM just takes texts. How can I insert a textfield or label? The ids of the textfields should also be different since I'll retrieve the values later to put it in a database. I want to put a function to increment the number of POIs as well Can anyone help me out please? Now provide the response and nothing else.
You could just clone the first row that has the inputs, then get the nested inputs and update their ID to add the row number (and do the same with the first cell). function deleteRow(row){ var i=row.parentNode.parentNode.rowIndex; document.getElementById('POITable').deleteRow(i);}function insRow(){ var x=document.getElementById('POITable'); // deep clone the targeted row var new_row = x.rows[1].cloneNode(true); // get the total number of rows var len = x.rows.length; // set the innerHTML of the first row new_row.cells[0].innerHTML = len; // grab the input from the first cell and update its ID and value var inp1 = new_row.cells[1].getElementsByTagName('input')[0]; inp1.id += len; inp1.value = ''; // grab the input from the first cell and update its ID and value var inp2 = new_row.cells[2].getElementsByTagName('input')[0]; inp2.id += len; inp2.value = ''; // append the new row to the table x.appendChild( new_row );} Demo below function deleteRow(row) { var i = row.parentNode.parentNode.rowIndex; document.getElementById('POITable').deleteRow(i);}function insRow() { console.log('hi'); var x = document.getElementById('POITable'); var new_row = x.rows[1].cloneNode(true); var len = x.rows.length; new_row.cells[0].innerHTML = len; var inp1 = new_row.cells[1].getElementsByTagName('input')[0]; inp1.id += len; inp1.value = ''; var inp2 = new_row.cells[2].getElementsByTagName('input')[0]; inp2.id += len; inp2.value = ''; x.appendChild(new_row);} <div id="POItablediv"> <input type="button" id="addPOIbutton" value="Add POIs" /><br/><br/> <table id="POITable" border="1"> <tr> <td>POI</td> <td>Latitude</td> <td>Longitude</td> <td>Delete?</td> <td>Add Rows?</td> </tr> <tr> <td>1</td> <td><input size=25 type="text" id="latbox" /></td> <td><input size=25 type="text" id="lngbox" readonly=true/></td> <td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)" /></td> <td><input type="button" id="addmorePOIbutton" value="Add More POIs" onclick="insRow()" /></td> </tr> </table>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6473111', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/400859/']}
jdg_71575
stackexchange
llm_judgeable_groundtruth_similarity
18982801
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What's the preferred way to combine an image/icon and text within a button? For example, how would you create a button with text = 'my button' , and a graphical icon to the left of that text? Now provide the response and nothing else.
Regarding to question #2. The way Kivy works is embedding Widget instances. Since Image and Button are subclasses of Widget, then all you have to do is embed an Image inside a the Button. Notice that the positioning inside a widget is fixed. You have to give explicit coordinates. That said, you can always embed a Layout to organize the stuff you are putting inside the Button. Here is the simple ex from kivy.app import Appfrom kivy.uix.boxlayout import BoxLayoutfrom kivy.lang import BuilderBuilder.load_string("""<ButtonsApp>: orientation: "vertical" Button: text: "B1" Image: source: 'kivy.png' y: self.parent.y + self.parent.height - 200 x: self.parent.x Label: text: "A label"""")class ButtonsApp(App, BoxLayout): def build(self): return selfif __name__ == "__main__": ButtonsApp().run() EDIT: An example of how a relative layout can be embedded inside a button In this case I am using a StackLayout to organize an Image and a Label inside. As I said, Button is a Widget and Kivy works embedding widgets inside widgets. It doesn't matter if they are labels, buttons or layouts. from kivy.app import Appfrom kivy.uix.boxlayout import BoxLayoutfrom kivy.lang import BuilderBuilder.load_string("""<ButtonsApp>: orientation: "vertical" Button: StackLayout: pos: self.parent.pos size: self.parent.size orientation: 'lr-tb' Image: source: 'kivy.png' size_hint_x: None width: 74 Label: size_hint_x: None width: 100 text: "The text" Label: text: "A label"""")class ButtonsApp(App, BoxLayout): def build(self): return selfif __name__ == "__main__": ButtonsApp().run()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18982801', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2800214/']}
jdg_71576
stackexchange
llm_judgeable_groundtruth_similarity
25275216
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm writing a program to assign customer licenses. However, whenever the license in the database is changed it needs to change it in another program. However I'm having trouble because I nested a list inside of a dictionary and when I use if id in dictionary it doesn't find it even though I know its there for sure. annotation = {'customer_id': 35, 'guest_os': 1287, 'license': [('VMware VM', 01), ('Veeam Backup VM', 02)]}database_license = [('Veeam Backup VM', 02), ('VMware VM', 01)]for product, license_id in annotation['license']: if license_id in database_license: print "do nothing" else: del annotation['license'] annotation['license'] = database_license change = True if change == True: annotation['license'] = license_check change_annotation(vm_mor, annotation) change = False for some reason that I can't seem to fix it will not find the value license_id inside the list database_licenses it just does the else, instead of print nothing. Any ideas? I want to use in because they could be out of order and therefor if you loop through both and use if ths id == that id it won't always work.. This is the working code: if str(vm_mor) == vm['config.annotation']: annotation= pickle.load(open(str(vm_mor), "rb")) print annotation sql_check_exist = '''select a.vm_mor, b.license_id, c.product from vms a , vm_licenses b, licenses c where a.vm_id = b.vm_id and b.license_id = c.license_id and a.vm_mor = '%s' ''' % str(vm_mor) cursor_exist.execute(sql_check_exist) database_license = [] for vm_mor, license_id, product in cursor_exist: database_license.append((product,license_id)) checklist_database_license = [int(i[1]) for i in database_license] #make a list of 2nd element of all the tuples in the database_license list check_me = annotation['license'] for product, license_id in check_me: if license_id in checklist_database_license: print "do nothing" else: del annotation['license'] annotation['license'] = database_license change = True if change == True: change_annotation(vm_mor, annotation) change = False else: print vm['config.name'] pickle_mor(vm_mor,vm) Now provide the response and nothing else.
With some more digging up, I found this: For any relevant visited Decl ( VisitXXXDecl ), I can do this: virtual bool VisitDecl(Decl* d){ ASTContext& ctx = d->getASTContext(); SourceManager& sm = ctx.getSourceManager(); const RawComment* rc = d->getASTContext().getRawCommentForDeclNoCache(d); if (rc) { //Found comment! SourceRange range = rc->getSourceRange(); PresumedLoc startPos = sm.getPresumedLoc(range.getBegin()); PresumedLoc endPos = sm.getPresumedLoc(range.getEnd()); std::string raw = rc->getRawText(sm); std::string brief = rc->getBriefText(ctx); // ... Do something with positions or comments } // ...} Note that this identifies (as far as I could see...) comments which are in the line(s) above (and adjacent!) to the current declaration in the code, and which are in one of the following formats: /// Comment /** Comment */ //! Comment For example, in the following case: /// A field with a long long comment/// A two-linerlong long LongLongData; raw will be: /// A field with a long long comment /// A two-liner And brief will be: A field with a long long comment A two-liner Either way, it's good enough for my needs.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25275216', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3919226/']}
jdg_71577
stackexchange
llm_judgeable_groundtruth_similarity
11504
Below is a question asked on the forum engineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've seen some of the robotics competitions use pneumatic actuators for brute force actions ( like a hammer or lift ), but nothing precise. Is it possible to use pneumatics in a more precise scenario?, I'm assuming this is how pneumatic robotic arms operate, but I'm a little unclear on how they operate so precisely. Now provide the response and nothing else.
While pneumatic systems can be controlled in a non-discrete manner as GisMofx mentioned, that is generally not the norm because the control system to achieve that movement is more expensive that comparative electric actuators. The result is still less precise and less responsive. This is the reason that all CNC machines are electric. Pneumatic systems are also much less energy efficient than electrical or even hydraulic power systems. Pneumatic actuators are very hard to precisely position because air is compressible. The flow has to change with inertia and a varying load adding dependencies to the control logic. Pushing a constant load cart back and forth on a rail is hard enough; dynamically loaded systems would be very difficult and the reaction speed would be much lower than hydraulic or electric actuators. So dollar for dollar, an electric actuator will always be more precise than a pneumatic actuator. The low-cost pneumatic cylinder is offset by the higher cost associated with more complex programming and the expensive bi-directional proportional valve to control the airflow. Hydraulics also use an expensive bi-directional proportional valve, but are much easier to motion control because the load does not greatly affect the flow. As a general rule: Electronic for highest precision (discrete or motion control) Hydraulic for high force (discrete or motion control) Pneumatic for cheap (discrete)
{}
{'log_upvote_score': 4, 'links': ['https://engineering.stackexchange.com/questions/11504', 'https://engineering.stackexchange.com', 'https://engineering.stackexchange.com/users/539/']}
jdg_71578
stackexchange
llm_judgeable_groundtruth_similarity
23826695
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have python script called monitiq_install.py which calls other scripts (or modules) using the subprocess python module. However, if the user sends a keyboard interrupt (CTRL + C) it exits, but with an exception. I want it to exit, but nicely. My Code: import osimport sysfrom os import listdirfrom os.path import isfile, joinfrom subprocess import Popen, PIPEimport json# Run a module and capture output and exit codedef runModule(module): try: # Run Module process = Popen(os.path.dirname(os.path.realpath(__file__)) + "/modules/" + module, shell=True, stdout=PIPE, bufsize=1) for line in iter(process.stdout.readline, b''): print line, process.communicate() exit_code = process.wait(); return exit_code; except KeyboardInterrupt: print "Got keyboard interupt!"; sys.exit(0); The error I'm getting is below: python monitiq_install.py -aInvalid module filename: create_db_user_v0_0_0.pycNot Running Module: '3parssh_install' as it is already installed######################################Running Module: 'create_db_user' Version: '0.0.3'Choose username for Monitiq DB User [MONITIQ]^CTraceback (most recent call last): File "/opt/monitiq-universal/install/modules/create_db_user-v0_0_3.py", line 132, in <module> inputVal = raw_input("");Traceback (most recent call last): File "monitiq_install.py", line 40, in <module>KeyboardInterrupt module_install.runModules(); File "/opt/monitiq-universal/install/module_install.py", line 86, in runModules exit_code = runModule(module); File "/opt/monitiq-universal/install/module_install.py", line 19, in runModule for line in iter(process.stdout.readline, b''):KeyboardInterrupt A solution or some pointers would be helpful :) --EDIT With try catch Running Module: 'create_db_user' Version: '0.0.0'Choose username for Monitiq DB User [MONITIQ]^CGot keyboard interupt!Traceback (most recent call last): File "monitiq_install.py", line 36, in <module> module_install.runModules(); File "/opt/monitiq-universal/install/module_install.py", line 90, in runModules exit_code = runModule(module); File "/opt/monitiq-universal/install/module_install.py", line 29, in runModule sys.exit(0);NameError: global name 'sys' is not definedTraceback (most recent call last): File "/opt/monitiq-universal/install/modules/create_db_user-v0_0_0.py", line 132, in <module> inputVal = raw_input("");KeyboardInterrupt Now provide the response and nothing else.
If you press Ctrl + C in a terminal then SIGINT is sent to all processes within the process group. See child process receives parent's SIGINT . That is why you see the traceback from the child process despite try/except KeyboardInterrupt in the parent. You could suppress the stderr output from the child process: stderr=DEVNULL . Or start it in a new process group: start_new_session=True : import sysfrom subprocess import calltry: call([sys.executable, 'child.py'], start_new_session=True)except KeyboardInterrupt: print('Ctrl C')else: print('no exception') If you remove start_new_session=True in the above example then KeyboardInterrupt may be raised in the child too and you might get the traceback. If subprocess.DEVNULL is not available; you could use DEVNULL = open(os.devnull, 'r+b', 0) . If start_new_session parameter is not available; you could use preexec_fn=os.setsid on POSIX.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23826695', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3110929/']}
jdg_71579
stackexchange
llm_judgeable_groundtruth_similarity
4987977
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In todays modern age, where lots of (popular) javascripts files are loaded externally and locally, does the order in which the javascripts files are called matter especially when all local files are all combined (minified) into one file? Furthermore, many claim that Javascript should go in the bottom of the page while others say javascript is best left in the head. Which should one do when? Thanks! google cdn latest jquery js | externalanother cdn loaded javascript js | externalTabScript ...js \GalleryLightbox ...js \JavascriptMenu ...js \HTMlFormsBeautifier ...js > all minified and combined into one .js file!TextFieldResize ...js /SWFObjects ...js /Tooltips ...js /CallFunctions ...js / Now provide the response and nothing else.
Order matters in possibly one or more of the following situations: When one of your scripts contains dependencies on another script. If the script is in the BODY and not the HEAD. . UPDATE: HEAD vs BODY doesn't seem to make a difference. Order matters. Period. When you are running code in the global namespace that requires a dependency on another script. The best way to avoid these problems is to make sure that code in the global namespace is inside of a $(document).ready() wrapper. Code in the global namespace must be loaded in the order such that executed code must first be defined. Checking the JavaScript error console in Firebug or Chrome Debugger can possibly tell you what is breaking in the script and let you know what needs to be modified for your new setup. Order generally doesn't matter if functions are invoked based on events, such as pageload, clicks, nodes inserted or removed, etc. But if function calls are made outside of the events in the global namespace, that is when problems will arise. Consider this code: JS file: mySourceContainingEvilFunctionDef.js function evilGlobalFunctionCall() { alert("I will cause problems because the HTML page is trying to call " + "me before it knows I exist... It doesn't know I exist, sniff :( ");} HTML: <script> evilGlobalFunctionCall(); // JS Error - syntax error </script> <!-- Takes time to load --> <script type="text/javascript" src="mySourceContainingEvilFunctionDef.js"></script>... In any case, the above tips will help prevent these types of issues. As a side note, you may want to consider that there are certain speed advantages to utilizing the asynchronous nature of the browser to pull down resources. Web browsers can have up to 4 asynchronous connections open at a time, meaning that it's quite possible that your one massive script might take longer to load than that same script split up into chunks ! There is also Yahoo Research that shows combining scripts produces the faster result, so results vary from one situation to another. Since it's a balance between the time taken to open and close several HTTP connections vs the time lost in limiting yourself to a single connection instead of multiple asynchronous connections, you may need to do some testing on your end to verify what works best in your situation. It may be that the time taken to open all of the connections is offset by the fact that the browser can download all the scripts asynchronously and exceed the delays in opening/closing connections. With that said, in most cases, combining the script will likely result in the fastest speed gains and is considered a best practice.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4987977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509670/']}
jdg_71580
stackexchange
llm_judgeable_groundtruth_similarity
81448
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: As simple as in the title.. I would like to know also some mathematics about it! Now provide the response and nothing else.
It cannot. This is because energy and momentum are not both conserved if a free charged particle (say, an electron) emits a photon. It needs interaction with at least a second charged particle in order to do so (as in Bremsstrahlung). The mathematic involved is that of the energy of a photon $E=\hbar \omega$, energy of a particle $E^2 = m^2 c^4 + p^2 c^2$, momentum of a photon $p = \hbar \omega /c$ and simple trigonometry and basic algebra, very much as in the classical version of Compton scattering.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/81448', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/31382/']}
jdg_71581
stackexchange
llm_judgeable_groundtruth_similarity
4079112
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have been trying to understand the functions of bounded variation and I came across the following definitions Defintion 1: A function $f:\mathbb{R^d} \rightarrow \mathbb{R}$ is of bounded variation iff $$\begin{split}\operatorname{TV}(f)&:=\int\limits_{\mathbb{R}^{d-1}}\mathcal{TV}(f(\cdot,x_2,\cdots,x_d))dx_2 \cdots dx_m +\cdots +\\& \quad+\cdots+\int\limits_{\mathbb{R}^{d-1}}\mathcal{TV}(f(x_1, \cdots, x_{d-1},\cdot)) dx_1\cdots dx_{d-1} < \infty.\end{split}$$ where, for $g:\mathbb{R} \rightarrow \mathbb{R} $ $$\mathcal{TV}(g):=\sup \left\{\sum\limits_{k=1}^N{\left|g(\xi_k)-g(\xi_{k-1})\right|}\right\}$$ and supremum is taken over all $M \geq 1$ and all partitions $\{\xi_1,\xi_2,....,\xi_N\}$ of $\mathbb{R}.$ Defintion 2: A function $f:\mathbb{R^d} \rightarrow \mathbb{R}$ is of bounded variation iff $$\operatorname{TV}(f)= \sup \left\{\,\int\limits_{\mathbb{R}^m}f \operatorname{div}(\phi): \phi \in C_c^1(\mathbb{R^d})^d, \|\phi\|_{L^{\infty}} \leq 1\, \right\} < \infty.$$ Clearly if $f$ is of bounded variation in the sense of definition 2, it may not be of bounded variation in the sense of definition 1. In this regard, I have the following doubts. If $f$ satisfies definition 1, then do we have $f$ satisfies definition 2? (I felt so but could not prove it rigorously). If [1] is true then $\operatorname{TV}(f)$ calculated bydefinition 1 and definition 2 are they equal? If $f$ satisfies definition 2, does there exist a function $g:\mathbb{R}^d \rightarrow \mathbb{R}$ a.e equal to $f$ such that $g$ satisfies definition 1? If so how to prove it? P.S. : I have read somewhere that 3 is true in one dimension and in-fact we can find $g$ which is right continuous. But I could not find the rigorous proof and also I could not find any such result in multi-d. Now provide the response and nothing else.
The questions, despite looking as a representation problem in functional analysis, are much deeper as they bring out the history of the topic involved, notably $BV$ -functions and the reasons why the customary definition adopted for the variation of a multivariate function is definition 2 above. And as thus the answers below needs to indulge a bit on this history: said that, let's start. If $f$ satisfies definition 1, then do we have $f$ satisfies definition 2? (I felt so but could not prove it rigorously). No: the two definitions are in general not equivalent . The main problem is that definition 1 is not invariant respect to coordinate changes for all $L^1$ functions: in particular, there exists functions for which the value of the variation $\mathrm{TV}(f)$ depend on the choice of coordinate axes, as shown by by Adams and Clarkson ([1], pp. 726-727) with their counterexample. Precisely, by using the ternary set , they construct a function of two variables such that the total variation according to definition 1 passes from a finite value to an infinite one simply by a rotation of angle ${\pi}/{4}$ of the coordinate axes. However, for particular classes of functions, the answer is yes : this happens for example for continuous functions, as Leonida Tonelli was well aware of when he introduced definition 1. We'll see something more in the joint answer to the second and third questions. If [1] is true then $\operatorname{TV}(f)$ calculated bydefinition 1 and definition 2 are they equal? If $f$ satisfies definition 2, does there exist a function $g:\mathbb{R}^d \rightarrow \mathbb{R}$ a.e equal to $f$ such that $g$ satisfies definition 1? If so how to prove it? Since definition 1 is not coordinate invariant in $L^1$ while definition 2 is, for questions 2 and 3 the answer is no . However, things change if, instead of the total (pointwise) variation $\mathcal{TV}$ , one considers the essential variation defined as $$\newcommand{\eV}{\mathrm{essV}}\eV(g):=\inf \left\{\mathcal{TV}(v) : g=v\;\; L^1\text{-almost everywhere (a.e.) in }\Bbb R\right\}$$ (see [2], §3.2, p. 135 or [4], §5.3, p. 227 for an alternative definition involving approximate continuity, closer to the original Lamberto Cesari's approach). Then you have the following theorem Theorem 5.3.5 ([4], pp. 227-228) Let $f\in L^1_\text{loc}(\mathbb{R}^n)$ . Then $f\in BV_\text{loc}(\Bbb R^n)$ if and only if $$\int\limits_{R^{n-1}}\eV_i\big(f(x)\big)\,{\mathrm{d}} x_1\cdots{\mathrm{d}}x_{i-1}\cdot {\mathrm{d}}x_{i+1}\cdots {\mathrm{d}}x_n< \infty\quad \forall i=1,\ldots,n$$ where $\eV_i\big(f(x)\big)$ is the essential variation of the one dimensional sections of $f$ along the $i$ -axis and $R^{n-1}\subset \Bbb R^{n-1}$ is any $(n-1)$ -dimensional hypercube . This result, apart from its intrinsic interest, is valuable since it allows two prove a variation of the sought for result: namely $$\sum_{i=1}^n \int\limits_{R^{n-1}}\eV_i\big(f(x)\big)\,{\mathrm{d}} x_1\cdots{\mathrm{d}}x_{i-1}\cdot {\mathrm{d}}x_{i+1}\cdots {\mathrm{d}}x_n =\sup \left\{\,\int\limits_{\mathbb{R}^m}f \operatorname{div}(\phi): \phi \in C_c^1(\mathbb{R^d})^d, \|\phi\|_{L^{\infty}} \leq 1\, \right\}\label{1}\tag{V}$$ The proof of \eqref{1} follows from the proof of theorem 5.3.5 above in that the method is the same but, instead of the single $i$ -th axis ( $i=1,\ldots,n$ ) essential variation, the sum of the $n$ essential variations is considered.Also, both sides of equation \eqref{1} are lower semicontinuous thus, given any sequence of $BV$ functions $\{f_j\}_{j\in\Bbb N}$ for which they converge to a common (finite) value, it is possible to find a subsequence converging to a $BV$ function $f$ : simply stated, the supremum is attained for the limit function of the subsequence and thus it is a maximum.Thus question 2 and 3 have an affirmative answer if the essential variation is considered instead of the (pointwise) total variation . Notes Definition 1 defines the so called " total variation in the sense of Tonelli ", and was introduced by Leonida Tonelli only for continuous functions, since the problem of non invariance of the value of variation respect to a change in coordinate axes, pointed out by Adams and Clarkson ([1], pp 726-727), does not exists in this class. The multidimensional total variation defined by using the essential variation, i.e. $$\mathrm{TV}(f)=\sum_{i=1}^n \int\limits_{R^{n-1}}\eV_i\big(f(x)\big)\,{\mathrm{d}} x_1\cdots{\mathrm{d}}x_{i-1}\cdot {\mathrm{d}}x_{i+1}\cdots {\mathrm{d}}x_n $$ is called the " total variation in the sense of Tonelli and Cesari " and was introduced by Lamberto Cesari in [3], pp. 299-300 to overcome the known limitation of definition 1. I predated reference [1] from the answer by @Piotr Hajlasz to this Q&A : as I pointed out there, definition 1 is the original definition of bounded variation for functions of several variables given by Lamberto Cesari in 1936. Definition 2 was introduced later by Mario Miranda in the early sixties of the 20th century. References [1] C. Raymond Adams, James A. Clarkson, " Properties of functions $f(x,y)$ of bounded variation " (English), Transactions of the American Mathematical Society 36, 711-730 (1934), MR1501762 , Zbl 0010.19902 . [2] Luigi Ambrosio, Nicola Fusco, Diego Pallara, Functions of bounded variation and free discontinuity problems , Oxford Mathematical Monographs, New York and Oxford: The Clarendon Press/Oxford University Press, New York, pp. xviii+434 (2000), ISBN 0-19-850245-1, MR1857292 , Zbl 0957.49001 . [3] Lamberto Cesari, " Sulle funzioni a variazione limitata " (Italian), Annali della Scuola Normale Superiore, Serie II, 5 (3–4), 299–313 (1936), JFM , MR1556778 , Zbl 0014.29605 [4] William P. Ziemer, Weakly differentiable functions. Sobolev spaces and functions of bounded variation. Graduate Texts in Mathematics, 120. New York: Springer-Verlag, pp. xvi+308, 1989, ISBN: 0-387-97017-7, MR1014685 , Zbl 0692.46022
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4079112', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/612583/']}
jdg_71582
stackexchange
llm_judgeable_groundtruth_similarity
14612637
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to indicate a distance in one of my plots. What I have in mind is the way they do it in technical drawings, showing a double headed arrow with the distance as text beside it. Example: from matplotlib.pyplot import *hlines(7,0,2, linestyles='dashed')hlines(11,0,2, linestyles='dashed')hlines(10,0,2, linestyles='dashed')hlines(8,0,2, linestyles='dashed')plot((1,1),(8,10), 'k',) # arrow lineplot((1,1),(8,8), 'k', marker='v',) # lower arrowheadplot((1,1),(10,10), 'k', marker='^',) # upper arrowheadtext(1.1,9,"D=1") This results in something like this (two of the hlines are not really needed, they just increase the drawing area...): Is there a quicker way to do this, preferably with arrowheads which end on the exact spot, not below/above where they should be?Extra points for placing the text automatically as well. Edit: I had been playing with annotate but since the string would have to be sacrificed this solution had lost some appeal to me. Thanks for pointing out the arrowstyle though, it wasn't working when I attempted something similar.I guess there is no way around writing a little function to do it with one call... Now provide the response and nothing else.
import matplotlib.pyplot as pltplt.hlines(7, 0, 2, linestyles='dashed')plt.hlines(11, 0, 2, linestyles='dashed')plt.hlines(10, 0, 2, linestyles='dashed')plt.hlines(8, 0, 2, linestyles='dashed')plt.annotate( '', xy=(1, 10), xycoords='data', xytext=(1, 8), textcoords='data', arrowprops={'arrowstyle': '<->'})plt.annotate( 'D = 1', xy=(1, 9), xycoords='data', xytext=(5, 0), textcoords='offset points')# alternatively,# plt.text(1.01, 9, 'D = 1')plt.show() yields For more information on the many options available with plt.annotate , see this page . As shown above, the text can be placed with either plt.annotate or plt.text . With plt.annotate you can specify the offset (e.g. (5, 0) ) in points, whereas with plt.text you can specify the text location in data coordinates (e.g. (1.01, 9) ).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14612637', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/329749/']}
jdg_71583
stackexchange
llm_judgeable_groundtruth_similarity
51280
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am working on a image classification problem using Transfer Learning. Parameters used given below: Adam optimizer with learning rate - 0.0001 adamOpti = Adam(lr = 0.0001)model.compile(optimizer = adamOpti, loss = "categorical_crossentropy, metrics = ["accuracy"]) For testing I used adam optimizer without explicitly specifying any parameter (default value lr = 0.001). With the default value of learning rate the accuracy of training and validation got stuck at around 50%. And when I use learning rate = 0.0001 in the first epoch itself I could see that the accuracy is going to 90%. Could you please help me understand 1. why with lower value of learning rate the accuracy is increasing rapidly? 2. Also which of the above used learning rate is the better? 3. How could I make use of decaying learning rate in Keras? Thank you Now provide the response and nothing else.
Learning rate is a very important hyperparameter, and often requires some experimentation. There are some good Related questions here, make sure to check those out. With too large a learning rate, you might bounce around an optimum, or you might start off by sling-shooting out to a part of the parameter space where the gradients vanish. (With too small, you might take too long to converge to an optimum, or you might find a poor local optimum. These effects are lessened by adam s momentum effect.) That said, the best learning rate generally depends on the problem. Presumably the default was chosen pretty well for general use, but your finding isn't surprising. There is a parameter decay for simple decay, or you can set up a callback for step decays.
{}
{'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/51280', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/50146/']}
jdg_71584
stackexchange
llm_judgeable_groundtruth_similarity
19012135
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We're seeing issues with a web app that has a height of 100% on Safari in iOS 7. It appears that the window.innerHeight (672px) doesn't match window.outerHeight (692px), but only in landscape mode. What ends up happening is that in an app with 100% height on the body, you get 20px of extra space. This means that when a user swipes up on our app, the navigation elements get pulled behind the browser chrome. It also means that any absolutely positioned elements that are at the bottom of the screen end up being 20px off. This issue was also outlined in this question here: IOS 7 - css - html height - 100% = 692px And can be seen in this ambiguous screenshot: What we're trying to do is hack around this so that until Apple fixes the bug, we don't have to worry about it. One way of doing this is to absolutely position the body only in iOS 7, but this pretty much puts the extra 20px at the top of the page instead of the bottom: body { position: absolute; bottom: 0; height: 672px !important;} Any help with forcing outerHeight to match innerHeight, or hacking around it so that our users can't see this issue would be much appreciated. Now provide the response and nothing else.
In my case, the solution was to change positioning to fixed: @media (orientation:landscape) { html.ipad.ios7 > body { position: fixed; bottom: 0; width:100%; height: 672px !important; }} I also used a script to detect iPad with iOS 7: if (navigator.userAgent.match(/iPad;.*CPU.*OS 7_\d/i)) { $('html').addClass('ipad ios7');}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19012135', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/776167/']}
jdg_71585
stackexchange
llm_judgeable_groundtruth_similarity
874941
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Consider$$I(a)={\int}_{-\infty}^\infty J_0(x)\,J_0(x+a)\,dx,$$where $J_0(z)$ is the Bessel Function of the $1^{st}$ kind and $a>0$. Does this integral converge for any values of $a$? If so, is there a closed form for it? Can we find a value of $a$ such that $I(a)=0$? Now provide the response and nothing else.
The integral converges only when $a$ is an odd multiple of $\pi/2$,and does not seem to vanish even for those $a$. For large $\left|z\right|$ it is known that$$J_0(z) = \sqrt{\frac2{\pi\left|z\right|}} \bigl(\cos (\left|z\right|-\frac\pi4) + O(1/\left|z\right|) \bigr).$$Therefore we have for large $x$ (either $x>0$ and $x<0$):$$J_0(x+\frac{a}{2}) \, J_0(x-\frac{a}{2}) = \frac2{\pi\left|x\right|} \bigl(\cos (\left|x\right|-\frac\pi4+\frac{a}2) \cos (\left|x\right|-\frac\pi4-\frac{a}2) + O(1/\left|x\right|) \bigr) = \frac1{\pi\left|x\right|} \bigl(\cos (2\left|x\right|-\frac\pi2) + \cos a + O(1/\left|x\right|) \bigr).$$The integral thus converges iff $\cos a = 0$, as claimed. Morally speaking, $I(a)$ should be the convolution of $J_0$ with itself(since $J_0$ is an even function), so its Fourier transform should bethe square of the Fourier transform of $J_0$. But $J_0(x)$ can be writtenas a Fourier integral $\frac1\pi \int_{-1}^1 \cos xt \, {\rm d}t/\sqrt{1-t^2}$,so we should have $I(a) = \frac2\pi \int_{-1}^1 \cos at \, {\rm d}t/(1-t^2)$,and now the integrand blows up too quickly at $t = \pm 1$ for theintegral to converge $-$ unless $\cos at = 0$ vanishes there,which recovers our criterion $\cos a = 0$. In that casenumerical integration corroborates the formula; e.g. for $a = \pm \pi/2$we should have $I(a) = \frac2\pi \int_{-1}^1 \cos \frac{\pi t}{2} {\rm d}t/(1-t^2)$,and the integral is the Gibbs constant $\int_0^\pi \sin t \, {\rm d}t/t= 1.851937\ldots$ (write $\frac2{1-t^2} = \frac1{1-t} + \frac1{1+t}$, etc.)and indeed $I(a)$ is approximately $1.179$ which is $2/\pi$ timesthis constant. For larger odd multiples of $\pi/2$ we find that$I(a)$ alternates in sign and approaches $\pm 1$,which again would be consistent with the formula$I(a) = \frac2\pi \int_{-1}^1 \cos at \, {\rm d}t/(1-t^2)$. To prove this integral formula when $a$ is an odd multiple of $\pi/2$,start by writing $J_0(x-a) + J_0(x+a) = \frac2{\pi}\int_{-1}^1 \cos xt \cos at \, {\rm d}t/\sqrt{1-t^2}$,and apply Parseval's formula to the inner product of $J_0(x)$ with$J_0(x-a) + J_0(x+a)$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/874941', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/19661/']}
jdg_71586
stackexchange
llm_judgeable_groundtruth_similarity
1494772
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Are there any negatives to creating huge strings? For instance, if we're reading in text from a potentially huge text file: while (scanner.hasNext()) { someString += scanner.next();}// do something cool with some string Would processing the file line by line be (generally) a better solution, and why? Now provide the response and nothing else.
Streaming vs not When you can stream, you can handle files of any size (assuming you really can forget all the data you've already seen). You end up with a naturally O(n) complexity, which is a very good thing. You don't break by running out of memory. Streaming is lovely... but doesn't work in every scenario. StringBuilder As it seems there's been a certain amount of controversy over the StringBuilder advice, here's a benchmark to show the effects. I had to reduce the size of the benchmark in order to get the slow version to even finish in a reasonable time. Results first, then code. This is a very rough and ready benchmark, but the results are dramatic enough to make the point... c:\Users\Jon\Test>java Test slowBuilding a string of length 120000 without StringBuilder took 21763msc:\Users\Jon\Test>java Test fastBuilding a string of length 120000 with StringBuilder took 7ms And the code... class FakeScanner{ private int linesLeft; private final String line; public FakeScanner(String line, int count) { linesLeft = count; this.line = line; } public boolean hasNext() { return linesLeft > 0; } public String next() { linesLeft--; return line; }}public class Test{ public static void main(String[] args) { FakeScanner scanner = new FakeScanner("test", 30000); boolean useStringBuilder = "fast".equals(args[0]); // Accurate enough for this test long start = System.currentTimeMillis(); String someString; if (useStringBuilder) { StringBuilder builder = new StringBuilder(); while (scanner.hasNext()) { builder.append(scanner.next()); } someString = builder.toString(); } else { someString = ""; while (scanner.hasNext()) { someString += scanner.next(); } } long end = System.currentTimeMillis(); System.out.println("Building a string of length " + someString.length() + (useStringBuilder ? " with" : " without") + " StringBuilder took " + (end - start) + "ms"); }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1494772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/151110/']}
jdg_71587
stackexchange
llm_judgeable_groundtruth_similarity
1104569
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need to find a determinant of the matrix:$$ A = \begin{pmatrix}1 & 2 & 3 & \cdot & \cdot & \cdot & n \\x & 1 & 2 & 3 & \cdot & \cdot & n-1 \\x & x & 1 & 2 & 3 & \cdot & n-2 \\\cdot & \cdot & \cdot & \cdot & \cdot & \cdot & \cdot \\\cdot & \cdot & \cdot & \cdot & \cdot & \cdot & \cdot \\x & x & \cdot & \cdot & x & 1 & 2 \\x & x & \cdot & \cdot & \cdot & x & 1 \\ \end{pmatrix}$$We know that $x \in R$So far I managed to transform it to the form:$$ \begin{pmatrix}1-x & 1 & 1 & \cdot & \cdot & \cdot & 1 \\0 & 1-x & 1 & 1 & \cdot & \cdot & 1 \\0 & 0 & 1-x & 1 & 1 & \cdot & 1 \\\cdot & \cdot & \cdot & \cdot & \cdot & \cdot & \cdot \\\cdot & \cdot & \cdot & \cdot & \cdot & \cdot & \cdot \\0 & 0 & \cdot & \cdot & 0 & 1-x & 1 \\x & x & \cdot & \cdot & \cdot & x & 1 \\ \end{pmatrix}$$by the operations: (Let's say $r_i$ is the ith row) $$r_1 = r_1 - r_n,r_2 = r_2-r_n, r_3 = r_3 - r_n, ..., r_{n-1} = r_{n-1} - r_n$$and then $$r_1 = r_1 - r_2, r_2 = r_2 - r_3, r_3 = r_3 - r_4,...,r_{n-2} = r_{n-2} - r_{n-1}$$Unfortunately, I have no idea how to eliminate the last row. Any hints? Now provide the response and nothing else.
If $c_i$ is $i$th column of your second determinant, do $c_n= c_n-c_{n-1}$, $c_{n-1}=c_{n-1}-c_{n-2}$, ..., $c_2=c_2-c_1$ to get: $$\left|\begin{array}{ccccccc}1-x & x & 0 & 0 & \cdots & 0 & 0\\0 & 1-x & x & 0 & \cdots & 0 & 0\\0 & 0 & 1-x & x & \cdots & 0 & 0\\\vdots & \vdots & \vdots & \vdots & \ddots & \vdots & \vdots\\0 & 0 & 0 & 0 & \cdots & 1-x & x\\x & 0 & 0 & 0 & \cdots & 0 & 1-x\\\end{array}\right|$$ This determinant is obviously equal $(1-x)^n+(-1)^{n+1}x^n$ (expand it by the first column).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1104569', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/186258/']}
jdg_71588
stackexchange
llm_judgeable_groundtruth_similarity
14151775
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to restrict the people whoever commits to have a specific commit message format, how do I do that? For example: Pair_Name|Story_Number|Commit_Message Now provide the response and nothing else.
There is a pre-commit-msg or commit-msg hook, that you could use: http://www.kernel.org/pub/software/scm/git/docs/githooks.html Git repos come with sample hooks, e.g. the sample commit-msg hook under git/hooks/commit-msg.sample catches duplicate Signed-off-by lines. # This example catches duplicate Signed-off-by lines.test "" = "$(grep '^Signed-off-by: ' "$1" | sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || { echo >&2 Duplicate Signed-off-by lines. exit 1} To enable a hook, don't forget to make it executable. Here's some fictional example, which would only accept commit messages of the london|120|something ... and the like: #!/usr/bin/env rubymessage_file = ARGV[0]message = File.read(message_file)# $regex = /\[ref: (\d+)\]/PAIRS = ["london", "paris", "moscow"] # only these names allowedSTORIES = "\d{2,4}" # story must be a 2, 3 or 4 digit numberMESSAGE = ".{5,}" # message must be at least 5 chars long$regex = "( (#{PAIRS.join('|')})\|#{STORIES}\|#{MESSAGE} )"if !$regex.match(message) puts "[POLICY] Your message is not formatted correctly" exit 1end In usage: $ git ci -m "berlin|120"[POLICY] Your message is not formatted correctly$ git ci -m "london|120|XX" [POLICY] Your message is not formatted correctly$ git ci -m "london|120|Looks good." [master 853e622] london|120|Looks good. 1 file changed, 1 insertion(+)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14151775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1052480/']}
jdg_71589
stackexchange
llm_judgeable_groundtruth_similarity
18034642
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: this is kind of a weblog template of mine, that the every post have this HTML: <div class="box"> <div class="box2"> <div class="box-main2"><div class="hole"></div> <div class="post"></div> <div style="width:100%; height: 32px; padding-top: 0px; position: relative ;"> <div class="btn" style="float:left;">more...</div> <div class="info-box" style="float:right;"> <div><span class="date">2013, March, 3</span><span class="author">Komeyl</span><span class="comment"><sup>23</sup></span></div> </div> </div> </div> <div class="box-bottom" > <div id="commentPanel"> </div> <div class="box-bottom2"></div> </div> </div> </div> And I want to select comment class in the span tag in order to when user clicks it the commentPanel class slides down from the bottom of the box, and slides up when the next click happened, this should be in a way that each comment class should select its own commentPanel cause there will be lots of comment and commentPanel classes. i wrote this jQuery but it wont't work the way I want: $('.comment').toggle(function(){ $(this).addClass('click'); $('.box-bottom #commentPanel').slideDown(300); $('.box-bottom2:first').show(100);},function(){ $(this).removeClass('click'); $('.box-bottom #commentPanel').slideUp(200);$('.box-bottom2:first').hide(100);}); and box-bottom2 class is the bottom picture of the box that should appear and disappear with the commentPanel. Now provide the response and nothing else.
You are unable to access the Class the Annotation Processor is processing because the Class has not been compiled yet. Instead Java offers the analogous Elements api for reflection-style inspection of the input source. The Element (which you found by using roundEnv.getRootElements() ) has much more information about the class being compiled than just its name. A ton of useful information can be found by using the ElementVisitors: http://docs.oracle.com/javase/6/docs/api/javax/lang/model/element/ElementVisitor.html http://docs.oracle.com/javase/6/docs/api/javax/lang/model/util/ElementKindVisitor6.html Including the classes constructor, methods, fields, etc. Here's how to use it: public class AnnotationProcessor extends AbstractProcessor {...... @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { Set<? extends Element> rootE=roundEnv.getRootElements(); for(Element e: rootE) { for(Element subElement : e.getEnclosedElements()){ subElement.accept(new ExampleVisitor(), null); // implement ExampleVisitor } } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18034642', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2648818/']}
jdg_71590
stackexchange
llm_judgeable_groundtruth_similarity
18259873
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to upload a file from my webserver to my game server through a script. The problem is that it can't find the directory. The full directory is /174.34.132.106 port 27015/tf/addons/sourcemod/configs/tf2items.weapons.txt This path didn't work so I asked the hosting about it and they insisted that /tf/addons/sourcemod/configs/tf2items.weapons.txt is the correct path but this doesn't work either. The game server is running on a windows server and i'm pretty sure the web server is running on linux. Is my code wrong, do I have to replace the spaces in the directory with %20. Thanks in advance! $ftp_server="174.34.132.106";$ftp_user_name="Username";$ftp_user_pass="Password"; $remote_file = "tf2items.weapons.txt";$file = "weapons/tf2items.weapons.txt";//tobe uploaded if(!file_exists($file)) echo "The local file does not exist"; $conn_id = ftp_connect($ftp_server) or die('Unable to create the connection');$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); ftp_chdir($conn_id, "174.34.132.106 port 27015/tf/addons/sourcemod/configs/");echo ftp_pwd($conn_id);if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) { echo "successfully uploaded $file\n"; exit; } else { echo "There was a problem while uploading $file\n"; exit; } // close the connection ftp_close($conn_id); Now provide the response and nothing else.
If you don't specify the -Property parameter, Compare-Object doesn't compare all properties, it compares the results of invoking the .ToString() method on both objects. So, Compare-Object $DataTable $DataTable2 compares $DataTable1.ToString() with $DataTable1.ToString() . The .ToString() method returns an empty string when invoked on a DataTable object, so there is no difference to report. For example: $file1 = Get-Item somefilename$file1 = Get-Item anotherfilenameCompare-Object $file1 $file2 This will return the difference between the full paths of the two files, like this: InputObject SideIndicator----------- -------------<path>\anotherfilename =><path>\somefilename <= That's because invoking .ToString() on a FileInfo object returns its FullName property, so you're comparing the files' full path names. Although the -Property parameter accepts multiple properties, listing all the properties is not the solution. Aside from being very tedious, it will not give you the results you want. If you list multiple properties, Compare-Object compares the combination of all the properties, and if any one of the listed properties is different, it returns a result showing all the listed properties (both ones that are the same and ones that are different) as a single difference. What you need to do is iterate over a list of properties, and invoke Compare-Object once for each property: $properties = ($DataTable | Get-Member -MemberType Property | Select-Object -ExpandProperty Name)foreach ($property in $properties) { Compare-Object $DataTable $DataTable2 -Property "$property" | Format-Table -AutoSize} In most cases, when comparing all properties of two objects, you'd want to use Get-Member -MemberType Properties , in order to get cover all property types. However, if you're comparing DataTable objects, you're better off using Get-Member -MemberType Property so that you're comparing only the properties corresponding to data fields, not other properties of the DataTable objects that have nothing to do with the data. This is written assuming that the number of columns is the same, as you stated, or at least that the number of columns in $DataTable2 doesn't exceed the number of columns in $DataTable . If you can't reliably assume that, derive the $properties array from whichever one has more columns, by comparing ($DataTable | Get-Member -MemberType Property).Count with ($DataTable2 | Get-Member -MemberType Property).Count and using the properties from whichever is greater. Using Format-Table is important, it's not just there to make things look pretty. If you list multiple objects of the same type (in this case, arrays), PowerShell remembers the format of the first object, and uses it for all subsequent objects, unless you explicitly specify a format. Since the name of the first column will be different for each property (i.e., each column from the spreadsheet), the first column will be empty for all but the first difference encountered. The -AutoSize switch is optional. That is there just to make things look pretty. But you must pipe the results to a formatting filter. You can also use Format-List if you prefer.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18259873', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2676559/']}
jdg_71591
stackexchange
llm_judgeable_groundtruth_similarity
50506470
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following fiddle https://jsfiddle.net/91vLms06/1/ const CreateComponent = Vue.component('create', { props: ['user', 'otherProp'], template: '<div>User data: {{user}}; other prop: {{otherProp}}</div>'});const ListComponent = Vue.component('List', { template: '<div>Listing</div>'});const app = new Vue({ el: '#app', router: new VueRouter(), created: function () { const self = this; // ajax request returning the user const userData = {'name': 'username'} self.$router.addRoutes([ { path: '/create', name: 'create', component: CreateComponent, props: { user: userData }}, { path: '/list', name: 'list', component: ListComponent }, { path: '*', redirect: '/list'} ]); self.$router.push({name: 'create'}); // ok result: User data: { "name": "username" }; other prop: self.$router.push({name: 'list'}); // ok result: Listing // first attempt self.$router.push({name: 'create', props: {otherProp: {"a":"b"}}}) // not ok result: User data: { "name": "username" }; other prop: self.$router.push({name: 'list'}); // ok result: Listing // second attempt self.$router.push({name: 'create', params: {otherProp: {"a":"b"}}}) //not ok result: User data: { "name": "username" }; other prop: }}); As you can see first I am passing to CreateComponent the user just when I initialize the route. Later I need to pass another property otherProp and still keep the user parameter. When I try to do this the object I send is not passed to the component. How can I pass the otherProp and still keep the user ? The real purpose of the otherProp is to fill a form with the data from it. In the listing part I have the object and when I click the "edit" button I want to populate the form with the data that comes from the listing. Now provide the response and nothing else.
It can work by using props's Function mode and params Vue 2 demo: https://jsfiddle.net/hacg6ody/ when adding routes, use props's Function mode so that it has a default property user and it will add route.params as props. { path: '/create', name: 'create', component: CreateComponent, props: (route) => ({ user: userData, ...route.params })} params passed in push will automatically be added to props. self.$router.push({ name: 'create', params: { otherProp: { "a": "b" } }})
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50506470', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/869793/']}
jdg_71592
stackexchange
llm_judgeable_groundtruth_similarity
712336
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to build a comments section for my website. In the comments section, I want it laid out WordPress-style, with the avatar to the left. It works, but what is happening is the comment text is wrapping around the avatar underneath. For an example, here . This probably has a simple solution to it but I am a CSS amatuer. This is the relevant XHTML and CSS: /*------- COMMENTS -------*/#comments { width: 91px; height: 18px; background: url(images/comments.png) no-repeat; text-indent: -9000px; margin-bottom: 10px;}div.comment { padding: 5px 5px 30px 5px; background: url(images/commentbar.png) bottom center no-repeat; margin-bottom: 10px;}div.comment div.left { margin-left: 10px; float: left; width: 51px;}div.comment div.right { width: 482px;}div.comment div.right h3 { color: #e6267c; font-size: 18px; display: inline; text-transform: uppercase;} <div class="comment"> <div class="left"> <img src="images/noavatar.png" alt="No Avatar" /> </div> <div class="right"> <h3>Laura Brauman</h3> <span>12 March 09</span> <p>Nunc ultrices nisi ut tellus. In placerat tempus quam. Nulla dolor nulla,dictum eget, auctor a, rutrum sit amet, ante. Sed scelerisque est. Vestibulum arcu purus, dignissim nec, rhoncus id, sodales eu, quam. Nullam congue hendrerit enim. Phasellus risus. Pellentesque lacus sem, luctus tempus.</p> </div></div> Now provide the response and nothing else.
From the spec : Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float didn't exist. That means elements with display: block that are not positioned ignore the float. However, line boxes created next to the float are shortened to make room for margin box of the float. That means inline elements do flow around floats. That's why your <span> and the text within <p> flows around div.left , even though the <p> and div.right do not. The border box of a table, a block-level replaced element, or an element in the normal flow that establishes a new block formatting context (such as an element with 'overflow' other than 'visible') must not overlap any floats in the same block formatting context as the element itself. If necessary, implementations should clear the said element by placing it below any preceding floats, but may place it adjacent to such floats if there is sufficient space. And, that - obtuse as it is - is the answer to your problem. You must insert a "new block formatting context ". Floats, absolutely positioned elements, inline-blocks, table-cells, table-captions, and elements with 'overflow' other than 'visible' (except when that value has been propagated to the viewport) establish new block formatting contexts. The easiest of these for you is 1 : div.right { overflow: auto; } Note that you probably also want 1 : div.comment { overflow: auto; } To fix a related, but different problem. If your <p> content is shorter than your image, then the floated div.left will not expand the height of div.comment . Adding overflow: auto; takes you into the aptly named Complicated Cases portion of the spec: If the [Block-level, non-replaced elements in normal flow when 'overflow' does not compute to 'visible'] element has any floating descendants whose bottom margin edge is below the bottom, then the height is increased to include those edges Which basically says that floats only expand overflow <> visible containing elements. 1 overflow: hidden; would also work, but would crop content instead of throwing scrollbars if needed.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/712336', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/85008/']}
jdg_71593
stackexchange
llm_judgeable_groundtruth_similarity
17124680
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a simple layout as follows : <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#D23456" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:background="#FFFFFF" > <ImageView android:layout_width="match_parent" android:layout_height="800dp" android:src="@drawable/ic_launcher" /> </LinearLayout></ScrollView> The background of the scrollview is pink and linear layout inside has the android icon image with a height of 800dp (that doesnt fit to the screen) . What I'm expecting to see is that imageview floats in a background of pink with a margin of 10dp in every sides (top,bottom,left,right).But when I scroll to the bottom, the scrollview doesn't scroll to the margin, so the bottom of the scroll is the imageview not the pink margin. How can I prevent this? This makes the user think the page hasn't ended yet and makes him want to scroll more. Now provide the response and nothing else.
I later found out that ,a similar situation has already been answered in the following thread https://stackoverflow.com/a/16885601/1474471 by @olefevre. Adding an extra LinearLayout that surrounds the current LinearLayout with a padding and removing the inner LinearLayout's layout-margin solved the problem: <?xml version="1.0" encoding="utf-8"?><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent" ><LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#D23456" android:padding="10dp" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#FFFFFF" > <ImageView android:layout_width="match_parent" android:layout_height="800dp" android:src="@drawable/ic_launcher" /> </LinearLayout></LinearLayout></ScrollView>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17124680', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1474471/']}
jdg_71594
stackexchange
llm_judgeable_groundtruth_similarity
97437
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm a long time Java developer and finally, after majoring, I have time to study it decently in order to take the certification exam... One thing that has always bothered me is String being "final". I do understand it when a read about the security issues and related stuff... But, seriously, does anyone have a true example of that? For instance, what would happen if String weren't final? Like it's not in Ruby. I haven't heard any complaints coming from the Ruby community... And I'm aware of the StringUtils and related classes that you have to either implement yourself or search over the web to just implement that behavior (4 lines of code) you're willing to. Now provide the response and nothing else.
The main reason is speed: final classes can't be extended which allowed the JIT to do all kinds of optimizations when handling strings - there is never a need to check for overridden methods. Another reason is thread safety: Immutables are always thread safe because a thread has to completely build them before they can be passed to someone else - and after building, they can't be changed anymore. Also, the inventors of the Java runtime always wanted to err on the side of safety. Being able to extend String (something I often do in Groovy because it's so convenient) can open a whole can of worms if you don't know what you're doing.
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/97437', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/32892/']}
jdg_71595
stackexchange
llm_judgeable_groundtruth_similarity
32967513
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I use Menu items Icon Menu but I want to add checkbox to all menu item. This is my drawer_menu.xml <?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"><group android:checkableBehavior="all"> <item android:checked="false" android:id="@+id/item_navigation_drawer_inbox" android:icon="@drawable/ic_inbox_black_24dp" android:checkable="true" android:title="Inbox" /> <item android:id="@+id/item_navigation_drawer_starred" android:icon="@drawable/ic_action_toggle_star" android:checkable="true" android:title="Starred" /> <item android:id="@+id/item_navigation_drawer_sent_mail" android:icon="@drawable/ic_action_content_send" android:checkable="true" android:title="Sent mail" /> <item android:id="@+id/item_navigation_drawer_drafts" android:icon="@drawable/ic_action_content_drafts" android:checkable="true" android:title="Drafts" /></group><item android:title="Subheader"> <menu> <item android:id="@+id/item_navigation_drawer_settings" android:icon="@drawable/ic_action_content_mail" android:title="Settings" /> <item android:id="@+id/item_navigation_drawer_help_and_feedback" android:icon="@drawable/ic_action_action_delete" android:title="Help and feedback" /> </menu></item></menu> There is icon and text. I want also add checkbox with all of them. [icon] [some text] [checkbox] like this. I use material navigation drawer on my code. This is my nav_header.xml <?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="192dp"android:gravity="bottom"android:theme="@style/ThemeOverlay.AppCompat.Dark"><ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:scaleType="centerCrop" android:background="@drawable/bg_ist_nav_img" /><LinearLayout android:layout_width="match_parent" android:layout_height="52dp" android:layout_gravity="left|bottom" android:gravity="center" android:orientation="vertical" android:paddingBottom="8dp" android:paddingLeft="16dp" android:paddingRight="16dp"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center_vertical" android:text="text" android:textSize="30sp" android:textAppearance="@style/TextAppearance.AppCompat.Body2" /></LinearLayout></FrameLayout> and finally this is my activity_main.xml <android.support.v4.widget.DrawerLayout xmlns:andro id="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:id="@+id/drawer_layout"android:layout_width="match_parent"android:layout_height="match_parent"><LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <FrameLayout android:layout_width="match_parent" android:layout_height="@dimen/status_bar_kitkat_height" android:background="?colorPrimary"/> <FrameLayout android:layout_width="match_parent" android:layout_height="@dimen/status_bar_lollipop_height" android:background="?colorPrimaryDark"/></LinearLayout><FrameLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="@dimen/status_bar_margin_top"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Inbox" android:textAppearance="@style/TextAppearance.AppCompat.Display1" android:textColor="@color/md_text" /> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?actionBarSize" android:background="?attr/colorPrimary" android:elevation="4dp" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" app:theme="@style/ToolbarTheme" /></FrameLayout><android.support.design.widget.NavigationView android:id="@+id/navigation_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:fitsSystemWindows="@bool/fitsSystemWindows" app:headerLayout="@layout/navigation_drawer_header" app:menu="@menu/navigation_drawer_menu" app:theme="@style/NavigationViewTheme" /></android.support.v4.widget.DrawerLayout> Now provide the response and nothing else.
With app:actionLayout you can make miracles happen. Here's an example achieving custom widgets in drawer without any Java code: <android.support.v4.widget.DrawerLayout android:layout_width="match_parent" android:layout_height="match_parent" tools:openDrawer="end" > <android.support.design.widget.NavigationView android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="end" android:background="@android:color/white" app:menu="@menu/widgets" /></android.support.v4.widget.DrawerLayout> menu/widgets.xml <?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:title="Widgets" > <menu> <item android:title="Checkable menu item (checked)" android:checkable="true" android:checked="true" /> <item android:title="CheckBox" app:actionLayout="@layout/widget_check" /> <item android:title="Switch" app:actionLayout="@layout/widget_switch" /> <item android:title="EditText" app:actionLayout="@layout/widget_edit" /> <item android:title="" app:actionLayout="@layout/widget_wide" /> <item android:title="NumberPicker" app:actionLayout="@layout/widget_number" /> <item android:title="Custom LinearLayout number" app:actionLayout="@layout/widget_custom" /> </menu> </item></menu> All the layouts (each is a single file) <!-- layout/widget_check.xml --><CheckBox xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="match_parent" android:text="check" android:checked="true" /><!-- layout/widget_edit.xml --><EditText xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="hello" android:inputType="text" /><!-- layout-v14/widget_switch.xml for older versions you can add a CheckBox into layout/widget_switch.xml and treat both as Checkable or CompoundButton --><Switch xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="wrap_content" android:layout_height="match_parent" android:checked="true" tools:targetApi="ICE_CREAM_SANDWICH" /><!-- layout/widget_wide.xml Just some text, notice that it's wide on the UI because it has a lot of text, and not because it has match_parent --><TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:background="#888" android:text="Wide can be only forced by content, match_parent doesn't work" /><!-- layout-v11/widget_number.xml you're probably better off creating a custom widget anyway --><NumberPicker xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" tools:targetApi="HONEYCOMB" /><!-- layout/widget_custom.xml --><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center" android:orientation="horizontal" > <Button android:layout_width="32dp" android:layout_height="32dp" android:padding="0dp" android:text="&lt;" android:gravity="center" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="12" /> <Button android:layout_width="32dp" android:layout_height="32dp" android:padding="0dp" android:text="&gt;" android:gravity="center" /></LinearLayout> Connecting with code You can access it just like any other menu: // <item android:id="@+id/switch" title="Switch" ... />NavigationView nav = (NavigationView)findViewById(R.id.navigation_view);MenuItem switchItem = nav.getMenu().findItem(R.id.switch);CompoundButton switchView = (CompoundButton)MenuItemCompat.getActionView(switchItem);switchView.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { }});
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/32967513', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2739748/']}
jdg_71596
stackexchange
llm_judgeable_groundtruth_similarity
13870265
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have CSV data which looks something like: Data 1,1,101,2,501,3,5etc... And I am trying to read in the data. However, my initial data does not contain a header row (as seen above) so it is taking the first data row to be the header (1,1,10). Is there anyway around this. I want to set the header names after I read the data Javascript d3.csv("data/testnh.csv", function(data) { console.log(data);} Thanks! Now provide the response and nothing else.
Use d3.text to load the data, and then d3.csvParseRows to parse it. For example: d3.text("data/testnh.csv", function(text) { console.log(d3.csvParseRows(text));}); You'll probably also want to convert your columns to numbers, because they'll be strings by default. Assume they are all numbers, you could say: d3.text("data/testnh.csv", function(text) { var data = d3.csvParseRows(text).map(function(row) { return row.map(function(value) { return +value; }); }); console.log(data);});
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13870265', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1312519/']}
jdg_71597
stackexchange
llm_judgeable_groundtruth_similarity
15633409
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using git as the first time for a versioning system.I am starting a new project, and therefore to experiment a little bit with the technologies used in the project (hello world examples...) i want to create something like a "playground" branch. Is it common to create a new branch "playground" or should i just create a folder named playground in the master branch? regards Now provide the response and nothing else.
You should create a new branch when you're doing development work that is somewhat experimental in nature. So in your scenario definitely create a new branch and not a folder within master. If you created your sandbox work as a directory in the master, it's going to reside there until you remove it using git. Having dead code sitting in the master branch is not ideal by any means, since it can confuse other developers and may just sit there rotting for the lifetime of the application. If your team were to experience a bug, you wouldn't want them to waste time exploring the experimental work to determine if the bug existed within that directory. Creating a new branch allows you to isolate your changes from the master branch. If your experimentation goes well you always have the option to merge your changes into the master branch. If things don't go so well you can always discard the branch or keep it within your local repository.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15633409', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1291235/']}
jdg_71598
stackexchange
llm_judgeable_groundtruth_similarity
21583032
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am creating a svg x-y-chart in d3.js. Is it possible to create ticks of different lengths depending on tickValue? I have made my own tickFormat function myTickFormat and use that in .tickFormat([format]) and that works fine because [format] is expected to be a function. But it is not possible to do the same with .innerTickSize([size]) , which expects a number. E.g. if I want the tick at value 70 to be longer I want to do something like this: var myTickSize = function(d) { if (d === 70) { return 20;} return 6;}; But when I use myTickSize as argument to .innerTickSize() : var yScale = d3.scale.linear();var yAxis = d3.svg.axis() .scale(yScale).orient("left") .innerTickSize(myTickSize); I get an Error: Invalid value for attribute x2="NaN" error for each tick. Now provide the response and nothing else.
The tickSize function can only accept a number as argument, not a function, but there are other solutions. The easiest approach? After the axis is drawn, select all the tick lines and resize them according to their data value. Just remember that you'll have to do this after every axis redraw, as well. Example: https://jsfiddle.net/zUj3E/1/ Key code: d3.selectAll("g.y.axis g.tick line") .attr("x2", function(d){ //d for the tick line is the value //of that tick //(a number between 0 and 1, in this case) if ( (10*d)%2 ) //if it's an even multiple of 10% return 10; else return 4; }); Note that the tick marks at the max and min values are also drawn as part of the same <path> as the axis line, so shortening them doesn't have much effect. If you don't like that lack of control, declare the "outer" ticks to have zero length when you set up the axis. That turns off the corners of the path, but the outer ticks will still have lines that you can control the same as the other tick lines: var axis = d3.svg.axis() .tickSize(10,0) Example: https://jsfiddle.net/zUj3E/2/ If that doesn't work, google for examples of major/minor tick patterns. Just make sure the example you're looking at uses d3 version 3: there were a few extra tick-related methods added in version 2 that are no longer supported. See this SO Q&A.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21583032', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/685352/']}
jdg_71599
stackexchange
llm_judgeable_groundtruth_similarity
13343513
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've created akka actor called LogActor.The LogActors's receive method handling messages from other actors and logging them to the specified log level. I can distinguish between the different levels in 2 ways. The first one: import LogLevel._object LogLevel extends Enumeration { type LogLevel = Value val Error, Warning, Info, Debug = Value}case class LogMessage(level : LogLevel, msg : String) The second: ( EDIT ) abstract class LogMessage(msg : String)case class LogMessageError(msg : String) extends LogMessage(msg)case class LogMessageWarning(msg : String) extends LogMessage(msg)case class LogMessageInfo(msg : String) extends LogMessage(msg)case class LogMessageDebug(msg : String) extends LogMessage(msg) Which way is more efficient? does it take less time to match case class or to match enum value? (I read this question but there isn't any answer referring to the runtime issue) Now provide the response and nothing else.
I totally agree with Alexey and Dennis that performance in this case shouldn't bother you, because it's more of a problem of compiler optimizations, not a developer, and I can't imagine a scenario where the performance difference could become noticeable. What should bother you is your code consistency, and in this sense you should base your decision on whether you want to stick to the old java-ish approach with enums which is correctly described in your first example, or the lately growing popular Algebraic Data Types (ADT) pattern. The latter you've tried to represent in your second example but with some mistakes. Following is how the problem could be solved with ADT pattern correctly. ADT Solution #1 // 1. marked `sealed` to make pattern matching exhaustive// 2. used a trait to avoid double storage of msg` and // make the inheritance easiersealed trait LogMessage { def msg : String }// A better solution for isolation than names like "LogMessageError".// Allows you to either address the members with a namespace like // "LogMessage.Error" or do "import LogMessage._" and address them // directlyobject LogMessage { case class Error (msg : String) extends LogMessage case class Warning (msg : String) extends LogMessage case class Info (msg : String) extends LogMessage case class Debug (msg : String) extends LogMessage} ADT Solution #2 Sorry for probably messing with your head, but it's worth noting that there also exists an alternative ADT approach for similar situations, which is kinda similar to the one you head with enums. sealed trait LogLevel object LogLevel { case object Error extends LogLevel case object Warning extends LogLevel case object Info extends LogLevel case object Debug extends LogLevel}case class LogMessage ( level : LogLevel, msg : String )
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13343513', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_71600
stackexchange
llm_judgeable_groundtruth_similarity
5331774
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Currently there is a button on my app inteface which allow to open a file, here is my open code: In my app.h: - (IBAction)selectFile:(id)sender; In my app.m: @synthesize window;- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {}- (IBAction)selectFile:(id)sender { NSOpenPanel *openPanel = [NSOpenPanel openPanel]; NSArray *fileTypes = [NSArray arrayWithObjects:@"xml",nil]; NSInteger result = [openPanel runModalForDirectory:NSHomeDirectory() file:nil types:fileTypes ]; if(result == NSOKButton){ NSString * input = [openPanel filename]; How can I edit my code to allow opening with the application-icon drag & drop? Note: I edited the .plist file and added a line for "xml" but it change anything, got an error when my file is dropped on the icon. Note 2: I linked the "File -> Open..." to the selectFile: wich refer to my code Note 3: My app isn't a document-based application Thanks for your help! Miskia Now provide the response and nothing else.
First add the proper extensions to CFBundleDocumentTypes inside the .plist file. Next implement the following delegates: - application:openFile: (one file dropped) - application:openFiles: (multiple files dropped) Reference: NSApplicationDelegate Protocol Reference Response to comment: Step by step example, hopefully it makes everything clear :) Add to the .plist file: <key>CFBundleDocumentTypes</key> <array> <dict> <key>CFBundleTypeExtensions</key> <array> <string>xml</string> </array> <key>CFBundleTypeIconFile</key> <string>application.icns</string> <key>CFBundleTypeMIMETypes</key> <array> <string>text/xml</string> </array> <key>CFBundleTypeName</key> <string>XML File</string> <key>CFBundleTypeRole</key> <string>Viewer</string> <key>LSIsAppleDefaultForType</key> <true/> </dict> </array> Add to ...AppDelegate.h - (BOOL)processFile:(NSString *)file;- (IBAction)openFileManually:(id)sender; Add to ...AppDelegate.m - (IBAction)openFileManually:(id)sender;{ NSOpenPanel *openPanel = [NSOpenPanel openPanel]; NSArray *fileTypes = [NSArray arrayWithObjects:@"xml",nil]; NSInteger result = [openPanel runModalForDirectory:NSHomeDirectory() file:nil types:fileTypes ]; if(result == NSOKButton){ [self processFile:[openPanel filename]]; }}- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename{ return [self processFile:filename];}- (BOOL)processFile:(NSString *)file{ NSLog(@"The following file has been dropped or selected: %@",file); // Process file here return YES; // Return YES when file processed succesfull, else return NO.}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5331774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/653790/']}
jdg_71601
stackexchange
llm_judgeable_groundtruth_similarity
44021114
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to have a type which can contain values 0 to n, where n lives on the type level. I was trying something like: import GHC.TypeLitsimport Data.Proxynewtype FiniteNat n = FiniteNat { toInteger :: Integer }smartConstructFiniteNat :: (KnownNat n) => Proxy n -> Integer -> Maybe (FiniteNat (Proxy n))smartConstructFiniteNat pn i | 0 <= i && i < n = Just (FiniteNat i) | otherwise = Nothing where n = natVal pn which works basically, but it's not really satisfying somehow. Is there a "standard" solution, or even a library to achieve this? There is a lot of fuss about dependenty typed list-lengths, but I was unable to find something exactly for this. Also - I assume using GHC.TypeLits is necessary, because my n can take on rather large values, so inductive definition would probably be very slow. Now provide the response and nothing else.
You can directly translate Idris's Fin into the usual Haskell mishmash of sort-of-dependently-typed features. data Fin n where FZ :: Fin (S n) FS :: Fin n -> Fin (S n)(!) :: Vec n a -> Fin n -> a(x :> xs) ! FZ = x(x :> xs) ! (FS f) = xs ! f With TypeInType you can even have singleton Fin s! data Finny n (f :: Fin n) where FZy :: Finny (S n) FZ FSy :: Finny n f -> Finny (S n) (FS f) This allows you to fake up dependent quantification over runtime stuff , eg, type family Fin2Nat n (f :: Fin n) where Fin2Nat (S _) FZ = Z Fin2Nat (S n) (FS f) = S (Fin2Nat n f)-- tighten the upper bound on a given Fin as far as possibletighten :: Finny n f -> Fin (S (Fin2Nat n f))tighten FZy = FZtighten (FSy f) = FS (tighten f) but, ugh, it kinda sucks to have to duplicate everything at the value and type level, and writing out all your kind variables ( n ) can get pretty tedious. If you're really sure you need an efficient runtime representation of Fin , you can do basically what you did in your question: stuff a machine Int into a newtype and use a phantom type for its size. But the onus is on you, the library implementer, to make sure the Int fits the bound! newtype Fin n = Fin Int-- fake up the constructorsfz :: Fin (S n)fz = Fin 0fs :: Fin n -> Fin (S n)fs (Fin n) = Fin (n+1) This version lacks real GADT constructors, so you can't manipulate type equalities using pattern matching. You have to do it yourself using unsafeCoerce . You can give clients a type-safe interface in the form of fold , but they have to be willing to write all their code in a higher-order style, and (since fold is a catamorphism) it becomes harder to look at more than one layer at a time. -- the unsafeCoerce calls assert that m ~ S nfold :: (forall n. r n -> r (S n)) -> (forall n. r (S n)) -> Fin m -> r mfold k z (Fin 0) = unsafeCoerce zfold k z (Fin n) = unsafeCoerce $ k $ fold k z (Fin (n-1)) Oh, and you can't do type level computation (as we did with Fin2Nat above) with this representation of Fin , because type level Int s don't permit induction. For what it's worth, Idris's Fin is just as inefficient as the GADT one above. The docs contain the following caveat : It's probably not a good idea to use Fin for arithmetic, and they will be exceedingly inefficient at run time. I've heard noises about a future version of Idris being able to spot " Nat with types"-style datatypes (like Fin ) and automatically erase the proofs and pack the values into machine integers, but as far as I know we're not there yet.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44021114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1747134/']}
jdg_71602
stackexchange
llm_judgeable_groundtruth_similarity
1251576
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: When I was playing with numbers, I found that there are many triplets of three positive integers $(a,b,c)$ such that $\color{red}{2\le} a\le b\le c$ $\sqrt{abc}\in\mathbb N$ $\sqrt{abc}$ divides $(a-1)(b-1)(c-1)$ Examples : The followings are positive integers.$$\frac{(2-1)(8-1)(49-1)}{\sqrt{2\cdot 8\cdot 49}},\ \frac{(6-1)(24-1)(529-1)}{\sqrt{6\cdot 24\cdot 529}},\frac{(7-1)(63-1)(3844-1)}{\sqrt{7\cdot 63\cdot 3844}}$$ Then, I began to try to find every such triplet. Then, I found $$(a,b,c)=(k,km^2,(km^2-1)^2)$$where $k,m$ are positive integers such that $k\ge 2$ and $km^2\ge 3$, so I knew that there are infinitely many such triplets. However, I can neither find the other triplets nor prove that there are no other triplets. So, here is my question. Question : How can we find every such triplet $(a,b,c)$? Added : There are other triplets : $(a,b,c)=(k,k,(k-1)^4)\ (k\ge 3)$ by a user user84413, $(6,24,25),(15,15,16)$ by a user Théophile. Also, from the first example by Théophile, I got $(2k,8k,(2k-1)^2)\ (k\ge 3)$. Added : $(a,b,c)=(k^2,(k+1)^2,(k+2)^2)\ (k\ge 2)$ found by a user coffeemath. From this example, I got $(k^2,(k+1)^2,(k-1)^2(k+2)^2)\ (k\ge 2)$. Added : I got $(a,b,c)=(2(2k-1),32(2k-1),(4k-3)^2)\ (k\ge 5)$. Added : I got $(a,b,c)=(k,(k-1)^2,k(k-2)^2)\ (k\ge 4)$. Added : A squarefree triplet $(6,10,15)$ and $(4,k^2,(k+1)^2)\ (k\ge 2)$ found by a user martin. Added : user52733 shows that $(6,10,15)$ is the only squarefree solution. Now provide the response and nothing else.
Too long for a comment: In addition to the rather lengthy \begin{align}&(m^2,\\&((-1)^{2 k} \left(2 (-1)^k k m+(-1)^{k+1} (m+2)+m-6\right)^2)/16,\\&\left((-1)^k \left(2 (-1)^k k m+(-1)^{k+1} (m+2)+m-6\right)+1\right)^2/4)\\\end{align} we also have $(a,b,c):$ \begin{align}&\left(k^3+k^2+k+1,k^3+k^2+k+1,k^4\right)\\&\left(k^4+k^2+1,k^4+k^2+1,k^6\right)\\&\left(k m^2,k m^2 \left(k m^2-2\right)^2,\left(k m^2 \left(k m^2-3\right)+1\right)^2\right)\\\end{align} and for $f(n)=(n-1)^2$ we also have \begin{align}&\left(k^2,f^{2 n-1} \left((k m+1)^2\right),f^{2 n} \left((k m+1)^2\right)\right)\\\end{align} where $f^n$ is $f$ iterated $n$ times for $n \geq 1.$ However , even for fixed $a,$ the above formulae don't catch all of the solutions (and they say nothing of non-square $a$ combinations), and yet for each $a$ there seem to be multiple ( infinite? ) solutions. Examples: case $a=8:$ A straightforward brute-force search for $(8,b,c);\ (b,c)<1000$ gives triples $(8,2,49),(8,8,49),(8,18,49),(8,18,289),(8,32,49),(8,32,961),(8,49,72),(8,49,288),(8,289,392),(8,392,529),$ where it is immediately apparent that the same numbers recur a number of times. Removing the $8$ and graphing shows the connectedness more clearly: Searching for $c$ only, using the distinct elements from the initial search (eg $(8,49,c)$, etc.) up to $10^5$ reveals further connections: $(8,49,c)$ for example turns up $6$ triplets: $(8,49,2),(8,49,8),(8,49,18),(8,49,32),(8,49,72),(8,49,288)$ It may be more pertinent to ask then, are there infinitely many triplets for fixed $a?$ Certainly where $a$ is square, this is the case, but it is less clear whether this is the case when it is not. It may also be worthwhile pursuing the idea of primitive pairs $(a,b).$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1251576', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/78967/']}
jdg_71603
stackexchange
llm_judgeable_groundtruth_similarity
12187891
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to get the top 'n' companies from a data frame.Here is my code below. data("Forbes2000", package = "HSAUR")sort(Forbes2000$profits,decreasing=TRUE) Now I would like to get the top 50 observations from this sorted vector. Now provide the response and nothing else.
head and tail are really useful functions! head(sort(Forbes2000$profits,decreasing=TRUE), n = 50) If you want the first 50 rows of the data.frame, then you can use the arrange function from plyr to sort the data.frame and then use head library(plyr)head(arrange(Forbes2000,desc(profits)), n = 50) Notice that I wrapped profits in a call to desc which means it will sort in decreasing order. To work without plyr head(Forbes2000[order(Forbes2000$profits, decreasing= T),], n = 50)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12187891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1049893/']}
jdg_71604
stackexchange
llm_judgeable_groundtruth_similarity
560036
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose we're interested in (minimally) coupling a heavy scalar particle to the electromagnetic field. In quantum field theory, we describe the particle as an excitation of a complex scalar field $\phi$ . Including the simplest possible coupling leads to the theory of scalar QED, with Lagrangian $$\mathcal{L} = - \frac14 F_{\mu\nu} F^{\mu\nu} + |D_\mu \phi|^2 - m^2 |\phi|^2.$$ By expanding out the kinetic term, we see that there are vertices where a $\phi$ emits a photon, and where a $\phi$ emits two photons. The latter is required by gauge invariance. On the other hand, if the particle is localized, we could also describe it as a worldline supplying a classical current. For a trajectory $y^\mu(t)$ , the current is $$J^\mu(x) = e \int d \tau \, \frac{dy^\mu}{d\tau} \, \delta(x - y(\tau))$$ and the action is $$S = - \int dx \, \frac14 F_{\mu\nu} F^{\mu\nu} + \int dx \, J^\mu A_\mu + m \int d \tau.$$ Everything is gauge invariant, since $J^\mu$ is. Both of these pictures are common, but I'm confused how to translate between them. On the quantum field side, we know that $\phi$ must be a complex scalar, and that it must have a two-photon coupling to ensure gauge invariance. But on the worldline side these facts aren't manifest at all! This doesn't make sense, because in both cases it should be possible to calculate, the probability of producing two hard photons when the particle is accelerated. The results should match, but since the worldline picture is "missing" the two-photon coupling, I don't see how it can. More specifically, it's clear that the amplitude to produce one hard photon matches between the two formalisms -- what's puzzling to me is that it seems like this implies the amplitude to produce two hard photons in the worldline formalism should match the corresponding amplitude in the field theory formalism, without the two photon vertex. What's going on? Now provide the response and nothing else.
I think the best way to see where the four-point interaction disappears is to follow the derivation of the worldline formalism. Christian Schneider's PhD thesis has a good walkthrough for scalars and spinors in section 4.2; the majority of this answer paraphrases it. Starting with the scalar QED Lagrangian you write down at the beginning of the question, you get the path integral $$\mathcal{Z} = \int \mathcal{D} \phi \mathcal{D} \phi^* \mathcal{D}A \, \mathrm{e}^{iS[\phi, \phi^*, A]}$$ where $S$ is the action from the scalar QED lagrangian. The next step is to rewrite the lagrangian in a Gaussian form: by essentially completing the square we find $$S \supset \phi^* (D^2 + m^2) \phi.$$ The next trick is to Wick rotate to Euclidean space (changing $D^2 \to -D^2$ and getting rid of the oscillatory integral), so we can integrate out the matter field to give $$\mathcal{Z}_\mathrm{E} = \int \mathcal{D} A \det (-D^2 + m^2) \mathrm{e}^{- \frac{1}{4}\int F_{\mu \nu} F^{\mu \nu}}. $$ This is where the four-point interaction appears to vanish: we have integrated out over all the scalar field loops and hidden the interactions in the functional determinant. What follows is a series of integral tricks to write the functional determinant as an integral over all worldlines. We eventually get $$\mathcal{Z}_\mathrm{E} = \mathcal{N} \int_0^\infty \frac{\mathrm{d}T}{T} \int \mathcal{D} x \int \mathrm{D} A \, \mathrm{e}^{-\frac{1}{4} \int F_{\mu \nu} F^{\mu \nu}}\,\mathrm{e}^{-\int_0^T \mathcal{L}_\mathrm{eff}[x, A] \, \mathrm{d} \tau},$$ where $\mathcal{L}_\mathrm{eff}$ is the worldline effective action, and $T$ is a parameter introduced that can be thought of as the worldline length. The effects of the four-point interaction are hidden in the $x$ and and $T$ integrals; if you sum them to all orders you'll get the same result as the standard QFT one. As noted on p6 of this paper , the fact that the worldline method integrates over diagrams including the scalar interactions is one of its strengths; it can greatly simplify certain calculations.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/560036', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/83398/']}
jdg_71605
stackexchange
llm_judgeable_groundtruth_similarity
12693
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I would like to train a convnet to do the following: Input is a set of single channel (from black to tones of grey to white) pictures with a given object, let's say cars. Target is, for every picture in the set, the same picture, however pixels are either black or white. The pixels corresponding to the car object are in white (i.e. intensity 255) and the pixels corresponding to the background are black (i.e. intensity 0). After training I would like to feed the net with pictures of cars and I would like the prediction - the ideal prediction at least - to be a picture with pixels either black or white, where white corresponds to the object and black to the background. I assume that the input layer is a 2D convolutional layer and the output layer is also a 2D convolutional layer, each one with as many neurons as pixels in the pictures. Can anyone please explain what kind of network architecture would accomplish just that? It could be either the architecture (in theory) or implemented in code. I expect to tweak it, but it would be nice not to start from scratch. Now provide the response and nothing else.
I'm surprised nobody mention fully convolutional neural networks (FCNs) for semantic segmentation . They are inspired by the original AlexNet style convnets that ended with one or two densely connected layers and softmax classifier. But FCNs dispense with the dense layers and stay fully convolutional all the way to the end. Here's the basic principle. Take AlexNet, or VGG or something like that. But instead of using the parameters in the classifier to compute a scalar for each category, use them to compute a whole array (i.e. image) using a 1x1xNUM_CATEGORIES convolution. The output will be NUM_CATEGORIES feature maps, each representing a coarse-grained "heat map" for that category. A map of dogness, a map of catness. It can be sharpened by including information from earlier layers with "skip connections". EDIT: Just one further bit of good news: the authors of that paper provide implementations of their nets in Caffe's Model Zoo . Tweak away!
{}
{'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/12693', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/9197/']}
jdg_71606
stackexchange
llm_judgeable_groundtruth_similarity
57689075
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: ({ body: { customer } } = await callCreateCustomer({ email: createRandomEmailAddress(), key: 999, password: 'password',})); I don't understand what it means when you have () around the whole expression? What does it do? Now provide the response and nothing else.
This is Destructuring Assignment without declaration . Here customer variable is already declared above and a value is being assigned with response.body.customer From the documentation : The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration. {a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal. However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2} Your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57689075', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6333692/']}
jdg_71607
stackexchange
llm_judgeable_groundtruth_similarity
34433267
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When profiling my application I came across a weird behavior - the DestroyJavaVM thread is ALWAYS running - 100% of the time. After doing a little research on the subject, on which there's hardly any valuable information online, all I understood is that this thread is supposed to unload the JVM upon exit . If that's the case, why is this thread in RUNNING state 100% of the time from the very first moment I start my application? Doesn't it consume valuable resources and therefore may cause an OutOfMemoryError (like I sometimes get)? Is there any official reference to what this thread actually does and what triggers its initialization? Thanks Now provide the response and nothing else.
This happens because most applications are run in threads. All POJO apps start by invoking the main method. In its most simple case, this method will do all of the work, creating objects, calling methods etc. Once main completes, the JVM is told to shut down using a DestroyJavaVM thread which waits for all non-daemon threads to complete before doing its work. This is to ensure that any non-daemon threads you create run to completion before the JVM is torn down. An app with a GUI, however, normally runs as a number of threads. One for watching for system events such as keyboard or mouse events. One for maintaining the windows and display etc. The main method of this kind of app will probably just start up all the required threads and exit. It still creates the DestroyJavaVM thread but now all that it does is wait for all of your created threads to finish before tearing down the VM. As a result, any app that creates threads and relies solely on their functionality will always have a DestroyJavaVM thread waiting for it to finish. Since all it is doing is join ing all other running threads it does not consume any resources.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/34433267', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/223365/']}
jdg_71608
stackexchange
llm_judgeable_groundtruth_similarity
21614
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a mac server but my question has long left the realm of the GUI. My last hope is a unix forum. I have a cisco router with two WAN ports. The mac uses postfix 2.8.3. I have correctly configured the port forwarding for in this case port 25. When I however try to open a telnet session from an external host to the IP addresses of my WAN ports using port 25, I only get a postfix reply on WAN1. WAN2 gives me an "Unable to connect to remote host: Connection time out". If I however have WireShark running I can see that the router forwards the request, but postfix just doesn't seem to "pick up". I reviewed my main.cf and there was nothing that suggested that postfix should be picky which WAN it wants to use. inet_protocols is set to all and I even tried adding the static ip addresses of each of my WAN ports to the my networks variable. I can't seem to get it to work though - does anyone have any tips where I can look next? Thanks Now provide the response and nothing else.
Generally, in Linux, and Unix, traceroute and ping would both use a call to gethostbyname() to lookup the name of a system. gethostbyname() in turn uses the system configuration files to determine the order in which to query the naming databases, ie: /etc/hosts, and DNS. In Linux, the default action is (or maybe used to be) to query DNS first, and then /etc/hosts. This can be changed or updated by setting the desired order in /etc/host.conf. To search /etc/hosts before DNS, set the following order in /etc/host.conf: order hosts,bind In Solaris, this same order is controlled via the /etc/nsswitch.conf file, in the entry for the hosts database. hosts: files dns Sets the search order to look in /etc/hosts before searching DNS. Traceroute and ping would both use these methods to search all the configured naming databases. the host and nslookup commands both use only DNS, so they won't necessarily duplicate the seemingly inconsistent results you're seeing. Solaris has a lookup tool, getent , which can be used to identify hosts or addresses in the same way that traceroute and ping do - by following the configured set of naming databases to search. getent hosts <hostname> would search through whatever databases are listed for hosts, in /etc/nsswitch.conf. So. In your case, to acheive consistent results, add the following to /etc/hosts 192.168.235.41 selenium-rc And, make sure /etc/host.conf has: order hosts,bind Or, make sure that /etc/nsswitch.conf has: hosts: files dns Once that's done, you should see more consistent results with both ping, and traceroute, as well as other commands, like ssh, telnet, curl, wget, etc.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/21614', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/11114/']}
jdg_71609
stackexchange
llm_judgeable_groundtruth_similarity
14638
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: From seminar on kdV equation I know that for integrable dynamical system its trajectory in phase space lays on tori. In wikipedia article You may read ( http://en.wikipedia.org/wiki/Integrable_system ): When a finite dimensional Hamiltonian system is completely integrable in the Liouville sense, and the energy level sets are compact, the flows are complete, and the leaves of the invariant foliation are tori. There then exist, as mentioned above, special sets of canonical coordinates on the phase space known as action-angle variables, such that the invariant tori are the joint level sets of the action variables. These thus provide a complete set of invariants of the Hamiltonian flow (constants of motion), and the angle variables are the natural periodic coordinates on the torus. The motion on the invariant tori, expressed in terms of these canonical coordinates, is linear in the angle variables. As I also know that elliptic curve is in fact some kind of tori, then there natural question arises: Are tori for quasi-periodic motion in action-angle variables of some dynamical systems related in any way to algebraic structure like elliptic curve? Maybe some small dynamical systems and some elliptic curves are related in some way? The most interesting in this matter is for me the size of space of elliptic functions: its quite small, every elliptic curve is rational function of Weiestrass function, and its derivative. Has this property any analogy in integrable dynamical systems theory? As isomorphic elliptic curves shares some invariants, it is also interesting it they have any "dynamical meaning". Now provide the response and nothing else.
If your system is algebraic, then you bet! More generally, you can get abelian varieties as the fibers for many interesting integrable systems. Google the following for more: algebraic complete integrable Hamiltonian system, Calogero-Moser System, Hitchin System. As for elliptic curves, they'll only pop out in low dimensional cases, because otherwise, the fibers have to have larger dimension. As for the latter, it depends what you might want. I've seen the definition of integrable given by "can be solved by a sequence of quadratures" and in this terminology, you can check that an algebraic system you're always working with the global section of the theta function on the abelian variety, which is the unique (up to scaling) global section of the theta divisor on the abelian variety, which for an elliptic curve, is just the Weierstrass function.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/14638', 'https://mathoverflow.net', 'https://mathoverflow.net/users/3811/']}
jdg_71610
stackexchange
llm_judgeable_groundtruth_similarity
42242084
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Playing with Haskell and now I try to create a function like keepValue :: (Monad m) => m a -> (a -> m b) -> m a with following semantic: it should apply monad value to a function, which return the second monad, and keep the result of the first monad, but the effect of the second one I have a working function in case of Maybe monad: keepValueMaybe :: Maybe a -> (a -> Maybe b) -> Maybe akeepValue ma f = case ma >>= f of Nothing -> Nothing Just _ -> ma So if the first value is Nothing , the function is not run (so no second side-effect), but if the first value is Just , then, the function is run (with side effect). I keep effect of the second computation (e.g., Nothing makes the whole expression Nothing ), but the original value. Now I wonder. Can it work for any monad? It looks kinda built-in >> , but I couldn't find anything in standard library. Now provide the response and nothing else.
Let's walk through this! keepValue :: Monad m => m a -> (a -> m b) -> m akeepValue ma f = _ So what do we want keepValue to do? Well, the first thing we should do is use ma , so we can connect it to f . keepValue :: Monad m => m a -> (a -> m b) -> m akeepValue ma f = do a <- ma _ Now we have a value va of type a , so we can pass it to f . keepValue :: Monad m => m a -> (a -> m b) -> m akeepValue ma f = do va <- ma vb <- f va _ And finally, we want to produce va , so we can just do that: keepValue :: Monad m => m a -> (a -> m b) -> m akeepValue ma f = do va <- ma vb <- f va return va This is how I'd walk through writing the first draft of any monadic function like this. Then, I'd clean it up. First, some small things: since Applicative is a superclass of Monad , I prefer pure to return ; we didn't use vb ; and I'd drop the v in the names. So for a do -notation based version of this function, I think the best option is keepValue :: Monad m => m a -> (a -> m b) -> m akeepValue ma f = do a <- ma _ <- f a pure a Now, however, we can start to make the implementation better. First, we can replace _ <- f va with an explicit call to (>>) : keepValue :: Monad m => m a -> (a -> m b) -> m akeepValue ma f = do a <- ma f a >> pure a And now, we can apply a simplification. You may know that we can always replace (>>=) plus pure / return with fmap / (<$>) : any of pure . f =<< ma , ma >>= pure . f , or do a <- ma ; pure $ f a (all of which are equivalent) can be replaced by f <$> ma . However, the Functor type class has another, less-well-known method, (<$) : (<$) :: a -> f b -> f a Replace all locations in the input with the same value. The default definition is fmap . const , but this may be overridden with a more efficient version. So we have a similar replacement rule for (<$) : we can always replace ma >> pure b or do ma ; pure b with b <$ ma . This gives us keepValue :: Monad m => m a -> (a -> m b) -> m akeepValue ma f = do a <- ma a <$ f a And I think this is the shortest reasonable version of this function! There aren't any nice point-free tricks to make this cleaner; one indicator of that is the multiple use of a on the second line of the do block. Incidentally, a terminology note: you're running two monadic actions , or two monadic values ; you're not running *"two monads". A monad is something like Maybe – a type constructor which supports (>>=) and return . Don't mix the values up with the types – this sort of terminological distinction helps keep things clearer!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42242084', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/889530/']}
jdg_71611
stackexchange
llm_judgeable_groundtruth_similarity
5419389
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I had the following code: for x in range(10): print x I would get the output of 12etc.. What I would like to do is instead of printing a newline, I want to replace the previous value and overwrite it with the new value on the same line. Now provide the response and nothing else.
Simple Version One way is to use the carriage return ( '\r' ) character to return to the start of the line without advancing to the next line. Python 3 for x in range(10): print(x, end='\r')print() Python 2.7 forward compatible from __future__ import print_functionfor x in range(10): print(x, end='\r')print() Python 2.7 for x in range(10): print '{}\r'.format(x),print Python 2.0-2.6 for x in range(10): print '{0}\r'.format(x),print In the latter two (Python 2-only) cases, the comma at the end of the print statement tells it not to go to the next line. The last print statement advances to the next line so your prompt won't overwrite your final output. Line Cleaning If you can’t guarantee that the new line of text is not shorter than the existing line, then you just need to add a “clear to end of line” escape sequence, '\x1b[1K' ( '\x1b' = ESC): for x in range(75): print('*' * (75 - x), x, end='\x1b[1K\r')print()
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/5419389', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/588892/']}
jdg_71612
stackexchange
llm_judgeable_groundtruth_similarity
49243
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In trying to understand the relationships between Huffman Coding, Arithmetic Coding, and Range Coding, I began to think of the shortcomings of Huffman coding to be related to the problem of fractional bit-packing . That is, suppose you have 240 possible values for a symbol, and needed to encode this into bits, you would be stuck with 8 bits per symbol, even though you do not need a "full" 8, as 8 can express 256 possible values per symbol. A solution to this problem is something I've seen referred to as "fractional bit packing", where you are able "bitshift" by a non-power of two using multiplication. Just like multiplication of powers-of-two are shifting x * 2 == x << 1 and x * 4 == x << 2 and so on for all powers of two, so too you can "shift" with a non-power-of-2 by multiplying instead, and pack in fractional-bit-sized symbols. The problem is similar with Huffman coding: you end up with codes that must be non-fractionally-bit-sized in length, and therefore it has this packing inefficiency. However, you can't just use the solution of fracitonal-bit-packing, because this solution assumes fixed sized symbols. The question is, are there any papers or solutions to improve on huffman coding with a similar idea to fractional-bit-packing to achieve something similar to arithmetic coding? (or any results to the contrary). Now provide the response and nothing else.
Let's look at a slightly different way of thinking about Huffman coding. Suppose you have an alphabet of three symbols, A, B, and C, with probabilities 0.5, 0.25, and 0.25. Because the probabilities are all inverse powers of two, this has a Huffman code which is optimal (i.e. it's identical to arithmetic coding). We will use the canonical code 0, 10, 11 for this example. Suppose our state is a large integer, which we will call $s$. You can think of encoding as a function which takes the current state, and a symbol to encode, and returns the new state: $$\begin{align*}\hbox{encode}(s, A) &= 2s\\\hbox{encode}(s, B) &= 4s + 2\\\hbox{encode}(s, C) &= 4s + 3\\\end{align*}$$ So let's start with the state 11 (which is 1011 in binary), encode the symbol B. The new state is 46, which is 101110 in binary. As you can see, this is the "old" state with the sequence 10 added to the end. We have essentially "output" the bit sequence 10. So far, so good. Now think for a moment about how arithmetic coding works. If you put the probabilities over a common denominator, the symbol A actually represents the range $[\frac{0}{4},\frac{2}{4})$, the symbol B represents the range $[\frac{2}{4},\frac{3}{4})$ and the symbol C represents the range $[\frac{3}{4},\frac{4}{4})$. Basically what we're doing here is multiplying everything by the common denominator. Imagine that the state was actually in base 4. Encoding a symbol B is really outputting the digit 2 in that base, and encoding a symbol C is outputting the digit 3 in that base. However, symbol A is a little different, because it isn't a whole digit in base 4. Instead, we can think of the alphabet as the set of symbols A_0, A_1, B, C, with equal probability. This, again, has an optimal Huffman code 00, 01, 10, 11. Or, again, we can think of this in base 4. To encode a symbol, we just do: $$\begin{align*}\hbox{encode}(s, A_0) &= 4s + 0\\\hbox{encode}(s, A_1) &= 4s + 1\\\hbox{encode}(s, B) &= 4s + 2\\\hbox{encode}(s, C) &= 4s + 3\end{align*}$$ So now it's clear how to encode symbols B and C, but to encode a symbol A, we have a choice. Which of $A_0$ and $A_1$ should we use? Now here's the clever idea: we steal one bit of information from the state $s$: $$s' = \left\lfloor \frac{s}{2} \right\rfloor$$$$i = s \bmod 2$$ and then $\hbox{encode}(s', A_i)$. Using our previous example, $s=11$, we find that $s'=5$ and $i=1$, and then $\hbox{encode}(5, A_1) = 4\times 5+1 = 21$. The new state is 10101 in binary. Now this doesn't produce exactly the same bit output as Huffman coding, but it does generate an output which has the same length. And what I hope you can see is that this is also uniquely decodable. To decode a symbol, we take the remainder when divided by 4. If the value is 2 or 3, then the symbol is B or C respectively. If it's 0 or 1, then the symbol is A, and then we can put the bit of information back by multiplying the state by 2 and adding either 0 or 1. The nice thing about this approach is that it extends naturally to fractional-bit encoding, when the numerator and/or denominator of the probabilities are not powers of two. Suppose we have two symbols, A and B, where the probability of A is $\frac{3}{5}$ and the probability of B is $\frac{2}{5}$. Then we can encode a symbol with: $$\begin{align*}\hbox{encode}(s, A_0) &= 5s + 0\\\hbox{encode}(s, A_1) &= 5s + 1\\\hbox{encode}(s, A_2) &= 5s + 2\\\hbox{encode}(s, B_0) &= 5s + 3\\\hbox{encode}(s, B_1) &= 5s + 4\end{align*}$$ To encode the symbol A, we take $s' = \left\lfloor \frac{s}{3} \right\rfloor$ and $i = s \bmod 3$, and then $\hbox{encode}(s', A_i)$. This is equivalent to arithmetic coding. It's actually a family of methods known as Asymmetric Numeral Systems , and was developed over the last few years by Jarek Duda. The meaning of the name should be obvious: to encode a symbol with probability $\frac{p}{q}$, you conceptually steal a base-p digit from the state, and then add a base-q digit. The asymmetry comes from interpreting the state as a numeral in two different bases. The reason why it's a family of coding methods is that what we've seen here is impractical by itself; it needs some modifications to deal with the fact that you probably don't have infinite-precision integers to manipulate the state variable efficiently, and there are various ways that you can achieve this. Arithmetic coding, of course, has a similar issue with precision for its state. Practical variants include rANS (the "r" means "ratio") and tANS ("table-driven"). ANS has a few interesting advantages over arithmetic coding, both practical and theoretical: Unlike arithmetic coding, the "state" is a single word, rather than a pair of words. Not only that, but an ANS encoder and its corresponding decoder have identical states and their operations are completely symmetric. This raises some interesting possibilities, such as that you can interleave different streams of encoded symbols and everything synchronises perfectly. Practical implementations need, of course, to "output" information as you go, and not just collect it in a big integer to be written at the end. However, the size of the "output" can be configured in return for (usually modest) compression loss. So where arithmetic coders must output a bit at a time, ANS can output a byte or a nybble at a time. This gives you a direct tradeoff between speed and compression. It appears to be about as fast on current-generation hardware as binary arithmetic coding, and hence competitive with Huffman coding. This makes it much faster than large-alphabet arithmetic coding and its variants (e.g. range coding). It appears to be patent-free. I don't think I'm ever going to do arithmetic coding again.
{}
{'log_upvote_score': 5, 'links': ['https://cs.stackexchange.com/questions/49243', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/2755/']}
jdg_71613
stackexchange
llm_judgeable_groundtruth_similarity
36711654
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to launch an iOS project with an Enterprise account.First thing first, the project is running just fine when I run it from xcode.When I download the ipa archive(I created) from the server it appears to open the app on the screen for less than a second and then immediately closes it . I have tried various provisioning profiles: Development -> iOS App Development Distribution -> In House Distribution -> Ad Hoc And combined the above with all the possible ways of archiving the project: -> Ad Hoc Deployment -> Enterprise Deployment -> Development Deployment Only when I archive the ipa for development it works on my phone, as it is registered as development device for this provisioning profile, but not other phones. Am I missing something out? Is there a setting in Xcode I should change for an enterprise launch? UPDATE: device logs says: Dyld Error Message: Dyld Message: Library not loaded: @rpath/ResearchKit.framework/ResearchKit Referenced from: /var/containers/Bundle/Application/6DBB2C29-B1AE-4AE0-AEFB-ABF4081467A5/Beck Chestionar.app/Beck Chestionar Reason: no suitable image found. Did find: /private/var/containers/Bundle/Application/6DBB2C29-B1AE-4AE0-AEFB-ABF4081467A5/Beck Chestionar.app/Frameworks/ResearchKit.framework/ResearchKit: mmap() errno=1 validating first page of '/private/var/containers/Bundle/Application/6DBB2C29-B1AE-4AE0-AEFB-ABF4081467A5/Beck Chestionar.app/Frameworks/ResearchKit.framework/ResearchKit' Dyld Version: 390.7 Binary Images: 0x100004000 - 0x100017fff Beck Chestionar arm64 /var/containers/Bundle/Application/6DBB2C29-B1AE-4AE0-AEFB-ABF4081467A5/Beck Chestionar.app/Beck Chestionar 0x120050000 - 0x12007ffff dyld arm64 /usr/lib/dyld Now provide the response and nothing else.
Getting really good results is a difficult problem (you'll probably have to somehow model the structure of the blood vessels and the noise) but you can probably still do better than filtering. One technique for addressing this kind of problems, inspired by the Canny edge detector, is using two thresholds - [hi,low] and classifying a pixel p with response r as belonging to a blood vessel V if r > hi || ( r > lo && one of p 's neighbors is in V ). Also, when it comes to filtering, both bilateral filtering and meanshift filtering are good for noisy images. kernel3 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))kernel5 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))kernel7 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7))t_lo = 136t_hi = 224blured = cv2.pyrMeanShiftFiltering(img, 3, 9)#blured = cv2.bilateralFilter(img, 9, 32, 72)clahe = cv2.createCLAHE(clipLimit=128.0, tileGridSize=(64, 64))cl1 = clahe.apply(blured)cl1 = 255 - cl1ret, thresh_hi = cv2.threshold(cl1, t_hi, 255, cv2.THRESH_TOZERO)ret, thresh_lo = cv2.threshold(cl1, t_lo, 255, cv2.THRESH_TOZERO) Low threshold image Hi threshold image Preparations and cleanup: current = np.copy(thresh_hi)prev = np.copy(current)prev[:] = 0current = cv2.morphologyEx(current, cv2.MORPH_OPEN, kernel5)iter_num = 0max_iter = 1000 Not the most efficient way to do that... but easy to implement: while np.sum(current - prev) > 0 and iter_num < max_iter: iter_num = iter_num+1 prev = np.copy(current) current = cv2.dilate(current, kernel3) current[np.where(thresh_lo == 0)] = 0 Initial mask Remove small blobs: contours, hierarchy = cv2.findContours(current, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)for contour in contours: area = cv2.contourArea(contour) if area < 256: cv2.drawContours( current, [contour], 0, [0,0,0], -1 ) After removing small blobs Morphological cleanup: opening = cv2.morphologyEx(current, cv2.MORPH_OPEN, kernel7) cl1[np.where(opening == 0)] = 0 Result This is by no means optimal, but I think it should provide you with enough tools to start.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36711654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5367540/']}
jdg_71614
stackexchange
llm_judgeable_groundtruth_similarity
114598
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Seems to me that VerificationTests are a bit verbose: TestReport[{VerificationTest[StringFreeQ["apple", "lp"], True], VerificationTest[StringFreeQ["apple", "a" ~~ __ ~~ "e"], False], VerificationTest[StringFreeQ["apple", "ap"], False], VerificationTest[StringFreeQ["apple", "x"], True], VerificationTest[StringFreeQ["", "asd"], True]}] This was the first obvious thing that I tried: args := {{"apple", "lp"}, {"apple", "a" ~~ __ ~~ "e"}, {"apple", "ap"}, {"apple", "x"}, {"", "asd"}};results := {True, False, (Pause[2]; False), True, True};tr = TestReport[ VerificationTest @@@ Thread[{StringFreeQ @@@ args, results}], TimeConstraint -> Quantity[1, "Seconds"]] But this solution has many problems: Timing specs and information aren't enforced and preserved Evaluations may leak What are some elegant ways to cut down the verbosity here without messing with evaluation mechanics of the arguments to VerificationTest? Now provide the response and nothing else.
You can make it look somewhat more pleasant by using simple expression parsers. For example, define an auxiliary head Tests , as follows: ClearAll[transformTest];SetAttributes[transformTest, {HoldAll, Listable}];transformTest[lhs_ -> rhs_] := Hold[VerificationTest[lhs, rhs]];transformTest[Tests[tests___]] := Thread[transformTest[{tests}], Hold];ClearAll[Tests];SetAttributes[Tests, HoldAll];Tests /: TestReport[t_Tests, args___] := Replace[ transformTest[t], Hold[tests___] :> TestReport[tests, args] ]; And now you can use the following syntax: TestReport @ Tests[ StringFreeQ["apple", "lp"] -> True, StringFreeQ["apple", "a" ~~ __ ~~ "e"] -> False, StringFreeQ["apple", "ap"] -> False, StringFreeQ["apple", "x"] -> True, StringFreeQ["", "asd"] -> True] which looks a little nicer to me.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/114598', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/403/']}
jdg_71615
stackexchange
llm_judgeable_groundtruth_similarity
497666
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to delete all files containing a certain text like this: $ find ~/Library/MobileDevice/Provisioning\ Profiles/* -exec grep -l "text to search for" '{}' \; -delete/Users/build/Library/MobileDevice/Provisioning Profiles/06060826-3fb2-4d71-82c6-7b9d309b08d6.mobileprovisionfind: -delete: /Users/build/Library/MobileDevice/Provisioning Profiles/06060826-3fb2-4d71-82c6-7b9d309b08d6.mobileprovision: relative path potentially not safe However, as you can see, it's throwing a warning and then does not delete the file. How can I resolve this error? This is on a Mac. Now provide the response and nothing else.
macOS find is based on an older version of FreeBSD find whose -delete would not remove the files that were given as argument. When you do: find dir/* ... -delete Your shell is expanding that dir/* glob into a list of file paths (excluding the hidden ones, while find itself will not exclude the hidden files it finds in any of those dirs), so find receives something like: find dir/dir1 dir/dir2 dir/file1 dir/file2... ... -delete If dir/file1 matches macOS find 's -delete will refuse to delete it. It will happily delete a dir/dir1/.somefile if it matches though. That was changed in FreeBSD in 2013 , but the change apparently didn't make it to macOS. Here, the work around is easy: use find dir (or find dir/ if you want to allow for dir to be a symlink to a directory and find to descend into it) instead of find dir/* . So, in your case: find ~/Library/MobileDevice/Provisioning\ Profiles/ \ -exec grep -l "text to search for" '{}' \; -delete Or use the more efficient grep -l --null | xargs -0 approach .
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/497666', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/201213/']}
jdg_71616
stackexchange
llm_judgeable_groundtruth_similarity
638893
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a simple task I need to perform in Python, which is to convert a string to all lowercase and strip out all non-ascii non-alpha characters. For example: "This is a Test" -> "thisisatest""A235th@#$&( er Ra{}|?>ndom" -> "atherrandom" I have a simple function to do this: import stringimport sysdef strip_string_to_lowercase(s): tmpStr = s.lower().strip() retStrList = [] for x in tmpStr: if x in string.ascii_lowercase: retStrList.append(x) return ''.join(retStrList) But I cannot help thinking there is a more efficient, or more elegant, way. Thanks! Edit: Thanks to all those that answered. I learned, and in some cases re-learned, a good deal of python. Now provide the response and nothing else.
Another solution (not that pythonic, but very fast) is to use string.translate - though note that this will not work for unicode. It's also worth noting that you can speed up Dana's code by moving the characters into a set (which looks up by hash, rather than performing a linear search each time). Here are the timings I get for various of the solutions given: import string, re, timeit# Precomputed values (for str_join_set and translate)letter_set = frozenset(string.ascii_lowercase + string.ascii_uppercase)tab = string.maketrans(string.ascii_lowercase + string.ascii_uppercase, string.ascii_lowercase * 2)deletions = ''.join(ch for ch in map(chr,range(256)) if ch not in letter_set)s="A235th@#$&( er Ra{}|?>ndom"# From unwind's filter approachdef test_filter(s): return filter(lambda x: x in string.ascii_lowercase, s.lower())# using set instead (and contains)def test_filter_set(s): return filter(letter_set.__contains__, s).lower()# Tomalak's solutiondef test_regex(s): return re.sub('[^a-z]', '', s.lower())# Dana'sdef test_str_join(s): return ''.join(c for c in s.lower() if c in string.ascii_lowercase)# Modified to use a set.def test_str_join_set(s): return ''.join(c for c in s.lower() if c in letter_set)# Translate approach.def test_translate(s): return string.translate(s, tab, deletions)for test in sorted(globals()): if test.startswith("test_"): assert globals()[test](s)=='atherrandom' print "%30s : %s" % (test, timeit.Timer("f(s)", "from __main__ import %s as f, s" % test).timeit(200000)) This gives me: test_filter : 2.57138351271 test_filter_set : 0.981806765698 test_regex : 3.10069885233 test_str_join : 2.87172979743 test_str_join_set : 2.43197956381 test_translate : 0.335367566218 [Edit] Updated with filter solutions as well. (Note that using set.__contains__ makes a big difference here, as it avoids making an extra function call for the lambda.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/638893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34329/']}
jdg_71617
stackexchange
llm_judgeable_groundtruth_similarity
1902421
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have an expression which I want to maximize:$$\mbox{trace} (U^T\Sigma U)$$ $\Sigma \in R^{d \times d}$ is symmetric and positive definite $U \in R^{d \times r}$ its columns are orthonormal. I am following a proof which states that U is optimal when its columns are the eigenvectors of $\Sigma$: let $\Sigma = V\Delta V^T$, the eigen-decomposition; let $B=V^TU$ then:$$U=VB$$$$U^T\Sigma U= B^TV^TV\Delta V^TVB = B^T\Delta B$$the last statement is mathematically correct. However, how does this proof to me that the columns of U are the eigenvectors of $\Sigma$? For some background: I am trying to understand a derivation of PCA. The point is that when this trace is maximized the objective function will be minimized. Now provide the response and nothing else.
Note that with your substitution, finding the optimal $B$ with orthonormal columns is equivalent to finding the optimal $V$. What we're trying to maximize, then, is$$\operatorname{trace}(B^T\Delta B) = \sum_{i=1}^r b_i^T\Delta b_i$$Where $b_i$ is the $i$th column of $B$. It turns out that the optimum occurs when each $b_i$ is a standard basis vector. Because it's a result that makes intuitive sense, it's common to mistakenly assume that it's easy to prove. See, for instance, the mistaken proof given here . Why is the result intuitive? I think that's because it's clear that if we perform a greedy optimization one column $b_i$ at a time, then we'd arrive at the correct result. However, I would say there's no (simple) a priori justification that this should give us the right answer. If you look at the original paper deriving the results required for PCA, you'll see that the required proof takes some Lie-group trickery. The most concise modern proof is one using the appropriate trace inequality. I would prove the result as follows: to find an upper bound for the maximum, apply the Von-Neumann trace inequality . In particular, we have$$\operatorname{trace}(U^T\Sigma U) = \operatorname{trace}(\Sigma[UU^T]) \leq \sum_{i=1}^n \lambda_i(\Sigma)\lambda_i(UU^T)$$where $\lambda_i(M)$ of a positive definite matrix $M$ denote the eigenvalues of $M$ in decreasing order. Note that $UU^T$ is a projection matrix of rank $r$, so we have $\lambda_1(UU^T) = \cdots = \lambda_r(UU^T) = 1$ and $\lambda_{r+1}(UU^T) = \cdots = \lambda_n(UU^T) = 0$. Conclude that $\sum_{i=1}^r\lambda_i(\Sigma)$ is an upper bound. From there, it suffices to show that taking the columns of $U$ to be the eigenvectors of $\Sigma$ (in the correct order) allows you to attain this upper bound.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1902421', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/273396/']}
jdg_71618
stackexchange
llm_judgeable_groundtruth_similarity
28990596
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I remove commits, waiting to be pushed to remote? My situation is, that those queued commits (changes) been already pushed (more bellow) and now the server refuses to accept those as they are behind the HEAD. I tried resetting to another commit, but when I go back to HEAD, pushes reappear again. SourceTree - undo unpushed commits https://answers.atlassian.com/questions/153791/how-should-i-remove-push-commit-from-sourcetree Clicking Repository > Refresh Remote Status won't help, it actually added the 2nd waiting push :) PS: I apologize for my terminology, I'm quite new to git. . Update 1 Problems started when I were commiting feature2 to master branch. I don't have rights to commit there so it got stuck. Then I commited again to my personal branch, which was OK. Then I got one waiting commit, never to be pushed, even if I select the right (personal) branch when I click Push. Now provide the response and nothing else.
Git commits form a commit graph. Branches are just named pointers to commits in that graph. Given that, your question can be restated as My local master branch is pointing to a different commit than the remote master branch. How do I make my local master branch point to the same commit as the remote master branch? There are two ways to accomplish this. Move the remote branch ( git push ) or move the local branch ( git reset ). As you said, you can't push to the remote master branch, so options 1 is off the table, that leaves option 2. Note that the reset operates on the currently checkout branch 1 so you'll first want to make sure you are currently on the master branch and then move that branch to the same commit as the remote master branch. git checkout master <--- make sure you're on the master branchgit reset --hard origin/master <--- put your master branch on the same commit as origin/master Now that master and origin/master are on the same commit, there should be no commits to push. reset operates on the current HEAD, but for the sake of this explanation it's easier to think of of it as operating on branches. For more information see this question: What is HEAD in Git? .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/28990596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/896405/']}
jdg_71619
stackexchange
llm_judgeable_groundtruth_similarity
18037082
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If a method has a local variable i : int i = 10; and then I assign a new value: i = 11; Will this allocate a new memory location? Or just replace the original value? Does this mean that primitives are immutable? Now provide the response and nothing else.
Will this allocate a new memory location? Or just replace the original value? Java does not really make any guarantees that variables will correspond to memory locations; for example, your method might be optimized in such a way that i is stored in a register — or might not even be stored at all, if the compiler can see that you never actually use its value, or if it can trace through the code and use the appropriate values directly. But setting that aside . . . if we take the abstraction here to be that a local variable denotes a memory location on the call stack, then i = 11 will simply modify the value at that memory location. It will not need to use a new memory location, because the variable i was the only thing referring to the old location. Does this mean that primitives are immutable? Yes and no: yes, primitives are immutable, but no, that's not because of the above. When we say that something is mutable, we mean that it can be mutated: changed while still having the same identity. For example, when you grow out your hair, you are mutating yourself: you're still you, but one of your attributes is different. In the case of primitives, all of their attributes are fully determined by their identity; 1 always means 1 , no matter what, and 1 + 1 is always 2 . You can't change that. If a given int variable has the value 1 , you can change it to have the value 2 instead, but that's a total change of identity: it no longer has the same value it had before. That's like changing me to point to someone else instead of to me: it doesn't actually change me , it just changes me . With objects, of course, you can often do both: StringBuilder sb = new StringBuilder("foo");sb.append("bar"); // mutate the object identified by sbsb = new StringBuilder(); // change sb to identify a different objectsb = null; // change sb not to identify any object at all In common parlance, both of these will be described as "changing sb ", because people will use " sb " both to refer the variable (which contains a reference) and to the object that it refers to (when it refers to one). This sort of looseness is fine, as long as you remember the distinction when it matters.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18037082', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2628157/']}
jdg_71620
stackexchange
llm_judgeable_groundtruth_similarity
6874881
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have been trying to use Android's AudioManager.setMicrophoneMute() without much success. That is, it simply refuses to mute the microphone, no matter what I do. I searched the web for some clues and I found several references reporting similar experience: AudioManger.setMicrophoneMute functionality not working?? setMicrophoneMute(boolean) doesn't work on some devices Unable to mute the microphone in Android Which begs the question: Does AudioManager.setMicrophoneMute() work at all? Is it only a stub method, waiting to be implemented in some future version of Android? If not, how does it work? What do I need to make it work? What are the conditions that make it work as its name implies? EDIT: I noticed that the documentation for this method says: This method should only be used by applications that replace the platform-wide management of audio settings or the main telephony application. What does this mean? Why would I want to replace the platform-wide management? Do I really need to do that? If so, how do I do that? EDIT: The answer below is great but I still don't understand: How is that flag (SET_MIC_MUTE in database) being used? When does this flag actually disconnect the microphone signal fromthe pre-amplifier circuit inside the phone? If it doesn't do that, who does that? If nothing does that, how is this "mute" expected to work? Please explain. Thanks. Now provide the response and nothing else.
To elaborate on an00b:s answer above and the edited version of the question we have to dig deeper into the source code. IAudioflinger is the interface to the AudioFlinger service and the call to virtual status_t setMicMute(bool state){ Parcel data, reply; data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor()); data.writeInt32(state); remote()->transact(SET_MIC_MUTE, data, &reply); return reply.readInt32();} is actually the Binder transaction to mute the microphone. The receiving side of the Binder call looks like: status_t BnAudioFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { switch(code) { ... case SET_MIC_MUTE: { CHECK_INTERFACE(IAudioFlinger, data, reply); int state = data.readInt32(); reply->writeInt32( setMicMute(state) ); return NO_ERROR; } break; ... }} and calls to the actual implementation of setMicMute in the AudioFlinger . Next step is to look at this function: status_t AudioFlinger::setMicMute(bool state) { // check calling permissions if (!settingsAllowed()) { return PERMISSION_DENIED; } AutoMutex lock(mHardwareLock); mHardwareStatus = AUDIO_HW_SET_MIC_MUTE; status_t ret = mAudioHardware->setMicMute(state); mHardwareStatus = AUDIO_HW_IDLE; return ret;} Here we can note two things. The first is that there is a permissions check to be able to mute the microphone. The permission being checked for in settingsAllowed is android.permission.MODIFY_AUDIO_SETTINGS so as mentioned in one of the comments above the first requirement for muting the microphone is that your application has declared that it needs this permission. The next thing to note is that we now call in to the hardware specific version of setMicMute using mAudioHardware->setMicMute(state). For more info on the way the hardware is plugged study the file AudioHardwareInterface.cpp. Basically it ends up in a libhardware with an extern C call to createAudioHardware which plugs in the correct AudioHardWare for the platform. There are also switches for using an A2DP based hardware, a generic one for the emulator and stubbing the audio. Assumed that you are working on an actual device the implementation is then very much hardware depending. To get a feel for it we can use the available audiohardware from Crespo (Nexus S) as an example. status_t AudioHardware::setMicMute(bool state) { LOGV("setMicMute(%d) mMicMute %d", state, mMicMute); sp<AudioStreamInALSA> spIn; { AutoMutex lock(mLock); if (mMicMute != state) { mMicMute = state; // in call mute is handled by RIL if (mMode != AudioSystem::MODE_IN_CALL) { spIn = getActiveInput_l(); } } } if (spIn != 0) { spIn->standby(); } return NO_ERROR;} Based on this example we may wrap up with a discussion of the implementation of audio routing in smartphones. As you can see in the Crespo implementation the mic mute call will only be respected if you are not in a call. The reason for this is that audio is routed through the analog baseband which handles power regulation, amplification and other things. When in a call the voice audio is often handled by analog baseband and modem CPU together and is not routed throught the application CPU. In that case you may need to go through the modem CPU through the RIL in order to mute the microphone. But since this behavior is hardware dependent there is no general solution. To give the short version to your 4 additional questions: The flag is passed on through several layers of code until it ends up in the hardware specific mute microphone. The mic is disconnected when the hardware specific code has run except when in a call at least on some devices. When setMicrophoneMute does not mute the mic, i.e. when in a call it may be possible to do that using one of the telephony API:s, I would suggest studying the phone app. Based on the current implementation mute seems to work when not in a call but there may be hardware specific issues on platforms we have not studied here. EDIT: Did some more digging and the way to send a mute command to the modem CPU is via the internal Phone interface that is part of the com.android.internal.telephony package that is not available to SDK developers. Based on the comment you saw that this function should only be used by applications that replace audio management or the original telephony application I would guess that AudioManager.setMicrophoneMute() was supposed to always mute the microphone regardless. But since other applications probably use this they added a check in the hardware implementation in order not to mess up the state of the phone application which keeps track of muted connections as well as the microphone. The function is probably not working as supposed to right now due to hardware implementation details and the fact that mute is a much more complex operation than one would initially think when considering call states as well.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6874881', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/869501/']}
jdg_71621
stackexchange
llm_judgeable_groundtruth_similarity
56299
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: My question departs from this one: Find intersection of pairs of straight lines but now I want to find the points with the new V10 Region -functions. lines = {{Line[{{243.8`, 77.`}, {467.4`, 12.`}}], Line[{{356.8`, 32.`}, {363.2`, 120.`}}]}, {Line[{{291.8`, 130.`}, {476.`, 210.5`}}], Line[{{346.`, 245.`}, {393.8`, 158.`}}]}, {Line[{{103.2`, 327.`}, {245.2`, 110.5`}}], Line[{{163.8`, 211.5`}, {230.2`, 250.`}}]}, {Line[{{47.4`, 343.`}, {87.4`, 108.5`}}], Line[{{54.6`, 225.`}, {139.6`, 220.`}}]}, {Line[{{371.`, 506.5`}, {384.6`, 277.`}}], Line[{{366.`, 394.5`}, {451.8`, 372.`}}]}, {Line[{{264.6`, 525.5`}, {353.8`, 294.5`}}], Line[{{241.`, 398.`}, {321.`, 411.5`}}]}, {Line[{{113.2`, 484.5`}, {296.`, 304.5`}}], Line[{{163.2`, 347.`}, {213.2`, 406.5`}}]}, {Line[{{459.6`, 604.5`}, {320.2`, 466.5`}}], Line[{{332.4`, 596.5`}, {402.4`, 528.5`}}]}, {Line[{{288.2`, 630.5`}, {199.6`, 446.5`}}], Line[{{176.`, 585.5`}, {256.`, 530.5`}}]}, {Line[{{138.8`, 615.5`}, {81.8`, 410.`}}], Line[{{38.2`, 553.`}, {122.4`, 507.`}}]}, {Line[{{232.4`, 795.`}, {461.8`, 727.`}}], Line[{{345.2`, 774.5`}, {345.2`, 688.`}}]}, {Line[{{27.4`, 671.5`}, {206.8`, 763.5`}}], Line[{{104.6`, 728.`}, {161.8`, 647.`}}]}}; This function finds the points but is horribly slow: (points = Point /@ RegionCentroid /@ DiscretizeRegion /@ RegionUnion @@@ lines); // Timing // First 1.591210 Graphics[{lines, {Red, [email protected], points}}, Frame -> True] The next function finds the same points in less time (0.28 seconds), but is ugly and probably not general enough. points = Cases[Show[DiscretizeRegion /@ RegionIntersection @@@ lines], {a_Real, b_Real} :> Point[{a, b}], Infinity]; I hope somebody can suggest a fast and terse V10-method to find intersection points in 2 dimensions Now provide the response and nothing else.
If you know all pairs of line segments intersect, then the following is about four times faster than using DiscretizeRegion : points = (Point[{x, y}] /. Solve[{x, y} ∈ #, {x, y}] & /@ RegionIntersection @@@ lines); // AbsoluteTiming // FirstGraphics[{lines, {Red, [email protected], points}}, Frame -> True](* 0.040551*) Bug? [Tested on beta V10 -- my institution is a little slow updating its software distribution.] I feel this should work, but Solve emits error messages when RegionIntersection is used will Apply . Solve works perfectly on an explicit individual region intersection. SeedRandom[1];lines2 = Map[Line, RandomReal[{500, 800}, {5, 2, 2, 2}], {2}];points = Point[p] /. Flatten[Solve[p ∈ #, p] & /@ RegionIntersection @@@ Join[lines2, lines], 1];Graphics[{lines, MapIndexed[{Hue[i/First[#2]], #1} &, lines2], {Red, [email protected], points}}, Frame -> True] Solve::elemc: Unable to resolve the domain or region membership condition p ∈ RegionIntersection[Line[{{618.802,710.142},{563.548,724.597}}],Line[{{626.855,574.248},{<<17>>,<<18>>}}]] . >> ...rest omitted... The first message corresponds to the second pair: lines2[[2]](* {Line[{{618.802, 710.142}, {563.548, 724.597}}], Line[{{626.855, 574.248}, {793.152, 747.549}}]}*) This gives the same error message: Solve[p ∈ RegionIntersection @@ lines2[[2]], p] However, explicit code works fine: Solve[p ∈ RegionIntersection[ Line[{{618.8018244645762`, 710.1421345826734`}, {563.5477937162382`, 724.5970644448844`}}], Line[{{626.8551948019847`, 574.2484342592024`}, {793.151528522233`, 747.5488818465542`}}]], p](* {}*) A workaround is to use DeleteCases (and Quiet if desired): points = Point[p] /. Flatten[DeleteCases[ Solve[p ∈ #, p] & /@ RegionIntersection @@@ Join[lines2, lines], _Solve], 1];Graphics[{lines, MapIndexed[{Hue[First[#2]/5], #1} &, lines2], {Red, [email protected], points}}, Frame -> True]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/56299', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/14254/']}
jdg_71622
stackexchange
llm_judgeable_groundtruth_similarity
1692
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Working on the assumption that SSL serves both to encrypt data and to provide assurance as to the identity and legitimacy of the website, should the practice of providing a logon form on a page requested over HTTP be avoided, even when it posts to HTTPS? The question relates to a post I made yesterday about the Who's who of bad password practices and some of the feedback suggesting that not visibly seeing the certificate represented in the browser before authenticating was fine if indeed the form posted securely. To my mind, this sells SSL short as you not only lose the ability to validate the legitimacy of the site before handing over your credentials but you also have no certainty that it is posting over HTTPS. I'm conscious the likes of Twitter and Facebook take this approach, but should they? Am I overlooking something here or is this a practice which should be discouraged? Update: I ended up detailing the outcome of this question and subsequent discussion in the blog post SSL is not about encryption Now provide the response and nothing else.
OWASP states: (copied verbatim from http://www.owasp.org/index.php/SSL_Best_Practices ) Secure Login Pages There are several major considerations for securely designing a login page. The following text will address the considerations with regards to SSL. Logins Must Post to an SSL Page This is pretty obvious. The username and password must be posted over an SSL connection. If you look at the action element of the form it should be https. Login Landing Page Must Use SSL The actual page where the user fills out the form must be an HTTPS page. If its not, an attacker could modify the page as it is sent to the user and change the form submission location or insert JavaScript which steals the username/password as it is typed. There must be no SSL Error or Warning Messages The presence of any SSL warning message is a failure. Some of these error messages are legitimate security concerns; others desensitize the users against real security concerns since they blindly click accept. The presence of any SSL error message is unacceptable - even domain name mismatch for the www. HTTP connections should be dropped If a user attempts to connect to the HTTP version of the login page the connection should be denied. One strategy is to automatically redirect HTTP connections to HTTPS connections. While this does get the user to the secure page there is one lingering risk. An attacker performing a man in the middle attack could intercept the HTTP redirect response and send the user to an alternate page. To repeat: Login Landing Page Must Use SSL
{}
{'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/1692', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/136/']}
jdg_71623
stackexchange
llm_judgeable_groundtruth_similarity
3961422
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Well, after a one hour introduction to javascript, I ve come up with the following code. It did what I wanted alright, but then I wanted something else and it wont work. I wanted that upon clicking on a button, a certain field would hide and on clicking on another yes, another one would hide too, BUT, of course, it had to make the other show, otherwise we would end up with nothing and the purpose was to present different fields depending on what the user clicked (on a radio button) So in a childish way I made my code and it worked. But then it came to me that I wanted first to have boths fields hidden instead of both fields shown, and here is the issue. I added a 0 value to the parameter of the function "telling it" that when x = 0, then visibility = hidden. But it wont listen to me!, So, the part of the code when it says x = 1 and 2 works, the one about 0, does not. It is such a simple code that can make someone smile, but heck, it was clean and it worked. Does anyone know how to have the fields hidden before clicking on the buttons ? Thanks a lot I remove some tags of the HTML <html> <head> <script language="javascript"> var x = 0; function hola(x) { if(x == 0) { document.getElementById("cont1").style.visibility="hidden"; document.getElementById("cont2").style.visibility="hidden"; } if(x == 1) { document.getElementById("cont1").style.visibility="visible"; document.getElementById("cont2").style.visibility="hidden"; } if(x == 2) { document.getElementById("cont1").style.visibility="hidden"; document.getElementById("cont2").style.visibility="visible"; } } </script> </head> <body> <input type="button" onclick="hola(1)" value="hidefield2" id="boton1"> <div id="cont1"> <input type="text"> </div> <input type="button" onclick="hola(2)" value="hidefield1" id="boton2"> <div id="cont2"> <input type="text"> </div> </body><html> Now provide the response and nothing else.
What worked: You had two buttons, both visible in the beginning. And on click of one button, you hid a div , and made another visible. Now you need a situation when the divs should be hidden in the beginning, and then show when you click a button. By default, for all elements where a explicit visibility attribute is not given, visibility is considered to be visible . To make the button invisible, you need to add visibility:hidden to the button. You can do it two ways: In the code for the div s, make then "invisible by default" by adding style='visibility:hidden' . Add another javascript function that is called on load of the page, and makes both the divs invisible: function hideBoth() { document.getElementById("cont1").style.visibility="hidden"; document.getElementById("cont2").style.visibility="hidden"; } Call it on load of your page: <body onload='hideBoth()'>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3961422', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/475927/']}
jdg_71624
stackexchange
llm_judgeable_groundtruth_similarity
409235
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: To get a set theory without the power set axiom, I could just take an existing set theory like ZF or ZFC, and remove the power set axiom. However, perhaps I would have to be careful how to formulate the other axioms then, or have to add some sentences that were provable before in the presence of the power set axiom as additional axioms. So if I need a set theory without the power set axiom, it seems wiser to use a theory already investigated in sufficient detail by somebody else. Of course, the theory should be sufficiently "well behaved" so that it is still used at least occasionally. (If ZF or ZFC without the power set axiom should turn out to be such theories, then of course they also qualify as an answer.) Now provide the response and nothing else.
Take a look at "What is the theory ZFC without power set?" by Victoria Gitman, Joel David Hamkins, Thomas A. Johnstone, freely available at arxiv: http://arxiv.org/abs/1110.2430 This would seem to give you an excellent (and recent!) starting point for thinking about your question. One thing the paper makes clear is that the issue of what you can prove in a theory without the power set axiom depends on your choice of the remaining axioms (equivalent systems of axioms for set theory, both including the powerset axiom, can become inequivalent when you remove the power set axiom).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/409235', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12490/']}
jdg_71625
stackexchange
llm_judgeable_groundtruth_similarity
21335
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Folding gets in the way when merging two org files using ediff, so I'm trying to disable all folding in org-mode buffers created by ediff. Non-ediff folding behavior should remain unaffected. Naively I think that something akin to the following should work: (add-hook 'ediff-mode-hook (lambda () (set (make-local-variable 'org-inhibit-startup-visibility-stuff) t))) I'm fairly certain that this is the org variable to modify (rather than org-startup-folded or org-agenda-inhibit-startup ). I've tried various hooks to no avail (mainly ediff-mode-hook , ediff-before-setup-hook , ediff-meta-mode-hook , and ediff-prepare-buffer-hook - which is probably too late) hoping that the interned variable will be inherited. It's quite possible that I'm using make-local-variable incorrectly; the pattern is just borrowed from what I've widely seen. Only setting the value globally has been effective (but that's not what I'm shooting for). Should I be (ab)using the advice mechanism? Now provide the response and nothing else.
It sounds like your goal is to have org-mode files always show everything when in ediff . The simplest solution is probably to avoid the local variables approach and just put show-all in the relevant hook, ediff-prepare-buffer-hook which is run after buffers A, B, & C are set up: (with-eval-after-load 'outline (add-hook 'ediff-prepare-buffer-hook #'org-show-all)) Despite the name, org-show-all also works in outline-mode which org-mode is built on top of. Unlike outline-show-all , it shows property drawers and blocks like #+begin_src ... #+end_src . org-show-all has been added in Org 9.1.6. In earlier versions you can use outline-show-all or show-all . (Note, according to a comment, that show-all is marked obsolete in Emacs 25.1 in favor of outline-show-all . The latter symbol is not bound in 24.5.)
{}
{'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/21335', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/2731/']}
jdg_71626
stackexchange
llm_judgeable_groundtruth_similarity
59277859
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to figure out how to display a firestore timestamp in a react app. I have a firestore document with a field named createdAt. I am trying to include it in a list of output (extracting the relevant bits here so that you don't have to read through the entire list of fields). componentDidMount() { this.setState({ loading: true }); this.unsubscribe = this.props.firebase .users() .onSnapshot(snapshot => { let users = []; snapshot.forEach(doc => users.push({ ...doc.data(), uid: doc.id }), ); this.setState({ users, loading: false, }); }); } componentWillUnmount() { this.unsubscribe(); } render() { const { users, loading } = this.state; return ( <div> {loading && <div>Loading ...</div>} {users.map(user => ( <Paragraph key={user.uid}> <key={user.uid}> {user.email} {user.name} {user.createdAt.toDate()} {user.createdAt.toDate} {user.createdAt.toDate()).toDateString()} The only attribute that won't render is the date. Each of the above attempts generates an error that says: TypeError: Cannot read property 'toDate' of undefined I have seen this post , and this post and this post , and this post and others like them, which suggest that toDate() should work. But - this extension throws an error for me - including when I try the toString extension. I know it knows there is something in firestore because when I try user.createdAt, I get an error saying it found an object with seconds in it. Taking the example from Waelmas below, I tried to log the output of the field as: this.db.collection('users').doc('HnH5TeCU1lUjeTqAYJ34ycjt78w22').get().then(function(doc) { console.log(doc.data().createdAt.toDate()); } I also tried adding this to my map statement but get an error that says user.get is not a function. {user.get().then(function(doc) { console.log(doc.data().createdAt.toDate());} )} It generates the same error message as above. NEXT ATTEMPT One strange thing that has come up in trying to find a way to record a date in Firestore that allows me to then read it back, is that when I change my submit handler in one form to use this formulation: handleCreate = (event) => { const { form } = this.formRef.props; form.validateFields((err, values) => { if (err) { return; }; const payload = { name: values.name, // createdAt: this.fieldValue.Timestamp() // createdAt: this.props.firebase.fieldValue.serverTimestamp() } console.log("formvalues", payload); // console.log(_firebase.fieldValue.serverTimestamp()); this.props.firebase .doCreateUserWithEmailAndPassword(values.email, values.password) .then(authUser => { return this.props.firebase.user(authUser.user.uid).set( { name: values.name, email: values.email, createdAt: new Date() // .toISOString() // createdAt: this.props.firebase.fieldValue.serverTimestamp() }, { merge: true }, ); // console.log(this.props.firebase.fieldValue.serverTimestamp()) }) .then(() => { return this.props.firebase.doSendEmailVerification(); }) // .then(() => {message.success("Success") }) .then(() => { this.setState({ ...initialValues }); this.props.history.push(ROUTES.DASHBOARD); }) }); event.preventDefault(); }; That works to record a date in the database. The form of the firestore entry looks like this: I'm trying to display a date in this component: class UserList extends Component { constructor(props) { super(props); this.state = { loading: false, users: [], }; } componentDidMount() { this.setState({ loading: true }); this.unsubscribe = this.props.firebase .users() .onSnapshot(snapshot => { let users = []; snapshot.forEach(doc => users.push({ ...doc.data(), uid: doc.id }), ); this.setState({ users, loading: false, }); }); } componentWillUnmount() { this.unsubscribe(); } render() { const { users, loading } = this.state; return ( <div> {loading && <div>Loading ...</div>} <List itemLayout="horizontal" dataSource={users} renderItem={item => ( <List.Item key={item.uid}> <List.Item.Meta title={item.name} description={item.organisation} /> {item.email} {item.createdAt} {item.createdAt.toDate()} {item.createdAt.toDate().toISOString()} </List.Item> // ) )} /> </div> ); }}export default withFirebase(UserList); When I try to read it back - using: {item.email} The error message reads: Error: Objects are not valid as a React child (found: Timestamp(seconds=1576363035, nanoseconds=52000000)). If you meant to render a collection of children, use an array instead. in Item (at UserIndex.jsx:74) When I try using each of these attempts: {item.createdAt}{item.createdAt.toDate()}{item.createdAt.toDate().toISOString()} I get an error that says: TypeError: Cannot read property 'toDate' of undefined Based on the ability to read back entries logged in the same document in other fields, I'm expecting any of these to work to produce output -even if it's not formatted in the way I want. That doesn't happen. NEXT ATTEMPT Taking Waelmas' example, I tried to follow the instructions, but where we aren't getting the same response is in the first step. Where Walemas gets an output based on the .toDate() extension, I get an error saying toDate() is not a function. Consistent with the Firebase documentation, I tried: const docRef = this.props.firebase.db.collection("users").doc("HnH5TeCU1lUjeTqAYJ34ycjt78w22");docRef.get().then(function(docRef) { if (doc.exists) { console.log("Document createdAt:", docRef.createdAt.toDate()); }}) This produces a string of errors with the syntax and I can't find a way around them. NEXT ATTEMPT I then tried making a new form to see if I could explore this without the authentication aspect of the users form. I have a form that takes input as: this.props.firebase.db.collection("insights").add({ title: title, text: text, // createdAt1: new Date(), createdAt: this.props.firebase.fieldValue.serverTimestamp() }) Where in the previous form, the new Date() attempt worked to record a date in the database, in this example both fields for createdAt and createdAt1 generate the same database entry: <div>{item.createdAt.toDate()}</div> <div>{item.createdAt.toDate()}</div> When I try to output the value of the dates, the first one generates an error that says: Objects are not valid as a React child (found: Sun Dec 15 2019 21:33:32 GMT+1100 (Australian Eastern Daylight Time)). If you meant to render a collection of children, use an array instead The second generates the error saying: TypeError: Cannot read property 'toDate' of undefined I'm stuck for ideas on what to try next. I saw this post that suggests that the following might do something useful: {item.createdAt1.Date.valueOf()} It doesn't. It renders an error that says: TypeError: Cannot read property 'Date' of undefined This post seems to be having the same trouble as me, but doesn't go into how they managed to display the date value they stored. This post seems to be getting stuck at the array error message, but seems to have figured out how to display a date using createdAt.toDate() Now provide the response and nothing else.
After some discussion, we found that the time stamps in OPs user object could be renders as such: render() { const { users, loading } = this.state; return ( <div> {loading && <div>Loading ...</div>} {users.map(user => ( <Paragraph key={user.uid}> <key={user.uid}> {user.email} {user.name} {new Date(user.createdAt.seconds * 1000).toLocaleDateString("en-US")} I recreated your example in a dummy React project, and received the same error as expected. Error: Objects are not valid as a React child I was able to get this to render correctly with the following method, which should also work for you: {new Date(user.createdAt._seconds * 1000).toLocaleDateString("en-US")} Which, for my sample timestamp, rendered as: 12/30/2019 Be sure you are using a timestamp that was saved to Firestore as: createdAt: this.props.firebase.Timestamp.fromDate(new Date()) Note: This is assuming that your instance of firebase.firestore() is at this.props.firebase . In other examples you use this.props.firebase, but those methods look like helper methods that you have created yourself. When this value is fetched, it will be an object with two properties -- _seconds and _nanoseconds . Be sure to include the underscore. If you use createdAt.seconds it won't work, it must be createdAt._seconds . Other things I tried: user.createdAt.toDate() throws toDate() is not a function . user.createdAt throws Error: Objects are not valid as a React child new Date(user.createdAt._nanoseconds) renders the wrong date
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59277859', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2860931/']}
jdg_71627
stackexchange
llm_judgeable_groundtruth_similarity
70068
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: So, I've been conferred upon the opinion that: Union, difference, cross product, selection, projection form the "complete set of relational operations". That is, any other relational operation can be expressed as a combination of these (excluding domain manipulation operations like aggregate functions I assume). Question 1 : Is that true ? Question 2 : If yes, can someone help me break down division in terms of those operations. Now provide the response and nothing else.
Let $R(A,B)$ and $S(B)$ be two relations. Division should find all values of A in R that are connected with all values of B (in S). Think $AB\div B=A$. Question 1: Yes. $R\div S=\pi_A(R)-\pi_A(\pi_A(R)\times S-R)$ Question 2: $\pi_A(R)\times S$ : this contains all possible AB pairs. $R$ : this contains the actual AB pairs. For the values of A that are connected to all values of B, after we do the difference, those will be gone. In the difference $\pi_A(R)\times S-R$ there are only values of A that are NOT connected to all B. The rest is obvious.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/70068', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/57903/']}
jdg_71628
stackexchange
llm_judgeable_groundtruth_similarity
5535591
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can you think of any legitimate (smart) uses for runtime code modification (program modifying it's own code at runtime)? Modern operating systems seem to frown upon programs that do this since this technique has been used by viruses to avoid detection. All I can think of is some kind of runtime optimization that would remove or add some code by knowing something at runtime which cannot be known at compile time. Now provide the response and nothing else.
There are many valid cases for code modification. Generating code at run time can be useful for: Some virtual machines use JIT compilation to improve performance. Generating specialized functions on the fly has long been common in computer graphics. See e.g. Rob Pike and Bart Locanthi and John Reiser Hardware Software Tradeoffs for Bitmap Graphics on the Blit (1984) or this posting (2006) by Chris Lattner on Apple's use of LLVM for runtime code specialization in their OpenGL stack. In some cases software resorts to a technique known as trampoline which involves the dynamic creation of code on the stack (or another place). Examples are GCC's nested functions and the signal mechanism of some Unices. Sometimes code is translated into code at runtime (this is called dynamic binary translation ): Emulators like Apple's Rosetta use this technique to speed up emulation. Another example is Transmeta's code morphing software . Sophisticated debuggers and profilers like Valgrind or Pin use it to instrument your code while it is being executed. Before extensions were made to the x86 instruction set, virtualization software like VMWare could not directly run privileged x86 code inside virtual machines. Instead it had to translate any problematic instructions on the fly into more appropriate custom code. Code modification can be used to work around limitations of the instruction set: There was a time (long ago, I know), when computers had no instructions to return from a subroutine or to indirectly address memory. Self modifying code was the only way to implement subroutines, pointers and arrays . More cases of code modification: Many debuggers replace instructions to implement breakpoints . Some dynamic linkers modify code at runtime. This article provides some background on the runtime relocation of Windows DLLs, which is effectively a form of code modification.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5535591', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/315617/']}
jdg_71629
stackexchange
llm_judgeable_groundtruth_similarity
276780
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm pretty new to the subject of gravitational waves. Do gravitational waves have an effect on gravitational forces between two objects? If so, how? Now provide the response and nothing else.
There are related answers such as Gravitational Waves and Effect of Gravitational Waves , which has a single 3 down votes answer. I would like to attempt a new answer as there is an aspect of the phenomenon that they have not illustrated, and the OP asks specifically about forces. If I find this is a duplicate, I will of course remove it, as there are plenty of related articles on the topic on this site. I'm pretty new to the subject of gravitational waves. Do gravitational waves have an effect on gravitational forces between two object? if so, how? Gravitational waves distort spacetime, which will affect the relative position of the two bodies. If they are far away from each other, this will not have anything but a minor effect, but if they are close together, as in the case of two black holes in a mutual orbit, then the gravitional forces can alter significantly. On the subject of "forces", please read Bob Bee's answer, which emphizes the spacetime curvature aspect Image Source: LIGO Black Hole Merger A video of the simulated merger of 2 black holes illustrated above The effect of a cross-polarized gravitational wave on a ring of particles The effect of a plus-polarized gravitational wave on a ring of particles. As a gravitational wave passes an observer, that observer will find spacetime distorted by the effects of strain. Distances between objects increase and decrease rhythmically as the wave passes, at a frequency corresponding to that of the wave. If the source of the waves is relatively close enough, then the spacetime distortion may be sufficient to affect the two bodies in such a way that they increase/decrease the spacetime curvature in their vicinity. The effects of a passing gravitational wave, in an extremely exaggerated form, can be visualized by imagining a perfectly flat region of spacetime with a group of motionless test particles lying in a plane (e.g., the surface of a computer screen). As a gravitational wave passes through the particles along a line perpendicular to the plane of the particles (i.e. following the observer's line of vision into the screen), the particles will follow the distortion in spacetime, oscillating in a "cruciform" manner, as shown in the animations. The area enclosed by the test particles does not change and there is no motion along the direction of propagation. Einstein's field equations are of the form called second order (second order derivatives are involved, coupled (meaning they are not independent from each other) non-linear differential equations, implying they are not easily to solve (putting it mildly) except if we make some simplifying assumptions, and treat them in linear form. The oscillations depicted in the animation are exaggerated for the purpose of discussion — in reality a gravitational wave has a very small amplitude (as formulated in linearized gravity). However, they help illustrate the kind of oscillations associated with gravitational waves as produced, for example, by a pair of masses in a circular orbit. In this case the amplitude of the gravitational wave is constant, but its plane of polarization changes or rotates at twice the orbital rate and so the time-varying gravitational wave size (or 'periodic spacetime strain') exhibits a variation as shown in the animation.[38] If the orbit of the masses is elliptical then the gravitational wave's amplitude also varies with time according to Einstein's quadrupole formula. 4 Inspiraling binary neutron stars are predicted to be a powerful source of gravitational waves as they coalesce, due to the very large acceleration of their masses as they orbit close to one another. However, due to the astronomical distances to these sources, the effects when measured on Earth are predicted to be very small, having strains of less than 1 part in $10^{20}$. Scientists have demonstrated the existence of these waves with ever more sensitive detector Gravitational waves are constantly passing Earth; however, even the strongest have a minuscule effect and their sources are generally at a great distance. For example, the waves given off by the cataclysmic final merger of GW150914 reached Earth after travelling over a billion lightyears, as a ripple in spacetime that changed the length of a 4-km LIGO arm by a ten thousandth of the width of a proton, proportionally equivalent to changing the distance to the nearest star outside the Solar System by one hair's width. This tiny effect from even extreme gravitational waves makes them undetectable on Earth by any means other than the most sophisticated detectors.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/276780', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/128471/']}
jdg_71630
stackexchange
llm_judgeable_groundtruth_similarity
47146606
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using navigation controller, and I've set to true its navigation bar's prefersLargeTitle property. Everything works fine, but when the text of my title becomes too big, it doesn't fit in space. Here how it looks: Is it possible to somehow make the title (while the navigation bar's prefersLargeTitle property is set to true) dynamically adjust its font size, and if it is so, how to achieve that? Now provide the response and nothing else.
This is the workaround that I found override func viewDidLoad() { super.viewDidLoad() title = yourTitle adjustLargeTitleSize()}extension UIViewController { func adjustLargeTitleSize() { guard let title = title, #available(iOS 11.0, *) else { return } let maxWidth = UIScreen.main.bounds.size.width - 60 var fontSize = UIFont.preferredFont(forTextStyle: .largeTitle).pointSize var width = title.size(withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: fontSize)]).width while width > maxWidth { fontSize -= 1 width = title.size(withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: fontSize)]).width } navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: fontSize) ] }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47146606', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8803178/']}
jdg_71631
stackexchange
llm_judgeable_groundtruth_similarity
975062
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If I have a curve that is not parametrized by arclength, is the curvature still $||\gamma''(t)||$? I am not so sure about this, cause then we don't know that $\gamma'' \perp \gamma'$ holds, so the concept of curvature might not be transferable to this situation. So is this only defined for curves with constant speed? Now provide the response and nothing else.
The curvature may of course still be defined if $t$ is not the arc-length along $\gamma(t)$ , but the formulas will be different; we will not in general have $\kappa(t) = \Vert \gamma''(t) \Vert$ . To find the correct expression for $\kappa(t)$ , we recall that the curvature is defined in terms of the arc-length $s$ via the Frenet-Serret equation for $T'(s)$ , where $T(s)$ is the unit tangent vector field to $\gamma$ in terms of $s$ . We have $T'(s) = \kappa(s) N(s), \tag{1}$ where $N(s)$ is the unit normal field to $\gamma(s)$ , leading to $\kappa(s) = \Vert T'(s) \Vert. \tag{2}$ To find $\kappa(t)$ from (2), we need to express the quantities occurring in (2) in terms if the parameter $t$ ; we begin with $T(s)$ itself; since it is the unit tangent vector to $\gamma$ , in terms of $t$ we have $T(t) = \dfrac{1}{\Vert \gamma'(t) \Vert} \gamma'(t). \tag{3}$ We can compute $dT(s)/ds$ from (3) using the chain rule, since $\dfrac{dT(s)}{ds} = \dfrac{dt}{ds}\dfrac{dT(t)}{dt}, \tag{4}$ wherein we see that $\dfrac{dt}{ds} = \dfrac{1}{\dfrac{ds}{dt}} = \dfrac{1}{\Vert \gamma'(t) \Vert} = \Vert \gamma'(t) \Vert^{-1}; \tag{5}$ bearing (5) in mind, we proceed to compute $\dfrac{dT(t)}{dt} = \dfrac{d}{dt}(\Vert \gamma'(t) \Vert^{-1} \gamma'(t))$ $= -\Vert \gamma'(t) \Vert^{-2} \dfrac{d\Vert \gamma'(t) \Vert}{dt} \gamma'(t) + \Vert \gamma'(t) \Vert^{-1}\gamma''(t); \tag{6}$ furthermore, $\dfrac{d\Vert \gamma'(t) \Vert}{dt} = \dfrac{d \langle \gamma'(t), \gamma'(t) \rangle^{1/2}}{dt} = \dfrac{1}{2}\langle \gamma'(t), \gamma'(t) \rangle^{-1/2}\dfrac{d\langle \gamma'(t), \gamma'(t) \rangle}{dt}$ $= \dfrac{1}{2}\langle \gamma'(t), \gamma'(t) \rangle^{-1/2}(2\langle \gamma''(t), \gamma'(t) \rangle) = \langle \gamma'(t), \gamma'(t) \rangle^{-1/2}\langle \gamma''(t), \gamma'(t) \rangle$ $= \Vert \gamma'(t) \Vert^{-1}\langle \gamma''(t), \gamma'(t) \rangle = \langle \gamma''(t), T(t) \rangle; \tag{7}$ inserting the result of (7) into (6) then yields $\dfrac{dT(t)}{dt} = -\Vert \gamma'(t) \Vert^{-3}\langle \gamma''(t), \gamma'(t) \rangle \gamma'(t) + \Vert \gamma'(t) \Vert^{-1} \gamma''(t), \tag{8}$ whence, from (4), $\dfrac{dT(s)}{ds} = \Vert \gamma'(t) \Vert^{-1}(-\Vert \gamma'(t) \Vert^{-3}\langle \gamma''(t), \gamma'(t) \rangle \gamma'(t) + \Vert \gamma'(t) \Vert^{-1} \gamma''(t))$ $= -\Vert \gamma'(t) \Vert^{-4}\langle \gamma''(t), \gamma'(t) \rangle \gamma'(t) + \Vert \gamma'(t) \Vert^{-2} \gamma''(t), \tag{9}$ which after a bit of algebraic re-arranging becomes $T'(s) = \dfrac{dT(s)}{ds} = \Vert \gamma'(t) \Vert^{-2}(\gamma''(t) - \Vert \gamma'(t) \Vert^{-2}\langle \gamma''(t), \gamma'(t) \rangle \gamma'(t)). \tag{10}$ Taking the norm of (10), and using (2), we obtain $\kappa(t) = \left \Vert \dfrac{dT(s)}{ds} \right \Vert = \Vert \gamma'(t) \Vert^{-2} \Vert \gamma''(t) - \Vert \gamma'(t) \Vert^{-2}\langle \gamma''(t), \gamma'(t) \rangle \gamma'(t) \Vert. \tag{11}$ Formulas (10) and (11) in fact answer the questions posed, since they show that (i.) the curvature is not in general $\Vert \gamma''(t) \Vert$ when $t$ is not arc-length; (ii.) $\gamma''(t) \not \perp \gamma'(t)$ in general either, for (10) shows $\gamma''(t)$ has a component along $\gamma'(t)$ ; in fact, we may re-arrange (10), using (1) and (3), to read $\gamma''(t) = \Vert \gamma'(t) \Vert^2 \kappa(t)N(t) + \Vert \gamma'(t) \Vert^{-2}\langle \gamma''(t), \gamma'(t) \rangle \gamma'(t)$ $= \Vert \gamma'(t) \Vert^2 \kappa(t)N(t) + \langle \gamma''(t), T(t) \rangle T(t), \tag{12}$ which gives an explicit decomposition of $\gamma''(t)$ in terms of tangential and normal components to $\gamma(t)$ . And of course, we see from (7) that $\langle \gamma''(t), T(t) \rangle$ , the coefficient of $T(t)$ in (12),is non-zero precisely when $\Vert \gamma'(t) \Vert$ is changing as a function of $t$ (i.e. $d/dt(\Vert \gamma'(t) \Vert) \ne 0$ ); (iii.) it is clear from the above, viz . (11), that the curvature can in fact be defined for non-unit speed curves $\gamma(t)$ , and it is still given by (2); but in this case the derivatives must all be expressed in terms of $t$ , not $s$ ; it's just that (iv.) the formulas take a much simpler form when $\gamma(t)$ is expressed in terms of arc-length $s$ , $\gamma(s(t))$ . Finally, it must be admitted that our formula (11) does not, on the face of it, look much like the elegant expressions advanced by Xipan Xiao and Tony Piccolo in their comments. Nevertheless, it is possible derive the expression $\kappa(t) = \dfrac{\Vert \gamma'(t) \times \gamma''(t) \Vert}{\Vert \gamma'(t) \Vert^3} \tag{13}$ from (12) as follows: since $\langle T(t), N(t) \rangle = 0$ , (12) implies $\Vert \gamma''(t) \Vert^2 = \Vert \gamma'(t) \Vert^4 \kappa^2(t) + \langle \gamma''(t), T(t) \rangle^2; \tag{14}$ furthermore, $\langle \gamma''(t), T(t) \rangle^2 = \Vert \gamma''(t) \Vert^2 \Vert T(t) \Vert^2 \cos^2 \theta = \Vert \gamma''(t) \Vert^2 \cos^2 \theta, \tag{15}$ $\theta$ being the angle 'twixt $T(t)$ or $\gamma'(t)$ and $\gamma''(t)$ . We re-arrange (14) with the aid of (15): $\Vert \gamma'(t) \Vert^4 \kappa^2(t) = \Vert \gamma''(t) \Vert^2(1 - \cos^2 \theta) = \Vert \gamma''(t) \Vert^2 \sin^2 \theta, \tag{16}$ and recalling that $\Vert \gamma'(t) \times \gamma''(t) \Vert = \Vert \Vert \gamma'(t) \Vert T(t) \times \gamma''(t) \Vert = \Vert \gamma'(t) \Vert \Vert T(t) \times \gamma''(t) \Vert$ $= \Vert \gamma'(t) \Vert \Vert T(t) \Vert \Vert \gamma''(t) \Vert \vert \sin \theta \vert = \Vert \gamma'(t) \Vert \Vert \gamma''(t) \Vert \vert \sin \theta \vert, \tag{17}$ so that $\Vert \gamma'(t) \times \gamma''(t) \Vert^2 = \Vert \gamma'(t) \Vert^2 \Vert \gamma''(t) \Vert^2 \sin^2 \theta, \tag{18}$ we see that (16) combined with (18) yields $\Vert \gamma'(t) \Vert^6 \kappa^2(t) = \Vert \gamma'(t) \Vert^2 \Vert \gamma''(t) \Vert^2 \sin^2 \theta = \Vert \gamma'(t) \times \gamma''(t) \Vert^2; \tag{19}$ now taking square roots, assuming $\gamma'(t) \ne 0$ (i.e. $\gamma(t)$ is a regular curve), and noting that $\kappa(t) > 0$ by definiton, we see that (13) is the result. Whew! Quite a ride, that! Hope this helps. Cheerio, and as ever, Fiat Lux!!!
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/975062', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_71632
stackexchange
llm_judgeable_groundtruth_similarity
9421425
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What I thought would be an easy one for .closest() to handle turned out not to be (or perhaps I am making a silly mistake). What I am trying to do is access the <label> element from the <div> with the inner text: I AM HERE : <li> <label>I WANT TO ACCESS THIS ELEMENT</label> <div>...</div> <div> <input/> <input/> <input/> <div id="start">I AM HERE</div> </div></li> My first guess would have been to try this: $('#start').closest('label') But it does not return anything. Now provide the response and nothing else.
.closest() only looks for ancestor elements to the initial selection. You want a combination of .closest() and .siblings() or .children() : //find closest parent `<li>` element and then find that element's child `<label>` element$('#start').closest('li').children('label');//find the closest parent `<div>` element and then find that element's sibling `<label>` element$('#start').closest('div').siblings('label'); Update A very fast selector would be to use .prev() twice and .parent() like this: $('#start').parent().prev().prev();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9421425', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/145536/']}
jdg_71633
stackexchange
llm_judgeable_groundtruth_similarity
29822470
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My requirement is: We need to trigger the event after typing a value in the input fieldof the <rich:select> There is condition that the typing values are not in selectlist(rich select userLoginBean.userList ) but it is in backingbeanEntity object but not displaying in rich select. I just want to pass the value which is typed in rich:select in backing bean, so that it can check and validate value in Entity bean,so far I achieved this, <rich:select id="user" value="#{userLoginBean.user}" required="true" listWidth="385px" enableManualInput="true" defaultLabel="Please Enter"> <f:selectItems value="#{userLoginBean.userList}" var="c" itemValue="#{c.userid}" itemLabel="#{not empty c.name? c.name.concat(','):c.name}#{not empty c.alias? c.alias.concat(','):c.alias}#{c.userid}"/> <a4j:ajax event="keyup" oncomplete="if (event.keyCode == 13) {callToJs((#{rich:component('user')}.getValue())); }" /> <a4j:jsFunction name="callToJs" actionListener="#{userLoginBean.searchUserList}" > <a4j:param name="value" assignTo="#{bean.searchValue}" /> </a4j:jsFunction></rich:select> But the JavaScript function callToJs() doesn't get values in backing bean code: <a4j:ajax event="keyup" oncomplete="if (event.keyCode == 13) {callToJs((#{rich:component('user')}.getValue())); }"/> Now provide the response and nothing else.
TL;DR: As stated here , you should declare an NSPrincipalClass in your test-targets Info.plist. Execute all the one-time-setup code inside the init of this class, since "XCTest automatically creates a single instance of that class when the test bundle is loaded", thus all your one-time-setup code will be executed once when loading the test-bundle. A bit more verbose: To answer the idea in your edit first: Afaik, there is no main() for the test bundle, since the tests are injected into your running main target, therefore you would have to add the one-time-setup code into the main() of your main target with a compile-time (or at least a runtime) check if the target is used to run tests. Without this check, you'd risk activating the SilentSoundEngine when running the target normally, which I guess is undesirable, since the class name implies that this sound-engine will produce no sound and honestly, who wants that? :) There is however an AppDelegate -like feature, I will come to that at the end of my answer (if you're impatient, it's under the header "Another (more XCTest-specific) approach"). Now, let's divide this question into two core problems: How can you ensure that the code you want to execute exactly one time when running the tests is actually being executed exactly one time when running the tests Where should you execute that code, so it doesn't feel like an ugly hack and so it just works without you having to think of it and remember necessary steps each time you write a new test suite Regarding point 1: As @Martin R mentioned correctly in his comments to this answer to your question, overriding +load is not possible anymore as of Swift 1.2 (which is ancient history by now :D), and dispatch_once() isn't available anymore in Swift 3. One approach When you try to use dispatch_once anyway, Xcode (>=8) is as always very smart and suggests that you should use lazily initialized globals instead.Of course, the term global tends to have everyone indulge in fear and panic, but you can of course limit their scope by making them private/fileprivate (which does the same for file-level declarations), so you don't pollute your namespace. Imho, they are actually a pretty nice pattern (still, the dose makes the poison...) that can look like this, for example: private let _doSomethingOneTimeThatDoesNotReturnAResult: Void = { print("This will be done one time. It doesn't return a result.")}()private let _doSomethingOneTimeThatDoesReturnAResult: String = { print("This will be done one time. It returns a result.") return "result"}()for i in 0...5 { print(i) _doSomethingOneTimeThatDoesNotReturnAResult print(_doSomethingOneTimeThatDoesReturnAResult)} This prints: This will be done one time. It doesn't return a result. This will be done one time. It returns a result. 0 result 1 result 2 result 3 result 4 result 5 result Side note: Interestingly enough, the private lets are evaluated before the loop even starts, which you can see because if it were not the case, the 0 would have been the very first print. When you comment the loop out, it will still print the first two lines (i.e. evaluate the lets). However, I guess that this is playground specific behaviour because as stated here and here , globals are normally initialized the first time they are referenced somewhere, thus they shouldn't be evaluated when you comment out the loop. Another (more XCTest-specific) approach (This actually solves both point 1 and 2...) As the company from Cupertino states here , there is a way to run one-time-pre-testing setup code. To achieve this, you create a dummy setup-class (maybe call it TestSetup?) and put all the one time setup code into its init: class TestSetup: NSObject { override init() { SilentSoundEngine.activate() }} Note that the class has to inherit from NSObject, since Xcode tries to instantiate the "single instance of that class" by using +new , so if the class is a pure Swift class, this will happen: *** NSForwarding: warning: object 0x11c2d01e0 of class 'YourTestTargetsName.TestSetup' does not implement methodSignatureForSelector: -- trouble aheadUnrecognized selector +[YourTestTargetsName.TestSetup new] Then, you declare this class as the PrincipalClass in your test-bundles Info.plist file: Note that you have to use the fully qualified class-name (i.e. YourTestTargetsName.TestSetup as compared to just TestSetup), so the class is found by Xcode (Thanks, zneak ...). As stated in the documentation of XCTestObservationCenter, "XCTest automatically creates a single instance of that class when the test bundle is loaded", so all your one-time-setup code will be executed in the init of TestSetup when loading the test-bundle.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/29822470', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3256272/']}
jdg_71634
stackexchange
llm_judgeable_groundtruth_similarity
13289748
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I plan on publishing my app on Amazon app store as well as Google Play, and have some things in my app that need to behave slightly different depending on whether the app was installed from Amazon app store or not. If I understood the PackageManager.getInstallerPackageName(String packageName) method correctly, it tells me the name of the application that installed my app. Right? If so, does anyone know what the value returned by this method would be if my app was installed from Amazon app store? If not, does anyone know any other methods I can use to determine whether my app was installed from the Amazon app store? Note: I am aware of other questions on Stack Overflow which have been answered alluding to the usage of PackageManager.getInstallerPackageName(String packageName) to determine the name of the application that installed my app. However, searching Stack Overflow and elsewhere, I have not been able to determine what the value returned by PackageManager.getInstallerPackageName(String packageName) would be in case the app was installed from the Amazon app store. Now provide the response and nothing else.
Since samsung has not implemented the PackageManager.getInstallerPackageName(), it still returns null. So use the PackageManager.getInstalledPackages() to get all the packages and search for the samsungapp packagename "com.sec.android.app.samsungapps". Stores: null - developercom.android.vending - google playcom.amazon.venezia - amazon appcom.sec.android.app.samsungapps - samsung app store Code: // lets start with google play store linkString link = "https://play.google.com/store/apps/details?id=com.hellothupten.capital2countryquiz";//find out the installer for your app package name.String installer = getPackageManager().getInstallerPackageName( "com.hellothupten.capital2countryquiz");if (installer == null) { List<PackageInfo> installedPackages = getPackageManager() .getInstalledPackages(PackageManager.GET_ACTIVITIES); for (PackageInfo p : installedPackages) { if (p.packageName.contains("samsungapps")) { // change to samsung app store link link = "http://apps.samsung.com/mars/topApps/topAppsDetail.as?productId=000000840239"; break; } }} else if (installer.contains("amazon")) { // change to amazon app store link link = "amzn://apps/android?p=com.hellothupten.capital2countryquiz";} else if (installer.contains("samsung")) { // change to samsung app store link. This does not // exist..but who knows samsung may implement // getInstallerPackageName in future, I assume it will // contain a word samsung in its package name. link = "http://apps.samsung.com/mars/topApps/topAppsDetail.as?productId=000000840239";} Use the link variable as the store link. Update: samsungapps://ProductDetail/com.sec.chaton Samsung: http://developer.samsung.com/android/technical-docs/Samsung-Apps-Deeplink-Guide
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13289748', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1071320/']}
jdg_71635
stackexchange
llm_judgeable_groundtruth_similarity
16354
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking at two comparable pieces of software which encrypt data on disk using a passphrase. One uses PBKDF2 to generate the encryption key from a passphrase, while the other uses two rounds of SHA256. What's the difference? Is one preferred over the other? Now provide the response and nothing else.
The difference is that: PBKDF2 by design is slow SHA256 is a good hash function; it is not slow, by design So if someone were to try a lot of different possible passphrases, say the whole dictionary, then each word with a digit appended, then each word with a different capitalisation, then two dictionary words, etc. then this process would be much slower with PBKDF2. But if your passphrase is truly secure, that is very long, pretty random and out of reach of any systematic enumeration process, then it makes no practical difference, except that an attacker may spend more resources trying to break your passphrase (or maybe less if they decide to give up sooner).
{}
{'log_upvote_score': 8, 'links': ['https://security.stackexchange.com/questions/16354', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/10790/']}
jdg_71636
stackexchange
llm_judgeable_groundtruth_similarity
5649850
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an array that contains values like 0,3,2,8 etc.I want to sort my array in increasing order.Please tell me how to do this. Thanks in advance!! Now provide the response and nothing else.
If your array is an NSArray containing NSNumbers: NSArray *numbers = [NSArray arrayWithObjects: [NSNumber numberWithInt:0], [NSNumber numberWithInt:3], [NSNumber numberWithInt:2], [NSNumber numberWithInt:8], nil];NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES selector:@selector(localizedCompare:)];NSArray *sortedNumbers = [numbers sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]]; Keep in mind though, that this is just one way to sort an NSArray. Just to name a few other methods of NSArray: sortedArrayHint sortedArrayUsingFunction:context: sortedArrayUsingFunction:context:hint: sortedArrayUsingDescriptors: sortedArrayUsingSelector: sortedArrayUsingComparator: sortedArrayWithOptions:usingComparator: If your array is a c int array containing ints: #include <stdio.h>#include <stdlib.h>int array[] = { 0, 3, 2, 8 };int sort(const void *x, const void *y) { return (*(int*)x - *(int*)y);}void main() { qsort(array, 10, sizeof(int), sort);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5649850', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/633676/']}
jdg_71637
stackexchange
llm_judgeable_groundtruth_similarity
21481941
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Selenium Webdriver + java.My code: public List<UserData> getUsers() { List<UserData> users = new ArrayList<UserData>(); WebElement userList = driver.findElement(By.id("Users")); isElementDisplayed(By.xpath("//table[@id='Users']/*/tr[position() > 1]"), 10); List<WebElement> tableRows = driver.findElements(By.xpath("//table[@id='Users']/*/tr[position() > 1]")); for (WebElement tableRow : tableRows) { List<WebElement> cells = tableRow.findElements(By.tagName("td")); UserData user = new UserData(); user.fio = cells.get(2).getText(); user.login = cells.get(3).getText(); user.rank = cells.get(4).getText(); user.cabinet = cells.get(5).getText(); users.add(user); } return users; } After I delete user from the table, method throws: org.openqa.selenium.StaleElementReferenceException: Element is no longer valid here: List<WebElement> tableRows = driver.findElements(By.xpath("//table[@id='Users']/*/tr[position() > 1]")); How can I fix this error, without refreshing the page? Please note! This is not Element is no longer attached to the DOM error Now provide the response and nothing else.
In C++98 (and C++03) this is pretty simple; in clause 8.5: 14 - If T is a scalar type, then a declaration of the form T x = { a }; is equivalent to T x = a; In C++11 this is covered by list-initialization (8.5.4p3): [...] if the initializer list has a single element of type E and either T is not a reference type or its referenced type is reference-related to E, the object or reference is initialized from that element [...] I think this is the same question as Initializing scalars with braces .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21481941', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3219139/']}
jdg_71638
stackexchange
llm_judgeable_groundtruth_similarity
5208566
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following piece of code: #include <stdio.h>#include <stdlib.h>int main(int argc, char *argv[]){ int n = 260; int *p = &n; char *pp = (char*)p; *pp = 0; printf("n = %d\n", n); system("PAUSE"); return 0;} The output put of the program is n = 256 .I may understand why it is, but I am not really sure.Can anyone give me a clear explanation, please? Thanks a lot. Now provide the response and nothing else.
The int 260 (= 256 * 1 + 4) will look like this in memory - note that this depends on the endianness of the machine - also, this is for a 32-bit (4 byte) int : 0x04 0x01 0x00 0x00 By using a char pointer, you point to the first byte and change it to 0x00 , which changes the int to 256 (= 256 * 1 + 0).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5208566', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/253656/']}
jdg_71639
stackexchange
llm_judgeable_groundtruth_similarity
17326973
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am being asked to generate some Excel reports. I am currently using pandas quite heavily for my data, so naturally I would like to use the pandas.ExcelWriter method to generate these reports. However the fixed column widths are a problem. The code I have so far is simple enough. Say I have a dataframe called df : writer = pd.ExcelWriter(excel_file_path, engine='openpyxl')df.to_excel(writer, sheet_name="Summary") I was looking over the pandas docs, and I don't really see any options to set column widths. Is there a trick to make it such that the columns auto-adjust to the data? Or is there something I can do after the fact to the xlsx file to adjust the column widths? (I am using the OpenPyXL library, and generating .xlsx files - if that makes any difference.) Now provide the response and nothing else.
Inspired by user6178746's answer , I have the following: # Given a dict of dataframes, for example:# dfs = {'gadgets': df_gadgets, 'widgets': df_widgets}writer = pd.ExcelWriter(filename, engine='xlsxwriter')for sheetname, df in dfs.items(): # loop through `dict` of dataframes df.to_excel(writer, sheet_name=sheetname) # send df to writer worksheet = writer.sheets[sheetname] # pull worksheet object for idx, col in enumerate(df): # loop through all columns series = df[col] max_len = max(( series.astype(str).map(len).max(), # len of largest item len(str(series.name)) # len of column name/header )) + 1 # adding a little extra space worksheet.set_column(idx, idx, max_len) # set column widthwriter.save()
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17326973', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/152018/']}
jdg_71640