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
|
3684440
|
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 use sprite imagesI have a very basic link <td align="center"> <img alt="my alt text" src="/Assets/t/myImage.gif" /></td> I am struggling for a while, tying to change this and making it use an image in my sprite instead of the src
Now provide the response and nothing else.
|
This is not possible at all: PHP serves HTML code. The browser renders it. Only after it is rendered, can height be determined reliably. Different browsers may end up with different heights. Different user settings (like font size) may end up with different heights. The only way to find out an element's height is using JavaScript which runs in the browser. You can theoretically send the results back to a separate PHP script using Ajax, but I doubt that'll make much sense. You could use jQuery's .height() like so: var height = $("#elementID").height(); (there are native JavaScript approaches to this as well, but they tend to be a bit long and complicated.)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3684440', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/385411/']}
|
jdg_378441
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13486850
|
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 developing in xCode for exactly 3 days now. The last time I did UI development it was in Windows 3.1 with the Petzold book. Regardless of that I have my first iOS app up and running and it basically does what I need. I have two sliders to select hue and saturation, and in response to them I dynamically draw a bunch of gradient shaded circles. I got that much running between the Hello World example and stackoverflow, including caching the gradient in CGLayer (so thanks to all the stackoverflow people). There is one little piece that I can't quite get right though: I want to set the initial value of one slider to 1.0 instead of the default 0.5. I know I can do that in IB, but I prefer to code it and I think I'd like to move away from IB altogether. I don't really understand how it makes connections between things and I'd like to understand the code. I have code like this to try to set it: - (void)viewDidLoad{ NSLog(@"viewDidLoad"); [super viewDidLoad]; [hue_slider setValue:0.5]; [sat_slider setValue:1.0]; self.led_view.hue_slider_value=0.5; self.led_view.sat_slider_value=1.0;// Do any additional setup after loading the view, typically from a nib.} sat_slider still ends up in the middle instead of at the end (1.0 is the max value). From stackexchange reading I understand that I am probably calling this at the wrong time, that the slider hasn't really been loaded when viewDidLoad is called, and my initial value is overwritten by the one specified in IB. What I haven't seen though is where the call should be made. So the question: Where in my program should I put [sat_slider setValue:1.0]; so that it sets the initial value of the slider, overwriting the default in IB? Can someone explain the order of how things start up in an iOS program? And a pointer to online or printed books regarding iOS and Objective C programming would be great. Edit When I check the value of sat_slider it is nil. So that means a connection is missing? I dragged it in the storyboard and created an IBOutlet in addition to an action. @interface led_testViewController : UIViewController- (IBAction)saturation_scroll:(id)sender;- (IBAction)hue_scroll:(id)sender;@property (retain, nonatomic) IBOutlet UISlider *hue_slider;@property (retain, nonatomic) IBOutlet UISlider *sat_slider;@property (strong, nonatomic) IBOutlet led_view *led_view;@end
Now provide the response and nothing else.
|
There are two ways that I think you can accomplish this. It all depends on your target platform and how important resources are but here we go: 1) If resources aren't an issue You could put all your normal scene and battle scene objects in one scene. Create two empty game objects (One for Town Scene objects and the other for Battle Scene Objects). You can then either have two versions of your game character(s) or one. Then write a script that simply switches the camera(s) from the town scene to the battle scene when a battle is triggered and back to the town scene when the battle is over. If you have one version of each character you could simply add a script that changes the behaviour of your game character controller to/from battle mode and normal/town mode. If you have two versions of each character then you would simply need to write the appropriate character controller scripts and activate/deactivate the game characters according to which one you are using. This is how games like Final Fantasy 7,8,9 achieved the same effect. There were two versions of the game characters: one for battle mode and the other for normal mode. 2) If resources ARE an issue (and I think a more efficient way) You could use the Application.LoadLevelAdditive function. This function allows you to load a different scene and rather than destroy everything in the current scene, it takes the new scene and all it's objects and adds them to the current scene.So basically you can use it something like this: Create a separate battlescene and within your scene, create an empty game object to hold every object in your scene. In your noraml scene do the same. When you need to go to battle mode use: Application.LoadLevelAdditive ('battlescene'); And when/if you want to unload your battlescene after that you can do so by simply writing code to destroy the battlescene game object since it contains everything from your battle scene. As with the first method you can decide whether you want to have two different versions of your characters or not. One of the pros of having two versions is that if you want to save time by not going into detail with you game models (especially if your game is really big) you can have save processing power by using scaled down models for the town scene and using polished more detailed models for the battle scene, assuming your battle scene is a small stage representing the place where your characters are fighting. Think final fantasy VII. Just something to consider. I hope that helps. I've written it all in a rush but lemme know if anything needs clearing up.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13486850', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1683910/']}
|
jdg_378442
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3321743
|
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 looking for a way get the following from a users youtube name or url. thumbnail link to video on youtube.com Title of the video Need to do it with PHP. Is there some youtube api I can use or is something like simple pie my best bet?
Now provide the response and nothing else.
|
Look at the code <?phperror_reporting(E_ALL);$feedURL = 'http://gdata.youtube.com/feeds/api/users/USER-ID/uploads?max-results=50';$sxml = simplexml_load_file($feedURL);$i=0;foreach ($sxml->entry as $entry) { $media = $entry->children('media', true); $watch = (string)$media->group->player->attributes()->url; $thumbnail = (string)$media->group->thumbnail[0]->attributes()->url; ?> <div class="videoitem"> <div class="videothumb"><a href="<?php echo $watch; ?>" class="watchvideo"><img src="<?php echo $thumbnail;?>" alt="<?php echo $media->group->title; ?>" /></a></div> <div class="videotitle"> <h3><a href="<?php echo $watch; ?>" class="watchvideo"><?php echo $media->group->title; ?></a></h3> <p><?php echo $media->group->description; ?></p> </div> </div> <?php $i++; if($i==3) { echo '<div class="clear small_v_margin"></div>'; $i=0; } } ?> Code is copied from the post SimpleXML loop works but breaks half way through It will get a users all youtube videos. Now it is very easy to develop your own.Know more about YouTube API from https://code.google.com/apis/youtube/2.0/reference.html
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3321743', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/157503/']}
|
jdg_378443
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11162473
|
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 Assembla to manage my Subversion repository. I have started some major revisions to my codebase and want to create a Tag of my most recent production revision ( which I forgot to do when I pushed that rev live to production a few weeks ago ). I'm currently on revision 588, and want to create a Tag of revision 577. How do I go about doing this from the command line using Subversion within Assembla? Assume my Assembla SVN URL is: https://subversion.assembla.com/svn/my_assembla_svn_directory/
Now provide the response and nothing else.
|
You can always use the -r parameter to refer to a specific revision. When doing so, you can also use the @rev revision pinning to make sure you're referring to the layout of the Subversion revision at a particular revision. The following will create a tag from trunk on revision 577 and call this tag REV-1.2 : $ svn cp -r 577 https://subversion.assembla.com/svn/my_assembla_svn_directory/trunk https://subversion.assembla.com/svn/my_assembla_svn_directory/tags/REV-1.2 If you don't have a trunk , branches , and tags directories, you'll need to move your work in order to create some: $ # Move the current directory to the "trunk"$ svn cp https://subversion.assembla.com/svn/my_assembla_svn_directory \ https://subversion.assembla.com/svn/my_assembla_svn_directory/trunk$ # Make a corresponding tags and branches directories too$ svn mkdir https://subversion.assembla.com/svn/my_assembla_svn_directory/branches$ svn mkdir https://subversion.assembla.com/svn/my_assembla_svn_directory/tags$ # Now, we can delete the old location. Let your developers know this,$ # so they're not surprised by this and will be able to do a "svn relocate"$ svn delete https://subversion.assembla.com/svn/my_assembla_svn_directory/$ # Whoops. I should have done the tagging when I had a chance. $ #Oh well, we'll use the `@rev` pinning:$ svn -r557 cp https://subversion.assembla.com/svn/my_assembla_svn_directory@557 \ https://subversion.assembla.com/svn/my_assembla_svn_directory/tags/REL-1.2 Subversion doesn't implement tagging and branching except as a copy. This isn't unusual. Perforce implements branching in the same way. In fact, once you get use to it, it works out really well: It's easy to see the valid branches and tags (simply do a svn ls on the right directory The complete history of tags and branches are easy to see. You can see who made the change, when, why, etc. The complete history of the tag or branch is shown. If someone changes a tag or branch, you see who did it very clearly. It discourages the helter-skelter type of branching you see in many other version control systems when developers pick and choose over various branches and the trunk what to branch or tag. That makes tracking the history very difficult to do. Subversion's scheme encourages you to think of branches and tags as affecting all files in a project.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11162473', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/456578/']}
|
jdg_378444
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31940285
|
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 create a color wheel in Python, preferably using Matplotlib. The following works OK: import numpy as npimport matplotlib as mplimport matplotlib.pyplot as pltxval = np.arange(0, 2*pi, 0.01)yval = np.ones_like(xval)colormap = plt.get_cmap('hsv')norm = mpl.colors.Normalize(0.0, 2*np.pi)ax = plt.subplot(1, 1, 1, polar=True)ax.scatter(xval, yval, c=xval, s=300, cmap=colormap, norm=norm, linewidths=0)ax.set_yticks([]) However, this attempt has two serious drawbacks. First, when saving the resulting figure as a vector ( figure_1.svg ), the color wheel consists (as expected) of 621 different shapes, corresponding to the different (x,y) values being plotted. Although the result looks like a circle, it isn't really. I would greatly prefer to use an actual circle, defined by a few path points and Bezier curves between them, as in e.g. matplotlib.patches.Circle . This seems to me the 'proper' way of doing it, and the result would look nicer (no banding, better gradient, better anti-aliasing). Second (relatedly), the final plotted markers (the last few before 2*pi ) overlap the first few. It's very hard to see in the pixel rendering, but if you zoom in on the vector-based rendering you can clearly see the last disc overlap the first few. I tried using different markers ( . or | ), but none of them go around the second issue. Bottom line: can I draw a circle in Python/Matplotlib which is defined in the proper vector/Bezier curve way, and which has an edge color defined according to a colormap (or, failing that, an arbitrary color gradient)?
Now provide the response and nothing else.
|
One way I have found is to produce a colormap and then project it onto a polar axis. Here is a working example - it includes a nasty hack, though (clearly commented). I'm sure there's a way to either adjust limits or (harder) write your own Transform to get around it, but I haven't quite managed that yet. I thought the bounds on the call to Normalize would do that, but apparently not. import matplotlib.pyplot as pltimport numpy as npfrom matplotlib import cmimport matplotlib as mplfig = plt.figure()display_axes = fig.add_axes([0.1,0.1,0.8,0.8], projection='polar')display_axes._direction = 2*np.pi ## This is a nasty hack - using the hidden field to ## multiply the values such that 1 become 2*pi ## this field is supposed to take values 1 or -1 only!!norm = mpl.colors.Normalize(0.0, 2*np.pi)# Plot the colorbar onto the polar axis# note - use orientation horizontal so that the gradient goes around# the wheel rather than centre outquant_steps = 2056cb = mpl.colorbar.ColorbarBase(display_axes, cmap=cm.get_cmap('hsv',quant_steps), norm=norm, orientation='horizontal')# aesthetics - get rid of border and axis labels cb.outline.set_visible(False) display_axes.set_axis_off()plt.show() # Replace with plt.savefig if you want to save a file This produces If you want a ring rather than a wheel, use this before plt.show() or plt.savefig display_axes.set_rlim([-1,1]) This gives As per @EelkeSpaak in comments - if you save the graphic as an SVG as per the OP, here is a tip for working with the resulting graphic: The little elements of the resulting SVG image are touching and non-overlapping. This leads to faint grey lines in some renderers (Inkscape, Adobe Reader, probably not in print). A simple solution to this is to apply a small (e.g. 120%) scaling to each of the individual gradient elements, using e.g. Inkscape or Illustrator. Note you'll have to apply the transform to each element separately (the mentioned software provides functionality to do this automatically), rather than to the whole drawing, otherwise it has no effect.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31940285', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1692028/']}
|
jdg_378445
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
51445767
|
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 define an interface which has some information on the format of a string? Take the following example: interface timeMarkers{ markerTime: string[] }; an example would be: { markerTime: ["0:00","1:30", "1:48"] } My question: Is there a way to define the type for markerTime such that that the string value must always match this regex, instead of declaring it as simply string[] and going from there? var reg = /[0-9]?[0-9]:[0-9][0-9]/;
Now provide the response and nothing else.
|
There is no way to define such a type. There is a proposal on GitHub to support this, but it currently does not appear to be a priority. Vote on it and maybe the team might include it in a future release. Edit Starting in 4.1 you can define a type that would validate the string without actually defining all the options: type MarkerTime =`${number| ''}${number}:${number}${number}`let a: MarkerTime = "0-00" // errorlet b: MarkerTime = "0:00" // oklet c: MarkerTime = "09:00" // ok Playground Link
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/51445767', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1336678/']}
|
jdg_378446
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
169366
|
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 want certain files to be able to be altered by myself on my basic account. To me, they are high priority files, with many backups. But we have some young'uns in the house and I don't quite trust them. I feel like they will find a way to delete the files. Is there a way I could hide them, or make them invisible without a command needed to be input from the command line?
Now provide the response and nothing else.
|
Directory permissions: The write bit allows the affected user to create, rename, or deletefiles within the directory, and modify the directory's attributes The read bit allows the affected user to list the files within thedirectory The execute bit allows the affected user to enter the directory, andaccess files and directories inside The sticky bit states that files and directories within thatdirectory may only be deleted or renamed by their owner (or root) You can save the files under the ownership of root user and thus this will require them to use password before accessing those files. As said in directory permissions, you can take away 'write bit' and 'execute bit' thus not allowing them to enter directory. only give them read permission so that they can view files without altering and deleting them. you can learn the use of sticky bit ( link here ) and disabling alter and delete feature on every file inside that directory If they have root password then hiding files is only the way to protect your files and root is god of the system, if they have root password, so they are the real god of your system !
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/169366', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/92149/']}
|
jdg_378447
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19428572
|
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 getting this issue when I type localhost:8000/admin/ . `TemplateSyntaxError: Could not parse the remainder: ':password_change' from 'admin:password_change'. The syntax of 'url' changed in Django 1.5, see the docs. Here's part of my settings.py : INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'grappelli', 'filebrowser', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: #'django.contrib.admindocs', 'tinymce', 'sorl.thumbnail', 'south', 'django_facebook', 'djcelery', 'devserver', 'main',)AUTH_USER_MODEL = 'django_facebook.FacebookCustomUser'AUTHENTICATION_BACKENDS = ( 'django_facebook.auth_backends.FacebookBackend', 'django.contrib.auth.backends.ModelBackend', # Uncomment the following to make Django tests pass: 'django.contrib.auth.backends.ModelBackend',) Did I do anything wrong? PS: This is my full traceback https://gist.github.com/anonymous/e8c1359d384df7a6b405 EDIT: I am pasting the output of grep as per request: $ ack-grep --type=python -r ':password_change' .lib/python2.7/site-packages/django/contrib/admin/sites.py264:url = reverse('admin:password_change_done', current_app=self.name)lib/python2.7/site-packages/grappelli/dashboard/dashboards.py147:reverse('%s:password_change' % site_name)],$ ack-grep --type=html -r ':password_change' .lib/python2.7/site-packages/django/contrib/admin/templates/admin/base.html36:<a href="{% url 'admin:password_change' %}">{% trans 'Change password' %}</a> /lib/python2.7/site-packages/grappelli/templates/admin/includes_grappelli/header.html12:{% url admin:password_change as password_change_url %}
Now provide the response and nothing else.
|
This error usually means you've forgotten a closing quote somewhere in the template you're trying to render. For example: {% url 'my_view %} (wrong) instead of {% url 'my_view' %} (correct). In this case it's the colon that's causing the problem. Normally you'd edit the template to use the correct {% url %} syntax . But there's no reason why the django admin site would throw this, since it would know it's own syntax. My best guess is therefore that grapelli is causing your problem since it changes the admin templates. Does removing grappelli from installed apps help?
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/19428572', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/356875/']}
|
jdg_378448
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
434140
|
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 struct like this: class Items {private: struct item { unsigned int a, b, c; }; item* items[MAX_ITEMS];} Say I wanted to 'delete' an item, like so: items[5] = NULL; And I created a new item on that same spot later: items[5] = new item; Would I still need to call delete[] to clean this up? Or won't this be needed since bounds of array items[] are known before compiling? Is setting that pointer to NULL valid or should I be calling delete there?
Now provide the response and nothing else.
|
You need to call delete before setting it to NULL. (Setting it to NULL isn't required, it just helps reduce bugs if you accidentally try to dereference the pointer after deleting it.) Remember that every time you use new , you will need to use delete later on the same pointer. Never use one without the other. Also, new [] and delete [] go together in the same way, but you should never mix new [] with delete or new with delete [] . In your example, since you created the object with new (rather than new [] which would create an array of objects) you must delete the object with delete (rather than delete [] ).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/434140', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51133/']}
|
jdg_378449
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
115749
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Do all the field theorems apply to surreal numbers? If fields were redefined so that their elements were allowed to come from an arbitrary class, would the theory look different to an algebraist?
Now provide the response and nothing else.
|
First, let me say that the set/class issue is not a problem to deal with properly, and so one shouldn't be very worried about it. It is true as you say that the surreal numbers No are aproper class, and they do not form a set. So in a purely technical sense, they are not a field. But nevertheless, they do satisfy all the field axioms and have all the usual kinds of structure that one would want in a field, and so one can correctly describe them as a proper class field, or Field as Conway writes it, in much the same way that the class of all ordinals is regarded as a proper class well-order. Although this set/class issue may seem mysterious or irritating, in practice it is a routine matterto handle correctly for those familiar with the set/classdistinction. But since you seem particularly interested in what might go wrong, let me suggest on the negative side, one issue that could make a difference is that when dealing with the surreal field No, one will want to strengthen the background set theory from ZFC to GBC, which includes the global axiom of choice, the assertion that there is a proper class well-ordering of the universe. The reason is that it is consistent with ZFC that the surreal numbers do not admit any proper class well-ordering, and actually, the assertion that they have a definable such well-ordering is equivalent to the set-theoretic axiom known as V=HOD, as I proved in my answer to David Feldman's question on a Definable map from all the ordinals to the surreal numbers . So if one wants to undertake algebraic constructions requiring one to have a well-ordering of the field itself, such as finding a proper class maximal ideal inside a particular subring of No, then there could be difficulties undertaking such a construction in ZFC as opposed to GBC. But nevertheless, the theory GBC is conservative over ZFC and one may thereby freely assume the global axiom of choice. (This is used in the various arguments showing that No is universal for class-sized objects, such as the assertion that every class order embeds to a suborder of No.) In particular, in GBC one has a well-ordering of the entire universe, including the surreals, and this situation would address such issues. Much of the theory undertaken by Ehrlich on the surreals, for example, works in GBC as the background theory. Beyond this issue, even in GBC one does not have any sense of a well-ordering of the (meta-class) collection of all class-sized subrings of No, if this were desired for any algebraic construction, and this is the kind of issue that would arise with the set/class issue. But meanwhile, there is also a positive answer. The situation is that if one wants set versions of the surreal numbers, they are abundantly available in increasingly powerful and accurate approximations, which are well-understood and studied. Specifically, we have numerous set-sizedapproximations to the surreal numbers, simply by considering theset of surreal numbers born before a given ordinal birthday. Forany ordinal $\lambda$, let $\text{No}(\lambda)$ be the set of surreal numbersborn before $\lambda$. One should regard $\text{No}(\lambda)$ asthe version of the surreal numbers as constructed inside theset-theoretic universe $V_\lambda$, which can satisfy increasingfragments of our set theory, as $\lambda$ is chosen to exhibitincreasingly strong closure properties. Philip Ehrlich mentioned in his recent talk at the CUNY Logic Workshop that he and Lou van den Dries prove in theirarticle Fields of surreal numbers with exponentiation the following facts: $\text{No}(\lambda)$ is an additive subgroup of No if and onlyif $\lambda=\omega^\alpha$ for some ordinal $\alpha$; that is, ifand only if $\lambda$ is additively indecomposable. $\text{No}(\lambda)$ is an additive subring of No if and onlyif $\lambda=\omega^{\omega^\alpha}$ for some ordinal $\alpha$; that is, if and only if $\lambda$ is multiplicatively indecomposable. $\text{No}(\lambda)$ is a subfield of No if and onlyif $\lambda$ is an $\epsilon$-number , that is, if and only if$\lambda=\epsilon_\alpha$ for some $\alpha$. These facts are proved by giving a careful analysis of exactly how long it takes to add the inverse of a given surreal number, based on its birthday, and so when the ordinal $\lambda$ is closed under those waiting times, then the resulting $\text{No}(\lambda)$ contains the requisite inverses. Ultimately, we obtain set-sized approximations $\text{No}(\lambda)$ to the surreals bytruncating at sufficiently powerful ordinals. Indeed, for any particular natural number $n$, there will be a closed unbounded proper class of ordinals $\lambda$ such that $\text{No}(\lambda)$ has all the same $\Sigma_n$-expressible properties as the full class of surreal numbers No. This can be proved as an immediate consequence of the reflection theorem. So in fact, No is the union of a proper class chain of increasingly elementary subfields $\text{No}(\lambda)$. One can think of the situation as corresponding to the small/large distinction that one finds in category theory with the use of Grothendieck universes, as in Daniel's answer. But in fact one doesn't need a whole Grothendieck universe just to have a subfield, since a mere epsilon number suffices in comparison with an inaccessible cardinal (which are all epsilon numbers).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/115749', 'https://mathoverflow.net', 'https://mathoverflow.net/users/29763/']}
|
jdg_378450
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4052739
|
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:
Given fundamental groupoid $\Pi_1(S^1)$ of the circle, how can one define a topology on it? The information on nlab did little help other than the fact that it can be done since $S^1$ is path-connected. Set theoretically we can make the association with $S^1 \times \mathbb{R}$ but how can we define a topology on $\Pi_1(S^1)$ so that we have a homeomorphism between them?
Now provide the response and nothing else.
|
In order to make the groupoid $\Pi_1(X)$ into a topological groupoid we need to put a topology on the set of objects of $\Pi_1(X)$ and a topology on the set of morphisms of $\Pi_1(X)$ . This is an example of a category internal to $\text{Top}$ . The set of objects already has a topology since objects are just points in $X$ . We can define a topology on the set of homotopy classes of paths in $X$ by defining an open set $S_{[\gamma],U,V}$ around $[\gamma]$ to be the set of all $[\eta * \gamma * \phi]$ where $\phi$ is completely contained in some open $U \subset X$ and $\eta$ is completely contained in some open $V \subset X$ . Assuming that the composition of paths is defined, i.e that $\eta(0) = \gamma(1)$ etc. The topology on the set of homotopy classes of paths in $X$ is the topology generated by all the $S_{[\gamma],U,V}$ . This is similar to how the set of homotopy classes of paths beginning at a base point $x_0 \in X$ is topologized in Hatcher to construct the universal cover.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4052739', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/498395/']}
|
jdg_378451
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5043235
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Having trouble getting the following code to work: $('#changeMode').button().click(function(){ $('#playfield').toggle(function() { $(this).switchClass("gridView","plainView"); }, function() { $(this).switchClass("plainView","gridView"); }); }); I cannot get it to switch the following div's class. <div id="playfield" class="gridView"></div> Any ideas? EDIT: I tried this: $('#changeMode').button().click(function(){ if ($('#playfield').attr('class') == "gridView"){ $('#playfield').removeClass("gridView"); $('#playfield').addClass("plainView"); } else { $('#playfield').removeClass("plainView"); $('#playfield').addClass("gridView"); }}); And it seems to work fine, what the heck?
Now provide the response and nothing else.
|
I wasn't aware of a switchClass, perhaps you were thinking of toggleClass? Anyways - I had some old code that used this (I was having some strange issues with toggleClass): $(this).removeClass("gridView").addClass("plainView"); or$(this).toggleClass("gridView plainView"); and vice versa. Example: $('#changeMode').button().click(function(){ $('#playfield').toggle(function() { $(this).toggleClass("gridView plainView"); //$(this).removeClass("gridView").addClass("plainView"); }, function() { $(this).toggleClass("plainView gridView"); //$(this).removeClass("plainView").addClass("gridView"); }); }); But as others have suggested toggleClass should work for your needs.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5043235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/607025/']}
|
jdg_378452
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38759437
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here is my HTML: <div class="table-wrapper" ng-app="groupModule"> <table class="tablify stylable" ng-controller="listController"> <thead> <tr> <th>Group Name</th> <th>Parent Group</th> <th>Effect</th> <th class="col-actions">Edit</th> <th class="col-actions">Delete</th> </tr> </thead> <tbody> <tr ng-repeat="group in groups"> <td>{{ group.groupName }}</td> <td>{{ group.parentGroupName }}</td> <td>{{ group.effect }}</td> <td class="col-actions"> <button type="button" class="btn btn-info btn-edit"></button> </td> <td class="col-actions"> <button type="button" class="btn btn-danger btn-delete"></button> </td> </tr> </tbody> </table></div> Here is my CSS: .table-wrapper { overflow-y: auto; height: 75%;}table.stylable { text-align: center; width: 100%;}table.stylable th { padding: 5px 0; text-align: center; background-color: #353535; color: white; border-right: 1px solid #DDD; height: 40px; cursor: pointer; cursor: hand;}table.stylable tr { background-color: #EEE;}table.stylable td { background-color: transparent; border-right: 1px solid #DDD;}table.stylable th:last-child,table.stylable td:last-child { border-right: 0px;}table.stylable tr th:first-child { border-top-left-radius: 6px;}table.stylable tr th:last-child { border-top-right-radius: 6px;}table.stylable tr:last-child td:first-child { border-bottom-left-radius: 6px;}table.stylable tr:last-child td:last-child { border-bottom-right-radius: 6px;}table.stylable tr:hover:not(.row-details):not(.selected) { background-color: #AAA; color: white;}table.stylable tr.selected { background-color: #777; color: white;}table.stylable tr:hover td { background-color: transparent;}table.stylable tr.selected td { background-color: transparent;}table.stylable table { width: 100%;}table.stylable td,table.stylable th{ padding: 3px 8px; min-width: 65px;}.btn-edit,.btn-delete{ position: relative; margin: 5px; border: none; width: 60%; padding: 0; padding-bottom: 60%; height: 0; background-size: contain;}.btn-edit { background-image: url(../images/Edit.png);}.btn-delete { background-image: url(../images/Delete.png);}.col-actions{ max-width: 80px;} If anybody wants then here is angular code: var groups = [{groupCode: 1, groupName: "Branch / Divisions"}, {groupCode: 2, groupName: "Capital Account", natureOfGroup: {natureOfGroupCode: 1, nature:"Assets"}, effectOfGroup: {effectOfGroupCode: 1, effect: "Balance Sheet"}}, {groupCode: 3, groupName: "Current Assets", natureOfGroup: {natureOfGroupCode: 1, nature:"Assets"}, effectOfGroup: {effectOfGroupCode: 1, effect: "Balance Sheet"}}, {groupCode: 4, groupName: "Current Liabilities", natureOfGroup: {natureOfGroupCode: 2, nature:"Liabilities"}, effectOfGroup: {effectOfGroupCode: 1, effect: "Balance Sheet"}}, {groupCode: 5, groupName: "Direct Expenses", natureOfGroup: {natureOfGroupCode: 4, nature:"Expenses"}, effectOfGroup: {effectOfGroupCode: 3, effect: "Trading Account"}}, {groupCode: 6, groupName: "Direct Incomes", natureOfGroup: {natureOfGroupCode: 3, nature:"Incomes"}, effectOfGroup: {effectOfGroupCode: 3, effect: "Trading Account"}}, {groupCode: 7, groupName: "Fixed Assets", natureOfGroup: {natureOfGroupCode: 1, nature:"Assets"}, effectOfGroup: {effectOfGroupCode: 1, effect: "Balance Sheet"}}, {groupCode: 8, groupName: "Indirect Expenses", natureOfGroup: {natureOfGroupCode: 4, nature:"Expenses"}, effectOfGroup: {effectOfGroupCode: 2, effect: "Profit & Loss Account"}}, {groupCode: 9, groupName: "Indirect Incomes", natureOfGroup: {natureOfGroupCode: 3, nature:"Incomes"}, effectOfGroup: {effectOfGroupCode: 2, effect: "Profit & Loss Account"}}, {groupCode: 10, groupName: "Investments", natureOfGroup: {natureOfGroupCode: 1, nature:"Assets"}, effectOfGroup: {effectOfGroupCode: 1, effect: "Balance Sheet"}}, {groupCode: 11, groupName: "Loans (Liability)", natureOfGroup: {natureOfGroupCode: 2, nature:"Liabilities"}, effectOfGroup: {effectOfGroupCode: 1, effect: "Balance Sheet"}}, {groupCode: 12, groupName: "Misc. Expenses (Asset)", natureOfGroup: {natureOfGroupCode: 1, nature:"Assets"}, effectOfGroup: {effectOfGroupCode: 1, effect: "Balance Sheet"}}, {groupCode: 13, groupName: "Purchase Accounts", natureOfGroup: {natureOfGroupCode: 4, nature:"Expenses"}, effectOfGroup: {effectOfGroupCode: 3, effect: "Trading Account"}}, {groupCode: 14, groupName: "Sales Accounts", natureOfGroup: {natureOfGroupCode: 3, nature:"Incomes"}, effectOfGroup: {effectOfGroupCode: 3, effect: "Trading Account"}}, {groupCode: 15, groupName: "Suspense A/c", natureOfGroup: {natureOfGroupCode: 2, nature:"Liabilities"}, effectOfGroup: {effectOfGroupCode: 1, effect: "Balance Sheet"}}, {groupCode: 16, groupName: "Bank Accounts", parentGroupCode: 3, natureOfGroup: {natureOfGroupCode: 1, nature:"Assets"}, effectOfGroup: {effectOfGroupCode: 1, effect: "Balance Sheet"}}, {groupCode: 17, groupName: "Bank OD A/c", alias: "Bank OCC A/c", parentGroupCode: 11, natureOfGroup: {natureOfGroupCode: 2, nature:"Liabilities"}, effectOfGroup: {effectOfGroupCode: 1, effect: "Balance Sheet"}}, {groupCode: 18, groupName: "Cash-in-hand", parentGroupCode: 3, natureOfGroup: {natureOfGroupCode: 1, nature:"Assets"}, effectOfGroup: {effectOfGroupCode: 1, effect: "Balance Sheet"}}, {groupCode: 19, groupName: "Deposits (Asset)", parentGroupCode: 3, natureOfGroup: {natureOfGroupCode: 1, nature:"Assets"}, effectOfGroup: {effectOfGroupCode: 1, effect: "Balance Sheet"}}, {groupCode: 20, groupName: "Duties & Taxes", parentGroupCode: 4, natureOfGroup: {natureOfGroupCode: 2, nature:"Liabilities"}, effectOfGroup: {effectOfGroupCode: 1, effect: "Balance Sheet"}}, {groupCode: 21, groupName: "Loans & Advances (Asset)", parentGroupCode: 3, natureOfGroup: {natureOfGroupCode: 1, nature:"Assets"}, effectOfGroup: {effectOfGroupCode: 1, effect: "Balance Sheet"}}, {groupCode: 22, groupName: "Provisions", parentGroupCode: 4, natureOfGroup: {natureOfGroupCode: 2, nature:"Liabilities"}, effectOfGroup: {effectOfGroupCode: 1, effect: "Balance Sheet"}}, {groupCode: 23, groupName: "Reserves & Surplus", alias: "Retained Earnings", parentGroupCode: 2, natureOfGroup: {natureOfGroupCode: 1, nature:"Assets"}, effectOfGroup: {effectOfGroupCode: 1, effect: "Balance Sheet"}}];angular.module('groupModule', []) .controller("listController", function($scope){ $scope.groups = groups.map(function(g){ return { groupCode: g.groupCode, groupName: g.groupName, parentGroupName: groups.filter(function(x){ return x.groupCode == g.parentGroupCode; })[0] == undefined ? 'Primary' : groups.filter(function(x){ return x.groupCode == g.parentGroupCode; })[0].groupName, nature: g.natureOfGroup == undefined ? '' : g.natureOfGroup.nature, effect: g.effectOfGroup == undefined ? '' : g.effectOfGroup.effect }}); }); Here is the JSFiddle reproducing issue: https://jsfiddle.net/Vishal1419/n7qmt8wt/
Now provide the response and nothing else.
|
For table cells the width property should be used, as the 'min-width' and 'max-width' is undefined for table cells. See the specification : The effect of 'min-width' and 'max-width' on tables, inline tables, table cells, table columns, and column groups is undefined. You just have to remember that cells shrink also below the given width since CSS caluclates the width of the cells depending on the table's width and the cells content. So what you can use is the fixed table layout what will change the algorithm behind the width calculation. But what I usually do is to make my own grid with div elements, instead of using tables (because of their weird behavior).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38759437', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2284240/']}
|
jdg_378453
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
40796231
|
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 does XPath deal with XML namespaces? If I use /IntuitResponse/QueryResponse/Bill/Id to parse the XML document below I get 0 nodes back. <?xml version="1.0" encoding="UTF-8" standalone="yes"?><IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2016-10-14T10:48:39.109-07:00"> <QueryResponse startPosition="1" maxResults="79" totalCount="79"> <Bill domain="QBO" sparse="false"> <Id>=1</Id> </Bill> </QueryResponse></IntuitResponse> However, I'm not specifying the namespace in the XPath (i.e. http://schema.intuit.com/finance/v3 is not a prefix of each token of the path). How can XPath know which Id I want if I don't tell it explicitly? I suppose in this case (since there is only one namespace) XPath could get away with ignoring the xmlns entirely. But if there are multiple namespaces, things could get ugly.
Now provide the response and nothing else.
|
Defining namespaces in XPath (recommended) XPath itself doesn't have a way to bind a namespace prefix with a namespace. Such facilities are provided by the hosting library. It is recommended that you use those facilities and define namespace prefixes that can then be used to qualify XML element and attribute names as necessary. Here are some of the various mechanisms which XPath hosts provide for specifying namespace prefix bindings to namespace URIs. (OP's original XPath, /IntuitResponse/QueryResponse/Bill/Id , has been elided to /IntuitResponse/QueryResponse .) C#: XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);nsmgr.AddNamespace("i", "http://schema.intuit.com/finance/v3");XmlNodeList nodes = el.SelectNodes(@"/i:IntuitResponse/i:QueryResponse", nsmgr); Java (SAX): NamespaceSupport support = new NamespaceSupport();support.pushContext();support.declarePrefix("i", "http://schema.intuit.com/finance/v3"); Java (XPath): xpath.setNamespaceContext(new NamespaceContext() { public String getNamespaceURI(String prefix) { switch (prefix) { case "i": return "http://schema.intuit.com/finance/v3"; // ... } }); Remember to call DocumentBuilderFactory.setNamespaceAware(true) . See also: Java XPath: Queries with default namespace xmlns JavaScript: See Implementing a User Defined Namespace Resolver : function nsResolver(prefix) { var ns = { 'i' : 'http://schema.intuit.com/finance/v3' }; return ns[prefix] || null;}document.evaluate( '/i:IntuitResponse/i:QueryResponse', document, nsResolver, XPathResult.ANY_TYPE, null ); Note that if the default namespace has an associated namespace prefix defined, using the nsResolver() returned by Document.createNSResolver() can obviate the need for a customer nsResolver() . Perl ( LibXML ): my $xc = XML::LibXML::XPathContext->new($doc);$xc->registerNs('i', 'http://schema.intuit.com/finance/v3');my @nodes = $xc->findnodes('/i:IntuitResponse/i:QueryResponse'); Python ( lxml ): from lxml import etreef = StringIO('<IntuitResponse>...</IntuitResponse>')doc = etree.parse(f)r = doc.xpath('/i:IntuitResponse/i:QueryResponse', namespaces={'i':'http://schema.intuit.com/finance/v3'}) Python ( ElementTree ): namespaces = {'i': 'http://schema.intuit.com/finance/v3'}root.findall('/i:IntuitResponse/i:QueryResponse', namespaces) Python ( Scrapy ): response.selector.register_namespace('i', 'http://schema.intuit.com/finance/v3')response.xpath('/i:IntuitResponse/i:QueryResponse').getall() PhP: Adapted from @Tomalak's answer using DOMDocument : $result = new DOMDocument();$result->loadXML($xml);$xpath = new DOMXpath($result);$xpath->registerNamespace("i", "http://schema.intuit.com/finance/v3");$result = $xpath->query("/i:IntuitResponse/i:QueryResponse"); See also @IMSoP's canonical Q/A on PHP SimpleXML namespaces . Ruby (Nokogiri): puts doc.xpath('/i:IntuitResponse/i:QueryResponse', 'i' => "http://schema.intuit.com/finance/v3") Note that Nokogiri supports removal of namespaces, doc.remove_namespaces! but see the below warnings discouraging the defeating of XML namespaces. VBA: xmlNS = "xmlns:i='http://schema.intuit.com/finance/v3'"doc.setProperty "SelectionNamespaces", xmlNS Set queryResponseElement =doc.SelectSingleNode("/i:IntuitResponse/i:QueryResponse") VB.NET: xmlDoc = New XmlDocument()xmlDoc.Load("file.xml")nsmgr = New XmlNamespaceManager(New XmlNameTable())nsmgr.AddNamespace("i", "http://schema.intuit.com/finance/v3");nodes = xmlDoc.DocumentElement.SelectNodes("/i:IntuitResponse/i:QueryResponse", nsmgr) SoapUI ( doc ): declare namespace i='http://schema.intuit.com/finance/v3';/i:IntuitResponse/i:QueryResponse xmlstarlet: -N i="http://schema.intuit.com/finance/v3" XSLT: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:i="http://schema.intuit.com/finance/v3"> ... Once you've declared a namespace prefix, your XPath can be written to use it: /i:IntuitResponse/i:QueryResponse Defeating namespaces in XPath (not recommended) An alternative is to write predicates that test against local-name() : /*[local-name()='IntuitResponse']/*[local-name()='QueryResponse'] Or, in XPath 2.0: /*:IntuitResponse/*:QueryResponse Skirting namespaces in this manner works but is not recommended because it Under-specifies the full element/attribute name. Fails to differentiate between element/attribute names in differentnamespaces (the very purpose of namespaces). Note that this concern could be addressed by adding an additional predicate to check the namespace URI explicitly 1 : /*[ namespace-uri()='http://schema.intuit.com/finance/v3' and local-name()='IntuitResponse'] /*[ namespace-uri()='http://schema.intuit.com/finance/v3' and local-name()='QueryResponse'] 1 Thanks to Daniel Haley for the namespace-uri() note. Is excessively verbose.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/40796231', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2077201/']}
|
jdg_378454
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19668395
|
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 some code which works well in Python 2.7. Python 2.7.3 (default, Jan 2 2013, 13:56:14) [GCC 4.7.2] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> from sys import stdout>>> foo = 'Bar'>>> numb = 10>>> stdout.write('{} {}\n'.format(numb, foo))10 Bar>>> But in 2.6 I get a ValueError exception. Python 2.6.8 (unknown, Jan 26 2013, 14:35:25) [GCC 4.7.2] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> from sys import stdout>>> foo = 'Bar'>>> numb = 10>>> stdout.write('{} {}\n'.format(numb, foo))Traceback (most recent call last): File "<stdin>", line 1, in <module>ValueError: zero length field name in format>>> When looking through the documentation ( 2.6 , 2.7 ), I can see no mention of changes having been done between the two versions. What is happening here?
Now provide the response and nothing else.
|
Python 2.6 and before (as well as Python 3.0) require that you number the placeholders: '{0} {1}\n'.format(numb, foo) The numbering, if omitted in Python 2.7 and Python 3.1 and up, is implicit, see the documentation : Changed in version 2.7 : The positional argument specifiers can be omitted, so '{} {}' is equivalent to '{0} {1}' . The implicit numbering is popular; a lot of examples here on Stack Overflow use it as it is easier to whip up a quick format string that way. I have forgotten to include them more than once when working on projects that must support 2.6 still.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19668395', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2223161/']}
|
jdg_378455
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37188
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
(For information on cardinal characteristics of the continuum aka cardinal invariants see Joel David Hamkins' MO answer here ; Andreas Blass's handbook article is an excellent reference.) Problem 2.3 of Shelah's "On What I Do Not Understand (and Have Something to Say), Part I" (published in 2000 in Fundamenta Mathematicae) states, "Investigate cardinal invariants of the continuum showing $\geq 3$ may have prescribed order". One major barrier to such an investigation is the fact that countable support iteration of proper forcings yields models where the continuum is $\aleph_2$. In such models given any three cardinal characteristics at least two will have to be equal. My question is the following. To what extent has such an investigation been pursued? In either the literature or folklore are there any results proving the consistency of inequalities $\mathfrak{c}_0<\mathfrak{c}_1<\mathfrak{c}_2$ where the $\mathfrak{c}_i$ are cardinal characteristics?
Now provide the response and nothing else.
|
There is a paper of Shelah and Goldstern devoted to the separation of many simple cardinal invariants (this is a technical term): Many simple cardinal invariants ( Sh:448 ). There are more recent papers on this subject by Kellner and Shelah, if I remember correctly. An easy case that I am very familiar with are the so called localization numbers.A closed set $S\subseteq\omega^\omega$ is $n$ -ary if in the tree $T(S)$ of finite initial segments of elements of $S$ every node has at most $n$ immediate successors. For $n\geq 2$ let $\ell_n$ be the least size of a family of $(n-1)$ -ary sets that covers all of $n^\omega$ . Any finitely many $\ell_n$ can be separated from each other simultaneously. This is shown in [Geschke, Kojman, Convexity numbers of closed subsets in R^n ,Proc. Am. Math. Soc. 130, No. 10, 2871-2881 (2002)], which is here ( Wayback Machine ). Proofs of such statements usually involve forcing with large countable support products over a model of GCH rather than iterated forcing. However, there are also some examples that use iterated forcing. See for example the paper The covering numbers of Mycielski ideals are all equal , by Shelah and Steprans ( Sh:665 ).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/37188', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2436/']}
|
jdg_378456
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1941814
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Long ago writing VBA macros for MSFT Office was part of my job. Now it looks like I may be traveling down that road again, and I have not touched MSFT Office for anything serious in years. Is VBA still the de-facto standard for creating msft office extensions? Is it possible to write (non-second-class-citizen) MSFT office extensions in any language besides VBA yet?
Now provide the response and nothing else.
|
You're passing the collection_type argument in as a keyword argument, because you specifically say collection_type=collection_type in your call to the form constructor. So Python includes it within the kwargs dictionary - but because you have also declared it as a positional argument in that function's definition, it attempts to pass it twice, hence the error. However, what you're trying to do will never work. You can't have user=None, parent=None before the *args dictionary, as those are already kwargs, and args must always come before kwargs. The way to fix it is to drop the explicit definition of collection_type, user and parent, and extract them from kwargs within the function: def __init__(self, *args, **kwargs): collection_type = kwargs.pop('collection_type', None) user = kwargs.pop('user', None) parent = kwargs.pop('parent', None)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1941814', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/42223/']}
|
jdg_378457
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3766688
|
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 need to filter a Cursor/CursorAdapter to only show rows that match a specific condition in the ListView. I don't want to requery the db all the time. I just want to filter the Cursor I got from querying the DB. I have seen the question: Filter rows from Cursor so they don't show up in ListView But I don't understand how to do the filtering by overwritting the "move" methods in my CursorWrapper. An example would be nice. Thank you very much.
Now provide the response and nothing else.
|
UPDATE: I have rewritten the source and my employer has made it available as open source software: https://github.com/clover/android-filteredcursor You don't need to override all the move methods in CursorWrapper, you do need to override a bunch though due to the design of the Cursor interface. Let's pretend you want to filter out row #2 and #4 of a 7 row cursor, make a class that extends CursorWrapper and override these methods like so: private int[] filterMap = new int[] { 0, 1, 3, 5, 6 };private int mPos = -1;@Overridepublic int getCount() { return filterMap.length }@Overridepublic boolean moveToPosition(int position) { // Make sure position isn't past the end of the cursor final int count = getCount(); if (position >= count) { mPos = count; return false; } // Make sure position isn't before the beginning of the cursor if (position < 0) { mPos = -1; return false; } final int realPosition = filterMap[position]; // When moving to an empty position, just pretend we did it boolean moved = realPosition == -1 ? true : super.moveToPosition(realPosition); if (moved) { mPos = position; } else { mPos = -1; } return moved;}@Overridepublic final boolean move(int offset) { return moveToPosition(mPos + offset);}@Overridepublic final boolean moveToFirst() { return moveToPosition(0);}@Overridepublic final boolean moveToLast() { return moveToPosition(getCount() - 1);}@Overridepublic final boolean moveToNext() { return moveToPosition(mPos + 1);}@Overridepublic final boolean moveToPrevious() { return moveToPosition(mPos - 1);}@Overridepublic final boolean isFirst() { return mPos == 0 && getCount() != 0;}@Overridepublic final boolean isLast() { int cnt = getCount(); return mPos == (cnt - 1) && cnt != 0;}@Overridepublic final boolean isBeforeFirst() { if (getCount() == 0) { return true; } return mPos == -1;}@Overridepublic final boolean isAfterLast() { if (getCount() == 0) { return true; } return mPos == getCount();}@Overridepublic int getPosition() { return mPos;} Now the interesting part is creating the filterMap, that's up to you.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3766688', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/391216/']}
|
jdg_378458
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
49684217
|
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 write a component in React that will use the fetch() API to get data from a website, then use setState to set a state equal to the data, and then finally render the data. My code looks like this: import React from 'react';export default class Test extends React.Component { constructor(props){ super(props); this.state = {apiInfo: 'default'}; } componentDidMount(){ fetch('https://fcctop100.herokuapp.com/api/fccusers/top/recent').then( function(response){ return response.json(); } ).then(function(jsonData){ return JSON.stringify(jsonData); } ).then(function(jsonStr){ this.setState({apiInfo: jsonStr}); console.log(jsonStr); }); } render(){ return( <tr> <td>{this.state.apiInfo}</td> </tr> ); }} However, this results with an error saying I'm unable to setState of undefined. I end up rendering 'default' on my HTML. What exactly am I doing wrong here?
Now provide the response and nothing else.
|
Your error message is telling you exactly what the problem is: unable to setState of undefined So you're trying call setState as a method of an object that doesn't exist at that point. As a property of what object are you trying to call setState as a method? this.setState({apiInfo: jsonStr}); Yes, it's your this that's the problem. At the point that you're trying to call it - i.e. inside a .then() of a fetch call - this is actually undefined. You can see this in the Chrome Devtools: I'm afraid that this is a slippery customer in JavaScript; its value can (and does) change depending upon the current context of your app. There's several ways you can workaround this. One slightly clunky (but it works!) way is to capture your this value before you enter your .fetch() call, and assign it to another variable. You'll often see that or self variables used for this purpose, but they're just conventions. You can call the variable what you like. Here's how I've reworked your componentDidMount() method capturing this to that , and calling that inside the .then() : componentDidMount() { const that = this; fetch("https://fcctop100.herokuapp.com/api/fccusers/top/recent") .then(function(response) { return response.json(); }) .then(function(jsonData) { return JSON.stringify(jsonData); }) .then(function(jsonStr) { that.setState({ apiInfo: jsonStr }); console.log(jsonStr); });} If you're comfortable using arrow functions, then another way is to replace your "normal" function call with one, like so: .then(jsonStr => { this.setState({ apiInfo: jsonStr }); console.log(jsonStr);}); An arrow function's this is always the this that its parent defined.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49684217', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9362785/']}
|
jdg_378459
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9179708
|
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 need to quickly knock up the functionality of the twitter bootstraps main navigation and sub navigation e.g. http://twitter.github.com/bootstrap/scaffolding.html (when you scroll the subnav becomes fixed to that main navigation) Has anyone implemented this or are there any tutorials?
Now provide the response and nothing else.
|
Here is my code to implement this feature: $(document).scroll(function(){ // If has not activated (has no attribute "data-top" if (!$('.subnav').attr('data-top')) { // If already fixed, then do nothing if ($('.subnav').hasClass('subnav-fixed')) return; // Remember top position var offset = $('.subnav').offset() $('.subnav').attr('data-top', offset.top); } if ($('.subnav').attr('data-top') - $('.subnav').outerHeight() <= $(this).scrollTop()) $('.subnav').addClass('subnav-fixed'); else $('.subnav').removeClass('subnav-fixed');});
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9179708', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/844070/']}
|
jdg_378460
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3346106
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
SVG standard allows to use and refer external SVG files. I have a file circle.svg that defines a circle object with id "the_circle".From the main SVG file I am able to include this circle and animate it, using SVG linking . I would also like to access the same circle object via javascript, how can I do this ?What is the javascript equivalent of xlink:href="url(#the_image)#the_circle" ? Using document.getElementById('the_image') I can only access the SVGImageElement but not the objects defined inside the included SVG. <?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg width="100%" height="100%" version="1.1"xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" > <image id="the_image" x="0" y="0" width="100%" height="100%" xlink:href="circle.svg" /> <animateTransform xlink:href="url(#the_image)#the_circle" attributeName="transform" attributeType="XML" type="translate" from="0" to="25" dur="1s" repeatCount="indefinite" additive="replace" fill="freeze" /></svg>
Now provide the response and nothing else.
|
It seems like the "right" way to do this would actually be to use an SVG "use" element, rather than an image. The reason for this is that the DOM interface of the SVG use element specifies a property "instanceRoot", which allows you to get the root of the "instance tree" corresponding to that use element: http://www.w3.org/TR/SVG/struct.html#InterfaceSVGUseElement So, you would end up with a solution that looks something like the following:circle.svg: <?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg width="4in" height="4in" id="the_svg" viewBox="0 0 4 4" version="1.1" xmlns="http://www.w3.org/2000/svg"> <circle r="1" fill="blue" stroke="none" id="the_circle"/></svg> Document which uses the svg root node of circle.svg: <?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg width="100%" height="100%" id="foo" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <use xlink:href="circle.svg#the_svg"/></svg> Unfortunately, though, while Firefox supports use of the use element with external documents, there's currently a bug in Webkit which does not allow this: https://bugs.webkit.org/show_bug.cgi?id=12499 Also, Firefox does not seem to implement the instanceRoot property for use elements. So, it seems you may need to work around the limitations of current SVG implementations. The way I would recommend doing this is to use XMLHttpRequest to download the document to which you would like to link, and import the DOM of the downloaded document into your host document's DOM. The following code implements this, and works in Firefox, Opera and Chromium: <?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg width="100%" height="100%" id="foo" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <script> function fetchXML (url, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.onreadystatechange = function (evt) { //Do not explicitly handle errors, those should be //visible via console output in the browser. if (xhr.readyState === 4) { callback(xhr.responseXML); } }; xhr.send(null); }; //fetch the document fetchXML("http://localhost:8082/tmp/circle.svg",function(newSVGDoc){ //import it into the current DOM var n = document.importNode(newSVGDoc.documentElement,true); document.documentElement.appendChild(n); var circle = document.getElementById("the_circle"); //now you have the circle }) </script></svg>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3346106', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/191068/']}
|
jdg_378461
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
65088
|
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:
A bipartite graph is planar iff it has no $K_{3, 3}$ or $K_5$ minors. I am looking for a necessary or/and sufficient conditions to allow planar drawings with no edges "going around" sets of vertices. These are drawings satisfying: All vertices of one part are drawn on a single vertical line. Vertices of the other part are drawn on a parallel verticle line. Edges do not intersect except at vertices. Edges are all in the infinite strip between the two vertical lines in point 1. For example, all drawings here except the bottom right are non-examples. The bottom-left graph can be re-drawn to satisfy the conditions by swapping the positions of Q and R. The tops two graphs cannot be redrawn to satisfy the conditions. The top two graphs are the only obstructions I could find. My questions are: Does this problem have a name? Any other obstructions that I missed? Any hints on how I can prove that these two obstructions (along with anything I missed), as minors of course, are necessary and sufficient. Note that this is not the same as being outer-planar, $K_{2, 2}$ is outer-planar (can be drawn as a square) but it cannot be drawn to satisfy the conditions I mention above.
Now provide the response and nothing else.
|
Your graphs are exactly the graphs of path-width $1$ or, equivalently, the forests each of whose components is a caterpillar . Caterpillars have two relevant characterizations: they're the trees in which there is a single path containing every vertex of degree more than $1$; they're the trees in which every vertex has at most two non-leaf neighbours. Lemma 1. Every caterpillar is in your class. Proof. Let $G$ be a caterpillar and let $P=x_1\dots x_\ell$ be a longest path containing every vertex of degree $2$ or more. Note that, by maximality, $d(x_1)=d(x_\ell)=1$. We can produce a drawing of $G$ by first drawing $P$ as a zig-zag and then adding the degree-$1$ vertices adjacent to $x_i$ between $x_{i-1}$ and $x_{i+1}$. $\Box$ Lemma 2. Every graph $G$ in your class is acyclic. Proof. Suppose $G$ contains the cycle $x_1y_1x_2y_2\dots x_ky_kx_1$ and suppose it has a drawing of the required form. W.l.o.g., $x_2$ is above $x_1$. But then we must have $y_2$ above $y_1$ since, otherwise, the lines $x_1y_1$ and $x_2y_2$ would cross. By induction, $x_{i+1}$ is above $x_i$ for all $i\in\{1, \dots, k-1\}$ and likewise for the $y$'s. But then any line $y_kx_1$ must either leave the region between the two columns of vertices or cross every other edge in the cycle. This contradicts our assumption that the graph has a proper drawing. $\Box$ Lemma 3. Every connected non-caterpillar is not in your class. Proof. Let $G$ be a connected graph that is not a caterpillar. If it contains a cycle, it is not in your class by Lemma $2$, so we may assume it is a tree. If it is not a caterpillar, it must contain a vertex $x$ with distinct neighbours $y_1$, $y_2$ and $y_3$, each of which has degree at least $2$. Suppose we have a drawing of $G$ with the required properties. W.l.o.g., $y_2$ is above $y_1$ and $y_3$ is above $y_2$. Let $z\neq x$ be a neighbour of $y_2$. The edge $y_2z$ must cross $xy_1$ or $xy_3$, contradicting our assumption that the graph has a drawing of the required form. $\Box$ Theorem. Your class of graphs is exactly the class of forests each of whose components is a caterpillar. Proof. Let $G$ be a graph. Clearly, $G$ is in your class if, and only if, every component is: if any component cannot be drawn as required, the whole graph cannot; if every component can be drawn as required, then the whole graph can be drawn by arranging the components one above the other. The result now follows by Lemmas $1$ and $3$. $\Box$ Corollary. Your class of graphs is the class of graphs that do not have $K_3$ or the subdivision of $K_{1,3}$ as a minor. Proof. These are the obstructions for path-width $1$ . $\Box$ These are essentially the obstructions you found: you need $K_3$ rather than $K_4$ because the latter would admit $K_3$ into the class; the subdivision of $K_{1,3}$ is exactly your second obstruction.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://cs.stackexchange.com/questions/65088', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/208/']}
|
jdg_378462
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1940784
|
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:
Express $\sqrt[3]{(7+5\sqrt{2})}$ in the form $x+y\sqrt{2}$ with $x$ and $y$ rational numbers. I.e. Show that it is $1+\sqrt{2}$.
Now provide the response and nothing else.
|
You can assume that the nested radical can be expressed in $a+b\sqrt{2}$ form. More specifically, we have $$\sqrt[m]{A+B\sqrt[n]{C}}=a+b\sqrt[n]{C}\tag{1}$$With your question, we have $$\sqrt[3]{7+5\sqrt{2}}=a+b\sqrt{2}\tag{2}$$ Cubing both sides, we get $$7+5\sqrt{2}=(a^3+6ab^2)+(3a^2b+2b^3)\sqrt{2}\tag{3}$$And equating corresponding coefficients, we get the following system of equations: $$\begin{cases}a^3+6ab^2=7\\3a^2b+2b^3=5\tag{4}\end{cases}$$Cross multiplying, we get a multi-variate polynomial. Namely, $$5a^3-21a^2b+30ab^2-14b^3=0\tag{5}$$Dividing both sides by $b^3$, we get: $$5\frac {a^3}{b^3}-21\frac {a^2}{b^2}+30\frac {a}{b}-14=0\tag{6}$$Which is also equal to $5\left(\frac ab\right)^3-21\left(\frac {a}{b}\right)^2+30\left(\frac {a}{b}\right)-14=0$. Substituting $a/b$ with $x$, we get the cubic polynomial$$5x^3-21x^2+30x-14=0\tag{7}$$ with $x=1$ as an integer root.Since $a/b=x$, we have $$\frac ab=1\implies a=b\tag{8}$$So from $(3)$, we have $a^3+6a(a)^2=7\implies a^3+6a^3=7\implies 7a^3=7\implies a=b=1$ $$\sqrt[3]{7+5\sqrt{2}}=1+\sqrt{2}$$ For practice, you can try to denest $\sqrt[3]{2+\sqrt{5}}$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1940784', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/266695/']}
|
jdg_378463
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38015452
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The following code is in head section of a page: <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script><![endif]--> Shouldn't the comment tags stop this script from being run?
Now provide the response and nothing else.
|
According to Jake Wharton, author of Butterknife, unbind() is only required for Fragments . See this comment on the issue tracker: https://github.com/JakeWharton/butterknife/issues/879 Q: In the RecyclerView , how do we unbind the ViewHolder ? A: You don't need to. Only Fragments need to in onDestroyView() . The reason being that [ ViewHolders ] don't outlive the associated view. A Fragment does. In other words, because a Fragment may continue to exist after its Views are destroyed, you need to call .unbind() from a Fragment to release the reference to the Views (and allow the associated memory to be reclaimed). With a ViewHolder , the lifecycle of the holder is the same as the Views it holds. In other words, the ViewHolder and its Views are destroyed at the same time, so there's never a lingering reference from one to the other that you need to manually clear.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38015452', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5006860/']}
|
jdg_378464
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
400533
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I am running an python script on an ec2 instance that inserts rows in an database on another instance. In ec2's monitoring I saw a 100% cpu utilization, whereas top only shows 20% for the python process. What is missing from top? Network overhead?
Now provide the response and nothing else.
|
The data exposed by top is often insufficient or misleading in virtualized environments like Amazon EC2 and the reported percentage depends on your instance type and the underlying processor core utilization (which usually doesn't match the virtualized hardware you are presented with from the hypervisor), amongst other things - what you are seeing is most likely caused by respective CPU steal time as exposed in most related Unix/Linux monitoring tools nowadays - see e.g. columns %steal or st in sar or top : st -- Steal Time The amount of CPU 'stolen' from this virtual machineby the hypervisor for other tasks (such as running another virtualmachine). The blog post EC2 monitoring: the case of stolen CPU provides a nice exploration and illustration of this topic: When the top command displays 40% CPU busy but CloudWatch says theserver is maxed out at 100% — which side do you take? The answer issimple (CloudWatch is correct, top is not) [...] Please note that this hypervisor metric seems to be (easily) accessible on Unix/Linux systems only, but doesn't seem to be observable on Windows (yet), see my question Is there a Windows equivalent of Unix 'CPU steal time'? for more regarding this problem.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/400533', 'https://serverfault.com', 'https://serverfault.com/users/121090/']}
|
jdg_378465
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21163976
|
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 plain text file with content like this: prežrať/RNprežrieť/Zprežrúc/zZprežuť/c... Q: How can I remove all strings after / symbol in every row in Notepad++? Desired output: prežraťprežrieťprežrúcprežuť... I am doing this with Find-and-Replace for every different string after / , but there are too many combinations.
Now provide the response and nothing else.
|
Search for: /.* , replace with nothing. The character / matches just / . . , however, matches any character except newlines, so .* will match a sequence of characters up until the first newline. You can find a demonstration here: http://regex101.com/r/kT0uE3 . If you want to remove characters only after the last on the line / , you should use the regex /[^/]*$ . You can find an explanation and demonstration here: https://regex101.com/r/sZ6kP7/74 .
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21163976', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1183662/']}
|
jdg_378466
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
96371
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Often introductory applied statistics texts distinguish the mean from the median (often in the the context of descriptive statistics and motivating the summarization of central tendency using the mean, median and mode) by explaining that the mean is sensitive to outliers in sample data and/or to skewed population distributions, and this is used as a justification for an assertion that the median is to be preferred when the data are not symmetrical. For example: The best measure of central tendency for a given set of data often depends on the way in which the values are distributed.... When data are not symmetric, the median is often the best measure of central tendency. Because the mean is sensitive to extreme observations, it is pulled in the direction of the outlying data values, and as a result might end up excessively inflated or excessively deflated." —Pagano and Gauvreau, (2000) Principles of Biostatistics , 2nd ed. (P&G were at hand, BTW, not singling them out per se .) The authors define "central tendency" thus: "The most commonly investigated characteristic of a set of data is its center, or the point about which observations tend to cluster." This strikes me as a less-than forthright way of saying only use the median, period , because only using the mean when the data/distributions are symmetrical is the same thing as saying only use the mean when it equals the median. Edit: whuber rightly points out that I am conflating robust measures of central tendency with the median. So it is important to keep in mind that I am discussing the specific framing of the arithmetic mean versus the median in introductory applied statistics (where, mode aside, other measures of central tendency are not motivated). Rather than judging the utility of the mean by how much it departs from the behavior of the median, ought we not simply understand these as two different measures of centrality? In other words being sensitive to skewness is a feature of the mean. One could just as validly argue "well the median is no good because it is largely insensitive to skewness, so only use it when it equals the mean." (The mode is quite sensibly not getting involved with this question.)
Now provide the response and nothing else.
|
I disagree with the advice as a flat out rule. (It's not common to all books.) The issues are more subtle. If you're actually interested in making inference about the population mean, the sample mean is at least an unbiased estimator of it, and has a number of other advantages. In fact, see the Gauss-Markov theorem - it's best linear unbiased. If your variables are heavily skew, the problem comes with 'linear' - in some situations, all linear estimators may be bad, so the best of them may still be unattractive, so an estimator of the mean which is not-linear may be better, but it would require knowing something (or even quite a lot) about the distribution. We don't always have that luxury. If you're not necessarily interested in inference relating to a population mean (" what's a typical age? ", say or whether there's a more general location shift from one population to another, which might be phrased in terms of any location, or even of a test of one variable being stochastically larger than another), then casting that in terms of the population mean is either not necessary or likely counterproductive (in the last case). So I think it comes down to thinking about: what are your actual questions? Is population mean even a good thing to be asking about in this situation? what is the best way to answer the question given the situation (skewness in this case)? Is using sample means the best approach to answering our questions of interest? It may be that you have questions not directly about population means, but nevertheless sample means are a good way to look at those questions (estimating the population median of a waiting time that you assume to be distributed as ab exponential random variable, for example is better estimated as a particular fraction of the sample mean) ... or vice versa - the question might be about population means but sample means might not be the best way to answer that question.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/96371', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/44269/']}
|
jdg_378467
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
136407
|
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 was reading Energy-momentum, and I came across this simplified equation:$$E^2 = (mc^2)^2 + (pc)^2$$ where $m$ is the mass and $p$ is momentum of the object. That said, the equation is pretty fundamental and nothing is wrong when looked upon, I similarly also believed this but I came across a "special" cases where this does not apply: If the body's speed $v$ is much less than $c$, then the equation reduces to $E = (mv^2/2) + mc^2$. I find this really crazy, because first Einstein, always wanted to create a theory\equation that applied to every aspect of physics and has no "fudge" factors, that said irony is present from Einstein. Next, why does this not work in every aspect? surely a equation should be "universal" and should still work with any values given. Most importantly, why does this not work, if velocity is "much" slower than light? What do they mean by "much slower", what is the boundary for "much slower"? Regards,
Now provide the response and nothing else.
|
First, the non-relativistic equation$$ E= mc^2 + \frac{mv^2}{2} $$is equivalent to its second power,$$ E^2 = (mc^2)^2 + m^2 c^2 v^2+ \frac{m^2v^4}{4} $$If $v/c\ll 1$, then the last term is much smaller than the previous two, and the first two terms on the right hand side are equivalent to the correct relativistic$$ E^2 = (mc^2)^2+ (pc)^2 $$which completes the proof that the two formulae are the same in the $v/c\ll 1$ limit. The last, relativistic formula is always right. The first one, if we want to consider "only absolutely correct and exact" formulae, is never correct – except for the case $v=0$. However, the non-relativistic equation may be written in a completely rigorous way (to describe that it is approximate) as$$ E = mc^2 + \frac{mv^2}{2} + O(mv^4/c^2) $$The symbol $O$ represents "a function that in the relevant limit, here $v/c\to 0$, has a finite limiting ratio with the function in the parentheses after $O$", and this concept may be and is defined 100% rigorously. The boundary of the values of $v$ where the non-relativistic formula applies is indeed "fuzzy" – one can't quote any exact value of $v$ (except for $v=0$, in the useless sense described above) where the non-relativistic formula ceases to hold. But for $v/c\lt 0.1$ or so, the error is smaller than one percent. For greater speed than $v=c/2$, the non-relativistic formula becomes so bad that it can't be use in any quantitative context. The error of the non-relativistic energy formula – or, more democratically, the difference between the two formulae – simply gradually increases from $0$ at $v=0$ to something comparable to 100% at $v=c/2$ and a huge error for $v\to c$. Physics is fundamentally based on continuous numbers which means that pretty much all of its quantities are gradually changing and their differences and errors are gradually changing, too. Also, errors smaller than a certain threshold are experimentally undetectable which allows one to say, in a very specific empirically rooted sense, that the error is basically zero. Because of the omnipresence of limits and limiting claims about formulae, expressions, and theories in physics, one may say that if you won't comprehend and embrace these important concepts about limits and expressions' being equivalent in limits, you have virtually no chance to understand anything in physics.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/136407', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/-1/']}
|
jdg_378468
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1195216
|
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:
There is an urn that contains $N$ balls. Each ball might be either white or blue. I dont know how many white balls are in the urn, but my prior is that a ball is blue with probability $b$. Someone iterates through the blue balls and, for each ball independently, they either show it to me, with probability $p$, or they don't. What is the probability that I am shown $v$ balls? Solution 1:$Pr=\sum\limits_{i=0}^{N}{N\choose i}b^{i}(1-b)^{N-i}{i\choose v}p^{v}(1-p)^{i-v}.$ Solution 2:$Pr={N \choose v}(bp)^v(1-bp)^{N-v}.$ I wish the second one is correct, but it must be wrong. Why?
Now provide the response and nothing else.
|
The formulas are equivalent: $$\sum\limits _{i=v}^{N}{N \choose i}b^{i}(1-b)^{N-i}{i \choose v}p^{v}(1-p)^{i-v}=\binom{N}{v}\left(bp\right)^{v}\sum\limits _{i=0}^{N-v}\binom{N-v}{i}(b-bp)^{i}(1-b)^{N-v-i}=\binom{N}{v}\left(bp\right)^{v}\left(1-bp\right)^{N-v}$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1195216', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/224555/']}
|
jdg_378469
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
647414
|
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:
Can someone explain how angular momentum is conserved while at the same time precession in freely rotating objects happens? It seems contradictory.
Now provide the response and nothing else.
|
Angular momentum is a much more complicated beast than linear momentum. $\renewcommand{\tensor}[1]{\overleftrightarrow{#1}}%% ugh, the \over arrows have different spacing than \vec\renewcommand{\vec}[1]{\overrightarrow{#1}} $ With linear momentum for a solid object, the relationship between momentum and velocity is always the same: $\vec{p}=m\vec{v}$ . The momentum is always in the same direction as the velocity and the are related by a fixed ratio (ignoring complicated cases where the mass changes). That means if an object has the same momentum at two points in time the velocity must not change as well: $m\vec{v}= m\vec{v}' \Rightarrow \vec{v}=\vec{v}'$ But for angular momentum the relationship is $\vec{L} = \tensor{I}\vec{\omega}$ . The first difference is that the angular momentum vector and the angular velocity vector don't necessarily point in the same direction. The second and most important difference is that the moment of inertia tensor $\tensor{I}$ can change, even for a perfectly rigid object! For anything shape more complicated than a sphere* if the object changes its orientation then its moment of inertia also changes. That means that the object can change its angular velocity without changing its angular momentum if its moment of inertia also changes: you go from $\vec{L} = \tensor{I}\vec{\omega}$ to $\vec{L} = \tensor{I}'\vec{\omega}'$ , and $\vec{\omega}'$ doesn't have to be the same as $\vec{\omega}$ because $\tensor{I}'\ne \tensor{I}$ . Ultimately, rotating objects, even ones with no external torque, have much more freedom of movement than non-rotating objects. You get used to the idea of unforced movement being very simple when you study linear motion, but it's just not the case when you study rotational motion.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/647414', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/147291/']}
|
jdg_378470
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19635269
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Some jQuery animation methods take an argument described as complete , which is a function that is to be called once the animation is done. For example: $(obj).slideUp(duration, easing, complete()); How is this different from calling complete after the animation as below? $(obj).slideUp(duration, easing).complete();
Now provide the response and nothing else.
|
I tend to write and see written the Functor instance first. Doubly so because if you use the LANGUAGE DeriveFunctor pragma then data Foo a = Foo a deriving ( Functor ) works most of the time. The tricky bits are around agreement of instances when your Applicative can be more general than your Monad . For instance, here's an Err data type data Err e a = Err [e] | Ok a deriving ( Functor )instance Applicative (Err e) where pure = Ok Err es <*> Err es' = Err (es ++ es') Err es <*> _ = Err es _ <*> Err es = Err es Ok f <*> Ok x = Ok (f x)instance Monad (Err e) where return = pure Err es >>= _ = Err es Ok a >>= f = f a Above I defined the instances in Functor -to- Monad order and, taken in isolation, each instance is correct. Unfortunately, the Applicative and Monad instances do not align: ap and (<*>) are observably different as are (>>) and (*>) . Err "hi" <*> Err "bye" == Err "hibye"Err "hi" `ap` Err "bye" == Err "hi" For sensibility purposes, especially once the Applicative/Monad Proposal is in everyone's hands, these should align. If you defined instance Applicative (Err e) where { pure = return; (<*>) = ap } then they will align. But then, finally, you may be capable of carefully teasing apart the differences in Applicative and Monad so that they behave differently in benign ways---such as having a lazier or more efficient Applicative instance. This actually occurs fairly frequently and I feel the jury is still a little bit out on what "benign" means and under what kinds of "observation" should your instances align. Perhaps some of the most gregarious use of this is in the Haxl project at Facebook where the Applicative instance is more parallelized than the Monad instance, and thus is far more efficient at the cost of some fairly severe "unobserved" side effects. In any case, if they differ, document it.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19635269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/314166/']}
|
jdg_378471
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
56621
|
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to build an in-house Raspberry Pi image based on Raspbian Lite which is already configured with the correct locale, timezone, etc. Unfortunately for me, current releases of Raspbian images automatically resize the file system, then reboot. I want to avoid the hassles of downsizing the filesystem by preventing the resize from ever occurring. How would I edit the image after burning such as to temporarily disable the automatic file system resize? Edited to clarify effects should be reversible; that is, I'll want my customized image to expand at first boot.
Now provide the response and nothing else.
|
[Beware this may not reflect the current mechanism as it is some years old.] There is a two part mechanism which takes responsibility for this on Raspbian; likely the best idea is to take care of both parts if they are enabled. The first is that the original /boot/cmdline.txt includes this: init=/usr/lib/raspi-config/init_resize.sh Referring to a script with that path on the root partition, which will be used as the init process at boot. Without that bit, it would default to a value built into the kernel, /sbin/init , which on Raspbian is a symbolic link to /lib/systemd/systemd . By removing that portion of cmdline.txt , the system should then boot normally. What that script actually does is resize the partition on the SD card. This is a distinct process from resizing the filesystem in the partition, 1 which is what happens next. The way that happens is the system is immediately rebooted normally (that is, via systemd) and an init.d script is set to trigger early on, which should be removed from the second partition: /etc/init.d/resizefs_once And the symbolic link to it, which should also be removed: /etc/rc3.d/S01resizefs_once You can keep a copy for later use if you want, but raspi-config can create it again for you (it's embedded in the raspi-config shell script). If it actually runs, it deletes itself, so it will not happen again. What it also does is resize the filesystem in the newly resized partition. No harm should be done if just one or the other part happens; in the first case you end up with a filesystem that doesn't fill the enlarged partition, in the second nothing will happen, because the filesystem already fills the partition. If you later use raspi-config to enlarge the filesystem, it does the partition resize right away, then sets up the init script (as already mentioned). Editing cmdline.txt on the first partition is simple on any computer since it is a VFAT partition. Removing the init.d file requires a system that can access and edit ext4 filesystems. Both tasks can instead be done to the image file itself prior to burning the card; to mount and modify a Raspbian image on a GNU/Linux system, see here . There is a parallel Q&A for Windows . This is also reversible, but you'll need to put back both parts of the mechanism as just described, since the first one does not include automatically staging the second one. Although an error message from that script arguably confuses those terms by claiming it failed to resize the root filesystem , when what it really failed to do is resize the partition on which the root filesystem resides. Doing one does not automatically accomplish the other.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://raspberrypi.stackexchange.com/questions/56621', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/54372/']}
|
jdg_378472
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32464974
|
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 making JavaFX desktop application with core components described in FXML and I would like to offer user the option to change the language. However I have not find any direct way how to change the language once the component has been loaded from the FXML. The question is is there any standard way how to deal with switching the language in JavaFX.
Now provide the response and nothing else.
|
You can do something like this. As in your answer, you would either want to implement this as a singleton, or use a DI framework to inject a single instance wherever you need it: public class ObservableResourceFactory { private ObjectProperty<ResourceBundle> resources = new SimpleObjectProperty<>(); public ObjectProperty<ResourceBundle> resourcesProperty() { return resources ; } public final ResourceBundle getResources() { return resourcesProperty().get(); } public final void setResources(ResourceBundle resources) { resourcesProperty().set(resources); } public StringBinding getStringBinding(String key) { return new StringBinding() { { bind(resourcesProperty()); } @Override public String computeValue() { return getResources().getString(key); } }; }} Now you can do things like: ObservableResourceFactory resourceFactory = .... ;resourceBundle.setResources(...);Label greetingLabel = new Label();greetingLabel.textProperty().bind(resourceFactory.getStringBinding("greeting")); And any time you update the resource with resourceFactory.setResources(...); will cause the label to update its text. Here's an SSCCE (with apologies for the extremely ugly way of forcing a ResourceBundle into a single runnable class...) import java.util.ListResourceBundle;import java.util.Locale;import java.util.ResourceBundle;import javafx.application.Application;import javafx.beans.binding.StringBinding;import javafx.beans.property.ObjectProperty;import javafx.beans.property.SimpleObjectProperty;import javafx.geometry.Insets;import javafx.scene.Scene;import javafx.scene.control.ComboBox;import javafx.scene.control.Label;import javafx.scene.control.ListCell;import javafx.scene.layout.BorderPane;import javafx.stage.Stage;public class ResourceBundleBindingExample extends Application { private static final String RESOURCE_NAME = Resources.class.getTypeName() ; private static final ObservableResourceFactory RESOURCE_FACTORY = new ObservableResourceFactory(); static { RESOURCE_FACTORY.setResources(ResourceBundle.getBundle(RESOURCE_NAME)); } @Override public void start(Stage primaryStage) { ComboBox<Locale> languageSelect = new ComboBox<>(); languageSelect.getItems().addAll(Locale.ENGLISH, Locale.FRENCH); languageSelect.setValue(Locale.ENGLISH); languageSelect.setCellFactory(lv -> new LocaleCell()); languageSelect.setButtonCell(new LocaleCell()); languageSelect.valueProperty().addListener((obs, oldValue, newValue) -> { if (newValue != null) { RESOURCE_FACTORY.setResources(ResourceBundle.getBundle(RESOURCE_NAME, newValue)); } }); Label label = new Label(); label.textProperty().bind(RESOURCE_FACTORY.getStringBinding("greeting")); BorderPane root = new BorderPane(null, languageSelect, null, label, null); root.setPadding(new Insets(10)); Scene scene = new Scene(root, 400, 400); primaryStage.setScene(scene); primaryStage.show(); } public static class LocaleCell extends ListCell<Locale> { @Override public void updateItem(Locale locale, boolean empty) { super.updateItem(locale, empty); if (empty) { setText(null); } else { setText(locale.getDisplayLanguage(locale)); } } } public static class ObservableResourceFactory { private ObjectProperty<ResourceBundle> resources = new SimpleObjectProperty<>(); public ObjectProperty<ResourceBundle> resourcesProperty() { return resources ; } public final ResourceBundle getResources() { return resourcesProperty().get(); } public final void setResources(ResourceBundle resources) { resourcesProperty().set(resources); } public StringBinding getStringBinding(String key) { return new StringBinding() { { bind(resourcesProperty()); } @Override public String computeValue() { return getResources().getString(key); } }; } } public static class Resources extends ListResourceBundle { @Override protected Object[][] getContents() { return new Object[][] { {"greeting", "Hello"} }; } } public static class Resources_fr extends ListResourceBundle { @Override protected Object[][] getContents() { return new Object[][] { {"greeting", "Bonjour"} }; } } public static void main(String[] args) { launch(args); }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32464974', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4335148/']}
|
jdg_378473
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8960037
|
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 encountering the following error when I delete the last record from a UITableView . Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (3) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (1 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).' My goal is to show "No Record found" if the table array is empty. This is the code I'm using. When I delete the last record from table array the app crashes. How is it possible to reload the table and show "No Record Found" label? // Customize the number of rows in the table view.- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if ([idArray count]==0) { return 3; } else { return [idArray count]; } }// Customize the appearance of table view cells.- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"array count %d",[idArray count]); if ([idArray count] == 0) { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } cell.textLabel.textAlignment = UITextAlignmentCenter; tableView.userInteractionEnabled = NO; self.navigationItem.leftBarButtonItem.enabled = NO; NSUInteger row = [indexPath row]; switch (row) { case 0: cell.textLabel.text = @""; break; case 1: cell.textLabel.text = @""; break; case 2: cell.textLabel.text = @"No Records Found"; break; default: break; } return cell; } else { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; } tableView.userInteractionEnabled = YES; self.navigationItem.leftBarButtonItem.enabled = YES; // Set up the cell identify *idItems = [idArray objectAtIndex:indexPath.row]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"dd MMM,yyyy"]; NSString *dateStr = [formatter stringFromDate:idItems.Date]; UIImageView *accDis = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Arrow.png"]]; cell.accessoryView = accDis; self.idTableView.separatorColor = [UIColor colorWithRed:150.0/255.0 green:150.0/255.0 blue:150.0/255.0 alpha:1]; cell.textLabel.textColor = [UIColor blackColor]; cell.textLabel.font = [UIFont boldSystemFontOfSize:18]; cell.textLabel.adjustsFontSizeToFitWidth = YES; cell.detailTextLabel.textColor = [UIColor colorWithRed:100.0/255.0 green:100.0/255.0 blue:100.0/255.0 alpha:1]; cell.detailTextLabel.font = [UIFont italicSystemFontOfSize:16]; cell.detailTextLabel.adjustsFontSizeToFitWidth = YES; NSString *detailText = [NSString stringWithFormat:@"%@ - %@",dateStr,idItems.GeoCode]; if (idItems.Image == NULL) { cell.imageView.image = [UIImage imageNamed:@"icon58x58.png"]; } else { //pass image to fix size 50 X 50 //UIImage *newImage = [self postProcessImage:idItems.Image]; cell.imageView.image = idItems.thumb;//newImage; cell.imageView.contentMode=UIViewContentModeScaleAspectFill; } cell.textLabel.text = idItems.TypeName; cell.detailTextLabel.text = detailText; return cell; } }- (void)tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if(editingStyle == UITableViewCellEditingStyleDelete) { if ([idArray count] >=1) { [idTableView beginUpdates]; //Get the object to delete from the array. identifyObject = [appDelegate.idArray objectAtIndex:indexPath.row]; //Delete the object from the table. [self.idTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; [appDelegate removeID:identifyObject]; if ([idArray count] == 0) { [self.idTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; } [idTableView endUpdates]; } }}
Now provide the response and nothing else.
|
The problem is that a tableview expects the operations performed on the view to match the data source. You have one record in the table, and you remove it. The tableview is expecting the datasource to now contain zero records, but because of your "no records found" logic, it actually returns a value of 3, hence the consistency error, and your crash. The bug seems to be this part: if ([idArray count] == 0) { [self.idTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];} I assume this was intended to insert the "no records found" row into the table when the last line is deleted, but since your "no records found" actually spans three rows, you need to insert three rows here instead, like this: if ([idArray count] == 0) { [self.idTableView insertRowsAtIndexPaths:[NSArray arrayWithObjects: [NSIndexPath indexPathForRow:0 inSection:indexPath.section], [NSIndexPath indexPathForRow:1 inSection:indexPath.section], [NSIndexPath indexPathForRow:2 inSection:indexPath.section], nil] withRowAnimation:UITableViewRowAnimationFade];} For you own sanity however, can I suggest a different approach? Rather than trying to keep your table and datasource in sync whilst juggling these fake three rows of data that are only there for display purposes, why not just insert a UILabel into your view hierarchy (either in front of or behind the tableview) that says "no records found" and show/hide it based on whether the table has any data? That way you can precisely control its position and appearance without having to screw around with your datasource logic.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8960037', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/537422/']}
|
jdg_378474
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5917956
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Every FOSS project I know has rules against trailing whitespace in code. But I think it's very natural to continue the current indentation on the next line: int main(){....int a = 42;........return a;} But git for instance throws warnings anyway. So my question is: Why are those tabs inside the current indentation bad? I'm not looking for answers like "It's always done this way". Let's assume indentation is done consistently in the whole project in question.
Now provide the response and nothing else.
|
It is probably because merging patches with useless whitespace is harder than it should be. diff(1) and patch(1) treat spaces and tabs as important content. (Ask any Makefile or .py source file -- they are important!) And if your "blank line" has four spaces on it, and my "blank line" has eight spaces on it, any attempt to share patches between us will fail for very trivial reasons. Granted, if you wholesale change the indentation of a block of code, you'll have to go to some work to make patches apply anyway . But trying to track down merge failures on lines that look blank is painful . (I've wasted too much of my life doing just that. Yes, vim listchars can help, but reading code with listchars on all the time is also annoying.) So people standardize on no trailing whitespace . It might not really make sense to worry about a dozen lost bytes here or there from a storage standpoint, but it really makes merging patches easier. We could probably just as well standardize on adding trailing whitespace, exactly as you have suggested, and be just as happy, but we might as well standardize on the approach that is as parsimonious as possible.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5917956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/742572/']}
|
jdg_378475
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
47136436
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hi I want to get the counts of unique values of the dataframe. count_values implements this however I want to use its output somewhere else. How can I convert .count_values output to a pandas dataframe. here is an example code: import pandas as pddf = pd.DataFrame({'a':[1, 1, 2, 2, 2]})value_counts = df['a'].value_counts(dropna=True, sort=True)print(value_counts)print(type(value_counts)) output is: 2 31 2Name: a, dtype: int64<class 'pandas.core.series.Series'> What I need is a dataframe like this: unique_values counts2 31 2 Thank you.
Now provide the response and nothing else.
|
Use rename_axis for name of column from index and reset_index : df = df.value_counts().rename_axis('unique_values').reset_index(name='counts')print (df) unique_values counts0 2 31 1 2 Or if need one column DataFrame use Series.to_frame : df = df.value_counts().rename_axis('unique_values').to_frame('counts')print (df) countsunique_values 2 31 2
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/47136436', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3879858/']}
|
jdg_378476
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
44226554
|
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 cannot get basice LogTrace(...) output in my application. Here's a repro: Create a new ASP.NET Core application using Visual Studio 2017. (Optional) comment out .UseApplicationInsights() so the repro is clearer Replace the code in ValuesController.cs with this: using System.Collections.Generic;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Logging;namespace WebApplication1.Controllers{ [Route("api/[controller]")] public class ValuesController : Controller { private readonly ILogger<ValuesController> logger; public ValuesController(ILogger<ValuesController> logger) { this.logger = logger; } [HttpGet] public IEnumerable<string> Get() { logger.LogError("ERROR!"); logger.LogWarning("WARN!"); logger.LogInformation("INFO!"); logger.LogTrace("TRACE!"); return new string[] { "value1", "value2" }; } }} Change appsettings.Development.json to this: { "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Trace", "System": "Information", "Microsoft": "Information" } }} Run and view the Debug output This leads to: Actual output: Expected output would be the "TRACE!" message as well I've tried tweaking the values in the appsettings.json file as well, but that had no effect either. Weirdly, changing the value in either file to "Error" doesn't do anything either. Bottom Line / Question What do I need to do to make my injected ILogger<ValuesController> respect the logging settings, including Trace level? Footnote Here's some of the relevant code that would be auto-generated with the above repro: Startup.cs public class Startup{ public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseMvc(); }} Program.cs public class Program{ public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .UseApplicationInsights() .Build(); host.Run(); }} appsettings.json default: { "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }}
Now provide the response and nothing else.
|
BREAKING CHANGES AS OF 2.0 As Tseng commented below, this answer will become obsolete as of 2.0 you can find more on this annoucement here: https://github.com/aspnet/Announcements/issues/238 Where the problem lies... Based on your Configure() method, I have spotted an issue: public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory){ loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); // ⇦ you're not passing the LogLevel! app.UseMvc();} This is the reason why none of your changes to the configuration set in the appsettings.json files is not working. The default behaviour of .AddDebug() without any arguments passed is Adds a debug logger that is enabled for LogLevel.Information or higher. If you want to explicitly set it to use a particular minimum LogLevel, then you can pass it directly to the AddDebug(ILoggerFactory, LogLevel) method. loggerFactory.AddDebug(LogLevel.Trace); More information can be found here . Binding it to your configuration. Method 1: Grab the value from the configuration. LogLevel foo = this.Configuration.GetSection("Logging:LogLevel") .GetValue<LogLevel>("Default");loggerFactory.AddDebug(foo); Method 2: Use the built-in object for LogLevel (Intentionally left out. Obviously it sits snug between these two methods offered.) I would favor one of the extremes than to go halfway) Method 3: Go Manual (use ConfigurationBinder) The fancy ConfigurationBinder var obj = new MyObject();ConfigurationBinder.Bind(_configuration.GetSection("Logging:LogLevel"), obj); which will map to an object like public class MyObject{ public LogLevel Default { get; set; } public LogLevel System { get; set; } public LogLevel Microsoft { get; set; }} so you could then pass: loggerFactory.AddDebug(obj.Default); Special note about nodes and appsettings.json Note that the delimiter for the configuration uses : . Example: "Logging:LogLevel" will go: "Logging": { "IncludeScopes": false, "LogLevel": { ⇦⇦⇦⇦⇦ Here "Default": "Debug", "System": "Information", "Microsoft": "Information" }} LogLevel Enum Just for reference, here are the valid LogLevel values: public enum LogLevel{ Trace = 0, Debug = 1, Information = 2, Warning = 3, Error = 4, Critical = 5, None = 6,} Source: https://learn.microsoft.com/en-us/aspnet/core/api/microsoft.extensions.logging.loglevel#Microsoft_Extensions_Logging_LogLevel
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44226554', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/419956/']}
|
jdg_378477
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14969507
|
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 testing out Libgdx and Scene2d. I expected this small program to display a logo, but it draws a black screen only. Any idea what am I missing? public class MyGame implements ApplicationListener { private Stage stage; @Override public void create() { stage = new Stage(800, 800, false); Gdx.input.setInputProcessor(stage); MyActor actor = new MyActor(); stage.addActor(actor); } @Override public void render() { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); stage.act(Gdx.graphics.getDeltaTime()); stage.draw(); } @Override public void dispose() { stage.dispose(); } @Override public void resize(int width, int height) { stage.setViewport(800, 800, false); }}public class MyActor extends Actor { Sprite sprite; public MyActor() { sprite = new Sprite(); sprite.setTexture(new Texture("data/libgdx.png")); setWidth(sprite.getWidth()); setHeight(sprite.getHeight()); setBounds(0, 0, getWidth(), getHeight()); setTouchable(Touchable.enabled); setX(0); setY(0); } @Override public void draw(SpriteBatch batch, float parentAlpha) { Color color = getColor(); batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); batch.draw(sprite, getX(), getY()); }}
Now provide the response and nothing else.
|
Construct the sprite with the texture and use Gdx.file.internal: sprite = new Sprite(new Texture(Gdx.files.internal("data/libgdx.png"))); Anyway, if you just want to display and act on images, you might prefer to use Image class: private Stage stage; private Texture texture; @Override public void create() { stage = new Stage(); Gdx.input.setInputProcessor(stage); texture = new Texture(Gdx.files.internal("data/libgdx.png")); TextureRegion region = new TextureRegion(texture, 0, 0, 512, 275); com.badlogic.gdx.scenes.scene2d.ui.Image actor = new com.badlogic.gdx.scenes.scene2d.ui.Image(region); stage.addActor(actor); } @Override public void render() { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); stage.act(Gdx.graphics.getDeltaTime()); stage.draw(); }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14969507', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/271813/']}
|
jdg_378478
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28421966
|
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 Spring Boot WebMVC application, and a bean that inherits from AbstractPreAuthenticatedProcessingFilter which I am explicitly adding to a specific spot in the Spring Security filter chain. My Spring Security configuration looks like this: <http pattern="/rest/**"> <intercept-url pattern="/**" access="ROLE_USER"/> <http-basic/> <custom-filter after="BASIC_AUTH_FILTER" ref="preAuthenticationFilter"/></http><beans:bean id="preAuthenticationFilter" class="a.b.PreAuthenticationFilter"> <beans:property name="authenticationManager" ref="customAuthenticationManager"/></beans:bean> The security configuration works. The problem is, because the PreAuthenticationFilter class inherits from AbstractPreAuthenticatedProcessingFilter, Spring Boot treats it as a general purpose servlet filter and is adding it to the servlet filter chain for all requests. I don't want this filter to be part of the filter chain for all requests. I only want it to be part of the specific Spring Security filter chain that I've configured. Is there a way to prevent Spring Boot from automatically adding the preAuthenticationFilter bean to the filter chain?
Now provide the response and nothing else.
|
By default Spring Boot creates a FilterRegistrationBean for every Filter in the application context for which a FilterRegistrationBean doesn't already exist. This allows you to take control of the registration process, including disabling registration, by declaring your own FilterRegistrationBean for the Filter . For your PreAuthenticationFilter the required configuration would look like this: @Beanpublic FilterRegistrationBean registration(PreAuthenticationFilter filter) { FilterRegistrationBean registration = new FilterRegistrationBean(filter); registration.setEnabled(false); return registration;} You may also be interested in this Spring Boot issue which discusses how to disable the automatic registration of Filter and Servlet beans.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/28421966', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1519265/']}
|
jdg_378479
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16737910
|
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 working on a game which involves vehicles at some point. I have a MySQL table named "vehicles" containing the data about the vehicles, including the column "plate" which stores the License Plates for the vehicles. Now here comes the part I'm having problems with. I need to find an unused license plate before creating a new vehicle - it should be an alphanumeric 8-char random string. How I achieved this was using a while loop in Lua, which is the language I'm programming in, to generate strings and query the DB to see if it is used. However, as the number of vehicles increases, I expect this to become even more inefficient it is right now. Therefore, I decided to try and solve this issue using a MySQL query. The query I need should simply generate a 8-character alphanumeric string which is not already in the table. I thought of the generate&check loop approach again, but I'm not limiting this question to that just in case there's a more efficient one. I've been able to generate strings by defining a string containing all the allowed chars and randomly substringing it, and nothing more. Any help is appreciated.
Now provide the response and nothing else.
|
This problem consists of two very different sub-problems: the string must be seemingly random the string must be unique While randomness is quite easily achieved, the uniqueness without a retry loop is not. This brings us to concentrate on the uniqueness first. Non-random uniqueness can trivially be achieved with AUTO_INCREMENT . So using a uniqueness-preserving, pseudo-random transformation would be fine: Hash has been suggested by @paul AES-encrypt fits also But there is a nice one: RAND(N) itself! A sequence of random numbers created by the same seed is guaranteed to be reproducible different for the first 8 iterations if the seed is an INT32 So we use @AndreyVolk's or @GordonLinoff's approach, but with a seeded RAND : e.g. Assumin id is an AUTO_INCREMENT column: INSERT INTO vehicles VALUES (blah); -- leaving out the number plateSELECT @lid:=LAST_INSERT_ID();UPDATE vehicles SET numberplate=concat( substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@lid)*4294967296))*36+1, 1), substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1), substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1), substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1), substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1), substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1), substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1), substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed)*36+1, 1))WHERE id=@lid;
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/16737910', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1333566/']}
|
jdg_378480
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1377134
|
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 am not able to figure out why the reminder of $8^{30} / 7$ is same as that of $1^{30} / 7$. I know Euclid division $a=bq+r$ but I don't know modular arithmetic, so please explain without referring to modular arithmetic. Thanks in advance.
Now provide the response and nothing else.
|
By the binomial theorem, we have$$8^{30}=(7+1)^{30}=\sum_{k=0}^{30}\binom{30}{k}7^{30-k}\cdot 1^k=7\left(\sum_{k=0}^{29}\binom{30}{k}7^{29-k}\right)+1^{30}$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1377134', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/103816/']}
|
jdg_378481
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1050043
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The active directory I have to deal with is laid out as such: the domain contains many OUs. One of these OUs is named "Primary OU". Within this OU are several OUs named with location of global offices (ie "Chicago" "Paris"). Any user account that is an actual flesh and bone person is put into the OU named for the office they work in as their primary OU. Any user account that is an alias, generic account, or otherwise not directly tied to a real person, has the "Primary OU" OU set as their primary OU. Data-wise, this primary OU distinction is the only thing that indicates which users are real people, and which users are not. There is no group that contains only real people, no indicator in any field that they are real people or not, and making any changes to active directory or any user accounts is strictly forbidden. My task is writing a query that will only get all actual flesh and bone people. Unfortunately LDAP is not exactly my strong suit and the only way I've come up with is searching each of these office sub OUs individually and putting all the results together, but there are a lot of offices and it would require a change to the query if any offices were added, which I need to avoid. Is there a way to query all users within a particular OU's "sub" OUs, but not return any users directly in the parent OU?
Now provide the response and nothing else.
|
Yes, sure - you would need to: 1) Bind to the particular OU DirectoryEntry myOU = new DirectoryEntry("LDAP://OU=MyOU,......,DC=MyCompany,DC=com"); 2) Enumerate all its sub-OU's DirectorySearcher subOUsearcher = new DirectorySearcher(myOU);subOUsearcher.SearchScope = SearchScope.OneLevel; // don't recurse downsubOUsearcher.Filter = "(objectClass=organizationalUnit)";foreach(SearchResult subOU in subOUsearcher.FindAll()){ // stick those Sub OU's into a list and then handle them} 3) One-by-one enumerate all the users in each of the sub-OU's and stick them into a global list of users DirectorySearcher userSearcher = new DirectorySearcher(myCurrentSubOu);userSearcher.SearchScope = SearchScope.OneLevel; // don't recurse downuserSearcher.Filter = "(objectClass=user)";foreach(SearchResult user in userSearcher.FindAll()){ // stick those users into a list being built up} 4) Return that list Marc
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1050043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/108971/']}
|
jdg_378482
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2236120
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
After I start the emulator by hitting Debug in Eclipse, after certain time it disconnects from the ADB, but the emulator stays open. It is responsive, I can navigate and start apps. How can I attach back the emulator to ADB, to be able to debug from Eclipse? (the current workaround is the terminate the emulator, close Eclipse and restart both of them, which takes 10 minutes as you know the emulator needs time to start up) EDIT 1 Check out this image: EDIT 2 After I kill and restart server. One emulator process shows up in Devices tab in Eclipse. But that cannot be expanded, and I don't see sub-processes. I can't hit debug already, as it says: Debug already running. (How to I stop the debug?) If I managed to start the debugging of another project, It hangs out in the emulator telling me: Waiting for the debugger to attach. Nothing happens.
Now provide the response and nothing else.
|
As you said, the problem is not Eclipse losing contact with the Emulator, but ADB - the Android Debug Bridge - losing contact with it. As Eclipse uses ADB to communicate with the emulator when ADB is broken Eclipse can do nothing. To fix this stop the ADB server by running the following command: adb kill-server Eclipse will then usually try to restart ADB, or you can restart it yourself by running an ADB command, such as: adb devices If you do, you'll see output like this: * daemon not running. starting it now ** daemon started successfully *List of devices attachedemulator-5554 device You can also do this via the mouse, using the Reset adb option in the Devices view in Eclipse. It's also worth noting the Console view has two modes, DDMS and Android . You're usually in Console mode but it's DDMS mode which will show ADB status messages. Select modes by clicking the button with the Monitor icon, or using the arrow next to it: If all else fails, try killing the adb processes from the OS. On Windows XP I use: TASKKILL /F /IM adb.exe
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2236120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/243782/']}
|
jdg_378483
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20264135
|
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 the following code acceptable in C++? If so, what happens? Does it create a temp string variable and pass its address? void f(const string& s) {}const char kJunk[] = "junk";f(kJunk);
Now provide the response and nothing else.
|
Yes, it's acceptable. The compiler will call the string(const char *) constructor and create a temporary that will be bound to s for the duration of the call. When the fall to f returns the temporary will be destroyed.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20264135', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/382939/']}
|
jdg_378484
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1283324
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There are a lot of cases in which one would alloc an instance, and release it right after it's being assigned to something else, which retains it internally. For example, UIView *view = [[UIView alloc] initWithFrame...];[self addSubView:view];[view release]; I have heard people suggesting that we go with autorelease rather than release right after. So the above becomes: UIView *view = [[[UIView alloc] initWithFrame...] autorelease];[self addSubView:view]; What's the best practice here? Pros and cons?
Now provide the response and nothing else.
|
In most cases, it wont really matter either way. Since -autorelease simply means that the object will be released at the end of the current iteration of the run loop, the object will get released either way. The biggest benefit of using -autorelease is that you don't have to worry about the lifetime of the object in the context of your method. So, if you decide later that you want to do something with an object several lines after it was last used, you don't need to worry about moving your call to -release . The main instance when using -release will make a noticeable difference vs. using -autorelease is if you're creating a lot of temporary objects in your method. For example, consider the following method: - (void)someMethod { NSUInteger i = 0; while (i < 100000) { id tempObject = [[[SomeClass alloc] init] autorelease]; // Do something with tempObject i++; }} By the time this method ends, you've got 100,000 objects sitting in the autorelease pool waiting to be released. Depending on the class of tempObject , this may or may not be a major problem on the desktop, but it most certainly would be on the memory-constrained iPhone. Thus, you should really use -release over -autorelease if you're allocating many temporary objects. But, for many/most uses, you wont see any major differences between the two.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1283324', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/66814/']}
|
jdg_378485
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
424368
|
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 would you open a file (that has a known file/app association in the registry) into a "running instance" of the application it's supposed to open in? An example would be, I have Excel open and I click on an XLS file.....the file opens up in the current Excel instance. I want to do this for a custom application...how does the eventing/messaging work that "tells" the current instance that it needs to open a file? Is there a "file watcher" that looks for a request to do so etc? Thanks..
Now provide the response and nothing else.
|
What you want to do is inherit a class from WindowsFormsApplicationBase , setting the protected IsSingleInstance property to true: // This should all be refactored to make it less tightly-coupled, obviously.class MyWindowsApplicationBase : WindowsFormsApplicationBase{ internal MyWindowsApplicationBase() : base() { // This is a single instance application. this.IsSingleInstance = true; // Set to the instance of your form to run. this.MainForm = new MyForm(); }} The Main method of your app then looks like this: // This should all be refactored to make it less tightly-coupled, obviously.public static void Main(string args[]){ // Process the args. <process args here> // Create the application base. MyWindowsApplicationBase appBase = new MyWindowsApplicationBase(); // <1> Set the StartupNextInstance event handler. appBase.StartupNextInstance = <event handler code>; // Show the main form of the app. appBase.Run(args);} Note the section marked <1>. You set this up with an event handler for the StartupNextInstanceEvent . This event is fired when the next instance of your app is fired when you have a single instance application (which you specified in the constructor of MyWindowsApplicationBase). The event handler will pass an EventArgs-derived class which will have the command line arguments which you can then process in the running instance of your app. Then, all you have to do is set the file associations normally for the file types you want your app to process, and you are set.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/424368', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4398/']}
|
jdg_378486
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48069034
|
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 deploying a large database (both schema and data) from an on-premise server to Azure SQL. I plan on using sqlpackage.exe from the command line. It looks like there are two options: Extract a DACPAC and then publish it to Azure, using theExtractAllTableData option to include data in the extraction Export a BACPAC and then import it to Azure Is there a preferred option? I need this process to run in the fastest way possible, so I'd be curious if one option is better for performance.
Now provide the response and nothing else.
|
As Grant said bacpac is dacpac+data.Below is one more definition that might help "A bacpac includes the schema and data from the database. A dacpac containers only the schema and not the data" You might have understood, you need bacpac. I need this process to run in the fastest way possible, so I'd be curious if one option is better for performance. We have few databases(400Gb) in Azure.we observed it is faster to import data when we load data from storage..The approach we followed was to load data into storage which is in same location as database and then import data.. SQLSERVER team tested a few options and they observed BCP is fastest compared to remaining options .. Below is how you import bcp data into azure bcp TestDB.dbo.Customer in "C:\Users\cesardl\BCP\Customer.txt" -c -U mysqlazureuser@mysqlazureservername -S tcp:mysqlazureservername.database.windows.net -P mypassword Further reading/References: Importing/Exporting data to SQL Azure databases using BCP and SQL Scripts Loading data to SQL Azure the fast way
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48069034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3397281/']}
|
jdg_378487
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2099699
|
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:
Let A be a non-empty set and $f : A → A$ be a function. Prove that f has a left inverse in $F_{A}$ if and only if f is injective(one-to-one). $\leftarrow$ assume f is injective then $\forall x\in A \space \space \space \space \space \space \space \space \space f(x) \in A $ such that if $f(x)=f(y) $ then $ x=y$ something something $g(f(x)) = x \space \space \space \space \forall x\in A$ $\rightarrow$ assume f has a left inverse in $F_{A}$ then $\forall x\in A$ $g(f(x)) = x$ something says that x must be one to one? Im really confused by this question First of all f must be a bijection if it is one to one from $ A \to A $ is it not? Can someone help me out with this proof?
Now provide the response and nothing else.
|
Suppose $f$ has a left inverse $g$. Suppose $f(x)=f(y)$ for some $x,y\in A$. Then $gf(x)=gf(y)$. Since $gf=i_A$, we have $x=y$ and hence $f$ is injective. Suppose $f$ is injective.Let $a_0$ be a fixed element in $A$. Define $g:A\rightarrow A$ by the rules: For $x\in A$ (i) If there is an element $y\in A$ such that $f(y)=x$, then $g(x)=y$. (ii) If no such element $y$ exists in $A$, then $g(x)=a_0$. For case (i), the element $y$ is unique as if $g(x)=y_1$ and $g(x)=y_2$, then $f(y_1)=x=f(y_2)$ which implies $y_1=y_2$. For case (ii), $g(x)=a_0$ is also unique by the way we define it. So $g$ is a function from $A$ to $A$. For $a\in A$, $gf(a)=a$ as $f(a)=x\in A$ implies $g(x)=a$ by (i). Hence $g$ is a left inverse of $f$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2099699', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/60353/']}
|
jdg_378488
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
42423774
|
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 debugging in Visual Studio Code and I have a JSON object that I would like to copy as text to the clipboard. Is this possible inside of Visual Studio Code?
Now provide the response and nothing else.
|
I found two ways to do that, both of which are a bit hacky (in my eyes). Use console.log I think there will be a limit to the size of the string that this can output, but it was satisfactory for my requirements. In the debug console, write console.log(JSON.stringify(yourJsonObject)) Copy the resulting output from the debug console. That can be a bit tedious for long strings, but a combination of mouse and keyboard (ctrl-shift-end) worked ok for me. Use a watch (limited to 10'000 characters) This method only works up to a limited size of the resulting json string (it looks like 10'000 characters). Set a breakpoint in a reasonable location where your variable is in scope and start your app. Go to the debug view, add a watch for a temporary variable, e.g. tmpJson Get your breakpoint to hit. In the debug console, write var tmpJson = JSON.stringify(yourJsonObject) This will now have populated the watched variable tmpJson with the string representation of your json object In the debug view, right click on the watched variable, click copy. If the string is too long, it cuts it off with a message like the following: ...,"typeName":"rouParallel","toolAssembly":{"id":"ASKA800201","description":"CeonoglodaloD50R6z5","c... (length: 80365)" But it would work for smaller objects. Maybe this helps some people.It would be great to have this properly built-in with vscode.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42423774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/426422/']}
|
jdg_378489
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4313418
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
async process dialog is not showing in application in android. Can anybody tell me what the problem is? My code public void onClick(View v){ new FetchTask(getBaseContext()).execute(null); } public class FetchTask extends AsyncTask<Object, ArrayList,ArrayList> { private ProgressDialog dlg; private Context ctx; public FetchTask(Context context) { ctx = context; } @Override protected void onPreExecute() { dlg = new ProgressDialog(ctx); dlg.setMessage("Loading...."); dlg.show(); super.onPreExecute(); } @Override protected void onPostExecute(ArrayList parserValue) { dlg.dismiss(); for(int i=0;i<parservalue.size();i++) { DomParserDataSet dataset=(DomParserDataSet)parservalue.get(i); if(dataset.getToken_string().length()>1) { Intent homeIntent=new Intent(ctx,HelloTabWidget.class); homeIntent.putExtra("strUserName", username); homeIntent.putExtra("strPassword",password ); homeIntent.putExtra("questGroupId",dataset.getQuest_group_id()); homeIntent.putExtra("userid",dataset.getUser_id()); homeIntent.putExtra("systemuserid", dataset.getSystem_user_id()); homeIntent.putExtra("providerid",dataset.getIndex_provider_id()); startActivity(homeIntent); //startActivity(new Intent(this,HelloTabWidget.class)); } else { DomParserDataSet dataset1=(DomParserDataSet)parservalue.get(i); AlertDialog.Builder alertbox = new AlertDialog.Builder(ctx); alertbox.setMessage(dataset1.getError_value()); alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int arg1) { // the button was clicked dialog.cancel(); } }); // show it alertbox.show(); } } // display data } @Override protected ArrayList doInBackground(Object... arg0) { try { username=edtUserName.getText().toString(); password=edtPassword.getText().toString(); WebService service=new WebService(); String webservicevalue=service.callServer(SOAP_ACTION,"", username,password,URL); webservicevalue=decodeXMLData(webservicevalue); DomParser xmlParser=new DomParser(); parservalue=xmlParser.parseXmlFile(webservicevalue); String parservalue1=Integer.toString(parservalue.size()); Log.d("parser value size is",parservalue1); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return parservalue; } } Can anybody tell me what I have to change?
Now provide the response and nothing else.
|
Okay, I found the answer. Sometimes you just don't see the forest for the trees. First off, handling cases of blocked ports is trivial. A simple try/catch does the trick. I was simply confused by the way Chrome displayed that exception and didn't recognize it as such right away (I usually use Firefox). Secondly, the WebSockets API Specification explicitly states that If port is a port to which the user agent is configured to block access, then throw a SECURITY_ERR exception. (User agents typically block access to well-known ports like SMTP.) What ports exactly are meant by that appears to be up to the browser's Websocket implementation. My tests have shown that Chrome and Safari block the following ports (only ports below 1024 were tested): 1: TCPMUX 7: Echo Protocol 9: Discard Protocol 11: systat service 13: Daytime Protocol 15: Netstat service 17: Quote of the Day 19: Character Generator Protocol 20: FTP 21: FTP 22: SSH 23: Telnet 25: SMTP 37: TIME protocol 42: nameserver/WINS 43: WHOIS 53: DNS 77: RJE Service 79: Finger 87: link 95: supdup 101: NIC host name 102: ISO-TSAP 103: gppitnp 104: ACR/NEMA 109: POP2 110: POP3 111: SunRPC 113: ident 115: SFTP 117: UUCP Path Service 119: NNTP 123: NTP 135: Microsoft EPMAP 139: NetBIOS Session Service 143: IMAP 179: BGP 389: LDAP 465: Cisco protocol 512: comsat 513: rlogin 514: Syslog 515: Line Printer Daemon 526: tempo 530: RPC 531: IRC 532: netnews 540: UUCP 556: RFS 563: NNTPS 587: SMTP 601: unknown 636: LDAPS 993: IMAPS 995: POP3S The associated services are taken from the list of TCP and UDP port numbers on Wikipeda .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4313418', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/426344/']}
|
jdg_378490
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
319916
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Suppose that $G=(V,E)$ is a simple graph and $P=(V_1,E_1)$ is a path in $G$ where $$V_1=\{v_0,v_1,\cdots,v_n\},\ E_1=\{v_0v_1,v_1v_2,\cdots,v_{n-1}v_n\}.$$ I found that if the path $P$ satisfies: For any $v_i\in V_1$ , there exist $v_j\in V_1\setminus \{v_i\}$ and $u\in V\setminus V_1$ such that $uv_i,uv_j\in E$ . Then you can always find a longer $v_0$ - $v_n$ path in $G$ . I have tried to find a counterexample to this for a long time but still cannot find one. So I think maybe the above conjecture is true. Is it true or is there any known result about this? Any ideas are welcome!
Now provide the response and nothing else.
|
MattF's counterexample, understood properly, is actually a counterexample. His original path sequence in my notation was 142341243 (there are 4 vertices 1,2,3,4 outside the path (octopus heads) and the number shows the leg of which octopus the path vertex is. The key property of this sequence is that if you go from the beginning to the end and make at least one jump, you have to miss at least one vertex. Now surround each vertex $*$ on this path with its own block of the type $aa\dots aa*A$ where each $a$ is connected to $A$ by its own extra vertex (so the jumps between $a$ and $A$ are possible but the jumps between $a$ and $a$ are not and there are no "A" or $a$ -connections between the blocks). If we execute at least one long $*$ to $*$ jump between blocks, we will gain at most 4 vertices on the long jumps and at most 2 vertices within each used block with the total gain of $2\cdot 8+4=20$ but we will lose an entire block, so if we have $19$ $a$ 's,the loss outweighs the gain. Otherwise, we have to honestly traverse each block and this does not create any gain either. It is funny that I have thought of this block construction long ago but missed that $aa\dots aa*A$ possibility. The examples where you have only octopuses all resulted in paths to $*$ from both ends of the block with gains comparable to the total block length, so increasing block length did not help. I hope that I haven't made a mistake here, but by all means check the details and ask questions if something looks wrong :-) Edit: Here is a picture of the graph with $19=5$ . The path is the horizontal straight line. If you just keep the bottom colored part, this would be exactly Matt F.'s original construction. Edit 2: Pure "octopus" construction. First, the notation. If the graph vertices outside the path are labelled with some symbols, then the graph will be represented as a string of these symbols according to which vertex outside the path each vertex on the path is connected to. The symbol $*$ is reserved for a vertex on the path that is not connected to anything. For instance, the graph with 7 path vertices $v_0,\dots v_6$ and 3 out of the path vertices labeled $u_0,u_1,u_2$ in which $u_0$ is connected to $v_0,v_4$ , $u_1$ is connected to $v_1,v_3$ , $u_2$ is connected to $v_2$ and $v_6$ and $v_5$ is not connected to anything is represented as $01210*2$ . When we move from the path to an out of the path vertex and then back to the path, we say that we make a jump . For instance, making the jump between $2$ 's in the above example means that we follow the route $v_2u_2v_6$ (possibly backwards). The length of the route is the number of vertices in it. When we make a simple move to a neighboring vertex along the path, the length of the route goes up by $1$ ; when we jump, it goes up by $2$ . The gain of the route is the excess of its length over the length of the original path. If it is negative, we call minus the gain a loss . The route we are talking about can be between any 2 vertices, not only between the beginning and the end. For instance, in our example $01210*2$ we can consider the route $1\to 1\to 2\to 2\to *\to 0\to 0$ from one of the $1$ 's to $0$ of length $1+2+1+2+1+1+2=10$ with gain $10-7=3$ . Of course, we can always change our symbols to any other ones: $abcba*c$ represents the same graph. A jumping block is a graph represented by a string with a single $*$ and each other symbol appearing at least twice and such that no route from the beginning to the end with positive gain is possible. For instance, the graph in our example is not a jumping block because it satisfies the first two conditions but not the third one: the route $0\to 0\to 1\to 1\to 2\to 2$ has length $9$ and gain $2>0$ but the graph $012*210$ , say, is. If $G$ is a jumping block, then we shall be concerned with 2 corresponding quantities: the length $L=L(G)$ of the underlying path and the maximal possible gain $a=a(G)$ on a route between $*$ and one of the ends. For instance, the jumping block $012*210$ has $L=7$ and $a=3$ (on the route $0\to 0\to 1\to 1\to 2\to 2\to *$ ). Note that we always have $a\le\frac{L-1}2$ because the gain can come only from jumps and we can execute at most $\frac{L-1}2$ jumps in any route (a jump corresponding to each symbol in the string can be used at most once). So, if we define $A(G)=2a(G)+1$ , we have $A(G)\le L(G)$ . Clearly, if some string is to a jumping block, the reverse string is also a jumping block with the same $L,a$ . Suppose we have a jumping block $H$ of length $L$ and $L$ jumping blocks $G_1,\dots, G_L$ (not necessarily identical) of the same length $M$ . Then we can construct a new jumping block $[G_1,\dots,G_L]_H$ as follows. Represent $H$ and $G_j$ by strings so that different strings have no common symbols (except $*$ ) and put the $G_j$ strings together in a row. Now we have $L$ $*$ -symbols in the resulting string. Replace them (from left to right) by the symbols in $H$ (so just one $*$ will remain a $*$ ). For example, if $H=0*0$ and $G_1=G_2=012*210, G_3=0102*21$ ( $L=3, M=7$ here) , we first write $H=a*a$ , $G_1=012*210$ , $G_2=345*543$ , $G_3=6768*87$ , then make the string $012*210345*5436768*87$ and then replace $*$ 's to get $[G_1,G_2,G_3]_H=012a210345*5436768a87$ . The first claim is that $[G_1,\dots,G_L]_H$ is again a jumping block. Indeed, any beginning to end route in $[G_1,\dots,G_L]_H$ corresponds to a beginning to end route in $H$ . Just see in each order you enter and exit the blocks $G_j$ . Note that it is possible to enter, exit, and then re-enter the same block $G_j$ , but then you get stuck there, so on the route from the beginning to the end, once you enter an intermediate block and exit it, you can never return and for the endpoint blocks, once you enter them, you either reach the end of the entire string, in which case your route terminates, or exit without reaching it and then can never return. Thus any route from the beginning to the end stays for a while in $G_1$ , then goes to some other block $G_j$ , stays for a while there, etc. Suppose now that we have some route from the beginning to the end in $[G_1,\dots,G_L]_H$ and the corresponding route in $H$ has $J$ jumps. Then, since $H$ is a jumping block, that corresponding route must miss $\ge J$ vertices in $H$ , i.e., the original route misses at least $J$ full blocks $G_j$ with the total of $JM$ vertices. What we may gain is that for each of the $2J$ blocks corresponding to the jump ends, we do not need to traverse them from the beginning to the end, but just from one endpoint to the jumping place. However, on those we can gain at most $2J\max_j a(G_j)\le J(M-1)$ extra vertices. Finally, the $J$ interblock jumps create $J$ extra vertices and the total gain is $-JM+(\le J(M-1))+J\le 0$ . We also need to bound $A([G_1,\dots,G_L]_H)$ . Again, a route to $*$ in this composite graph corresponds to a similar route to $*$ in $H$ for the same reasons as before (note that it is essential here that we cannot jump to $*$ or into a $*$ -block). Now denote by $J$ the number of jumps on that route in $H$ . By the definition of $a(H)$ we see that we must miss at least $(J-a(H))_+$ vertices in $H$ , each of which corresponds to a full block in $[G_1,\dots,G_L]_H$ . So we conclude that our total gain on any route to $*$ from any of the endpoints is at most $$-M(J-a(H))_++(2J+1)a+J\\=-M(J-a(H))_++J(2a+1)+a\le a(H)(2a+1)+a\,.$$ Here $a=\max_j a(G_j)$ , the second term corresponds to most $2J+1$ blocks $G_j$ in which we need to connect one of the endpoints to the jump position instead of the other endpoint (the ends of interblock jumps and the final $*$ block), $J$ is the gain on the interblock jumps, and the inequality $2a+1\le M$ is used in the last step. This estimate can be rewritten as $A([G_1,\dots,G_L]_H)\le A(H)\max_j A(G_j)$ . In particular, when $G_1=\dot=G_L=G$ , we have $$A([G,\dots,G]_H)\le A(H)A(G)\,.$$ Assume now that we have a jumping block $G$ with $a(G)\le \frac 18L(G)-\frac 12$ . Then we can use the Matt F's graph $H=142341243$ to create the graph $[G,\dots,G]_H$ in which every path from the beginning to the end either does not use the interblock jumps at all (so no gain is possible here), or misses an entire block (so the gain is at most $-L(G)+8a(G)+4\le 0$ again), thus providing a pure octopus counterexample. To build such a jumping block, it would suffice to have any jumping block $G$ with $A(G)<L(G)$ because then we can consider the sequence of the jumping blocks $G_1=G$ , $G_{k+1}=[G_k,\dots,G_k]_G$ with $A(G_k)\le A(G)^k, L(G_k)=L(G)^k$ and choose a sufficiently large $k$ . Finally, to build a jumping block with $A(G)<L(G)$ , it would suffice to build one in which no route from the left end to $*$ can use all available jumps. If $G_0$ is such a jump block, then $G=[G_0G_0\bar G_0]_{a*a}$ , where $\bar G_0$ is represented by the same string as $G_0$ but written backwards, will work because now, to reach the $*$ from either of the ends , we must either reach the jumping position in $G$ from the left end, or not to use the interblock jump and, thus, miss the opposite block entirely. Thus, we just need a single jumping block with no route from the left end to the star position using all jumps. Fortunately, the computer search yielded the result with $L=15$ (a few seconds of computer time) and the block is $0121345*5407372$ . Once you know it, the verification of the properties by hand is a routine (though somewhat boring) casework, so I'll skip it (but if you discover that there is an error here, by all means let me know :-) ) The result of our construction with this block is a graph with $45^{31}$ vertices on the path and about half that number out of the path. Note also that in the entire graph we have just a single out of the path vertex of degree 3 (the one in the Matt F. graph), which shows that the domotorp result cannot be improved.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/319916', 'https://mathoverflow.net', 'https://mathoverflow.net/users/58096/']}
|
jdg_378491
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48020703
|
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 need to remove all empty/null values from List<Optional<String>> . Example: List<Optional<String>> list = new ArrayList<>();list.add(Optional.empty());list.add(Optional.of("Str1"));list.add(Optional.of("Str2"));list.add(Optional.of("Str3"));list.add(Optional.of("Str4"));list.add(Optional.of("Str5"));list.add(Optional.empty());list.add(Optional.ofNullable(null)); Currently, I'm using one of the below approaches: Way 1: List<String> collect = list.stream() .filter(Optional::isPresent) .map(obj ->obj.get()) .collect(Collectors.toList()); Way 2: List<Optional<String>> emptlist = new ArrayList<>();emptlist.add(Optional.empty());list.removeAll(emptlist); Is there any other better way?
Now provide the response and nothing else.
|
With Java9 , you can do this using the newly added Optional::stream API : List<String> collect = list.stream() .flatMap(Optional::stream) .collect(Collectors.toList()); This method can be used to transform a Stream of optional elements to a Stream of present value elements . Sticking with Java8 , the Way1 in the question is good enough IMHO - List<String> collect = list.stream() .filter(Optional::isPresent) .map(Optional::get) // just a small update of using reference .collect(Collectors.toList());
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48020703', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/320087/']}
|
jdg_378492
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
653494
|
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 reading calculus book by Morris Kline. This book treats physics because calculus grew out of physical and geometrical problems. I have no background about physics and got a question while reading the book. $$F = \frac{GmM}{r^2}$$ When considering a tennis ball and the earth with this Newton's law and assuming the earth's mass is concentrated at its center, they exert the same force according to the equation. Then if I drop the tennis ball onto the ground and it travels 40 feet, which one moves by the force as a result? Does the tennis ball move 40 feet to the earth, the earth move 40 feet to the ball, each one move 20 feet to each other or anything else?
Now provide the response and nothing else.
|
They both move towards each other. But the acceleration of, and thus distance traveled by, the earth is infinitesimal compared to the the ball because the mass of the earth is so much greater than the ball. From Newton's 2nd law, the acceleration of the ball towards the earth is $$a_{ball}=\frac{F}{m}$$ The acceleration of the earth towards the ball is $$a_{earth}=\frac{F}{M}$$ Since $$M \gg m \\ a_{earth} \ll a_{ball}$$ Hope this helps.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/653494', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/307895/']}
|
jdg_378493
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3490648
|
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:
Is there a sequence of positive numbers $\epsilon_1,\epsilon_2,...$ with the following property? If $g_n\in C[0,1]$ (continuous functions on $[0,1]$ ) and $g_n\rightarrow0$ pointwise, then $\epsilon_ng_n\rightarrow0$ uniformly. Attempt) Since $g_n\in C[0,1]$ , $|g_n|\leq M_n$ for each $n$ . I guess since $g_n\rightarrow0$ pointwise, $M_n\leq M$ for some $M$ . Then if we take $\epsilon_n=\frac{1}{n}$ . $\sup\limits_{x\in [0,1]}|\epsilon_ng_n(x)-0|\leq\frac{M}{n}\rightarrow0$ . So $\epsilon_ng_n\rightarrow0$ uniformly.
Now provide the response and nothing else.
|
Given any sequence of positive numbers $\epsilon_n$ , you can find $g_n$ such that $g_n(0)=0$ and $g_n(x) = 0$ on $[1/n, 1]$ , but $\epsilon_n g_n(1/(2n)) =1$ .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3490648', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
|
jdg_378494
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
205835
|
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:
Despite being very stakeholders friendly, ATDD aimed to provide a "stop" line when a feature has just been done. This avoids wasting time to add non-focused (and sometimes useless) code. That's why some teams start by establishing a walking skeleton of the application, and directly specifying with an acceptance test the first required feature. Let's suppose this first acceptance test (not representing a relevant first acceptance test, just being an example): Given Michael has just been created in the application,his status should be left to non-activated. I want to write my acceptances tests focusing on business logic directly (use-cases), not dealing with GUI for business rules. Thus my question would be...how to write it? since I don't even already know what is a "User", what is a status etc...Indeed, shouldn't it be the role of TDD to emerge the design and therefore these components? But if I firstly practice TDD in order to emerge them, the benefit of ATDD (as a stop line) would disappear. I imagine that it would be more consistent to write some acceptance tests (before entering TDD cycle) when the project has well progressed, since all main components would already be designed. To sum up, should I always write my acceptances test BEFORE my TDD cycle?
Now provide the response and nothing else.
|
Acceptance tests access the application through a special purpose API. You presented this use case: Given Michael has just been created in the application, his status should be left to non-activated. The API implied from this use case is something like: CreateUser(String name);enum UserStatus {non-activated};UserStatus GetUserStatus(String name); So far this has nothing to do with TDD. It's just a simple API that your acceptance tests can use to access the application. Now, to make this acceptance test pass, you'll have to implement this API. That's when you start doing TDD. The decisions you make while test-driving the solution will help you determine the design of the application. Note that the design of the application has nothing to do with the design of the API that's used by your acceptance tests. That API is an adapter layer between those tests and your application. That layer allows your application to assume any design you so desire. Regarding TDD and design. It is true that design emerges from TDD. But TDD is not the sole process by which you design your application. You also think through the design in many other ways. You might draw some UML diagrams. You might use CRC cards. You might have a design session with your co-workers. Indeed, you should likely do ALL of these things. And you should also allow designs to emerge with TDD. TDD doesn't replace previous design tools, it adds a new tool to the kit. Some folks will likely complain that this sounds like BDUF, and doesn't sound very "Agile". The problem with that is the letter 'B'. It's entirely true that we don't want to do BIG design up front. But it's not true at all that we don't want to do some design up front. We do! A few hours, or even days of design up front is not bad. Months and months of it is.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/205835', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/43961/']}
|
jdg_378495
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1798118
|
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 am trying to compute the discriminant of the trinomial $x^n+ax^m+b$. I have tried using resultants but cannot see how to approach it. Any hints?
Now provide the response and nothing else.
|
Since $X$ is irreducible, for any state $j$ there exist positive integers $n,n'$ such that $P_{ij}^n>0$ and $P_{ji}^{n'}>0$. Since $P_{ii}>0$, it follows that $P_{ii}^m>0$ for all positive integers $m$, and hence $$P_{jj}^{n+n'+m}\geqslant P_{ji}^{n'}P_{ii}^mP_{ij}^n>0. $$ This implies that the period of state $j$ is $1$. Since $j$ was arbitrary, we conclude that $X$ is aperiodic.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1798118', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/341966/']}
|
jdg_378496
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27473
|
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a 12" dobsonian with a 1500mm focal length and want to do some higher magnification planetary viewing. Currently my highest magnification is ~80x via my 19mm eyepiece (calculated here ), but I would like to do some viewing at higher magnification. My telescope is fitted for 2" diameter eyepieces, but I have an adapter for 1¼" eyepieces as well. I'm seeing a plethora of affordable 1¼-inch 9mm eyepieces , but very few 2" diameter options and very pricey at that. At this point, I see the following options, by increasing price: 1¼" diameter 9mm eyepiece 3x Barlow lens 2" diameter 9mm eyepiece I've read that the 2" eyepieces yield greater field of view advantages. Is that still true when the goal is a narrow focal length on solar system objects? Would using a Barlow lens on my existing 2" eyepieces retain this advantage in a meaningful way? In summary, is there any significant value in keeping to the 2" diameter eyepiece capability of my telescope when doing planetary viewing with low focal length given the magnitude of the cost difference? I've referenced a "9mm" eyepiece here merely as an example, I'm sure most anything in the 5mm-12mm range would be fine.
Now provide the response and nothing else.
|
I would recommend a quality 1¼" 9 mm or 12 mm eyepiece as the optimal solution. You already have a 19 mm so something close to that such as 15 mm would bring small difference, so take a step or two down to a 9 mm or 12 mm Plössl lens. While a 2" eyepiece usually offers better eye relief (from bigger lens) the cost is also substantially more, and if you compromise on quality by buying a cheaper eyepiece the results will be less than satisfactory - lack of clarity, distortions from imperfections in the glass, etc. Extra magnification can also be obtained by using a Barlow, but you are also adding extra lenses to the optical path which will slightly reduce the amount of light you are getting at the eyepiece, but also any imperfections will be magnified. Also, with Dobsonians (usually) not having any tracking mechanisms you will be manually tracking your object of interest, and extra magnification means that it will be moving more quickly across your field of view as well as making it a little more difficult to keep it smoothly in the eyepiece. These are also arguments in favour of a 2" eyepiece over a 1¼" eyepiece, but either way, good eyepieces can be kept and re-used when/if you upgrade your telescope.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/27473', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/15920/']}
|
jdg_378497
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5899213
|
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 using Team Foundation Server 2010 with Visual Studio 2010. Whenever I modify a file outside of Visual Studio, TFS doesn't seem to detect the change done to the file, and thus doesn't offer me the option to check-in the file after it has been modified. How can this be solved?
Now provide the response and nothing else.
|
If you have a network connection to your server while you're working outside of Visual Studio, it's probably best to go ahead and check the file out before editing it, either using the tf command line client, or using the Windows Explorer shell integration that's available in the TFS Power Tools release. (Plus an increasing number of other tools have TFS integration that makes this automatic, but if you're just using notepad, this still needs to be a manual step.) Of course, there are many times when you're working and you don't have a network connection available that allows you to check out the files. If you know what files you've modified, you can just check them out from within Visual Studio, then you'll be able to check them back in. If you don't know what files you've edited, you can detect the changes by running the tfpt online command (also part of the Power Tools release). This will locate the files that have been modified locally and check these files out from the server.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5899213', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_378498
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4437089
|
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 am given the plot of a signal function. The expectation is to derive the full function given the graph's parameters. Here's what I've come up with so far for the negative side of the function: $\Pi(\frac{t}{10})+3\Lambda(\frac{(t+2)}{3})$ where and Unfortunately I am lost as to how to deal with the plateau in the middle and subsequently the positive side. Any hints or tips please?
Now provide the response and nothing else.
|
The definitions are not equivalent, even on the real line. For every integrable function $f \ge 0$ , the family of translates $\{x \mapsto f(x-c)\}_{c \in {\mathbb R}}$ is uniformly integrable by definition T but not by definition H. In fact, definition T does not yield that an almost everywhere convergent, uniformly integrable sequence converges in $L^1$ . Definition H does imply definition T. We will verify property (3.) in T, assuming a sequence $f_n$ satisfies H. Given $\epsilon>0$ ,find $g \in L_1^+$ such that $$\sup_n \int_{|f_n|>g} |f_n| \, d\mu <\epsilon \,. \quad (*)$$ We have $$ \sup_n \int_{|f_n| \le g \wedge \delta} |f_n| \, d\mu \le \int g \wedge \delta \, d\mu \to 0 \quad \text{as} \; \delta \downarrow 0$$ by dominated convergence. Together with (*), this gives $$ \limsup_{\delta \downarrow 0} \sup_n \int_{|f_n| \le \delta} |f_n| \, d\mu \le \epsilon \,,$$ and property (3.) in definition T follows.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4437089', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/373534/']}
|
jdg_378499
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1592457
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Interview question- Often its pretty easier to debug a program once you have trouble with your code.You can put watches,breakpoints and etc.Life is much easier because of debugger. But how to debug a program without a debugger? One possible approach which I know is simply putting print statements in your code wherever you want to check for the problems. Are there any other approaches other than this? As its a general question, its not restricted to any specific language.So please share your thoughts on how you would have done it? EDIT - While submitting your answer, please mention a useful resource (if you have any) about any concept. e.g. Logging This will be lot helpful for those who don't know about it at all.(This includes me, in some cases :) UPDATE: Michal Sznajderhas put a real "best" answer and also made it a community wiki.Really deserves lots of up votes.
Now provide the response and nothing else.
|
Actually you have quite a lot of possibilities. Either with recompilation of source code or without. With recompilation. Additional logging . Either into program's logs or using system logging (eg. OutputDebugString or Events Log on Windows). Also use following steps: Always include timestamp at least up to seconds resolution. Consider adding thread-id in case of multithreaded apps. Add some nice output of your structures Do not print out enums with just %d. Use some ToString() or create some EnumToString() function (whatever suits your language) ... and beware: logging changes timings so in case of heavily multithreading you problems might disappear. More details on this here . Introduce more asserts Unit tests "Audio-visual" monitoring: if something happens do one of use buzzer play system sound flash some LED by enabling hardware GPIO line (only in embedded scenarios) Without recompilation If your application uses network of any kind: Packet Sniffer or I will just choose for you: Wireshark If you use database: monitor queries send to database and database itself. Use virtual machines to test exactly the same OS/hardware setup as your system is running on. Use some kind of system calls monitor. This includes On Unix box strace or dtrace On Windows tools from former Sysinternals tools like http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx , ProcessExplorer and alike In case of Windows GUI stuff: check out Spy++ or for WPF Snoop (although second I didn't use) Consider using some profiling tools for your platform. It will give you overview on thing happening in your app. [Real hardcore] Hardware monitoring: use oscilloscope (aka O-Scope) to monitor signals on hardware lines Source code debugging: you sit down with your source code and just pretend with piece of paper and pencil that you are computer. Its so called code analysis or "on-my-eyes" debugging Source control debugging. Compare diffs of your code from time when "it" works and now. Bug might be somewhere there. And some general tips in the end: Do not forget about Text to Columns and Pivot Table in Excel. Together with some text tools ( awk , grep or perl ) give you incredible analysis pack. If you have more than 32K records consider using Access as data source. Basics of Data Warehousing might help. With simple cube you may analyse tons of temporal data in just few minutes. Dumping your application is worth mentioning. Either as a result of crash or just on regular basis Always generate you debug symbols (even for release builds ). Almost last but not least: most mayor platforms has some sort of command line debugger always built in (even Windows!). With some tricks like conditional debugging and break-print-continue you can get pretty good result with obscure bugs And really last but not least: use your brain and question everything . In general debugging is like science: you do not create it you discover it. Quite often its like looking for a murderer in a criminal case. So buy yourself a hat and never give up.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1592457', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/170339/']}
|
jdg_378500
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1637807
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
l = range(100) for i in l: print i, print l.pop(0), print l.pop(0) The above python code gives the output quite different from expected. I want to loop over items so that I can skip an item while looping. Please explain.
Now provide the response and nothing else.
|
I've been bitten before by (someone else's) "clever" code that tries to modify a list while iterating over it. I resolved that I would never do it under any circumstance. You can use the slice operator mylist[::3] to skip across to every third item in your list. mylist = [i for i in range(100)]for i in mylist[::3]: print(i) Other points about my example relate to new syntax in python 3.0 . I use a list comprehension to define mylist because it works in Python 3.0 (see below) print is a function in python 3.0 Python 3.0 range() now behaves like xrange() used to behave, except it works with values of arbitrary size. The latter no longer exists.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1637807', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/69746/']}
|
jdg_378501
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7975005
|
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 string with say: My Name is %NAME% and my age is %AGE%. %XXX% are placeholders. We need to substitute values there from an object. Object looks like: {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"} I need to parse the object and replace the string with corresponding values. So that final output will be: My Name is Mike and my age is 26. The whole thing has to be done either using pure javascript or jquery.
Now provide the response and nothing else.
|
The requirements of the original question clearly couldn't benefit from string interpolation, as it seems like it's a runtime processing of arbitrary replacement keys. However , if you just had to do string interpolation, you can use: const str = `My name is ${replacements.name} and my age is ${replacements.age}.` Note the backticks delimiting the string, they are required. For an answer suiting the particular OP's requirement, you could use String.prototype.replace() for the replacements. The following code will handle all matches and not touch ones without a replacement (so long as your replacement values are all strings, if not, see below). var replacements = {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"}, str = 'My Name is %NAME% and my age is %AGE%.';str = str.replace(/%\w+%/g, function(all) { return replacements[all] || all;}); jsFiddle . If some of your replacements are not strings, be sure they exists in the object first. If you have a format like the example, i.e. wrapped in percentage signs, you can use the in operator to achieve this. jsFiddle . However, if your format doesn't have a special format, i.e. any string, and your replacements object doesn't have a null prototype, use Object.prototype.hasOwnProperty() , unless you can guarantee that none of your potential replaced substrings will clash with property names on the prototype. jsFiddle . Otherwise, if your replacement string was 'hasOwnProperty' , you would get a resultant messed up string. jsFiddle . As a side note, you should be called replacements an Object , not an Array .
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/7975005', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/658659/']}
|
jdg_378502
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1775116
|
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 can $$\frac{2x-1}{x+2}$$ be split to give $$A-\frac{B}{x+2}$$ where $A$ and $B$ are integers? The solution is $$2-\frac{5}{x+2}.$$
Now provide the response and nothing else.
|
Observe that if you set $$y=x+2,\quad x=y-2,$$ then you get$$\frac{2x-1}{x+2}=\frac{2(y-2)-1}{y}=\frac{2y-5}{y}=2-\frac{5}{y}=2-\frac{5}{x+2}$$ as wanted.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1775116', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/140396/']}
|
jdg_378503
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23794713
|
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 set up a flexbox layout with three columns where the left and right columns have a fixed width, and the center column flexes to fill the available space. Despite setting up dimensions for the columns, they still seem to shrink as the window shrinks. Anyone know how to accomplish this? An additional thing I will need to do is hide the right column based on user interaction, in which case the left column would still keep its fixed width, but the center column would fill the rest of the space. #container { display: flex; justify-content: space-around; align-items: stretch; max-width: 1200px;}.column.left { width: 230px;}.column.right { width: 230px; border-left: 1px solid #eee;}.column.center { border-left: 1px solid #eee;} <div id="container"> <div class="column left"> <p>Anxiety was a blog series that ran in the New York Times Opinion section from January 2012 to July 2013. It featured essays, fiction, and art by a wide range of contributors that explored anxiety from scientific, literary, and artistic perspectives.</p> </div> <div class="column center"> <img src="http://i.imgur.com/60PVLis.png" width="100" height="100" alt=""> </div> <div class="column right"> Balint Zsako <br/> Someone’s Knocking at My Door <br/> 01.12.13 </div></div> Here's a JSFiddle: http://jsfiddle.net/zDd2g/185/
Now provide the response and nothing else.
|
Instead of using width (which is a suggestion when using flexbox), you could use flex: 0 0 230px; which means: 0 = don't grow (shorthand for flex-grow ) 0 = don't shrink (shorthand for flex-shrink ) 230px = start at 230px (shorthand for flex-basis ) which means: always be 230px . See fiddle , thanks @TylerH Oh, and you don't need the justify-content and align-items here. img { max-width: 100%;}#container { display: flex; x-justify-content: space-around; x-align-items: stretch; max-width: 1200px;}.column.left { width: 230px; flex: 0 0 230px;}.column.right { width: 230px; flex: 0 0 230px; border-left: 1px solid #eee;}.column.center { border-left: 1px solid #eee;}
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/23794713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/287436/']}
|
jdg_378504
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10851445
|
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 split a string by a list of indices, where the split segments begin with one index and end before the next one. Example: s = 'long string that I want to split up'indices = [0,5,12,17]parts = [s[index:] for index in indices]for part in parts: print part This will return: long string that I want to split up string that I want to split up that I want to split up I want to split up I'm trying to get: long string that I want to split up
Now provide the response and nothing else.
|
s = 'long string that I want to split up'indices = [0,5,12,17]parts = [s[i:j] for i,j in zip(indices, indices[1:]+[None])] returns ['long ', 'string ', 'that ', 'I want to split up'] which you can print using: print '\n'.join(parts) Another possibility (without copying indices ) would be: s = 'long string that I want to split up'indices = [0,5,12,17]indices.append(None)parts = [s[indices[i]:indices[i+1]] for i in xrange(len(indices)-1)]
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10851445', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/165673/']}
|
jdg_378505
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
537383
|
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:
Why is ${x^{\frac{1}{2}}}$ the same as $\sqrt x $? I'm currently studying indices/exponents, and this is a law that I was told to accept without much proof or explanation, could someone explain the reasoning behind this. Thank you.
Now provide the response and nothing else.
|
When $m$ and $n$ are integers, we have the important law that $$x^m\cdot x^n =x^{m+n}$$ We'd like this law to continue to hold when we define $x^\alpha$ for fractional $\alpha$, unless there's a good reason it shouldn't. If we do want it to continue to hold for fractional exponents, then whatever we decide that $x^{1/2}$ should mean, it should obey the same law: $$x^{1/2}\cdot x^{1/2} = x^{1/2+1/2} = x^1 = x$$ and so $x^{1/2} = \sqrt x$ is the only choice. Similarly, what should $x^0$ mean? If we want the law to continue to hold, we need $$x^0\cdot x^n = x^{0+n} = x^n$$ and thus the only consistent choice is $x^0 = 1$. And again, why does $x^{-1} = \frac1x$? Because that's again the only choice that preserves the multiplication law, since we need $x^{-1}\cdot x^{1} = x^{-1+1} = x^0 = 1$. But there is more to it than that. Further mathematical developments, which you may not have seen yet, confirm these choices. For example, one shows in analysis that as one adds more and more terms of the infinite sum $$1 + x + \frac{x^2}2 + \frac{x^3}6 + \frac{x^4}{24} + \cdots$$ the sum more and more closely approaches the value $e^x$, where $e$ is a certain important constant, approximately $2.71828$. One can easily check numerically that this holds for various integer values of $x$. For example, when $x=1$, and taking only the first five terms, we get $$1 + 1 + \frac12 + \frac16 + \frac1{24}$$ which is already $2.708$, quite close to $e^1$, and the remaining terms make up the difference. One can calculate $e^2$ by this method and also by straightforward multiplication of $2.71828\cdot2.71828$ and get the same answer. But we can see just by inspection that taking $x=0$ in this formula gives $e^0 = 1$ because all the terms vanish except the first. And similarly, if we put in $x=\frac12$ we get approximately $1.648$, which is in fact the value of $\sqrt e$. If it didn't work out this way, we would suspect that something was wrong somewhere. And in fact it has often happened that mathematicians have tried defining something one way, and then later developments revealed that the definition was not the right one, and it had to be revised. Here, though, that did not happen.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/537383', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/45635/']}
|
jdg_378506
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
862970
|
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 table in Sql Server 2008 Express which contains 18 million records.The structure looks something like this (simplified): Id, GroupId, Value, Created Id is the primary key with a clustered index GroupId is a non-clustered index In this case, every 10 rows get a new groupId meaning that records 1-10 have GroupId 1, records 11-20 have GroupId 2 and so on. Test 1: This query takes 23 seconds to run and returns 99 records: DECLARE @Start INT SET @Start = 1050 select * from FieldValues where GroupId between @Start and @Start + 10 Test 2: This query takes 0 seconds to run and returns 99 records: DECLARE @Start INT SET @Start = 1050 select * from FieldValues where GroupId = @Start union select * from FieldValues where GroupId = @Start + 1 union select * from FieldValues where GroupId = @Start + 2 union select * from FieldValues where GroupId = @Start + 3 union select * from FieldValues where GroupId = @Start + 4 union select * from FieldValues where GroupId = @Start + 5 union select * from FieldValues where GroupId = @Start + 6 union select * from FieldValues where GroupId = @Start + 7 union select * from FieldValues where GroupId = @Start + 8 union select * from FieldValues where GroupId = @Start + 9 union select * from FieldValues where GroupId = @Start + 10 Note: Since results can get cached i always scramble the @Start variable between each test to get non-cached time estimations Why does these multiple selects (which looks like some beginner have throught up) go so much faster than the more elegant one in test 1?
Now provide the response and nothing else.
|
Try using the "Show actual execution plan" in the query analyser and you will see that the second query is probably achieving the results by performing an index seek, whereas the former (slower) is not able to do this because it doesn't know that the records are sequential because the index it is using is non-clustered.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/862970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/97966/']}
|
jdg_378507
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25674
|
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:
For a scene in a SciFi book, I want to know: Is it possible to estimate how much energy per m² an object would receive that hides behind an in-system planet when the sun goes nova?
Now provide the response and nothing else.
|
Is it possible to estimate? Yes. I'll give it a quick try. But the details of whether the planet will be incinerated and so on will make the reality much more complicated. As a ballpark, I think supernovae release about $10^{53}$ erg of energy . Spread over a sphere of, say, 1 AU gives $3.55\times10^{22}$J.m$^{-2}$. This energy isn't all released in one go and I don't know how much is radiative or kinetic. If its released over, say, 20 days, that gives $2.06\times10^{16}$W.m$^{-2}$ For comparison, the Sun emits 1368 W.m$^{-2}$, or 15 trillion times less. The timescale is roughly the time it takes for observed supernova luminosities to rise to a peak but much shorter timescales might be relevant. About 1% of that energy is released in a few seconds in a neutrino burst, but they don't interact much. Also, 1 AU is pretty arbitrary. A star that undergoes core-collapse must be bigger than the Sun, so its habitable zone would be much further away. 100 AU might be just as reasonable and reduce the energy flux by a factor of 100$^2$. To estimate further, you could work out how much energy your planet would absorb based on its cross-section and compare that to its gravitational binding energy to get a rough guess about whether it would survive the blast. Hope this helps though.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/25674', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/662/']}
|
jdg_378508
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32767000
|
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 code: $g = 2e3;echo $g;echo <br>;echo "var_dump g gives:<br>"; Displays: 2000float(2000) I don't understand why it wouldn't display "8" and "float(8)"? Isn't 2 to the 3rd power equal to 8 ?? I tried looking for this question on this website already. Any help would be greatly appreciated. I did figure out that for 2e2 it displays 200. So it sounds like it just adds that many zeros to the end of the number instead of finding the 3rd power of 2. When I search for how to write exponential in php, the answers I've found said to use 'e' or 'E', but that doesn't seem to work or I've forgotten basic math. I'm sure somebody on here has a very simple answer for me. Ok so why does $g = 2^3; give me 1? How can I write 2 to the 3rd power in php?
Now provide the response and nothing else.
|
It's called scientific notation (or in this case "E notation"). 2e3 is the same as 2 x 10^3 , which is 2000 . If you want 2^3 , you can use $g = pow(2, 3); Or in PHP 5.6+: $g = 2**3; Note: You need to use pow() (or ** ) because in PHP, when you do $g = 2^3; , you are doing 2 XOR 3 .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32767000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5370253/']}
|
jdg_378509
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2809547
|
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 send HTML-emails, using Django templates like this: <html><body>hello <strong>{{username}}</strong>your account activated.<img src="mysite.com/logo.gif" /></body> I can't find anything about send_mail , and django-mailer only sends HTML templates, without dynamic data. How do I use Django's template engine to generate e-mails?
Now provide the response and nothing else.
|
From the docs , to send HTML e-mail you want to use alternative content-types, like this: from django.core.mail import EmailMultiAlternativessubject, from_email, to = 'hello', 'from@example.com', 'to@example.com'text_content = 'This is an important message.'html_content = '<p>This is an <strong>important</strong> message.</p>'msg = EmailMultiAlternatives(subject, text_content, from_email, [to])msg.attach_alternative(html_content, "text/html")msg.send() You'll probably want two templates for your e-mail - a plain text one that looks something like this, stored in your templates directory under email.txt : Hello {{ username }} - your account is activated. and an HTMLy one, stored under email.html : Hello <strong>{{ username }}</strong> - your account is activated. You can then send an e-mail using both those templates by making use of get_template , like this: from django.core.mail import EmailMultiAlternativesfrom django.template.loader import get_templatefrom django.template import Contextplaintext = get_template('email.txt')htmly = get_template('email.html')d = Context({ 'username': username })subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'text_content = plaintext.render(d)html_content = htmly.render(d)msg = EmailMultiAlternatives(subject, text_content, from_email, [to])msg.attach_alternative(html_content, "text/html")msg.send()
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/2809547', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/85107/']}
|
jdg_378510
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16512
|
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:
I am interested in what sort of metrics are there that try to give a measure of how complex a given graph is, what are the corresponding algorithms, and what is their time complexity. A short description or list of relevant paper would be great. It might help to say that I have two graphs and I want to somehow tell which one is ``more complex." I will use this metric as a heuristic, so I would like to try various metrics on empirical data. (It might help even more if I say that those graphs represent two FSMs.)
Now provide the response and nothing else.
|
You can use all sorts of properties of a graph this way; obviously how good they are for you depends on your purpose. Non-comprehensive list of graph attributes, for general undirected graphs: Compare simple graph attributes: $|V|$, $|E|$, $\frac{|E|}{|V|}$; you must decide if more or less is considered "more complex". Obviously if the graph has multiple components, you can use that, as a measure of simplicity or complexity; and/or you can consider it multiple separate graphs. Treewidth of the undirected graph; computing the treewidth of a graph is exponential-time in the treewidth, $k$; however, you can set $k$ to a constant, and compute the treewidth quickly (wrt. size of the graph) and consider graphs with higher treewidth to be "complex" How "planar" a graph is Crossing number (NP-complete problem to compute) Compare the resulting Kuratowski subgraphs when planarity testing fails (such forbidden graphs can be extracted quickly, but there can be a large number of such graphs) Presumably a higher number means that there are more non-planar crossings required, thus it is more complex. Sparseness, average vertex degree, vertex degree distribution A low average degree, with a nice distribution can indicate an evenly sparse graph, thus perhaps lower "complexity". Easy to compute, simply average the degree of each vertex over all of them; distribution is slightly more complicated I suppose; depends on how you choose to do it; see wikipedia on degree distribution . Average eccentricity (see wikipedia on Distance (graph theory) ), eccentricity distribution Diameter, radius ratios. Example: large diameter, low radius (see (see wikipedia on Distance (graph theory) ); test ratios of these on "complex" and non-"complex" graphs, see if it diffrentiates. Compare the dimensions of the graphs (NP-hard) Have some subgraphs you consider "complex", and test for subgraph isomorphism in your actual graphs (NP-complete), or, use Maximum common subgraph isomorphism (NP-hard) Perhaps some sort of compressibility/entropy measure, but this touches on isomorphism; the same graph can be layed-out or represented in a matrix multiple ways, not all of them equally compressible. A canonical graph labeling could help with this, but that is itself difficult. Some ideas for an FSM: Size (though note that you can have equivalent FSMs of different sizes; these measurements are about the graph complexity, not necessarily FSM complexity) You can do a topological sort or level structure , and compare them that way; possible measures of complexity: depth, level-width. You can do a DFS, and detect cycles; perhaps more cycles == more complex? Counting cycles can be a hard problem (NP-hard). Perhaps you can find some relaxation for your specific graphs, for example if they are planar (I don't know that counting cycles in planar graph is any easier, but you would start searching for special cases based on what special cases you do know). There are some approximation algorithms for general cycle counting though. See Counting cycles in an undirected graph using DFS-XOR algorithm , (IEEE paywalled off); abstract: We present an algorithm for counting the number of cycles in an undirected graph. The given algorithm generates exact results but it is not guaranteed to run in a polynomial time. Afterwards, an approximated version from the algorithm guaranteed to run in a polynomial time was introduced. The obtained results was used to measure the entropy of graphs. Entropy represents robustness of the graph under analysis. An experiment is conducted to compare the results of our algorithm with the results of another algorithm based on the Donald Johnson backtracking algorithm.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/16512', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/8508/']}
|
jdg_378511
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18642225
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
UPDATE: Things I tried - see answer below for solution I installed a fresh MVC3 site and it served up the resources properly. That eliminated the machine.config settings as a problem. I then when section by section in the web.config to see if any particular changes in web.config caused the problem. When the configs were identical, the fresh site still worked and the old site was still broken. I uninstalled IIS, reinstalled IIS, and then installed apps again in an attempt to clear any settings that were lingering around. Still borked. I then used publish (instead of msi deploy) to new directory. I used the iis option to "Create Application" on new directory of exact same code that is broken. Things worked perfectly. I assumed file permissions, so I deleted offending directory and renamed new working version to old directory name. Site was still borked. This made me assume that some iis setting that is not in the machine.config or web.config is to blame. I used IIS 6 Metabase explorer (yes I used it on IIS 8 site) and saw quite a few entries that were not in the working site. After deleting one by one, I found it was the "scriptMaps" entry that was being added during our MSI install causing a problem. This was added to automatically add wildcard mappings during install. It works on IIS6, but apparently not on IIS8. We have an webforms and MVC3 application that look like one application. This is deployed in many environments (2003, 2008, Win 7) and works properly. I have just set these applications up on a new Windows Server 2012 machine and everything works except getting resource files for the MVC site. The browser gets a 500 Internal Server ErrorServer Application UnavailableThe web application you are attempting to access on this web server is currently unavailable. Please hit the "Refresh" button in your web browser to retry your request.Administrator Note: An error message detailing the cause of this specific request failure can be found in the application event log of the web server. Please review this log entry to discover what caused this error to occur. The resources are referenced in the _layout.cshtml <head> <meta http-equiv='X-UA-Compatible' content='IE=EmulateIE8' /> <title>@this.Title</title> <script type="text/javascript" src="@Url.Content("~/Scripts/2012.2.607/jquery-1.7.1.min.js")"></script> <script type="text/javascript" src="/Sentri7/scripts/jquery-p1s.banner.js"></script> <script type="text/javascript" src="/Sentri7/scripts/jquery-p1s.patientsearch.js"></script> <link type="text/css" rel="stylesheet" href="/sentri7/content/jquery-p1s.patientsearch.css"></link> <link type="text/css" rel="stylesheet" href="/sentri7/content/jquery-p1s.banner.css" /> <link type="text/css" rel="stylesheet" href="/quantifi/resources/application/css/jqueryui/jquery-ui-1.7.2.custom.css" /> <link type="text/css" rel="stylesheet" href="/quantifi/resources/application/css/styles.css" /> @(RenderSection("PageHead", required: false))</head> as well as using the telerik scriptmanager: @{ Title = "Reportable Conditions"; SelectedSubTab = SubTabIndex.Reportables; Html.Telerik().ScriptRegistrar().DefaultGroup(dg => dg .Add("~/Scripts/ReportableConditions/List.js") .Add("~/Scripts/ClientObjects/GridSettings.js")) .OnDocumentReady("bootStrapUI()");} If I try to navigate directly to the javascript file, I get the same error: http://[server]/S7D/Scripts/2012.2.607/jquery-1.7.1.min.js Some weird stuff: If I IISReset and hit the js file, it will work the first request only. Any js, css, or image requested from another (webforms) site (same app pool) on the server works fine. There is nothing in the event log related to this 500 error. I have tried adding permissions full permissions to the user that the app pool is running. I have also added file permissions to the [Machine]\IUSR. Here is my web.config <?xml version="1.0" encoding="UTF-8"?><configuration> <configSections> <sectionGroup name="telerik"> <section name="webAssets" type="Telerik.Web.Mvc.Configuration.WebAssetConfigurationSection, Telerik.Web.Mvc" requirePermission="false" /> </sectionGroup> <sectionGroup name="spring"> <section name="typeAliases" type="Spring.Context.Support.TypeAliasesSectionHandler, Spring.Core" /> <section name="context" type="Spring.Context.Support.WebContextHandler, Spring.Web" /> <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" /> </sectionGroup> <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /> <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /> </sectionGroup> </configSections> <spring> <context> <!-- Load web.config definition ** This resource reference is essential to define objects in the web.configs --> <resource uri="config://spring/objects" /> <resource uri="assembly://CAS2/CAS2.CASLibDAO/_SpringObjects.xml" /> <resource uri="file://~/App_Data/MvcApplicationContext.xml" /> <resource uri="assembly://P1S.S7D.Core/P1S.S7D.Core.ApplicationContext/ApplicationContext-Common.xml" /> <resource uri="assembly://P1S.S7D.Core/P1S.S7D.Core.ApplicationContext/ApplicationContext-DAO.xml" /> <resource uri="assembly://P1S.S7D.Core/P1S.S7D.Core.ApplicationContext/ApplicationContext.xml" /> <resource uri="assembly://P1S.S7D.Core/P1S.S7D.Core.ApplicationContext/Services.xml" /> <resource uri="assembly://P1S.S7D.Common/P1S.S7D.Common.ApplicationContext/ApplicationContext-AuthModule.xml" /> <resource uri="assembly://P1S.S7D.Common/P1S.S7D.Common.ApplicationContext/ApplicationContext-Web-Common.xml" /> <resource uri="assembly://P1S.S7D.Core/P1S.S7D.Core.ApplicationContext.WCF/ApplicationContext.xml" /> <resource uri="assembly://P1S.S7D.Core/P1S.S7D.Core.ApplicationContext/ApplicationContext-Circular-Reference-IPReporting.xml" /> </context> <objects xmlns="http://www.springframework.net"> <!--cached objects--> </objects> </spring> <system.web.webPages.razor> <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <pages pageBaseType="P1S.S7D.Web.Mvc.WebViewPage"> <namespaces> <add namespace="P1S.S7D.Web.Mvc" /> <add namespace="System.Web.Helpers" /> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="System.Web.WebPages" /> <add namespace="Telerik.Web.Mvc.UI" /> </namespaces> </pages> </system.web.webPages.razor> <appSettings> <add key="Spring.Data.NHibernate.Support.OpenSessionInViewModule.SessionFactoryObjectName" value="NHibernateSessionFactory" /> <add key="Spring.Data.NHibernate.Support.OpenSessionInViewModule.EntityInterceptorObjectName" value="MultiTenantInterceptor" /> <add key="webpages:Version" value="1.0.0.0" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings> <system.web> <sessionState allowCustomSqlDatabase="true" mode="SQLServer" sqlConnectionString="Server=dev-ct-nhsn.dev.rph.int;Database=aspstate;User ID=UID;Password=*****; Application Name=S7DSharedSession" /> <compilation debug="true" targetFramework="4.0"> <assemblies> <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> </assemblies> </compilation> <authentication mode="Forms"> <forms loginUrl="~/Account/LogOn" timeout="2880" /> </authentication> <membership> <providers> <clear /> <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" /> </providers> </membership> <profile> <providers> <clear /> <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" /> </providers> </profile> <roleManager enabled="false"> <providers> <clear /> <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" /> <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" /> </providers> </roleManager> <pages pageBaseType="P1S.S7D.Web.Mvc.WebViewPage"> <namespaces> <add namespace="P1S.S7D.Web.Mvc" /> <add namespace="System.Web.Helpers" /> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="System.Web.WebPages" /> <add namespace="Telerik.Web.Mvc.UI" /> </namespaces> <controls> <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> </controls> </pages> <httpHandlers> <add verb="GET,HEAD" path="asset.axd" validate="false" type="Telerik.Web.Mvc.WebAssetHttpHandler, Telerik.Web.Mvc" /> </httpHandlers> <httpModules> <add name="AuthenticationModule" type="Web.Handlers.AuthenticationModule,P1S.S7D.Web.Mvc" /> <add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web" /> <add name="OpenSessionInView" type="Spring.Data.NHibernate.Support.OpenSessionInViewModule, Spring.Data.NHibernate31" /> </httpModules> <customErrors mode="Off" /> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <modules runAllManagedModulesForAllRequests="true"> <add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web" /> <add name="AuthenticationModule" type="Web.Handlers.AuthenticationModule,P1S.S7D.Web.Mvc" /> <add name="OpenSessionInView" type="Spring.Data.NHibernate.Support.OpenSessionInViewModule, Spring.Data.NHibernate31" /> </modules> <!-- --> <handlers> <remove name="asset" /> <add name="asset" preCondition="integratedMode" verb="GET,HEAD" path="asset.axd" type="Telerik.Web.Mvc.WebAssetHttpHandler, Telerik.Web.Mvc" /> </handlers> </system.webServer> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" /> </dependentAssembly> </assemblyBinding> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="NHibernate" culture="neutral" publicKeyToken="aa95f207798dfdb4" /> <bindingRedirect oldVersion="3.1.0.4000" newVersion="3.3.1.4000" /> </dependentAssembly> </assemblyBinding> </runtime> <telerik> <webAssets useTelerikContentDeliveryNetwork="false" /> </telerik></configuration> All the resources, whether using Telerik or adding them with the script tag give the 500 error. The controller and view show up correctly (without styles or javascript) EDIT: Register Routes: public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); RouteTable.Routes.RouteExistingFiles = false; routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); }
Now provide the response and nothing else.
|
I was getting the same error when I published my site from local (Windows 7) to the server (Windows 2012). My Local IIS had added this code: <staticContent> <mimeMap fileExtension=".woff" mimeType="application/x-font-woff" /> <mimeMap fileExtension=".woff2" mimeType="application/x-font-woff" /></staticContent> Where as I needed this on Win 2012 <staticContent> <remove fileExtension=".woff" /> <mimeMap fileExtension=".woff" mimeType="application/x-font-woff" /> <mimeMap fileExtension=".woff2" mimeType="application/x-font-woff" /></staticContent> It seems the newer version of IIS on Win2012 already has .woff added and instead of giving me any kind of details, it just went 500!
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18642225', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989829/']}
|
jdg_378512
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
42478661
|
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 exactly is the difference between the two? I've seen people use: function foo () { ...}export default foo; And I've seen: function bar () { ...}export bar; Also, why would you use the one over the other?
Now provide the response and nothing else.
|
It's easiest to just look at what the three different ES6 import/export styles compile down to in CommonJS. // Three different export stylesexport foo;export default foo;export = foo;// The three matching import stylesimport {foo} from 'blah';import foo from 'blah';import * as foo from 'blah'; Roughly compiles to: exports.foo = foo;exports['default'] = foo;module.exports = foo;var foo = require('blah').foo;var foo = require('blah')['default'];var foo = require('blah'); (Actual compiler output may differ)
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/42478661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_378513
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50805
|
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:
My circuit has 5v and 3.3v supplies. They share a ground. A component that uses the 3.3v supply says it needs a .01uF bypass capacitor across its power and ground pins. Questions: Does it have to literally be on the pins, or can the capacitor be on any wire connected directly to those pins? Is there any issue with the ground being shared between the two power supplies with respect to the cap, which is only connected to the +3.3v supply?
Now provide the response and nothing else.
|
The capacitor doesn't have to be literally on the pins, but should be (as everyone has indicated) as close to the IC as possible. As for the 3.3V vs 5V: You want to use a capacitor that has a voltage rating above that which it will routinely operate at, to handle the occasional spike. Most small through-hole ceramic capacitors will be rated at 25, 50, 100V or more, so you should have no problems using a given bypass capacitor on either your 5V or 3.3V supply. (Be aware that surface mount ceramic capacitors voltage ratings can be much lower, 6.3, 10, etc.) For more information about bypass capacitors, there's a good article at Seattle Robotics .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/50805', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/11947/']}
|
jdg_378514
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6406957
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Since when using sql lite if you try and do a function at the same moment it throws an error, im just trying to make a function that will check if its executing, and if it is try again in 10 milliseconds, this exact function works fine if i dont have to pass any arguments to the function but im confused how I can pass the vars back into the function it'll be executing. I want to do: timer.addEventListener(TimerEvent.TIMER, saveChat(username, chatBoxText)); But it will only allow me to do: timer.addEventListener(TimerEvent.TIMER, saveChat); It gives me this compile error: 1067: Implicit coercion of a value of type void to an unrelated type Function How can I get this to pass this limitation? Here's what I've got: public function saveChat(username:String, chatBoxText:String, e:TimerEvent=null):void{ var timer:Timer = new Timer(10, 1); timer.addEventListener(TimerEvent.TIMER, saveChat); if(!saveChatSql.executing) { saveChatSql.text = "UPDATE active_chats SET convo = '"+chatBoxText+"' WHERE username = '"+username+"';"; saveChatSql.execute(); } else timer.start();}
Now provide the response and nothing else.
|
A function called by a listener can only have one argument, which is the event triggering it. listener:Function — The listener function that processes the event. This function must accept an Event object as its only parameter and must return nothing, as this example shows: function(evt:Event):void Source You can get around this by having the function called by the event call another function with the required arguments: timer.addEventListener(TimerEvent.TIMER, _saveChat);function _saveChat(e:TimerEvent):void{ saveChat(arg, arg, arg);}function saveChat(arg1:type, arg2:type, arg3:type):void{ // Your logic.} Another thing you can do create a custom event class that extends flash.events.Event and create properties that you need within. package{ import flash.events.Event; public class CustomEvent extends Event { // Your custom event 'types'. public static const SAVE_CHAT:String = "saveChat"; // Your custom properties. public var username:String; public var chatBoxText:String; // Constructor. public function CustomEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false):void { super(type, bubbles, cancelable); } }} Then you can dispatch this with properties defined: timer.addEventListener(TimerEvent.TIMER, _saveChat);function _saveChat(e:TimerEvent):void{ var evt:CustomEvent = new CustomEvent(CustomEvent.SAVE_CHAT); evt.username = "Marty"; evt.chatBoxText = "Custom events are easy."; dispatchEvent(evt);} And listen for it: addEventListener(CustomEvent.SAVE_CHAT, saveChat);function saveChat(e:CustomEvent):void{ trace(e.username + ": " + e.chatBoxText); // Output: Marty: Custom events are easy.}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6406957', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/393373/']}
|
jdg_378515
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23521230
|
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 "flatten" (not in the classical sense of .flatten ) down a hash with varying levels of depth, like this: { :foo => "bar", :hello => { :world => "Hello World", :bro => "What's up dude?", }, :a => { :b => { :c => "d" } }} down into a hash with one single level, and all the nested keys merged into one string, so it would become this: { :foo => "bar", :"hello.world" => "Hello World", :"hello.bro" => "What's up dude?", :"a.b.c" => "d"} but I can't think of a good way to do it. It's a bit like the deep_ helper functions that Rails adds to Hashes, but not quite the same. I know recursion would be the way to go here, but I've never written a recursive function in Ruby.
Now provide the response and nothing else.
|
You could do this: def flatten_hash(hash) hash.each_with_object({}) do |(k, v), h| if v.is_a? Hash flatten_hash(v).map do |h_k, h_v| h["#{k}.#{h_k}".to_sym] = h_v end else h[k] = v end endendflatten_hash(:foo => "bar", :hello => { :world => "Hello World", :bro => "What's up dude?", }, :a => { :b => { :c => "d" } })# => {:foo=>"bar", # => :"hello.world"=>"Hello World", # => :"hello.bro"=>"What's up dude?", # => :"a.b.c"=>"d"}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/23521230', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3090225/']}
|
jdg_378516
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
36246999
|
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 know that in SQL I can use the 'String_agg(Test1, ',')' function for grouping rows and concatenate values in a selected field ('Test1' in this case). For Example: I have a query that the result without using String_agg on 'Buyer' field is: **Key** | **Buyer** | **MP**1 | Josh | Gregory1 | Bred | Gregory2 | John | Ethan The expected results when using String_agg is: **Key** | **Buyer** | **MP**1 | Josh, Bred | Gregory2 | John | Ethan But the problem is that I'm trying to execute it in SQL query which retrieves data to Excel file from another Excel file and it fails because of an error that seems like the Excel query doesn't know the String_agg function. The query is: SELECT `Sheet1$`.Key, string_agg(`Sheet1$`.Buyer, `, `) AS `Buyer`, `Sheet1$`.MPFROM `C:\Input\Data.xls`.`Sheet1$` `Sheet1$`GROUP BY 2ORDER BY `Sheet1$`.Key Screenshot: Query screenshot Error: Error Screenshot Someone can help me and tell me how should I correct my query to make it works? Thank you!
Now provide the response and nothing else.
|
It's not clear why you have a List<DataCarName> in first place instead of a List/Set<String> . The predicate you have to provide must check if for the corresponding data car instance, there's its name in the list. e -> e.getName().contains("BMW") will only check if the name of the data car contains BMW which is not what you want. Your first attempt then may be e -> listCarName.contains(e.getName()) but since listCarName is a List<DataCarName> and e.getName() a string (I presume), you'll get an empty list as a result. The first option you have is to change the predicate so that you get a stream from the list of data car names, map them to their string representation and check that any of these names corresponds to the current data car instance's name you are currently filtering: List<DataCar> listOutput = listCar.stream() .filter(e -> listCarName.stream().map(DataCarName::getName).anyMatch(name -> name.equals(e.getName()))) .collect(Collectors.toList()); Now this is very expensive because you create a stream for each instance in the data car stream pipeline. A better way would be to build a Set<String> with the cars' name upfront and then simply use contains as a predicate on this set: Set<String> carNames = listCarName.stream() .map(DataCarName::getName) .collect(Collectors.toSet());List<DataCar> listOutput = listCar.stream() .filter(e -> carNames.contains(e.getName())) .collect(Collectors.toList());
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/36246999', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3613778/']}
|
jdg_378517
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9153718
|
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 a way to change an attribute of a CSS class using javascript? <style type="text/css"> .fool select { display: block; }</style><p class="fool"> <select id="a" onchange="changeCSS()"> ... </select> <select id="b" > ... </select> <select id="c" > ... </select></p> I want to change display:block to display:none for ALL <select> elements after a user call function changeCSS(). It looks simple but I can't find a way to do this...
Now provide the response and nothing else.
|
The key is to define extra rules for additional classes and add these classes to the elements rather than to rewrite the rules for a given style rule. JS function changeCSS() { var selects = document.getElementsByTagName("select"); for(var i =0, il = selects.length;i<il;i++){ selects[i].className += " hidden"; }} CSS .fool select.hidden, select.hidden { display: none;} Or for a really efficient method (but which might need a few more specific style rules too) JS function changeCSS() { document.getElementsByTagName("body")[0].className += " hideAllSelects"} CSS body.hideAllSelects select { display: none;}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9153718', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/755424/']}
|
jdg_378518
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48008832
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Typically in my .ts files I can access the window object by calling something such as: (<any>window).myObject I am getting compilation errors for this in my .tsx files. Is there any way I can access it from a .tsx file? Thanks.
Now provide the response and nothing else.
|
You can use the as syntax for type assertion. This is the alternate syntax for type assertion as <type>obj conflicts with JSX syntax: (window as any).myObject The above will work, however if you want strong typing consider augmenting the Window interface to add your property so you will get compile-time type checking: declare global { interface Window { myObject: YourObjectType; }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48008832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5698929/']}
|
jdg_378519
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
293495
|
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 am making the check for update script for my theme I have 2 text files. First one is called "current.txt" and contains the current version. There is 4.1.1 string in that text file. Second one is called "latest.txt" and contains the latest version. There is 4.2 string in this text file. So here is the code echo "Checking update";x=$(cat ./current.txt)y=$(cat ./latest.txt)if [ "$x" -eq "$y" ]then echo There is version $y updateelse echo Version $x is the latest versionfi What it mean is if current.txt is NOT the same with latest.txt then it will say "there is version 4.2 update". If not, it will say "version 4.1.1 is the latest version" But when I try to run it. I get this error Checking update./test.sh: line 4: [: 4.1.1: integer expression expectedVersion 4.1.1 is the latest version So what am I doing wrong with this?
Now provide the response and nothing else.
|
The test command, also named [ , has separate operators for string comparisons and integer comparisons: INTEGER1 -eq INTEGER2 INTEGER1 is equal to INTEGER2 vs STRING1 = STRING2 the strings are equal and STRING1 != STRING2 the strings are not equal Since your data is not strictly an integer, your test needs to use the string comparison operator. The last realization in the comments was that the "-eq" logic did not match the sense of the if/else echo statements, so the new snippet should be: ...if [ "$x" != "$y" ]then echo There is version $y updateelse echo Version $x is the latest versionfi
|
{}
|
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/293495', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/177727/']}
|
jdg_378520
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
134227
|
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 have two lists: list={{1,2,3,5},{5,3,9,11,12},{5,9,10,16}};list2={{7,89},{96,5},{-6,-98}}; This is the expected result. {{1->{7,89},2->{7,89},3->{7,89},5->{7,89}}, {5->{96,5},3->{96,5},9->{96,5},11->{96,5},12->{96,5}}, {5->{-6,-98},9->{-6,-98},10->{-6,-98},16->{-6,-98}}} This is my current try. Thread /@ Thread[Rule[list, MapIndexed[ConstantArray[list2[[First[#2]]], Length[#1]] &, list]]]
Now provide the response and nothing else.
|
Tuples /@ Thread[list -> List /@ list2] { {1 -> {7, 89}, 2 -> {7, 89}, 3 -> {7, 89}, 5 -> {7, 89}}, {5 -> {96, 5}, 3 -> {96, 5}, 9 -> {96, 5}, 11 -> {96, 5}, 12 -> {96, 5}}, {5 -> {-6, -98}, 9 -> {-6, -98}, 10 -> {-6, -98}, 16 -> {-6, -98}}}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/134227', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/21532/']}
|
jdg_378521
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7942586
|
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 some code like this. Should the break occur before the periods or after? # beforemy_var = somethinglikethis.where(we=do_things).where(we=domore).where(we=everdomore)# this waymy_var = somethinglikethis.where(we=do_things) \ .where(we=domore) \ .where(we=everdomore)# or this waymy_var = somethinglikethis.where(we=do_things). \ where(we=domore). \ where(we=everdomore)
Now provide the response and nothing else.
|
PEP 8 recommends using parenthesis so that you don't need \ , and gently suggests breaking before binary operators instead of after them. Thus, the preferred way of formatting you code is like this: my_var = (somethinglikethis .where(we=do_things) .where(we=domore) .where(we=everdomore)) The two relevant passages are this one from the Maximum Line Length section: The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. ... and the entire Should a line break before or after a binary operator? section: Should a line break before or after a binary operator? For decades the recommended style was to break after binary operators.But this can hurt readability in two ways: the operators tend to getscattered across different columns on the screen, and each operator ismoved away from its operand and onto the previous line. Here, the eyehas to do extra work to tell which items are added and which aresubtracted: # No: operators sit far away from their operandsincome = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest) To solve this readability problem, mathematicians and their publishersfollow the opposite convention. Donald Knuth explains the traditionalrule in his Computers and Typesetting series: "Although formulaswithin a paragraph always break after binary operations and relations,displayed formulas always break before binary operations" Following the tradition from mathematics usually results in morereadable code: # Yes: easy to match operators with operandsincome = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest) In Python code, it is permissible to break before or after a binaryoperator, as long as the convention is consistent locally. For newcode Knuth's style is suggested. Note that, as indicated in the quote above, PEP 8 used to give the opposite advice about where to break around an operator, quoted below for posterity: The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it. Some examples: class Rectangle(Blob): def __init__(self, width, height, color='black', emphasis=None, highlight=0): if (width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight > 100): raise ValueError("sorry, you lose") if width == 0 and height == 0 and (color == 'red' or emphasis is None): raise ValueError("I don't think so -- values are %s, %s" % (width, height)) Blob.__init__(self, width, height, color, emphasis, highlight)
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7942586', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/305633/']}
|
jdg_378522
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9674411
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Please take a look at following code: public class SomeEntity{ public int Id { get; set; } public int UserId { get; set; } public virtual User User { get; set; }}public class SomeEntityA : SomeEntity{ public int Number { get; set; }}public class SomeEntityB : SomeEntity{ public string Text { get; set; }}public class User{ public int Id { get; set; } public int Username { get; set; } public virtual ICollection<SomeEntityA> SomeEntitiesA { get; set; } public virtual ICollection<SomeEntityB> SomeEntitiesB { get; set; }} My question is - is there a way to set the FluentApi to make relationships shown above work properly? Currently when new SomeEntityA object is being added to User, EF creates a new record in SomeEntities table with properly set User_Id FK, however in SomeEntitesA which is an inherited table, there's also a FK property User_Id - set as null and when I try to get SomeEntitesA collection from User object - it's empty. I do realize why that happens, but I'm not sure whether there's a way to fix this? The only solution that comes to my mind at this moment is to replace following code: public virtual ICollection<SomeEntityA> SomeEntitiesA { get; set; } public virtual ICollection<SomeEntityB> SomeEntitiesB { get; set; } with: public virtual ICollection<SomeEntity> SomeEntitiesA { get; set; } public virtual ICollection<SomeEntity> SomeEntitiesB { get; set; } and configure FluentApi. Any thoughts would be highly appreciated.
Now provide the response and nothing else.
|
Use the JoinColumn annotation on your ManyToOne relation: /** * @ORM\ManyToOne(targetEntity="Package", inversedBy="users") * @ORM\JoinColumn(name="package_id", referencedColumnName="id", nullable=false) */private $package; The ManyToOne itself cannot be nullable, because it doesn't relate to a specific column. The JoinColumn on the other hand identifies the column in the database. Thus, you can use "normal" attributes like nullable or unique!
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/9674411', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/689249/']}
|
jdg_378523
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
34407468
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
According to this page by some user named "w3c" the default namespace for HTML is: http://www.w3.org/1999/xhtml He's obviously wrong since xhtml was used for a failed XML based HTML4 standard. What is the correct namespace I should use? Background: I'm writing an app that uses XML. I want to be able to save data on the XML node using namespaces. For example, <s:Button width="100" height="100" html:color="blue" color="black" /> The XML parser needs a namespace for the "html" prefix to be valid.
Now provide the response and nothing else.
|
As documented by the W3C, who are the body behind both the XML and HTML specifications (WHATWG has a separate HTML 5 spec, but while it in some ways out of sync with the W3C spec, WHATWG does still consider it the W3C's role to bring standardise a spec as a REC), the namespace for HTML when used with an XML serialisation (which is sometimes refered to as XHTML) is http://www.w3.org/1999/xhtml . This namespace covers all versions of HTML with such XML serialisations that have been specified so far including XHTML 1.0 and 1.1 which were in considerable use for over a decade, XHTML 2.0 which introduced several modular ideas but which was arguably of more import as an incubator for several ideas than as an implemented version, and "HTML5 serialized as XML" which is sometimes called XHTML5. Since the other body with a horse in the race as to just how HTML 5 is specified is WHATWG, you may note that they also say that if you are serialising HTML5 as XML then you must use the namespace http://www.w3.org/1999/xhtml and with the other serialisation either not use a namespace, or use that one. Per https://wiki.whatwg.org/wiki/FAQ#What_is_the_namespace_declaration.3F : In XHTML, you are required to specify the namespace. <html xmlns="http://www.w3.org/1999/xhtml"> In HTML, the xmlns attribute is currently allowed on any HTML element, but only if it has the value “ http://www.w3.org/1999/xhtml “. It doesn’t do anything at all, it is merely allowed to ease migration from XHTML1. It is not actually a namespace declaration in HTML, because HTML doesn’t yet support namespaces. See the question will there be support for namespaces in HTML. The next FAQ is also relevant here: HTML is being defined in terms of the DOM and during parsing of a text/html all HTML elements will be automatically put in the HTML namespace, http://www.w3.org/1999/xhtml . However, unlike the XHTML serialization, there is no real namespace syntax available in the HTML serialization (see previous question). In other words, you do not need to declare the namespace in your HTML markup, as you do in XHTML. However, you are permitted to put an xmlns attribute on each HTML element as long as the namespace is http://www.w3.org/1999/xhtml . In addition, the HTML syntax provides for a way to embed elements from MathML and SVG. Elements placed inside the container element math or svg will automatically be put in the MathML namespace or the SVG namespace, respectively, by the parser. Namespace syntax is not required, but again an xmlns attribute is allowed if its value is the right namespace. In conclusion, while HTML does not allow the XML namespace syntax, there is a way to embed MathML and SVG and the xmlns attribute can be used on any element under the given constraints, in a way that is reasonably compatible on the DOM level.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34407468', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/441016/']}
|
jdg_378524
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
158410
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm curious about why we always find mle using the first (partial) derivative without checking the end points or singular point or the second (partial) derivative? Thx a lot!
Now provide the response and nothing else.
|
It's not a stupid question at all. See this post for a case where a likelihood can have two maxima and a minimum. When dealing with maximum likelihood in a general theoretical approach, we tend to silently assume that the likelihood is a unimodal function (usually having a maximum). Moreover, many "known" distributions have log-concave densities (in their variable). This, coupled with the fact that the unknown coefficients have in many cases a linear relationship with the variable (or we can make it linear through a one-to-one parametrization, which leaves the MLE unaffected), makes the density log-concave in the unknown coefficients also... which are the arguments with respect to which we maximize the (by now, concave) log-likelihood. Satisfaction of the second-order conditions follows, in such cases. But in more specific theoretical works, where novel log-likelihoods arise, the researcher has in my opinion the responsibility to treat specifically the issue of whether the second-order conditions are satisfied or not. Finally, in applied work, the software algorithms check on their own whether the Hessian is negative definite at the point that they locate as stationary, (and report on the matter) so at least we know whether we have a local maximum or not.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/158410', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/48417/']}
|
jdg_378525
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5876424
|
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 of object literals like this: var myArr = [];myArr[0] = { 'score': 4, 'name': 'foo'}myArr[1] = { 'score': 1, 'name': 'bar'}myArr[2] = { 'score': 3, 'name': 'foobar'} How would I sort the array so it ascends by the 'score' parameter such that it would change to: myArr[0] = { 'score': 1, 'name': 'bar'}myArr[1] = { 'score': 3, 'name': 'foobar'}myArr[2] = { 'score': 4, 'name': 'foo'} Thanks in advance.
Now provide the response and nothing else.
|
Try myArr.sort(function (a, b) {return a.score - b.score}); The way the array elements are sorted depends on what number the function passed in returns: < 0 (negative number): a goes ahead of b > 0 (positive number): b goes ahead of a 0 : In this cases the two numbers will be adjacent in the sorted list. However, the sort is not guaranteed to be stable: the order of a and b relative to each other may change.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5876424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684730/']}
|
jdg_378526
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7480608
|
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 tried to mask the characters in a creditcard number string using character 'X'.I wrote two functions as below .The second function uses commons.lang.StringUtils class .I tried to find the time it takes in both cases public static String maskCCNumber(String ccnum){ long starttime = System.currentTimeMillis(); int total = ccnum.length(); int startlen=4,endlen = 4; int masklen = total-(startlen + endlen) ; StringBuffer maskedbuf = new StringBuffer(ccnum.substring(0,startlen)); for(int i=0;i<masklen;i++) { maskedbuf.append('X'); } maskedbuf.append(ccnum.substring(startlen+masklen, total)); String masked = maskedbuf.toString(); long endtime = System.currentTimeMillis(); System.out.println("maskCCNumber:="+masked+" of :"+masked.length()+" size"); System.out.println("using StringBuffer="+ (endtime-starttime)+" millis"); return masked; } public static String maskCCNumberCommons(String ccnum){ long starttime = System.currentTimeMillis(); int total = ccnum.length(); int startlen=4,endlen = 4; int masklen = total-(startlen + endlen) ; String start = ccnum.substring(0,startlen); String end = ccnum.substring(startlen+masklen, total); String padded = StringUtils.rightPad(start, startlen+masklen,'X'); String masked = padded.concat(end); long endtime = System.currentTimeMillis(); System.out.println("maskCCNumber:="+masked+" of :"+masked.length()+" size"); System.out.println("using Stringutils="+(endtime-starttime)+" millis"); return masked; }public static void ccNumberMaskingDemo() { String mcard1="5555555555554444"; maskCCNumber(mcard1); maskCCNumberCommons(mcard1);} When I ran this ,I got this result maskCCNumber:=5555XXXXXXXX4444 of :16 sizeusing StringBuffer=0 millismaskCCNumber:=5555XXXXXXXX4444 of :16 sizeusing Stringutils=25 millis I can't understand why commons.StringUtils is taking more time than the for loop+StringBuffer in the first function.Obviously I am using the api ,the wrong way.. Can someone advise how to use this api correctly, in this case?
Now provide the response and nothing else.
|
Here you go. Clean and reusable: /** * Applies the specified mask to the card number. * * @param cardNumber The card number in plain format * @param mask The number mask pattern. Use # to include a digit from the * card number at that position, use x to skip the digit at that position * * @return The masked card number */public static String maskCardNumber(String cardNumber, String mask) { // format the number int index = 0; StringBuilder maskedNumber = new StringBuilder(); for (int i = 0; i < mask.length(); i++) { char c = mask.charAt(i); if (c == '#') { maskedNumber.append(cardNumber.charAt(index)); index++; } else if (c == 'x') { maskedNumber.append(c); index++; } else { maskedNumber.append(c); } } // return the masked number return maskedNumber.toString();} Sample Calls: System.out.println(maskCardNumber("1234123412341234", "xxxx-xxxx-xxxx-####"));> xxxx-xxxx-xxxx-1234System.out.println(maskCardNumber("1234123412341234", "##xx-xxxx-xxxx-xx##"));> 12xx-xxxx-xxxx-xx34 Good luck.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7480608', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/855171/']}
|
jdg_378527
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1932384
|
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:
In ${RP}^3\times {RP}^3$, $d(e^3\times e^3)$=0, since $d(e^3)$=0. So in this sense, $H_6({RP}^3\times {RP}^3)$ should be $Z$, however, by Kunneth Formula, we can get it should be in the form of ⊕ $(Tor(H_k(RP^m), H_{i−k−1}(RP^3)))$, which should be the product of $Z_2$. Where did I go wrong?
Now provide the response and nothing else.
|
If the problem is about an equality of the determinant, all you have to do is compute the determinants separately. The determinant of the $3\times 3$ matrix is$$(2)(0)(6) + (-1)(5)(4) + (4)(3)(1) - (4)(0)(4) - (1)(5)(2) - (6)(3)(-1) = 0 - 20 + 12 - 0 - 10 + 18 = 0.$$The $2\times 2$ determinant is just $x^{2} - 20$. Then, we arrive at the equation$$0 = x^{2} - 20$$which has two possible solutions: $x=\sqrt{20}$ or $x=-\sqrt{20}$. Thus, the answer is (D) if the question refers to determinants. If not, then there is no solution.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1932384', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/370235/']}
|
jdg_378528
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3172032
|
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:
Is it true that every sufficiently large integer can be written in the form $$2^a3^b5^c+2^d3^e5^f$$ for some integer $a,b,c,d,e,f \ge 0$ ?
Now provide the response and nothing else.
|
No, this is not the case. The number of such possible sums $\le N$ for large $N$ is far less than $N$ . The number of powers of $2$ (or of $3$ or $5$ ) up to $N$ is $O(\log N)$ . Hence the number of products $2^a 3^b 5^c$ up to $N$ is $O((\log N)^3)$ . The number of sums of pairs of such products is $O((\log N)^6)$ , which is $o(N)$ .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3172032', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/45736/']}
|
jdg_378529
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11208890
|
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 typedef std::string OrderID; I would like to overload the operator ++ for this. The value of OrderID starts out at 1 and is just incremented using hex every time. Possible values are... 001 002 ... 00A 00B ... 00F 010 ... 1) Can you overload operators for specific type defines, so that std::string++ is not overloaded? 2) Can you increment like above (using Hex)? Thanks
Now provide the response and nothing else.
|
In mid 2014 AWS introduced 'lifecycle hooks' which allows for full control of the termination process. Our high level down scale process is: Auto Scaling sends a message to a SQS queue with an instance ID Controller app picks up the message Controller app issues a 'stop instance' request Controller app re-queues the SQS message while the instance is stopping Controller app picks up the message again, checks if the instance has stopped (or re-queues the message to try again later) Controller app notifies Auto Scaling to 'PROCEED' with the termination Controller app deletes the message from the SQS queue More details: http://docs.aws.amazon.com/autoscaling/latest/userguide/lifecycle-hooks.html
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11208890', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1143465/']}
|
jdg_378530
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28178
|
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
There are a number of large trend-following CTAs that have been successfully running for 10+ years. Their main instrument is diversified futures. Why not ETFs (is it due to liquidity / scaling, costs , risk)?
Now provide the response and nothing else.
|
Leverage: futures usually require much lower margin than their ETF counterparts. For example /ES (E-mini S&P 500 futures) requires about \$4K overnight maintenance margin per contract (may vary by brokerage) to control 50 times the S&P 500 index (currently valued at about \$108K). This is over 20:1 leverage. Furthermore you do NOT pay interest on your short positions. Tax Benefits: in United States the futures contracts typically qualify for the so called Section 1256 Contracts and have special tax treatment. You may be able to significantly reduce your tax liability on realized short-term gains compared to ETF. Commissions: in general commissions are lower with futures contracts.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://quant.stackexchange.com/questions/28178', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/11655/']}
|
jdg_378531
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
54114
|
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:
Referring to Lang's Algebra p. 46, given an abelian group $G$ of exponent $m$, the dual group is defined to be $Hom(G,Z_m)$ and is denoted by $G^{\wedge}$. This is were it does not feel right: every multiple of $m$ is an exponent as well and so we could have defined $G^{\wedge}$ as $Hom(G,Z_{km})$ for any integer $k>1$. Does this not mean that this definition is not well-posed? On the contrary if we were to restrict $m$ to be the smallest exponent of $G$, then we have a unique dual group $G^{\wedge}$. Any insights?
Now provide the response and nothing else.
|
Let $m$ be the smallest exponent of $G$ (or if you're not Lang the exponent of $G$). Then every element of $G$ has order dividing $m.$ The same is true of image of $G$ under a homomorphism. Therefore, under any homomorphism of $G$ into a $\mathbb{Z}/km,$ it must be the case that the image of $G$ lies in the unique subgroup of $\mathbb{Z}/km$ of order $m.$ Consequently, $$Hom(G,\mathbb{Z}/km) = Hom(G,\mathbb{Z}/m)$$ and there is no problem with a wellposedness. Observing this, we can make a definition for the dual group that does not mention the exponent of the group. Definition : Given a finite Abelian group $G,$ the dual group $G^{\wedge}$ is the group of homomorphisms from $G$ into the colimit of the diagram of all finite cyclic groups i.e. $$G^{\wedge} := Hom(G,\mathbb{Q}/\mathbb{Z})$$ One easily checks that this definition coincides with the one given by Lang.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/54114', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11921/']}
|
jdg_378532
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1905237
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Where in memory is vtable stored?
Now provide the response and nothing else.
|
Depends on compiler. In VC++, the vtable pointer stored at the beginning of the object allocation, before any member data. (Provided your class has at least one virtual member function.) There also may be multiple vtable pointers, if your class multiply-inherits from other classes with vtables. The vtables themselves are statically allocated somewhere in your address space. Then the object layout looks like (for an instance of C): A's VTable ptrA's member variables.B's Vtable ptrB's member variables.C's member variables. for the heirarchy class A { virtual Ax() {} int a, b;};class B { virtual Bx() {} int c, d;};class C : public A, public B { int foo, bar;};
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1905237', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/228492/']}
|
jdg_378533
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1333428
|
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 can form a mental image of sets with structures like metrics or norms. But if I try to picture a topology/ topological space I fail every time. The information provided in Wikipedia confuses me quite a bit since the concept of topology is new to me. So, is there a (preferably simple) explanation of a topology placed on a set? And how should someone picture such topologies/ topological spaces?
Now provide the response and nothing else.
|
If you start with a metric space $X$, then you define the open sets in $X$ to be those $U\subseteq X$ satisfying that for all $x\in U$ there exists $\varepsilon >0 $ such that $B_\varepsilon (x)\subseteq U$. The reason we are interested in open sets (and their complements, known as closed sets) is due to various elementary theorems of metric spaces which I assume you've seen (otherwise I will just say that the open sets allow to precisely capture the notion of continuity). It is quite easy to prove that the open sets in a metric space are closed under finite intersections and under arbitrary unions. Now, by analysing proofs one discovers that some of the theorems we like can actually be stated in terms of open/closed sets only, and the proof can be obtained only by using the properties of open sets mentioned above. That means that if one is in a situation that you start with a metric space, note what the open sets are, and then suffer from amnesia whereby you totally forget what the metric was, you can still do quite a lot with the remaining 'space'. Of course, amnesia is not the reason for this, rather we realise that the metric information can be forgotten as long as one remembers the open sets, at least for some purposes (loosely speaking, those related to continuity). So at this level it's a game - there is a metric, but we pretend to only have the open sets it produces, and we see what we can still do with it. Now, we change the setting. What if there really is no metric at all, only a bunch of subsets which are closed under finite intersections and arbitrary unions? Well, then this is a topology and the resulting thing is a topological space, which you can think of as the result of forgetting some metric that led to these open sets. This turns out to be extremely useful. Now here is the nice thing. Any topological space is in fact coming from a metric, if one slightly generalises what metric means. The details of this is in Flagg's paper "Quantales and continuity spaces". The bottom line then is that any topology arises as the collection of open sets for some $V$-valued metric space. So you can really think of a topology as the result of temporary amnesia, forgetting the metric.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1333428', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/212451/']}
|
jdg_378534
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3528
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let Σ be an axiom system. Can there be a formula φ, s.t. Con(Σ) does not imply Con(Σ + φ) AND Con(Σ) does not imply Con(Σ + not φ) If yes, can you give me an example for ZFC?
Now provide the response and nothing else.
|
No, it's impossible for any axiom system. If Σ is consistent, then by the Completeness theorem, it has some model M. In M, φ is either true or false. So M is a model of either (Σ+φ) or (Σ+not φ). So at least one of them is consistent. It might be that your metatheory doesn't know which one is consistent, but it knows that at least one of them is.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/3528', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1330/']}
|
jdg_378535
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9315611
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
as a new ggplot2 user, I am a bit lost with the amount of possibilities, and struggle to find on the net a simple answer to what I consider a simple problem. I would like to display multiple plots from ggplot2 on a same sheet, BUT knowing that these plots come from a for loop. Following example does not compile, it is only to illustrate : for(i in c(1:n)){ for(j in c(1:m)){ .......... # some data production p <- ggplot(df.all) + geom_bar(aes_string(x=class.names[i],fill=var.names[j])}} Here, p is overwritten, but I would like to have instead a matrix or a list in which I can put all the p as they are produced, then a simple function like display_in_a_grid(list_of_ggplot_plots) But as far as I tried, I was not able to make a list of matrix of plot, neither to find a function that takes only one argument for input. About things I have had a look at : "arrangeGrob" from package gridExtra doesn't work because it requires an explicit name for each plot (e.g.: p1,p2,p3,...) like in http://code.google.com/p/gridextra/wiki/arrangeGrob "facet" method of ggplot2 is not adapted to the organization of my data set (or the contrary :p ) Would you have a simple way to manage this ? Thank you, François
Now provide the response and nothing else.
|
I would be inclined to agree with Richie, but if you want to arrange them yourself: library(gridExtra)library(ggplot2)p <- list()for(i in 1:4){ p[[i]] <- qplot(1:10,10:1,main=i)}do.call(grid.arrange,p) take a look at the examples at the end of ?arrangeGrob for ways to eliminate the for loop altogether: plots = lapply(1:5, function(.x) qplot(1:10,rnorm(10),main=paste("plot",.x)))require(gridExtra)do.call(grid.arrange, plots)
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9315611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1148042/']}
|
jdg_378536
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32804032
|
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 believe that an unsafe function is a function that says that it will return a value of some type, but that it can actually throw an exception and end the execution therefore not returning any value at all, but I'm not sure. Or could it be that an unsafe function is a function that can return a value of other type than the declared in the signature? Wouldn't that be a weakly typed function? Or are weakly typed and unsafe synonyms in Haskell? This may be a silly question, but I couldn't find a straightforward answer. I checked the documentation of readLn hoping to see a reference to unsafe functions, but there wasn't any. This article, Unsafe functions , says something about breaking the type system, but it doesn't specify in which manner; through exceptions?, through returning values of the wrong type? So, what is an unsafe function in Haskell?
Now provide the response and nothing else.
|
There are several notions of "unsafe" in Haskell. Calculating the value leads to I/O. The prime suspect here is unsafePerformIO . It's a bit controversial whether lazy I/O and unsafeInterleaveIO should be considered unsafe by this definition. Something breaks the type system. The prime suspect is unsafeCoerce , but unsafePerformIO can do it too. Something breaks memory safety without breaking the type system (thanks to Carl for reminding me). The prime suspects are unsafe array or vector indexing operations and incorrect use of the foreign function interface. The result of the calculation depends on the order of evaluation. The prime suspect is unsafePerformIO but unsafeInterleaveST can certainly do it too. Evaluation can lead to an exception or infinite loop. This is a relatively mild sort of unsafety ... except when it's not. Something breaks the conventions ("laws") Haskell programmers rely on to reason about their code. Whether this should be considered "unsafe" is subject to debate. Examples: applying seq to a function, using coerce in such a manner as to change the arity of a function relative to its reference implementation and cause a problem if someone applies seq to what was previously a partial application and now can possibly be bottom (there are good performance reasons to do this in some cases), writing class instances that break functor, applicative, monad, traversable, etc., laws. Expecting arguments to satisfy pre-conditions but not checking that they do (e.g., functions that quickly turn ascending lists into sets or maps). Safe Haskell To help programmers control some of these forms of unsafety, the Safe Haskell system classifies modules as safe or unsafe depending on the imports and language extensions they use. I haven't studied the details, but GarethR indicates that I think your notion 1 through 3 would be considered unsafe by Safe Haskell. It may be worth reading up on it because the Safe Haskell authors have clearly thought deeply on safety. and Ørjan Johansen indicates that Safe Haskell also disallows some things that fit in point 6, such as extensions that can circumvent module export boundaries (Template Haskell, generalized newtype deriving) or change the behavior of imported code (rules, overlapping instances). A programmer can mark a module Safe to indicate that they want GHC to check that it is safe, Unsafe to indicate that it is not safe, or Trustworthy to indicate that the author claims to believe that its API is safe to use despite the fact that its implementation uses unsafe features.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32804032', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1120410/']}
|
jdg_378537
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50688380
|
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 create symlinks for a file using ansible only when I have a certain machine hostname.I know inventory_hostname will give me the hostname, but can I do something like: when: inventory_hostname in group['machines'] so I can run this with all machines in that group?Then, I want to symlink based on name of machine. So: file: src: {{ ansible_hostname }}.png dest: anything.png
Now provide the response and nothing else.
|
You dont need the when: inventory_hostname in group['machines'] condition at all. You just have to run this task in a play towards hosts: machines , and you will have the symbolic link created to all hosts of the machines group. UPDATE if you still want to go for it, and run the playbook towards a big_group but only take action when host is part of the small_group , here is a play that can do it: hosts file: [big_group]greenhatlocalhost[small_group]localhost playbook: ---- hosts: big_group # connection: local gather_facts: false vars: tasks: - name: print if machine is eligible for symbolic debug: msg: "machine: {{ inventory_hostname }} is eligible for symbolic link!" when: inventory_hostname in groups['small_group'] result: PLAY [big_group] ****************************************************************************************************************************************************************************************************TASK [print if machine is eligible for symbolic] ********************************************************************************************************************************************************************skipping: [greenhat]ok: [localhost] => { "msg": "machine: localhost is eligible for symbolic link!"}PLAY RECAP **********************************************************************************************************************************************************************************************************greenhat : ok=0 changed=0 unreachable=0 failed=0 localhost : ok=1 changed=0 unreachable=0 failed=0 hope it helps
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50688380', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6475414/']}
|
jdg_378538
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
191796
|
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 met with the following difficulty reading the paper Li, Rong Xiu "The properties of a matrix order column" (1988) : Define the matrix $A=(a_{jk})_{n\times n}$, where $$a_{jk}=\begin{cases}j+k\cdot i&j<k\\k+j\cdot i&j>k\\2(j+k\cdot i)& j=k\end{cases}$$ and $i^2=-1$. The author says it is easy to show that $rank(A)=n$. I have proved for $n\le 5$, but I couldn't prove for general $n$. Following is an attempt to solve this problem:let$$A=P+iQ$$where$$P=\begin{bmatrix}2&1&1&\cdots&1\\1&4&2&\cdots& 2\\1&2&6&\cdots& 3\\\cdots&\cdots&\cdots&\cdots&\cdots\\1&2&3&\cdots& 2n\end{bmatrix},Q=\begin{bmatrix} 2&2&3&\cdots& n\\2&4&3&\cdots &n\\3&3&6&\cdots& n\\\cdots&\cdots&\cdots&\cdots&\cdots\\n&n&n&\cdots& 2n\end{bmatrix}$$ and define$$J=\begin{bmatrix}1&0&\cdots &0\\-1&1&\cdots& 0\\\cdots&\cdots&\cdots&\cdots\\0&\cdots&-1&1\end{bmatrix}$$then we have$$JPJ^T=J^TQJ=\begin{bmatrix}2&-2&0&0&\cdots&0\\-2&4&-3&\ddots&0&0\\0&-3&6&-4\ddots&0\\\cdots&\ddots&\ddots&\ddots&\ddots&\cdots\\0&0&\cdots&-(n-2)&2(n-1)&-(n-1)\\0&0&0&\cdots&-(n-1)&2n\end{bmatrix}$$and $$A^HA=(P-iQ)(P+iQ)=P^2+Q^2+i(PQ-QP)=\binom{P}{Q}^T\cdot\begin{bmatrix}I& iI\\-iI & I \end{bmatrix} \binom{P}{Q}$$
Now provide the response and nothing else.
|
OK, let me try again, maybe I'll get it right this time. I'll show that $P$ is positive definite. This will imply the claim because if $(P+iQ)(x+iy)=0$ with $x,y\in\mathbb R^n$, then $Px=Qy$, $Py=-Qx$, and by taking scalar products with $x$ and $y$, respectively, we see that $\langle x, Px \rangle = -\langle y, Py\rangle$, which implies that $x=y=0$. Here I use that $Q$ is symmetric. Let me now show that $P>0$. Following math110's suggestion, we can simplify my original calculation as follows: Let$B=B_n = P -\textrm{diag}(1,2,\ldots , n)$. For example, for $n=5$, this is the matrix$$ B_ 5= \begin{pmatrix} 1 & 1 & 1 & 1 & 1\\1 & 2 & 2 & 2 & 2\\1 & 2 & 3 & 3 & 3\\1 & 2 & 3 & 4 & 4\\1 & 2 & 3 & 4 & 5\end{pmatrix} .$$I can now (in general) subtract the $(n-1)$st row from the last row, then the $(n-2)$nd row from the $(n-1)$st row etc. This confirms that $\det B_n=1$. Moreover, the upper left $k\times k$ submatrices of $B_n$ are of the same type; they equal $B_k$.This shows that $B>0$, by Sylvester's criterion, and thus $P>0$ as well.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/191796', 'https://mathoverflow.net', 'https://mathoverflow.net/users/38620/']}
|
jdg_378539
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22077445
|
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 give myself permission to download existing files in an S3 bucket. I've modified the Bucket Policy, as follows: { "Sid": "someSID", "Action": "s3:*", "Effect": "Allow", "Resource": "arn:aws:s3:::bucketname/AWSLogs/123123123123/*", "Principal": { "AWS": [ "arn:aws:iam::123123123123:user/myuid" ] } } My understanding is that addition to the policy should give me full rights to "bucketname" for my account "myuid", including all files that are already in that bucket. However, I'm still getting Access Denied errors when I try to download any of those files via the link that comes up in the console. Any thoughts?
Now provide the response and nothing else.
|
David , You are right but I found that, in addition to what bennie said below, you also have to grant view (or whatever access you want) to 'Authenticated Users'. But a better solution might be to edit the user's policy to just grant access to the bucket: { "Statement": [ { "Sid": "Stmt1350703615347", "Action": [ "s3:*" ], "Effect": "Allow", "Resource": [ "arn:aws:s3:::mybucket/*" ] }, { "Effect": "Allow", "Action": [ "s3:ListBucket" ], "Resource": ["arn:aws:s3:::mybucket"], "Condition": {} } ]} The first block grants all S3 permissions to all elements within the bucket. The second block grants list permission on the bucket itself.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22077445', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/641455/']}
|
jdg_378540
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.