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
3564139
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 problem with overriding the equals method in an Enum to make it compatible with other classes.The Enum implements an interface and the idea is that all implementations of this interface can be tested for equality, regardless of their type. For Example: public interface Group { public Point[] getCoordinates();}public enum BasicGroups implements Group { a,b,c; // simplified, they actually have constructors // + fields and methods}public class OtherGroup implements Group { // fields and methods} If both a BasicGroup and an OtherGroup have the same coordinates (in arbitrary order) then the equals method should return true. No problem when performing myOtherGroup.equals(BasicGroup.a) but since the equals method in Enums is final, I can't override them. Is there some way to work around this? Like when testing on another BasicGroup the default equals method (reference equality) is used and when testing other classes my own implementation is used. And how do I make sure that java doesn't use the wrong one when I do BasicGroup.a.equals(myOtherGroup) ? Now provide the response and nothing else.
You can NOT @Override a final method ( §8.4.3.3 ); this much is clear. enum types ( §8.9 ) are treated very specially in Java, which is why the equals is final (also clone , hashCode , etc.) It's simply not possible to @Override the equals method of an enum , nor would you really want to in a more typical usage scenario. HOWEVER , looking at the big picture, it looks like you are trying to follow the pattern recommended in Effective Java 2nd Edition, Item 34: Emulate extensible enums with interfaces (see the language guide for more information about enum ): You have defined this interface (now documented explicitly for expected equals behavior): public interface Group implements Group { public Point[] getCoordinates(); /* * Compares the specified object with this Group for equality. Returns true * if and only if the specified object is also a Group with exactly the same * coordinates */ @Override public boolean equals(Object o);} It is perfectly acceptable for an interface to define how equals method for implementors should behave, of course. This is exactly the case with, e.g. List.equals . An empty LinkedList is equals to an empty ArrayList and vice versa, because that's what the interface mandates. In your case, you've chosen to implement some Group as enum . Unfortunately you now can't implement equals as per the specification, since it's final and you can't @Override it. However, since the objective is to comply to the Group type , you can use decorator pattern by having a ForwardingGroup as follows: public class ForwardingGroup implements Group { final Group delegate; public ForwardingGroup(Group delegate) { this.delegate = delegate; } @Override public Point[] getCoordinates() { return delegate.getCoordinates(); } @Override public boolean equals(Object o) { return ....; // insert your equals logic here! }} Now, instead of using your enum constants directly as Group , you wrap them in an instance of a ForwardingGroup . Now this Group object will have the desired equals behavior, as specified by the interface . That is, instead of: // before: using enum directly, equals doesn't behave as expectedGroup g = BasicGroup.A; You now have something like: // after: using decorated enum constants for proper equals behaviorGroup g = new ForwardingGroup(BasicGroup.A); Additional notes The fact that enum BasicGroups implements Group , even though it does not itself follow the specification of Group.equals , should be very clearly documented . Users must be warned that constants must be e.g. wrapped inside a ForwardingGroup for proper equals behavior. Note also that you can cache instances of ForwardingGroup , one for each enum constants. This will help reduce the number of objects created. As per Effective Java 2nd Edition, Item 1: Consider static factory methods instead of constructors , you may consider having ForwardingGroup define a static getInstance(Group g) method instead of a constructor, allowing it to return cached instances. I'm assuming that Group is an immutable type ( Effective Java 2nd Edition, Item 15: Minimize mutability ), or else you probably shouldn't implement it with enum in the first place. Given that, consider Effective Java 2nd Edition, Item 25: Prefer lists to arrays . You may choose to have getCoordinates() return a List<Point> instead of Point[] . You can use Collections.unmodifiableList (another decorator!), which will make the returned List immutable. By contrast, since arrays are mutable, you'd be forced to perform defensive copying when returning a Point[] . See also Using the decorator design pattern for a hierarchy of classes when do we need Decorator Pattern? com.google.common.collect.ForwardingObject What is the best way to cache and reuse immutable singleton objects in Java?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3564139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/426371/']}
jdg_82741
stackexchange
llm_judgeable_groundtruth_similarity
15134720
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 working Dynamic Placeholder solution in MVC.There are at least two good descriptions of this "pattern" for use with WebForms: http://trueclarity.wordpress.com/2012/06/19/dynamic-placeholder-keys-in-sitecore/ http://www.techphoria414.com/Blog/2011/August/Dynamic_Placeholder_Keys_Prototype And I also found this blog explaining how to do it with MVC: http://blogs.perficient.com/portals/2012/10/17/sitecore-mvc-dynamic-placeholders/ First I have tried to implement Techphoria's method (with GUIDs) using techniques from the MVC blogpost (extension of the SitecoreHelper) and I also tried implementing the last described method (uses number suffixes that are incremented Column_1, Column_2, etc). With all the variations I tried I didn't succeed in creating a working solution. My placeholders don't get properly named (I ended up with strange placeholder structures, or placeholders repeating themselves). Without going into the specifics of my attempts, I would like to know if anyone else has a working solution ready that I could use. If I can't find an already working solution, I will describe my problem in more detail and see if I can get that to work. Now provide the response and nothing else.
I created this extension that creates dynamic placholders public static class SitecoreHelper{ public static HtmlString DynamicPlaceholder(this Sitecore.Mvc.Helpers.SitecoreHelper helper, string dynamicKey) { var currentRenderingId = RenderingContext.Current.Rendering.UniqueId; return helper.Placeholder(string.Format("{0}_{1}", dynamicKey, currentRenderingId)); }} It creates a placeholder with the guid in the name.I also created a step in the pipeline that extracts the guid, and checks for placeholder settings. Code to get placeholder settings to the dynamic placeholder If you create a dynamic placeholder with @Html.Sitecore().DynamicPlaceholder("test") - the following code takes the setting from the placeholder settings named test /// <summary>/// Handles changing context to the references dynamic "master" renderings settings for inserting the allowed controls for the placeholder and making it editable/// </summary>public class GetDynamicKeyAllowedRenderings : GetAllowedRenderings{ //text that ends in a GUID private const string DYNAMIC_KEY_REGEX = @"(.+)_[\d\w]{8}\-([\d\w]{4}\-){3}[\d\w]{12}"; public new void Process(GetPlaceholderRenderingsArgs args) { Assert.IsNotNull(args, "args"); string placeholderKey = args.PlaceholderKey; Regex regex = new Regex(DYNAMIC_KEY_REGEX); Match match = regex.Match(placeholderKey); if (match.Success && match.Groups.Count > 0) { placeholderKey = match.Groups[1].Value; } else { return; } // Same as Sitecore.Pipelines.GetPlaceholderRenderings.GetAllowedRenderings but with fake placeholderKey Item placeholderItem = null; if (ID.IsNullOrEmpty(args.DeviceId)) { placeholderItem = Client.Page.GetPlaceholderItem(placeholderKey, args.ContentDatabase, args.LayoutDefinition); } else { using (new DeviceSwitcher(args.DeviceId, args.ContentDatabase)) { placeholderItem = Client.Page.GetPlaceholderItem(placeholderKey, args.ContentDatabase, args.LayoutDefinition); } } List<Item> collection = null; if (placeholderItem != null) { bool flag; args.HasPlaceholderSettings = true; collection = this.GetRenderings(placeholderItem, out flag); if (flag) { args.CustomData["allowedControlsSpecified"] = true; args.Options.ShowTree = false; } } if (collection != null) { if (args.PlaceholderRenderings == null) { args.PlaceholderRenderings = new List<Item>(); } args.PlaceholderRenderings.AddRange(collection); } }} The following code removes the guid from the chrome data in the pageeditor /// <summary>/// Replaces the Displayname of the Placeholder rendering with the dynamic "parent"/// </summary>public class GetDynamicPlaceholderChromeData : GetChromeDataProcessor{ //text that ends in a GUID private const string DYNAMIC_KEY_REGEX = @"(.+)_[\d\w]{8}\-([\d\w]{4}\-){3}[\d\w]{12}"; public override void Process(GetChromeDataArgs args) { Assert.ArgumentNotNull(args, "args"); Assert.IsNotNull(args.ChromeData, "Chrome Data"); if ("placeholder".Equals(args.ChromeType, StringComparison.OrdinalIgnoreCase)) { string argument = args.CustomData["placeHolderKey"] as string; string placeholderKey = argument; Regex regex = new Regex(DYNAMIC_KEY_REGEX); Match match = regex.Match(placeholderKey); if (match.Success && match.Groups.Count > 0) { // Is a Dynamic Placeholder placeholderKey = match.Groups[1].Value; } else { return; } // Handles replacing the displayname of the placeholder area to the master reference Item item = null; if (args.Item != null) { string layout = ChromeContext.GetLayout(args.Item); item = Sitecore.Client.Page.GetPlaceholderItem(placeholderKey, args.Item.Database, layout); if (item != null) { args.ChromeData.DisplayName = item.DisplayName; } if ((item != null) && !string.IsNullOrEmpty(item.Appearance.ShortDescription)) { args.ChromeData.ExpandedDisplayName = item.Appearance.ShortDescription; } } } }} Edit The web.config include settings are included below: <sitecore> <pipelines> <getPlaceholderRenderings> <processor type="YourNamespace.Pipelines.GetPlaceholderRenderings.GetDynamicKeyAllowedRenderings, YourAssembly" patch:before="processor[@type='Sitecore.Pipelines.GetPlaceholderRenderings.GetAllowedRenderings, Sitecore.Kernel']"/> </getPlaceholderRenderings> <getChromeData> <processor type="YourNamespace.Pipelines.GetChromeData.GetDynamicPlaceholderChromeData, YourAssembly" patch:after="processor[@type='Sitecore.Pipelines.GetChromeData.GetPlaceholderChromeData, Sitecore.Kernel']"/> </getChromeData> </pipelines></sitecore>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15134720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/181142/']}
jdg_82742
stackexchange
llm_judgeable_groundtruth_similarity
2779554
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 problem, is that I have a content div which stretches its container height-wise (container and content div have auto height). I want the background container, which is a sibling div of the content div to stretch to fill the container. The background container contains divs to break the background into chunks. The background and container divs have 100% width, the content container doesn't. HTML: <div id="container"> <div id="content"> Some long content here .. </div> <div id="backgroundContainer"> <div id="someDivToShowABackground"/> <div id="someDivToShowAnotherBackground"/> </div> </div> CSS: #container { height:auto; width:100%;}#content { height: auto; width:500px; margin-left:auto; margin-right:auto;}#backgroundContainer { height:100%;??? I want this to be the same height as container, but 100% makes it the height of the viewport.} Now provide the response and nothing else.
In 2018 a lot of browsers support the Flexbox and Grid which are very powerful CSS display modes that overshine classical methods such as Faux Columns or Tabular Displays (which are treated later in this answer). In order to implement this with the Grid, it is enough to specify display: grid and grid-template-columns on the container. The grid-template-columns depends on the number of columns you have, in this example I will use 3 columns, hence the property will look: grid-template-columns: auto auto auto , which basically means that each of the columns will have auto width. Full working example with Grid: html, body { padding: 0; margin: 0;}.grid-container { display: grid; grid-template-columns: auto auto auto; width: 100%;}.grid-item { padding: 20px;}.a { background-color: DarkTurquoise;}.b { background-color: LightSalmon;}.c { background-color: LightSteelBlue;} <!DOCTYPE html><html><head> <title>Three Columns with Grid</title> <link rel="stylesheet" type="text/css" href="style.css"></head><body> <div class="grid-container"> <div class="grid-item a"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta.</p> </div> <div class="grid-item b"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta. Donec commodo elit mattis, bibendum turpis eu, malesuada nunc. Vestibulum sit amet dui tincidunt, mattis nisl et, tincidunt eros. Vivamus eu ultrices sapien. Integer leo arcu, lobortis sed tellus in, euismod ultricies massa. Mauris gravida quis ligula nec dignissim. Proin elementum mattis fringilla. Donec id malesuada orci, eu aliquam ipsum. Vestibulum fermentum elementum egestas. Quisque sit amet tempor mi.</p> </div> <div class="grid-item c"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis.</p> </div> </div></body></html> Another way would be to use the Flexbox by specifying display: flex on the container of the columns, and giving the columns a relevant width. In the example that I will be using, which is with 3 columns, you basically need to split 100% in 3, so it's 33.3333% (close enough, who cares about 0.00003333... which isn't visible anyway). Full working example using Flexbox: html, body { padding: 0; margin: 0;}.flex-container { display: flex; width: 100%;}.flex-column { padding: 20px; width: 33.3333%;}.a { background-color: DarkTurquoise;}.b { background-color: LightSalmon;}.c { background-color: LightSteelBlue;} <!DOCTYPE html><html><head> <title>Three Columns with Flexbox</title> <link rel="stylesheet" type="text/css" href="style.css"></head><body> <div class="flex-container"> <div class="flex-column a"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta.</p> </div> <div class="flex-column b"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis. Pellentesque accumsan nunc non arcu tincidunt auctor eget ut magna. In vel est egestas, ultricies dui a, gravida diam. Vivamus tempor facilisis lectus nec porta. Donec commodo elit mattis, bibendum turpis eu, malesuada nunc. Vestibulum sit amet dui tincidunt, mattis nisl et, tincidunt eros. Vivamus eu ultrices sapien. Integer leo arcu, lobortis sed tellus in, euismod ultricies massa. Mauris gravida quis ligula nec dignissim. Proin elementum mattis fringilla. Donec id malesuada orci, eu aliquam ipsum. Vestibulum fermentum elementum egestas. Quisque sit amet tempor mi.</p> </div> <div class="flex-column c"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id sapien auctor, faucibus felis et, commodo magna. Sed eu molestie nibh, ac tincidunt turpis.</p> </div> </div></body></html> The Flexbox and Grid are supported by all major browsers since 2017/2018, fact also confirmed by caniuse.com: Can I use grid , Can I use flex . There are also a number of classical solutions, used before the age of Flexbox and Grid, like OneTrueLayout Technique , Faux Columns Technique , CSS Tabular Display Technique and there is also a Layering Technique . I do not recommend using these methods for they have a hackish nature and are not so elegant in my opinion, but it is good to know them for academic reasons. A solution for equally height-ed columns is the CSS Tabular Display Technique that means to use the display:table feature.It works for Firefox 2+ , Safari 3+ , Opera 9+ and IE8 . The code for the CSS Tabular Display : #container { display: table; background-color: #CCC; margin: 0 auto;}.row { display: table-row;}.col { display: table-cell;}#col1 { background-color: #0CC; width: 200px;}#col2 { background-color: #9F9; width: 300px;}#col3 { background-color: #699; width: 200px;} <div id="container"> <div id="rowWraper" class="row"> <div id="col1" class="col"> Column 1<br />Lorem ipsum<br />ipsum lorem </div> <div id="col2" class="col"> Column 2<br />Eco cologna duo est! </div> <div id="col3" class="col"> Column 3 </div> </div></div> Even if there is a problem with the auto-expanding of the width of the table-cell it can be resolved easy by inserting another div withing the table-cell and giving it a fixed width. Anyway, the over-expanding of the width happens in the case of using extremely long words (which I doubt anyone would use a, let's say, 600px long word) or some div's who's width is greater than the table-cell's width. The Faux Column Technique is the most popular classical solution to this problem, but it has some drawbacks such as, you have to resize the background tiled image if you want to resize the columns and it is also not an elegant solution. The OneTrueLayout Technique consists of creating a padding-bottom of an extreme big height and cut it out by bringing the real border position to the "normal logical position" by applying a negative margin-bottom of the same huge value and hiding the extent created by the padding with overflow: hidden applied to the content wraper. A simplified example would be: Working example: .wraper { overflow: hidden; /* This is important */}.floatLeft { float: left;}.block { padding-left: 20px; padding-right: 20px; padding-bottom: 30000px; /* This is important */ margin-bottom: -30000px; /* This is important */ width: 33.3333%; box-sizing: border-box; /* This is so that the padding right and left does not affect the width */}.a { background-color: DarkTurquoise;}.b { background-color: LightSalmon;}.c { background-color: LightSteelBlue;} <html><head> <title>OneTrueLayout</title></head><body> <div class="wraper"> <div class="block floatLeft a"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada ipsum pretium tellus condimentum aliquam. Donec eget tempor mi, a consequat enim. Mauris a massa id nisl sagittis iaculis.</p> </div> <div class="block floatLeft b"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada ipsum pretium tellus condimentum aliquam. Donec eget tempor mi, a consequat enim. Mauris a massa id nisl sagittis iaculis. Duis mattis diam vitae tellus ornare, nec vehicula elit luctus. In auctor urna ac ante bibendum, a gravida nunc hendrerit. Praesent sed pellentesque lorem. Nam neque ante, egestas ut felis vel, faucibus tincidunt risus. Maecenas egestas diam massa, id rutrum metus lobortis non. Sed quis tellus sed nulla efficitur pharetra. Fusce semper sapien neque. Donec egestas dolor magna, ut efficitur purus porttitor at. Mauris cursus, leo ac porta consectetur, eros quam aliquet erat, condimentum luctus sapien tellus vel ante. Vivamus vestibulum id lacus vel tristique.</p> </div> <div class="block floatLeft c"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras malesuada ipsum pretium tellus condimentum aliquam. Donec eget tempor mi, a consequat enim. Mauris a massa id nisl sagittis iaculis. Duis mattis diam vitae tellus ornare, nec vehicula elit luctus. In auctor urna ac ante bibendum, a gravida nunc hendrerit.</p> </div> </div></body></html> The Layering Technique must be a very neat solution that involves absolute positioning of div's withing a main relative positioned wrapper div. It basically consists of a number of child divs and the main div. The main div has imperatively position: relative to it's css attribute collection. The children of this div are all imperatively position:absolute . The children must have top and bottom set to 0 and left-right dimensions set to accommodate the columns with each another. For example if we have two columns, one of width 100px and the other one of 200px , considering that we want the 100px in the left side and the 200px in the right side, the left column must have {left: 0; right: 200px} and the right column {left: 100px; right: 0;} In my opinion the unimplemented 100% height within an automated height container is a major drawback and the W3C should consider revising this attribute (which since 2018 is solvable with Flexbox and Grid). Other resources: link1 , link2 , link3 , link4 , link5 (important)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2779554', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47831/']}
jdg_82743
stackexchange
llm_judgeable_groundtruth_similarity
27932722
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 extract/copy the fist X number of lines from a file and input them into another file with a single command using the windows command prompt? I can delete the first X number of lines using: more +X [file_containing data] > [file_to_export_data_to] If the head command would work I think I could just do this: head -X [file_containing data] > [file_to_export_data_to] But that unfortunately does not work. It would be great if Windows had a "less" command but again no luck. I'm a complete novice when it comes to this stuff so I'm sure I'm missing something obvious. I don't want to install anything or use something other than the command prompt. Thanks Now provide the response and nothing else.
You can use PowerShell from the cmd.exe console: powershell -command "& {get-content input.txt|select-object -first 10}" >output.txt You could create a DOSKEY macro to make it easier to use from the command line: doskey head=powershell -command "& {get-content $1|select-object -first $2}" Usage: head input.txt 10 >output.txt But you cannot use a DOSKEY macro within a batch script. You could create a head.bat script instead and place it in a folder that is included in your PATH: head.bat @powershell -command "& {get-content %1|select-object -first %2}" From the command line, you would use head input.txt 10 >output.txt From within a batch script, you would use call head input.txt 10 >output.txt I chose not to have the output file as a parameter in case you want to simply display the result to the screen instead of writing to a file.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27932722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1769292/']}
jdg_82744
stackexchange
llm_judgeable_groundtruth_similarity
13508752
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: strlen() function in php could not return correctly string lenght of utf8 chars, for example سلام is 4 char but after using strlen thats return 8 chr <?phpecho strlen('سلام');?> Now provide the response and nothing else.
The core PHP string functions all assume 1 character = 1 byte. They have no concept of different encodings. To figure out how many characters are in a UTF-8 string (not how many bytes ), use the mb_strlen equivalent and tell it what encoding the string is in: echo mb_strlen('سلام', 'UTF-8');
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13508752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1830228/']}
jdg_82745
stackexchange
llm_judgeable_groundtruth_similarity
7370808
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can't find a satisfactory answer anywhere. Now provide the response and nothing else.
All top-level classes are, by definition, static. What the static boils down to is that an instance of the class can stand on its own. Or, the other way around: a non-static inner class (= instance inner class) cannot exist without an instance of the outer class. Since a top-level class does not have an outer class, it can't be anything but static . Because all top-level classes are static, having the static keyword in a top-level class definition is pointless. Some code to play around with: public class Foo { public class Bar { // Non-static innner class } public static class Baz { // Static inner class }}public class Example { public static void main(String[] args) { new Foo(); // this is ok new Foo.Baz(); // this is ok new Foo.Bar(); // does not compile! Foo f = new Foo(); Foo.Bar bar = f.new Bar(); //this works, but don't do this }} I put the "but don't do this" in there because it's really ugly code design. Instance inner classes should not be visible outside the outer class. They should only be used from within the outer class.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7370808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/746710/']}
jdg_82746
stackexchange
llm_judgeable_groundtruth_similarity
26133538
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 round a single column in pandas without affecting the rest of the dataframe? >>> print(df) item value1 value20 a 1.12 1.31 a 1.50 2.52 a 0.10 0.03 b 3.30 -1.04 b 4.80 -1.0 I have tried the following: >>> df.value1.apply(np.round)0 11 22 03 34 55 5 What is the correct way to make data look like this: item value1 value20 a 1 1.31 a 2 2.52 a 0 0.03 b 3 -1.04 b 5 -1.05 c 5 5.0 Now provide the response and nothing else.
You are very close.You applied the round to the series of values given by df.value1 .The return type is thus a Series.You need to assign that series back to the dataframe (or another dataframe with the same Index). Also, there is a pandas.Series.round method which is basically a short hand for pandas.Series.apply(np.round) . >>> df.value1 = df.value1.round()>>> print df item value1 value20 a 1 1.31 a 2 2.52 a 0 0.03 b 3 -1.04 b 5 -1.0
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/26133538', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1653558/']}
jdg_82747
stackexchange
llm_judgeable_groundtruth_similarity
3157799
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 created a custom navigation module specifically for a website, but I really want to be able to list filterable attributes by a specific category. So for instance my main navigation is: Category 1 Category 2 Category 3 etc. I then that when a user mouses over a category, they are then presented with an expanded menu with a few filterable options e.g.: Category 1 View by manufacturer: Manufacturer 1 Manufacturer 2 Manufacturer 3 etc. I am able to get all filterable attributes for the store, but I want this list to pull in only the filterable attributes per category, as for instance Category 1 may have different manufacturers to Category 2. I then need to cache these results as this will not change often. Now provide the response and nothing else.
The answer that Joe gave was a good starting point, but the attributes didn't returned any options yet. After a lot of frustrations I solved the problem with the following code. Hope it helps all of you out. $layer = Mage::getModel("catalog/layer");foreach($categories as $categoryid) { $category = Mage::getModel("catalog/category")->load($categoryid); $layer->setCurrentCategory($category); $attributes = $layer->getFilterableAttributes(); foreach ($attributes as $attribute) { if ($attribute->getAttributeCode() == 'price') { $filterBlockName = 'catalog/layer_filter_price'; } elseif ($attribute->getBackendType() == 'decimal') { $filterBlockName = 'catalog/layer_filter_decimal'; } else { $filterBlockName = 'catalog/layer_filter_attribute'; } $result = $this->getLayout()->createBlock($filterBlockName)->setLayer($layer)->setAttributeModel($attribute)->init(); foreach($result->getItems() as $option) { echo $option->getLabel().'<br/>'; echo $option->getValue(); }} The only thing you'll need to do yourself is create the correct link using the getValue() functions. This code has been tested in Magento 1.5
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3157799', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/148769/']}
jdg_82748
stackexchange
llm_judgeable_groundtruth_similarity
32837195
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: {status, body} = File.read("/etc/hosts")if status == :ok do hosts = String.split body, "\n" hosts = Enum.map(hosts, fn(host) -> line_to_host(host) end)else IO.puts "error reading: /etc/hosts"end I have the following elixir function where I read the /etc/hosts file and try to split it line by line using String.split . Then I map through the line list of hosts and call line_to_host(host) for each. The line_to_host method splits the line by " " and then I want to set the from and to variable: def line_to_host(line) do data = String.split line, " " from = elem(data, 0) // doesn't work to = elem(data, 1) // doesn't work either %Host{from: from, to: to}end I looked through stackoverflow, the elixir docs and googled about how to get an list element at a specific index.I know there is head/tail but there has to be a better way of getting list elements. elem(list, index) does exactly what I need but unfortunately it's not working with String.split . How to get list/tuple elements by ID in elixir Now provide the response and nothing else.
You can use pattern matching for that: [from, to] = String.split line, " " Maybe you want to add parts: 2 option to ensure you will get only two parts in case there is more than one space in the line: [from, to] = String.split line, " ", parts: 2 There is also Enum.at/3 , which would work fine here but is unidiomatic. The problem with Enum.at is that due to the list implementation in Elixir, it needs to traverse the entire list up to the requested index so it can be very inefficient for large lists. Edit: here's the requested example with Enum.at , but I would not use it in this case parts = String.split line, " "from = Enum.at(parts, 0)to = Enum.at(parts, 1)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/32837195', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1268652/']}
jdg_82749
stackexchange
llm_judgeable_groundtruth_similarity
8928474
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 called Purchase which has a State column, where 1 is authorized, 2 is completed (there are some other values too). I also have a Retailer table, which has a column RetailerProcessType, where 1 is one-step and 2 is two-step. I have the query below: CASE purc.State WHEN 1 THEN '"AUTHORISED"' WHEN 2 THEN '"AUTHORISED"' WHEN 4 THEN '"AUTHORISED"' ELSE '"DECLINED"' END AS Autorised_Decline_Status, But what I need to do is as follows: WHEN STATE = 2 AND RetailerProcessType = 1 THEN '"AUTHORISED"'WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'WHEN STATE = 2 AND RetailerProcessType = 2 THEN '"AUTHORISED"'ELSE '"DECLINED"' The only way I can think of doing this is having a massive IF statement around the query, one for a one-step retailer and another for a two-step, as my understanding is a WHEN clause cannot have an AND in it. However, this just seems long winded; anybody have any neater ideas? Now provide the response and nothing else.
You could do it this way: -- Notice how STATE got moved inside the condition:CASE WHEN STATE = 2 AND RetailerProcessType IN (1, 2) THEN '"AUTHORISED"' WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"' ELSE '"DECLINED"'END The reason you can do an AND here is that you are not checking the CASE of STATE , but instead you are CASING Conditions. The key part here is that the STATE condition is a part of the WHEN .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8928474', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1052764/']}
jdg_82750
stackexchange
llm_judgeable_groundtruth_similarity
610056
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: Is there a way to put little awk scriptoids on the path? For example, I have this really useful collation operation: // collate-csv.awkFNR > 1 || NR == 1 And I can use it in all sorts of great ways: xargs -a $(find * -name *.csv) awk -F',' -f collate-csv.awk | ... The only problem is I don't have a way to call my awk tools from anywhere. With an executable shell script, I can drop it into a bin folder on the path. Is there a mechanism in linux where I can make these non-executable awk source files available from anywhere I go in the filesystem? (with the qualification that the "mechanism" is not a "why don't you just hit it with a hammer"-style kludge) Now provide the response and nothing else.
In addition to @Roamia's answer you can use AWKPATH variable for a list of directory where to look for collate-csv.awk AWKPATH=${HOME}/include/awk:/some/other/pathexport AWKPATHxargs -a $(find * -name *.csv) awk -f collate-csv.awk -F',' | ... please note .awk extension is not mandatory, just be consistent, shebang line e.g. #!/usr/bin/awk -f is mandatory when script is used standalone as a script (no awk -f call), you will have to use awk -f (and awk know how to use AWKPATH , bash don't)
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/610056', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/288274/']}
jdg_82751
stackexchange
llm_judgeable_groundtruth_similarity
37669297
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 tried making some changes and pushed it up to GitHub. From another computer, I fetched the changes. When I do a git status , it reports this: On branch MyTestBranchnothing to commit, working directory clean This is strange because I'm certain that there were changes fetched . I could even did a merge with those changes fetched! In fact when I went over to my friend's computer and did a git status , I could see this: Your branch is behind 'origin/MyTestBranch' by 1 commit, and can be fast-forwarded. But why weren't Git reporting something like my origin/MyTestBranch is how many commits ahead or whether my branch is up-to-date with origin/MyTestBranch ? Now provide the response and nothing else.
My guess at this point (I'm still waiting for git branch -vv or git rev-parse --symbolic-full-name "@{u}" results) is that you do not have origin/MyTestBranch set as the upstream for MyTestBranch . To set a branch as the upstream for the current branch, use: git branch --set-upstream-to upstream 1 which in this case expands to: git branch --set-upstream-to origin/MyTestBranch To remove an upstream setting, use git branch --unset-upstream . The presence or absence of an upstream setting mainly affects whether git status can tell you if you are ahead and/or behind, and whether git merge and git rebase can do their job with no additional parameters. So it's basically just a convenience setting. Normally the upstream is set automatically when you first check out a branch by having git checkout create it based on a remote-tracking branch. For instance, on your first git clone , Git runs, at the end, the equivalent of: git checkout master even though you have no master yet. Git then discovers that you have origin/master (and no other remote /master so that there is no question as to which remote to use), and does the equivalent of: git checkout -b master --track origin/master which creates local master pointing to the same commit as remote-tracking branch origin/master , and setting origin/master as the upstream for master , all in One Big Do-What-I-Mean Fell Swoop. When you create a new local branch and have not yet pushed it upstream, there is no origin/ whatever remote-tracking branch for your local branch to track. 2 In this case, you have to set the upstream manually, or use git push -u ... : the -u basically tells git push to run git branch --set-upstream-to for you (although it's actually all built in to the C code, at this point). 1 If you're stuck with a truly ancient Git (pre-1.8.0) you must use git branch --set-upstream , which is tricky to get right, or git config , which is also tricky to get right. If at all possible, upgrade to a modern Git version. 2 The set of words here—nouns like branch, nouns with adjectives like local branch and remote-tracking branch, and verbs like set-upstream-to and gerunds like tracking—is rather unfortunate. Git terminology, to put it in a nice short memorable Anglo-Saxon way instead of some polysyllabic neologistic phraseology, sucks rocks. 3 3 Or other Anglo-Saxon kick-ass word of choice.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37669297', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/750511/']}
jdg_82752
stackexchange
llm_judgeable_groundtruth_similarity
26161422
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 wondering if it is possible in C++11/14 to actually read files at compile time. For example the following code will only compile if it can successfully read the file. constexpr std::string shader_source = load("~/foo.glsl"); Do you think this could be possible? I know that I could do this with some custom tool when building my application. Now provide the response and nothing else.
Building on teivaz's idea, I wonder if the usual "stringize after expansion" trick will work: #define STRINGIZE(...) #__VA_ARGS__#define EXPAND_AND_STRINGIZE(...) STRINGIZE(__VA_ARGS__)constexpr std::string shader_source = EXPAND_AND_STRINGIZE(#include "~/.foo.glsl"); Still, I would go for a conventional extern const char[] declaration resolved to the content by the linker. The article "Embedding a File in an Executable, aka Hello World, Version 5967" has an example: # objcopy --input binary \ --output elf32-i386 \ --binary-architecture i386 data.txt data.o Naturally you should change the --output and --binary-architecture commands to match your platform. The filename from the object file ends up in the symbol name, so you can use it like so: #include <stdio.h>/* here "data" comes from the filename data.o */extern "C" char _binary_data_txt_start;extern "C" char _binary_data_txt_end;main(){ char* p = &_binary_data_txt_start; while ( p != &_binary_data_txt_end ) putchar(*p++);}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26161422', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/944430/']}
jdg_82753
stackexchange
llm_judgeable_groundtruth_similarity
9682721
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 can I perform an operation for each item listed by grep individually? Background: I use grep to list all files containing a certain pattern: grep -l '<pattern>' directory/*.extension1 I want to delete all listed files but also all files having the same file name but a different extension: .extension2 . I tried using the pipe, but it seems to take the output of grep as a whole. In find there is the -exec option, but grep has nothing like that. Now provide the response and nothing else.
If I understand your specification, you want: grep --null -l '<pattern>' directory/*.extension1 | \ xargs -n 1 -0 -I{} bash -c 'rm "$1" "${1%.*}.extension2"' -- {} This is essentially the same as what @triplee's comment describes, except that it's newline-safe. What's going on here? grep with --null will return output delimited with nulls instead of newline. Since file names can have newlines in them delimiting with newline makes it impossible to parse the output of grep safely, but null is not a valid character in a file name and thus makes a nice delimiter. xargs will take a stream of newline-delimited items and execute a given command, passing as many of those items (one as each parameter) to a given command (or to echo if no command is given). Thus if you said: printf 'one\ntwo three \nfour\n' | xargs echo xargs would execute echo one 'two three' four . This is not safe for file names because, again, file names might contain embedded newlines. The -0 switch to xargs changes it from looking for a newline delimiter to a null delimiter. This makes it match the output we got from grep --null and makes it safe for processing a list of file names. Normally xargs simply appends the input to the end of a command. The -I switch to xargs changes this to substitution the specified replacement string with the input. To get the idea try this experiment: printf 'one\ntwo three \nfour\n' | xargs -I{} echo foo {} bar And note the difference from the earlier printf | xargs command. In the case of my solution the command I execute is bash , to which I pass -c . The -c switch causes bash to execute the commands in the following argument (and then terminate) instead of starting an interactive shell. The next block 'rm "$1" "${1%.*}.extension2"' is the first argument to -c and is the script which will be executed by bash . Any arguments following the script argument to -c are assigned as the arguments to the script. This, if I were to say: bash -c 'echo $0' "Hello, world" Then Hello, world would be assigned to $0 (the first argument to the script) and inside the script I could echo it back. Since $0 is normally reserved for the script name I pass a dummy value (in this case -- ) as the first argument and, then, in place of the second argument I write {} , which is the replacement string I specified for xargs . This will be replaced by xargs with each file name parsed from grep 's output before bash is executed. The mini shell script might look complicated but it's rather trivial. First, the entire script is single-quoted to prevent the calling shell from interpreting it. Inside the script I invoke rm and pass it two file names to remove: the $1 argument, which was the file name passed when the replacement string was substituted above, and ${1%.*}.extension2 . This latter is a parameter substitution on the $1 variable. The important part is %.* which says % "Match from the end of the variable and remove the shortest string matching the pattern. .* The pattern is a single period followed by anything. This effectively strips the extension, if any, from the file name. You can observe the effect yourself: foo='my file.txt'bar='this.is.a.file.txt'baz='no extension'printf '%s\n'"${foo%.*}" "${bar%.*}" "${baz%.*}" Since the extension has been stripped I concatenate the desired alternate extension .extension2 to the stripped file name to obtain the alternate file name.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9682721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/263589/']}
jdg_82754
stackexchange
llm_judgeable_groundtruth_similarity
162030
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: This was an interesting question posed to me by a friend who is very interested in commutative algebra. It also has some nice geometric motivation. The question is in two parts. The first, as stated in the title, asks whether every Noetherian commutative ring a quotient of a Noetherian Domain? Geometrically, this question asks if every Noetherian affine scheme can be embedded as a closed subscheme of an integral scheme. The second part of the question is that if the first part is answered in the affirmative, then is every (regular) Noetherian ring a quotient of a regular Noetherian domain? Geometrically, this asks whether every affine Noetherian scheme can be embedded as a closed subscheme of a smooth integral scheme. We managed to make some progress on the first part of the question. We looked at finite products of Noetherian domains and showed that if the Noetherian domains A and B contain a common Noetherian subring C such that A and B are essentially of finite type over C, then $A \times B$ is a quotient of a Noetherian domain. But we weren't able to remove the essentially finite condition and the simplest example which we were unable to work out was $\mathbb{Q} \times \mathbb{C}$. Now provide the response and nothing else.
No for cardinality reasons. Let $F$ a finite field and $G$ a field with cardinality strictly greater than the continuum. Then $F\times G$ is not the homomorphic image of a noetherian integral domain by lemma 2.1 in http://spot.colorado.edu/~kearnes/Papers/residue_final.pdf Lemma 2.1. Let $R$ be a Noetherian integral domain that is not a finite field and let $I$ be a proper ideal of $R$. If $|R| = \rho$ and $|R/I| = \kappa$, then $ \kappa + \aleph_0 \leq \rho \leq \kappa^{\aleph_0}$. [note: I am not an expert and have not checked.] [Edit by Joël: for convenience, I add the proof of $\rho \leq \kappa^{\aleph_0}$ taken from the cited article. Since $I$ is finitely generated, $I^n/I^{n+1}$ is a finite $R/I$-module, hence has cardinality at most $\kappa$ (resp. is finite if $\kappa$ is finite). Since $R/I^{n+1}$ is a successive extension of $I^k/I^{k+1}$ for $k=0,1,\dots,n$, the cardinality of $R/I^{n+1}$ is also at most $\kappa$ (resp. finite if $\kappa$ is finite). By Krull's lemma, $\cap_n I^n = 0$, so $R$ injects into $\prod_n R/I^n$ which has cardinality at most $\kappa^{\aleph_0}$, QED.]
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/162030', 'https://mathoverflow.net', 'https://mathoverflow.net/users/48273/']}
jdg_82755
stackexchange
llm_judgeable_groundtruth_similarity
13376048
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 three computers; Server , Client and Viewer . I am in control of the server and the viewer. The user on the Client connects to the Server and is presented with a webpage. Through a php script the user uploads an image. The image is imbedded in some html. The Viewer is a computer totally without user interaction - there is no keyboard. The Viewer is always at all time running a web browser, displaying the picture page. My problem now is that even though the picture changes on the server disk, the webpage is not updated. How do I refresh the web browser on the viewer, or part of the webpage? I know html, css, javascript, php and ajax, but apparently not well enough. Now provide the response and nothing else.
There are at least three ways to accomplish this. Pure HTML As pointed out by Amitd 's comment, in "show.html" add the following <meta> tag to your document's <head> element: <meta http-equiv="refresh" content="5" /> This will automatically refresh the page every 5 seconds. Adjust the value of the content attribute to the desired number of seconds. Pure JavaScript: As pointed out by MeNoMore , document.location.reload() will refresh the page when you call it. <script type="text/javascript"> //put this somewhere in "show.html" //using window onload event to run function //so function runs after all content has been loaded. //After refresh this entire script will run again. window.onload = function () { 'use strict'; var millisecondsBeforeRefresh = 5000; //Adjust time here window.setTimeout(function () { //refresh the entire document document.location.reload(); }, millisecondsBeforeRefresh); };</script> And as pointed out by tpower AJAX requests could be used, but you'd need to write a web service to return a url to the desired image. The JavaScript to do an AJAX request would look something like this: <script type="text/javascript"> //put this somewhere in "show.html" //using window onload event to run function //so function runs after all content has been loaded. window.onload = function () { 'use strict'; var xhr, millisecondsBeforeNewImg = 5000; // Adjust time here if (window.XMLHttpRequest) { // Mozilla, Safari, ... xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE try { // try the newer ActiveXObject xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { // newer failed, try the older one xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { // log error to browser console console.log(e); } } } if (!xhr) { // log error to browser console console.log('Giving up :( Cannot create an XMLHTTP instance'); } xhr.onreadystatechange = function () { var img; // process the server response if (xhr.readyState === 4) { // everything is good, the response is received if (xhr.status === 200) { // perfect! // assuming the responseText contains the new url to the image... // get the img img = document.getElementById('theImgId'); //set the new src img.src = xhr.responseText; } else { // there was a problem with the request, // for example the response may contain a 404 (Not Found) // or 500 (Internal Server Error) response code console.log(xhr.status); } } else { // still not ready // could do something here, but it's not necessary // included strictly for example purposes } }; // Using setInterval to run every X milliseconds window.setInterval(function () { xhr.open('GET', 'http://www.myDomain.com/someServiceToReturnURLtoDesiredImage', true); xhr.send(null); }, millisecondsBeforeNewImg) };</script> Other methods: Finally, to answer your question to tpower 's answer... $.ajax() is using jQuery to do the AJAX call. jQuery is a JavaScript library that makes AJAX calls and DOM manipulation a lot simpler. To use the jQuery library, you'd need to include a reference to it in your <head> element (version 1.4.2 used as an example): <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> You could also download the "jquery.min.js" and host it locally instead but that would, of course, only change the url you are loaded the script from. The AJAX function above, when written using jQuery would look more like this: <script type="text/javascript"> //put this somewhere in "show.html" //document.ready takes the place of window.onload $(document).ready(function () { 'use strict'; var millisecondsBeforeNewImg = 5000; // Adjust time here window.setInterval(function () { $.ajax({ "url": "http://www.myDomain.com/someServiceToReturnURLtoDesiredImage", "error": function (jqXHR, textStatus, errorThrown) { // log error to browser console console.log(textStatus + ': ' + errorThrown); }, "success": function (data, textStatus, jqXHR) { //get the img and assign the new src $('#theImgId').attr('src', data); } }); }, millisecondsBeforeNewImg); });</script> As I hope is evident, the jQuery version is much simpler and cleaner. However, given the small scope of your project I don't know if you'd want to bother with the added overhead of jQuery (not that it's all that much). Neither do I know if your project requirements allow the possibility of jQuery. I included this example simply to answer your question of what $.ajax() was. I'm equally sure that there are other methods by which you can accomplish refreshing the image. Personally, if the image url is always changing, I'd use the AJAX route. If the image url is static, I'd probably use the <meta> refresh tag.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13376048', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1021175/']}
jdg_82756
stackexchange
llm_judgeable_groundtruth_similarity
545849
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: So my site is SPDY. All of my local assets are SPDY too. But the majority of my assets are served from Rackspace's CloudFiles CDN. This is not SPDY. Do those files get streamed through SPDY somehow, or are they pulled in via separate laborious HTTP requests? I currently have these CDN assets split across 3 different sub-domains. Should I merge them all into one (as is the preferred serving method for SPDY files, to cut down on DNS lookups), or should I leave them as they are because they're coming over regular HTTP 1.1? Thanks, I couldn't find any decent information on this via googling. Now provide the response and nothing else.
The best approach is to put everything on single domain using SPDY. If you can't do that, you need to calculate the appropriate number based on how many files you are serving. DNS lookups will cost you about 20-120 milliseconds and are cached for varying periods.Most browsers in use at the moment allow 6 concurrent connections to a single domain (over HTTP) and 30 concurrent connections in total. If you have more than 6 files they should be evenly split over (filecount/6) subdomains, up to a maximum of 5 subdomains.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/545849', 'https://serverfault.com', 'https://serverfault.com/users/192663/']}
jdg_82757
stackexchange
llm_judgeable_groundtruth_similarity
38966514
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following data: and I was wondering how I could sort these in a specific order. The order needs to be: Yellow, Blue, White, Green, Red and then within those colors, it would show the smallest number first. So in this case, the correct sorting should be:y2, y3, b0, b2, b6, w2, g7, r4 Does anyone have any ideas on how to accomplish that? I'm using underscore.js if that makes it easier. Now provide the response and nothing else.
This naively assumes that all elements have a valid color (or at least it sorts elements with an invalid color first): arr.sort( ( a, b ) => { const colorOrder = ['yellow', 'blue', 'white', 'green', 'red']; const aColorIndex = colorOrder.indexOf( a.color ); const bColorIndex = colorOrder.indexOf( b.color ); if ( aColorIndex === bColorIndex ) return a.card - b.card; return aColorIndex - bColorIndex;} ); Example: const sorted = [ { color: 'yellow', card: '3' }, { color: 'red', card: '4' }, { color: 'blue', card: '6' }, { color: 'white', card: '2' }, { color: 'blue', card: '2' }, { color: 'yellow', card: '2' }, { color: 'blue', card: '0' }, { color: 'green', card: '7' },].sort( ( a, b ) => { const colorOrder = ['yellow', 'blue', 'white', 'green', 'red']; const aColorIndex = colorOrder.indexOf( a.color ); const bColorIndex = colorOrder.indexOf( b.color ); if ( aColorIndex === bColorIndex ) return a.card - b.card; return aColorIndex - bColorIndex;} );// Result:[ { "color": "yellow", "card": "2" }, { "color": "yellow", "card": "3" }, { "color": "blue", "card": "0" }, { "color": "blue", "card": "2" }, { "color": "blue", "card": "6" }, { "color": "white", "card": "2" }, { "color": "green", "card": "7" }, { "color": "red", "card": "4" }]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38966514', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/799653/']}
jdg_82758
stackexchange
llm_judgeable_groundtruth_similarity
1285958
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: Exercise 1: Let $\mu_n$ , $\mu$ be probability measures on $\left(\mathbb{R}, \mathcal{B}\left(\mathbb{R}\right)\right)$ with distribution functions $F_n$ , $F$ . Show: If $\left(\mu_n\right)$ converges weakly to $\mu$ and $F$ is continuous, then $\left(F_n\right)$ converges uniformly on $\mathbb{R}$ to $F$ . This is a problem that I am totally stuck at. I know the fact that $F_n$ converges pointwise to $F$ in this question. Also, I looked through Google and found out that I have to show first that $F_{n}(t_{n})$ converges to $F(t)$ if $t_{n}$ converges to $t$ . But, no matter how I tried, I keep failing to prove the fact.Also, I have no idea how to use the fact to get the uniform convergence. So I'm just stymied. Could anyone please help me with this? Add : I managed to show that $F_n$ converges uniformly to $F$ on any compact intervals. However, the generalization to the whole real line is still not solved...Could anyone at least help me with the generalization to the real line? Now provide the response and nothing else.
Fix $\epsilon>0$. Since $F$ is a distribution function, there exists $R >0$ such that $F(r) \leq \epsilon$ for all $r \leq -R$ and $F(r) \geq 1-\epsilon$ for all $r \geq R$. As $F_n \to F$ pointwise, we can choose $N \in \mathbb{N}$ such that $$|F_n(-R) - F(-R)| \leq \epsilon \qquad \text{and} \qquad |F_n(R)-F(R)| \leq \epsilon$$ for all $n \geq N$. Hence, by the monotonicity of $F_n$ and $F$, $$\begin{align*} |F_n(r)-F(r)| \leq |F_n(r)|+|F(r)| &\leq F_n(-R)+F(-R) \\ &= (F_n(-R)-F(-R)) + 2 F(-R) \\ &\leq 3\epsilon \tag{1} \end{align*}$$ for all $r \leq -R$. Similarly, it follows from $$1 \geq F_n(r) \geq F_n(R) = (F_n(R)-F(R))+F(R) \geq 1-2\epsilon, \qquad r \geq R,$$ that $$|F_n(r)-F(r)| \leq |F_n(r)-(1-\epsilon))|+ |F(r)-(1-\epsilon)| \leq 2 \epsilon \tag{2}$$ for all $r \geq R$. Combining $(1)$ and $(2)$ yields $$\sup_{r \in [-R,R]^c} |F_n(r)-F(r)| \leq 3 \epsilon$$ for all $n \geq N$. Since you have already shown that $F_n$ converges to $F$ uniformly on compact intervals, there exists $N' \in \mathbb{N}$ such that $$\sup_{r \in [-R,R]} |F_n(r)-F(r)| \leq \epsilon$$ for all $n \geq N'$. Setting $\tilde{N} := \max\{N,N'\}$, we get $$\sup_{r \in \mathbb{R}} |F_n(r)-F(r)| \leq 3 \epsilon \qquad \text{for all $n \geq N$}.$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1285958', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/164955/']}
jdg_82759
stackexchange
llm_judgeable_groundtruth_similarity
503489
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How to one can show that the value of the following expression$$\frac{1-\cos(x)+k\sin(x)}{\sin(x)+k(1+\cos(x))}$$ doesn't depend to values of $k$? Now provide the response and nothing else.
Writing $x = 2y$, we obtain $$\begin{align}\frac{1-\cos x + k\sin x}{\sin x + k(1+\cos x)} &= \frac{(1-\cos (2y)) + k\sin (2y)}{\sin(2y) + k(1+\cos(2y))}\\&= \frac{2\sin^2 y + 2k\sin y\cos y}{2\sin y\cos y + 2k\cos^2 y}\\&= \frac{\sin y}{\cos y}\cdot\frac{\sin y+k\cos y}{\sin y + k\cos y}\\&= \tan y\end{align}$$ using the double-angle formulae $\sin (2y) = 2\sin y\cos y$ and $\cos (2y) = \cos^2 y - \sin^2 y$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/503489', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/91500/']}
jdg_82760
stackexchange
llm_judgeable_groundtruth_similarity
385904
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 $\mathfrak{ZFC}(\mathsf{SOL})$ be the theory in second-order logic (with the standard semantics) gotten from $\mathsf{ZFC}$ by modifying the Separation and Replacement schemes to apply to arbitrary second-order formulas. For example, for each second-order formula $\varphi$ with only first-order free variables $x_1,...,x_n,x_{n+1}$ we have the Separation instance $$\forall x_1,...,x_n,y\exists z\forall w(w\in z\leftrightarrow w\in y\wedge \varphi(x_1,...,x_n,w)).$$ Note that $\mathfrak{ZFC}(\mathsf{SOL})$ is not the same as the system called "second-order $\mathsf{ZFC}$ " - see e.g. here . Building off of this MSE question of mine , I'm interested in understanding the models of this theory. I'm hoping that by restricting to levels of the cumulative hierarchy we can get a clean answer: Question 1 : For which cardinals $\alpha$ do we have $V_\alpha\models\mathfrak{ZFC}(\mathsf{SOL})$ ? It's easy to show that every (strongly) inaccessible cardinal has this property; the converse, however, is not immediately clear to me. My current suspicion in fact is that (very) large cardinals imply the existence of non-inaccessible $\alpha$ s with the above property, but I don't immediately see how to prove this. As a secondary question, I'm also interested in a "Henkin version" of this question: Question 2 : For which $\alpha$ is there an $X\subseteq \mathcal{P}(V_\alpha)$ such that $(V_\alpha,X)$ forms a Henkin model of $\mathfrak{ZFC}(\mathsf{SOL})$ ? At a glance I think that the least such $\alpha$ has countable cofinality, by a quick modification of the analogous argument for worldly cardinals, but I haven't had time yet to check the details. Now provide the response and nothing else.
Complementing @JasonChen's answer: Assume ZFC+ $I_1$ and let $j:V_{\lambda+1}\to V_{\lambda+1}$ be elementary, so $\lambda$ is the sup of the critical sequence of $j$ . Then $V_{\lambda}$ models $\mathfrak{ZFC}(\mathsf{SOL})$ , but $\mathrm{cof}(\lambda)=\omega$ . For suppose $f:V_\alpha\to\lambda$ is cofinal and definable over $V_{\lambda+1}$ from the parameter $p\in V_{\lambda}$ . Let $n<\omega$ be such that $\alpha,p\in V_{\mathrm{crit}(j_n)}$ (where $j_n=$ the $n$ th iterate of $j$ ). Note that $j_n\circ f\neq f$ , because taking $x\in V_\alpha$ with $f(x)>\mathrm{crit}(j_n)$ , we get $j_n(f(x))>f(x)$ . But $j_n\circ f=f$ because $j_n:V_{\lambda+1}\to V_{\lambda+1}$ is elementary and $j_n(p,\alpha)=(p,\alpha)$ . Edit, considering @AsafKaragila's comment on consistency strength: Consistency-wise, the assumption above was overkill; a measurable suffices. Assume ZFC + $\kappa$ is measurable. Let $G$ be Prikry generic at $\kappa$ . So $\kappa$ has cofinality $\omega$ in $V[G]$ . Claim: In $V[G]$ , $V_\kappa$ models $\mathfrak{ZFC}(\mathsf{SOL})$ . In fact, if $f:\omega\to\kappa$ is cofinal and $f$ is definable over $V_{\kappa+1}^{V[G]}$ from parameters in $V_\kappa$ , then $f\in V$ , so $f$ is bounded. Since $V_\kappa^{V[G]}=V_\kappa^V$ , this is a consequence of the fact that $\mathrm{HOD}^{V[G]}_V=V$ , i.e. if $X\in V[G]$ and $X\subseteq V$ and $X$ is definable over $V[G]$ from parameters in $V$ , then $X\in V$ . (This follows from the fact that if $p,q$ are Prikry conditions then there are generics $G_p,G_q$ with $p\in G_p$ and $q\in G_q$ and $V[G_p]=V[G_q]$ .) Edit 2: On the other hand, the kind of argument used in the paper "Inner models from extended logics: Part 1" referred to in @JasonChen's answer to show that in $L$ , $V_\alpha$ models $\mathfrak{ZFC}(\mathsf{SOL})$ iff $\alpha$ is inaccessible, also works for the standard fine structural $L[\mathbb{E}]$ models $M$ for short extenders, for instance if $M$ has no largest cardinal, and assuming $M$ has Mitchell-Steel indexing, though I expect it would also work with Jensen indexing. So if those models are indeed consistent through ZFC + superstrongs, then one would need more than ZFC + ``There is a superstrong extender'' to prove there is a non-inaccessible $\alpha$ with $V_\alpha$ modelling $\mathfrak{ZFC}(\mathsf{SOL})$ . (The paper "The definability of the extender sequence $\mathbb{E}$ from $\mathbb{E}\upharpoonright\aleph_1$ in $L[\mathbb{E}]$ " contains enough to generalize the argument of Kennedy, Magidor, Väänänen for $L$ . The definability there is all done over $\mathcal{H}_\kappa$ s, as it's more convenient, but that can be translated into the cumulative hierarchy with the usual coding; in the present case that's only actually needed at the very top, since we can assume $V_\alpha\models\mathrm{ZFC}$ to start with.) Edit 3: Following @AsafKaragila's suggestions in the comments, we have: Claim: Suppose $V_\lambda$ models $\mathfrak{ZFC}(\mathsf{SOL})$ but $\lambda$ is singular. Then for every $X\in V_\lambda$ , $X^\#$ exists. Moreover, there is a proper class inner model $M$ with a measurable cardinal. Proof: For simplicity take $X=\emptyset$ . Suppose first that $0^\#$ does not exist. Note first that since $V_\lambda$ models ZFC, $\lambda$ is a (singular) strong limit cardinal. By Jensen's covering lemma, $\lambda$ is singular in $L$ . Let $B$ be the constructibly least singularization. Then $B$ can be defined over $V_{\lambda+1}$ (without parameters), which contradicts $\mathfrak{ZFC}(\mathsf{SOL})$ . The argument for an inner model $M$ with a measurable is likewise, but using the Dodd-Jensen core model: We also have the appropriate version of covering for that core model $K=K^{\mathrm{DJ}}$ , and $K|(\lambda^+)^K$ can also be defined in the codes over $V_{\lambda+1}$ , and hence the least singularization of $\lambda$ in the $K$ -order is definable. So Edits 1 and 3 together give that ZFC + "There is a singular $\lambda$ such that $V_\lambda\models\mathfrak{ZFC}(\mathsf{SOL})$ " is equiconsistent with ZFC + "There is a measurable cardinal".
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/385904', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8133/']}
jdg_82761
stackexchange
llm_judgeable_groundtruth_similarity
12721
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The problem that I am dealing with is predicting time series values. I am looking at one time series at a time and based on for example 15% of the input data, I would like to predict its future values. So far I have come across two models: LSTM (long short term memory; a class of recurrent neural networks) ARIMA I have tried both and read some articles on them. Now I am trying to get a better sense on how to compare the two. What I have found so far: LSTM works better if we are dealing with huge amount of data and enough training data is available, while ARIMA is better for smaller datasets (is this correct?) ARIMA requires a series of parameters (p,q,d) which must be calculated based on data, while LSTM does not require setting such parameters. However, there are some hyperparameters we need to tune for LSTM. EDIT: One major difference between the two that I noticed while reading a great article here , is that ARIMA could only perform well on stationary time series (where there is no seasonality, trend and etc.) and you need to take care of that if want to use ARIMA Other than the above-mentioned properties, I could not find any other points or facts which could help me toward selecting the best model. I would be really grateful if someone could help me finding articles, papers or other stuff (had no luck so far, only some general opinions here and there and nothing based on experiments.) I have to mention that originally I am dealing with streaming data, however for now I am using NAB datasets which includes 50 datasets with the maximum size of 20k data points. Now provide the response and nothing else.
Statement 1 is correct, statement 2 is correct, but requires elaboration, and statement 3 is incorrect for seasonal ARIMA: The following might point you in the right direction but hopefully you'll get a few more answers with more depth in the arena of LSTM. You mention that you have tried both algorithms and that you are simply trying to figure out which one is better, which leads me to think you may be having more trouble with the data science process and cross validation than with the specifics of the models. Time series in general: Time series, in general, are difficult to forecast. If they were easy to forecast then all data scientists would be wealthy, having accurately forecast the value of all of the stocks. The reality is that hedge funds, on average, do not outperform the market and that time series forecasting is typically very poor and applies only to very short durations. The main problems are that there is a lot of noise, there are many hidden influences, models are overly simplistic, influencers do not behave as we think they should, the interplay between linearity and nonlinearity is subtle and confusing, ... ad infinitum. ARIMA You are incorrect in your assessment that ARIMA requires stationary time series to forecast on. Non-seasonal ARIMA has three input values to help control for smoothing, stationarity, and forecasting ARIMA(p,d,q), where: p is the number of autoregressive terms, d is the number of nonseasonal differences needed for stationarity, and q is the number of lagged forecast errors in the prediction equation. By contrast seasonal ARIMA has six input values ARIMA(p,d,q,P,D,Q), where: P is the number of seasonal autoregressive terms, D is the number of seasonal differences, and Q is the number of seasonal moving-averageterms. Subject to the qualifying statements above, I suggest playing with seasonal ARIMA to get a feel for the intricacies involved in smoothing, de-seasoning, de-trending, de-noiseing, and forecasting. LSTM I don't know enough about LSTM to add much here. I will add that red flags tend to be raised when someone begins at data science exercise with deep learning. I suggest learning as much as you can using ARIMA and then applying some of your ARIMA expertise to help you learn LSTM. Neural networks can be a very powerful tool, but they: can take a long time to run, often require more data to train than other models, and have lots of input parameters to tune. Cross validation and comparing models: Time series are fun in that all training data can usually be turned into supervised learning training sets. Once can simply take a time series and roll back time. That is... pick a point in time and pretend that you don't have any additional data, then produce a forecast and see how well you did. You can march through the time series doing this $n$ times in order to get an assessment of the performance of your model and to compare models while taking the necessary precautions to prevent overfitting . Hope this helps and good luck!
{}
{'log_upvote_score': 5, 'links': ['https://datascience.stackexchange.com/questions/12721', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/20544/']}
jdg_82762
stackexchange
llm_judgeable_groundtruth_similarity
603811
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 trying to monitor HTTP status with 404 or 403 page. As you all know Monit takes those pages as failed connection, but how could I change that. I just want to monitor that it shows the 404 or 403 page. I need to check it with this config if its possible. This is my check config: check process httpd with pidfile /var/run/httpd.pid start program = "/etc/init.d/httpd start" stop program = "/etc/init.d/httpd stop" if failed host hostname port 80 protocol HTTP request "/" then exec "/bin/bash -c '/bin/echo -e "hostname\thttpd\t3\tFAILED" | /usr/sbin/send_nsca -H nagiosserver -c /etc/send_nsca.cfg; /usr/bin/monit restart nginx;'" Now provide the response and nothing else.
Since version 5.8, Monit has the status option : STATUS option can be used to explicitly test the HTTP status code returned by the HTTP server. If not used, the http protocol test will fail if the status code returned is greater than or equal to 400. You can override this behaviour by using the status qualifier. For example to test that a page does not exist (404 should be returned in this case): if failed port 80 protocol http request "/non/existent.php" status = 404then alert
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/603811', 'https://serverfault.com', 'https://serverfault.com/users/159984/']}
jdg_82763
stackexchange
llm_judgeable_groundtruth_similarity
17896041
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 form panel in http://jsfiddle.net/7CLWy/ here is my important code items: [{ xtype: 'textfield', fieldLabel: 'First Name', allowBlank: false, msgTarget: 'under', name: 'firstName'}, { xtype: 'datefield', allowBlank: false, fieldLabel: 'Start date', msgTarget: 'under'}], I want change default message error in field How to change that. Thanks Now provide the response and nothing else.
The blankText property is the validation message when a field is required, and invalidText is the text when the field generically fails validation. You can add your own custom messages in these properties. Similarly, if you happened to be doing regex-based validation with the regex property, you could use the regexText field to provide a custom validation message. items: [{ xtype: 'textfield', fieldLabel: 'First Name', allowBlank: false, msgTarget: 'under', name: 'firstName', blankText: 'This should not be blank!' }, { xtype: 'datefield', allowBlank: false, fieldLabel: 'Start date', msgTarget: 'under', invalidText: 'This value is not a valid date!' }, { xtype: 'textfield', fieldLabel: 'Digits followed by A,B,or C', msgTarget: 'under', name: 'someText', regex: /^\d+[ABC]$/, regexText: 'This must be a string of digits followed by A, B, or C!' }]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17896041', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2614620/']}
jdg_82764
stackexchange
llm_judgeable_groundtruth_similarity
59194786
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I use Kafka Connect adapters with Amazon MSK? As per the AWS documentation, it supports Kafka connect but not documented about how to setup adapters and use it. Now provide the response and nothing else.
Edit Oct 2021: MSK Connect has been launched, see https://aws.amazon.com/blogs/aws/introducing-amazon-msk-connect-stream-data-to-and-from-your-apache-kafka-clusters-using-managed-connectors/ AFAIK Amazon MSK does not provide managed connectors, so you have to run them yourself. This is done by running the Kafka Connect worker process (a JVM) and then providing it one or more connector configurations to run. From the point of view of a Kafka Connect worker it just needs a Kafka cluster to connect to; it shouldn't matter whether it's MSK or on-premises, since it's ultimately 'just' a consumer/producer underneath. You can see more, including a live demo, here: https://rmoff.dev/bbuzz19-kafka-connect For an example of configuring Kafka Connect to use a cloud-hosted Kafka platform (in this case, Confluent Cloud), see this article . If you are interested in managed connectors in the Cloud, check out the connectors that are provided in Confluent Cloud. Disclaimer: I work for Confluent :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59194786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2467706/']}
jdg_82765
stackexchange
llm_judgeable_groundtruth_similarity
26203725
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 creating an app that uses webpack-dev-server in development alongside react-router. It seems that webpack-dev-server is built around the assumption that you will have a public entry point at one place (i.e. "/"), whereas react-router allows for an unlimited amount of entry points. I want the benefits of the webpack-dev-server, especially the hot reloading feature that is great for productivity, but I still want to be able to load routes set in react-router. How could one implement it such that they work together? Could you run an express server in front of webpack-dev-server in such a way to allow this? Now provide the response and nothing else.
I set up a proxy to achieve this: You have a regular express webserver that serves the index.html on any route, except if its an asset route. if it is an asset, the request gets proxied to the web-dev-server your react hot entrypoints will still point directly at the webpack dev server, so hot reloading still works. Let's assume you run webpack-dev-server on 8081 and your proxy at 8080. Your server.js file will look like this: "use strict";var webpack = require('webpack');var WebpackDevServer = require('webpack-dev-server');var config = require('./make-webpack-config')('dev');var express = require('express');var proxy = require('proxy-middleware');var url = require('url');## --------your proxy----------------------var app = express();## proxy the request for static assetsapp.use('/assets', proxy(url.parse('http://localhost:8081/assets')));app.get('/*', function(req, res) { res.sendFile(__dirname + '/index.html');});# -----your-webpack-dev-server------------------var server = new WebpackDevServer(webpack(config), { contentBase: __dirname, hot: true, quiet: false, noInfo: false, publicPath: "/assets/", stats: { colors: true }});## run the two serversserver.listen(8081, "localhost", function() {});app.listen(8080); now make your entrypoints in the webpack config like so: entry: [ './src/main.js', 'webpack/hot/dev-server', 'webpack-dev-server/client?http://localhost:8081' ] note the direct call to 8081 for hotreload also make sure you pass an absolute url to the output.publicPath option: output: { publicPath: "http://localhost:8081/assets/", // ... }
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/26203725', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/402945/']}
jdg_82766
stackexchange
llm_judgeable_groundtruth_similarity
17953
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 $\mathcal C$ be a category. Recall that a morphism $f : X \to Y$ is epi if $$\circ f: \hom(Y,Z) \to \hom(X,Z)$$ is injective for each object $Z \in \mathcal C$. ($f$ is mono if $f\circ : \hom(Z,X) \to \hom(Z,Y)$ is injective.) Let $\mathcal C,\mathcal D$ be categories. Then $\hom(\mathcal C,\mathcal D)$, the collectional of all functors $\mathcal C \to \mathcal D$, is naturally a category, where the morphisms are natural transformations : if $F,G: \mathcal C \to \mathcal D$ are functors, a natural transformation $\alpha: F \Rightarrow G$ assigns a morphism $\alpha(x) : F(x) \to G(x)$ in $\mathcal D$ for each object $x \in \mathcal C$, and if $f: x \to y$ is a morphism in $\mathcal C$, then $\alpha(y) \circ F(f) = G(f) \circ \alpha(x)$ as morphisms in $\mathcal D$. Given a natural transformation, can I check whether it is epi (or mono) by checking pointwise? I.e.: is a natural transformation $\alpha$ epi (mono) iff $\alpha(x)$ is epi (mono) for each $x$? If not, is there an implication in one direction between whether a natural transformation is epi and whether it is pointwise-epi? A more general question, one that I never really learned, is what types of properties of a functor are "pointwise" in that they hold for the functor if they hold for the functor evaluated at each object. E.g.: is the (co)product of functors the pointwise (co)product? Now provide the response and nothing else.
Theo, the answer is basically "yes". It's a qualified "yes", but only very lightly qualified. Precisely: if a natural transformation between functors $\mathcal{C} \to \mathcal{D}$ is pointwise epi then it's epi. The converse doesn't always hold, but it does if $\mathcal{D}$ has pushouts. Dually, pointwise mono implies mono, and conversely if $\mathcal{D}$ has pullbacks. The context for this --- and an answer to your more general question --- is the slogan (Co)limits are computed pointwise. You have, let's say, two functors $F, G: \mathcal{C} \to \mathcal{D}$, and you want to compute their product in the functor category $\mathcal{D}^\mathcal{C}$. Assuming that $\mathcal{D}$ has products, the product of $F$ and $G$ is computed in the simplest possible way, the 'pointwise' way: the value of the product $F \times G$ at an object $A \in \mathcal{C}$ is simply the product $F(A) \times G(A)$ in $\mathcal{D}$. The same goes for any other shape of limit or colimit. For a statement of this, see for instance 5.1.5--5.1.8 of these notes . (It's probably in Categories for the Working Mathematician too.) See also sheet 9, question 1 at the page linked to. For the connection between monos and pullbacks (or epis and pushouts), see 4.1.31. You do have to impose this condition that $\mathcal{D}$ has all (co)limits of the appropriate shape (pushouts in the case of your original question). Kelly came up with some example of an epi in $\mathcal{D}^\mathcal{C}$ that isn't pointwise epi; necessarily, his $\mathcal{D}$ doesn't have all pushouts.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/17953', 'https://mathoverflow.net', 'https://mathoverflow.net/users/78/']}
jdg_82767
stackexchange
llm_judgeable_groundtruth_similarity
8061185
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've always done the simple connection of mysql_connect , mysql_pconnect : $db = mysql_pconnect('*host*', '*user*', '*pass*');if (!$db) { echo("<strong>Error:</strong> Could not connect to the database!"); exit;}mysql_select_db('*database*'); While using this I've always used the simple method to escape any data before making a query, whether that be INSERT , SELECT , UPDATE or DELETE by using mysql_real_escape_string $name = $_POST['name'];$name = mysql_real_escape_string($name);$sql = mysql_query("SELECT * FROM `users` WHERE (`name` = '$name')") or die(mysql_error()); Now I understand this is safe, to an extent! It escapes dangerous characters; however, it is still vulnerable to other attacks which can contain safe characters but may be harmful to either displaying data or in some cases, modifying or deleting data maliciously. So, I searched a little bit and found out about PDO, MySQLi and prepared statements. Yes, I may be late to the game but I've read many, many tutorials (tizag, W3C, blogs, Google searches) out there and not a single one has mentioned these. It seems very strange as to why, as just escaping user input really isn't secure and not good practice to say the least. Yes, I'm aware you could use Regex to tackle it, but still, I'm pretty sure that's not enough? It is to my understanding that using PDO/prepared statements is a much safer way to store and retrieve data from a database when the variables are given by user input. The only trouble is, the switch over (especially after being very stuck in my ways/habits of previous coding) is a little difficult. Right now I understand that to connect to my database using PDO I would use $hostname = '*host*';$username = '*user*';$password = '*pass*';$database = '*database*'$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);if ($dbh) { echo 'Connected to database';} else { echo 'Could not connect to database';} Now, function names are different so no longer will my mysql_query , mysql_fetch_array , mysql_num_rows etc work. So I'm having to read/remember a load of new ones, but this is where I'm getting confused. If I wanted to insert data from say a sign up/registration form, how would I go about doing this, but mainly how would I go about it securely? I assume this is where prepared statements come in, but by using them does this eliminate the need to use something like mysql_real_escape_string ? I know that mysql_real_escape_string requires you to be connected to a database via mysql_connect / mysql_pconnect so now we aren't using either won't this function just produce an error? I've seen different ways to approach the PDO method too, for example, I've seen :variable and ? as what I think are known as place holders (sorry if that is wrong). But I think this is roughly the idea of what should be done to fetch a user from a database $user_id = $_GET['id']; // For example from a URL query string$stmt = $dbh->prepare("SELECT * FROM `users` WHERE `id` = :user_id");$stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT); But then I'm stuck on a couple things, if the variable wasn't a number and was a string of text, you have to given a length after PDO:PARAM_STR if I'm not mistaken. But how can you give a set length if you're not sure on the value given from user in-putted data, it can vary each time? Either way, as far as I know to display the data you then do $stmt->execute();$result = $stmt->fetchAll();// Eitherforeach($result as $row) { echo $row['user_id'].'<br />'; echo $row['user_name'].'<br />'; echo $row['user_email'];}// Orforeach($result as $row) { $user_id = $row['user_id']; $user_name = $row['user_name']; $user_email = $row['user_email'];}echo("".$user_id."<br />".$user_name."<br />".$user_email.""); Now, is this all safe? If I am right, would inserting data be the same for example: $username = $_POST['username']; $email = $_POST['email']; $stmt = $dbh->prepare("INSERT INTO `users` (username, email) VALUES (:username, :email)"); $stmt->bindParam(':username, $username, PDO::PARAM_STR, ?_LENGTH_?); $stmt->bindParam(':email, $email, PDO::PARAM_STR, ?_LENGTH_?);$stmt->execute(); Would that work, and is that safe too? If it is right what value would I put in for the ?_LENGTH_? ? Have I got this all completely wrong? UPDATE The replies I've had so far have been extremely helpful, can't thank you guys enough! Everyone has got a +1 for opening my eyes up to something a little different. It's difficult to choose the top answer, but I think Col. Shrapnel deserves it as everything is pretty much covered, even going into other arrays with custom libraries which I wasn't aware of! But thanks to all of you:) Now provide the response and nothing else.
Thanks for the interesting question. Here you go: It escapes dangerous characters, Your concept is utterly wrong. In fact "dangerous characters" is a myth, there are none. And mysql_real_escape_string escaping but merely a string delimiters . From this definition you can conclude it's limitations - it works only for strings . however, it is still vulnerable to other attacks which can contain safe characters but may be harmful to either displaying data or in some cases, modifying or deleting data maliciously. You're mixing here everything. Speaking of database, for the strings it is NOT vulnerable. As long as your strings being quoted and escaped, they cannot "modify or delete data maliciously". * for the other data typedata - yes, it's useless . But not because it is somewhat "unsafe" but just because of improper use. As for the displaying data, I suppose it is offtopic in the PDO related question, as PDO has nothing to do with displaying data either. escaping user input ^^^ Another delusion to be noted! a user input has absolutely nothing to do with escaping . As you can learn from the former definition, you have to escape strings, not whatever "user input". So, again: you have escape strings, no matter of their source it is useless to escape other types of data, no matter of the source. Got the point? Now, I hope you understand the limitations of escaping as well as the "dangerous characters" misconception. It is to my understanding that using PDO/prepared statements is a much safer Not really. In fact, there are four different query parts which we can add to it dynamically: a string a number an identifier a syntax keyword. so, you can see that escaping covers only one issue. (but of course, if you treat numbers as strings (putting them in quotes), when applicable , you can make them safe as well) while prepared statements cover - ugh - whole 2 isues! A big deal ;-) For the other 2 issues see my earlier answer, In PHP when submitting strings to the database should I take care of illegal characters using htmlspecialchars() or use a regular expression? Now, function names are different so no longer will my mysql_query, mysql_fetch_array, mysql_num_rows etc work. That is another, grave delusion of PHP users , a natural disaster, a catastrophe: Even when utilizing old mysql driver, one should never use bare API functions in their code! One have to put them in some library function for the everyday usage! (Not as a some magic rite but just to make the code shorter, less repetitive, error-proof, more consistent and readable). The same goes for the PDO as well! Now on with your question again. but by using them does this eliminate the need to use something like mysql_real_escape_string? YES. But I think this is roughly the idea of what should be done to fetch a user from a database Not to fetch, but to add a whatever data to the query ! you have to given a length after PDO:PARAM_STR if I'm not mistaken You can, but you don't have to. Now, is this all safe? In terms of database safety there are just no weak spots in this code. Nothing to secure here. for the displaying security - just search this site for the XSS keyword. Hope I shed some light on the matter. BTW, for the long inserts you can make some use of the function I wrote someday, Insert/update helper function using PDO However, I am not using prepared statements at the moment, as I prefer my home-brewed placeholders over them, utilizing a library I mentioned above. So, to counter the code posted by the riha below, it would be as short as these 2 lines: $sql = 'SELECT * FROM `users` WHERE `name`=?s AND `type`=?s AND `active`=?i';$data = $db->getRow($sql,$_GET['name'],'admin',1); But of course you can have the same code using prepared statements as well. * (yes I am aware of the Schiflett's scaring tales)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8061185', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/584711/']}
jdg_82768
stackexchange
llm_judgeable_groundtruth_similarity
91138
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: So I have an alias for "sublime text" http://www.sublimetext.com/docs/2/osx_command_line.html and very often I need to open a file or a folder right from the terminal, easy for a file: subl myfile.html and for a folder subl /Users/me But how can I use 'pwd' command to open current directory in sublime? Is there a way to pipe it in? Now provide the response and nothing else.
$(pwd) or, you can use backticks, like `pwd` So: subl `pwd` Either way, what happens is the command pwd gets executed, then its return text gets passed as the command-line. A good way to see what's happening, assuming you're using bash, is to issue set -x then run your command. As this example, where subl is aliased to echo shows, the result of pwd is passed on the command-line to the expanded alias (lines beginning with + indicate the actual command being executed): $ alias subl=echo$ mkdir /tmp/abc$ cd /tmp/abc$ set -x$ subl `pwd`++ pwd+ echo /tmp/abc/tmp/abc$ (When you're done, you can stop printing commands by issuing set +x .)
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/91138', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/43520/']}
jdg_82769
stackexchange
llm_judgeable_groundtruth_similarity
26994354
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 implement feature in my Andorind app which allows to play two different synthesized languages in current Acitivity - for instance having two buttons Say English and Say French I've tried to do it in two following ways but both of them works ineffectively because there is long delay before sound plays: first approach: create single instance of TTS and change language by setLocale method depending on what language has to be played. Unfortunately switching between languages by setLocale is time consuming which has impact on reaction after button is clicked second approach: create two instances of TTS each for respective language. Unfortunately delay occurs here as well and there is no difference between the first solution. Can you please help to solve this annoying problem? Now provide the response and nothing else.
Approach #1 For a N x 2 sized points/pixels array, you can avoid permute as suggested in the other solution by Luis , which could slow down things a bit, to have a kind of "permute-unrolled" version of it and also let's bsxfun work towards a 2D array instead of a 3D array, which must be better with performance. Thus, assuming clusters to be ordered as a N x 2 sized array, you may try this other bsxfun based approach - %// Get a's and b'sim_a = im(:,:,2);im_b = im(:,:,3);%// Get the minimum indices that correspond to the cluster IDs[~,idx] = min(bsxfun(@minus,im_a(:),clusters(:,1).').^2 + ... bsxfun(@minus,im_b(:),clusters(:,2).').^2,[],2);idx = reshape(idx,size(im,1),[]); Approach #2 You can try out another approach that leverages fast matrix multiplication in MATLAB and is based on this smart solution - d = 2; %// dimension of the problem sizeim23 = reshape(im(:,:,2:3),[],2);numA = size(im23,1);numB = size(clusters,1);A_ext = zeros(numA,3*d);B_ext = zeros(numB,3*d);for id = 1:d A_ext(:,3*id-2:3*id) = [ones(numA,1), -2*im23(:,id), im23(:,id).^2 ]; B_ext(:,3*id-2:3*id) = [clusters(:,id).^2 , clusters(:,id), ones(numB,1)];end[~, idx] = min(A_ext * B_ext',[],2); %//'idx = reshape(idx, size(im,1),[]); %// Desired IDs What’s going on with the matrix multiplication based distance matrix calculation? Let us consider two matrices A and B between whom we want to calculate the distance matrix. For the sake of an easier explanation that follows next, let us consider A as 3 x 2 and B as 4 x 2 sized arrays, thus indicating that we are working with X-Y points. If we had A as N x 3 and B as M x 3 sized arrays, then those would be X-Y-Z points. Now, if we have to manually calculate the first element of the square of distance matrix, it would look like this – first_element = ( A(1,1) – B(1,1) )^2 + ( A(1,2) – B(1,2) )^2 which would be – first_element = A(1,1)^2 + B(1,1)^2 -2*A(1,1)* B(1,1) + ... A(1,2)^2 + B(1,2)^2 -2*A(1,2)* B(1,2) … Equation (1) Now, according to our proposed matrix multiplication, if you check the output of A_ext and B_ext after the loop in the earlier code ends, they would look like the following – So, if you perform matrix multiplication between A_ext and transpose of B_ext , the first element of the product would be the sum of elementwise multiplication between the first rows of A_ext and B_ext , i.e. sum of these – The result would be identical to the result obtained from Equation (1) earlier. This would continue for all the elements of A against all the elements of B that are in the same column as in A . Thus, we would end up with the complete squared distance matrix. That’s all there is!! Vectorized Variations Vectorized variations of the matrix multiplication based distance matrix calculations are possible, though there weren't any big performance improvements seen with them. Two such variations are listed next. Variation #1 [nA,dim] = size(A);nB = size(B,1);A_ext = ones(nA,dim*3);A_ext(:,2:3:end) = -2*A;A_ext(:,3:3:end) = A.^2;B_ext = ones(nB,dim*3);B_ext(:,1:3:end) = B.^2;B_ext(:,2:3:end) = B;distmat = A_ext * B_ext.'; Variation #2 [nA,dim] = size(A);nB = size(B,1);A_ext = [ones(nA*dim,1) -2*A(:) A(:).^2];B_ext = [B(:).^2 B(:) ones(nB*dim,1)];A_ext = reshape(permute(reshape(A_ext,nA,dim,[]),[1 3 2]),nA,[]);B_ext = reshape(permute(reshape(B_ext,nB,dim,[]),[1 3 2]),nB,[]);distmat = A_ext * B_ext.'; So, these could be considered as experimental versions too.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26994354', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4265323/']}
jdg_82770
stackexchange
llm_judgeable_groundtruth_similarity
658444
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 teach myself some numerical methods and having more issues than expected trying to solve $$y'' = -y$$ with initial conditions $y'(0) = 0$ and $y(0) = 1$. As I understand the problem, based on the information found here Solve a second order DEQ using Euler's method in MATLAB , I made the substitution $u = y'$ and reduced the problem to the following coupled system: \begin{align*}\begin{cases}y' = u;\\u' = -y.\end{cases}\end{align*}So in this case, since $y'(0) = 0$, this implies $u=0$ and $y(0) = 1$ implies $u'(0) = -1$. With these initial conditions, I have the vector $[y_{0},u_{0}] = [0,-1]^{T}$. I tried to use a forward Euler method on this system using \begin{align*}y_{n+1} = y_{n} + hu_{n}\\u_{n+1} = u_{n} - hy_{n}\end{align*}with $y_{0} = 0$, $u_{0} = -1$ but at this point I am not sure how I can extract the solution to my original differential equation. I am storing my $y_{i}$'s and $u_{i}'s$ in a $2\times n$ matrix where the first row contains $[y_{0},y_{1},y_{2},\dots, y_{n}]$ and the second row contains the same information for $u_{i}$'s in the same manner. It appears to me, that my matrix should contain the solution to my original differential equation in the first row, but this cannot be the case because the solution to the differential equation is $y(t) = \cos(t)$, and $\cos(t_{0}) = \cos(0) = 1\neq 0$. Similarly, it cannot be the second row because $\cos(0) = 1 \neq -1$. If I change the initial condition to $[y_{0},u_{0}]^{T} =[0,1]$ and I take the solution to be the second row corresponding to the $u_{i}$'s, it looks like I get a reasonable answer, but I cannot understand whether this is simply a numerical fluke or if I made a flawed calculation. Now provide the response and nothing else.
We can also find the differential equation by just differentiating under the integral sign, after rewriting a little: $$F(x) = \int_0^\infty \frac{\cos (xt)}{1+t^2}\,dt$$ is continuous by the dominated convergence theorem, with $F(0) = \frac{\pi}{2}$ known and $\lvert F(x)\rvert \leqslant \frac{\pi}{2}$. For $x \neq 0$, we can integrate by parts, $$\begin{align}F(x) &= \left[\frac{1}{x}\cdot \frac{\sin (xt)}{1+t^2}\right]_0^\infty + \frac{2}{x} \underbrace{\int_0^\infty \frac{t\sin (xt)}{(1+t^2)^2}\,dt}_{G(x)}\\&= \frac{2}{x}G(x).\end{align}$$ $G(x)$ can be differentiated under the integral sign by the dominated convergence theorem, and $$G'(x) = \int_0^\infty \frac{t^2\cos (xt)}{(1+t^2)^2}\,dt = F(x) - \underbrace{\int_0^\infty \frac{\cos (xt)}{(1+t^2)^2}\,dt}_{H(x)}.$$ $H(x)$ can also be differentiated under the integral sign by the dominated convergence theorem, and $$H'(x) = -G(x).$$ Thus $$\begin{align}F'(x) &= -\frac{2}{x^2}G(x) + \frac{2}{x}G'(x)\\&= -\frac{1}{x}F(x) + \frac{2}{x}\left(F(x) - H(x)\right)\\&= \frac{1}{x}F(x) - \frac{2}{x}H(x),\quad\text{and}\\F''(x) &= -\frac{1}{x^2}F(x) + \frac{1}{x} F'(x) + \frac{2}{x^2}H(x) - \frac{2}{x}H'(x)\\&= -\frac{1}{x^2}F(x) + \frac{1}{x^2}F(x) - \frac{2}{x^2}H(x) + \frac{2}{x^2}H(x) + \frac{2}{x}G(x)\\&= \frac{2}{x}G(x)\\&= F(x).\end{align}$$ From the boundedness of $F$ and the differential equation together with the initial value $F(0)$ we then obtain $$F(x) = \frac{\pi}{2}e^{-\lvert x\rvert}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/658444', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/102435/']}
jdg_82771
stackexchange
llm_judgeable_groundtruth_similarity
60561573
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: use futures::{future, Future};fn test() -> Box<dyn Future<Output = bool>> { Box::new(future::ok::<bool>(true))}async fn async_fn() -> bool { let result: bool = test().await; return result;}fn main(){ async_fn(); println!("Hello!");} Playground Error: error[E0277]: the trait bound `dyn core::future::future::Future<Output = bool>: std::marker::Unpin` is not satisfied --> src/main.rs:8:24 |8 | let result: bool = test().await; | ^^^^^^^^^^^^ the trait `std::marker::Unpin` is not implemented for `dyn core::future::future::Future<Output = bool>` | = note: required because of the requirements on the impl of `core::future::future::Future` for `std::boxed::Box<dyn core::future::future::Future<Output = bool>>` Now provide the response and nothing else.
According to the implementation : impl<F> Future for Box<F>where F: Unpin + Future + ?Sized, Boxed futures only implement the Future trait when the future inside the Box implements Unpin . Since your function doesn't guarantee that the returned future implements Unpin , your return value will be considered to not implement Future . You'll not able to await it because your type is basically not a Future . The solution from @Stargateur, adding an explicit type boundary to the signature, works ( Playground ): fn test() -> Box<dyn Future<Output = Result<bool, ()>> + Unpin> If you are using futures-rs, there is a helper type BoxFuture . You can use BoxedFuture without explicitly stating Unpin : use futures::future::BoxFuture;fn test() -> BoxFuture<'static, Result<bool, ()>> { Box::pin(async { Ok(true) })} Playground
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60561573', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6360083/']}
jdg_82772
stackexchange
llm_judgeable_groundtruth_similarity
1680250
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 = \{4~\text{digit integers}~X~\text{having no}~0~\text{such that}~X~\text{has exactly one}~1\}$. Let $B = \{4~\text{digit integers}~X~\text{having no}~0~\text{such that}~X~\text{has exactly one}~5\}$. Let $A+B = \{4~\text{digit integers}~X~\text{having no}~0\}$. Then $|C| = |A| + |B| - |A + B|$. Set A has $4C1 \cdot 8 \cdot 8 \cdot 8 = 2048$ elements. Set B has $4C1 \cdot 8 \cdot 8 \cdot 8 = 2048$ elements. Set $A+B$ has $8 \cdot 8 \cdot 8 \cdot 8 = 4096$ elements. Therefore $|A| + |B| - |A + B| = 2048 + 2048 - 4096 = 0$. I think my steps are correct, but doubt that I got the correct answer. Now provide the response and nothing else.
Consider the function $$f: K \times L \rightarrow \mathbb{R}$$$$(x,y) \mapsto |x-y|.$$ $f=\vert\cdot\vert \circ -|_{K \times L},$ where $-: \mathbb{R} \times \mathbb{R}$ is the subtraction and $| \cdot|$ is the module function. Hence, $f$ is the composition of continuous functions, therefore continuous. It is clear that $\inf_{x \in K \times L} f=d$. It is also clear, since those sets are disjoint, that $f>0$. Since $f$ is a real continuous function in a compact set, it achieves its infimum in its domain. Therefore, $d>0$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1680250', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_82773
stackexchange
llm_judgeable_groundtruth_similarity
2332847
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 a customized ListView (or similar) which will behave like a closed (circular) one: scrolling down - after the last item was reached the first begins (.., n-1, n, 1, 2, ..) scrolling upward - after the first item was reached the last begins (.., 2, 1, n, n-1, ..) It sounds simple conceptually but, apparently, there is no straightforward approach to do this.Can anyone point me to the right solution ?Thank you ! I have already received an answer (from Streets Of Boston on Android-Developers google groups), but it sounds somehow ugly :) - I did this by creating my own list-adapter (subclassed from BaseAdapter). I coded my own list-adapter in such a way that its getCount() method returns a HUUUUGE number. And if item 'x' is selected, then this item corresponds to adapter position='adapter.getCount()/2+x' And for my adapter's method getItem(int position), i look in my array that backs up the adapter and fetch the item on index: (position-getCount()/2) % myDataItems.length You need to do some more 'special' stuff to make it all work correctly, but you get the idea. In principle, it is still possible to reach the end or the beginning of the list, but if you set getCount() to around a million or so, this is hard to do :-) Now provide the response and nothing else.
My colleague Joe, and I believe we have found a simpler way to solve the same problem. In our solution though instead of extending BaseAdapter we extend ArrayAdapter. The code is as follows : public class CircularArrayAdapter< T > extends ArrayAdapter< T >{ public static final int HALF_MAX_VALUE = Integer.MAX_VALUE/2; public final int MIDDLE; private T[] objects; public CircularArrayAdapter(Context context, int textViewResourceId, T[] objects) { super(context, textViewResourceId, objects); this.objects = objects; MIDDLE = HALF_MAX_VALUE - HALF_MAX_VALUE % objects.length; } @Override public int getCount() { return Integer.MAX_VALUE; } @Override public T getItem(int position) { return objects[position % objects.length]; } } So this creates a class called CircularArrayAdapter which take an object type T (which may be anything) and uses it to create an array list. T is commonly a string though may be anything. The constructor is the same as is for ArrayAdapter though initializes a constant called middle. This is the middle of the list. No matter what the length of the array MIDDLE can be used to center the ListView in the mid of the list. getCount() is overrides to return a huge value as is done above creating a huge list. getItem() is overrides to return the fake position on the array. Thus when filling the list the list is filled with objects in a looping manner. At this point CircularArrayAdapter simply replaces ArrayAdapter in the file creating the ListView. To centre the ListView the fallowing line must be inserted in your file creating the ListView after the ListView object has been initialised: listViewObject.setSelectionFromTop(nameOfAdapterObject.MIDDLE, 0); and using the MIDDLE constant previously initialized for the list the view is centered with the top item of the list at the top of the screen. : ) ~ Cheers, I hope this solution is useful.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2332847', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/281076/']}
jdg_82774
stackexchange
llm_judgeable_groundtruth_similarity
611135
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: Background (feel free to skip this part) Suppose we want to $k$-partition all the positive integers up to (and including) some integer $N$. This partition should divide the numbers into $k$ sets, such that each set has the same sum. For example, for $N=4$, there is one possible $2$-partition: $\{1,4\},\{2,3\}$ (since the sum of the numbers in each is $5$). For another example, with $N=7$ there are multiple possible 2-partitions, one of which is: $\{1,2,4,7\},\{3,5,6\}$ (since the sum of the numbers in each is $14$). We can see that in order for any $N$ to have a valid $2$-partition, we need $\sum_{i=1}^N i = \frac{N(N+1)}{2}$ to be divisible by $2$, meaning$$N(N+1) \text{ divisible by 4} \Rightarrow N \text{ or } N+1 \text{ divisible by 4}$$ It isn’t too difficult to determine similar requirements on $N$ for the existence of other $k$-partitions:$$k=3: \quad N(N+1) \text{ divisible by 6} \Rightarrow N \text{ or } N+1 \text{ divisible by 3}$$$$k=4: \quad N(N+1) \text{ divisible by 8} \Rightarrow N \text{ or } N+1 \text{ divisible by 8}$$$$\vdots$$ It might be interesting to investigate how many $k$-partitions there are for any given $N$, but I’m more interested in the problem of imposing restrictions on the partitions (which makes it more difficult to find the $N$ for which they exist). The problem Let’s say we want (what I have dubbed) a consecutive $k$-partition. That is, divide the positive integers up to (and including) $N$ into $k$ sets, such that each set has the same sum and the sets are ordered, with the largest number in each set being 1 less than the smallest number in the next set. (Clearly, if there exists a consecutive $k$-partition for $N$, there is only one such partition.) In the case $k=2$, a consecutive $2$-partition exists for $N$ if we can find an $a$ such that:$$1+2+\ldots+a = (a+1)+(a+2)+\ldots+N$$ For example, for $N=3$ there is one possible consecutive $2$-partition: $\{1,2\},\{3\}$. The next $N$ for which there exists a consecutive $2$-partition is $N=20$, where $a=14$ and we have:$$1+2+\ldots+14=105=15+16+\ldots+20$$ In general, a consecutive $2$-partition exists for $N$ if we can find an $a$ such that$$\frac{a(a+1)}{2} = \frac{N(N+1)}{2} - \frac{a(a+1)}{2},$$which by the quadratic formula means we need$$a = \frac{\sqrt{2N^2 + 2N + 1}-1}{2}$$to be a positive integer. Since the root term will always be odd, the top will always be divisible by $2$, so we just need$$a = 2N^2 + 2N + 1$$to be a square number. Interesting note: We want $a = Z^2$ for some positive integer $Z$, and we can write $a = 2N^2 + 2N + 1 = N^2 + (N+1)^2 = Z^2$, and the rightmost equation is precisely the set of Pythagorean triples $(X, X+1, Z)$. Using this formula, the next $N$ after $3$ then $20$ seems to be $119$, then $696$, then $4059$, then $23660$. Clearly these grow farther apart, and a brute-force iteration over all the positive integers will be very slow in finding these. Is there a formula to find $N$s for which this $a$ exists? Or, as a more theoretical question: What can we know about the set of these $N$s (how are they distributed among the positive integers)? This gets more tricky with consecutive $3$-partitions. For any $N$, we need to find a $b$ and $c$ such that$$\frac{b(b+1)}{2} = \frac{c(c+1)}{2} - \frac{b(b+1)}{2} = \frac{N(N+1)}{2} - \frac{c(c+1)}{2},$$which means we need both of the following to be positive integers:$$b = \frac{\sqrt{12b^2 + 12b + 9} – 3}{6}$$$$c = \frac{\sqrt{24b^2 + 24b + 9} - 3}{6}$$Multiplying the top and bottom by $\frac{1}{3}$ and noting that the top will then always be divisible by $2$, we just need$$b = \frac{4}{3}N^2 + \frac{4}{3}N + 1$$$$c = \frac{8}{3}N^2 + \frac{8}{3}N + 1$$to be square numbers. I tested the above formulas on the first $25000$ positive integers, and haven’t found any $N$s with a consecutive $3$-partition. Are there any? Summary of the questions Is there a formula to find $N$s for which a consecutive $2$-partition exists (without needing to iterate and see if there exists an integer $a$)? Are there any $N$s for which a consecutive $3$-partition exists? What about for consecutive $4$-partitions, or $5$, etc.? For any $k$, what do we know (about the distribution among the positive integers) of the set of $N$s for which a consecutive $k$-partition exists? I’m fascinated by this topic, and any insights you can provide (perhaps using knowledge gleaned from more advanced number theory) would be helpful! UPDATE on question 2 For consecutive $3$-partitions, it seems like $N$s that satisfy the conditions on $b$ and $c$ can be expressed by recursive formulas:$$\text{condition on } b \Rightarrow N_{i+2} = 4N_{i+1} - N_i + 1 \text{, with } N_0=0 \text{ and } N_1 = 2$$$$\text{condition on } c \Rightarrow N'_{i+2} = 10N'_{i+1} - N'_i + 4 \text{, with } N'_0=0 \text{ and } N'_1 = 5$$ Side question: Is there a way to prove this? By iterating $i$, we can generate $N$s which satisfy the first condition, and $N'$s which satisfy the second condition. I have done this to generate $N$ and $N'$ all the way up to $10^{300}$, and there are none which satisfy both conditions! Does this make it very likely that no consecutive $3$-partitions exist? These recursive formulas can also be expressed in closed form:$$N_i = \frac{1}{4} \left((1+\sqrt{3})(2+\sqrt{3})^i + (1-\sqrt{3})(2-\sqrt{3})^i - 2 \right)$$$$N'_i = \frac{1}{4} \left((1+\frac{\sqrt{6}}{2})(5+2\sqrt{6})^i + (1-\frac{\sqrt{6}}{2})(5-2\sqrt{6})^i - 2 \right)$$So the question becomes:$$\{N_i \mid i \in \mathbb{Z^+}\} \cap \{N'_i \mid i \in \mathbb{Z^+}\} = \emptyset?$$ Now provide the response and nothing else.
[ Edited to include the connection with Euler's theorem thatthere's no nonconstant $4$-term arithmetic progression of squares; briefly,since $1$ and $4(N^2+N)+1 = (2N+1)^2$ are always squares, $(1,b,c,(2N+1)^2)$is such a $4$-term progression, so $b=c=1$ and $N^2+N=0$ for any rationalsolution. It seems that the same deals with all $k \geq 3$. ] The Diophantine equations$$ B^2 = b = \frac43(N^2+N) + 1 $$$$ C^2 = c = \frac83(N^2+N) + 1 $$have no simultaneous solution in integers other than the eight trivialsolutions with $N=0,-1$, $B = \pm 1$, $C = \pm 1$. Such a resultcan be tricky to prove in general, but here we are somewhat luckyin that these are the only rational solutions, and moreover$N=0$ and $N=-1$ are the only rational numbers for which the product $bc$is a square. This can be proved using Fermat's "descent" method;the calculations, though elementary, may be somewhat laboriousto carry out by hand, but happily this is no longer necessarythanks to existing tables and software. In general, if $P,Q$ are quadratic polynomials such that $PQ$ hasfour distinct factors then the simultaneous Diophantine equations$B^2 = P(N)$, $C^2 = Q(N)$ define an elliptic curve. A fundamental 1929theorem of Siegel assures that such a curve has only finitely manyintegral points. The proof is "ineffective" and does not in generalgive an algorithm guaranteed to determine all solutions. Latertheoretical and computational advances do provide such an algorithm,which is feasible at least for $P,Q$ with small coefficients;but the resulting proof is very far from elementary, and it can behard to predict in any given case how hard it is to give an elementary proof. In the present case, though,the elliptic curve already has finitely many rational points,as does the "isogenous" curve $A^2 = P(N) Q(N)$. We bring this curve$$A^2 = \left( \frac43(N^2+N) + 1 \right) \left( \frac83(N^2+N) + 1 \right)$$into standard Weierstrass form in the usual way starting from therational point $(N,A) = (0,1)$: the Taylor expansion of $A$ about $N=0$starts $1 + 2N + O(N^2)$, so for $N\neq 0$ we can write$$A = 1 + 2N + rN^2$$for some rational $r$, and divide the resulting equation by $N^2$ to get$$(9r^2-32)N^2 + (36r-64)N + (18r-32) = 0.$$This equation is quadratic in $N$, and thushas rational roots iff its discriminant w.r.t. $N$ is a square.That discriminant factors as $-72(r-2)r(9r-16)$; taking $r=-2x/9$and removing a factor $(8/3)^2$ we find that$$y^2 = x (x+8) (x+9) = x^3 + 17 x^2 + 72 x$$for some rational $x,y$. This elliptic curve turns out to haveconductor $24$, so it already appears in Tingley's "Antwerp Tables"of modular elliptic curves of conductor at most $200$;it turns out to have label 24C here .We find that it has rank zero, and only four rational points, whichmust be the point at infinity and the three "$2$-torsion points" with $y=0$.Alternatively, we can input [0,17,0,72,0] to Cremona's program mwrank to find that the curve has rank zero, and then find its torsion pointswith gp . Either way, we finish by retracing our stepsto find that each of $r=0,2,16/9$corresponds to one of the known solutions with $N=0$ or $N=-1$(in each case a double root of the quadratic in $N$), so we are done. [Thanks to Will Jagy for calling my attention to this question.] Added later : It turns out that this $2$-descent calculationlong predates the Antwerp tables: it is essentially equivalent toEuler's proof of his theorem that there is no nonconstant$4$-term arithmetic progression of squares. (See for instance KeithConrad's exposition , which states that Euler proved the result in 1780,answering a question "first raised by Fermat in 1640".)Indeed if $b$ and $c$ are squares then$$1, \\frac43(N^2+N)+1, \\frac83(N^2+N)+1, \4(N^2+N)+1$$is such a progression (the last term being $(2N+1)^2$,so it is constant by Euler, whence $b=c=1$ and we are done. jamaicanworm writes in a comment that for general $k \geq 3$the problem is whether there exists a positive integer $N$such that $c_i := \frac{4(k-i)}{k}(N^2+N) + 1$ is a squarefor each $i=1,2,\ldots,k-1$. These $c_i$ form an arithmetic progression,and extending it by one term in each direction again yields the squares$c_k = 1$ and $c_0 = (2N+1)^2$. Hence we have an arithmetic progressionof $k+1$ squares, and again Euler's theorem shows that even if we allow$N$ to be rational the only examples are the trivial ones with $N^2+N=0$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/611135', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/23390/']}
jdg_82775
stackexchange
llm_judgeable_groundtruth_similarity
31907212
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In the terminal, I executed a main parent process which will fork a child process. In both the parent and child processes I implemented a SIGINT signal handler. So when I press "ctrl+c", will both the handlers be called at the same time? Or do I need to call the child process's signal handler explicitly in the parent process's handler? I looked up this post: How does Ctrl-C terminate a child process? which says that " The SIGINT signal is generated by the terminal line discipline, and broadcast to all processes in the terminal's foreground process group ". I just didn't quite understand what does "foreground process group" means. Thanks, Now provide the response and nothing else.
In both the parent and child processes I implemented a SIGINT signal handler. So when I press "ctrl+c", will both the handlers be called at the same time? Yes, they both will receive SIGINT . Or do I need to call the child process's signal handler explicitly in the parent process's handler? "Calling" another process' signal handler doesn't make sense. If the both the process have a handler installed then they will be called once they receive the signal SIGINT . I just didn't quite understand what does "foreground process group" means. Typically, a process associated with a controlling terminal is foreground process and its process group is called foreground process group. When you start a process from the command line, it's a foreground process: E.g. $ ./script.sh # foreground process$ ./script & # background process I suggest you read about tty and The TTY demystified for a detailed explanation.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31907212', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/980818/']}
jdg_82776
stackexchange
llm_judgeable_groundtruth_similarity
1328496
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Simplified version of the code: Foo.h: class Foo { private: class Bar { // ... }; typedef std::map<int, Bar> mapType; mapType _map; public: void method(mapType::iterator it);}; Foo.cpp: void Foo::method(mapType::iterator it) { // ... notMethod(it);}void notMethod(mapType::iterator it) { // ...} Unsurprisingly, I get the error 'mapType' is not a class or namespace name in VS2008 at notMethod 's definition. Is there any (elegant) way that I can avoid having to type out std::map<int, Bar> everywere in notMethod 's definition without turning notMethod into a method? Now provide the response and nothing else.
Use void notMethod(Foo::mapType::iterator it) { // ...} and put the typedef in the public section of Foo 's class declaration. Edit: If you want to avoid this, you can make notMethod a friend (as suggested by DanDan), use sbi's template solution, or make notMethod a private static member function of Foo (which generates exactly the same code as if it was a free non-member function). Which solution is the most appropriate really depends on what notMethod does. If notMethod uses Bar and Bar really only makes sense in the context of Foo 's internal implementation, I would make notMethod a private static member function, since it's part of Foo 's internals. If notMethod was an operator that needs to take a non- Foo as its first argument (meaning that it can't be a member of Foo ), and if I wanted to keep Bar private, I would make the operator a friend. If notMethod implements a generic operation on iterators, I would make it a template function. If Bar is a class that might be of interest to Foo 's clients, I would make Bar and the typedef public and use the solution I suggested originally.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1328496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/143642/']}
jdg_82777
stackexchange
llm_judgeable_groundtruth_similarity
13534654
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I execute this code: [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(showButtons) userInfo:nil repeats:NO]; do I need to nil it or release it, ot whatever for memory management? I am using ARC Now provide the response and nothing else.
Yes, NSTimer will maintain a strong reference to the target , which can cause (especially in repeating timers) strong reference cycles (a.k.a. retain cycles). In your example, though, the timer does not repeat, and is delayed only 0.5, so worst case scenario, you will have a strong reference cycle that will automatically resolve itself in 0.5 seconds. But a common example of an unresolved strong reference cycle would be to have a UIViewController with a NSTimer property that repeats, but because the NSTimer has a strong reference to the UIViewController , the controller will end up being retained. So, if you're keeping the NSTimer as an instance variable, then, yes, you should invalidate it, to resolve the strong reference cycle. If you're just calling the scheduledTimerWithTimeInterval , but not saving it to an instance variable (as one might infer from your example), then your strong reference cycle will be resolved when the NSTimer is complete. And, by the way, if you're dealing with repeating NSTimers , don't try to invalidate them in dealloc of the owner of the NSTimer because the dealloc obviously will not be called until the strong reference cycle is resolved. In the case of a UIViewController , for example, you might do it in viewDidDisappear . By the way, the Advanced Memory Management Programming Guide explains what strong reference cycles are. Clearly, this is in a section where they're describing the proper use of weak references, which isn't applicable here (because you have no control over the fact that NSTimer uses strong references to the target), but it does explain the concepts of strong reference cycles nicely. If you don't want your NSTimer to keep a strong reference to self , in macOS 10.12 and iOS 10, or later, you can use the block rendition and then use the weakSelf pattern: typeof(self) __weak weakSelf = self;[NSTimer scheduledTimerWithTimeInterval:0.5 repeats:false block:^(NSTimer * _Nonnull timer) { [weakSelf showButtons];}]; By the way, I notice that you're calling showButtons . If you're trying to just show some controls on your view, you could eliminate the use of the NSTimer altogether and do something like: self.button1.alpha = 0.0;self.button2.alpha = 0.0;[UIView animateWithDuration:0.25 delay:0.5 options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionAllowUserInteraction animations:^{ self.button1.alpha = 1.0; self.button2.alpha = 1.0; } completion:nil]; This doesn't suffer the retain issues of NSTimer objects, and performs both the delay as well as the graceful showing of the button(s) all in one statement. If you're doing additional processing in your showButtons method, you can put that in the completion block.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13534654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1191072/']}
jdg_82778
stackexchange
llm_judgeable_groundtruth_similarity
7269811
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've loaded few forms using .load() to different DIVs. The loaded file looks like the following example. <div id="block_id-299"> <div id="content"> <form name="form1" method="post"> <input type="submit" name="field1" value="Submit"> </form> </div></div> And now I am trying to retrieve submitted form's name and later, it's values using .serialize() . I was using $('form').submit(function(){ ... } but since I am loading the form dynamically, this does not work anymore. Any help? PS: The event can be catched using $(document).submit(function(){ but how to get form's name and/or ID? Now provide the response and nothing else.
You can do this with $().delegate: $(document).delegate('form', 'submit', function(event) { var $form = $(this); var id = $form.attr('id'); var data = $form.serialize(); // ...}); This works even on forms added after you called delegate(). This works by listening for submit events the bubbled up to document , and by testing if the even originates from a form element. This is similar to $('form').live('click', ...) , but doesn't initially executes the selector. See .delegate() and .live() documentation.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7269811', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/200268/']}
jdg_82779
stackexchange
llm_judgeable_groundtruth_similarity
9214754
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I run this: /([^\/]+)+/g.exec('/a/b/c/d'); I get this: ["a", "a"] But if I run this: '/a/b/c/d'.match(/([^\/]+)+/g); Then I get the expected result of this: ["a", "b", "c", "d"] What's the difference? Now provide the response and nothing else.
exec with a global regular expression is meant to be used in a loop, as it will still retrieve all matched subexpressions. So: var re = /[^\/]+/g;var match;while (match = re.exec('/a/b/c/d')) { // match is now the next match, in array form.}// No more matches. String.match does this for you and discards the captured groups.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9214754', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/763074/']}
jdg_82780
stackexchange
llm_judgeable_groundtruth_similarity
47910127
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 render() function for my simple category list page . Recently I added pagination for my FlatList View so when the user scrolls to the bottom, onEndReached is called in a certain point( onEndReachedThreshold value length from the bottom), and it will fetch the next categories and concatenate the categories props. But my problem is onEndReached is called when render() is called In other words, FlatList's onEndReached is triggered before it reach the bottom. Am I putting wrong value for onEndReachedThreshold? Do you see any problem? return ( <View style={{ flex:1 }}> <FlatList data={this.props.categories} renderItem={this._renderItem} keyExtractor={this._keyExtractor} numColumns={2} style={{flex: 1, flexDirection: 'row'}} contentContainerStyle={{justifyContent: 'center'}} refreshControl={ <RefreshControl refreshing = {this.state.refreshing} onRefresh = {()=>this._onRefresh()} /> } // curent value for debug is 0.5 onEndReachedThreshold={0.5} // Tried 0, 0.01, 0.1, 0.7, 50, 100, 700 onEndReached = {({distanceFromEnd})=>{ // problem console.log(distanceFromEnd) // 607, 878 console.log('reached'); // once, and if I scroll about 14% of the screen, //it prints reached AGAIN. this._onEndReachedThreshold() }} /> </View>) UPDATE I fetch this.props.categories data here componentWillMount() { if(this.props.token) { this.props.loadCategoryAll(this.props.token); } } Now provide the response and nothing else.
Try to implement onMomentumScrollBegin on FlatList : constructor(props) { super(props); this.onEndReachedCalledDuringMomentum = true;} ... <FlatList ... onEndReached={this.onEndReached.bind(this)} onEndReachedThreshold={0.5} onMomentumScrollBegin={() => { this.onEndReachedCalledDuringMomentum = false; }}/> and modify your onEndReached onEndReached = ({ distanceFromEnd }) => { if(!this.onEndReachedCalledDuringMomentum){ this.fetchData(); this.onEndReachedCalledDuringMomentum = true; }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/47910127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7820956/']}
jdg_82781
stackexchange
llm_judgeable_groundtruth_similarity
135444
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: A homework problem asked to find a short exact sequence of abelian groups $$0 \rightarrow A \longrightarrow B \longrightarrow C \rightarrow 0$$ such that $B \cong A \oplus C$ although the sequence does not split. My solution to this is the sequence $$0 \rightarrow \mathbb{Z} \overset{i}{\longrightarrow}\mathbb{Z} \oplus (\mathbb{Z}/2\mathbb{Z})^{\mathbb{N}} \overset{p}{\longrightarrow}(\mathbb{Z}/2\mathbb{Z})^{\mathbb{N}} \rightarrow 0$$ with $i(x)=(2x,0,0,\dotsc)$ and $p(x,y_1,y_2,\dotsc)=(x+2\mathbb{Z},y_1,y_2,\dotsc)$ . My new questions: Is there an example with finite/finitely generated abelian groups? If the answer to (1) is negative, will it help to pass to general $R$ -modules for some ring $R$ ? Now provide the response and nothing else.
There is no counterexample with $A,B,C$ finitely generated abelian groups. There is, more generally, no counterexample with $A,B,C$ finitely generated modules over any noetherian ring $R$. To see this, consider the exact sequence $$0\rightarrow\mathrm{Hom}(C,A)\rightarrow\mathrm{Hom}(B,A)\rightarrow \mathrm{Hom}(A,A).$$ The original sequence splits if and only if this sequence is exact on the right. If $A$, $B$ and $C$ are of finite length as modules, this follows immediately just by counting lengths. Otherwise, it's enough to show exactness after localizing and completing at an arbitrary prime $P$, and for this it's enough to show exactness after tensoring with $R/P^n$, and for this you can assume the lengths are finite, which is the case we've already dealt with.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/135444', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/3533/']}
jdg_82782
stackexchange
llm_judgeable_groundtruth_similarity
52986691
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using pytest 3.9 on Python 3.6 and did not find the answer to this question in pytest docs. I have some test cases which involves checking if a given key is in a dictionary. When that key is not there, pytest shows the failure, but it somehow "reduces" the dictionary value, showing only some of its values.Same thing happens when outputting local variables values (dicts and lists are reduced so that only some values are shown). Is there any way to disable that "value minimization" and show the full variable value instead ? Example test case that shows this behavior: def test_in(): d = {key: key for key in range(500)} # makes d sufficiently big to trigger minimization of output assert 1000 in d # this will fail shows: ================ FAILURES ===========________________ test_in ___________def test_in(): d = {key: key for key in range(500)}> assert 1000 in d E assert 1000 in {0: 0, 1: 1, 2: 2, 3: 3, ...} I would like to have the full value of d instead of that abbreviated value. This would help me analyze some of the failure cases. Now provide the response and nothing else.
Using --showlocals If you just need the full variables printing, you can use the --showlocals option, combined with the verbose output. Example: $ pytest -vvl==================================== test session starts ====================================platform darwin -- Python 3.6.6, pytest-3.9.1, py-1.5.4, pluggy-0.7.1cachedir: .pytest_cacherootdir: /Users/hoefling/projects/private/stackoverflow, inifile:collected 1 itemtest_spam.py::test_in FAILED [100%]========================================= FAILURES ==========================================__________________________________________ test_in __________________________________________ def test_in(): d = {key: key for key in range(500)} # makes d sufficiently big to trigger minimization of output> assert 1000 in d # this will failE assert 1000 in {0: 0, 1: 1, 2: 2, 3: 3, ...}d = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, etc. Custom pytest_assertrepr_compare hook Another option is to redefine the specific assertion messages via pytest_assertrepr_compare hook. In the example below, I redefine assertion for el in dict checks. This will be automatically applied to all matching assertions in all tests: # conftest.pydef pytest_assertrepr_compare(op, left, right): if op == 'in' and isinstance(right, dict): return [f'{left} in {right}'] Running pytest -vv will now yield the full dict as no no truncating is done in custom hook: $ pytest -vv================================== test session starts ===================================platform darwin -- Python 3.6.6, pytest-3.9.1, py-1.5.4, pluggy-0.7.1cachedir: .pytest_cacherootdir: /Users/hoefling/projects/private/stackoverflow, inifile:collected 1 itemtest_spam.py::test_in FAILED [100%]======================================== FAILURES ========================================________________________________________ test_in _________________________________________ def test_in(): d = {key: key for key in range(500)} # makes d sufficiently big to trigger minimization of output> assert 1000 in d # this will failE assert 1000 in {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 11, 12: 12, 13: 13, 14: 14, 15: 15, 16: 16, 17: 17, 18: 18, 19: 19, 20: 20, 21: 21, 22: 22, 23: 23, 24: 24, 25: 25, 26: 26, 27: 27, 28: 28, 29: 29, 30: 30, 31: 31, 32: 32, 33: 33, 34: 34, 35: 35, 36: 36, 37: 37, 38: 38, 39: 39, 40: 40, 41: 41, 42: 42, 43: 43, 44: 44, 45: 45, 46: 46, 47: 47, 48: 48, 49: 49, 50: 50, 51: 51, 52: 52, 53: 53, 54: 54, 55: 55, 56: 56, 57: 57, 58: 58, 59: 59, 60: 60, 61: 61, 62: 62, 63: 63, 64: 64, 65: 65, 66: 66, 67: 67, 68: 68, 69: 69, 70: 70, 71: 71, 72: 72, 73: 73, 74: 74, 75: 75, 76: 76, 77: 77, 78: 78, 79: 79, 80: 80, 81: 81, 82: 82, 83: 83, 84: 84, 85: 85, 86: 86, 87: 87, 88: 88, 89: 89, 90: 90, 91: 91, 92: 92, 93: 93, 94: 94, 95: 95, 96: 96, 97: 97, 98: 98, 99: 99, 100: 100, 101: 101, 102: 102, 103: 103, 104: 104, 105: 105, 106: 106, 107: 107, 108: 108, 109: 109, 110: 110, 111: 111, 112: 112, 113: 113, 114: 114, 115: 115, 116: 116, 117: 117, 118: 118, 119: 119, 120: 120, 121: 121, 122: 122, 123: 123, 124: 124, 125: 125, 126: 126, 127: 127, 128: 128, 129: 129, 130: 130, 131: 131, 132: 132, 133: 133, 134: 134, 135: 135, 136: 136, 137: 137, 138: 138, 139: 139, 140: 140, 141: 141, 142: 142, 143: 143, 144: 144, 145: 145, 146: 146, 147: 147, 148: 148, 149: 149, 150: 150, 151: 151, 152: 152, 153: 153, 154: 154, 155: 155, 156: 156, 157: 157, 158: 158, 159: 159, 160: 160, 161: 161, 162: 162, 163: 163, 164: 164, 165: 165, 166: 166, 167: 167, 168: 168, 169: 169, 170: 170, 171: 171, 172: 172, 173: 173, 174: 174, 175: 175, 176: 176, 177: 177, 178: 178, 179: 179, 180: 180, 181: 181, 182: 182, 183: 183, 184: 184, 185: 185, 186: 186, 187: 187, 188: 188, 189: 189, 190: 190, 191: 191, 192: 192, 193: 193, 194: 194, 195: 195, 196: 196, 197: 197, 198: 198, 199: 199, 200: 200, 201: 201, 202: 202, 203: 203, 204: 204, 205: 205, 206: 206, 207: 207, 208: 208, 209: 209, 210: 210, 211: 211, 212: 212, 213: 213, 214: 214, 215: 215, 216: 216, 217: 217, 218: 218, 219: 219, 220: 220, 221: 221, 222: 222, 223: 223, 224: 224, 225: 225, 226: 226, 227: 227, 228: 228, 229: 229, 230: 230, 231: 231, 232: 232, 233: 233, 234: 234, 235: 235, 236: 236, 237: 237, 238: 238, 239: 239, 240: 240, 241: 241, 242: 242, 243: 243, 244: 244, 245: 245, 246: 246, 247: 247, 248: 248, 249: 249, 250: 250, 251: 251, 252: 252, 253: 253, 254: 254, 255: 255, 256: 256, 257: 257, 258: 258, 259: 259, 260: 260, 261: 261, 262: 262, 263: 263, 264: 264, 265: 265, 266: 266, 267: 267, 268: 268, 269: 269, 270: 270, 271: 271, 272: 272, 273: 273, 274: 274, 275: 275, 276: 276, 277: 277, 278: 278, 279: 279, 280: 280, 281: 281, 282: 282, 283: 283, 284: 284, 285: 285, 286: 286, 287: 287, 288: 288, 289: 289, 290: 290, 291: 291, 292: 292, 293: 293, 294: 294, 295: 295, 296: 296, 297: 297, 298: 298, 299: 299, 300: 300, 301: 301, 302: 302, 303: 303, 304: 304, 305: 305, 306: 306, 307: 307, 308: 308, 309: 309, 310: 310, 311: 311, 312: 312, 313: 313, 314: 314, 315: 315, 316: 316, 317: 317, 318: 318, 319: 319, 320: 320, 321: 321, 322: 322, 323: 323, 324: 324, 325: 325, 326: 326, 327: 327, 328: 328, 329: 329, 330: 330, 331: 331, 332: 332, 333: 333, 334: 334, 335: 335, 336: 336, 337: 337, 338: 338, 339: 339, 340: 340, 341: 341, 342: 342, 343: 343, 344: 344, 345: 345, 346: 346, 347: 347, 348: 348, 349: 349, 350: 350, 351: 351, 352: 352, 353: 353, 354: 354, 355: 355, 356: 356, 357: 357, 358: 358, 359: 359, 360: 360, 361: 361, 362: 362, 363: 363, 364: 364, 365: 365, 366: 366, 367: 367, 368: 368, 369: 369, 370: 370, 371: 371, 372: 372, 373: 373, 374: 374, 375: 375, 376: 376, 377: 377, 378: 378, 379: 379, 380: 380, 381: 381, 382: 382, 383: 383, 384: 384, 385: 385, 386: 386, 387: 387, 388: 388, 389: 389, 390: 390, 391: 391, 392: 392, 393: 393, 394: 394, 395: 395, 396: 396, 397: 397, 398: 398, 399: 399, 400: 400, 401: 401, 402: 402, 403: 403, 404: 404, 405: 405, 406: 406, 407: 407, 408: 408, 409: 409, 410: 410, 411: 411, 412: 412, 413: 413, 414: 414, 415: 415, 416: 416, 417: 417, 418: 418, 419: 419, 420: 420, 421: 421, 422: 422, 423: 423, 424: 424, 425: 425, 426: 426, 427: 427, 428: 428, 429: 429, 430: 430, 431: 431, 432: 432, 433: 433, 434: 434, 435: 435, 436: 436, 437: 437, 438: 438, 439: 439, 440: 440, 441: 441, 442: 442, 443: 443, 444: 444, 445: 445, 446: 446, 447: 447, 448: 448, 449: 449, 450: 450, 451: 451, 452: 452, 453: 453, 454: 454, 455: 455, 456: 456, 457: 457, 458: 458, 459: 459, 460: 460, 461: 461, 462: 462, 463: 463, 464: 464, 465: 465, 466: 466, 467: 467, 468: 468, 469: 469, 470: 470, 471: 471, 472: 472, 473: 473, 474: 474, 475: 475, 476: 476, 477: 477, 478: 478, 479: 479, 480: 480, 481: 481, 482: 482, 483: 483, 484: 484, 485: 485, 486: 486, 487: 487, 488: 488, 489: 489, 490: 490, 491: 491, 492: 492, 493: 493, 494: 494, 495: 495, 496: 496, 497: 497, 498: 498, 499: 499}test_spam.py:3: AssertionError================================ 1 failed in 0.08 seconds ================================
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52986691', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6618996/']}
jdg_82783
stackexchange
llm_judgeable_groundtruth_similarity
15742125
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 add image to android PDF using iText. I want to achieve this without saving image to SDCard first. I put my image into res/drawable folder but proving the image path doesn’t work and it throws FileNotFound Exception. My path is like this: String path = “res/drawable/myImage.png”Image image = Image.getInstance(path);document.add(image); Now please suggest me a solution how I will add correct file path to getInstance(…) method. Thanks Now provide the response and nothing else.
Of course it'll not work at that way. move your image to assets folder to access it with getassets() method // load image try { // get input stream InputStream ims = getAssets().open("myImage.png"); Bitmap bmp = BitmapFactory.decodeStream(ims); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); Image image = Image.getInstance(stream.toByteArray()); document.add(image); } catch(IOException ex) { return; }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15742125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/810435/']}
jdg_82784
stackexchange
llm_judgeable_groundtruth_similarity
37322747
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was wondering whether it is possible to actually authenticate to the Firebase REST API withouth using the custom authentication ? I've worked with Firebase now for some time and I'm currently thinking about migrating a backend of mine to Firebase.The app that uses the backend currently uses a REST API and does not need realtime data at all.Thus I'd like to use only the REST API and not the full Android framework on the clients. Is it possible to get an auth token using the mail & password authentication of Firebase via HTTP-requests? In the old docs I've only found a solution with custom login and in the new docs you seem to need a Google Service Account. Any help or advice appreciated. Now provide the response and nothing else.
Update: Firebase REST authentication is now documented! View the documentation Firebase REST authentication I figured out how to perform email and password authentication for Firebase by examining the requests sent by the Javascript API. These APIs are undocumented and unsupported Firebase 3 Firebase 3 authentication is an updated and renamed version of the Google Identity Toolkit. The old documentation is not fully accurate, but may be useful and can be found here: https://developers.google.com/identity/toolkit/web/reference/ Firebase 3 requires all requests to have Content-Type: application/json in the header API Key Firebase 3 requires an API key to be attached to all authentication requests. You can find the API key for your database by visiting the Firebase project overview and clicking on "Add Firebase to your web app". You should see a window with code like the following: <script src="https://www.gstatic.com/firebasejs/live/3.0/firebase.js"> </script><script> // Initialize Firebase var config = { apiKey: "<my-firebase-api-key>", authDomain: "my-firebase.firebaseapp.com", databaseURL: "https://my-firebase.firebaseio.com", storageBucket: "my-firebase.appspot.com", }; firebase.initializeApp(config);</script> Copy the apiKey value and save it for later. Registration Method: POST URL: https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=<my-firebase-api-key> Payload: { email: "<email>", password: "<password>", returnSecureToken: true} Response: { "kind": "identitytoolkit#SignupNewUserResponse", "localId": "<firebase-user-id>", // Use this to uniquely identify users "email": "<email>", "displayName": "", "idToken": "<provider-id-token>", // Use this as the auth token in database requests "registered": true, "refreshToken": "<refresh-token>", "expiresIn": "3600"} Login Method: POST URL: https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=<my-firebase-api-key> Payload: { email: "<email>", password: "<password>", returnSecureToken: true} Response: { "kind": "identitytoolkit#VerifyPasswordResponse", "localId": "<firebase-user-id>", // Use this to uniquely identify users "email": "<email>", "displayName": "", "idToken": "<provider-id-token>", // Use this as the auth token in database requests "registered": true, "refreshToken": "<refresh-token>", "expiresIn": "3600"} Get Account Info Method: POST URL: https://www.googleapis.com/identitytoolkit/v3/relyingparty/getAccountInfo?key=<my-firebase-api-key> Payload: { idToken: "<provider-id-token>"} Response: { "kind": "identitytoolkit#GetAccountInfoResponse", "users": [ { "localId": "<firebase-user-id>", "email": "<email>", "emailVerified": false, "providerUserInfo": [ { "providerId": "<password>", "federatedId": "<email>", "email": "<email>", "rawId": "<email>" }], "passwordHash": "<hash>", "passwordUpdatedAt": 1.465327109E12, "validSince": "1465327108", "createdAt": "1465327108000" }]} Firebase 2 These requests return JSON data described in the Firebase docs. https://www.firebase.com/docs/web/guide/login/password.html#section-logging-in Login You can authenticate by sending a GET request with the following format: https://auth.firebase.com/v2/<db_name>/auth/password?&email=<email>&password=<password> Registration User creation can also be performed by sending the same GET request with _method=POST as part of the query string https://auth.firebase.com/v2/<db_name>/users?&email=<email>&password=<password>&_method=POST
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/37322747', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3160089/']}
jdg_82785
stackexchange
llm_judgeable_groundtruth_similarity
34731869
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In Angular 1.x, UI-Router was my primary tool for this. By returning a promise for "resolve" values, the router would simply wait for the promise to complete before rendering directives. Alternately, in Angular 1.x, a null object will not crash a template - so if I don't mind a temporarily incomplete render, I can just use $digest to render after the promise.then() populates an initially empty model object. Of the two approaches, if possible I'd prefer to wait to load the view, and cancel route navigation if the resource cannot be loaded. This saves me the work of "un-navigating". EDIT: Note this specifically means this question requests an Angular 2 futures-compatible or best-practice method to do this, and asks to avoid the "Elvis operator" if possible! Thus, I did not select that answer. However, neither of these two methods work in Angular 2.0. Surely there is a standard solution planned or available for this. Does anyone know what it is? @Component() { template: '{{cats.captchans.funniest}}'}export class CatsComponent { public cats: CatsModel; ngOnInit () { this._http.get('/api/v1/cats').subscribe(response => cats = response.json()); }} The following question may reflect the same issue: Angular 2 render template after the PROMISE with data is loaded . Note that question has no code or accepted answer in it. Now provide the response and nothing else.
Try {{model?.person.name}} this should wait for model to not be undefined and then render. Angular 2 refers to this ?. syntax as the Elvis operator . Reference to it in the documentation is hard to find so here is a copy of it in case they change/move it: The Elvis Operator ( ?. ) and null property paths The Angular “Elvis” operator ( ?. ) is a fluent and convenient way to guard against null and undefined values in property paths. Here it is, protecting against a view render failure if the currentHero is null. The current hero's name is {{currentHero?.firstName}} Let’s elaborate on the problem and this particular solution. What happens when the following data bound title property is null? The title is {{ title }} The view still renders but the displayed value is blank; we see only "The title is" with nothing after it. That is reasonable behavior. At least the app doesn't crash. Suppose the template expression involves a property path as in this next example where we’re displaying the firstName of a null hero. The null hero's name is {{nullHero.firstName}} JavaScript throws a null reference error and so does Angular: TypeError: Cannot read property 'firstName' of null in [null] Worse, the entire view disappears. We could claim that this is reasonable behavior if we believed that the hero property must never be null. If it must never be null and yet it is null, we've made a programming error that should be caught and fixed. Throwing an exception is the right thing to do. On the other hand, null values in the property path may be OK from time to time, especially when we know the data will arrive eventually. While we wait for data, the view should render without complaint and the null property path should display as blank just as the title property does. Unfortunately, our app crashes when the currentHero is null. We could code around that problem with NgIf <!--No hero, div not displayed, no error --> <div *ngIf="nullHero">The null hero's name is {{nullHero.firstName}}</div> Or we could try to chain parts of the property path with &&, knowing that the expression bails out when it encounters the first null. The null hero's name is {{nullHero && nullHero.firstName}} These approaches have merit but they can be cumbersome, especially if the property path is long. Imagine guarding against a null somewhere in a long property path such as a.b.c.d. The Angular “Elvis” operator ( ?. ) is a more fluent and convenient way to guard against nulls in property paths. The expression bails out when it hits the first null value. The display is blank but the app keeps rolling and there are no errors. <!-- No hero, no problem! --> The null hero's name is {{nullHero?.firstName}} It works perfectly with long property paths too: a?.b?.c?.d
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34731869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/608220/']}
jdg_82786
stackexchange
llm_judgeable_groundtruth_similarity
1854750
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: From Peter Winkler's book: Given a matrix, prove that after first sorting each row, then sorting each column, each row remains sorted. For example: starting with $$\begin{bmatrix}1 & -3 & 2 \\0 & 1 & -5 \\4 & -1 & 1\end{bmatrix}$$ Sorting each row individually and in ascending order gives $$\begin{bmatrix}-3 & 1 & 2 \\-5 & 0 & 1 \\-1 & 1 & 4\end{bmatrix}$$ Then sorting each column individually in ascending order gives $$\begin{bmatrix}-5 & 0 & 1 \\-3 & 1 & 2 \\-1 & 1 & 4\end{bmatrix}$$ And notice the rows are still individually sorted, in ascending order. I was trying to find a 'nice' proof that does not involve messy index comparisons... but I cannot find one! Now provide the response and nothing else.
Notice that you can start from after the first step. Specifically, you only need to prove that, given an arbitrary matrix where each row is already in ascending order, sorting each column in ascending order keeps each row sorted. Here is a very neat trick to do this. Let $m$ be the number of columns. For each $k$ from $1$ to $m$ , sort the rows of the subarray from column $k$ to column $m$ in increasing order of the element in column $k$ . (Each row of the subarray stays together.) We do this sorting by bubble sort. We maintain the invariant that the elements in each row stays sorted. This invariant is trivially true when $k = 1$ . When $k > 1$ , and we perform a swap involving rows $p$ and $(p+1)$ , consider the elements in those rows and in the columns $(k-1)$ and $k$ : $\cdots \quad a \quad d \quad \cdots_1$ $\cdots \quad b \quad c \quad \cdots_2$ By the invariance we have $a \le b \le c$ and the swap is only done because $c \le d$ . After the swap we have: $\cdots \quad a \quad c \quad \cdots_2$ $\cdots \quad b \quad d \quad \cdots_1$ And the invariance is preserved since $a \le c$ and $b \le d$ . Look! No index chasing!
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1854750', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/244966/']}
jdg_82787
stackexchange
llm_judgeable_groundtruth_similarity
653368
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'd like to create a Python decorator that can be used either with parameters: @redirect_output("somewhere.log")def foo(): .... or without them (for instance to redirect the output to stderr by default): @redirect_outputdef foo(): .... Is that at all possible? Note that I'm not looking for a different solution to the problem of redirecting output, it's just an example of the syntax I'd like to achieve. Now provide the response and nothing else.
I know this question is old, but some of the comments are new, and while all of the viable solutions are essentially the same, most of them aren't very clean or easy to read. Like thobe's answer says, the only way to handle both cases is to check for both scenarios. The easiest way is simply to check to see if there is a single argument and it is callabe (NOTE: extra checks will be necessary if your decorator only takes 1 argument and it happens to be a callable object): def decorator(*args, **kwargs): if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): # called as @decorator else: # called as @decorator(*args, **kwargs) In the first case, you do what any normal decorator does, return a modified or wrapped version of the passed in function. In the second case, you return a 'new' decorator that somehow uses the information passed in with *args, **kwargs. This is fine and all, but having to write it out for every decorator you make can be pretty annoying and not as clean. Instead, it would be nice to be able to automagically modify our decorators without having to re-write them... but that's what decorators are for! Using the following decorator decorator, we can deocrate our decorators so that they can be used with or without arguments: def doublewrap(f): ''' a decorator decorator, allowing the decorator to be used as: @decorator(with, arguments, and=kwargs) or @decorator ''' @wraps(f) def new_dec(*args, **kwargs): if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): # actual decorated function return f(args[0]) else: # decorator arguments return lambda realf: f(realf, *args, **kwargs) return new_dec Now, we can decorate our decorators with @doublewrap, and they will work with and without arguments, with one caveat: I noted above but should repeat here, the check in this decorator makes an assumption about the arguments that a decorator can receive (namely that it can't receive a single, callable argument). Since we are making it applicable to any generator now, it needs to be kept in mind, or modified if it will be contradicted. The following demonstrates its use: def test_doublewrap(): from util import doublewrap from functools import wraps @doublewrap def mult(f, factor=2): '''multiply a function's return value''' @wraps(f) def wrap(*args, **kwargs): return factor*f(*args,**kwargs) return wrap # try normal @mult def f(x, y): return x + y # try args @mult(3) def f2(x, y): return x*y # try kwargs @mult(factor=5) def f3(x, y): return x - y assert f(2,3) == 10 assert f2(2,5) == 30 assert f3(8,1) == 5*7
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/653368', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15109/']}
jdg_82788
stackexchange
llm_judgeable_groundtruth_similarity
389818
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm building a web application that has a feature which allows visitors to directly access resources using URL patterns, for example: www.site.com/client/[clientID]/orders www.site.com/client/[clientID]/orders/[orderId]/details These URLs can be static or dynamic links from other applications/sites. The URLs are secured, but if header of the HTTP request contains the authentication token (e.g. the visitor was logged into the previous site), then the authentication process is invisible to the visitor. My question is, is it correct to describe this feature as an API? Why or why not? My instinct is no, because the request is received by and returned in the browser. Also, the system as it would not accept a request that did not have that auth token in the header. My colleagues refer to this as an API, and I'm having trouble explaining why this feature doesn't fit the definition of an API (and what it should be called instead). Now provide the response and nothing else.
Ask a human to do it with pixels and we call it a GUI: Graphic User Interface. Ask a human to do it with text and we call it a CLI: Command Line Interface. Ask a computer to do it with bytes and we call it an API: Application Program Interface. This is likely the mentality of your colleagues. And I'd agree with them with one qualification: It isn't the API that is doing the authenticating. That's the client that uses the API. A human normally does this by entering a username and pass. The client is doing that part for them by sending the authentication token. We call that automation. The API likely doesn't even know or care how the authentication token was created so long as it's valid. The API's job is to validate the authentication. Not provide it. Whatever provided it is either a human or an automated client.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/389818', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/332821/']}
jdg_82789
stackexchange
llm_judgeable_groundtruth_similarity
280641
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: The following is the pattern of dodecagons and triangles: which is called a truncated hexagonal tiling. In the Mathematica documentation there are different methods to tessellate the surface, like VoronoiMesh. Most of these methods seem to produce polygons between 3- to 6-sided polygons. Can one produce the above with Mathematica? Now provide the response and nothing else.
I'm not sure if the scope of the question is to derive the tiling from some more abstract definition or just to reproduce it, but reproducing it is not particularly hard: With[ {gridbasis = a {1, 0} + b RotationTransform[60 Degree][{1, 0}]}, Graphics[ {EdgeForm[Black], FaceForm[LightBlue], (* Place regular 12-gons, rotated and sized correctly, on the hexagonal grid. *) RegularPolygon[ gridbasis, {1/(2 Cos[Pi/12]), Pi/12}, 12] /. Solve[ (* Find hexagonal grid points inside the specified rectangle on basis of a and b. *) RegionMember[ Rectangle[{-3, -3}, {3, 3}], gridbasis], {a, b}, Integers]}]] One could of course just use a basis and reason PlotRange on the formed parallelogram area manually, but it is also quite easy to find polygon positions on a (rectangular) region with Solve . On counting (whole) 12-gons and triangles in a region - here's a stab at it. Note that this does not scale well, as CylindricalDecomposition is quite a complicated operation. This is more an example of "we can use brute computational force as a substitute for brainpower" exercise (mostly in computation of triangles ) than anything else; one could relatively easily figure out grid positions for triangles on the tiling and perform RegionWithin checks for them, but the task can be performed purely by real algebraic geometry starting from known 12-gons and the constraining area. gridbasis = a {1, 0} + b RotationTransform[60 Degree][{1, 0}];(* List of 12-gons. *)polys = RegularPolygon[gridbasis, {1/(2 Cos[Pi/12]), Pi/12}, 12] /. Solve[ RegionMember[Rectangle[{-3, -3}, {3, 3}], gridbasis], {a, b}, Integers];(* Region where we are counting regions. This region must be completely covered by the tiling. *)countregion = Rectangle[{-5/2, -5/2}, {5/2, 5/2}];(* Visualise 12-gons (polys) which are inside in countregion. *)Cases[polys, poly_RegularPolygon /; RegionWithin[countregion, poly]] // Graphics[ {FaceForm@LightBlue, polys, FaceForm@Lighter@Blue, #, FaceForm[None], EdgeForm[Black], countregion}] &(* Count them. *)Count[polys, poly_RegularPolygon /; RegionWithin[countregion, poly]](* Construct a region consisting of inside of countregion which is not overlapped by polys. Convert it to implict equation form, and separate it to connected components. Convert these to implicit regions, which correspond to full or partial (cut by countregion) triangles between polys. *)triangles = ImplicitRegion[#, {x, y}] & /@ CylindricalDecomposition[ RegionMember[RegionDifference[countregion, RegionUnion[polys]], {x, y}], {x, y}, "Components"];(* Compute areas of triangles and simplify their forms. *)triangleareas = RootReduce@*Area /@ triangles;(* Select those triangles with area equal to largest area seen. *)completetriangles = Cases[Thread[{triangles, triangleareas}], {t_, Max[triangleareas]} :> t];(* Visualise completetriangles. *)Graphics[ {FaceForm@LightBlue, polys, FaceForm@Lighter@Blue, MeshPrimitives[ Quiet@BoundaryDiscretizeRegion[#], {2}] & /@ completetriangles, FaceForm@None, EdgeForm@Black, countregion}](* Count them. *)Count[triangleareas, Max[triangleareas]] 23 54
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/280641', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/-1/']}
jdg_82790
stackexchange
llm_judgeable_groundtruth_similarity
2268567
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If my file stream is in use (every time I try to debug, it hits that first line and says it's in use), how can I force a release? every time it hits this code, I get a message saying something is using it: FileStream fileStream = File.Open(@"C:\somefile", FileMode.Open, FileAccess.Read);byte[] buffer = new byte[fileStream.Length];...etc.fileStream.Close(); Now provide the response and nothing else.
Learn to use using : using (FileStream fileStream = File.Open(@"C:\somefile", FileMode.Open, FileAccess.Read)){ ...} The using construct ensures that the file will be closed when you leave the block even if an exception is thrown. Your problem might not be here, but somewhere else in your code. You'll have to go through all your code and look for places where you have opened files but not put it inside a using statement.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2268567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/93468/']}
jdg_82791
stackexchange
llm_judgeable_groundtruth_similarity
105903
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: $\operatorname{ GPF}(n)=$Greatest prime factor of $n$, eg. $\operatorname{ GPF}(17)=17$, $\operatorname{ GPF}(18)=3$. How to evaluate convergence/divergence/value of the sum $$\sum_{n=1}^{\infty} \frac{1}{n\operatorname{ GPF}(n)}\,?$$ Now provide the response and nothing else.
If $\{r_1,\dots,r_k,p\}$ is the set of primes $\le p$, then $$\{n\in \mathbb{Z}: \operatorname{gpf}(n)=p\}=\{r_1^{e_1}\cdots r_k^{e_k}p^f:\text{each }e_i\ge 0,f\ge1\}.$$ Now we have the Euler product factorization $$\sum_{e_1\,\ge0}\cdots\sum_{e_k\,\ge0}\sum_{f\ge1}\frac{1}{r_1^{e_1}\cdots r_k^{e_k} p^f}= \prod_{i=1}^k \left(1+\frac{1}{r_i}+\frac{1}{r_i^2}+\cdots\right)\cdot \left(\frac{1}{p}+\frac{1}{p^2}+\frac{1}{p^3}+\cdots\right) $$ $$\implies \bullet =\sum_p \frac{1}{p}\sum_{\operatorname{gpf}(n)=p}\frac{1}{n}=\sum_p \frac{1}{p}\left[\,\prod_{q\,< \,p}\left(1-\frac{1}{q}\right)^{-1}\right]\frac{1/p}{1-1/p}$$ $$=\sum_p \frac{1}{p(p-1)}\prod_{q<p}\left(1-\frac{1}{q}\right)^{-1}.$$ With Mertens' Theorem , we know that the $\prod$ above is $\le C\log p$ eventually, so after we ignore a finite sum corresponding to the $p$ before this "eventually" we may say that $$\frac{\bullet}{C} + \zeta_P'(2)\le \sum_p \frac{\log p}{p}\left(\frac{1}{p-1}-\frac{1}{p}\right)\le \sum_p\frac{\log p}{p^2}=-\zeta_P'(2).$$ Here $\zeta_P$ is the prime zeta function . With monotonicity of the terms, this proves convergence.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/105903', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5904/']}
jdg_82792
stackexchange
llm_judgeable_groundtruth_similarity
1410088
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's define a distance between two permutation of length $N$: it is the minimum steps to change one to be another. "A step of change" means that exchanging any two elements' location. For example, series $\{1,2,3\}$ can be changed into $\{2,1,3\}$ in one step, by exchanging the location of $1$ and $2$. So it means $$\text{d}(\{1,2,3\},\{2,1,3\}) = 1$$ $\text{d}$ means distance. So, we can easily get that $\text{d}(\{1,2,3\},\{3,1,2\})$ is $2$ and so on. But while $N$ is big enough, how can I get the distance between two arbitrary series? Now provide the response and nothing else.
Instead of "series" the mathematical term in this case is a permutation. Mathematically speaking you want to determine the following: For two permutations $\pi$, $\tau$ you want to find the minimal number $n$ of transpositions $\sigma_i$ so that $$\pi = \sigma_1 \circ \ldots \circ \sigma_n \circ \tau.$$Equivalently one might ask for the minimal $n$ for which $$\pi \tau^{-1} = \sigma_1 \circ \ldots \circ \sigma_n.$$ Now you can decompose the permutation $\pi \tau^{-1}$ into disjoint cycles . I don't have a rigorous proof, but $n$ should be the sum of the lengths of all cycles, minus the number of cycles [or equivalently: sum up all the cycle-lengths after substracting $1$ from every length]. Edit: If the permutation consists of $k$ elements, then this number is actually the difference between $k$ and the number of cycles in the cycle-representation of the permutation. Now observe that with a transposition you can only increase or decrease this number by $1$ and that the identity is the only permutation with $k$ cycles. This should yield a rigorous proof of my statement.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1410088', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/117403/']}
jdg_82793
stackexchange
llm_judgeable_groundtruth_similarity
7045151
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I have the below XML, how to specify a xpath to return a string based on a condition. For example here if //b[@id=23] then "Profit" else "Loss" <a> <b id="23"/> <c></c> <d></d> <e> <f id="23"> <i>123</i> <j>234</j> <f> <f id="24"> <i>345</i> <j>456</j> <f> <f id="25"> <i>678</i> <j>567</j> <f> </e></a> Now provide the response and nothing else.
I. XPath 2.0 solution (recommended if you have access to an XPath 2.0 engine) (: XPath 2.0 has if ... then ... else ... :) if(//b[@id=23]) then 'Profit' else 'Loss' II. XPath 1.0 solution : Use: concat(substring('Profit', 1 div boolean(//b[@id=23])), substring('Loss', 1 div not(//b[@id=23])) ) Verification using XSLT 1.0 : This transformation: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/"> <xsl:value-of select= "concat(substring('Profit', 1 div boolean(//b[@id=23])), substring('Loss', 1 div not(//b[@id=23])) )"/> </xsl:template></xsl:stylesheet> when applied on the provided XML document (corrected to make it well-formed): <a> <b id="23"/> <c></c> <d></d> <e> <f id="23"> <i>123</i> <j>234</j> </f> <f id="24"> <i>345</i> <j>456</j> </f> <f id="25"> <i>678</i> <j>567</j> </f> </e></a> produces the wanted, correct result : Profit When we replace in the XML document : <b id="23"/> with : <b id="24"/> again the correct result is produced : Loss Explanation : We use the fact that: substring($someString, $N) is the empty string for all $N > string-length($someString) . Also, the number Infinity is the only number greater than the string-length of any string . Finally: number(true()) is 1 by definition, number(false()) is 0 by definition. Therefore: 1 div $someCondition is 1 exactly when the $someCondition is true() and is Infinity exactly when $someCondition is false() Thus it follows from this that if we want to produce $stringX when $Cond is true() and to produce $stringY when $Cond is false() , one way to express this is by : concat(substring($stringX, 1 div $cond), substring($stringY, 1 div not($cond)), ) In the above expression exactly one of the two arguments of the concat() function is non-empty .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7045151', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/890825/']}
jdg_82794
stackexchange
llm_judgeable_groundtruth_similarity
43574234
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 establish a communication between a client and server application using Springs new reactive webflux extension. For dependency management I use gradle . My build.gradle file on the server, as well as on the client side basically is: buildscript { repositories { mavenCentral() maven { url "https://repo.spring.io/snapshot" } } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.0.BUILD-SNAPSHOT") }}repositories { mavenCentral() maven { url "https://repo.spring.io/snapshot" }}apply plugin: 'java'apply plugin: 'org.springframework.boot'apply plugin: "io.spring.dependency-management" dependencies { compile("org.springframework.boot:spring-boot-starter-webflux")} (It should be noted that 2.0.0.BUILD- SNAPSHOT is a moving target and the problem at hand may just vanish one day due to changes inside the dependency) When I start the server side application everything starts up well, including the start of an embedded netty server. But when start the client application also a netty server is started, causing a "java.net.BindException: Address already in use", because the clientside netty server listens on the same port as the serverside netty server. My question is: Why is netty started on the client side in the first place and how can I prevent it? According to the Spring-Boot Documentation Spring tries to determine if Web support is required and configures the Spring Application context accordingly. And according to the Docs this can be overridden by a call to setWebEnvironment(false). My client startup code then looks like: @SpringBootApplication(scanBasePackages = { "com.tatics.flux.main" })public class Client { public static void main(String[] args) throws Exception { SpringApplication app = new SpringApplication(Client.class); app.setWebEnvironment(false); app.run(Client.class, args); WebClient webClient = WebClient.create(); Mono<String> result = webClient .post() .uri("http://localhost:8080/fluxService") // This does not work any more: .body("Hallo") // and must be replaced by: .body(BodyInserters.fromObject("Hallo")) .accept(MediaType.TEXT_PLAIN) .exchange() .flatMap(response -> response.bodyToMono(String.class)); }} Unfortunately netty is still started. Also I note that setWebEnvironment(false) is marked as deprecated. Any help on how to prevent netty from starting but otherwise preserve all webflux-dependencies is appreciated. Here is an excerpt from the auto-configuration Report: =========================AUTO-CONFIGURATION REPORT=========================Positive matches:-----------------...ReactiveWebServerAutoConfiguration matched: - found ReactiveWebApplicationContext (OnWebApplicationCondition)ReactiveWebServerAutoConfiguration#defaultReactiveWebServerCustomizer matched: - @ConditionalOnMissingBean (types: org.springframework.boot.autoconfigure.web.reactive.DefaultReactiveWebServerCustomizer; SearchStrategy: all) did not find any beans (OnBeanCondition)ReactiveWebServerConfiguration.ReactorNettyAutoConfiguration matched: - @ConditionalOnClass found required class 'reactor.ipc.netty.http.server.HttpServer'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition) - @ConditionalOnMissingBean (types: org.springframework.boot.web.reactive.server.ReactiveWebServerFactory; SearchStrategy: all) did not find any beans (OnBeanCondition)ReactorCoreAutoConfiguration matched: - @ConditionalOnClass found required classes 'reactor.core.publisher.Mono', 'reactor.core.publisher.Flux'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)...Negative matches:-----------------...ReactiveWebServerConfiguration.JettyAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.eclipse.jetty.server.Server' (OnClassCondition)ReactiveWebServerConfiguration.TomcatAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.apache.catalina.startup.Tomcat' (OnClassCondition)ReactiveWebServerConfiguration.UndertowAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'io.undertow.Undertow' (OnClassCondition)...ReactiveWebServerConfiguration.JettyAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.eclipse.jetty.server.Server' (OnClassCondition)ReactiveWebServerConfiguration.TomcatAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.apache.catalina.startup.Tomcat' (OnClassCondition)ReactiveWebServerConfiguration.UndertowAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'io.undertow.Undertow' (OnClassCondition) Now provide the response and nothing else.
The main issue with your code is that you're currently creating a SpringApplication , then you customize it - to finally drop everything and run the static method run(Object primarySource, String... args) . The following should work: @SpringBootApplicationpublic class Client { public static void main(String[] args) throws Exception { SpringApplication app = new SpringApplication(Client.class); app.setWebApplicationType(WebApplicationType.NONE); app.run(args); } @Bean public CommandLineRunner myCommandLineRunner() { return args -> { // we have to block here, since command line runners don't // consume reactive types and simply return after the execution String result = WebClient.create("http://localhost:8080") .post() .uri("/fluxService") .body("Hallo") .accept(MediaType.TEXT_PLAIN) .retrieve() .bodyToMono(String.class) .block(); // print the result? }; }} If not, please run your application using the --debug flag and add to your question the relevant parts of the auto-configuration report, especially the auto-configurations dealing with servers.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43574234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1740779/']}
jdg_82795
stackexchange
llm_judgeable_groundtruth_similarity
1707799
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 having weird problem with java TimeZone.. Calling TimeZone.getDefault() gives my local time zone, which has an ID "GMT+02:00".Funny thing is that this ID doesn't appear in a list provided by TimeZone.getAvailableIDs() . Apparently my zone appears to be "Etc/GMT+2". I'm trying to populate a combo with time zones, but it's impossible to put a selection because GMT+02:00 is not in the list..Anyone seen this problem? Any ideas? Update: The bottom line is - can't rely on ID strings, must go with the offset as display ID's may vary from system to system. Now provide the response and nothing else.
GMT+02:00 is a custom ID, it won't appear in the output of TimeZone.getAvailableIDs() (which is huge). What you could do is to ask the user to specify his offset first and then get the available IDs for the given offset. For example, for GMT+02:00, the following piece of code: for (String string : TimeZone.getAvailableIDs(TimeZone.getTimeZone( "GMT+02:00").getRawOffset())) { System.out.println(string);} gives the following output: ARTAfrica/BlantyreAfrica/BujumburaAfrica/CairoAfrica/GaboroneAfrica/HarareAfrica/JohannesburgAfrica/KigaliAfrica/LubumbashiAfrica/LusakaAfrica/MaputoAfrica/MaseruAfrica/MbabaneAfrica/TripoliAsia/AmmanAsia/BeirutAsia/DamascusAsia/GazaAsia/IstanbulAsia/JerusalemAsia/NicosiaAsia/Tel_AvivCATEETEgyptEtc/GMT-2Europe/AthensEurope/BucharestEurope/ChisinauEurope/HelsinkiEurope/IstanbulEurope/KaliningradEurope/KievEurope/MariehamnEurope/MinskEurope/NicosiaEurope/RigaEurope/SimferopolEurope/SofiaEurope/TallinnEurope/TiraspolEurope/UzhgorodEurope/VilniusEurope/ZaporozhyeIsraelLibyaTurkey It's still big but human browsable this time.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1707799', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/80382/']}
jdg_82796
stackexchange
llm_judgeable_groundtruth_similarity
13727030
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 new to Java and have tried to implement mergesort in Java. However, even after running the program several times, instead of the desired sorted output, I am getting the same user given input as the output. I would be thankful if someone could help me understand this unexpected behaviour. import java.io.*;import java.util.Arrays;public class MergeSort { public static void main(String[] args) throws IOException { BufferedReader R = new BufferedReader(new InputStreamReader(System.in)); int arraySize = Integer.parseInt(R.readLine()); int[] inputArray = new int[arraySize]; for (int i = 0; i < arraySize; i++) { inputArray[i] = Integer.parseInt(R.readLine()); } mergeSort(inputArray); for (int j = 0; j < inputArray.length; j++) { System.out.println(inputArray[j]); } } static void mergeSort(int[] A) { if (A.length > 1) { int q = A.length / 2; int[] leftArray = Arrays.copyOfRange(A, 0, q); int[] rightArray = Arrays.copyOfRange(A, q + 1, A.length); mergeSort(leftArray); mergeSort(rightArray); A = merge(leftArray, rightArray); } } static int[] merge(int[] l, int[] r) { int totElem = l.length + r.length; int[] a = new int[totElem]; int i, li, ri; i = li = ri = 0; while (i < totElem) { if ((li < l.length) && (ri < r.length)) { if (l[li] < r[ri]) { a[i] = l[li]; i++; li++; } else { a[i] = r[ri]; i++; ri++; } } else { if (li >= l.length) { while (ri < r.length) { a[i] = r[ri]; i++; ri++; } } if (ri >= r.length) { while (li < l.length) { a[i] = l[li]; li++; i++; } } } } return a; }} Now provide the response and nothing else.
Here is a corrected version of your code: import java.io.*;import java.util.Arrays;public class MergeSort { public static void main(String[] args) throws IOException{ BufferedReader R = new BufferedReader(new InputStreamReader(System.in)); int arraySize = Integer.parseInt(R.readLine()); int[] inputArray = new int[arraySize]; for (int i = 0; i < arraySize; i++) { inputArray[i] = Integer.parseInt(R.readLine()); } mergeSort(inputArray); for (int j = 0; j < inputArray.length; j++) { System.out.println(inputArray[j]); } } static void mergeSort(int[] A) { if (A.length > 1) { int q = A.length/2;//changed range of leftArray from 0-to-q to 0-to-(q-1) int[] leftArray = Arrays.copyOfRange(A, 0, q-1);//changed range of rightArray from q-to-A.length to q-to-(A.length-1) int[] rightArray = Arrays.copyOfRange(A,q,A.length-1); mergeSort(leftArray); mergeSort(rightArray); merge(A,leftArray,rightArray); } } static void merge(int[] a, int[] l, int[] r) { int totElem = l.length + r.length; //int[] a = new int[totElem]; int i,li,ri; i = li = ri = 0; while ( i < totElem) { if ((li < l.length) && (ri<r.length)) { if (l[li] < r[ri]) { a[i] = l[li]; i++; li++; } else { a[i] = r[ri]; i++; ri++; } } else { if (li >= l.length) { while (ri < r.length) { a[i] = r[ri]; i++; ri++; } } if (ri >= r.length) { while (li < l.length) { a[i] = l[li]; li++; i++; } } } } //return a; }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13727030', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1135880/']}
jdg_82797
stackexchange
llm_judgeable_groundtruth_similarity
23866919
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 new to mobile applications. I am basically from a web development platform. I am just playing around mobile frameworks like App Framework, LungoJS, Jquery Mobile, kendo etc to gain some knowledge in this vertical. The app I am developing is still in UI level. All I need is to fetch data from the server and populate in my app. I need some ideas to establish server communication between the smart device and the server. My questions are What kind of server needed for mobile applications ? A cloud or aregular web server is enough ? What are the ways to connect the app with the server ? ( on crossplatform mobile development ) What is the secure way to communication with the server ? Now provide the response and nothing else.
What kind of server needed for mobile applications ? A cloud or a regular web server is enough ? Because you are creating a hybrid mobile application you can use any type of server side technology, it doesn't matter is it a classic web server technology (using Java, PHP or .NET) or some kind of cloud technology like Parse.com . You also don't need to create anything from scratch. Best course of action would be to use some kind of micro RESTFul framework(like PHP Falcon or Java Play Framework ). Read more about them here . But, there's always a but. You can't use server side technology for classic content generation, you only need to use it to send data to your hybrid application. I will explain this later. There's also an alternative to RESTFul services, you can create a webservice, again using Java, PHP or .NET. What are the ways to connect the app with the server ? ( on cross platform mobile development ) You would use AJAX as a technology (in case of RESTFul), rest depends on you. You would probably do it in JSON format (or JSONP if you are doing cross-domain calls, but you don't need to think about JSONP when creating a hybrid application). If you intend to use a web service then you would use a SOAP connection and communicate via XML format. No matter which server side technology you use you will always use AJAX on a client side. Now let me tell you why you should not generate your content on server side. Basically nothing can prevent you from doing that, you can generate your complete page on web server and just show it in PhoneGap app, it would still be a hybrid app. But, if you try to put this app in Apple store you will get yourself rejected. What is the secure way to communication with the server ? Security of course depends on server side technology. Every framework has its own kind of security handling, but all of them relay on HTTPS so you should not worry too much. From the client side you can always encrypt JSON/XML data and send them using POST. Examples: If you want to use jQuery Mobile then take a look at this tutorial. It will show you basics of client - server side communication.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23866919', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2736748/']}
jdg_82798
stackexchange
llm_judgeable_groundtruth_similarity
1817421
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 website I'm working on has some fairly complicated routing structures and we're experiencing some difficulties working with the routing engine to build URLs the way we need them to be built. We have a search results page that uses RegEx based pattern matching to group several variables into a single route segment (i.e. "www.host.com/{structuralParameters}" can be the following: "www.host.com/variableA-variableB-variableC" - where variables A through C are all optional). This is working for us fine after a bit of work. The problem we are experiencing resolves around an annoying feature of the ActionLink method: if you point to the same controller/action it will retain the existing route values whether you want them or not. We prefer to have control over what our links look like and, in some cases, cannot have the existing parameters retained. An example would be where our site's main navigation leads to a search results page with no parameters set - a default search page, if you like. I say this is an annoying feature because it is a rare instance of the ASP.Net MVC Framework seemingly dictating implementation without an obvious extension point - we would prefer not to create custom ActionLink code to write a simple navigation link in our master page! I've seen some say that you need to explicitly set such parameters to be empty strings but when we try this it just changes the parameters from route values into query string parameters. It doesn't seem right to me that we should be required to explicitly exclude values we aren't explicitly passing as parameters to the ActionLink method but if this is our only option we will use it. However at present if it is displaying in the query string then it is as useless to us as putting the parameters directly into the route. I'm aware that our routing structure exasperates this problem - we probably wouldn't have any issue if we used a simpler approach (i.e. www.host.com/variableA/variableB/variableC) but our URL structure is not negotiable - it was designed to meet very specific needs relating to usability, SEO, and link/content sharing. How can we use Html.ActionLink to generate links to pages without falling back on the current route data (or, if possible, needing to explicitly excluding route segments) even if those links lead to the same action methods? If we do need to explicitly exclude route segments, how can we prevent the method from rendering the routes as query string parameters? This seemingly small problem is causing us a surprising amount of grief and I will be thankful for any help in resolving it. EDIT: As requested by LukLed, here's a sample ActionLink call: // I've made it generic, but this should call the Search action of the // ItemController, the text and title attribute should say "Link Text" but there// should be no parameters - or maybe just the defaults, depending on the route.// // Assume that this can be called from *any* page but should not be influenced by// the current route - some routes will be called from other sections with the same// structure/parameters.Html.ActionLink( "Link Text", "Search", "Item", new { }, new { title = "Link Text" } ); Now provide the response and nothing else.
Setting route values to be null or empty string when calling Html.ActionLink or Html.RouteLink (or any URL generation method) will clear out the "ambient" route values. For example, with the standard MVC controller/action/id route suppose you're on "Home/Index/123". If you call Html.RouteLink(new { id = 456 }) then MVC will notice the "ambient" route values of controller="Home" and action="Index" . It will also notice the ambient route value of id="123" but that will get overwritten by the explicit "456". This will cause the generated URL to be "Home/Index/456". The ordering of the parameters matters as well. For example, say you called Html.RouteLink(new { action = "About" }) . The "About" action would overwrite the current "Index" action, and the "id" parameter would get cleared out entirely! But why, you ask? Because once you invalidate a parameter segment then all parameter segments after it will get invalidated. In this case, "action" was invalidated by a new explicit value so the "id", which comes after it, and has no explicit value, also gets invalidated. Thus, the generated URL would be just "Home/About" (without an ID). In this same scenario if you called Html.RouteLink(new { action = "" }) then the generated URL would be just "Home" because you invalidated the "action" with an empty string, and then that caused the "id" to be invalidated as well because it came after the invalidated "action".
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1817421', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32935/']}
jdg_82799
stackexchange
llm_judgeable_groundtruth_similarity
82157
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: This is probably a very trivial question, still I don't seem to find an answer. I'd like to see an example (in some language) of two countable structures $\mathcal{M}_1 $ and $ \mathcal{M}_2 $ with $$ \mathcal{M}_1 \equiv\mathcal{M}_2 $$ and the property that there is no elementary embedding from either one to the other. Maybe also another one: the same setting as above, but with existing embeddings, just no elementary embeddings.Are there such examples? Now provide the response and nothing else.
Take two mutually transcendental real numbers $s$ and $t$ and consider the ordered fields $\mathbb{Q}[r]$ and $\mathbb{Q}[s]$. These are elementarily equivalent but there is no embedding from one to the other because the type defined by either $r$ or $s$ defines a Dedekind cut in the rationals that can be filled in one field but not the other.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/82157', 'https://mathoverflow.net', 'https://mathoverflow.net/users/16989/']}
jdg_82800
stackexchange
llm_judgeable_groundtruth_similarity
4041007
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need to find a solution to this differential equation $(1+x^2) $$\tfrac{\mathrm{d}y}{\mathrm{d}x} = x-xy^2$ , with boundary condition $y=2$ at $x=0$ I collect all terms on the RHS to get $$\tfrac{\mathrm{d}y}{\mathrm{d}x} = \frac{x}{1+x^2} (1-y^2)$$ I integrate then move the y terms to the left side and integrate both sides and simplify to get $$\frac{1}{\sqrt{1-y^2}} = k\sqrt{1+x^2}$$ I then isolate y in order to get it in a y= form and sub in the y and x value but I don't get the correct answer; I'm not sure where I'm going wrong Now provide the response and nothing else.
We show that $P_n : a_n < 2^n$ is true. for $n=1$ , it's ok. for $n >1$ , suppose $P_1,...,P_{n-1}$ . We see that $$a_n = a_{n-3}+a_{n-2}+a_{n-1} \le 2^{n-3}+2^{n-2} + 2^{n-1}=2^n(\frac{1}{2^3}+\frac{1}{2^2}+\frac{1}{2})<2^n$$ So $P_n$ is true. Here are some comments about your proof: The way you stated your inductive hypothesis is odd (to me). Also here we know that $a_n$ is defined by induction so using strong induction is a good idea. It seems to me that you got kind of lost when applying the hypothesis. You started your proof from the result not the hypothesis...
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4041007', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/854082/']}
jdg_82801
stackexchange
llm_judgeable_groundtruth_similarity
13006505
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I generate a pdf-file from a binary file retrieved from database in php5? It comes base64 encoded, and I just decoded it, but don't know what to do next... Now provide the response and nothing else.
The binary data is simply the actual file , or rather the important contents of that file, just without file name. $base64 = /* some base64 encoded data fetched from somewhere */;$binary = base64_decode($base64); And there you have the file data/contents of the file in the $binary variable. From here, it depends on what you want to do. You can write the data to a file, and you get an "actual" PDF file: file_put_contents('my.pdf', $binary); You can spit the data out to the browser with an appropriate header, and the user will receive something that looks like a PDF file to him: header('Content-type: application/pdf');header('Content-Disposition: attachment; filename="my.pdf"');echo $binary;
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13006505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/847123/']}
jdg_82802
stackexchange
llm_judgeable_groundtruth_similarity
276100
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 we show that $ \displaystyle \int_{0}^{\pi/2}\frac{1}{\sqrt{\sin{x}}}\;{dx}=\int_{0}^{\pi/2}\frac{2}{\sqrt{2-\sin^2{x}}}\;{dx}? $ It feels like it should be simple, but I've tried many things and no luck. Now provide the response and nothing else.
Let $\sin (x) = u $, we get$$ \int_0^1 \frac{1}{\sqrt u \sqrt{1 - u^2}}du = \int_0^1 \frac{1}{\sqrt u \sqrt{(1 - u)(1+u)}}du$$Again let $u = \cos ^2 y $ $$ \int_{\pi/2}^0 \frac{-2 \cos (y)\; \sin (y) \;dy}{\cos (y) \; \sin (y) \sqrt{1 + \cos^2 y}} = \int_0^{\pi \over 2} \frac{2}{\sqrt{2 - \sin^2 x}} dx $$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/276100', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/16261/']}
jdg_82803
stackexchange
llm_judgeable_groundtruth_similarity
37706370
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: An intermittent proxy was causing my pages to get cached with an asp.net core site I deployed. The web server was not caching pages. I added request and response caching to prevent any caching this proxy was causing In my Startup.cs app.UseStaticFiles(); app.UseIdentity(); app.Use(async (context, next) => { context.Response.Headers.Append("Cache-Control", "no-cache"); context.Response.Headers.Append("Cache-Control", "private, no-store"); context.Request.Headers.Append("Cache-Control", "no-cache"); context.Request.Headers.Append("Cache-Control", "private, no-store"); await next(); }); I can see in fiddler these no cache headers have been added to my pages as well as to javascript files, css files and image files. How do I limit this no caching headers to only apply to asp.net mvc pages so these no cache headers don't showup in fiddler for non page files like js,css, and image files Is there a way that for HTTP requests for css and js files to not check if the file exists on the server for every request, and rather just the browser version is used for the first get of those files. The reason I ask is that on heavy load (1000 users) I in Fiddler I notice I get 404 errors for HTTPGETs for my css,js and image file so I'm trying to limit the number of requests for those resources. When the requests are successful(not under load) I get 304 responses (not modified). Is there not a way to tell the browser to not make the request in the first place and use the local cached version. Now provide the response and nothing else.
app.UseStaticFiles(new StaticFileOptions(){ OnPrepareResponse = r => { string path = r.File.PhysicalPath; if (path.EndsWith(".css") || path.EndsWith(".js") || path.EndsWith(".gif") || path.EndsWith(".jpg") || path.EndsWith(".png") || path.EndsWith(".svg")) { TimeSpan maxAge = new TimeSpan(7, 0, 0, 0); r.Context.Response.Headers.Append("Cache-Control", "max-age=" + maxAge.TotalSeconds.ToString("0")); } }});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37706370', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2349045/']}
jdg_82804
stackexchange
llm_judgeable_groundtruth_similarity
95962
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 just went through Observation of Dirac monopoles in a synthetic magnetic field . What exactly has been observed? More importantly, are these monopoles localized inside the apparatus (no stray monopole field lines coming out), or can they be used to create tangible monopoles? (By tangible monopoles I mean an object that is overall a monopole without any external influence. It may contain a condensate or similar inside) Now provide the response and nothing else.
Let me make quite clear that the recent experiment does NOT imply the detection of a true magnetic monopole. Somehow, in all the excitement, the word "synthetic" was dropped rather quickly from the phrase "synthetic magnetic field". A synthetic magnetic field is a physical quantity that obeys the same equations as a magnetic field, typically realized in things like the velocity field of the atoms inside a BEC. The recent paper claims the observation of the analogue of a Dirac monopole in such a quantity, and it is a significant result in the field of quantum simulation. However, their experiment is made completely out of atoms, and therefore of protons, neutrons and electrons. It cannot have any magnetic flux into or out of any region within or around it, and it does not violate the laws of electromagnetism. Indeed, it's built within them. Synthetic magnetic fields are explained nicely in this review: Colloquium: Artificial gauge potentials for neutral atoms. Jean Dalibard et al. Rev. Mod. Phys. 83 no. 4, 1523–1543 (2011) . arXiv:1008.5378 . They describe a simple toy model which captures, I think the basics of the recent experiment. Consider a two-level atom which is at the influence of an external field which couples its two internal states. Its hamiltonian can be written as$$H=\left(\frac{P^2}{2m}+V\right)+U,$$where the part in brackets does not couple to the internal state, and$$U=\frac{\hbar\Omega}{2}\begin{pmatrix}\cos\theta&e^{-i\phi}\sin\theta \\ e^{i\phi}\sin\theta & -\cos\theta\end{pmatrix}$$in the ground - excited state basis $\{|g\rangle,|e\rangle\}$. In such a scheme $\Omega$ is the Rabi frequency and determines the strength of the coupling; $\phi$ is the phase of the laser that's used to couple the states; and $\theta$ is called the mixing angle and determines whether the coupling acts more like a Stark shift (at $\theta=0$), more like a pure coupling (at $\theta=\pi/2$), or somewhere in between. The distinction between those regimes is dependent on the detuning to the atomic transition, and it can vary with the atom's position $\mathbf{r}$. The game here is to have the atom move around slowly enough that it will always stay in the ground state of the laser-induced atomic hamiltonian $U$. This is the first of the two eigenstates$$|\chi_1\rangle=\begin{pmatrix}\cos(\theta/2) \\ e^{i\phi}\sin(\theta/2)\end{pmatrix},\quad|\chi_2\rangle=\begin{pmatrix}-e^{-i\phi}\sin(\theta/2)\\ \cos(\theta/2)\end{pmatrix},$$which depend on the position $\mathbf{r}$ through the laser parameters $\theta$ and $\phi$. If you vary these parameters slowly enough, you will stay in the same eigenstate as you started in, without any nonadiabatic transitions. More precisely, because the states $|\chi_j\rangle$ are a basis, one can always write the atom's wavefunction as$$|\Psi(\mathbf{r},t)\rangle=\langle \mathbf{r}|\Psi(t)\rangle=\sum_j\psi_j(\mathbf{r},t)|\chi_j(\mathbf{r})\rangle.$$(Note that this is the position-dependent internal state, which can be obtained from the full state $|\Psi(t)\rangle$ by projecting on a position state $|\mathbf{r}\rangle$.) If the atom's velocity spread is small enough, it will never transition to $|\chi_2\rangle$ and one can describe the system simply in terms of a single Schrödinger equation for $\psi_1(\mathbf{r},t)$. To get that equation, you first have to work rigorously with the full state, and then afterwards neglect the possibility of transitions. Thus, if you act with the momentum $\mathbf{P}=-i\hbar\nabla$ on the component $\psi_j(\mathbf{r},t) |\chi_j(\mathbf{r})\rangle$, you will get contributions from both factors:$$\nabla\left[\psi_j(\mathbf{r},t)|\chi_j(\mathbf{r})\rangle\right]=\left(\nabla\psi_j(\mathbf{r},t)\right)|\chi_j(\mathbf{r})\rangle+\psi_j(\mathbf{r},t)\nabla_\mathbf{r}|\chi_j(\mathbf{r})\rangle.$$Multiplying on the left with the completeness relation $\sum_i|\chi_i\rangle\langle\chi_i|$, we can obtain a nice expression for the action of the momentum:$$\mathbf{P}\psi_j(\mathbf{r},t)|\chi_j(\mathbf{r})\rangle=\sum_i|\chi_i\rangle\left[\delta_{ij}\mathbf{P}-\mathbf{A}_{ij}\right]\psi_j(\mathbf{r},t),$$where $\mathbf{A}_{ij}=i\hbar\langle\chi_i|\nabla_\mathbf{r}|\chi_j\rangle$ is, broadly speaking, the rate at which nonadiabatic transitions can occur. Dotting this again with the momentum operator, one obtains$$P^2\psi_j(\mathbf{r},t)|\chi_j(\mathbf{r})\rangle=\sum_{l,i}|\chi_l\rangle(\delta_{li}\mathbf{P}-\mathbf{A}_{li})(\delta_{ij}\mathbf{P}-\mathbf{A}_{ij})\psi_j(\mathbf{r},t),$$as long as one can neglect a term in $\nabla\cdot\mathbf{A}_{ij}=i\hbar\nabla\cdot\langle\chi_i|\nabla_\mathbf{r}\chi_j\rangle$. This corresponds to saying that the potential's variation is only relevant to first order at the low momenta encompassed by $\Psi$. One can then neglect the possibility of transitions, and simply ignore all the terms that have $|\chi_2\rangle$ in them. (Or one might not, in which case you can try and build non-Abelian gauge fields instead.) If you do this, all the sums go away, and you get the simple Schrödinger equation$$i\hbar\frac{\partial\psi_1}{\partial t}=\left[\frac{1}{2m}(\mathbf{P}-\mathbf{A})^2+V+\frac{\hbar\Omega}{2}+W.\right]\psi_1$$ This equation is identical in form to that of a single particle under the action of the old potential $V$, an 'electrostatic potential'$$W=\frac{\hbar^2}{2m}|\langle\chi_2|\nabla\chi_1\rangle|^2$$which measures virtual transitions from $|\chi_1\rangle$ to $|\chi_2\rangle$ and back, and a magnetic field with vector potential $$\mathbf{A}=i\hbar\langle\chi_1|\nabla_\mathbf{r}|\chi_1\rangle.$$This magnetic field will be nonzero whenever $\theta$ and $\phi$ both have significant spatial dependence with non-collinear gradients. Most importantly, this 'magnetic field' depends on experimentally controllable parameters through $\theta(\mathbf{r})$ and $\phi(\mathbf{r})$. If one can build a sufficiently clever experiment, the 'field' $\mathbf{B}$, which is really the vector field$$\nabla\times\langle\chi_1|\nabla\chi_1\rangle,$$can exhibit monopolar behaviour. One can create 'coupled' monopoles (i.e. separated by a finite Dirac string) or even take one of those out of the cloud to make a 'true' Dirac monopole as far as the cloud is concerned. It is my understanding that this is the case for the recent experiment. This does not, of course, imply that any net real magnetic flux is coming out of that apparatus.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/95962', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/7433/']}
jdg_82805
stackexchange
llm_judgeable_groundtruth_similarity
18896154
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 automating the publication of my Android app and I'm using Gradle , great utility! Just a problem, consider this .bat file (under Windows 7): :: assemble the projectgradle assemble -Pprofile_name=%profile_name% -p%destination_dir%::copy apk to repositorycopy "D:\compile\myapp\build\apk\*.apk" "d:\build_repository" Well the copy command is never executed, never. It seems that the execution stops after calling gradle utility. Any idea? The build within Gradle has ends with success and no error at all... Now provide the response and nothing else.
I ran into this very same problem, but for a webapp. Gradle isn't necessarily the issue, but how you are invoking it. As explained in this post, How to execute more than one maven command in bat file? because gradle is a batch file itself, it completes execution and doesn't return control back to your batch file. Use the same 'call' strategy and everything should work.Like so for your original post, call gradle assemble -Pprofile_name=%profile_name% -p%destination_dir%::copy apk to repositorycopy "D:\compile\myapp\build\apk\*.apk" "d:\build_repository"
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18896154', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1331488/']}
jdg_82806
stackexchange
llm_judgeable_groundtruth_similarity
37588733
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 exact Exception is as follows com.datastax.driver.core.exceptions.CodecNotFoundException: Codec not found for requested operation: [varchar <-> java.math.BigDecimal] These are the versions of Software I am usingSpark 1.5 Datastax-cassandra 3.2.1CDH 5.5.1 The code I am trying to execute is a Spark program using the java api and it basically reads data (csv's) from hdfs and loads it into cassandra tables . I am using the spark-cassandra-connector. I had a lot of issues regarding the google s guava library conflict initially which I was able to resolve by shading the guava library and building a snap-shot jar with all the dependencies. However I was able to load data for some files but for some files I get the Codec Exception . When I researched on this issue I got these following threads on the same issue. https://groups.google.com/a/lists.datastax.com/forum/#!topic/java-driver-user/yZyaOQ-wazk https://groups.google.com/a/lists.datastax.com/forum/#!topic/java-driver-user/yZyaOQ-wazk After going through these discussion what I understand is either it is a wrong version of the cassandra-driver I am using . Or there is still a class path issue related to the guava library as cassandra 3.0 and later versions use guava 16.0.1 and the discussions above say that there might be a lower version of the guava present in the class path . Here is pom.xml file <dependencies> <dependency><groupId>org.apache.spark</groupId><artifactId>spark-core_2.10</artifactId><version>1.5.0</version> </dependency><dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope></dependency><dependency><groupId>com.datastax.spark</groupId><artifactId>spark-cassandra-connector-java_2.10</artifactId><version>1.5.0-M3</version></dependency><dependency><groupId>org.apache.cassandra</groupId><artifactId>cassandra-clientutil</artifactId><version>3.2.1</version></dependency></dependencies> <build><plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.3</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <filters> <filter> <artifact>*:*</artifact> <excludes> <exclude>META-INF/*.SF</exclude> <exclude>META-INF/*.DSA</exclude> <exclude>META-INF/*.RSA</exclude> </excludes> </filter></filters> <relocations> <relocation> <pattern>com.google</pattern> <shadedPattern>com.pointcross.shaded.google</shadedPattern> </relocation> </relocations> <minimizeJar>false</minimizeJar> <shadedArtifactAttached>true</shadedArtifactAttached> </configuration> </execution> </executions> </plugin></plugins></build></project> and these are the dependencies that were downloaded using the above pom spark-core_2.10-1.5.0.jarspark-cassandra-connector- java_2.10-1.5.0-M3.jarspark-cassandra-connector_2.10-1.5.0-M3.jarspark-repl_2.10-1.5.1.jarspark-bagel_2.10-1.5.1.jarspark-mllib_2.10-1.5.1.jarspark-streaming_2.10-1.5.1.jarspark-graphx_2.10-1.5.1.jarguava-16.0.1.jarcassandra-clientutil-3.2.1.jarcassandra-driver-core-3.0.0-alpha4.jar Above are some of the main dependencies on in my snap-shot jar. Y is the CodecNotFoundException ? Is it because of the class path (guava) ? or cassandra-driver (cassandra-driver-core-3.0.0-alpha4.jar for datastax cassandra 3.2.1) or because of the code . Another point is all the dates I am inserting to columns who's data type is timestamp . Also when I do a spark-submit I see the class path in the logs , There are other guava versions which are under the hadoop libs . R these causing the problem ? How do we specify the a user-specific class path while do a spark-submit. Will that help ? Would be glad to get some points on these.Thanks Following is the stacktrace com.datastax.driver.core.exceptions.CodecNotFoundException: Codec not found for requested operation: [timestamp <-> java.lang.String]at com.datastax.driver.core.CodecRegistry.notFound(CodecRegistry.java:689)at com.datastax.driver.core.CodecRegistry.createCodec(CodecRegistry.java:550)at com.datastax.driver.core.CodecRegistry.findCodec(CodecRegistry.java:530)at com.datastax.driver.core.CodecRegistry.codecFor(CodecRegistry.java:485)at com.datastax.driver.core.AbstractGettableByIndexData.codecFor(AbstractGettableByIndexData.java:85)at com.datastax.driver.core.BoundStatement.bind(BoundStatement.java:198)at com.datastax.driver.core.DefaultPreparedStatement.bind(DefaultPreparedStatement.java:126)at com.cassandra.test.LoadDataToCassandra$1.call(LoadDataToCassandra.java:223)at com.cassandra.test.LoadDataToCassandra$1.call(LoadDataToCassandra.java:1)at org.apache.spark.api.java.JavaPairRDD$$anonfun$toScalaFunction$1.apply(JavaPairRDD.scala:1027)at scala.collection.Iterator$$anon$11.next(Iterator.scala:328)at org.apache.spark.util.Utils$.getIteratorSize(Utils.scala:1555)at org.apache.spark.rdd.RDD$$anonfun$count$1.apply(RDD.scala:1121)at org.apache.spark.rdd.RDD$$anonfun$count$1.apply(RDD.scala:1121)at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1850)at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1850)at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)at org.apache.spark.scheduler.Task.run(Task.scala:88)at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)at java.lang.Thread.run(Thread.java:745) I also got com.datastax.driver.core.exceptions.CodecNotFoundException: Codec not found for requested operation: [Math.BigDecimal <-> java.lang.String] Now provide the response and nothing else.
When you call bind(params...) on a PreparedStatement the driver expects you to provide values w/ java types that map to the cql types. This error ( [timestamp <-> java.lang.String] ) is telling you that there is no such Codec registered that maps the java String to a cql timestamp . In the java driver, the timestamp type maps to java.util.Date . So you have 2 options here: Where the column being bound is for a timestamp, provide a Date -typed value instead of a String . Create a codec that maps timestamp <-> String . To do so you could create sub class of MappingCodec as described on the documentation site , that maps String to timestamp: public class TimestampAsStringCodec extends MappingCodec<String, Date> { public TimestampAsStringCodec() { super(TypeCodec.timestamp(), String.class); } @Override protected Date serialize(String value) { ... } @Override protected String deserialize(Date value) { ... }} You then would need to register the Codec: cluster.getConfiguration().getCodecRegistry() .register(new TimestampAsStringCodec());
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37588733', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4653573/']}
jdg_82807
stackexchange
llm_judgeable_groundtruth_similarity
304699
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: What is auxiliary loss that is mentioned in the PSPNet(Pyramid Scene Parsing Network) paper link ? I'm quoting the part of the paper down below An example of our deeply supervised ResNet101 [13] model is illustrated in Fig. 4. Apart from the main branch using softmax loss to train the final classifier, another classifier is applied after the fourth stage, i.e., the res4b22 residue block. Different from relay backpropagation [32] that blocks the backward auxiliary loss to several shallow layers, we let the two loss functions pass through all previous layers. The auxiliary loss helps optimize the learning process, while the master branch loss takes the most responsibility. We add weight to balance the auxiliary loss. My question is how does this auxiliary loss work and how does it help in training process. What is its work in the network ? Now provide the response and nothing else.
The idea of auxiliary loss (aka auxiliary towers) comes from GoogLeNet paper . At core intuition can be explained in this way: Let's say you are building a network by stacking up lots of identical modules. As network becomes deeper, you face slowed down training because of vanishing gradient issue (this was before BatchNorm days). To promote learning for each module layer, you can attach some small network to the output of that module. This network typically have a couple of conv layers followed by FCs and then final classification prediction. This auxiliary network's task is to predict same label as final network would predict but using the module's output. We add the loss of this aux network to the final loss of the entire network weighted by some value < 1. For example, in GoogLeNet, you can see two tower like aux networks on the right ending in orange nodes: Now, if the module is learning slowly then it would generate big loss and cause gradient flow in that module helping gradients further downstream as well. This technique has apparently found to help training for very deep networks. Even when using batch norm, this can help to accelerate training during early cycles when weights are randomly initialized. Many NAS architecture uses this technique for initial evaluation during the search as you have a very limited budget to run epochs when evaluating 1000s of architectures so early acceleration improves performance. As aux networks are removed from the final model, it is not considered "cheating".
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/304699', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/133443/']}
jdg_82808
stackexchange
llm_judgeable_groundtruth_similarity
49367492
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_READ_ONLY flag: "0" by default, "1" if the row cannot be modified or deletedexcept by a sync adapter. See CALLER_IS_SYNCADAPTER. Type: INTEGERConstant Value: "is_read_only" When I have apply the above in my code, I am getting -1 as the output for all the contacts. I am using IS_READ_ONLY to identify the read only contacts synced in WhatsApp, PayTM, Duo, etc. Cursor curContacts = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); if (curContacts != null) { while (curContacts.moveToNext()) { int contactsReadOnly = curContacts.getColumnIndex(ContactsContract.Data.IS_READ_ONLY); Log.d(Config.TAG, String.valueOf(contactsReadOnly)); } } OutPut -1-1-1 Have also tried the below line instead of Data.IS_READ_ONLY , but the output is same. int contactsReadOnly = curContacts.getColumnIndex(ContactsContract.RawContacts.RAW_CONTACT_IS_READ_ONLY); Now provide the response and nothing else.
My answer does not assume that ICMP ping is allowed, it uses TCP based measures. But you will have to ensure there are security group rules to allow access from the shell running the tests to the RDS instance First, ensure some useful packages are installed apt-get install netcat-openbsd traceroute Check that basic connectivity works to the database port. This example is for Oracle, ensure you use the endpoint and port from the console nc -vz dev-fulfil.cvxzodonju67.eu-west-1.rds.amazonaws.com 1521 Then see what the latency is. The number you want is the final one (step 12) sudo tcptraceroute dev-fulfil.cvxzodonju67.eu-west-1.rds.amazonaws.com 1521traceroute to dev-fulfil.cvxzodonju67.eu-west-1.rds.amazonaws.com (10.32.21.12), 30 hops max, 60 byte packets 1 pc-0-3.ioppublishing.com (172.16.0.3) 0.691 ms 3.341 ms 3.400 ms 2 10.100.101.1 (10.100.101.1) 0.839 ms 0.828 ms 0.811 ms 3 xe-10-2-0-12265.lon-001-score-1-re1.interoute.net (194.150.1.229) 10.591 ms 10.608 ms 10.592 ms 4 ae0-0.lon-001-score-2-re0.claranet.net (84.233.200.190) 10.575 ms 10.668 ms 10.668 ms 5 ae2-0.lon-004-score-1-re0.claranet.net (84.233.200.186) 12.708 ms 12.734 ms 12.717 ms 6 169.254.254.6 (169.254.254.6) 12.673 ms * * 7 169.254.254.1 (169.254.254.1) 10.623 ms 10.642 ms 10.823 ms 8 * * * 9 * * *10 * * *11 * * *12 * 10.32.21.12 (10.32.21.12) <syn,ack> 20.662 ms 21.305 ms A better measure of "latency" might be "the time a typical transaction takes with no or little data to transfer". To do this, write a script element that does this in a loop, maybe 1000 times and then time it with a high precision timer. But the exact details of this vary according to your needs
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49367492', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8041854/']}
jdg_82809
stackexchange
llm_judgeable_groundtruth_similarity
3099515
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: Each of the two cabinets has 3 drawers. Cabinet I contains a gold coin in each drawer and cabinet II contains a gold coin in one of its drawers and a silver coin in the other. A cabinet is randomly selected ,one of its drawers is opened and a gold coin is found. Find the probability that there is a gold coin in the other drawer. The answer given in book is 3/4 Now provide the response and nothing else.
I have no idea what $C$ is doing there. There is no need to specify the event that a cabinet is chosen, as that event is guaranteed to happen, and doesn't affect any probabilities. Try using the events $L$ for picking the left cabinet and $G$ for picking a gold drawer. You want $$P(L\mid G)=\frac{P(L\cap G)}{P(G)}$$ $P(L\cap G)=P(L)$ is immediately seen to be $\frac12$ , while $P(G)$ takes some calculation. Alternately, as long as we are in land the land of assuming that $G$ occurs, there are $4$ equally likely possibilities. Three of them are in the all-gold cabinet and one isn't.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3099515', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/606943/']}
jdg_82810
stackexchange
llm_judgeable_groundtruth_similarity
173249
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: A linear inverse problem is given by: $\ \mathbf{d}=\mathbf{A}\mathbf{m}+\mathbf{e}$ where d: observed data, A: theory operator, m: unknown model and e: error. To minimize the effect of the noise; a Least Square Error (LSE) model estimate is commonly used: $\ \mathbf{\tilde{m}}=(\mathbf{A^\top A})^{-1}\mathbf{A^\top d}$ As an example problem I am considering the model: $\ T(x,z) = 0.5*sin(2\pi*x) - z$ My observed data is the noisy partial derivatives of T: $\ P(x,z)=T_x+e$ $\ Q(x,z)=T_z+e$ By introducing matrix finite difference operators I can formulate these two pdes as linear equations: $\ \mathbf{P=D_x*T} $ $\ \mathbf{Q=D_z*T} $ Below is the LSE solution of these equations: There is one big problem with this solution:in the model the line where T=0 goes between z=-0.5 and z=0.5,whereas in the estimate it goes between z=-1 and z=1.Some "scaling" of the z coordinate seems to be taking place. Why is this happening? Other than this the solution is quite good except for the blocky pattern.This pattern seems to be related to the sampling; the finer the sampling the finer the blocky pattern. What is the explanation for this pattern? In order to get a smoother solution I tested with a smoothing regularization constraint: $\ a*\mathbf{L*T}=0$ where a is a scaling parameter and L is the finite difference Laplacian matrix. I noticed a trade-off between smoothness and correctness depending on the scaling parameter. For large scaling parameters the sine wave pattern of the model turns into a square wave pattern: How can I determine a suitable a? Inverse problems are often troubled by instabilities which make it necessary to introduce a dampening regularization term.This does not seem to be the case for this problem.However since A is not square I could not find its condition number using cond() in Matlab. Is there some way in Matlab to find if an LSE problem with a nonsquare matrix is unstable? BTW Here is the Matlab code I used: % number of samples in x and z direction:n = 101;% amount of noise added to partial derivatives:e = 0.5;x = linspace(-1,1,n);z = linspace(-1,1,n);dx = x(2) - x(1);dz = z(2) - z(1);[X,Z] = meshgrid(x,z);% Hidden model:subplot(1,3,1);T = 0.5*sin(2*pi*X) - Z;imagesc(x,z,T);xlabel('x');ylabel('z');title('T = 0.5*sin(2*pi*x) - z');colorbar;% Observed noisy data:P = pi*cos(2*pi*X) + e*randn(n,n); % TxQ = -ones(n,n) + e*randn(n,n); % Tzsubplot(1,3,2);imagesc(x,z,P);xlabel('x');ylabel('z');title('P = Tx + e');colorbar;subplot(1,3,3);imagesc(x,z,Q);xlabel('x');ylabel('z');title('Q = Tz + e');colorbar;% Central difference matrices:E = sparse(2:n, 1:n-1, 1, n, n);D = (E' - E) / 2;I = speye(n); Dx = kron(D,I)/dx;Dz = kron(I,D)/dz;A = []; b = [];A = [A; Dx]; b = [b; P(:)]; A = [A; Dz]; b = [b; Q(:)];% Least Squares Solution:figure;subplot(1,2,1);imagesc(x,z,T);xlabel('x');ylabel('z');title('T');colorbar;tlse = lsqr(A, b, 1e-3, 1000*100);Tlse = reshape(tlse, [n n]);subplot(1,2,2);imagesc(x,z,Tlse);xlabel('x');ylabel('z');title('Tlse');colorbar;figure;% Least Squares Solution regularized by smoothing Laplace operator:D2 = E + E' + sparse(1:n, 1:n, -2, n, n);Dxx = kron(D2,I)/(dx^2);Dzz = kron(I,D2)/(dz^2);L = Dxx + Dzz;ns = 3;si = 1;for si = 1 : ns; subplot(1,ns,si); % regularization: a = (si - 1)*5e-4; Ar = [A; a*L]; br = [b; zeros(n^2,1)]; tlse = lsqr(Ar, br, 1e-3, 1000*100); Tlse = reshape(tlse, [n n]); imagesc(x,z,Tlse); str = sprintf('Tlse a=%g',a); title(str); si = si + 1;end EDIT:My central difference matrix D had an edge problem. As an example for size n=5:was: D = 0 0.5000 0 0 0 -0.5000 0 0.5000 0 0 0 -0.5000 0 0.5000 0 0 0 -0.5000 0 0.5000 0 0 0 -0.5000 0 Rewrote this to D = -1.0000 1.0000 0 0 0 -0.5000 0 0.5000 0 0 0 -0.5000 0 0.5000 0 0 0 -0.5000 0 0.5000 0 0 0 -1.0000 1.0000 With more correct difference matrices I get much nicer results: And this is without any regularization. Sorry for the sloppiness. I learned a lot tough :-). Thanks for your answers! Now provide the response and nothing else.
Factor of 2 Can't be sure, but it looks like your central difference matrix has an extra factor of 1/2 that shouldn't be there. That would cause the estimate to be incorrectly scaled by (1/2*1/2)^-1*(1/2)=2. Condition number The relevant condition number is the condition number of $A^T A$, since that is the matrix that is getting inverted. Choice of regularization parameter Choosing the regularization parameter is a classic problem, for which there is a vast literature and many methods. A good book on the subject is "Regularization of Inverse Problems" by Engl, Hanke, and Neubauer (though it lacks recent developments). One particularly simple but effective method is the discrepancy principle. Discrepancy principle: Choose the regularization parameter so that the least square error residual is approximately the same size as the noise level. Eg, if the expected noise level is $\delta$, start with $k=0$ and solve the inverse problem with $\alpha=1/2^k$. Then check if $||Am-d||<\delta$. If it is, stop, if it isn't, set $k=k+1$ and repeat. What is the source of the blocky noise For ill-posed inverse problems, the eigenfunctions of the forward operator are generally higher and higher frequency oscillatory functions, with smaller and smaller eigenvalues decaying to zero. When you try to invert, those high frequency modes get amplified. If you have a look at your noise, you see it looks like someone added a high frequency sinusoid on top of the true function - there was a little tiny bit of noise in that high frequency sinusoidal component, and it got amplified hugely by $(A^TA)^{-1}$. There was also noise in the other components, but it didn't get amplified as much since their eigenvalues are larger (so 1/eigenvalue is smaller). If you want a visual demonstration of what's happening, compute eig($A^TA$), and plot the last eigenfunction. Mesh as regularization A coarse mesh can act as regularization, if the nature of the mesh averages out the high frequency components. Meshes can actually be chosen for the purpose of regularization - doing so adaptively is actually an area of current research!
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/173249', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/9855/']}
jdg_82811
stackexchange
llm_judgeable_groundtruth_similarity
935493
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need help evaluating $$\int 4x \sqrt{1 - x^4} dx$$ What I have tried so far: Rewriting the integral as $$\int \frac{4x}{\sqrt{1 - x^4}} (1 - x^4) dx$$ $$\int \frac{4x}{\sqrt{1 - x^4}}dx - \int \frac{4x^5}{\sqrt{1 - x^4}} dx$$ The first integral I can evaluate using substituting $t = x^2, dt = 2xdx$ $$\int \frac{2}{\sqrt{1 - t^2}} dt = 2 \sin^{-1} t$$ I tried the same substitution on the second integral: $$\int \frac{2t^2}{\sqrt{1 - t^2}}dt $$ But now I am stuck. Am I going in the right direction? edit: trying out integration by parts. That just struck me. Now provide the response and nothing else.
I recommend starting from scratch, with the substitution $x^2=\sin\theta$, so that $2x\,dx=\cos\theta \,d\theta$ and $\sqrt{1-x^4}=\sqrt{1-\sin^2\theta}=\cos\theta$. Thus, using a couple of other standard trig identities, $$\int4x\sqrt{1-x^4}\,dx=\int2\cos^2\theta\,d\theta=\int(1+\cos2\theta)\,d\theta\\=\theta+{1\over2}\sin2\theta+C\\ =\theta+\sin\theta\cos\theta+C\\=\arcsin(x^2)+x^2\sqrt{1-x^4}+C$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/935493', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/92774/']}
jdg_82812
stackexchange
llm_judgeable_groundtruth_similarity
740036
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 don't follow the section of the solution highlighted. I am attempting to compute the parameters of a gamma function by the Method of moments. Now provide the response and nothing else.
Let $X$ be a finite set and $R \subseteq X^2$ be some binary relation. Then $R$ is very similar to a directed graph that has elements of $X$ as vertices, or in other words, $R$ can be drawn as dots and arrows. The following example depicts a graph and corresponding relation.$$\begin{array}{ccc}1 &\to& \stackrel{\curvearrowright} 2 \\\downarrow & & \updownarrow\\3 & \gets & 4\end{array}$$$$\{(1,2),(1,3),(2,2),(2,4),(4,2),(4,3)\}$$ Now, to talk about equivalence classes we need an equivalence relation. How an appropriate graph looks like? It has to be reflexive, that is, each vertex $v$ has to have a loop $\stackrel{\curvearrowleft}v$ like $2$ in the previous example. It has to be symmetric, i.e. each edge of the graph has to be bidirectional, like $\{2,4\}$ in the above diagram. If all the edges are bidirectional, then such graph is called undirected. It has to be transitive. This means that the graphs includes all the possible "shortcuts", i.e. if you can get from vertex $u$ to $v$, then there is an edge $u \to v$, or in case of undirected graphs $u \leftrightarrow v$. The above conditions together imply that if some two vertices are connected, then they belong to a clique (a graph that has all the possible edges, modulo loops), that is, each connected component forms a clique. These cliques are precisely the equivalence classes . In the following diagram we have two: $\{1,2,3,4\}$ and $\{5,6,7\}$ (loops omitted for clarity). $$\begin{array}{ccc}1 &\leftrightarrow & 2 & & 5 & \leftrightarrow & 6\\\updownarrow & \swarrow\hspace{-10pt}\nearrow\hspace{-10pt}\nwarrow\hspace{-10pt}\searrow & \updownarrow & &\updownarrow & \swarrow\hspace{-10pt}\nearrow\\3 & \leftrightarrow & 4 & & 7\end{array}$$ Observe, that if we would add edge $4 \to 5$ then symmetry would require also $5 \to 4$ and then transitivity would add all the other edges. The two clusters would merge into a single equivalence class, i.e. the graph would become the $K_7$ clique. This intuition also holds for infinite sets, but it's hard to draw infinite graphs. I hope this helps $\ddot\smile$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/740036', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/138837/']}
jdg_82813
stackexchange
llm_judgeable_groundtruth_similarity
791533
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 question for all the hardcore low level hackers out there. I ran across this sentence in a blog. I don't really think the source matters (it's Haack if you really care) because it seems to be a common statement. For example, many modern 3-D Games have their high performance core engine written in C++ and Assembly. As far as the assembly goes - is the code written in assembly because you don't want a compiler emitting extra instructions or using excessive bytes, or are you using better algorithms that you can't express in C (or can't express without the compiler mussing them up)? I completely get that it's important to understand the low-level stuff. I just want to understand the why program in assembly after you do understand it. Now provide the response and nothing else.
I think you're misreading this statement: For example, many modern 3-D Games have their high performance core engine written in C++ and Assembly. Games (and most programs these days) aren't "written in assembly" the same way they're "written in C++". That blog isn't saying that a significant fraction of the game is designed in assembly, or that a team of programmers sit around and develop in assembly as their primary language. What this really means is that developers first write the game and get it working in C++. Then they profile it, figure out what the bottlenecks are, and if it's worthwhile they optimize the heck out of them in assembly. Or, if they're already experienced, they know which parts are going to be bottlenecks, and they've got optimized pieces sitting around from other games they've built. The point of programming in assembly is the same as it always has been: speed . It would be ridiculous to write a lot of code in assembler, but there are some optimizations the compiler isn't aware of, and for a small enough window of code, a human is going to do better. For example, for floating point, compilers tend to be pretty conservative and may not be aware of some of the more advanced features of your architecture. If you're willing to accept some error, you can usually do better than the compiler, and it's worth writing that little bit of code in assembly if you find that lots of time is spent on it. Here are some more relevant examples: Examples from Games Article from Intel about optimizing a game engine using SSE intrinsics. The final code uses intrinsics (not inline assembler), so the amount of pure assembly is very small. But they look at the assembler output by the compiler to figure out exactly what to optimize. Quake's fast inverse square root . Again, the routine doesn't have assembler in it, but you need to know something about architecture to do this kind of optimization. The authors know what operations are fast (multiply, shift) and which are slow (divide, sqrt). So they come up with a very tricky implementation of square root that avoids the slow operations entirely. High-Performance Computing Outside the domain of games, people in scientific computing frequently optimize the crap out of things to get them to run fast on the latest hardware. Think of this as games where you can't cheat on the physics. A great recent example of this is Lattice Quantum Chromodynamics (Lattice QCD) . This paper describes how the problem pretty much boils down to one very small computational kernel, which was optimized heavily for PowerPC 440's on an IBM Blue Gene/L . Each 440 has two FPUs, and they support some special ternary operations that are tricky for compilers to exploit. Without these optimizations, Lattice QCD would've run much slower, which is costly when your problem requires millions of CPU hours on expensive machines. If you are wondering why this is important, check out the article in Science that came out of this work. Using Lattice QCD, these guys calculated the mass of a proton from first principles, and showed last year that 90% of the mass comes from strong force binding energy, and the rest from quarks. That's E=mc 2 in action. Here's a summary . For all of the above, the applications are not designed or written 100% in assembly -- not even close. But when people really need speed, they focus on writing the key parts of their code to fly on specific hardware.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/791533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8435/']}
jdg_82814
stackexchange
llm_judgeable_groundtruth_similarity
39684548
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Need some help on processing data inside a pandas dataframe.Any help is most welcome. I have OHCLV data in CSV format. I have loaded the file in to pandas dataframe. How do I convert the volume column from 2.90K to 2900 or 5.2M to 5200000.The column can contain both K in form of thousands and M in millions. import pandas as pdfile_path = '/home/fatjoe/UCHM.csv'df = pd.read_csv(file_path, parse_dates=[0], index_col=0)df.columns = ["closing_price", "opening_price", "high_price", "low_price","volume","change"]df['opening_price'] = df['closing_price']df['opening_price'] = df['opening_price'].shift(-1)df = df.replace('-', 0)df = df[:-1]print(df.head())Console: Date 2016-09-23 0 2016-09-22 9.60K 2016-09-21 54.20K 2016-09-20 115.30K 2016-09-19 18.90K 2016-09-16 176.10K 2016-09-15 31.60K 2016-09-14 10.00K 2016-09-13 3.20K Now provide the response and nothing else.
assuming you have the following DF: In [30]: dfOut[30]: Date Val0 2016-09-23 1001 2016-09-22 9.60M2 2016-09-21 54.20K3 2016-09-20 115.30K4 2016-09-19 18.90K5 2016-09-16 176.10K6 2016-09-15 31.60K7 2016-09-14 10.00K8 2016-09-13 3.20M you can do it this way: In [31]: df.Val = (df.Val.replace(r'[KM]+$', '', regex=True).astype(float) * \ ....: df.Val.str.extract(r'[\d\.]+([KM]+)', expand=False) ....: .fillna(1) ....: .replace(['K','M'], [10**3, 10**6]).astype(int))In [32]: dfOut[32]: Date Val0 2016-09-23 100.01 2016-09-22 9600000.02 2016-09-21 54200.03 2016-09-20 115300.04 2016-09-19 18900.05 2016-09-16 176100.06 2016-09-15 31600.07 2016-09-14 10000.08 2016-09-13 3200000.0 Explanation: In [36]: df.Val.replace(r'[KM]+$', '', regex=True).astype(float)Out[36]:0 100.01 9.62 54.23 115.34 18.95 176.16 31.67 10.08 3.2Name: Val, dtype: float64In [37]: df.Val.str.extract(r'[\d\.]+([KM]+)', expand=False)Out[37]:0 NaN1 M2 K3 K4 K5 K6 K7 K8 MName: Val, dtype: objectIn [38]: df.Val.str.extract(r'[\d\.]+([KM]+)', expand=False).fillna(1)Out[38]:0 11 M2 K3 K4 K5 K6 K7 K8 MName: Val, dtype: objectIn [39]: df.Val.str.extract(r'[\d\.]+([KM]+)', expand=False).fillna(1).replace(['K','M'], [10**3, 10**6]).astype(int)Out[39]:0 11 10000002 10003 10004 10005 10006 10007 10008 1000000Name: Val, dtype: int32
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39684548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2408288/']}
jdg_82815
stackexchange
llm_judgeable_groundtruth_similarity
324984
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: As the title said, I'm trying to find solution in naturals numbers to $a^b=b^a$ with the help of the function $f(x)=\large\frac{\ln(x)}{x}$. I've been reading some solutions of that problem posted in math forums, and still don't know how to deduce, the obvious solutions, $(2,4)$ and $(4,2).$ Thank you very much! Now provide the response and nothing else.
Knowing that when $x > 0,\;\; x^y = e^{\large \ln x^y}= e^{y \ln x}$, we have, since $a, b \in \mathbb{N}:$ $$a^b = b^a \iff e^{b\ln a} = e^{a \ln b} \iff b \ln a = a\ln b$$ Now try dividing each side of the equation by $\;ab$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/324984', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/46105/']}
jdg_82816
stackexchange
llm_judgeable_groundtruth_similarity
280814
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: This is a question concerning the lemma discussed in Question about a proof about singular cardinals . In this question, it is proved that if an infinite cardinal $\kappa$ is singular, then it can be written as the sum of strictly smaller cardinals over a strictly smaller index set. What about the converse? If $\kappa=\sum_{\alpha<\lambda}\kappa_{\alpha}$, with $\lambda<\kappa$ and $\kappa_{\alpha}<\kappa$, then it follows easily that $\kappa=sup_{\alpha<\lambda}\kappa_{\alpha}$. But how do we get a strictly increasing sequence from this? Jech says by transfinite recursion, which I don't really know, so maybe there is a more elementary way of seeing it? Now provide the response and nothing else.
Looking at the valencies is not enough. A rearrangement of the labels is only a symmetry if labels that were connected by an edge before are connected after, and labels that were unconnected before are still unconnected after. This will preserve the valencies, but not every mapping that preserves valencies is a symmetry. For example, consider this graph: There are two symmetries here: you can have $ABCDE\to ABCDE$, or you can flip the whole thing over, $ABCDE\to EDCBA$. $B$ and $D$ are in symmetrical positions, and there is a symmetry taking $B\to D$ and $D\to B$. But there is no symmetry that takes $C\to D$ even though both have valence 2. $C$ is in the middle of the line, and $D$ is not. This should agree with the idea of "symmetry" that you had before you took this class. In your original graph, the point 3 can go to 10, but if it does, point 2, to which it is attached, must go to 8, which is attached to 10. Then point 4, which is also attached to 2, must go to 9. So once you've decided that 2 goes to 8, you know that 3 and 4, which were attached to 2, must go to 9 and 10, which are attached to 8. You get to choose whether $3\to9\atop 4\to 10$, or $3\to 10\atop 4\to 9$, but that's the only further choice you get about 3 and 4. As you noted, 1 must go to 1. (We'll deal with why that is later on.) Then 2, 5, and 8 must go to 2, 5, and 8, but each of those could go to any of the others, so there are 6 choices about how to arrange them. Let's say that we have $(2,5,8)\to(8,2,5)$ just as an example. Then 3 and 4, which were attached to 2 before, must be attached to 8 after, so they must go to 9 and 10. You can choose whether $$\begin{align}& 3\to9, & 4\to 10,\\ \text{ or } & 3\to 10,& 4\to 9,\end{align}$$ as in the previous paragraph. Then similarly you can choose whether $$\begin{align}& 6\to3, & 7\to 4,\\ \text{ or } & 6\to 4,& 7\to 3,\end{align}$$ and you can choose whether $$\begin{align}& 9\to6, & 10\to 7,\\ \text{ or } & 9\to 7,& 10\to 6.\end{align}$$ That means that after you choose one of six ways to map $2,5,8$, you get three independent choices about how to flip the forks at the ends of the arms. Each choice has two possible ways to go, so the total number of choices is $3!\cdot2!\cdot2!\cdot2! = 48$, and that's the answer. Now you said you are not sure why we must have $1\to 1$. Let's try $1\to 5$ and see what happens. Since 1 is attached to 258, and 5 is attached to 167 we must have each of 258 going to something in 167. But 258 all have valence 3 while 6 and 7 have valence only 1, so there is nothing that can go properly to 6 or to 7. So $1\to 5$ will never work. And 2 and 8 look just like 5, so $1\to 2$ and $1\to 8$ will fail for essentially the same reason.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/280814', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/55336/']}
jdg_82817
stackexchange
llm_judgeable_groundtruth_similarity
87542
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: It is known that exists formula for geting a square root of complex number without use of De Moivre formula. Will be interesting if we can find the cubic roots of complex numbers without using De Moivre formula. Now provide the response and nothing else.
It is not that widely taught that one is pretty much stuck when taking the cube root of a complex number. The theorem is called the Casus Irreducibilis If an irreducible cubic, with rational coefficients, has three real (and thereby irrational) roots, these may only be found by taking the cube roots of complex numbers, which is what one gets with Cardano's formula. Cardano gives the real roots, in brief, by taking the cube root of a complex number and adding the cube root of its complex conjugate. If one insists on separately finding the real and imaginary parts of the cube root of a complex number, one is led to finding roots of cubics with three real roots. So the whole thing is a bit circular, and in the end we must keep Cardano's description, no further "simplification" is possible. In conclusion, for cube roots of complex numbers, there is not really anything "better" than De Moivre.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/87542', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12848/']}
jdg_82818
stackexchange
llm_judgeable_groundtruth_similarity
12911524
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 implementing Tab environment as follow : There is one class TabScreenABCActivity extends TabActivity ,in that i have handled the tabchange functionality. I have implemented MyTabGroupActivity extends TabGroupActivity . From this class, i have called MyActivity like so: startChildActivity(getResources().getString(R.string.MyActivity), new Intent(this,MyActivity.class)); Now, MyActivity extends TabGroupActivity , from this class i called two other classes using intent like so: Intent intent=new Intent();intent.setClass(MyActivity.this,XYZActivity.class);TabGroupActivity tab = (TabGroupActivity) MyActivity.this.getParent();tab.startChildActivity("Tab", intent); I have also overridden method to go back Activity onBackPressed() method in each activity. But it is not working properly. Can anyone guide me on how to handle it? Now provide the response and nothing else.
Walter beat me to analysing the issue :-) Adding a bit of detail: It's correct that a JScrollPane supports mouseWheelHandling. According to the rules of mouseEvent dispatching, the top-most (in z-order) component gets the event, and that's the scrollPane around the textArea. So if wheeling the textarea is not required, a simple solution might be to disable the wheel-support in its scrollPane. And JScrollPane even has api for doing it: scrollPane.setWheelScrollingEnabled(false); Unfortunately, that doesn't work. Reason it's not working is that this property has no effect in the event dispatch chain which ultimately calls into eventTypeEnabled: case MouseEvent.MOUSE_WHEEL: if ((eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0 || mouseWheelListener != null) { return true; } This returns true if a mouseWheelListener is installed - which is done unconditionally by BasicScrollPaneUI, and not removed when the wheelEnabled property is changed (the ui doesn't even listen to that property ...) Plus the listener simply does nothing if the property is false. At least one of those facts is a bug, the ui should either remove/add the listener depending on wheelEnabled or: implement the listener such that it dispatches the event up the chain (as Walter does in his example) The first option can be handled by application code: scrollPane = new JScrollPane();scrollPane.removeMouseWheelListener(scrollPane.getMouseWheelListeners()[0]); it's a bit of a hack (as bug-workarounds always are :-), production code would have to listen to the wheelEnable to re-install if needed plus listen to LAF changes to update/re-remove the listeners installed by the ui. Implementing the second option in slight modification (as to Walter's dispatching) by subclassing the JScrollPane and dispatch the event to parent if the wheelEnabled is false: scrollPane = new JScrollPane() { @Override protected void processMouseWheelEvent(MouseWheelEvent e) { if (!isWheelScrollingEnabled()) { if (getParent() != null) getParent().dispatchEvent( SwingUtilities.convertMouseEvent(this, e, getParent())); return; } super.processMouseWheelEvent(e); }};scrollPane.setWheelScrollingEnabled(false);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12911524', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1428170/']}
jdg_82819
stackexchange
llm_judgeable_groundtruth_similarity
20318822
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: if(stopwatch >= track[song].duration) track[song].duration finds the duration of a soundcloud track. I am looking to create a stopwatch function that starts counting milliseconds when you click on the swap ID stopwatch so that when the function has been "clicked" for a certain amount of time the if function will do something. In my case replace an image. And also that the function will reset it itself when clicked again. so like stopwatch = current time - clicked time How can I set up the clicked time current time = new Date().getTime(); ? And is this in milliseconds? $('#swap').click(function()... Now provide the response and nothing else.
You'll see the demo code is just a start/stop/reset millisecond counter. If you want to do fanciful formatting on the time, that's completely up to you. This should be more than enough to get you started. This was a fun little project to work on. Here's how I'd approach it var Stopwatch = function(elem, options) { var timer = createTimer(), startButton = createButton("start", start), stopButton = createButton("stop", stop), resetButton = createButton("reset", reset), offset, clock, interval; // default options options = options || {}; options.delay = options.delay || 1; // append elements elem.appendChild(timer); elem.appendChild(startButton); elem.appendChild(stopButton); elem.appendChild(resetButton); // initialize reset(); // private functions function createTimer() { return document.createElement("span"); } function createButton(action, handler) { var a = document.createElement("a"); a.href = "#" + action; a.innerHTML = action; a.addEventListener("click", function(event) { handler(); event.preventDefault(); }); return a; } function start() { if (!interval) { offset = Date.now(); interval = setInterval(update, options.delay); } } function stop() { if (interval) { clearInterval(interval); interval = null; } } function reset() { clock = 0; render(0); } function update() { clock += delta(); render(); } function render() { timer.innerHTML = clock / 1000; } function delta() { var now = Date.now(), d = now - offset; offset = now; return d; } // public API this.start = start; this.stop = stop; this.reset = reset;};// basic examplesvar elems = document.getElementsByClassName("basic");for (var i = 0, len = elems.length; i < len; i++) { new Stopwatch(elems[i]);}// programmatic examplesvar a = document.getElementById("a-timer");aTimer = new Stopwatch(a);aTimer.start();var b = document.getElementById("b-timer");bTimer = new Stopwatch(b, { delay: 100});bTimer.start();var c = document.getElementById("c-timer");cTimer = new Stopwatch(c, { delay: 456});cTimer.start();var d = document.getElementById("d-timer");dTimer = new Stopwatch(d, { delay: 1000});dTimer.start(); .stopwatch { display: inline-block; background-color: white; border: 1px solid #eee; padding: 5px; margin: 5px;}.stopwatch span { font-weight: bold; display: block;}.stopwatch a { padding-right: 5px; text-decoration: none;} <h2>Basic example; update every 1 ms</h2><p>click <code>start</code> to start a stopwatch</p><pre>var elems = document.getElementsByClassName("basic"); for (var i=0, len=elems.length; i&lt;len; i++) { new Stopwatch(elems[i]);}</pre><div class="basic stopwatch"></div><div class="basic stopwatch"></div><hr><h2>Programmatic example</h2><p><strong>Note:</strong> despite the varying <code>delay</code> settings, each stopwatch displays the correct time (in seconds)</p><pre>var a = document.getElementById("a-timer");aTimer = new Stopwatch(a);aTimer.start();</pre><div class="stopwatch" id="a-timer"></div>1 ms<br><pre>var b = document.getElementById("b-timer");bTimer = new Stopwatch(b, {delay: 100});bTimer.start();</pre><div class="stopwatch" id="b-timer"></div>100 ms<br><pre>var c = document.getElementById("c-timer");cTimer = new Stopwatch(c, {delay: 456});cTimer.start();</pre><div class="stopwatch" id="c-timer"></div>456 ms<br><pre>var d = document.getElementById("d-timer");dTimer = new Stopwatch(d, {delay: 1000});dTimer.start();</pre><div class="stopwatch" id="d-timer"></div>1000 ms<br> Get some basic HTML wrappers for it <!-- create 3 stopwatches --><div class="stopwatch"></div><div class="stopwatch"></div><div class="stopwatch"></div> Usage is dead simple from there var elems = document.getElementsByClassName("stopwatch");for (var i=0, len=elems.length; i<len; i++) { new Stopwatch(elems[i]);} As a bonus, you get a programmable API for the timers as well. Here's a usage example var elem = document.getElementById("my-stopwatch");var timer = new Stopwatch(elem, {delay: 10});// start the timertimer.start();// stop the timertimer.stop();// reset the timertimer.reset(); jQuery plugin As for the jQuery portion, once you have nice code composition as above, writing a jQuery plugin is easy mode (function($) { var Stopwatch = function(elem, options) { // code from above... }; $.fn.stopwatch = function(options) { return this.each(function(idx, elem) { new Stopwatch(elem, options); }); };})(jQuery); jQuery plugin usage: // all elements with class .stopwatch; default delay (1 ms)$(".stopwatch").stopwatch();// a specific element with id #my-stopwatch; custom delay (10 ms)$("#my-stopwatch").stopwatch({delay: 10}); jsbin.com demo
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/20318822', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2768038/']}
jdg_82820
stackexchange
llm_judgeable_groundtruth_similarity
20528552
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 dialog Fragment which look like that. AlertDialog ad = builder.create();Drawable d = new ColorDrawable(Color.BLACK);d.setAlpha(130);ad.getWindow().setBackgroundDrawable(d); This code get background semi transparent. But I still got a white part on the bottom. I want to get rid of the white to just have semi transparent background I already tried a lot of stuff that I saw in other posts. I don't know what is the object that I must change between the DialogFragment, the AlertDialog and the LinearLayout. It may not be the LinearLayout, because when I increase margin, nothing is moving. Here is my code : @Overridepublic Dialog onCreateDialog(Bundle savedInstanceState) {// setStyle(DialogFragment.STYLE_NORMAL, 0);// setStyle(STYLE_NO_FRAME, R.style.CustomDialog);// setStyle(STYLE_NO_FRAME, 0); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); View view = getActivity().getLayoutInflater().inflate( R.layout.share_or_die, null); AlertDialog ad = builder.create(); Drawable d = new ColorDrawable(Color.BLACK); d.setAlpha(130); ad.getWindow().setBackgroundDrawable(d); ad.setCanceledOnTouchOutside(true); ad.getWindow().requestFeature(Window.FEATURE_NO_TITLE); ad.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); return ad;} I just call it in the mainActivity when user click back button: @Overridepublic void onBackPressed() { if (isUserConnected && !hasShared) { shareOnExitDialog = new ShareOnExitDialog(); shareOnExitDialog.setCancelable(true); shareOnExitDialog.show(getSupportFragmentManager(), "Exit"); } else { finish(); }} Any help would be appreciated ! Now provide the response and nothing else.
The issue is in default dialog theme. Based on this and this answers it's much easier to achieve your target. The Activity should be like the following: public class MyActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); } @Override public void onBackPressed() { MyDialogFragment.newInstance("title title").show(getSupportFragmentManager(), "dialog"); }} And fragment: public class MyDialogFragment extends android.support.v4.app.DialogFragment { /** * Create a new instance of MyDialogFragment, providing "title" * as an argument. */ static MyDialogFragment newInstance(String title) { MyDialogFragment frag = new MyDialogFragment(); Bundle args = new Bundle(); args.putString("title", title); frag.setArguments(args); return frag; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Dialog dialog = new Dialog(getActivity(),android.R.style.Theme_Translucent_NoTitleBar); final View view = getActivity().getLayoutInflater().inflate(R.layout.share_or_die, null); final Drawable d = new ColorDrawable(Color.BLACK); d.setAlpha(130); dialog.getWindow().setBackgroundDrawable(d); dialog.getWindow().setContentView(view); final WindowManager.LayoutParams params = dialog.getWindow().getAttributes(); params.width = WindowManager.LayoutParams.WRAP_CONTENT; params.height = WindowManager.LayoutParams.WRAP_CONTENT; params.gravity = Gravity.CENTER; dialog.setCanceledOnTouchOutside(true); return dialog; }} Also, be sure to do the following: before setContentView() in the activity, getWindow().requestFeature(Window.FEATURE_NO_TITLE) should be added in order to use *NoTitleBar style. The result is (I've used LinearLayout with single TextView inside):
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20528552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1956558/']}
jdg_82821
stackexchange
llm_judgeable_groundtruth_similarity
2440752
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In irb, I do this class Text include FileUtilsend I get: NameError: uninitialized constant Test::FileUtils If I just do: include FileUtils (i.e. now class) everthing works. What gives? Now provide the response and nothing else.
You need to make sure Ruby knows about the FileUtils module. That module isn't loaded by default: >> FileUtilsNameError: uninitialized constant FileUtils from (irb):1>> require 'fileutils'=> true>> FileUtils=> FileUtils Don't worry too much about the error NameError: uninitialized constant Text::FileUtils - when you try to include a constant that Ruby doesn't know about, it looks in a few places. In your case, first it will look for Text::FileUtils and then it will look for ::FileUtils in the root namespace. If it can't find it anywhere (which in your case it couldn't) then the error message will tell you the first place it looked.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2440752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/253511/']}
jdg_82822
stackexchange
llm_judgeable_groundtruth_similarity
5385326
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 view in SQL server, something like this: select 6.71/3.41 as NewNumber The result is 1.967741 (note 6 decimal points) -> decimal (38,6) I try the same thing in a calculator but the result is 1.967741935483871xxxx I want to force SQL Server to return more accurate result something like decimal(38,16) I have tried the obvious things like casting, but SQL Server doesn't improve the output I just get some trailing zeros at the end like 1.9677410000 Is there a way to force SQL Server to not truncate the result or give more accurate one? Now provide the response and nothing else.
If you want something like decimal(38,16) then you need to cast the inputs not the output after truncation has already occurred! SELECT CAST(6.71 AS DECIMAL(38,18))/3.41 AS NewNumber Returns 1.9677419354838709 Check the datatype SELECT SQL_VARIANT_PROPERTY(CAST(6.71 AS DECIMAL(38,18))/3.41, 'BaseType'),SQL_VARIANT_PROPERTY(CAST(6.71 AS DECIMAL(38,18))/3.41, 'Precision'),SQL_VARIANT_PROPERTY(CAST(6.71 AS DECIMAL(38,18))/3.41, 'Scale') Returns numeric 38 16 Edit This is just to add an additional link as follow up to the comments. The rules for decimal to decimal conversion are described in BOL . That link includes the following phrase *The result precision and scale have an absolute maximum of 38. When a result precision is greater than 38, the corresponding scale is reduced to prevent the integral part of a result from being truncated. but leaves it unspecified exactly how such truncation is performed. This is documented here .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5385326', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/670368/']}
jdg_82823
stackexchange
llm_judgeable_groundtruth_similarity
11566182
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 a bit lost getting started with a simple WCF service. I have two methods and I want to expose one to the world and the second one I want to limit to certain users. Eventually I want to be able to use a client application to use the restricted method. So far I can access both methods anonymously: C# Code namespace serviceSpace{ [ServiceContract] interface ILocationService { [OperationContract] string GetLocation(string id); [OperationContract] string GetHiddenLocation(string id); } [AspNetCompatibilityRequirements( RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class LocationService : ILocationService { [WebGet(UriTemplate = "Location/{id}")] public string GetLocation(string id) { return "O hai, I'm available to everyone."; } // only use this if authorized somehow [WebGet(UriTemplate = "Location/hush/{id}")] public string GetHiddenLocation(string id) { return "O hai, I can only be seen by certain users."; } }} Configuration <?xml version="1.0"?><configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> <standardEndpoints> <webHttpEndpoint> <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/> </webHttpEndpoint> </standardEndpoints> </system.serviceModel></configuration> How do I get started? Now provide the response and nothing else.
A lot of the answers I found were almost what I needed but not quite right. I wound up setting up ASP.net membership and implementing a custom attribute to pull an authorization header and process login as the request came in. All of the magic happens in BeforeCall and ParseAuthorizationHeader below: public class UsernamePasswordAuthentication : Attribute, IOperationBehavior, IParameterInspector{ public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation) { dispatchOperation.ParameterInspectors.Add(this); } public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState) { } public object BeforeCall(string operationName, object[] inputs) { var usernamePasswordString = parseAuthorizationHeader(WebOperationContext.Current.IncomingRequest); if (usernamePasswordString != null) { string[] usernamePasswordArray = usernamePasswordString.Split(new char[] { ':' }); string username = usernamePasswordArray[0]; string password = usernamePasswordArray[1]; if ((username != null) && (password != null) && (Membership.ValidateUser(username, password))) { Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(username), new string[0]); return null; } } // if we made it here the user is not authorized WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized; throw new WebFaultException<string>("Unauthorized", HttpStatusCode.Unauthorized); } private string parseAuthorizationHeader(IncomingWebRequestContext request) { string rtnString = null; string authHeader = request.Headers["Authorization"]; if (authHeader != null) { var authStr = authHeader.Trim(); if (authStr.IndexOf("Basic", 0) == 0) { string encodedCredentials = authStr.Substring(6); byte[] decodedBytes = Convert.FromBase64String(encodedCredentials); rtnString = new ASCIIEncoding().GetString(decodedBytes); } } return rtnString; } public void AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) { } public void Validate(OperationDescription operationDescription) { }} From there I just need to add my new attribute to the service contract entries. Any request to that method will require a valid authorization header or a Not Authorized response will be sent back with doing any further processing. [ServiceContract]interface ILocationService{ [OperationContract] string GetLocation(string id); [OperationContract] [UsernamePasswordAuthentication] // this attribute will force authentication string GetHiddenLocation(string id);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11566182', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/119507/']}
jdg_82824
stackexchange
llm_judgeable_groundtruth_similarity
15328416
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 tell the code to position by the center point of an element, rather than by the top-left point?If my parent element has width: 500px; and my child element has /*some width, for this example let's say it's 200px*/position: absolute;left: 50%; one would assume that based on the 50% positioning, the child element will be in the middle of the parent, leaving 150px of free space on each side. However, it is not, since it is the top-left point of the child that goes to 50% of the parent's width, therefore the whole child's width of 200px goes to the right from there, leaving 250px of free space on the left and only 50px on the right. So, my question is, how to achieve center positioning ? I found this solution: position: absolute;width: 200px;left: 50%;margin-left: -100px; but I don't like it because you need to edit it manually for each element's width - I would like something that works globally. (For example, when I work in Adobe After Effects, I can set a position for an object and then set specific anchor point of that object that will be put to that position. If the canvas is 1280px wide, you position an object to 640px and you choose the center of the object to be your anchor point, then the whole object will be centered within the 1280px wide canvas.) I would imagine something like this in CSS: position: absolute;left: 50%;horizontal-anchor: center; Similarly, horizontal-anchor: right would position the element by its right side, so the whole content would be to the left from the point of its parent's 50% width. And, the same would apply for vertical-anchor , you get it. So, is something like this possible using only CSS (no scripting)? Thanks! Now provide the response and nothing else.
If the element must be absolutely positioned (so, margin: 0 auto; is of no use for centering), and scripting is out of the question, you could achieve this with CSS3 transforms. .centered-block { width: 100px; left: 50%; transform: translate(-50%, 0); position: absolute;} See this fiddle for some examples. The important parts: left: 50%; pushes block halfway across its parent (so its left side is on the 50% mark, as you mentioned). transform: translate(-50%, 0); pulls the block half it's own width back along the x-axis (ie. to the left), which will place it right in the center of the parent.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15328416', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2127783/']}
jdg_82825
stackexchange
llm_judgeable_groundtruth_similarity
26315734
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can someone please help me understand the difference between the below two pieces of code . Why are the results different for both . I each case i am selecting the same property (name) : Code 1 : $obj = Get-Service | Where-Object {$_.Status -eq "Running"} | foreach-object {$_.Name} | select -first 3foreach ( $item in $obj ) { write-output "Name is : $item" }Output :Name is : AeLookupSvcName is : AppinfoName is : AudioEndpointBuilder Code 2 : $obj = Get-Service | Where-Object {$_.Status -eq "Running"} | select -first 3 nameforeach ( $item in $obj ) { write-output "Name is : $item" }Output :Name is : @{Name=AeLookupSvc}Name is : @{Name=Appinfo}Name is : @{Name=AudioEndpointBuilder} Now provide the response and nothing else.
Select-Object returns an array of custom objects to the pipeline; in this case having only one property which happens to be a string. As @walidtourni mentions, using expand works around this issue. This is because expand causes the output to be the property's value, instead of a custom object with a property with that value. The reason this is possible is expand only takes one argument; i.e. there's no possibility of you attempting to return multiple values for the same "row". The foreach-object on the other hand is simply spitting stuff out to the pipeline. If you tried to include a second property without manually wrapping both into a custom object, the output would create another row rather than two properties on the same row. To demonstrate, run the following: Clear$x = Get-Service | Where-Object {$_.Status -eq "Running"} | select -first 3 $x | foreach-object {$_.Name} #returns 3 rows, single column; string$x | foreach-object {$_.Name;$_.CanPauseAndContinue;} #returns 6 rows, single column; alternate string & boolean$x | select Name #returns 3 rows, single column (string); custom object$x | select Name, CanPauseAndContinue #returns 3 rows, two columns (string & boolean); custom property$x | select -expand Name #returns 3 rows, single column; string; notice the lack of column header showing this is a string, not a string property of a custom object$x | select -expand Name,CanPauseAndContinue #error; -expand can only take single valued arguments$x | select -expand Name -expand CanPauseAndContinue #error; you can't try to define the same paramenter twice
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26315734', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1867151/']}
jdg_82826
stackexchange
llm_judgeable_groundtruth_similarity
49322511
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 use a codegen tool for Go to automatically generate some code based on the contents of other go files. The codegen tool will get standard arguments which can be deduced from the name of the file its generating and the name of the file that it's parsing. If I were doing it all manually, it would look like: foo-tool -name FooInterface -file foo/api.gofoo-tool -name BarInterface -file foo/api.gofoo-tool -name BingInterface -file foo/bing.gofoo-tool -name BazInterface -file foo/baz.go But I don't want to do it manually, I want to use Make! So I tried to accomplish the same thing with a Makefile and a pattern rule. foo_FooInterface.go : foo/api.go foo_BarInterface.go : foo/api.gofoo_BingInterface.go : foo/bing.gofoo_BazInterface.go : foo/baz.gofoo_%.go : %.go $(eval foo_name=$(subst mock_,,$(subst .go,,$(@F)))) build-foo -name $(foo_name) -file $< In my mind, the first 3 rules would set up the dependency graph, and the pattern rule would tell Make what to do with the dependencies. But when I try running make foo_BarInterface.go , I get make: Nothing to be done for foo_BarInterface.go . I understand why this happens, because Make is expecting to match foo_FooInterface.go with FooInterface.go, but I don't want to restructure my project's files like that. Is this possible, or do I need to do something like: foo_FooInterface.go : foo/api.go build-foo -name FooInterface -file foo/api.gofoo_BarInterface.go : foo/api.go build-foo -name BarInterface -file foo/api.gofoo_BingInterface.go : foo/bing.go build-foo -name BingInterface -file foo/bing.gofoo_BazInterface.go : foo/baz.go build-foo -name BingInterface -file foo/baz.go Which I really don't want to do, because new Interface s will be added as the codebase grows, and I don't want to require people to type all of that every time. Edit: I wouldn't mind specifying the rule manually every time, but I need a rule that collects all the generated files together, and I don't want to specify every foo_*.go in that one. Is there a way to say "This rule depends on all rules (not files) matching a pattern?" I was able to do foo_files := $(shell grep 'foo_\w\+.go' Makefile | cut -d : -f1) But this seems bad to me. Now provide the response and nothing else.
ThreadPoolExecutor.submit returns a future object that represents the result of the computation, once it's available. In order to not ignore the exceptions raised by the job, you need to actually access this result. First, you can change run_job to return the created futures: def run_jobs(): fut1 = EXECUTOR.submit(some_long_task1) fut2 = EXECUTOR.submit(some_long_task2, 'hello', 123) return fut1, fut2 Then, have the top-level code wait for the futures to complete, and access their results: import concurrent.futuresif __name__ == '__main__': futures = run_jobs() concurrent.futures.wait(futures) for fut in futures: print(fut.result()) Calling result() on a future whose execution raised an exception will propagate the exception to the caller. In this case the ZeroDivisionError will get raised at top-level.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49322511', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3204951/']}
jdg_82827
stackexchange
llm_judgeable_groundtruth_similarity
13333571
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 found a problem with jQuery UI Datepicker on my site. When I click on the input, it does show a datepicker properly. Nevertheless, when I don't select any date and I just click outside the element, it doesn't hide the datepicker as I'd expect. When I press the Esc, it disappears, when I select a day it disappears but when I click outside it stays there. Is there anyone who is able to find the problem? Link: http://pec.solarismedia.net/index.html#content Now provide the response and nothing else.
Your datepickers have the class hasDatepicker , so try this: $(".hasDatepicker").blur(function(e) { $(this).datepicker("hide"); }); I'm 99% positive that will work! And FYI, if you want it to be dynamic (apply to inputs created after), you can use .on $(".hasDatepicker").on("blur", function(e) { $(this).datepicker("hide"); }); UPDATE (PS, to use the following completely remove the above from your code) To answer your comment, the following may not be the best solution, but through trial and error (on your site, using console) it works! And it's relatively short compared to alternate ways I thought of. $(document).click(function(e) { var ele = $(e.toElement); if (!ele.hasClass("hasDatepicker") && !ele.hasClass("ui-datepicker") && !ele.hasClass("ui-icon") && !$(ele).parent().parents(".ui-datepicker").length) $(".hasDatepicker").datepicker("hide"); }); As One Line $(document).click(function(e) { var ele = $(e.toElement); if (!ele.hasClass("hasDatepicker") && !ele.hasClass("ui-datepicker") && !ele.hasClass("ui-icon") && !$(ele).parent().parents(".ui-datepicker").length) $(".hasDatepicker").datepicker("hide"); }); the problem i encountered was being able to tell when the span icon was clicked, it wasnt really wanting to cooperate, thus the extra has class checks
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13333571', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1816379/']}
jdg_82828
stackexchange
llm_judgeable_groundtruth_similarity
19691082
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm writing a shell script to streamline my development workflow. It takes an argument as to which theme folder I'm going to be working in and starts grunt watch on that directory. If I call the script without the necessary argument I'm currently printing a warning that a theme needs to be specified as a command line argument. I'd like to print a list of the available options, e.g. theme directories This is what I have so far... THEME=$1if [ $THEME == '' ]then echo 'Need to specify theme'else cd 'workspace/aws/ghost/'$THEME'/' grunt watchfi Ideally I'd replace the output of the echo line with an ls of the themes parent directory like so THEME=$1if [ $THEME == '' ]then echo 'Need to specify theme from the following' ls workspace/aws/ghostelse cd 'workspace/aws/ghost/'$THEME'/' grunt watchfi However this gives me the following error ./ghost_dev.sh: line 3: [: ==: unary operator expected Now provide the response and nothing else.
You need quotes around $THEME here: if [ $THEME == '' ] Otherwise, when you don't specify a theme, $THEME expands to nothing, and the shell sees this syntax error: if [ == '' ] With quotes added, like so: if [ "$THEME" == '' ] the expansion of an empty $THEME yields this valid comparison instead: if [ "" == '' ] This capacity for runtime syntax errors can be surprising to those whose background is in more traditional programming languages, but command shells (at least those in the Bourne tradition) parse code somewhat differently. In many contexts, shell parameters behave more like macros than variables; this behavior provides flexibility, but also creates traps for the unwary. Since you tagged this question bash , it's worth noting that there is no word-splitting performed on the result of parameter expansion inside the "new" test syntax available in bash (and ksh/zsh), namely [[ ... ]] . So you can also do this: if [[ $THEME == '' ]] The places you can get away without quotes are listed here . But it's a fine habit to always quote parameter expansions anyway except when you explicitly want word-splitting (and even then, look to see if arrays will solve your problem instead). It would be more idiomatic to use the -z test operator instead of equality with the empty string: if [ -z "$THEME" ] You technically don't need the quotation marks in this simple case; [ -z ] evaluates to true. But if you have a more complicated expression, the parser will get confused, so it's better to just always use the quotes. Of course, [[ ... ]] doesn't require any here, either: if [[ -z $THEME ]] But [[ ... ]] is not part of the POSIX standard; for that matter, neither is == . So if you care about strict compatibility with other POSIX shells, stick to the quoting solution and use either -z or a single = .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19691082', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/814038/']}
jdg_82829
stackexchange
llm_judgeable_groundtruth_similarity
39119
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: There are several volcanoes on Mars, including Olympus Mons, the largest volcano in the solar system, the volcanoes on the Tharsis bulge,... But they are all thought to be inactive now. When did the last volcano erupt on Mars? Now provide the response and nothing else.
Berman and Hartman (2002) dated some lava flows of the Athabasca–Marte Valles system at < 20 Ma (mega-annum). Later, Vaucher et al. (2009) dated lava flows of the same region, finding ages even younger in some cases (around 2.5 Ma). In both studies the age estimates are derived from surface morphology (i.e., crater counts). In Volcanoes: Global Perspectives , Lockwood & Hazlett go even further (emphasis mine): Unlike Earth’s Moon, volcanic activity may be far from over on Mars. Detailed photographic studies by NASA’s Global Surveyor starting in 1997, and the Mars Express High Resolution Stereo Camera, which began orbiting Mars in December of 2003, provide evidence of effusive volcanism perhaps as young as 2–2.5 million years, with flows mantling the flanks of Olympus Mons erupted mostly within the past 200 million years. It cannot be assumed that Mars is now internally cold and volcanically dead, and in fact, volatile efflux may still be in progress .
{}
{'log_upvote_score': 5, 'links': ['https://astronomy.stackexchange.com/questions/39119', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/9527/']}
jdg_82830
stackexchange
llm_judgeable_groundtruth_similarity
114525
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: JavaScript: var functionName = function() {} vs function functionName() {} What's the difference between: function sum(x, y) { return x+y;}// and var sum = function (x, y) { return x+y;} Why is one used over the other? Now provide the response and nothing else.
The first is known as a named function where the second is known as an anonymous function. The key practical difference is in when you can use the sum function. For example:- var z = sum(2, 3);function sum(x, y) { return x+y;} z is assigned 5 whereas this:- var z = sum(2, 3);var sum = function(x, y) { return x+y;} Will fail since at the time the first line has executed the variable sum has not yet been assigned the function. Named functions are parsed and assigned to their names before execution begins which is why a named function can be utilized in code that precedes its definition. Variables assigned a function by code can clearly only be used as function once execution has proceeded past the assignment.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/114525', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3983/']}
jdg_82831
stackexchange
llm_judgeable_groundtruth_similarity
9805
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: Why don't spinning tops fall over? (The young scientist version) My nine year old son asked me this very question when playing with his "Battle Strikers" set. Having studied Physics myself, I am very keen to encourage him to take an interest in Science and I am delighted when he asks me such questions. In this case, however, I'm stumped. How do I explain why a spinning top doesn't fall down without going into the mathematics of angular momentum? I thought the following post would help, but the answers would just bamboozle him I'm afraid. Why don't spinning tops fall over? So, how do you explain spinning tops to a nine year old? Now provide the response and nothing else.
Well, the angular momentum conservation is still the essence although it may be formulated in a different language. The top is spinning around a vertical axis and the spinning around this axis can't disappear. if the top decided to fall, the spinning would either disappear or would be replaced by a totally different spinning around a horizontal axis, and Nature doesn't allow such a change of the amount of spinning to occur quickly. One has to have a torque to change the amount of spinning, some force attempting to change the rotation, but the torque acting on the bottom tip of the top is so small that with a fast enough initial spinning, it takes a lot of time to change the spin substantially. Moreover, energy conservation guarantees that if there's no friction, the top can't ever fall. More practically, I would probably take a wheel from a bicycle, made the kid hold it, rotate it quickly, and then make him or her feel the forces when he tries to change the direction of the wheel. This is a pretty nice yet simple toy in various science museums, including "Techmania" we have here in Pilsen. See also this page which contains the picture above as well as some other insightful games and experiments relevant for the angular momentum.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/9805', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/3525/']}
jdg_82832
stackexchange
llm_judgeable_groundtruth_similarity
237268
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 please answer how dark matter theory resolves/eliminates these two possible problems Dark matter, per my understanding, due to gravity, keeps moving, and due to its non-interactive nature, does not stick to itself or normal matter. Therefore, it is in continuous (and may be somewhat random) movement. Wouldn't this make the speed curve of spiral galaxies pretty unstable, or unpredictable? Dark matter, due to gravity, keeps moving, (usually most dense at the center of the galaxy). Whenever some of it enters the event horizon of the central black hole, it should not be able to come out ever again. Over million/billions of years, all of it, little by little, should eventually end up inside the central black hole, making it impossible to maintain the uniform speed curve. Even though it is non-interactive, is it correct that it still could not escape the event horizon? If so, how it is still possible to maintain the uniform speed curve of galaxies for billions of years? I am thinking due to non-interactive, non-sticking nature, movement/rotation of dark matter should not be uniform, and it should be crossing in and out passing the central black hole, thereby some of it being consumed for ever. Once this process starts, the central black hole would begin to become heavier making the process even faster. Also, I am thinking that to cause uniform speed curve, dark matter has to be distributed over the galaxy in certain way. All or most of it in the central black hole would not support the uniform speed curve. Do the dark matter simulations take these two problems into account? How they are resolved/avoided? Now provide the response and nothing else.
The properties you attribute to dark matter (non-interacting, affected only by gravity) are alo properties of a large fraction of the visible matter in our Galaxy. i.e. Stars orbit in the Galactic potential without directly interacting with other stars and their trajectories are only influenced by gravitational forces. Far from being "random", dark matter is expected to orbit the Galaxy in a similar way to stars. The main difference being that most of the dark matter is on much larger orbits and the orbital axes are distributed more uniformly in space. In the same way that stars on circular or even quite elliptical orbits never come anywhere near the BH at the centre of the galaxy, nor does most dark matter. Some dark matter will have been captured in the past, but only that which had almost perfectly radial orbits. The rest continues to orbit in the same way that the Earth continues to orbit the Sun, with nothing to dissipate its orbital kinetic energy. To extend the analogy between non-interacting stars and dark matter - there is a class of stars formed very early on in the Milky Way's history called population II or halo stars . These have been orbiting the Milky Way in pseudo-spherical orbits since they first formed more than 10 billion years ago - like dark matter. Yes, the dark matter density is higher near the centre of the galaxy but the mass of dark matter is dominated by that which occupies the enormous volume at large distances from the centre. To summarise, neither of the problems you have invented are problems.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/237268', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/106205/']}
jdg_82833
stackexchange
llm_judgeable_groundtruth_similarity
62162006
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 one parent and one child component. If the child component updates its value internally I am unable to update value back from Parent. See the example in this Stackblitz: https://stackblitz.com/edit/angular-ivy-tynepp . When the child component loses focus I fire an event and the parent resets value of the child component. But I think that because the parent's "this.value" didn't change that the update doesn't trigger detection changes in the child. How can I solve this dilemma? Now provide the response and nothing else.
As you said, change detection is not triggered because the bound value has not changed. You can force an update of the data binding with the following steps: Set a temporary value Call ChangeDetectorRef.detectChanges() Reset the value constructor(private changeDetectorRef: ChangeDetectorRef) {}resetValue() { this.value = "____TempValue____"; this.changeDetectorRef.detectChanges(); this.value = "";} See this stackblitz for a demo.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/62162006', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/967588/']}
jdg_82834
stackexchange
llm_judgeable_groundtruth_similarity
46298605
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 developing one application using asp dot net core 2 using MySql database .Please help me How can i use Asp Net Identity in MySqlDatabase . Now provide the response and nothing else.
I had to do this for a client. And I did in an application with ASP.NET Core 1.0, but for curiosity I also tried for an application in .NET Core 2.0. What I did was first install the Entity Framework MySQL package from https://www.nuget.org/packages/Pomelo.EntityFrameworkCore.MySql/ using package manager console. After that I changed in the startup.cs , in the method ConfigureServices , the option UseSqlServer to UseMySql , like the image below. In my appsettings.json I have the MySQL connection named IdentityConnection like this: { "ConnectionStrings": { "IdentityConnection": "Server=127.0.0.1;Database=identitycoredb;Uid=root;Pwd=1234;" }, To create the identity tables I executed the migration command in package manager console: EntityFrameworkCore\Update-Database -Verbose
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46298605', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8562114/']}
jdg_82835
stackexchange
llm_judgeable_groundtruth_similarity
5155
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If a reaction requires a "strong" acid - what does this mean? Does it mean any acid of a specific concentration or pH? Are only certain acids classed as "strong"? I have read on Wikipedia that it needs to ionise completely in an aqueous solution - in this case, is a strong acid (for example, HCl) still classed as a strong acid if it is in a 0.00001M solution? Now provide the response and nothing else.
The strength or weakness of an acid is independent of its concentration. A strong acid dissociates completely in solution, so $\ce{HCl}$ at any molarity would be considered strong, and $\ce{HCOOH}$ (for example) at any molarity would be weak. It is more enlightening to consider $K_a$ values, which are essentially the equilibrium constants for the ionization of an acid $\ce{HA}$.$$K_a=\frac{[\ce{H}^+][\ce{A}^-]}{[\ce{HA}]}$$This value will either be very small (<<1) or very large (>>1000). Acids with very small $K_a$ are considered weak, and acids with very large $K_a$ are considered strong (the $K_a$ of strong acids is usually not stated and assumed to be infinite). Addendum: The $K_a$ value is concentration-independent because you are only interested in how well the acid dissociates from its molecular form. If you had $0.0000001\ \text{mol}\cdot\text{dm}^{-3}\ \ce{HCl}$, practically every molecule of $\ce{H-Cl}$ would dissociate into $\ce{H^+}$ and $\ce{Cl^-}$ no matter how many there are. But if you had $12 \ \text{mol}\cdot\text{dm}^{-3}\ \ce{HCOOH}$ (methanoic acid), only a small proportion of the $\ce{HCOOH}$ would dissociate into $\ce{H^+}$ and $\ce{HCOO}^-$, irrespective of how many you had to start.
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/5155', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/842/']}
jdg_82836
stackexchange
llm_judgeable_groundtruth_similarity
10176312
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 a newbie with the Storyboard and so I have some difficulties... I have created a TableViewController and I would like to customize the Cell Prototype. In the Cell Prototype I have added several Labels I would like to customize with my own class which inherits from UITableViewCell (AreaListCell). In the Storyboard, for the Cell Prototype I have configured the Custom Class with "AreaListCell" and its style is "Custom". In the storyboard, when I select the Cell Prototype and then the assistant, the assistant display my class that implements the UITableViewController (AreasTableViewController) and not my "AreaListCell" class. The consequence is I can create outlet (using Ctrl + Drag from the label of the Cell Prototype) to the AreasTableViewController class but not to the AreaListCell class !Any idea how to connect the Cell Prototype with my AreaListCell class? Thanks for your help! Now provide the response and nothing else.
UPDATE: As of Xcode 4.6 (possibly earlier) you can now create outlets by control-dragging! - This has to be done into an interface section or class extension (the class extension doesn't exist by default for new cell subclasses. Thanks to Steve Haley for pointing this out. You can't get the outlet automatically connected and created by dragging into the code block in the assistant editor, which is poor, but you can create the outlets manually and connect them then. In your cell subclass interface: @interface CustomCell : UITableViewCell@property (nonatomic) IBOutlet UILabel* customLabel;@end Synthesize as normal in the implementation. In the storyboard, select the cell and go to the connections inspector, you will see the new outlet. Drag from there to the relevant element in your prototype: This can now be accessed as cell.customLabel in your cellForRowAtIndexPath: method.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/10176312', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/951368/']}
jdg_82837
stackexchange
llm_judgeable_groundtruth_similarity
228822
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 would like to create a table like the one shown below in mathematica: Here is the code i wrote: I was wondering if there is more efficient way to writing the code where i don't have to type out individual sin(xt) for each value of x and t. This is a modified version of the question that is in the book "Hands-on Start to Wolfram Mathematica and Programming with the Wolfram Language, Second Edition". If anyone has the pdf solutions to the all exercises in the book, would you be able to send it to me? Thanking you in advance Now provide the response and nothing else.
(* create your values *)rows = Range[10];cols = Range[6];vals = Outer[Sin@*Times, rows, cols];(* make a table *)tf = TableForm[N@vals, TableHeadings -> {rows, cols}];(* label it *)Labeled[tf, {"x-vals", "t-vals"}, {Left, Top}, RotateLabel -> True] You may want to use NumberForm for a nicer display of the values. E.g., vals = Map[NumberForm[#, {4, 3}] &, vals, {2}]tf = TableForm[N@vals, TableHeadings -> {rows, cols}, TableAlignments -> Right];
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/228822', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/74316/']}
jdg_82838
stackexchange
llm_judgeable_groundtruth_similarity
19098295
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 writing an application which connects to a database. I want to create that db connection once, and then reuse that connection throughout the life of the application. I also want to authenticate users. A user's auth will live for only the life of a request. How can I differentiate between objects stored for the life of a flask app, versus specific to the request? Where would I store them so that all modules (and subsequent blueprints) have access to them? Here is my sample app: from flask import Flask, gapp = Flask(__name__)@app.before_first_requestdef setup_database(*args, **kwargs): print 'before first request', g.__dict__ g.database = 'DATABASE' print 'after first request', [email protected]('/')def index(): print 'request start', g.__dict__ g.current_user = 'USER' print 'request end', g.__dict__ return 'hello'if __name__ == '__main__': app.run(debug=True, port=6001) When I run this (Flask 0.10.1) and navigate to http://localhost:6001/ , here is what shows up in the console: $ python app.py * Running on http://127.0.0.1:6001/ * Restarting with reloaderbefore first request {}after first request {'database': 'DATABASE'}request start {'database': 'DATABASE'}request end {'current_user': 'USER', 'database': 'DATABASE'}127.0.0.1 - - [30/Sep/2013 11:36:40] "GET / HTTP/1.1" 200 -request start {}request end {'current_user': 'USER'}127.0.0.1 - - [30/Sep/2013 11:36:41] "GET / HTTP/1.1" 200 - That is, the first request is working as expected: flask.g is holding my database, and when the request starts, it also has my user's information. However, upon my second request, flask.g is wiped clean! My database is nowhere to be found. Now, I know that flask.g used to apply to the request only. But now that it is bound to the application (as of 0.10), I want to know how to bind variables to the entire application, rather than just a single request. What am I missing? edit: I'm specifically interested in MongoDB - and in my case, maintaining connections to multiple Mongo databases. Is my best bet to just create those connections in __init__.py and reuse those objects? Now provide the response and nothing else.
flask.g will only store things for the duration of a request. The documentation mentioned that the values are stored on the application context rather than the request, but that is more of an implementation issue: it doesn't change the fact that objects in flask.g are only available in the same thread, and during the lifetime of a single request. For example, in the official tutorial section on database connections , the connection is made once at the beginning of the request, then terminated at the end of the request. Of course, if you really wanted to, you could create the database connection once, store it in __init__.py , and reference it (as a global variable) as needed. However, you shouldn't do this: the connection could close or timeout, and you could not use the connection in multiple threads. Since you didn't specify HOW you will be using Mongo in Python, I assume you will be using PyMongo , since that handles all of the connection pooling for you. In this case, you would do something like this... from flask import Flaskfrom pymongo import MongoClient# This line of code does NOT create a connectionclient = MongoClient()app = Flask()# This can be in __init__.py, or some other file that has imported the "client" [email protected]('/'):def index(): posts = client.database.posts.find() You could, if you wish, do something like this... from flask import Flask, gfrom pymongo import MongoClient# This line of code does NOT create a connectionclient = MongoClient()app = Flask()@app.before_requestdef before_request(): g.db = [email protected]('/'):def index(): posts = g.db.posts.find() This really isn't all that different, however it can be helpful for logic that you want to perform on every request (such as setting g.db to a specific database depending on the user that is logged in). Finally, you can realize that most of the work of setting up PyMongo with Flask is probably done for you in Flask-PyMongo . Your other question deals with how you keep track of stuff specific to the user that is logged in. Well, in this case, you DO need to store some data that sticks around with the connection. flask.g is cleared at the end of the reuquest, so that's no good. What you want to use is sessions . This is a place where you can store values that is (with the default implementation) stored in a cookie on the user's browser. Since the cookie will be passed along with every request the user's browser makes to your web site, you will have available the data you put in the session. Keep in mind, though, that the session is NOT stored on the server. It is turned into a string that is passed back and forth to the user. Therefore, you can't store things like DB connections onto it. You would instead store identifiers (like user IDs). Making sure that user authentication works is VERY hard to get right. The security concerns that you need to make sure of are amazingly complex. I would strongly recommend using something like Flask-Login to handle this for you. You can still use the session for storing other items as needed, or you can let Flask-Login handle determining the user ID and store the values you need in the database and retrieving them from the database in every request. So, in summary, there are a few different ways to do what you want to do. Each have their usages. Globals are good for items that are thread-safe (such as the PyMongo's MongoClient). flask.g can be used for storing data in the lifetime of a request. With SQLAlchemy-based flask apps, a common thing to do is to ensure that all changes happen at once, at the end of a request using an after_request method. Using flask.g for something like this is very helpful. The Flask session can be used to store simple data (strings and numbers, not connection objects) that can be used on subsequent requests that come from the same user. This is entirely dependent on using cookies, so at any point the user could delete the cookie and everything in the "session" will be lost. Therefore, you probably want to store much of your data in databases, with the session used to identify the data that relates to the user in the session.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19098295', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3788/']}
jdg_82839
stackexchange
llm_judgeable_groundtruth_similarity
22150023
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 capture http status code 3XX/302 for a redirection url. But I cannot get it because it gives 200 status code. Here is the code: import requestsr = requests.get('http://goo.gl/NZek5')print r.status_code I suppose this should issue either 301 or 302 because it redirects to another page. I had tried few redirecting urls (for e.g. http://fb.com ) but again it is issuing the 200. What should be done to capture the redirection code properly? Now provide the response and nothing else.
requests handles redirects for you , see redirection and history . Set allow_redirects=False if you don't want requests to handle redirections, or you can inspect the redirection responses contained in the r.history list . Demo: >>> import requests>>> url = 'https://httpbin.org/redirect-to'>>> params = {"status_code": 301, "url": "https://stackoverflow.com/q/22150023"}>>> r = requests.get(url, params=params)>>> r.history[<Response [301]>, <Response [302]>]>>> r.history[0].status_code301>>> r.history[0].headers['Location']'https://stackoverflow.com/q/22150023'>>> r.url'https://stackoverflow.com/questions/22150023/http-redirection-code-3xx-in-python-requests'>>> r = requests.get(url, params=params, allow_redirects=False)>>> r.status_code301>>> r.url'https://httpbin.org/redirect-to?status_code=301&url=https%3A%2F%2Fstackoverflow.com%2Fq%2F22150023' So if allow_redirects is True , the redirects have been followed and the final response returned is the final page after following redirects. If allow_redirects is False , the first response is returned, even if it is a redirect.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/22150023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2789099/']}
jdg_82840