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
|
288992
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it safe to connect yourself to an electrical outlet? Either directly or indirectly. I would prefer to not connect myself directly to an electrical outlet, via (as I've heard) attaching a wrist strap to the middle screw of an outlet. Though I am wondering about connecting more indirectly. I am building a computer, that has a fully painted case. I have heard of a way to ground using the computer's power supply by: Plug in power supply to wall outlet, turn power supply OFF, partially unscrew one of the four power supply screws (that hold it onto the computer case), then attach the anti-static wrist strap to the threads of the unscrewed screw. Is that safe, in regards to indirectly connecting yourself to a wall outlet? I would prefer a standalone ESD setup, that doesn't involve a wall outlet, however I have not yet heard of any ways to do so. Thank you very much for helping with this.
Now provide the response and nothing else.
|
If your plug has a correctly wired earth pin, then you can use that to ground yourself. However before you do, it is worth noting that all reputable ESD wrist bands contain an embedded 1MOhm resistor. This is done primarily so that if you accidentally connect yourself to mains voltage (either through what you are handling, or through a wiring fault in the plug) the resistor limits the current that can pass through you, and so protects you from certain death. I would suggest buying an ESD wrist strap. If you make your own, be sure to include a 1M resistor. To be fair though even if you don't include the resistor, as long as you are absolutely sure you have connected yourself to the earth pin and nothing else, it will not do anything worse than touching the back panel on your PC (or the case of the PSU) because those are generally tied directly to earth on the outlet anyway. If touching your PC gives you an electric shock, consult an electrician. As an alternative to the earth pin on an electrical outlet, you can also use things like metal plumbing pipes as these are typically earth bonded to the electrical system earth in the house, or go down physically into the ground.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/288992', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/140413/']}
|
jdg_369441
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3775102
|
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 file in my ~/Sites directory that works fine when I browse to it through coderama.local/~coderama/index2.php Now I want to get tricky and move my index2.php file to somewhere else on my system, so I do this by creating a symbolic link. However, when I try to access coderama.local/~coderama/index2.php I now get the following error. Any ideas anyone? Thanks! Forbidden You don't have permission to access /~coderama/index2.php on this server.
Now provide the response and nothing else.
|
That's a configurable Apache option. It appears that by default on Macs (and probably most installations) Apache is configured to not follow symbolic links. I'm guessing (as others mention above) that it's for security purposes. But it can be really convenient at times to enable following of symbolic links, particularly during development of certain kinds of apps. What you need to do is 1) change the Apache configuration to allow the following of symbolic links, and then 2) restart Apache. The configuration step is performed as follows: a) cd /etc/apache2 (this is where Apache's configuration files are by default on a Mac) b) you'll see a couple of directories here. One is called users c) cd users d) ls should reveal a .conf file with your login name ( login .conf) I'm "marvo" so mine is named "marvo.conf" e) Edit this file (I use vi) -- but you have to do it using sudo: sudo vi marvo.conf f) You'll see something like <Directory "/Users/marvo/Sites/"> Options Indexes MultiViews AllowOverride None Order allow,deny Allow from all</Directory> g) Add the "FollowSymLinks" option so that the second line of that .conf file looks like: Options Indexes MultiViews FollowSymLinks (You can find other configuration options out there on the 'net. I found this page: http://httpd.apache.org/docs/2.0/mod/core.html#directory ) h) Save the file. Now you have to restart Apache so that it picks up the configuration change. Googling around a bit, I found that this is most easily done from the command line with the following command: sudo /usr/sbin/apachectl restart (Found that at http://mcapewell.wordpress.com/2006/09/22/restart-apache-in-mac-os-x/ ) Now that symbolic link should work just fine on your Sites pages.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3775102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/427499/']}
|
jdg_369442
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1060746
|
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 I prove $$1+2^n+3^n+4^n$$ is divisible by $10$ if $$n\neq 0,4,8,12,16.....$$
Now provide the response and nothing else.
|
We consider it $(\mathrm{mod}\;2)$ and $(\mathrm{mod}\;5)$ separately. Clearly $1$ and $3^n$ are odd, while $2^n$ and $4^n$ are even, so their sum is even. Now by Fermat's Little Theorem, when $a$ is not divisible by $5$, $a^5 \equiv a \mod 5$, so $a^4 \equiv 1 \mod 5$. Thus we only need to check $n=1$, $2$, and $3$. (note that $1$, $2$, $3$, and $4$ are not divisible by $5$. If $n=1$, we get $1+2+3+4=10$, which is divisible by $5$If $n=2$, we get $1+4+9+16=30$, which is divisible by $5$. If $n=3$, we get $1+8+27+64=100$, which is divisible by $5$. Thus we have proved it $(\mathrm{mod}\;5)$ and we are done.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1060746', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/187799/']}
|
jdg_369443
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16458340
|
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 these two lists: la = [1, 2, 3]lb = [4, 5, 6] I can iterate over them as follows: for i in range(min(len(la), len(lb))): print la[i], lb[i] Or more pythonically for a, b in zip(la, lb): print a, b What if I have two dictionaries? da = {'a': 1, 'b': 2, 'c': 3}db = {'a': 4, 'b': 5, 'c': 6} Again, I can iterate manually: for key in set(da.keys()) & set(db.keys()): print key, da[key], db[key] Is there some builtin method that allows me to iterate as follows? for key, value_a, value_b in common_entries(da, db): print key, value_a, value_b
Now provide the response and nothing else.
|
There is no built-in function or method that can do this. However, you could easily define your own. def common_entries(*dcts): if not dcts: return for i in set(dcts[0]).intersection(*dcts[1:]): yield (i,) + tuple(d[i] for d in dcts) This builds on the "manual method" you provide, but, like zip , can be used for any number of dictionaries. >>> da = {'a': 1, 'b': 2, 'c': 3}>>> db = {'a': 4, 'b': 5, 'c': 6}>>> list(common_entries(da, db))[('c', 3, 6), ('b', 2, 5), ('a', 1, 4)] When only one dictionary is provided as an argument, it essentially returns dct.items() . >>> list(common_entries(da))[('c', 3), ('b', 2), ('a', 1)] With no dictionaries, it returns an empty generator (just like zip() ) >>> list(common_entries())[]
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16458340', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/102441/']}
|
jdg_369444
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17764619
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
suppose I have a dataframe with index as monthy timestep, I know I can use dataframe.groupby(lambda x:x.year) to group monthly data into yearly and apply other operations. Is there some way I could quick group them, let's say by decade? thanks for any hints.
Now provide the response and nothing else.
|
To get the decade, you can integer-divide the year by 10 and then multiply by 10. For example, if you're starting from >>> dates = pd.date_range('1/1/2001', periods=500, freq="M")>>> df = pd.DataFrame({"A": 5*np.arange(len(dates))+2}, index=dates)>>> df.head() A2001-01-31 22001-02-28 72001-03-31 122001-04-30 172001-05-31 22 You can group by year, as usual (here we have a DatetimeIndex so it's really easy): >>> df.groupby(df.index.year).sum().head() A2001 3542002 10742003 17942004 25142005 3234 or you could do the (x//10)*10 trick: >>> df.groupby((df.index.year//10)*10).sum() A2000 291062010 1007402020 1727402030 2447402040 77424 If you don't have something on which you can use .year , you could still do lambda x: (x.year//10)*10) .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17764619', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/758677/']}
|
jdg_369445
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2494823
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Given a dictionary of <string, Drink> , how would you bind the dictionary.Values to a WPF ListBox, so that the items use the .Name property? struct Drink{ public string Name { get; private set; } public int Popularity { get; private set; } public Drink ( string name, int popularity ) : this ( ) { this.Name = name; this.Popularity = popularity; }}
Now provide the response and nothing else.
|
Setting the ItemsSource on an items control creates a binding to the enumerator for the source object. The enumerator of a Dictionary<T1, T2> is of type IEnumerable<KeyValuePair<T1, T2>> . So in your item template, you can bind to the Key and Value properties, and use the path syntax to get specific properties of the key and value. Here's an example. First the code that creates and populates the dictionary and adds it to the resource dictionary (there are lots of different ways you can expose the dictionary to data binding; this one's simple): namespace WpfApplication17{ /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { Dictionary<string, Drink> d = new Dictionary<string, Drink>(); d.Add("A", new Drink("Nehi", 0)); d.Add("B", new Drink("Moxie", 1)); d.Add("C", new Drink("Vernor's", 2)); d.Add("D", new Drink("Canfield's", 3)); Resources["Drinks"] = d; InitializeComponent(); } public class Drink { public Drink(string name, int popularity) { Name = name; Popularity = popularity; } public string Name { get; set; } public int Popularity { get; set; } } }} Now the XAML for populating a ListBox (though a ListView would be easier, because you wouldn't have to define a template this complicated to make it look nice): <Window x:Class="WpfApplication17.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid Margin="10"> <ListBox ItemsSource="{DynamicResource Drinks}" Grid.IsSharedSizeScope="True"> <ListBox.ItemTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition SharedSizeGroup="Key" /> <ColumnDefinition SharedSizeGroup="Name" /> <ColumnDefinition SharedSizeGroup="Popularity" /> </Grid.ColumnDefinitions> <TextBlock Margin="2" Text="{Binding Key}" Grid.Column="0"/> <TextBlock Margin="2" Text="{Binding Value.Name}" Grid.Column="1"/> <TextBlock Margin="2" Text="{Binding Value.Popularity}" Grid.Column="2"/> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid></Window> The XAML for a ListView is a lot simpler, and displays more nicely to boot: <ListView ItemsSource="{DynamicResource Drinks}"> <ListView.View> <GridView> <GridViewColumn Header="Key" DisplayMemberBinding="{Binding Key}" /> <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Value.Name}" /> <GridViewColumn Header="Popularity" DisplayMemberBinding="{Binding Value.Popularity}" /> </GridView> </ListView.View> </ListView> To answer your follow-up questions: I recommend Adam Nathan's Windows Presentation Foundation Unleashed . The chapter on layout with panels explains how the Grid works in considerable detail. The Grid 's pretty counter-intuitive in a lot of ways. You think that you'd want to create a single Grid that contains many items, but the number of rows and columns in a Grid isn't dynamic. So what you do instead is create a Grid for each item, and then use the shared-size functionality to make sure that the columns in each Grid are the same size. The ListView has quirks of its own, but it's a lot more straightforward for the common "display multiple items in a grid" use case. DynamicResource is a markup extension that works a lot like StaticResource . The difference is that when the XAML parser resolves StaticResource as it parses it - if the referenced resource isn't in the resource dictionary, it throws an exception. DynamicResource resolves the reference if the item gets added to the dictionary later. There's a bit of a performance cost to this, but it's negligible in most cases. The code I posted works if you use StaticResource , because the XAML gets parsed in InitializeComponent . But I don't like having to remember that, so I use DynamicResource by default if I'm binding to something that I'm adding to the resource dictionary in code and just don't worry about whether it's being created before or after the XAML gets parsed. And as for the toolbox: Maybe I'll start using that in VS2010, but I find the one in 2008 unusably buggy. And not very useful anyway. I do almost all of my layout work in the editor, and some in Kaxaml. I think the visual editor in 2008 actually made learning WPF harder , because it imposed an abstraction layer between me and the XAML (which is itself an abstraction layer between me and the WPF object model). And it's not a very good abstraction layer: the design decisions that went into deciding what should be hidden and what should be visible aren't, it seems to me, the right ones. Also it's buggy as hell.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2494823', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51816/']}
|
jdg_369446
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
678217
|
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 seen a lot of questions related to mapping DTOs to Domain Objects, but I didn't feel they answered my question. I've used many methods before and have my own opinions but I'm looking for something a little more concrete. The Situation: We have many domain objects. We are using a CSLA model so our domain objects can be pretty complex and they contain their own data access. You do not want to pass these around on the wire. We are going to be writing some new services that will return data in a number of formats (.Net, JSON, etc.). For this (and other reasons) we are also creating a lean, data transfer object to pass around on the wire. My question is: How should the DTO and Domain object be connected? My first reaction is to use a Fowler, DTO pattern-type solution . I've seen this done many times and it feels right to me. The domain object contains no reference to the DTO. An outside entity (a "mapper" or "assembler") is called to create a DTO from a Domain Object. Normally there is an ORM on the domain object side. The downside of this is that the "mapper" tends to get extremely complex for any real situation and can be very fragile. Another idea put forth is for the Domain Object to "contain" the DTO, since it's just a lean data object. The Domain Object properties would internally reference the DTO properties and could just return the DTO if asked for. I can see no problems with this but it feels wrong. I have seen some articles where people using NHibernate appeared to use this method. Are there other ways? Is one of the ways above worth using? If so or if not, why?
Now provide the response and nothing else.
|
A benefit of having a mapper that sits between your domain and your DTO is not as appearent when you are only supporting a single mapping, but as the number of mappings increases, having that code isolated from the domain helps keep the domain simpler and leaner. You won't be cluttering your domain with a lot of extra weight. Personally, I try and keep the mapping out of my domain entities and put the responsibility in what I call "Manager / Service layer". This is a layer that sits between the application and the respository(ies), and provides business logic such as workflow coordination (If you modify A, you might have to also modify B so service A will work with Service B). If I had a lot of possible ending formats, I might look at creating a plugable formatter that could use the Visitor pattern, for example to transform my entities, but I've not found a need yet for anything this complex.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/678217', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3129/']}
|
jdg_369447
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
74763
|
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Does there exist an equivalent arithmetic circuit for each computable function? I've been trying to wrap my head around the statement above, but haven't found a counter example although I believe the statement to be false. What has made me curious is that I've read some theorems stating that a protocol (cryptograhy protocol theory) can compute any computable function, but then requires that the function should be specified as an arithmetic circuit.
Now provide the response and nothing else.
|
Arithmetic circuits compute a polynomial in their input. An arithmetic circuit over some field $\mathbb{F}$ with $n$ variables and total degree $d$ can compute functions $f:\mathbb{F}^n\rightarrow\mathbb{F}$ of the form: $$f(x_1,...,x_n)=\sum\limits_{i_1+...+i_n\le d}\alpha _{i_1,...,i_n}\cdot x_1^{i_1}x_2^{i_2}...x_n^{i_n}$$ where $\alpha _{i_1,...,i_n}\in\mathbb{F}$ are the coefficients of the multivariate polynomial. There are many computable functions that cannot be expressed as a polynomial, e.g. take $f:\mathbb{Q}\rightarrow\mathbb{Q}$ which is $1$ at $x=0$ and zero everywhere else. Since $f$ is non constant with an infinite number of zeros, it cannot be written as a univariate polynomial.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/74763', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/8264/']}
|
jdg_369448
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
53964219
|
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 activate/deactivate a button based on the content of a TextFormField? I want to make sure a user can only press Button X if the TextFormField has 10 entered numbers (if it's a mobile number). Thanks!
Now provide the response and nothing else.
|
The state of the widget can be updated in the Form's onChanged callback which is called whenever any of the form fields' value changes. There you can use a form key to validate the form and set a flag to enable/disable the button. This solution allows you to scale to disable buttons in forms with multiple fields. For example, /// Key used to reference the form.final _formKey = GlobalKey<FormState>();...Form( key: _formKey, onChanged: () => setState(() => _enableBtn = _formKey.currentState.validate()), child: ListView( children: <Widget>[ TextFormField( validator: (value) => value.length < 10 ? 'Number must be at least 10 digits' : // return an error message null, ... ), ], ),)...FlatButton( onPressed: _enableBtn ? () => _doSomething() : null, // setting onPressed to null disables the button. ...
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53964219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9526494/']}
|
jdg_369449
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11920972
|
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 reading someone else's code and he had something like this: return val1 and val2 I tried this in the Python interpreter and it gave me the latter value on AND while OR gives me the prior value. So my question is what exactly is happening in that statement? Thanks.
Now provide the response and nothing else.
|
An expression using and or or short-circuits when it can determine that the expression will not evaluate to True or False based on the first operand, and returns the last evaluated value: >>> 0 and 'string'0>>> 1 and 'string''string'>>> 'string' or 10'string'>>> '' or 1010 This 'side-effect' is often used in python code. Note that not does return a boolean value. See the python documentation on boolean operators for the details.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11920972', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1204312/']}
|
jdg_369450
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
238300
|
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:
Alright, so the idea of an exponent, $x$, is that you are multiplying its base by itself $x$ number of times. With base $5$ and $x=3$, we have that $5^3$ = $5 \cdot 5 \cdot 5$ I understand that the logarithm with base $a$ of $x = c$, tells us that $$a^c = x$$ and for $c =$ positive; values for $x$ are greater than $1$, and for $c =$ negative; values for $x$ are less than $1$, and for $c = 0$, values for $x$ are...$1$. So in short, I understand how, by means of observation of the graph of $f(x) = \log x$, we can see that $f(1) = 0$, BUT, I see no other way to understand why $x^0 = 1$, apart from the graph and everything around that very point. I honestly cannot get my head around the idea, "$5$ times itself $0$ times... is one". Is it that there is no fundamental answer for this but that we simply know by the graph? Or can I truly understand $x^0 = 1$ on its own?
Now provide the response and nothing else.
|
$x^{n+1}=x\cdot x^n$ right? so $x^1=x \cdot x^0$ but $x=x^1$ so for that to hold true, $x^0$ must be $1$. Similarily, $\large x^{-n} = \frac{1}{x^n}$. So $\large x^n \cdot x^{-n} = x^n \frac{1}{x^n} = 1$. But $\large x^n \cdot x^{-n} = x^{n+(-n)} = x^0$, so once more, $x^0=1$. There are really many reasons for that to hold, and all of them are just a consequence of some agreements we've made previously.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/238300', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/49200/']}
|
jdg_369451
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23646
|
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Should we force website from HTTP to HTTPS , one of the method is using .htaccess: RewriteCond %{SERVER_PORT} 80RewriteRule ^(.*)$ https://www.example.com/$1 [R,L] But what I notice is that some service like Google Translate can't translate any HTTPS website. So what is the best practice to do it while keeping the user secure? Force to HTTPS using .htaccess even they browsing static page Don't force user to HTTPS automatically but the link in the hyperlinks will link to HTTPS? Use HTTPS only while form POST or page that contain sensitive information. Allow user to select HTTP or HTTPS ...
Now provide the response and nothing else.
|
Set up a rule which redirects any attempt to access the site via HTTP, over to the front page via HTTPS (redirect any attempt to access anything matching http://www.example.com/* to https:/www.example.com/ ). Enable HSTS . This tells browsers to connect to your site via HTTPS in the future. Set the secure flag on all cookies. Make sure pages delivered over HTTPS don't load any content via HTTP. Read the following questions on this site: Is a forced rewrite from http to https secure? What does SSLRequireSSL add? HSTS extra security over HTTPS Guidance for implementors of HTTPS-only sites (Server side) Options when defending against SSLstrip? Strict Transport Security — max_age value What are the pros and cons of site wide SSL (https)?
|
{}
|
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/23646', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/15721/']}
|
jdg_369452
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25374001
|
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 experiencing issues running my application on a physical device such as the Samsung Note 3 running on 4.4.2. For some odd reasons, the application works on the ace 2, as well as the emulator. To try and understand as to why it was not working on the note 3. I ran the application from eclipse through the device (connected it using a USB), and below is the log message that was generated from the unexpected error message that was triggered after login. The social media login is located in the login page, and then redirects users to another page, which is where the unexpected error is triggered. Below is the log cat message: 8-18 15:57:56.227: E/AndroidRuntime(19911): FATAL EXCEPTION: main 08-18 15:57:56.227: E/AndroidRuntime(19911): Process: com.dooba.beta, PID: 19911 08-18 15:57:56.227: E/AndroidRuntime(19911): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dooba.beta/com.dooba.beta.MoodActivity}: android.view.InflateException: Binary XML file line #90: Error inflating class <unknown> 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2282) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2340) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.app.ActivityThread.access$800(ActivityThread.java:157) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.os.Handler.dispatchMessage(Handler.java:102) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.os.Looper.loop(Looper.java:157) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.app.ActivityThread.main(ActivityThread.java:5293) 08-18 15:57:56.227: E/AndroidRuntime(19911): at java.lang.reflect.Method.invokeNative(Native Method) 08-18 15:57:56.227: E/AndroidRuntime(19911): at java.lang.reflect.Method.invoke(Method.java:515) 08-18 15:57:56.227: E/AndroidRuntime(19911): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265) 08-18 15:57:56.227: E/AndroidRuntime(19911): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081) 08-18 15:57:56.227: E/AndroidRuntime(19911): at dalvik.system.NativeStart.main(Native Method) 08-18 15:57:56.227: E/AndroidRuntime(19911): Caused by: android.view.InflateException: Binary XML file line #90: Error inflating class <unknown> 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.view.LayoutInflater.createView(LayoutInflater.java:626) 08-18 15:57:56.227: E/AndroidRuntime(19911): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:675) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:700) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.view.LayoutInflater.rInflate(LayoutInflater.java:761) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.view.LayoutInflater.inflate(LayoutInflater.java:498) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.view.LayoutInflater.inflate(LayoutInflater.java:398) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.view.LayoutInflater.inflate(LayoutInflater.java:354) 08-18 15:57:56.227: E/AndroidRuntime(19911): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:340) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.app.Activity.setContentView(Activity.java:1973) 08-18 15:57:56.227: E/AndroidRuntime(19911): at com.dooba.beta.MoodActivity.onCreate(MoodActivity.java:20) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.app.Activity.performCreate(Activity.java:5389) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2246) 08-18 15:57:56.227: E/AndroidRuntime(19911): ... 11 more 08-18 15:57:56.227: E/AndroidRuntime(19911): Caused by: java.lang.reflect.InvocationTargetException 08-18 15:57:56.227: E/AndroidRuntime(19911): at java.lang.reflect.Constructor.constructNative(Native Method) 08-18 15:57:56.227: E/AndroidRuntime(19911): at java.lang.reflect.Constructor.newInstance(Constructor.java:423) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.view.LayoutInflater.createView(LayoutInflater.java:600) 08-18 15:57:56.227: E/AndroidRuntime(19911): ... 24 more 08-18 15:57:56.227: E/AndroidRuntime(19911): Caused by: java.lang.OutOfMemoryError 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:677) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:507) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:872) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.content.res.Resources.loadDrawable(Resources.java:3022) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.content.res.TypedArray.getDrawable(TypedArray.java:602) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.view.View.<init>(View.java:3694) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.widget.TextView.<init>(TextView.java:868) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.widget.Button.<init>(Button.java:108) 08-18 15:57:56.227: E/AndroidRuntime(19911): at android.widget.Button.<init>(Button.java:104) 08-18 15:57:56.227: E/AndroidRuntime(19911): ... 27 more class activity public class LoginActivity extends Activity { private Button facebookButton; private Button twitterButton; private Dialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); twitterButton = (Button) findViewById(R.id.twitterButton); twitterButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { findViewById(R.id.twitterButton).setBackgroundResource(R.drawable.ltwitternf); onTwitterButtonClicked(); } }); facebookButton = (Button) findViewById(R.id.facebookButton); facebookButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { findViewById(R.id.facebookButton).setBackgroundResource(R.drawable.lfacebooknf); onLoginButtonClicked(); } }); // Check if there is a currently logged in user // and they are linked to a Facebook account. ParseUser currentUser = ParseUser.getCurrentUser(); if ((currentUser != null) && ParseFacebookUtils.isLinked(currentUser)) { // Go to the user info activity intropage(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); ParseFacebookUtils.finishAuthentication(requestCode, resultCode, data); } private void onLoginButtonClicked() { LoginActivity.this.progressDialog = ProgressDialog.show( LoginActivity.this, "", "Logging in...", true); List<String> permissions = Arrays.asList("public_profile", "user_about_me", "user_relationships", "user_birthday", "user_location"); ParseFacebookUtils.logIn(permissions, this, new LogInCallback() { @Override public void done(ParseUser user, ParseException err) { LoginActivity.this.progressDialog.dismiss(); if (user == null) { Log.d(IntegratingFacebookTutorialApplication.TAG, "Uh oh. The user cancelled the Facebook login."); } else if (user.isNew()) { Log.d(IntegratingFacebookTutorialApplication.TAG, "User signed up and logged in through Facebook!"); showUserDetailsActivity(); } else { Log.d(IntegratingFacebookTutorialApplication.TAG, "User logged in through Facebook!"); moodpage(); } } }); } private void onTwitterButtonClicked() { ParseTwitterUtils.logIn(this, new LogInCallback() { @Override public void done(ParseUser user, ParseException err) { if (user == null) { Log.d("MyApp", "Uh oh. The user cancelled the Twitter login."); } else if (user.isNew()) { Log.d("MyApp", "User signed up and logged in through Twitter!"); showUserDetailsActivity(); } else { Log.d("MyApp", "User logged in through Twitter!"); moodpage(); } } }); } private void showUserDetailsActivity() { Intent intent = new Intent(this, ProfileCreation.class); startActivity(intent); } private void moodpage() { Intent intent = new Intent(this, MoodActivity.class); startActivity(intent); } private void intropage() { Intent intent = new Intent(this, introActivity.class); startActivity(intent); }} Below is the moodactivity page public class MoodActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mood); final TextView teating = (TextView) this.findViewById(R.id.tdinning); teating.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MoodActivity.this.startActivity(new Intent(MoodActivity.this, CasualEventsActivity.class)); } }); final ImageView ieating = (ImageView) this.findViewById(R.id.idinning); ieating.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MoodActivity.this.startActivity(new Intent(MoodActivity.this, CasualEventsActivity.class)); } }); final TextView tdrinks = (TextView) this.findViewById(R.id.tcasual); tdrinks.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MoodActivity.this.startActivity(new Intent(MoodActivity.this, CasualEventsActivity.class)); } }); final ImageView idrinks = (ImageView) this.findViewById(R.id.icasual); idrinks.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MoodActivity.this.startActivity(new Intent(MoodActivity.this, CasualEventsActivity.class)); } }); final TextView tshows = (TextView) this.findViewById(R.id.tshows); tshows.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MoodActivity.this.startActivity(new Intent(MoodActivity.this, CultureEventsActivity.class)); } }); final ImageView ishows = (ImageView) this.findViewById(R.id.ishows); ishows.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MoodActivity.this.startActivity(new Intent(MoodActivity.this, CultureEventsActivity.class)); } }); final TextView tarts = (TextView) this.findViewById(R.id.tculture); tarts.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MoodActivity.this.startActivity(new Intent(MoodActivity.this, CultureEventsActivity.class)); } }); final ImageView iarts = (ImageView) this.findViewById(R.id.iculture); iarts.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MoodActivity.this.startActivity(new Intent(MoodActivity.this, CultureEventsActivity.class)); } }); final Button viewall = (Button) this.findViewById(R.id.brandom); viewall.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MoodActivity.this.startActivity(new Intent(MoodActivity.this, CasualEventsActivity.class)); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main_activity_actions, menu); getActionBar().setDisplayShowTitleEnabled(false); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.pageExperience: openPageExperience(); return true; case R.id.pageMessaging: openPageMessage(); return true; case R.id.pageEventsBooking: openPageBook(); return true; case R.id.pageProfile: openPageProfile(); return true; case R.id.pageReport: openPageReport(); return true; case R.id.pageAbout: openPageAbout(); return true; default: return super.onOptionsItemSelected(item); } } private void openPageAbout() { // TODO Auto-generated method stub } private void openPageReport() { // TODO Auto-generated method stub } private void openPageProfile() { // TODO Auto-generated method stub Intent intent = new Intent(this, ProfileChange.class); startActivity(intent); } private void openPageBook() { // TODO Auto-generated method stub } private void openPageMessage() { // TODO Auto-generated method stub } private void openPageExperience() { // TODO Auto-generated method stub Intent intent = new Intent(this, MoodActivity.class); startActivity(intent); } } If you need clarification, let me know.Thanks in advance.
Now provide the response and nothing else.
|
Prior to Sass 3.4 , this is just not possible at all. The deal-breaking features here are the ability to store the current selector into a variable and the ability to split a string (though the later could be created via SassScript functions). @mixin append-attr($x) { $sel: &; $collector: (); @for $i from 1 through length($sel) { $s: nth($sel, $i); $last: nth($s, -1); @if str-slice($last, -1) == "]" { // if is just the bare attribute with no value, $offset will be -1, otherwise it will be -2 $offset: -1; $current-x: $x; @if str-slice($last, -2) == '"]' { // this attribute already has a value, so we need to adjust the offset $offset: -2; } @else { // no attribute value, so add the equals and quotes $current-x: '="' + $x + '"'; } $last: str-slice($last, 1, $offset - 1) + $current-x + str-slice($last, $offset); $collector: append($collector, set-nth($s, -1, $last), comma); } @else { // following line will append $x to your non-attribute selector $collector: append($collector, selector-append($s, $x), comma); // the following line will not change your non-attribute selector at all //$collector: append($collector, $s, comma); } } @at-root #{$collector} { @content; }} Usage: [data-product] { color: white; @include append-attr("red") { color: red; @include append-attr('-green') { color: green; } }}[one], [two] { color: orange; @include append-attr('alpha') { color: yellow; }}[test], .test { @include append-attr('-one') { color: red; }}.bar input[min] { @include append-attr('5') { background: yellow; }} Output: [data-product] { color: white;}[data-product="red"] { color: red;}[data-product="red-green"] { color: green;}[one], [two] { color: orange;}[one="alpha"], [two="alpha"] { color: yellow;}[test="-one"], .test-one { color: red;}.bar input[min="5"] { background: yellow;} Related: Modifying the middle of a selector in Sass (adding/removing classes, etc.)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25374001', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3827788/']}
|
jdg_369453
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2161912
|
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 try to write a method like below public void someStuff(Object ... args, String a ) I get this error The variable argument type Object of the method someStuff must be the last parameter. I don't fully understand the requirement of variable argument type to be the last.Any inputs will be helpful.
Now provide the response and nothing else.
|
It follows the C convention. The C convention in turn is based on CPU architectures which pass arguments on the stack. The first non-vararg arguments end up at a fixed offset in the stackframe. If you could put the vararg arguments first, the stack offset of the following arguments would depend on how many vararg parameters you would have passed. This would greatly complicate the amount of code needed to access them. In your example, with String a first, it's conceptually at offset 0 independent how the number of vararg arguments that follow. But with String a last, it could be at offset 0, 4, 8, 12 etc - you'd have to calculate args.size * 4 everytime you needed String a .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2161912', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/177758/']}
|
jdg_369454
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21006701
|
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 an Android app that I would like to eventually port to iOS and Windows Mobile (though I know absolutely nothing about them right now). I'd like my app to be able to find other phones within a certain radius (maybe 20-30 feet) that also have the game installed so that the users can interact with others in their current physical space. Is this possible and, if so, how? I plan on the app requiring an internet connection so my first thought was to use GPS like described at iOS Find Other Nearby Devices (GPS locations) , but that would require continually transmitting data to the server to update the user's location using both bandwidth and battery (not to mention the server resources). GPS also seems to take a while to get any sort of accurate fix, and even though I wouldn't store historical data I wouldn't expect users to trust me with that sort of private information (as well they shouldn't!) I know there are proprietary technologies, such as Sony's NFC, but that's far too narrow a focus to use for an app that I'd like to be device and OS agnostic. What other options are there? Assuming the user is willing to give the app the appropriate permissions, what other methods could allow one device to find another nearby one, within a 10-15 meter range, that is practical for a large (million+) userbase? Is HTML5 Geolocation a better path? Or is GPS my only real option? I did find Use Android GPS to detect and connect with other phones , but was hoping the past few years have opened up further options. UPDATE Thank you for all the responses so far. To answer some questions posed in the comments and answers, I thought I'd describe how I expect the apps/devices to interact. All users who install this app will have an agent running in the background to update their current geolocation and to listen for pings. Any user may open the full program and send a quick request for all other users nearby. If I go the central server route, then the server responds to that request with a list of nearby usernames. The user can then pick one of those to initiate a connection, in which case the target device makes a sound to notify of a request to connect. From there it's easy enough to handle the interaction between two devices. Finding those nearby users is the sticking point for me.
Now provide the response and nothing else.
|
Options I can see Bluetooth (BT). I don't know, if I'm not too skeptical about it, but I see couple of problems. Short range. The biggest energy consumption. Maximum 7 peers connected at the same time (but maybe it's enough...). The big advantage is that a lot of devices support BT. BT LE (low energy). Ok, it helps energy consumption problem. But, requires Android 4.3. WiFi Direct (aka P2P). I gave it a shot, I'm a bit disappointed. The problem is that it needs Android 4.0 or higher. Even worse, some devices don't have required hardware. I launched WiFiDirectDemo from Android samples on Samsung Xperia Miro ST23i. Clicked on "search" and the only thing I got was a toast "enable WiFi P2P - in your settings". I clicked on everything in that settings, there is just normal WiFi and other stuff, no mention about Direct or P2P. Xperio Miro just doesn't support WiFi Direct. WiFi connection with a server through internet + device geolocation. Server keeps positions of users and answers questions like "who is 20 feet in my range?". The problem can be the precision of geolocation. If the walls are thick or you are in a place on earth with few satellites - it can be very inaccurate. To sum up There is greater probability that somebody will have WiFi turned on all the time than BT. BT also have some time limits after which it is turned off (they make it this way to probably save battery). So, WiFi seems a better choice than BT. If WiFi Direct is popular enough for you - I would give it a try. If not, option number 4 seems the best. It's not ideal, I know, but at this point it's hard to come with something better (we still need technology development, WiFi Direct looks promising).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21006701', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/762721/']}
|
jdg_369455
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24259947
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
g++ appears to accept any combination of auto and decltype(auto) as initial and trailing return types: int a;auto f() { return (a); } // intauto g() -> auto { return (a); } // intauto h() -> decltype(auto) { return (a); } // int&decltype(auto) i() { return (a); } // int&decltype(auto) j() -> auto { return (a); } // intdecltype(auto) k() -> decltype(auto) { return (a); } // int& However, clang rejects j and k , saying: error: function with trailing return type must specify return type 'auto', not 'decltype(auto)' ( demonstration ). Which compiler is correct? Which rule ( auto or decltype(auto) ) should be used in each case? And does it make any sense to use a placeholder type in a trailing-return-type ?
Now provide the response and nothing else.
|
auto is required when introducing a trailing-return-type . §8.3.5 [dcl.fct] /2 In a declaration T D where D has the form D1 ( parameter-declaration-clause ) cv-qualifier-seq opt ref-qualifier opt exception-specification opt attribute-specifier-seq opt trailing-return-type and the type of the contained declarator-id in the declaration T D1 is “derived- declarator-type-list T ”, T shall be the single type-specifier auto. [...] See also Core Issue 1852 for the apparent contradiction with [dcl.spec.auto]/1.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24259947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/567292/']}
|
jdg_369456
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3372
|
Below is a question asked on the forum scicomp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I implemented downhill simplex simulated annealing algorithm. Algorithm is very hard to tune, w.r.t. parameters including cooling schedule, starting temperature... My first question is about convergence. In general, independently from choice of initial parameters, is it sure that algorithm converges to global optimal solution? More precisely: I use SA with downhill simplex based on Num.recipes, however, I am adding some specific actions for observing constraints. Do you think my additional conditions for constraints are cause for bad convergence? Then, I would like your advice on how to go on with solver conception: for instance, my algo is tested on data in 10-D space (10 parameters). It goes as follows: a preprocessing (monte carlo) picks up a good starting point. Then I run simplex downhill --> does not converge. I run simulated annealing (with simplex downhill to go to next step), and it remains far to solution (RMSE == 0.001). Excel solver on these data does the job very good. Excel method is generalized reduced gradient. Should i go on with fine tuning for SA, or go to non-derivative-free methods s.a. GRG ? Finally, to speak the same language: with my example, convergence is not reach AT ALL. i don't have time to reach a local minimum either, since I have put some exit conditions when the simplex gets stuck. what does one mean in general with 'solver does not converge'? does it mean that termination condition (s.a. go below a tolerance value) is met and solution is sub optimal, or can it mean that termination condition is never met? Thanks & regards. EDIT My objective function is given explicitly. It can, for instance, look like $F(p) = \sum_{j=1}^{n}\Bigg(y_{j} - (p_{1} + p_{2}\exp{\Big(-\frac{(x_{i}-p_{3})^{2}}{p_{4}}\Big)} + p_{5}\exp{\Big(-\frac{(x_{j}-p_{6})^{2}}{p_{7}}\Big)} + p_{8}\exp{\Big(-\frac{(x_{j}-p_{9})^{2}}{p_{10}}\Big))}\Bigg)^{2}$ so, the squared residuals with a 'three Gaussians + step' model. This is an example, solver should solve for any combination of functions among gaussians, exponential, power, polynomial, linear, rational with 'reasonable' number of parameters. Box constraints on parameters are specified, with form $l_{i} \leq p_{i} \leq u_{i}$.
Now provide the response and nothing else.
|
There is a theorem that syas that a black box algorithm is guaranteed to find the global minimum of an arbitrary smooth (i.e., twice continuously differentiable) function if and only if it samples points densely in the search space. Here dense is meant in the topological sense, i.e., it must sample points in arbirarily small neighborhoods of every point. In this case, the worst case complexity is $O(\Big(\frac{d}{\delta}\Big)^{-n})$, [ the Latex parser chokes with nested big brackets ] where $d$ is the diameter of the search space and $\delta$ the guaranteed error in $x$. Edit: While this looks like being the worst case complexity for locating an $\delta$-accurate $x$ rather than for locating a point for a $\epsilon$-accurate $f$, the complexity for the latter is as bad (even for the rather big value of $\epsilon=(f_{first}-f_{global})/2$), as one can easily construct a smooth function which interpolates all data points so far but takes much smaller values in the center of the largest open ball not containing one of the points evaluated. Thus guaranteed convergence to a global minimum is worthless in practice. (For example, uniformly random search has a convergence guarantee to the global minimizer, whereas most practically fast algorithms don't have one.) Note that simulated annealing usually performs much worse than modern methods. Rather use code recommended in: Comparison of derivative-free optimization algorithms (2012, by Nick Sahinidis) Black-Box Optimization Benchmarking (BBOB) 2012 (by Auger, Hansen, et al.)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://scicomp.stackexchange.com/questions/3372', 'https://scicomp.stackexchange.com', 'https://scicomp.stackexchange.com/users/1184/']}
|
jdg_369457
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
344570
|
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 often find myself writing functions that look like this because theyallow me to easily mock data access, and still provide a signature that accepts parameters to determine what data to access. public static string GetFormattedRate( Func<string, RateType>> getRate, string rateKey){ var rate = getRate(rateKey); var formattedRate = rate.DollarsPerMonth.ToString("C0"); return formattedRate;} Or public static string GetFormattedRate( Func<RateType, string> formatRate, Func<string, RateType>> getRate, string rateKey){ var rate = getRate(rateKey); var formattedRate = formatRate(rate); return formattedRate;} Then I use it something like this: using FormatterModule;public static Main(){ var getRate = GetRateFunc(connectionStr); var formattedRate = GetFormattedRate(getRate, rateType); // or alternatively var formattedRate = GetFormattedRate(getRate, FormatterModule.FormatRate, rateKey); System.PrintLn(formattedRate);} Is this a common practice? I feel like I should be doing something more like public static string GetFormattedRate( Func<RateType> getRate()){ var rate = getRate(); return rate.DollarsPerMonth.ToString("C0");} But that doesn't seem to work very well because I'd have to make a new function to pass into the method for every rate type. Sometimes I feel like I should be doing public static string GetFormattedRate(RateType rate){ return rate.DollarsPerMonth.ToString("C0");} But that seems to take away any fetch and format re-usability. Whenever I want to fetch and format I have to write two lines, one to fetch and one to format. What am I missing about functional programming? Is this the right way to do it, or is there a better pattern that's both easy to maintain and use?
Now provide the response and nothing else.
|
There is absolutely no reason to pass a function, and its parameters, only to then call it with those parameters. In fact, in your case you have no reason to pass a function at all . The caller might as well just call the function itself and pass the result. Think about it - instead of using: var formattedRate = GetFormattedRate(getRate, rateType); why not simply use: var formattedRate = GetFormattedRate(getRate(rateType)); ? As well as reducing unnecessary code it also reduces coupling - if you want to change how the rate is fetched (say, if getRate now needs two arguments) you don't have to change GetFormattedRate . Likewise, there's no reason to write GetFormattedRate(formatRate, getRate, rateKey) instead of writing formatRate(getRate(rateKey)) . Don't overcomplicate things.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/344570', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/115850/']}
|
jdg_369458
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19770131
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
According to Accelerated C++: To use this strategy, we need a way to remove an element from a vector. The good news is that such a facility exists; the bad news is that removing elements from vectors is slow enough to argue against using this approach for large amounts of input data. If the data we process get really big, performance degrades to an astonishing extent. For example, if all of our students were to fail, the execution time of the function that we are about to see would grow proportionally to the square of the number of students. That means that for a class of 100 students, the program would take 10,000 times as long to run as it would for one student. The problem is that our input records are stored in a vector, which is optimized for fast random access. One price of that optimization is that it can be expensive to insert or delete elements other than at the end of the vector. The authors do not explain why the vector would be so slow for 10,000+ students, and why in general it is slow to add or remove elements to the middle of a vector. Could somebody on Stack Overflow come up with a beautiful answer for me?
Now provide the response and nothing else.
|
Take a row of houses: if you build them in a straight line, then finding No. 32 is really easy: just walk along the road about 32 houses' worth, and you're there. But it's not quite so fun to add house No. 31½ in the middle — that's a big construction project with a lot of disruption to husband's/wife's and kids' lives. In the worst case, there is not enough space on the road for another house anyway, so you have to move all the houses to a different street before you even start. Similarly, vectors store their data contiguously , i.e. in a continuous, sequential block in memory. This is very good for quickly finding the n th element (as you simply have to trundle along n positions and dereference), but very bad for inserting into the middle as you have to move all the later elements along by one, one at a time. Other containers are designed to be easy to insert elements, but the trade-off is that they are consequently not quite as easy to find things in. There is no container which is optimal for all operations.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19770131', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2836797/']}
|
jdg_369459
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22380467
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am getting a list of missing icons when uploading binary to Apple store. I have already added these missing icons by selecting the project icon --> General --> Selected the required icon file. I have already added these icon files to my project. After that I performed clean and Archive. How can we remove this warning message?
Now provide the response and nothing else.
|
sizeof 5 + 5 it's parsed as (sizeof(5)) + 5 and not sizeof(5+5) due to operators priorities, so it becomes 4 + 5 and 9 . For more info about this, like chris said, have a look at this table . For the substraction it's the same, but as the type of the expression is size_t which is unsigned, the substraction is done on unsigned ints which wrap around 2^32 which is 4,294,967,296 . Thererfore, sizeof 10 - 5 is 4 - 5 which becomes (4,294,967,296) - 1 in 32 bit unsigned arithmetic, that's the 4,294,967,295 you're getting. Going further Internally during the parsing step of the compilation process, each source code statement is transformed into an expression tree (often called AST ), you can look here for exemple if you're curious about these things. For a more hands-on practical understanding, install the clang compiler and play with clang -Xclang -ast-dump -fsyntax-only source.cpp Which displays the tree from your code. Really nice, but I recommand short code because the output can be overwhelming otherwise ;)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22380467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1999876/']}
|
jdg_369460
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
733868
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the difference between AppDomain , Assembly , Process , and a Thread ?
Now provide the response and nothing else.
|
An AppDomain is an isolation unit within a process. AppDomains can be created at runtime, loaded with code, and unloaded. Its an isolation boundary designed to make .NET apps more reliable. An assembly holds one or more modules, which hold compiled chunks of code. You will typically see an assembly as an .EXE or a .DLL. A process is an executing application (waaaay oversimplified). A thread is an execution context. The operating system executes code within a thread. The operating system switches between threads, allowing each to execute in turn, thus giving the impression that multiple applications are running at the same time. To put it all together (very simplified)... A program is executed. A process is created by the operating system, and within its single thread it starts loading code to execute. In a .NET application, a single AppDomain is created by the CLR. The application's executing assembly (the .EXE) is loaded into this AppDomain and begins execution. The application can spawn new processes, create AppDomains, load other assemblies into these domains, and then create new Threads to execute code in any of these AppDomains.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/733868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/88918/']}
|
jdg_369461
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29835232
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Please explain to me why this code produces a StackOverflowException . There is a mistake in one of the lines as I have shown using comment. I do not however understand why this gives me a StackOverflowException . class TimePeriod{ private double seconds; public double hour { get { return hour / 3600; } // should be : get { return seconds / 3600; } set { seconds = value * 3600; } }}class Program{ static void Main() { TimePeriod t = new TimePeriod(); t.hour = 5; System.Console.WriteLine("Time in hours: " + t.hour); }}
Now provide the response and nothing else.
|
This produces a stack-overflow, because there is a recursive call on the hour , when you try to get it. Here t.hour , you try to get the value of hour . This we call the getter, which returns hour / 3600 . This will call again the hour and so on and so forth, until the stack will overflow.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29835232', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3670482/']}
|
jdg_369462
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23535355
|
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 my app to send a notification when there is a call (incoming call, connected, call ended) I registered my viewController with notification. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callReceived:) name:CTCallStateIncoming object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callEnded:) name:CTCallStateDisconnected object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callConnected:) name:CTCallStateConnected object:nil]; I also made a method to check call state -(IBAction)checkForCall:(id)sender{ NSLog(@"call state %@ id %@",call.callState,call.callID); CTCallCenter *callCenter = [[CTCallCenter alloc] init]; callCenter.callEventHandler = ^(CTCall* call){ if (call.callState == CTCallStateDisconnected) { NSLog(@"Call has been disconnected"); } else if (call.callState == CTCallStateConnected) { NSLog(@"Call has just been connected"); } else if(call.callState == CTCallStateIncoming) { NSLog(@"Call is incoming"); } else { NSLog(@"None of the conditions"); } };} But none of this works. Please help me. Where is the mistake? Is there any code which tells how to use core telephony?
Now provide the response and nothing else.
|
use this Appdelegate.h #import <CoreTelephony/CTCallCenter.h>#import <CoreTelephony/CTCall.h>...@property (nonatomic, strong) CTCallCenter* callCenter; AppDelegate.m - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ .... self.callCenter = [[CTCallCenter alloc] init]; [self handleCall]; .... }-(void)handleCall{ self.callCenter.callEventHandler = ^(CTCall *call){ if ([call.callState isEqualToString: CTCallStateConnected]) { //NSLog(@"call stopped"); } else if ([call.callState isEqualToString: CTCallStateDialing]) { } else if ([call.callState isEqualToString: CTCallStateDisconnected]) { //NSLog(@"call played"); } else if ([call.callState isEqualToString: CTCallStateIncoming]) { //NSLog(@"call stopped"); } }; }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23535355', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3535353/']}
|
jdg_369463
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
58190
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
[02:48][root@server:~] ps ax | grep svn 23986 ? Ss 0:00 /usr/bin/svnserve -d -r /srv/svnAs you see from arguments my svn root dir is /srv/svn. Now, some magic from remote machine... This works: > svn co svn://svn-user@domain.com/test-repo But this not: > svn co svn+ssh://svn-user@<putty-session-name>/test-repo'No repository found in 'svn+ssh://svn-user@<putty-session-name>/test-repo' Playing around for couple of hours I've found that appearantly if I use ssh tunnel, I'm able to get my repo using following: > svn co svn+ssh://svn-user@<putty-session-name>/srv/svn/test-repo ...which means that I should specify full physical path to the repo.Huh?
Now provide the response and nothing else.
|
As womble have said, indeed this is the 'feature' of svn over ssh. I had svn+ssh working without specifying the full path to repositories because the svn server had a svnserve wrapper script in place of original svnserve binary. Later, during subversion update this script was overwritten by the original binary. Solution: Rename svnserve to bin mv /usr/bin/svnserve /usr/bin/svnserve.bin Save this script as /usr/bin/svnserve: #!/bin/shexec /usr/bin/svnserve.bin -r /srv/svn "$@" Update permissions chmod 755 /usr/bin/svnserve
|
{}
|
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/58190', 'https://serverfault.com', 'https://serverfault.com/users/18079/']}
|
jdg_369464
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25835
|
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have recently came across an old blog post by Jeff Atwood which got me thinking. What could be easier than a EncryptStringForBrowser() method which has security and tamper-resistance built in, that's part of a proven, domain-expert-tested set of code that thousands if not millions of developers already rely on? Obviously the first rule of cryptography is to never roll your own. However, how far should a developer take this? Should they build upon the cryptography libraries present in the programming language? Should they use third party cryptography libraries? Or should they take things on step further and use a library that takes care of everything, such as uLogin for PHP for example. If a third party library is to be used, how can a non-cryptographer verify the security of said library besides going by it's reputation.
Now provide the response and nothing else.
|
My take-aways would be: Never roll your own cryptography if you can avoid it. (Sometimes you'll have to for tailor-made solutions / embedded platforms.) If you have to roll your own, always build on known working protocols. Don't rely on hiding your implementation. Obfuscation is a valid layer of defense in depth, but should only be used to add to existing security, not be your main source of security. Use third party products that have some kind of trust and reputation. For C / C++ / Objective C, I use the cryptographic parts of the SSL library PolarSSL . PolarSSL has very little inside and outside dependencies and you can just rip out the parts you need and PolarSSL has been vetted by the Dutch government . Checking it yourself is not really an option.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/25835', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/-1/']}
|
jdg_369465
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5931261
|
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 could only do this with String, for example: String str="";for(int i=0;i<100;i++){ str=i+str;} Is there a way to achieve this with StringBuilder? Thanks.
Now provide the response and nothing else.
|
StringBuilder sb = new StringBuilder();for(int i=0;i<100;i++){ sb.insert(0, Integer.toString(i));} Warning: It defeats the purpose of StringBuilder , but it does what you asked. Better technique (although still not ideal): Reverse each string you want to insert. Append each string to a StringBuilder . Reverse the entire StringBuilder when you're done. This will turn an O( n ²) solution into O( n ).
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/5931261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/685275/']}
|
jdg_369466
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7310454
|
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 having trouble remembering how (but not why) to use IEnumerator s in C#. I am used to Java with its wonderful documentation that explains everything to beginners quite nicely. So please, bear with me. I have tried learning from other answers on these boards to no avail. Rather than ask a generic question that has already been asked before, I have a specific example that would clarify things for me. Suppose I have a method that needs to be passed an IEnumerable<String> object. All the method needs to do is concatenate the letters roxxors to the end of every String in the iterator. It then will return this new iterator (of course the original IEnumerable object is left as it was). How would I go about this? The answer here should help many with basic questions about these objects in addition to me, of course.
Now provide the response and nothing else.
|
Here is the documentation on IEnumerator . They are used to get the values of lists, where the length is not necessarily known ahead of time (even though it could be). The word comes from enumerate , which means "to count off or name one by one". IEnumerator and IEnumerator<T> is provided by all IEnumerable and IEnumerable<T> interfaces (the latter providing both) in .NET via GetEnumerator() . This is important because the foreach statement is designed to work directly with enumerators through those interface methods. So for example: IEnumerator enumerator = enumerable.GetEnumerator();while (enumerator.MoveNext()){ object item = enumerator.Current; // Perform logic on the item} Becomes: foreach(object item in enumerable){ // Perform logic on the item} As to your specific scenario, almost all collections in .NET implement IEnumerable . Because of that, you can do the following: public IEnumerator Enumerate(IEnumerable enumerable){ // List implements IEnumerable, but could be any collection. List<string> list = new List<string>(); foreach(string value in enumerable) { list.Add(value + "roxxors"); } return list.GetEnumerator();}
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7310454', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/758446/']}
|
jdg_369467
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35883
|
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
So our website was hacked, and these are the things that were done: Some entries in the database were changed. I don't know if this was via SQL injection, or direct database access (only root is allowed to make database changes, is it possible to emulate root or obtain its password?) or through the CMS of the website. My guess is that it was through the CMS. The code of the index page was changed to some dramatic declaration of hacking success on the part of the hacker. I just got a free scan done from Qualys ( https://freescan.qualys.com/freescan-front/module/freescan/#scan_report?id=39003& ) which says that SSL Server Allows Anonymous Authentication Vulnerability . This is probably true because whenever I log in to FTP, it tells me that some certificate isn't valid, but I always just ignore and hit "Continue". I'm using a VPS (not shared) account on my hosting company's server. What are the first things I should look to fix? Edit #1 I just found some weird files added on the server, including a "wso.php" which appeared to be accessing cookies and other things with system passwords.Then in the public_html folder I found a new folder I hadn't seen before, called sym , and when i opened it, lo and behold it had a folder called root which was basically a recursive clone of my entire root folder, and next to it an .htaccess which said the following: Options all DirectoryIndex Sux.html AddType text/plain .php AddHandler server-parsed .php AddType text/plain .html AddHandler txt .html Require None Satisfy Any I have a few questions - Does that give any more hints on what kind of attack this was? Are these "evil" .htaccess contents? One of the files was boy.php.jpg. Given that one of the site's forms allows users to upload images, stores their file paths, and then through a DB-backed CMS accesses those uploaded images, could this have been a SQL injection where a malicious file dressed as an image was uploaded and then accessed as regular page content? My company's annoyed by the hack but I have to admit I'm a tad excited about this mystery! (a total newbie at security as you can probably tell) Edit #2 Yet another update. I discovered this page: http://dealshop.cc/a7a/ What is this and any idea how it works? My website is one of the ones listed, so maybe the shell was "uploaded" as a jpg file? Edit #3 For some reason it didn't occur to me to mention this earlier, but my MySQL database has been hacked - when I browse tables through phpMyAdmin, some of the ID columns of some tables are full of lines like cat /etc/pwd and +response.write(9062801*9462776)+ . Does this mean that the entry point was definitely a SQL injection?
Now provide the response and nothing else.
|
Get a known clean version of your site and identify the differences between the known good code the and current (hacked) production code. Study how the changes may have been made and repair. Update the passwords. Fix the FTP certificate issue - consider using 2 factor authentication. Find a way to scan your code for vulnerabilities - peer review or automated analysis. Enable logging so if this happens again you have log files. If you already have decent logging, look at the files accessed and see if there's injection via the URL. Consider using a web application firewall. Tell your legal department, the police, partners, customers if you believe their data to have been stolen or compromised
|
{}
|
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/35883', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/25989/']}
|
jdg_369468
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30336365
|
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 sort data by the date from latest to earliest. My trouble is that the data i have has dates in mm-dd-yyyy text format. I could easily clean this up using Pandas in python but don't know the tools available in excel. Even when I try to change the format by hand it does not remove the hyphens. I believe that due to the poor formatting when I sort on the data it sorts on the month first and years end up grouped together instead of keeping the data chronological. Something this basic must be an easy fix but I haven't found a tool to use. Thanks in advance! Solved using Selection.TextToColumns Destination:=Range("A5"), DataType:=xlDelimited, _ TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _ Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _ :="-", FieldInfo:=Array(Array(1, 3), Array(2, 1), Array(3, 1)), _ TrailingMinusNumbers:=True Which eliminates the hyphen by identifying it as the delimited and breaking each date segment into its own cell. Very sorry for using \selection\ which I know people hate.
Now provide the response and nothing else.
|
In your example UserHasSignedUp is an Event . SendWelcomeEmail and SendAdminEmail are two listeners "waiting" for the event UserHasSignedUp to be fired and they should implement the required business logic at handle method of each one. Super simple example: Somewhere in UserController Event::fire(new UserHasSignedUp($user)); //UserHasSignedUp is the event being fired SendWelcomeEmail class class SendWelcomeEmail //this is the listener class{ public function handle(UserHasSignedUp $event) //this is the "handler method" { //send an email } } As you can see, each event can have multiple listeners, but a listener can't listen to more than a single event.If you want a class listening to many events, you should take a look to Event Subscribers Hope it helps.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30336365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3033634/']}
|
jdg_369469
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
896808
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Which one is more efficient over a very large set of files and should be used? find . -exec cmd {} + or find . | xargs cmd (Assume that there are no funny characters in the filenames)
Now provide the response and nothing else.
|
Speed difference will be insignificant. But you have to make sure that: Your script will not assume that nofile will have space, tab, etc infile name; the first version issafe, the second is not. Your script will not treat a file starting with " - " as an option. So your code should look like this: find . -exec cmd -option1 -option2 -- {} + or find . -print0 | xargs -0 cmd -option1 -option2 -- The first version is shorter and easier to write as you can ignore 1, but the second version is more portable and safe, as " -exec cmd {} + " is a relatively new option in GNU findutils (since 2005, lots of running systems will not have it yet) and it was buggy recently . Also lots of people do not know this " -exec cmd {} + ", as you can see from other answers.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/896808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7412/']}
|
jdg_369470
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
51355699
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
To my understanding the following code should print False as output However, when I ran this code it is printing True as output. From Java docs: Return true if the integer argument includes the abstract modifier, false otherwise. public class Test{ public static void main(String[] args) { System.out.println(Modifier.isAbstract(byte[].class.getModifiers())); }} Can some one help me understand this behavior ?
Now provide the response and nothing else.
|
The Javadoc of int java.lang.Class.getModifiers() specifies what should be returned for some of the modifiers for array types (for example, the final modifier is required to be true and the interface modifier is required to be false ). On the other hand, it doesn't specify what the abstract or static modifiers should be for array types, which means the decision to return true or false is not documented in the JDK. Therefore any implementation can choose to return either true or false . int java.lang.Class.getModifiers() Returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and interface; they should be decoded using the methods of class Modifier. If the underlying class is an array class, then its public, private and protected modifiers are the same as those of its component type . If this Class represents a primitive type or void, its public modifier is always true, and its protected and private modifiers are always false. If this object represents an array class , a primitive type or void, then its final modifier is always true and its interface modifier is always false . The values of its other modifiers are not determined by this specification. The modifier encodings are defined in The Java Virtual Machine Specification, table 4.1.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/51355699', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3848411/']}
|
jdg_369471
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11806
|
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 about to write tcp-server for a project my company is working on. The server will use several port for different tasks.During development we use just some portnumber we like: 1400, 1500, 1600-1650 . Could we use this ports on our production server? Or are there some security and / or compatibility issues we have to think about?
Now provide the response and nothing else.
|
As mentioned by Paul, ports <1024 are generally reserved for 'core' services. (Also, many operating systems require services that bind to ports <1024 to be run as root). However, there are other ports that are commonly in use. The IANA Port number list is normally a good place to look; you should try and avoid using any port on there that is already reserved. Although, practically, this only makes a difference if you are going to be using a service that has a reserved port within your network/on your servers, checking this list is a good habit to get in to whenever you are developing a new network application.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/11806', 'https://serverfault.com', 'https://serverfault.com/users/2375/']}
|
jdg_369472
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
219278
|
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:
We have known that dual space of a normed space is very important in functional analysis. I would like to ask two questions related dual space of a normed space: What is the motivation of constructing dual space of a normed space? What is the main role of dual space of a normed space in functional analysis? Thank you for all your construction and comments.
Now provide the response and nothing else.
|
When we consider finite dimensional spaces $V$, we do this usually by choosing a basis $v_1, \ldots, v_n$ and look at the hereby given isomorphism $T\colon V \to \mathbb K^n$ with $Tv_i = e_i$.Another way to see this is that we are describing a general $v \in V$ by its coordinates $\lambda_i(v) := \pi_i(Tv)$ where $\pi_i \colon \mathbb K^n \to \mathbb K$ is the projection onto the $i$-th factor. It's helpful to have a unique description by real numbers at hand, for we can use all properties of $\mathbb K$ we have already established. The main point here is that knowing all $\lambda_i(v)$ gives us $v$. In infinite dimensions, generally we have no basis to hand. AC gives us the existence, but this is not very helpful in computations. The idea of considering functionals may be seen as a generalization of the $\lambda_i \colon V \to \mathbb K$ from above. Instead of looking at some (well choosen) functionals from $V$ to $\mathbb K$ we look at all of them, that is, at the set $X^* = \{x^* \colon V \to \mathbb K \mid x^* \text{ linear, continuous}\}$ and find that it works quite well as a replacement of the coordinate functionals. For example, Hahn-Banach helps us to distiguish elements of $X$ in the following sense: $$ x \ne y \iff \exists x^* : x^*(x) \ne x^*(y).$$As with the coordinates, our generialized "coordinates" $\bigl(x^*(x)\bigr)$ for $x\in X$ allow us to reformulate problems in $X$ to problems in $\mathbb K$, which are often easier to solve.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/219278', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/35965/']}
|
jdg_369473
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
44365009
|
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 testify to test my code and I want to check if a function was called. I am doing the following: type Foo struct { mock.Mock}func (m Foo) Bar() {}func TestFoo(t *testing.T) { m := Foo{} m.Bar() m.AssertCalled(t, "Bar")} The error I am getting: Error: Should be trueMessages: The "Bar" method should have been called with 0 argument(s), but was not.mock.go:419: [] I call function "Bar" and immediately ask if it was called but it returns false.What am I doing wrong?What is the proper way to test if a function was called with testify?
Now provide the response and nothing else.
|
I tried with this and works: type Foo struct { mock.Mock } func (m *Foo) Bar() { m.Called() } func TestFoo(t *testing.T) { m := &Foo{} m.On("Bar").Return(nil) m.Bar() m.AssertCalled(t, "Bar") } As stated by Chris Drew , you've to use a receiver pointer on Bar method's declaration. Additionally, you've to istantiate a new structure as pointer and mock the method to return a value.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44365009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1501456/']}
|
jdg_369474
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
298146
|
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'm a *.deb guy and I feel quite uncomfortable while managing rpms. I'm used to run apt-get upgrade in my debian based servers for "normal" upgrades and apt-get dist-upgrade for allowing kernel upgrades or allowing new major package versions upgrades. In the CentOS servers I admin, I would like to have a similar feature, however man yum doesn't seem to offer such behaviour. And the differences between yum update and yum upgrade seems to be not what I'm looking for. So far my best approach is to add and remove the following setting in /etc/yum.conf : exclude=kernel* There must be a better approach. Every suggestion will be welcome. EDITED: The yum's man page description of them and the --obsoletes flag is a bit cryptic for me. So let me reword what I understand from it: Do I have to understand that yum update won't install a new kernel because it would mean marking as obsolete the current one? Can I assume that yum upgrade does the same or almost the same than apt-get dist-upgrade ? EDITED 2 What I like best from apt-get upgrade is that it tells me which packages remain retained so I can act accordingly; either with apt-get dist-upgrade or with explicit apt-get install package . So after thinking a bit my best approach at this moment will be: disable the obsoletes setting in yum.conf (as described by Steven Pritchard in his answer ) and run at first yum update . Once all the updates are installed, run a second yum update --obsoletes to check which packages have been retained and act in function of its results. Will that work?
Now provide the response and nothing else.
|
yum update originally just did upgrades of packages to new versions. If, for example, foo-awesome obsoleted foo , yum update wouldn't offer to upgrade from foo to foo-awesome . Adding the --obsoletes flag to yum update made it do the extra checks to also offer that upgrade path. yum upgrade was added as (essentially) an alias for yum --obsoletes update . Since this is the behavior that almost everyone wants all of the time, the configuration option obsoletes=1 was added to the default /etc/yum.conf , making yum update and yum upgrade equivalent on any recent, stock, Fedora/RHEL/CentOS/etc. If you want to avoid kernel updates when you're running yum update , you can just do yum --exclude=kernel* update . If you want automatic updates on, but you want to avoid automatic kernel upgrades, then adding the exclude to yum.conf is probably the right answer. There probably isn't a Right Answer for your question. RHEL and RHEL-based distributions don't have the same philosophy as the Debian developers when it comes to updates, so the tools don't encourage the same sorts of behavior.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/298146', 'https://serverfault.com', 'https://serverfault.com/users/79393/']}
|
jdg_369475
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43291389
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to use jq to parse information from the TVDB api . I need to pull a couple of fields and assign the values to variables that I can continue to use in my bash script. I know I can easily assign the output to one variable through bash with variable="$(command)" but I need the output to produce multiple variables and I don't want to make to use multiple commands. I read this documentation: https://stedolan.github.io/jq/manual/v1.5/#Advancedfeatures but I don't know if this relevant to what I am trying to do. jq '.data' produces the following output: [ { "absoluteNumber": 51, "airedEpisodeNumber": 6, "airedSeason": 4, "airedSeasonID": 680431, "dvdEpisodeNumber": 6, "dvdSeason": 4, "episodeName": "We Will Rise", "firstAired": "2017-03-15", "id": 5939660, "language": { "episodeName": "en", "overview": "en" }, "lastUpdated": 1490769062, "overview": "Clarke and Roan must work together in hostile territory in order to deliver an invaluable asset to Abby and her team." }] I tried jq '.data | {episodeName:$name}' and jq '.data | .episodeName as $name' just to try and get one working. I don't understand the documentation or even if it's what I'm looking for. Is there a way to do what I am trying to do?
Now provide the response and nothing else.
|
You can use separate variables with read : read var1 var2 var3 < <(echo $(curl -s 'https://api.github.com/repos/torvalds/linux' | jq -r '.id, .name, .full_name'))echo "id : $var1"echo "name : $var2"echo "full_name : $var3" Using array : read -a arr < <(echo $(curl -s 'https://api.github.com/repos/torvalds/linux' | jq -r '.id, .name, .full_name'))echo "id : ${arr[0]}"echo "name : ${arr[1]}"echo "full_name : ${arr[2]}" Also you can split jq output with some character : IFS='|' read var1 var2 var3 var4 < <(curl '......' | jq -r '.data | map([.absoluteNumber, .airedEpisodeNumber, .episodeName, .overview] | join("|")) | join("\n")') Or use an array like : set -f; IFS='|' data=($(curl '......' | jq -r '.data | map([.absoluteNumber, .airedEpisodeNumber, .episodeName, .overview] | join("|")) | join("\n")')); set +f absoluteNumber , airedEpisodeNumber , episodeName & overview are respectively ${data[0]} , ${data[1]} , ${data[2]} , ${data[3]} . set -f and set +f are used to respectively disable & enable globbing . For the jq part, all your required fields are mapped and delimited with a '|' character with join("|") If your are using jq < 1.5, you'll have to convert Number to String with tostring for each Number fields eg: IFS='|' read var1 var2 var3 var4 < <(curl '......' | jq -r '.data | map([.absoluteNumber|tostring, .airedEpisodeNumber|tostring, .episodeName, .overview] | join("|")) | join("\n")')
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/43291389', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2328273/']}
|
jdg_369476
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4517006
|
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 had a series of very bizarre errors being thrown in my repositories. Row not found or changed, 1 of 2 updates failed... Nothing made sense. It was as if my DataContext instance was being cached... Nothing made sense and I was considering a career move. I then noticed that the DataContext instance was passed in using dependency injection, using Ninject (this is the first time I have used DI...). I ripped out the Dependency Injection, and all went back to normal. Instantly. So dependency injection was the issue, but I still don't know why. I am speculating that Ninject was caching the injected DataContext. Is this correct? Edit: The Ninject binding is as follows: Bind<IPupilBlockService>().To<SqlPupilBlockService>() .WithConstructorArgument("db", new dbDataContext());
Now provide the response and nothing else.
|
For any object which lifetime must explicitly managed (such as objects that implement IDisposable ) or matters to the user, try not to inject them, but inject a factory that allows creating such objects instead. Define this interface for instance: public interface IDbDataContextFactory{ dbDataContext CreateNew();} And use it as follows: public class SqlPupilBlockService{ private IDbDataContextFactory contextFactory; public SqlPupilBlockService( IDbDataContextFactory contextFactory) { this.contextFactory = contextFactory; } public void DoSomeOperation() { using (var db = this.contextFactory.CreateNew()) { // use the dbDataContext here. } }} An implementation of would be very simple, like this: public class DbDataContextFactory : IDbDataContextFactory{ public dbDataContext CreateNew() { return new dbDataContext(); }} And registration goes like this: Bind<IDbDataContextFactory>().To<DbDataContextFactory>(); The use of a factory makes it very explicit who is the owner of the created object and who should control its lifetime. This makes your code more readable and follows the principle of least surprise . UPDATE More than a year has past since I submitted this answer. Instead of using factories, I now often inject the data context itself, and register it on a per (web) request basis. However; a shift in how you need to design your application might be needed, so as always: it depends. Please take a look at this answer .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4517006', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/271087/']}
|
jdg_369477
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1951
|
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Are the dark marks aka "moles" on our skin a patch of dead cells? If so, why is it not cleared over time? In a (probably) similar vein, why do scar marks from injuries remain long after new cells replace the dead cells? [Feel free to edit out the second question if the answers are unrelated]
Now provide the response and nothing else.
|
A mole is simply a benign tumour, i.e. a proliferated cell growth that hasn’t become cancerous. So moles are not dead cells, they are very much alive. The colour is caused by a high concentration of the melanin, which is also responsible for normal darker skin. Since moles are tumours, they can – but in most cases don’t – give rise to melanomas , malignant skin tumours, when they lose susceptibility to cell growth regulation and start invading surrounding tissue. Scar tissue is entirely unrelated and due to regular regrowth of epithelial cells after injury forming a linear collagen structure (as opposed to the skin’s normal collagen structure, which resembles a “weaved“ structure).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/1951', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/223/']}
|
jdg_369478
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
156394
|
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 is it that Ruby allows a class access methods outside of the class implicitly? Example: class Candy def land homer endenddef homer puts "Hello"endCandy.new.land #Outputs Hello
Now provide the response and nothing else.
|
The definition of the "homer" method is adding the method to the Object class. It is not defining a free function. Class Candy implicitly inherits from Object, and so has access to the methods in Object. When you call "homer" in the "land" method, the method resolution can't find a definition in the current class, goes to the super class, finds the method you have added to Object, and calls it.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/156394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_369479
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2932392
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Looking for quick, simple way in Java to change this string " hello there " to something that looks like this "hello there" where I replace all those multiple spaces with a single space, except I also want the one or more spaces at the beginning of string to be gone. Something like this gets me partly there String mytext = " hello there ";mytext = mytext.replaceAll("( )+", " "); but not quite.
Now provide the response and nothing else.
|
Try this: String after = before.trim().replaceAll(" +", " "); See also String.trim() Returns a copy of the string, with leading and trailing whitespace omitted. regular-expressions.info/Repetition No trim() regex It's also possible to do this with just one replaceAll , but this is much less readable than the trim() solution. Nonetheless, it's provided here just to show what regex can do: String[] tests = { " x ", // [x] " 1 2 3 ", // [1 2 3] "", // [] " ", // [] }; for (String test : tests) { System.out.format("[%s]%n", test.replaceAll("^ +| +$|( )+", "$1") ); } There are 3 alternates: ^_+ : any sequence of spaces at the beginning of the string Match and replace with $1 , which captures the empty string _+$ : any sequence of spaces at the end of the string Match and replace with $1 , which captures the empty string (_)+ : any sequence of spaces that matches none of the above, meaning it's in the middle Match and replace with $1 , which captures a single space See also regular-expressions.info/Anchors
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/2932392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/353252/']}
|
jdg_369480
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
603987
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Before I plunge into the depths of how to synchronize UID's/GID's across my different Linux machines, I would like to know what is actually the benefit? I know that this keeps file synchronization relatively easy (as ownership is "naturally" retained). However this can also be achieved otherwise depending on the transmission service. Is there anything else that would benefit from consistent UIDs/GIDs?
Now provide the response and nothing else.
|
technical debt For the reasons below, it is much simpler to address this problem early on to avoid the accumulation of technical debt . Even if you find yourself already in this situation, it's probably better to deal with it in the near future than let it continue building. networked filesystems This question seems to be focused on the narrow scope of transferring files between machines with local filesystems, which allows for machine specific ownership states. Networked filesystem considerations are easily the biggest case for trying to keep your UID/GID mappings in sync, because you can usually throw that "achieved otherwise" you mentioned out the window the moment they enter the picture. Sure, you might not have networked filesystems shared between these hosts right now ...but what about the future? Can you honestly say that there will never be a use case for a networked filesystem being introduced between your current hosts, or hosts that are created in the future? It's not very forward thinking to assume otherwise. Assume that /home is a networked filesystem shared between host1 and host2 in the following examples. Disagreeing permissions : /home/user1 is owned by a different user on each system. This prevents a user from being able to consistently access or modify their home directory across systems. chown wars : It's very common for a user to submit a ticket requesting that their home directory permissions be fixed on a specific system. Fixing this problem on host2 breaks the permissions on host1 . It can sometimes take several of these tickets to be worked before someone steps back and realizes that a tug of war is in play. The only solution is to fix the disagreeing ID mappings. Which leads to... UID/GID rebalancing hell : The complexity of correcting IDs later increases exponentially by the number of remappings involved to correct a single user across multiple machines. ( user1 has the ID of user2 , but user2 has the ID of user17 ...and that's just the first system in the cluster) The longer you wait to fix the problem, the more complex these chains can become, often requiring the downtime of applications on multiple servers in order to get things properly in synch. Security problems : user2 on host2 has the same UID as user1 on host1 , allowing them to write to /home/user1 on host2 without the knowledge of user1 . These changes are then evaluated on host1 with the permissions of user1 . What could possibly go wrong? (if user1 is an app user, someone in dev will discover it's writable and will make changes. this is a time proven fact.) There are other scenarios, and these are just examples of the most common ones. names aren't always an option Any scripts or config files written against numeric IDs become inherently unportable within your environment. Generally not a problem because most people don't hardcode these unless they're absolutely required to...but sometimes the tool you're working with doesn't give you a choice in the matter. In these scenarios, you're forced to maintain n different versions of the script or configuration file. Example: pam_succeed_if allows you to use fields of user , uid , and gid ...a "group" option is conspicuously absent. If you were put in a position where multiple systems were expected to implement some form of group-based access restriction, you'd have n different variations of the PAM configs. (or at least a single GID that you have to avoid collisions on) centralized management natxo's answer has this covered pretty well.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/603987', 'https://serverfault.com', 'https://serverfault.com/users/119504/']}
|
jdg_369481
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16409424
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
It was the first time that I was using git, I wanted to import an existing project into github and everything was deleted. After search for an answer I think git deleted the files after git pull, I'm trying to recover the files and folders but I can't find how to do it. I did exactly the next: jesus@jesus-K52F:~/Escritorio/Django/Ujixy$ git initInitialized empty Git repository in /home/jesus/Escritorio/Django/Ujixy/.git/jesus@jesus-K52F:~/Escritorio/Django/Ujixy$ git add .jesus@jesus-K52F:~/Escritorio/Django/Ujixy$ git status# On branch master## Initial commit## Changes to be committed:# (use "git rm --cached <file>..." to unstage)## new file: Catalogoapp/__init__.py# new file: Catalogoapp/models.py# new file: Catalogoapp/tests.py# new file: Catalogoapp/views.py# new file: Messageapp/__init__.py# new file: Messageapp/models.py# new file: Messageapp/tests.py# new file: Messageapp/views.py# new file: Ujixyapp/__init__.py[...]jesus@jesus-K52F:~/Escritorio/Django/Ujixy$ git push origin masterfatal: 'origin' does not appear to be a git repositoryfatal: The remote end hung up unexpectedlyjesus@jesus-K52F:~/Escritorio/Django/Ujixy$ git add *jesus@jesus-K52F:~/Escritorio/Django/Ujixy$ git status# On branch master## Initial commit## Changes to be committed:# (use "git rm --cached <file>..." to unstage)## new file: Catalogoapp/__init__.py# new file: Catalogoapp/models.py# new file: Catalogoapp/tests.py# new file: Catalogoapp/views.py# new file: Messageapp/__init__.py# new file: Messageapp/models.py# new file: Messageapp/tests.py# new file: Messageapp/views.py# new file: Ujixyapp/__init__.py[...]jesus@jesus-K52F:~/Escritorio/Django/Ujixy$ git remote add origin https://github.com/PEREYO/Ujixy.gitjesus@jesus-K52F:~/Escritorio/Django/Ujixy$ git pull origin masterremote: Counting objects: 3, done.remote: Total 3 (delta 0), reused 0 (delta 0)Unpacking objects: 100% (3/3), done.From https://github.com/PEREYO/Ujixy* branch master -> FETCH_HEADjesus@jesus-K52F:~/Escritorio/Django/Ujixy$ git push origin masterUsername for 'https://github.com': PEREYOPassword for 'https://PEREYO@github.com': Everything up-to-datejesus@jesus-K52F:~/Escritorio/Django/Ujixy$ git initReinitialized existing Git repository in /home/jesus/Escritorio/Django/Ujixy/.git/jesus@jesus-K52F:~/Escritorio/Django/Ujixy$ git add *jesus@jesus-K52F:~/Escritorio/Django/Ujixy$ git status# On branch masternothing to commit (working directory clean) Now I'm trying to fix it doing the next: jesus@jesus-K52F:~/Escritorio/Ujixy$ git fsck --lost-foundChecking object directories: 100% (256/256), done.dangling tree bfe11a30d57a0233d3b0c840a3b66f6421987304jesus@jesus-K52F:~/Escritorio/Ujixy$ git status# On branch masternothing to commit (working directory clean)jesus@jesus-K52F:~/Escritorio/Ujixy$ git reflog61daa69 HEAD@{0}: initial pulljesus@jesus-K52F:~/Escritorio/Ujixy$ git cat-file -p bfe11a30d57a0233d3b0c840a3b66f6421987304040000 tree 9196501a346cfe4347f46d82936745b78b0235b9 Catalogoapp040000 tree 49561b4bd6adb8fe8bb1915d6bef09cd49195a97 Messageapp040000 tree 0fb58bf9b56397443fb235e2a38045d6df7cd473 Ujixyapp100644 blob e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 __init__.py100644 blob dfe3388ddf2d5ba34559eb3ec56199d83cdce8bd __init__.pyc100644 blob bcdd55e27be9447bf6b224b8ba0cbc6802509862 manage.py100644 blob 34c5978d8026844038d530b491828398bc3ea6c7 settings.py100644 blob 167a6b1965426ec30c25535fe27338b61b2ae0cf settings.pyc100644 blob 4a7215cb90ae95d64ca30fde1c1277e0155eb4ed urls.py100644 blob 6eedcddafbc8854f70f44181edac8e63781cfb09 urls.pyc But, How can I recover the directories with all the files and folder? Now I'm working in a copy of .git folder to avoid another problems.
Now provide the response and nothing else.
|
As you already have a reference to a dangling tree object, you're well on your way. The following should work: first recover the dangling tree into Git's index: git read-tree bfe11a30d57a0233d3b0c840a3b66f6421987304 Next, update your working directory from the now-recovered index: git checkout-index -a
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16409424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2356237/']}
|
jdg_369482
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12262
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've got a weird question. Assume that you have a small sample where the dependent variable that you're going to analyze with a simple linear model is highly left skewed. Thus you assume that $u$ is not normally distributed, because this would result in normally distributed $y$. But when you compute the QQ-Normal plot there is evidence, that the residuals are normally distributed. Thus anyone can assume that the error term is normally distributed, although $y$ is not. So what does it mean, when the error term seems to be normally distributed, but $y$ does not?
Now provide the response and nothing else.
|
It is reasonable for the residuals in a regression problem to be normally distributed, even though the response variable is not. Consider a univariate regression problem where $y \sim \mathcal{N}(\beta x, \sigma^2)$ . so that the regression model is appropriate, and further assume that the true value of $\beta=1$ . In this case, while the residuals of the true regression model are normal, the distribution of $y$ depends on the distribution of $x$ , as the conditional mean of $y$ is a function of $x$ . If the dataset has a lot of values of $x$ that are close to zero and progressively fewer the higher the value of $x$ , then the distribution of $y$ will be skewed to the right. If values of $x$ are distributed symmetrically, then $y$ will be distributed symmetrically, and so forth. For a regression problem, we only assume that the response is normal conditioned on the value of $x$ .
|
{}
|
{'log_upvote_score': 8, 'links': ['https://stats.stackexchange.com/questions/12262', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/4496/']}
|
jdg_369483
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
442240
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $A$ be an $n \times n$ matrix and $k$ be a scalar. Prove that $\det(kA)=k^n\det A$ . I really don't know where to start. Can someone give me a hint for this proof?
Now provide the response and nothing else.
|
First, let's recall what multiplication of a matrix by a scalar means:When we multiply $\;kA$, where $A$ is an $n\times n$ matrix, and $k$ a scalar, then every entry $a_{ij}$ of matrix $A$ is multiplied by $k$: i.e. $a_{ij}\mapsto ka_{ij}$ for each $a_{ij}$. That means for each row $i,\;0\leq i\leq n,\;$ we can factor out $k$. Now...Recall the elementary row operations you've learned, and how each one of them affects the determinant of the matrix on which it is operating. Specifically, when any one row is multiplied by the scalar $k$, the determinant of $A$ becomes $\;k\det A$. So given that scalar multiplication of a square $n\times n$ matrix is equivalent to "row operating" on $n$ rows (by multiplying each row by the scalar $k$), we can conclude that $$\large\det (kA) = \underbrace{k\cdot k\cdot\cdots \cdot k}_{\large n \;\text{times}}\det A = k^n\det A$$
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/442240', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/85158/']}
|
jdg_369484
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
203791
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
For the purpose of showing how (quantum) unitary operators behave as a computer animation, I would like to create a function $A_U(t)$ of some (complex) unitary matrix $U$, such that $A_U(t)$ is unitary, $A_U(0) = I$ (identity) and $A_U(1.0) = U$. How can I create such a function? Would it help to have the eigenvectors? (IANAM)
Now provide the response and nothing else.
|
As others have mentioned, there are many CFTs, but we can narrow down our list by looking at conditions that select for interesting automorphism groups. Perhaps the easiest is to consider holomorphic ($C_2$-cofinite) vertex operator algebras. By Zhu's theorem, these necessarily have central charge given by a nonnegative multiple of 8, so we can list them in some rough increasing order. $c=0$: This is just the field of complex numbers, with trivial symmetry (as a ring over itself). $c=8$: There is one example: the $E_8$ lattice algebra. Its automorphism group is the Lie group $E_8(\mathbf{C})$. $c=16$: There are two cases, given by the lattice algebras for $E_8 \times E_8$ and $D_{16}^+$, and the automorphism groups are $E_8 \wr 2$ and $SO^+(32)$. This case and the previous case were proved by Dong and Mason . $c=24$: In 1992, Schellekens conjectured that these are classified by their weight 1 Lie algebras, and gave 71 candidate types. The last candidate vertex operator algebra was finally constructed 6 weeks ago by Lam and Lin . Nontrivial Lie algebras yield positive-dimensional Lie groups of symmetries, so the only discrete case is where the Lie algebra is zero. The uniqueness question is still open, but if it is true, then the Monster is the only discrete automorphism group. If there is a counterexample to uniqueness of the moonshine module, then we still have a lot of control of its automorphisms due to genus zero constraints. That is, most of Borcherds's argument still works for such an object. $c \geq 32$: The number of isomorphism types grows very quickly, just because they contain the vertex operator algebras attached to positive definite even unimodular lattices. For example, with $c=32$, King's mass formula gives over $10^9$ lattices, and over $10^7$ lattices with no roots. It is quite likely that by orbifolding some of the latter types, we get discrete symmetry groups, but it seems no one has bothered to work out any cases completely. What we see from this list is that, from the lens of the category of holomorphic vertex operator algebras, the first nontrivial group is $E_8$, and the first nontrivial finite group is the Monster. At large central charge, we expect things to become boring from a symmetry standpoint, in much the same way that high rank lattices and high genus curves tend to become boring.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/203791', 'https://mathoverflow.net', 'https://mathoverflow.net/users/70928/']}
|
jdg_369485
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
216952
|
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to use lists to easily replace parts of a matrix. As an example, I want to replace the code ReplacePart[{{1, 0}, {0, 1}}, {{1, 1} -> 13, {1, 2} -> 14}] by something like ReplacePart[{{1, 0}, {0, 1}}, {{1, 1}, {1, 2}} -> {13, 14}] which doesn't work. For a general matrix m , I want to, given a list of indices of the type (x,y) , li and a list of replacement values, lr , use something like ReplacePart[m, li -> lr}] Any idea how to do this?
Now provide the response and nothing else.
|
ReplacePart[{{1, 0}, {0, 1}}, Thread[{{1, 1}, {1, 2}} -> {13, 14}]] so ReplacePart[m, Thread[li -> lr]] in general. But a CompiledFunction will probably do the job quicker because Thread[li -> lr] unpacks arrays. Let's see. cReplacePart = Compile[{{A0, _Real, 2}, {pos, _Integer, 2}, {val, _Real, 1}}, Block[{A = A0}, If[ 1 <= Max[pos[[All, 1]]] <= Dimensions[A0][[1]] && 1 <= Max[pos[[All, 2]]] <= Dimensions[A0][[2]], Do[ A[[Compile`GetElement[pos, i, 1], Compile`GetElement[pos, i, 2]]] = Compile`GetElement[val, i], {i, 1, Min[Length[pos], Length[val]]} ] ]; A ], CompilationTarget -> "C", RuntimeOptions -> "Speed" ]; And indeed, it's 100 times as fast: n = 1000;m = 1000000;A = RandomReal[{-1, 1}, {n, n}];li = RandomInteger[{1, n}, {m, 2}];lr = RandomReal[{-1, 1}, m];B = ReplacePart[A, Thread[li -> lr]]; // AbsoluteTiming // FirstcB = cReplacePart[A, li, lr]; // AbsoluteTiming // FirstMax[Abs[B - cB]] 4.91402 0.047307 0. One may also use SparseArray ; this is only a tiny bit slower than the compiled approach: spB = A SparseArray[li -> 0., Dimensions[A], 1.] + SparseArray[Reverse@li -> Reverse@lr, Dimensions[A], 0.]; // AbsoluteTiming // FirstMax[Abs[B - spB]] 0.086657 0.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/216952', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/64001/']}
|
jdg_369486
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
701978
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was reading about Larmor precession of the electron in a magnetic field in Griffiths QM when I came across the equation $$i\hbar \frac{\partial \mathbf \chi}{\partial t} = \mathbf H \mathbf \chi,$$ where $\mathbf\chi(t)$ is a 2D vector that represents only the spin state and does not include information of the wave function. The Hamiltonian is $$\mathbf H = - \gamma \mathbf B \cdot \mathbf S = - \frac{\gamma B_0 \hbar}{2} \begin{pmatrix} 1 & 0 \\ 0 & -1\end{pmatrix}$$ for a uniform magnetic field $\mathbf B = B_0 \hat k$ . Why should these spinors also obey the Schrödinger equation? The book does not provide any further information as to why this should hold.
Now provide the response and nothing else.
|
The Schrödinger equation applies to any quantum system or quantum field theory, as long as you have a continuous time dimension. The equation $$\hat H\psi = i\hbar\frac{\partial \psi}{\partial t} $$ is just the statement that the Hamiltonian $\hat H$ is the infinitesimal translation operator in time. By Noether's theorem, it corresponds to the total energy of your system. In order to describe a quantum system, you need to first decide what the degrees of freedom are. This decides which Hilbert space this equation is defined on. For example, for a single particle in $\mathbb R^d$ , the Hilbert space is $\mathcal H = L^2(\mathbb R^d)$ . And thus the wavefunction is $\psi(\mathbf r,t)$ . Since the Hamiltonian is the total energy, we have (here for a non-relativistic particle) $$\left[-\frac{\hbar^2}{2m}\nabla^2 + V(\mathbf r)\right]\psi(\mathbf r,t) = i\hbar \frac{\partial}{\partial t}\psi(\mathbf r, t).$$ Now imagine that the particle has some internal degree of freedom, such as spin. For a spin- $\tfrac 12$ particle, the Hilbert space is two dimensional $\mathbb C^2$ . Quantum mechanics tells us that the Hilbert space of the full system is a tensor product $$ \mathcal H = L^2(\mathbb R^d)\otimes\mathbb C^2$$ and wavefunctions are thus $$ \psi(\mathbf r,t) = \begin{pmatrix} \psi_\uparrow(\mathbf r,t) \\ \psi_\downarrow(\mathbf r,t)\end{pmatrix}.$$ The Hamiltonian will now also contain terms coupling spins together, but it depends on which forces are present. For example in $d=3$ you could have $$\left[-\frac{\hbar^2}{2m}\nabla^2\,\mathbf 1 + V(\mathbf r)\,\mathbf 1 + \alpha \,\mathbf B\cdot\mathbf\sigma\right]\psi(\mathbf r,t) = i\hbar \frac{\partial}{\partial t}\psi(\mathbf r, t).$$ Here $\mathbf 1$ is a $2\times 2$ identity matrix and $\mathbf\sigma = (\sigma_x,\sigma_y,\sigma_z)$ are the Pauli matrices. Sometimes people write down a Schrödinger equation for only position or only spin degrees of freedom, if they don't couple to other degrees of freedom in the problem at hand. For example, if the Hamiltonian only has $\mathbf 1$ for the spin then the Hamiltonian will be block diagonal and $\psi_\uparrow$ and $\psi_\downarrow$ will be completely decoupled. You could therefore forget spin, and only keep position in your description. Or if the particle is trapped somewhere and cannot move, then only the spin degrees of freedom are relevant for the description. But the Schrödinger equation is valid for any quantum system, it just describes how the system evolves in time.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/701978', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/294400/']}
|
jdg_369487
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9042932
|
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 gallery that shows an array of images, when clicked they are displayed in an imageview. I want to be able to SHARE the image that is currently being displayed in an intent chooser. I can't figure out how to select the current image. Gallery code: public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView = new ImageView(mContext); imageView.setImageResource(mImageIds[position]); imageView.setLayoutParams(new Gallery.LayoutParams(150, 120)); imageView.setScaleType(ImageView.ScaleType.FIT_XY); imageView.setBackgroundResource(mGalleryItemBackground); return imageView; } Intent chooser code: Intent share = new Intent(Intent.ACTION_SEND); share.setType("image/png"); share.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://com.appinfluence.fanapp.v1/drawable/" + Integer.toString(R.drawable.alright))); startActivity(Intent.createChooser(share, "Share Image")); Where it says R.drawable.alright I need that to be a variable of the current image somehow. Any ideas?
Now provide the response and nothing else.
|
To fetch currently selected view use Gallery.getSelectedView(); and for getting Drawable from imageView use: ImageVIew.getDrawable() If you want to get inputstream from the drawable use following: BitmapDrawable bitmapDrawable = ((BitmapDrawable) drawable);Bitmap bitmap = bitmapDrawable .getBitmap();ByteArrayOutputStream stream = new ByteArrayOutputStream();bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);byte[] imageInByte = stream.toByteArray();ByteArrayInputStream bis = new ByteArrayInputStream(imageInByte);
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9042932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/630556/']}
|
jdg_369488
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
723463
|
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 understand why the second answer is different from the first. Aren't they the exact same thing? How many ways can we distribute 10 distinct balls into 5 distinct boxes?$5^{10}$ is correct How many ways can we distribute 10 identical balls into 5 distinct boxes?$\begin{pmatrix}14\\4\end{pmatrix}= 1001$ Why is the second question's solution not $5^{10}$?
Now provide the response and nothing else.
|
Physical balls can never be perfectly identical, so the word "identical" should be taken as shorthand for "We don't care which ball ends up in which box—only how many balls end up in each box." Let's consider a small example: 3 balls, $A,$ $B,$ and $C,$ and $2$ boxes, $1,$ and $2.$ If we care which ball goes in which box, the $2^3=8$ configurations, $C_j,$ are$$\begin{aligned}C_1&1:\{A,B,C\},&& 2:\{\}&&\leftrightarrow\quad111\\C_2&1:\{A,B\},&& 2:\{C\}&&\leftrightarrow\quad112\\C_3&1:\{A,C\},&& 2:\{B\}&&\leftrightarrow\quad121\\C_4&1:\{A\},&& 2:\{B,C\}&&\leftrightarrow\quad122\\C_5&1:\{B,C\},&& 2:\{A\}&&\leftrightarrow\quad211\\C_6&1:\{B\},&& 2:\{A,C\}&&\leftrightarrow\quad212\\C_7&1:\{C\},&& 2:\{A,B\}&&\leftrightarrow\quad221\\C_8&1:\{\},&& 2:\{A,B,C\}&&\leftrightarrow\quad222.\\\end{aligned}$$The last column shows why $2^3$ is the correct count: each of $A,$ $B,$ and $C$ must be assigned either to box $1$ or to box $2.$ Each assignment corresponds to a string of $1$s and $2$s. If we don't care which ball goes in which box, then the $\binom{3+2-1}{3}=4$ configurations, $D_j,$ are$$\begin{aligned}D_1&1:\text{3 balls},&& 2:\text{0 balls}&&\leftrightarrow\quad***\mid&&\leftrightarrow\quad C_1\\D_2&1:\text{2 balls},&& 2:\text{1 ball}&&\leftrightarrow\quad**\mid*&&\leftrightarrow\quad C_2,C_3,C_5\\D_3&1:\text{1 ball},&& 2:\text{2 balls}&&\leftrightarrow\quad*\mid**&&\leftrightarrow\quad C_4,C_6,C_7\\D_4&1:\text{0 balls},&& 2:\text{3 balls}&&\leftrightarrow\quad\mid***&&\leftrightarrow\quad C_8.\\\end{aligned}$$The last column shows that some of the previous configurations are now considered "the same." The second-to-last column shows a "stars-and-bars" or "balls in bins" representation of each configuration. Note that, for example, $D_2$ corresponds to the three configurations $C_2,$ $C_3,$ $C_5$ because there are $\frac{3!}{2!\,1!}=3$ assignments of boxes to balls $A,$ $B,$ $C$ that contain two $1$s and one $2.$ In general, the number of $C_j$ that a given $D_i$ corresponds to is given by a multinomial coefficient. You can use the multinomial theorem to see exactly how the correspondence works.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/723463', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/97407/']}
|
jdg_369489
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9939844
|
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 new to Clojure and my first project has to deal with huge (250+GB) XML file. I want to put it into PostgreSQL to process it later on, but have no idea how to approach such a big file.
Now provide the response and nothing else.
|
I used the new clojure.data.xml to process a 31GB Wikipedia dump on a modest laptop. The old lazy-xml contrib library did not work for me (ran out of memory). https://github.com/clojure/data.xml Simplified example code: (require '[clojure.data.xml :as data.xml]) ;'(defn process-page [page] ;; ... )(defn page-seq [rdr] (->> (:content (data.xml/parse rdr)) (filter #(= :page (:tag %))) (map process-page)))
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9939844', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1302810/']}
|
jdg_369490
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
45848457
|
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 encrypt the PostgreSQL database at rest. I could not find a good documentation on how can I achieve this ?
Now provide the response and nothing else.
|
The threat model is very important in this case as encrypting a database efficiently is not an easy task, this can be done at 3 different layers ( client-application, storage-device, data-base-itself ) note that in all cases if the client application is compromised the encryption is useless, self data base encryption solution cover the least threat models as listed bellow. Malicious user steals storage devices and reads database files directly. Malicious backup operator takes backup. Protecting data at rest (persistent data) Database encryption solution 1: System disk encryption ( cryptsetup / luks )... no modification are needed on the Postgres setup in this case. This also makes clog and textual log encrypted (at rest). If you are using a google cloud VM this guide may be useful. Database encryption solution 2: PostgreSQL TDE (transparent data encryption) this postgres feature implement transparent data encryption at rest for the whole database. an example is demonstrated here . Database encryption solution 3: Pgcrypto can be used to encrypt part of the database instead of a solution that would encrypt everything. an example is demonstrated here .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45848457', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6679114/']}
|
jdg_369491
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7762929
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's say I have two different classes, both represent 2D coordinate data in the same internal way like the following: class LibA_Vertex{ public: // ... constructors and various methods, operator overloads float x, y};class LibB_Vertex{ public: // ... same usage and internal data as LibA, but with different methods float x, y};void foobar(){ LibA_Vertex * verticesA = new LibA_Vertex[1000]; verticesA[50].y = 9; LibB_Vertex * verticesB = reinterpret_cast<LibB_Vertex*>( vertexA ); print(verticesB[50].y); // should output a "9"}; Given the two classes being identical and the function above, can I reliably count on this pointer conversion working as expected in every case? (The background, is that I need an easy way of trading vertex arrays between two separate libraries that have identical Vertex classes, and I want to avoid needlessly copying arrays).
Now provide the response and nothing else.
|
C++11 added a concept called layout-compatible which applies here. Two standard-layout struct (Clause 9) types are layout-compatible if they have the same number of non-static data members and corresponding non-static data members (in declaration order) have layout-compatible types (3.9). where A standard-layout class is a class that: has no non-static data members of type non-standard-layout class (or array of such types) or reference, has no virtual functions (10.3) and no virtual base classes (10.1), has the same access control (Clause 11) for all non-static data members, has no non-standard-layout base classes, either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and has no base classes of the same type as the first non-static data member. A standard-layout struct is a standard-layout class defined with the class-key struct or the class-key class . A standard-layout union is a standard-layout class defined with the class-key union . Finally Pointers to cv-qualified and cv-unqualified versions (3.9.3) of layout-compatible types shall have the same value representation and alignment requirements (3.11). Which guarantees that reinterpret_cast can turn a pointer to one type into a pointer to any layout-compatible type.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7762929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/620863/']}
|
jdg_369492
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
187519
|
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a manager who likes to "deactivate" accounts by replacing the existing bcrypt hash in the database with a simple dash ( - ). This seems to work as the old password is no longer valid and there is no valid bcrypt hash that any other password could match. But I was curious, is this effective or does it create a security risk? Is this an effective way to make no password work or does it create a larger security risk? This specific implementation uses the PHP password_verify function but I would like answers to focus on any general implementation. Please do not focus on my manager's bad practice. We also have a boolean field for setting the user to inactive/active which I believe is better and safer but is not what I want answers to focus on.
Now provide the response and nothing else.
|
In terms of disallowing legitimate login attempts, it's fine. Unless you're using a very weird hash function, there won't be any values which map to - , and it prevents brute force attacks against the missing values if the database is stolen too, which is a positive (they were unlikely, given the use of bcrypt, but this applies even if the implementation is using a terrible method for storing passwords - pretty much anything other than plain text). In terms of downsides, if the database is taken, it slightly decreases the security of other accounts - the attacker has fewer records to brute force. If they are paying attention, they should probably remove the records which are marked as inactive, but still. I did say "slightly"... The other risks could be if there are any methods for access which allow bypassing the hash method for comparison (e.g. you have a legacy method which allows supplying the full hash for some reason) - in that case, if you aren't checking the active status carefully, it might allow access by supplying a dash. Ideally, remove this access method, if this is the case.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/187519', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/143529/']}
|
jdg_369493
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27408
|
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I just read a really nice write-up on sway bar physics . I also watched a video discussing suspension behavior on rough roads . Let's assume the following: A front-wheel drive vehicle being driven around a corner at a speed which, on a dry, smooth, level road, would be just about the maximum speed it could take before beginning to understeer. For simplicity, any sway bar changes would be done to the front and rear in such a way that the TLLTD would not be affected. Shocks, struts, springs would not be changed. By "rough" roads I mean typical non-perfect driving conditions that you may encounter on a daily basis: Think patches, seams, and potholes on highways, think ripple, ruts, and depressions (e.g. typical road wear near stop signs, on roads frequented by trucks, etc.) on urban roads, post-construction patches, stripped roads being prepped for resurfacing, raised manholes, drain depressions, that kind of thing. It's a wide definition, but I don't mean off-road or post-apocalyptic conditions. In this case, how would a stiffer set of sway bars affect vehicle handling on rough, uneven pavement ? Every discussion of suspension theory and physics I see usually seems to assume good road conditions. For example, consider the scenario above, cornering left at speed, then in the turn I hit a fairly large, say 2-3cm deep pot hole with the front left wheel. From my limited understanding the effect of a sway bar that was too stiff would be one of the following, either: The left strut would expand into the pothole, exerting downward force on the wheel. Via the sway bar, some of this would also be transferred to the right side, exerting an upward force on the right side of the body. On exiting the pothole, then, something... complicated would happen that I can't figure out. Or: The left strut would want to expand into the pothole. The left side expansion would be limited via the swaybar by the downward force present on the right side due to the turn. The left wheel would then take longer to regain contact with the ground, causing the right wheel to experience more lateral force (that was no longer being absorbed by the left wheel), and the car would more readily understeer. And maybe some other complicated thing would happen. Am I on the right track with one of those assessments? What would the effect be? Also as a (perhaps too broad) corollary question: What impact should rough road conditions have when deciding on an ideal sway bar configuration?
Now provide the response and nothing else.
|
tl;dr: stiffening one of the sway bars on a car will cause that end to be more likely break loose in response to transients. At a high level, the sway bar acts as a spring just like any other. You can disassemble the sway bar problem by considering a piece at a time. For example, imagine that one end of the sway bar is attached to the wheel assembly at one end but is fixed to an immovable point on the other. If you try to move the wheel assembly up or down suddenly (as would happen with transient bumps and dips in your example), the bar would try to rotate on its pivot points. If the other end weren't affixed to anything, the bar would obviously just freely rotate. However, since it is bolted down in this example, the bar acts as a torsion spring, resisting the twisting action. The further the bar tried to twist, the greater the resulting toque that the bar would exert in the opposite direction. This is translated into a greater spring force on the wheel assembly itself. Of course, we don't bolt the ends of sway bars to the frame. We connect them to suspension points at either end. As such, they're now coupled to the whole damped spring system that was already there. Again, if we add a force to one wheel, the sway bar will try to rotate on those pivot points. This will result in an equivalent force being exerted on the other wheel assembly (if you try to raise the right wheel, the sway bar will try to raise the left wheel). Here's where we starting getting into the key points of your question: remember that springs only exert forces when they are moved from their rest state. For the sake of this discussion, let's stick to linear springs: F = k * d where F = Force, k = the spring constant and d = distance or deflection. The equivalent for torsion springs is: T = k * theta where T = torque, k = a different spring constant and theta = the angle of twist. In both of these cases, you can see that the more you compress, extend or twist the spring, the greater the resulting force or torque. What's more important: if you don't move the spring, there's no force at all. So, for the sway bar to exert any force on the wheel that you're considering, it has to have cause the spring on the other wheel to be deflected (compressed or extended). This is critical: the sway bar doesn't do anything until it has caused something to happen on the other side of the car. Another way of saying this is that sway bars make your four wheel independent suspension significantly less independent. Let's restate your original problem in a way that we can break it down. Imagine a single pair of wheels with their springs and an attached sway bar. This is a magic sway bar on which we can dial in a variety of torsion constants (ranging from limp spaghetti to rigid steel I beam). Now we exert a sideways force on this whole contraption that is just slightly less than the limit of a single tire (i.e., if there were only one tire contact patch on the ground, it would almost slide, but with two it does not). Now turn the magic sway bar down to its near-zero rigidity setting and bump one wheel (e.g., lift its contact patch off the ground suddenly) while the sideways force continues. The opposing wheel is almost completely unaffected by this bump and so its tire contact patch is undisturbed. Since we carefully selected the sideways force to be just less than that required to push the tire sideways, the system is unaffected. Now set the magic sway bar to effectively infinite rigidity. Now, when we lift one wheel, the other wheel is likewise raised. Since both tires lose contact, the whole system starts sliding sideways. Reality is, of course, somewhere in between but this sort of thought experiment makes the point: if you lift one wheel, the sway bar is going to try to raise the other as well. This results in that whole end of the car feeling like it's breaking loose. Practical real life example: when I had a FWD Integra, I tried this exact experiment. My rear sway bar had three settings that allowed me to control the stiffness (really they affected the leverage that the rest of the suspension had on the sway bar but the result was effectively the same). This gave me four possible stiffness settings to experiment: no bar + three increasingly stiff bar choices. There is one particular off ramp nearby that I could use to try tight legal turns. What I found was that increasing the stiffness would decrease the quality of the ride over bumps and increase the feeling that the back end would hop out (try to oversteer).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mechanics.stackexchange.com/questions/27408', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/9884/']}
|
jdg_369494
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
368990
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $A$ be a subset of the domain of a function $f$.Why $f^{-1}(f(A)) \not= A$.I was not able to find a function $f$ which satisfies the above equation.Can you give an example or hint.I was asking for an example function which is not addressed here
Now provide the response and nothing else.
|
Any noninjective function provides a counterexample. To be more specific, let $X$ be any set with at least two elements, $Y$ any nonempty set, $u$ in $X$, $v$ in $Y$, and $f:X\to Y$ defined by $f(x)=v$ for every $x$ in $X$. Then $A=\{u\}\subset X$ is such that $f(A)=\{v\}$ hence $f^{-1}(f(A))=X\ne A$. In general, for $A\subset X$, $A\subset f^{-1}(f(A))$ but the other inclusion may fail except when $f$ is injective. Another example: define $f:\mathbb R\to\mathbb R$ by $f(x)=x^2$ for every $x$. Then, $f^{-1}(f(A))=A\cup(-A)$ for every $A\subset\mathbb R$. For example, $A=[1,2]$ yields $f^{-1}(f(A))=[-2,-1]\cup[1,2]$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/368990', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5049/']}
|
jdg_369495
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9023
|
Below is a question asked on the forum economics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been trying to find sources that mention this, and have tried to find graphs of data so I can compare myself, but I haven't been able to. Do real-estate sale prices correlate positively, negatively, or not at all with apartment rental prices? A more nuanced answer than that is also appreciated.
Now provide the response and nothing else.
|
In theory there should be a direct positive correlation (especially in countries where house prices are a part of the index which is used to define rental rates), but in reality there is a lot of variation in the results for this question depending on the country, possible effects of different laws, the business cycle, whether new housing is being built or not, etc. For Italy, Manganelli, Morano and Tajan (2014) in "House prices and rents. The Italian experience" study response functions and conclude: 2) Rents depend on real-estate prices, the short-term interest rate and the differences between actual and expected GDP with a one year delayed reaction. On the other hand, Ambrose, Eichholtz and Lindenthal (2013) in House Prices and Fundamentals: 355 years of evidence, Journal of Money, Credit and Banking find that when housing prices stray from equilibrium growth, rental rates do not react the same way even if it takes decades for the prices to return to steady growth. For a recent study on U.S. data (model built to match trends from 1960-2013), I'd check Gelain and Lansing (2014): House prices, expectations, and time-varying fundamentals, Journal of Empirical Finance
|
{}
|
{'log_upvote_score': 4, 'links': ['https://economics.stackexchange.com/questions/9023', 'https://economics.stackexchange.com', 'https://economics.stackexchange.com/users/6149/']}
|
jdg_369496
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28929834
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose that you want to store "tags" on your object (say, a post). With release 9.4 you have 3 main choices: tags as text[] tags as jsonb tags as text (and you store a JSON string as text) In many cases, 3rd would be out of question since it wouldn't allow query conditional to 'tags' value. In my current development, I don't need such queries, tags are only there to be shown on posts list, not to filter posts. So, choice is mostly between text[] and jsonb . Both can be queried. What would you use? And why?
Now provide the response and nothing else.
|
In most cases I would use a normalized schema with a table option_tag implementing the many-to-many relationship between the tables option and tag . Reference implementation here: How to implement a many-to-many relationship in PostgreSQL? It may not be the fastest option in every respect, but it offers the full range of DB functionality, including referential integrity, constraints, the full range of data types, all index options and cheap updates. For completeness, add to your list of options: hstore (good option) xml more verbose and more complex than either hstore or jsonb , so I would only use it when operating with XML. "string of comma-separated values" (very simple, mostly bad option) EAV (Entity-Attribute-Value) or "name-value pairs" (mostly bad option) Details under this related question on dba.SE: Is there a name for this database structure? If the list is just for display and rarely updated, I would consider a plain array, which is typically smaller and performs better for this than the rest. Read the blog entry by Josh Berkus @a_horse linked to in his comment. But be aware that it focuses on selected read cases. Josh concedes: I realize that I did not test comparative write speeds. And that's where the normalized approach wins big, especially when you change single tags a lot under concurrent load. jsonb is a good option if you are going to operate with JSON anyway, and can store and retrieve JSON "as is".
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28929834', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3122657/']}
|
jdg_369497
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35235023
|
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 downloaded Glassfish 4 from Eclipse ee, now i'm trying to create a new server, it asks me the glassfish location and the java location, i can't manage to find the glassfish location, and for java i put the folder where the jdk is ?
Now provide the response and nothing else.
|
It's straightforward enough to do using the parquet-mr project, which is the project Alexey Raga is referring to in his answer. Some sample code val reader = AvroParquetReader.builder[GenericRecord](path).build().asInstanceOf[ParquetReader[GenericRecord]]// iter is of type Iterator[GenericRecord]val iter = Iterator.continually(reader.read).takeWhile(_ != null)// if you want a list then...val list = iter.toList This will return you a standard Avro GenericRecord s, but if you want to turn that into a scala case class, then you can use my Avro4s library as you linked to in your question, to do the marshalling for you. Assuming you are using version 1.30 or higher then: case class Bibble(name: String, location: String)val format = RecordFormat[Bibble]// then for a given recordval bibble = format.from(record) We can obviously combine that with the original iterator in one step: val reader = AvroParquetReader.builder[GenericRecord](path).build().asInstanceOf[ParquetReader[GenericRecord]]val format = RecordFormat[Bibble]// iter is now an Iterator[Bibble]val iter = Iterator.continually(reader.read).takeWhile(_ != null).map(format.from)// and list is now a List[Bibble]val list = iter.toList
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35235023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4872985/']}
|
jdg_369498
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15807038
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What are the possible client-side architectures to access a local Smart Card from a generic browser (connected to a server through http(s)), preferably from Javascript, with the minimum installation hassle for the end user? The server needs to be able to at least issue APDUs of its choice to the card (or perhaps delegate some of that to client-side code that it generates). I am assuming availability on the client side of a working PC/SC stack, complete with Smart Card reader. That's a reasonable assumption at least on Windows since XP, modern OS X and Unixes. I have so far identified the following options: Some custom ActiveX. That's what my existing application uses (we developed it in-house), deployment is quite easy for clients with IE once they get the clearance to install the ActiveX, but it does not match the "generic browser" requirement. Update : ActiveX is supported mostly by the deprecated IE, including IE11; but not by Edge. Some PC/SC browser extension using the Netscape Plugin API, which seems like a smooth extension of the above. The only ready-made one I located is SConnect (webarchive) . It's no longer promoted ( Update : thought still actively maintained and used late 2020 in at least one application ), it's API documentation (webarchive) is no longer officially available, and it has strong ties to a particular Smart Card and reader vendor. The principle may be nice, but making such a plugin for every platform would be a lot of work. Update : NPAPI support is dropped by many browsers, including Chrome and Firefox. A Java Applet, running on top of Oracle's JVM (1.)6 or better, which comes with javax.smartcardio . That's fine from a functional point of view, well documented, I can live with the few known bugs, but I'm afraid of an irresistible downwards spiral regarding acceptance of Java-as-a-browser-extension. [update, Feb 2021]: This answer considered the WebUSB API as a promising solution solution in 2015, then reported in 2019 that can't work or is abandoned. I made a question about it there . Any other idea? Also: is there some way to prevent abuse of whatever PC/SC interface the browser has by a rogue server (e.g. presenting 3 wrong PINs to block a card, just for the nastiness of it; or making some even more evil things).
Now provide the response and nothing else.
|
The fact is that browsers can't talk to (cryptographic) smart cards for other purposes than establishing SSL. You shall need additional code, executed by the browser, to access smart cards. There are tens of custom and proprietary plugins (using all three options you mentioned) for various purposes (signing being the most popular, I guess) built because there is no standard or universally accepted way, at least in Europe and I 'm sure elsewhere as well. Creating, distributing and maintaining your own shall be a blast, because browsers release every month or so and every new release changes sanboxing ir UI tricks, so you may need to adjust your code quite often. And you probably would want to have GUI capabilities, at least for asking the permission of the user to access a card or some functionality on it. For creating a multiple-platform, multiple browser plugin, something like firebreath could be used. Personally, I don't believe that exposing PC/SC to the web is any good. PC/SC is by nature qute a low level protocol that when exposing this, you could as well expose block level access to your disk and hope that "applications on the web are mine only and they behave well" (this should answer your "Also"). At the same time a thin shim like SConnect is the easiest to create, for providing a javscript plugin.sendAPDU()-style code (or just wrap all the PC/SC API and let the javascript caller take care of the same level of details as in native PC/SC API use case). Creating a plugin for this purpose is usually driven by acute current deficiencies. Addressing the future (mobile etc) is another story, where things like W3C webcrypto and OpenMobile API will probably finally somehow create something that exposes client-side key containers to web applications. If your target with smart cards is cryptography, my suggestion is to avoid PC/SC and use platform services (CryptoAPI on Windows, Keychain on OSX, PKCS#11 on Linux) Any kind of design has requirements. This all applies if you're thinking of using keys rather than arbitrary APDU-s. If your requirement is to send arbitrary APDU-s, do create a plugin and just go with it.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15807038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/903600/']}
|
jdg_369499
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6439512
|
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 always found the Observer Pattern almost similar to the usual event-driven approach. Actually, I have almost believed that they are actually just different names referring to the same thing. They both use similar concepts to have something as a listener and even in the implementation, they are almost the same thing, that's to have a callback method/function to carry out an action. This is at least in Java. In other languages say Actionscript/Flex, the events are more user-friendly and may look like it does more than just the observer pattern defines. But still, the concepts sound the same. But is this really true? Is the Observer Pattern the same thing as the usual event-driven programming style?
Now provide the response and nothing else.
|
The Observer Pattern is a very special instance. Event-Driven can mean anything. In most Observer Pattern implementations the Observer is an object watching the observee. When the observee is changed, a method of the observer is called. Strictly speaking this is not an "Event". That means: various different actions on the observee, usually lead to the call of different methods in the observer. The semantics "what" got changed is in the method.In Event Driven Systems, you basically have one consuming object/method and the message what was changed or what happend is in the Event. That can be anything and is not limitd to the idea of observing something! That means: in an Event Driven System you get new semantics by adding new Event types. In an Observer Pattern you usually add semantics by adding a method to the Observer class. HOWEVER: no one is preventing you to implement an Observer as a special listern to ChangeEvents.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6439512', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/750511/']}
|
jdg_369500
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7130334
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We need to add more seed data for some newly added tables to "version 100" of our rails project. However, if we simply add it to the seeds.rb and re-run the rake db:seed command, it will of course Re-add the original seed data, duplicating it. So if you've already added seed data to seeds.rb for, say, TableOne ... How can we incrementally add seed data for TableTwo and TableThree at later stages of development? I'd hoped I could simply create a NEW seeds_two.rb file and run rake db:seeds_two but that gave an error Don't know how to build task 'db:seeds_two' So it looks like ONLY "seeds.rb" can be used. How do people maintain incremental additions to seed data?
Now provide the response and nothing else.
|
You can re-use the seed task, but make it idempotent . To make the seed idempotent, simply check for the existence of the condition before executing a command. An example: do you want to create a new admin user? User.find_or_create_by_username(:username => "admin") instead of User.create(:username => "admin") However, seed should be used to populate your database when the project is created. If you want to perform complex data seeding durin the lifecycle of the app, simply create a new rake task, execute it then remove it.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7130334', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/597992/']}
|
jdg_369501
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2229238
|
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 $K/k$ be a finite extension of fields, is $K[[T]]$ algebraic over $k[[T]]$? I think the compositum $Kk[[T]]$ is algebraic over $k[[T]]$, but not sure about $K[[T]]/Kk[[T]]$
Now provide the response and nothing else.
|
The dual space is always non-empty, as it contains the zero functional. The Hahn-Banach theorem implies that if $X \neq \{0\}$, then also $X^* \neq \{0\}$. Choose a non-zero vector $a \in X$. Denote the subspace $Y := \mathrm{span} (a) \subseteq X$ and the bounded functional $\varphi \in Y^*$ defined by $\varphi(a) = 1$. By Hahn-Banach, it can be extended to some bounded functional on the whole space $\overline{\varphi} \in X^*$, which is non-zero (since $\overline{\varphi}(a) \neq 0$), hence $X^* \neq \{0\}$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2229238', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
|
jdg_369502
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22990
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In Lebesgue integration we usually approximate the function we want to integrate with step-functions on measurable sets. How much "power" do we take away if we require that the step functions are on intervals instead? What functions are left that are integrable? I'm asking this because I want some integral to converge but I only know the values on $1_{(x_1,x_2)}$. Maybe we can get to Lipschitz functions that way? Edit to be more specific. Usually we define an integral for a positive function in this sense. First if we have$$f = \sum a_i 1_{A_i} \text{ then } \int f \, d\mu = \sum a_i \mu(A_i)$$ Now if $f$ is a positive measurable function we then define $$\int f \, d\mu := \sup \left \{\int g : g \leq f \text{ and $g$ is a simple function} \right \}$$ My question now is: what is left of the theory if we require the $A_i$ to be intervals instead of elements of the whole $\sigma$-algebra? My apologies for the unclear question. I shouldn't ask questions in the middle of the night.
Now provide the response and nothing else.
|
Terminologically speaking, step function usually means linear combination of characteristic functions of intervals, whereas simple function is used for functions taking on finitely many values. If you're talking about Lebesgue measure, you can approximate arbitrary $L^1$ functions with step functions in $L^1$ norm. It's just that in defining the Lebesgue integral, it's easiest to do so first for arbitrary simple functions, because then all measurable functions can be approximated in a particularly nice way. In particular, if $f$ is nonnegative, then $\int f$ can be defined to be the supremum of the integrals of nonnegative simple functions dominated by $f$. This would not work for step functions, as the characteristic function of the irrationals in $[0,1]$ shows; or, less trivially, the characteristic function of a fat Cantor set. Thus, your proposed change in definitions would break down for relatively nice Borel functions. However, the problem of $L^1$ approximation by step functions could be settled if you could find, for each finite measure set $E$ and for each $\varepsilon\gt0$, a finite union of intervals $F$ such that $\int |\chi_E - \chi_F |\lt \varepsilon$. That is, you want the measure of the symmetric difference of $E$ and $F$ to be less than $\varepsilon$. That this is true for Lebesgue measure on the line is (a version of) one of Littlewood's 3 principles .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/22990', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1120/']}
|
jdg_369503
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38543660
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Having the example array below, how do you slice by column to get the following (e.g. 3rd column) [0, 0, ..., 1338, 1312, 1502, 0, ...] Looking for the most efficient way, thanks! >>> rarray([[[ 0, 0, 0], [ 0, 0, 0], [ 0, 0, 0], [ 0, 0, 0], [ 0, 0, 0], [ 0, 0, 0]], [[ 0, 0, 1338], [ 0, 0, 1312], [ 0, 0, 1502], [ 0, 0, 0], [ 0, 0, 0], [ 0, 0, 0]], [[ 0, 0, 1400], [ 0, 0, 1277], [ 0, 0, 1280], [ 0, 0, 0], [ 0, 0, 0], [ 0, 0, 0]]], dtype=uint16)
Now provide the response and nothing else.
|
For a generic ndarray of any dimensions, one way would be - arr[...,n] To get a flattened version, use .ravel() method - arr[...,n].ravel() Sample run - In [317]: arrOut[317]: array([[[[2, 1, 2], [0, 2, 3], [1, 0, 1]], [[0, 2, 0], [3, 1, 2], [3, 3, 1]]], [[[2, 0, 0], [0, 2, 3], [3, 3, 1]], [[2, 0, 1], [2, 3, 0], [3, 3, 2]]]])In [318]: arr[...,2].ravel()Out[318]: array([2, 3, 1, 0, 2, 1, 0, 3, 1, 1, 0, 2])
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38543660', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5960055/']}
|
jdg_369504
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32953
|
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 it possible to use gzip to decompress a gzipped file, without the gz extension, and without moving the file?
Now provide the response and nothing else.
|
You can pass the -S option to use a suffix other than .gz . gunzip -S .compressed file.compressed If you want the uncompressed file to have some other name, run gzip -dc <compressed-file >uncompressed-filegunzip <compressed-file >uncompressed-file (these commands are equivalent). Normally unzipping restores the name and date of the original file (when it was compressed); this doesn't happen with -c . If you want the compressed file and the uncompressed file to have the same name, you can't do it directly, you need to either rename the compressed file or rename the uncompressed file. In particular, gzip removes and recreates its target file, so if you need to modify the file in place because you don't have write permission in the directory, you need to use -c or redirection. cp somefile /tmpgunzip </tmp/somefile >|somefile Note that gunzip <somefile >somefile will not work, because the gunzip process would see a file truncated to 0 bytes when it starts reading. If you could invoke the truncation, then gunzip would feed back on its own output; either way, this one can't be done in place.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/32953', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/9191/']}
|
jdg_369505
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1268177
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Apparently oracle doesn't seem to distinguish between empty strings and nulls. E.g. Select name from TABLE_A where id=100; ID NAME 100 nullUpdate TABLE_A set NAME='' where id=100;SELECT --> ID NAME 100 nullSELECT length(NAME) FROM TABLE_A WHERE id=100; null I can't think of any good reason why Oracle would be built to behave this way (does it do this in sqlplus as well?-I'm accessing through a java interface, the article referenced used a php client). Wouldn't you at least want to distinguish 0 length from undefined length? Is this a known issue? Intentional behavior for some specific purpose? A long-running dispute in database theory? What gives? (This was prompted by Matt Solnit's answer to this question .)
Now provide the response and nothing else.
|
Oracle is very very very old. Back in 80's when it was developed (and before there were any standards) they thought is was a good idea, and given then way Oracle stores its values, it really was. Here's how Oracle stores data (taken from the documentation ): No datatype is stored within the data, only the data length and the data itself. If the NULL occurs between two columns with values, it's stored as a single byte meaning column has length 0 (actually, 0xFF ). Trailing NULL s are not stored at all. So to store the value 'test' , Oracle needs to store 5 bytes: 04 74 65 73 74 . However, to store both an empty string and a NULL , Oracle just needs to set data length to 0 . Very smart if your data are to be stored on 20 Mb hard drives that cost 5,000$ each. Later, when the standards appeared, it wasn't such a good idea anymore, but by that time there already were lots and lots of code relying on NULL and '' being the same thing. Making VARCHAR to do such a distinction will break tons of code. To fix it, they renamed VARCHAR to VARCHAR2 (which is not a part of any standard), stated that VARCHAR2 will never distinguish between a NULL and an empty string and urged everybody to use this datatype instead. Now they are probably waiting for the last person who used a VARCHAR in Oracle database to die.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1268177', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19479/']}
|
jdg_369506
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
82947
|
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:
Kind of hard to explain but I noticed when strace ing the PID that has the socket open I cannot see any of the communication. How can I sit in the middle of a socket file to watch communication?
Now provide the response and nothing else.
|
sockets are a kernel API for communication. Using the socket API, you can exchange data between two endpoints over TCP/IP connections, SCTP associations, UDP datagrams, or between two processes (datagram or connection) using Unix domain sockets... Being a kernel API, any interaction with a socket is via system calls ( socket , bind , connect , listen , accept , sendmsg , send , recv , write/read ...). So typically, strace will be able to trace those because strace traces system calls. The only communication mechanism that strace can't trace is IPC over shared memory (because reading/writing something in memory obviously doesn't involve a system call). More likely, in your case, it's something else. My bet would be that the application is multi-threaded and you're not stracing the right thread. Or it could be that the application is setuid/setgid and not started as superuser. If you want to strace what's being exchanged over Unix domain sockets, the options are: strace and other ptrace debugger (trace the server or the clients) The audit system ( auditd / auditctl ), again that traces the system calls use a LD_PRELOAD trick to wrap the system calls that interact with the socket instrument the code of the application to add logging there. systemtap and other low level kernel tracing/debugging systems as already mentioned insert a man in the middle. For the MITM, you could for instance use socat . Here for a connection oriented Unix domain socket like for X11: socat -x unix-listen:/tmp/.X11-unix/X42,fork unix:/tmp/.X11-unix/X0DISPLAY=:42 xlogo Then, you see the X11 traffic that xlogo and the X server exchange.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/82947', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/-1/']}
|
jdg_369507
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15414505
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is probably really easy to do and I'm probably missing the wood for the trees but I'm trying to display a menu on a selection of pages which contains the sub menu items from the equivalent main menu item. For example, the main menu has 'Products' (parent item) listed with 'Product 1', 'Product 2' and 'Product 3' as sub menu items (child items). Is it possible (without creating duplicate articles) to create a submenu which only shows the child items but which links to the same articles as from the main menu? I've read about using menu-alias but none of the documentation I've found gives a clear message on this. Thanks.
Now provide the response and nothing else.
|
Looks like python stdin buffer is too small for images. You can run your program with -u flag in order to remove buffering. More details in this answer. Second is that numpy.asarray probably not right way to get numpy array from the data, numpy.frombuffer works for me very well. So here is working code (only I used cv2 instead of cv hope it wont matter too much): import sysimport cv2import numpystdin = sys.stdin.read()array = numpy.frombuffer(stdin, dtype='uint8')img = cv2.imdecode(array, 1)cv2.imshow("window", img)cv2.waitKey() Can be executed this way: python -u test.py < cat.jpeg
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15414505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2170633/']}
|
jdg_369508
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6163335
|
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 a messaging system for use in an XNA game. My Message types are structs because I want them to behave in a Value Type way. struct MyMessageType1 : IMessage {}struct MyMessageType2 : IMessage {}List<IMessage> messageQueue = new List<IMessage>(); I want to be able to store Messages of different types in my message queue, but I want to do so without any of them being boxed. If I have the structs implement an interface such as IMessage and I try to store them in a List, they get boxed. I don't know all the possible message types ahead of time, so I can't just hard code one List for each type. So the question is how can I store a list of structs of different types without them being boxed?
Now provide the response and nothing else.
|
This cannot be done. Alternative 1 However, you can emulate things, by using two Lists ( List<MyMessageType1> and List<MyMessageType2> ). You then concoct one Super Index (possibly, just another array of ints (longs?)) to make it possible to (indirectly) address an item as if it were one list. You might want to optimize the index (runlength encoding: store just the indexes where the backing array switches: this will also enormously help when iterating a subrange that is known to be contiguous in one of the backing arrays) Lists use Array storage internally, so - you get no boxing - fast random access - blazing iteration with list.ForEach Alternative 2 Look at the StructLayout attribute and somehow emulate a Union by doing all the manipulations. If you are really prepared to get your hands dirty, throw in unsafe {} blocks (and compile with /unsafe) ... however, seriously consider P/Invoke a C DLL or use C++/CLI if it matters that much Alternative 3 (added) Because I really liked the fact that Marc Gravell pointed out you can use the StructLayout that I mentioned, to pinpoint all three members of a union .NET struct at the same offset; I thought I'd go the extra step and see whether I could make that a hell of a lot more leaky tranparent still. This comes pretty close to being transparent: using System.Collections.Generic;using System.Runtime.InteropServices;namespace LeakyAbstractions{ struct TypeA {} struct TypeB {} struct TypeC {} [StructLayout(LayoutKind.Explicit)] internal struct AnyMessage { [FieldOffset(0)] public TypeA A; [FieldOffset(0)] public TypeB B; [FieldOffset(0)] public TypeC C; AnyMessage(TypeA a) { A = a; } AnyMessage(TypeB b) { B = b; } AnyMessage(TypeC c) { C = c; } public static implicit operator TypeA(AnyMessage msg) { return msg.A; } public static implicit operator TypeB(AnyMessage msg) { return msg.B; } public static implicit operator TypeC(AnyMessage msg) { return msg.C; } public static implicit operator AnyMessage(TypeA a) { return a; } public static implicit operator AnyMessage(TypeB b) { return b; } public static implicit operator AnyMessage(TypeC c) { return c; } } public class X { public static void Main(string[] s) { var anyMessages = new List<AnyMessage> { new TypeA(), new TypeB(), new TypeC(), }; TypeA a = anyMessages[0]; TypeB b = anyMessages[1]; TypeC c = anyMessages[2]; anyMessages.Add(a); anyMessages.Add(b); anyMessages.Add(c); } }} I'll leave the problem of discriminating this poor men's variant as an exercise to you. The simplist way would be to add a field to the AnyMessage struct, but depending on the payload, other strategies might be much more (space/time) efficient. My $0.02 Oh, I'd never actually do this, because it seems like overcomplicated. I'm assuming you have a valid reason to optimize this PS. If you are asking this after reading my answer here (yesterday: Should I use a struct or a class to represent a Lat/Lng coordinate? ), I'm going to snap-judge this premature optimization
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6163335', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/253732/']}
|
jdg_369509
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1069865
|
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:
Sometimes I get a little confused with what order to do things in when it comes to $ln$ being raised to the natural base. For example $e^{\int -A\ln{x} dx}$ where $A$ is an arbitrary constant. Should this be rewritten as $e^{-A \cdot \int \ln{x} dx}$ or $e^{\int \ln{x^{-A}} dx}$ ? I guess what I'm asking is, do you simplify using normal rules of algebra first or using rules pertaining to integrals?
Now provide the response and nothing else.
|
For subspaces isomorphic to $\mathbb{Z}_p\times \mathbb{Z}_p$, you have to pick two linearly independent vectors. There are $p^3-1$ choices for the first vector and $p^3-p$ choices for the second vector. At this point we've overcounted by as many times as the number of distinct ordered bases in $\mathbb{Z}_p\times\mathbb{Z}_p$, which is $(p^2-1)(p^2-p)$ (which can be deduced in the same way). The answer is therefore$$\frac{(p^3-1)(p^3-p)}{(p^2-1)(p^2-p)}=\frac{p(p^3-1)(p^2-1)}{p(p^2-1)(p-1)}=p^2+p+1$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1069865', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/43325/']}
|
jdg_369510
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
69147
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Assume $G$ is a profinite group such that the Jordan-Hölder factors appearing in the finite quotients vary in a finite number of isomorphism classes of simple groups. Assume also $G$ to have a finite number of subgroups whose corresponding quotient is simple. Does this imply that $G$ is (topologically) finitely generated? I'm asking here after some attempt to make work a modification of the principle the for a $p$-group $P$ each set of elements generating $P/\Phi(P)$ is a generating set for $P$. For $P$ groups the question is clearly much simpler, and i have been thinking that elements generating each simple quotient had to be be enough (this is not true, as shown by the simple example $Sym_n$. But the different symmetric groups have bigger and bigger Jordan-Holder factors). However the issue is not totally trivial, because maximal (non-normal) subgroups are in generally not contained in a proper normal subgroup, so it is not possible to replicate a similar proof smoothly. Note that the hypothesis of having a finite number of factors rules out silly couterexamples like $\prod_{i=4}^\infty Alt_i$. Is anything know about this question? Thanks for the attention!
Now provide the response and nothing else.
|
I think the answer is no. Fix a nonabelian finite simple group $S$ and a sequence $(m_n)$ of integers at least 2. Define inductively $G_1=S$ and $G_{n}=S^{m_n}\wr G_{n-1}$. This group admits only $S=G_1$ as simple quotient and only $S$ as Jordan-Hölder factor. I claim that, provided $(m_n)$ grows fast enough, the rank (minimal number of generators) of $G_n$ is unbounded, so that the inverse limit of the $G_n$ is not finitely generated, although it satisfies your assumptions. The claim that $G_n$ has a unique maximal normal subgroup $W_n$ is obtained by an easy induction. This uses only that $G_n=V_n\rtimes G_{n-1}$, where the only subgroups of $V_n$ that are normal in $G_n$ are $V_n$ and {1} (we need $S$ be nonabelian here) and $V_n$ has trivial centralizer in $G_n$. On the other hand, we use that the rank $r(G)$ of a wreath product $G=A\wr B$ is at least $r(A)/|B|$. Indeed, Suppose that $G$ is generated by $r$ elements. Then it's generated by $B$ and $r$ elements of $A^B$, $a_i=(a_{ij})_{1\le j\le |B|}, i=1\dots r$. So $A$ is generated by the $a_{ij}$. Thus $r(A)\le |B|r(G)$. Since the rank of $S^n$ tends to infinity when $n$ tends to infinity, we can define inductively the sequence $(m_n)$ so that the rank of $G_n$ is at least $n$. Edit: as pointed out by Maurizio in an email, in the example it's not true that the only subgroups of $V_n=S^{m_n}$ that are normal in $G_n$, are $V_n$ and the trivial group. Actually there are a little more: $T^{m_n}$, where $T$ is a direct factor in $S^{m_n}$. This is however enough to run an induction that $G_n$ has a unique maximal normal subgroup.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/69147', 'https://mathoverflow.net', 'https://mathoverflow.net/users/3680/']}
|
jdg_369511
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26394778
|
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 just modified spring boot configuration, and encountered @ConditionalOnProperty(prefix = "spring.social.", value = "auto-connection-views") from org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration @Bean(name = { "connect/twitterConnect", "connect/twitterConnected" })@ConditionalOnProperty(prefix = "spring.social.", value = "auto-connection-views")public View twitterConnectView() { return new GenericConnectionStatusView("twitter", "Twitter");} I don't understand purpose of this annotation. I guess this might be enable to use bean only if property value exist(e.g. "spring.social", "auto-connection-views").
Now provide the response and nothing else.
|
The annotation is used to conditionally create a Spring bean depending on the configuration of a property. In the usage you've shown in the question the bean will only be created if the spring.social.auto-connection-views property exists and it has a value other than false . This means that, for this View bean to be created, you need to set the spring.social.auto-connection-views property and it has to have a value other than false. You can find numerous other uses of this annotation throughout the Spring Boot code base. Another example is: @ConditionalOnProperty(prefix = "spring.rabbitmq", name = "dynamic", matchIfMissing = true)public AmqpAdmin amqpAdmin(CachingConnectionFactory connectionFactory) { return new RabbitAdmin(connectionFactory);} Note the use of matchIfMissing . In this case the AmqpAdmin bean will be created if the spring.rabbitmq.dynamic property exists and has a value other than false or the property doesn't exist at all. This makes the creation of the bean opt-out rather than the example in the question which is opt-in.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/26394778', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3409583/']}
|
jdg_369512
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
47350199
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Environment:Asp Net MVC app(.net framework 4.5.1) hosted on Azure app service with two instances.App uses Azure SQL server database.Also, app uses MemoryCache (System.Runtime.Caching) for caching purposes. Recently, I noticed availability loss of the app. It happens almost every day. Observations:The memory counter Page Reads/sec was at a dangerous level (242) on instance RD0003FF1F6B1B. Any value over 200 can cause delays or failures for any app on that instance. What 'The memory counter Page Reads/sec' means?How to fix this issue?
Now provide the response and nothing else.
|
What 'The memory counter Page Reads/sec' means? We could get the answer from this blog . The recommended Page reads/sec value should be under 90 . Higher values indicate insufficient memory and indexing issues . “Page reads/sec indicates the number of physical database page reads that are issued per second. This statistic displays the total number of physical page reads across all databases. Because physical I/O is expensive, you may be able to minimize the cost, either by using a larger data cache, intelligent indexes, and more efficient queries, or by changing the database design.” How to fix this issue? Based on my experience, you could have a try to enable Local Cache in AppService . You enable Local Cache on a per-web-app basis by using this app setting: WEBSITE_LOCAL_CACHE_OPTION = Always By default, the local cache size is 300 MB . This includes the /site and /siteextensions folders that are copied from the content store, as well as any locally created logs and data folders. To increase this limit, use the app setting WEBSITE_LOCAL_CACHE_SIZEINMB . You can increase the size up to 2 GB (2000 MB) per web app.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47350199', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5841485/']}
|
jdg_369513
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
34307647
|
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 define a bootstrap modal that gets a dynamic width regarding its content and if necessary a vertical scrollbar. The vertical scrollbar works but the horizontal width seems to be a fixed width. Could you please help? Modal: <div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"><h4 class="modal-title">Dynamic Modal Title</h4></div> <div class="modal-body">Dynamic Modal Body</div> <div class="modal-footer">Dynamic Modal Footer</div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --></div><!-- /.modal --> CSS: .modal .modal-body { /* Vertical scrollbar if necessary */ max-height: 480px; overflow-y: auto;}body .modal-dialog { /* Width */ max-width: 100%;}
Now provide the response and nothing else.
|
inline-block elements get dynamic width regarding their content. body .modal-dialog { /* Width */ max-width: 100%; width: auto !important; display: inline-block;} Note: width: auto !important; is required to overwrite bootstrap css.Finally to place it in middle of viewport you to display: flex; on the parent element .modal { z-index: -1; display: flex !important; justify-content: center; align-items: center;}.modal-open .modal { z-index: 1050;}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34307647', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5367675/']}
|
jdg_369514
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19206
|
Below is a question asked on the forum engineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In theory of bending of beams, often these terms are used. There are no clear definition present. Most of them contradicting. Which of the property(bending moment and shear force) is zero in which case? The definition of contraflexure is defined as the point of zero bending moment. Then why have another term, i.e inflection point ? NOTE:The wikipedia link has no references.
Now provide the response and nothing else.
|
A point of inflection is defined as the point where a function changes from convex to concave or vice versa. For a function $f(x)$ , this is frequently mathematically defined as the point where $f''(x) = 0$ , since $f''(x)$ describes $f(x)$ 's curvature [1] . Being more pedantic about it, this is a necessary but not sufficient condition: a function might have no curvature $\left(f''(x) = 0\right)$ but not actually change between convex and concave (this is strictly called an undulation point). That being said, in common parlance any point which satisfies $f''(x) = 0$ is considered an inflection point. Note that the above has nothing to do with bending moment, it is a characteristic of any mathematical function. Contraflexure, on the other hand, is as you've said: the point where a beam suffers no bending moment. For example, here's the bending moment of a cantilever beam with a linear load which generates a point of contraflexure and a point of inflection (notice that to the left of the point, the curve has negative curvature, and to the right of the point, it has positive curvature). The point of contraflexure is easily identifiable on a diagram (it's where the bending moment diagram equals zero). The point of inflection is harder to identify precisely; you can quickly tell that there is a point of inflection and that is it "around here", but you can't easily point to its exact location (without doing the math, I can tell it's somewhere in the circled region). However, when speaking of beams, it is possible to state that the point of contraflexure is the same as the point of inflection. However , one will actually be talking about two different things at the same time. As previously stated, the point of contraflexure is that point where bending moment is equal to zero. However, according to the fundamental beam equation, we know that bending moment is the second derivative of deflection (times the stiffness). So, since the point of inflection is that point where the second derivative of a function is equal to zero [2] , the point of contraflexure is equal to the deflection's inflection point. [1] As mentioned by @Mohan's answer , there is a possible exception to this rule: continuous functions $f(x)$ with continuous $f'(x)$ but discontinuous $f''(x)$ . If $f''(x)$ is discontinuous at $x=a$ and $\text{sign}\left(\lim\limits_{x\rightarrow a^+}f''(x)\right) \ne \text{sign}\left(\lim\limits_{x\rightarrow a^-}f''(x)\right)$ (in English: the sign of $f''(x)$ to the left of the discontinuity is different than to its right), then $x=a$ is $f(x)$ 's inflection point. This only works in cases where $f'(x)$ is continuous. This is because for a point to serve as an inflection point for $f(x)$ , there must be a single valid tangent at that point. So if the derivative is continuous, that condition is met even if $f''(x)$ (the curvature) is discontinuous). [2] The exception described above in [1] applies to beams. If a beam suffers a concentrated bending moment, that leads to a discontinuous bending (or curvature) diagram, but the deflection's derivative (tangent angle diagram) will still be continuous. So if that concentrated bending moment leads to a change in the bending diagram's sign at that point, then that will be an inflection point in the beam's deflection.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://engineering.stackexchange.com/questions/19206', 'https://engineering.stackexchange.com', 'https://engineering.stackexchange.com/users/14771/']}
|
jdg_369515
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
34534151
|
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 struggling to understand how to pass data between components in vue.js. I have read through the docs several times and looked at many vue related questions and tutorials, but I'm still not getting it. To wrap my head around this, I am hoping for help completing a pretty simple example display a list of users in one component (done) send the user data to a new component when a link is clicked (done) - see update at bottom. edit user data and send it back to original component (haven't gotten this far) Here is a fiddle, which fails on step two: https://jsfiddle.net/retrogradeMT/d1a8hps0/ I understand that I need to use props to pass data to the new component, but I'm not sure how to functionally do it. How do I bind the data to the new component? HTML: <div id="page-content"> <router-view></router-view> </div> <template id="userBlock" > <ul> <li v-for="user in users">{{user.name}} - <a v-link="{ path: '/new' }"> Show new component</a> </li> </ul> </template> <template id="newtemp" :name ="{{user.name}}"> <form> <label>Name: </label><input v-model="name"> <input type="submit" value="Submit"> </form> </template> js for main component: Vue.component('app-page', { template: '#userBlock', data: function() { return{ users: [] } },ready: function () { this.fetchUsers();},methods: { fetchUsers: function(){ var users = [ { id: 1, name: 'tom' }, { id: 2, name: 'brian' }, { id: 3, name: 'sam' }, ]; this.$set('users', users); } } }) JS for second component: Vue.component('newtemp', { template: '#newtemp', props: 'name', data: function() { return { name: name, } },}) UPDATE Ok, I've got the second step figured out. Here is a new fiddle showing the progress: https://jsfiddle.net/retrogradeMT/9pffnmjp/ Because I'm using Vue-router, I don't use props to send the data to a new component. Instead, I need set params on the v-link and then use a transition hook to accept it. V-link changes see named routes in vue-router docs : <a v-link="{ name: 'new', params: { name: user.name }}"> Show new component</a> Then on the component, add data to the route options see transition hooks : Vue.component('newtemp', { template: '#newtemp', route: { data: function(transition) { transition.next({ // saving the id which is passed in url name: transition.to.params.name }); } }, data: function() { return { name:name, } },})
Now provide the response and nothing else.
|
-------------Following is applicable only to Vue 1 -------------- Passing data can be done in multiple ways. The method depends on the type of use. If you want to pass data from your html while you add a new component. That is done using props. <my-component prop-name="value"></my-component> This prop value will be available to your component only if you add the prop name prop-name to your props attribute. When data is passed from a component to another component because of some dynamic or static event. That is done by using event dispatchers and broadcasters. So for example if you have a component structure like this: <my-parent> <my-child-A></my-child-A> <my-child-B></my-child-B></my-parent> And you want to send data from <my-child-A> to <my-child-B> then in <my-child-A> you will have to dispatch an event: this.$dispatch('event_name', data); This event will travel all the way up the parent chain. And from whichever parent you have a branch toward <my-child-B> you broadcast the event along with the data. So in the parent: events:{ 'event_name' : function(data){ this.$broadcast('event_name', data); }, Now this broadcast will travel down the child chain. And at whichever child you want to grab the event, in our case <my-child-B> we will add another event: events: { 'event_name' : function(data){ // Your code. },}, The third way to pass data is through parameters in v-links. This method is used when components chains are completely destroyed or in cases when the URI changes. And i can see you already understand them. Decide what type of data communication you want, and choose appropriately.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/34534151', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3111954/']}
|
jdg_369516
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16146
|
Below is a question asked on the forum robotics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been looking into implementations of Extended Kalman filters over the past few days and I'm struggling with the concept of "sensor fusion". Take the fusion of a GPS/IMU combination for example, If I applied a kalman filter to both sensors, Which of these will I be doing? Convert both sensors to give similar measurements (eg. x, y, z), apply a kalman filter to both sensors and return an average of the estimates Convert both sensors to give similar measurements (eg. x, y, z), apply a kalman filter, and return an estimate of the sensor I trust more based on a certain parameter (measurement noise covariance)?
Now provide the response and nothing else.
|
I realize this question already has an accepted answer, but I'd like to provide some additional input. The question of sensor fusion is a good one, but, depending on the application, you don't typically want to "convert" (i.e., integrate twice) the IMU to obtain xyz position. Frankly, in my experience, the best way to approach fusing GPS and IMU data for a mobile robot (quadcopter, unmanned ground vehicle, etc) is already provided within the EKF framework: Identify a plant process model and associated process noise for the robot. 2a. Identify an observation model and associated measurement noise for the GPS 2b. Identify an observation model and associated measurement noise for the IMU tl;dr: to answer your specific question: you'd be doing neither! The IMU provides acceleration corrections to the process model, and the GPS provides position corrections to the process model. The sensor fusion aspect is more or less a weighted average based on the process noise and measurement noise. Sure, a purely kinematic process model might act as a double integrator, but that's not the only choice of process models. It might sound like semantics, but I think it represents a fundamental misunderstanding of the Kalman filter to speak in terms of "converting" the IMU to provide xyz corrections. Additional thoughts: The plant process model can be a simple kinematic model (constant velocity or constant acceleration) or a sophisticated dynamical model. It is generally best to start simple and add complexity later if required. Process model are typically developed from first principles (physics), but you can probably find some decent ones online if you get stuck. The same is true for observation models for a GPS and IMU sensors. The measurement noise statistics can be found from the manufacturer data sheets or experimentally.[Aside: if you're working with real instruments, it's best to try to get your own data on the measurement noise. If a static test will give you representative data, set the sensor on the bench, collect a bunch of data, and determine the measurement noise statistics. Pro tip: the std dev of the noise (aka sigma) often varies inversely with the square root of the sampling frequency, e.g., sampling at 10Hz instead of 1KHz reduces sigma by an order of magnitude. You can see this mathematically by working out the expected values.] With a GPS and IMU, a more sophisticated dynamical plant process model will likely just improve the estimate of linear velocity. Depending on the update rate of your GPS and how much you care about your velocity estimate, the added complexity of a dynamic model may be unnecessary for your given application. If you have a good linear-velocity sensor, a dynamic model is rarely required. Many papers have been written and accepted to respected journals and conferences with kinematic process models. [Aside: The difficulty of dynamic models is that their accuracy depends on knowing: 1. the structure of the model. 2. the parameters (mass, drag, etc) used in the model. The structure of the model can often be developed from first principles, but parameter estimation can be difficult even for known model structures.] The "black art" of the EKF is the choice of process noise. In the linear case, Kalman proved that the KF will converge regardless of the noise (we understand how to propogate Gaussian distributions through linear systems), but the same isn't true for the nonlinear extension. There are many papers written on the subject of estimating process noise for nonlinear models. This still an area of active research. My advice is just to play with the process noise until you achieve acceptable performance. Also: the paper linked in the accepted answer is certainly interesting, but far from the simplest approach. Based on a quick scan, the purpose of that paper is to report a new method/approach for real-time rejection of bad data from the IMU or GPS based on fuzzy logic and "contextual variables." NB: Again, in the context of EKFs, "bad data" means data inconsistent with the expected measurement noise. This is an important problem to address because the accuracy (and even stability) of the EKF hinges on the idea that measurement data from the instruments have the noise characteristics that you specified. This is a key important point because it means any additional instrument, no matter how bad the noise is, won't make the state estimate worse PROVIDED the measurement noise used in the EKF matches the noise from the actual measured data. NB. this can be proven mathematically for the KF, but not for the EKF, though it works as expected the vast majority of the time with reasonable process noise. Instrument failure and outlier rejection are worth investigating and understanding...after you've already implemented an EKF that can handle asynchronous measurements and a bias in the IMU measurement. Start simple and add complexity. Hope this helps.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://robotics.stackexchange.com/questions/16146', 'https://robotics.stackexchange.com', 'https://robotics.stackexchange.com/users/20491/']}
|
jdg_369517
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12481506
|
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 looking for a graceful JSF way to do this and was wondering if there was any commonly accepted practice for doing this. When I navigate from one page to another, I want the new page to show a FacesMessage in a h:message component (actually p:message but it should be the same thing) that was transmitted from the last page. So for example, if a user clicks a "Create Document" button it navigates to a new page on success, and shows the success message on the new page. I want all my data-base changing operations to behave that way. It seems that the FacesContext clears all messages on the navigation, so my closest solution looks like this: Store the FacesMessage object in the session bean. Create a method checkMessage in the message bean that calls FacesContext.getCurrentInstance().addMessage(..) and removes the message from the message bean. Put a EL reference to checkMessage in the destination page. Put a p:message in the destination page. This seems a bit forced -- is there a better way of doing this?
Now provide the response and nothing else.
|
Faces messages are indeed request scoped. Just make use of the new JSF 2.0 Flash scope: Flash#setKeepMessages() : context.addMessage(clientId, message);context.getExternalContext().getFlash().setKeepMessages(true);// ... This has only one caveat in the current Mojarra 2.1.13 release: the redirect has to take place in the same "folder" in the URL. This is fixed in the shortly upcoming 2.1.14. See also issue 2136 .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12481506', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/527470/']}
|
jdg_369518
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23822
|
Below is a question asked on the forum scicomp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a linear system of equations that can be expressed $$A=B+AB,$$ where $A$ and $B$ are real, symmetric matrices. I would like to solve for $A$ given $B$. At present, I solve for $A$ directly via $$A=B(I-B)^{-1},$$ with the inverse computed via $LU$ factorization. For most relevant inputs $B$, the inversion goes well, but of course, sometimes $(I-B)$ is simply ill-conditioned. Is there a way to solve for $A$ without explicitly computing a matrix inverse?
Now provide the response and nothing else.
|
If $A$ and $B$ are real symmetric, then $A=B+AB$ if and only if the product $AB$ is also real symmetric. In turn, $AB=BA$ holds if any only if $A$ and $B$ share a common eigendecomposition. This latter statement gives a recipe for computing $A$ given $B$. Given $B$, compute its eigendecomposition $B=V\Lambda V^T$, in which $V$ is the orthonormal set of of eigenvectors, and $\Lambda = \mathrm{diag}(\lambda_1,\dots,\lambda_n)$ is the diagonal matrix of real eigenvalues. Compute the diagonal matrix $S= \mathrm{diag}(s_1,\dots,s_n)$ in which each $s_k$ is defined with respect to the corresponding $\lambda_k$ as in $$s_k=\frac{\lambda_k}{1-\lambda_k}\text{ for all }k\in\{1,\ldots,n\}.$$ Output $A=VSV^T$. In fact, this is the most numerically stable procedure possible for solving the desired equation. The computed $A$ is exactly real symmetric by construction. Also, limiting all matrix-matrix operations to orthogonal transformations minimizes the numerical error that are propagated from the problem data to the computed solution. Of course, we will none-the-less encounter ill-conditioning if the eigenvalues of $B$ are close to 1. But this latter phenomenon is physical, and reflects the underlying ill-conditioning of the equation to be solved. In this latter case, we may reformulate the problem and solve it in a least-squares sense, using essentially the same steps as the ones presented above.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://scicomp.stackexchange.com/questions/23822', 'https://scicomp.stackexchange.com', 'https://scicomp.stackexchange.com/users/14469/']}
|
jdg_369519
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5997189
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Python has Queue.PriorityQueue, but I cannot see a way to make each value in it unique as there is no method for checking if a value already exists (like find(name) or similar). Moreover, PriorityQueue needs the priority to remain within the value, so I could not even search for my value, as I would also have to know the priority. You would use (0.5, myvalue) as value in PriorityQueue and then it would be sorted by the first element of the tuple. The collections.deque class on the other hand does offer a function for checking if a value already exists and is even more natural in usage (without locking, but still atomic), but it does not offer a way to sort by priority. There are some other implementations on stackoverflow with heapq, but heapq also uses priority within the value (e.g. at the first position of a tuple), so it seems not be great for comparison of already existing values. Creating a python priority Queue https://stackoverflow.com/questions/3306179/priority-queue-problem-in-python What is the best way of creating a atomic priority queue (=can be used from multiple threads) with unique values? Example what I’d like to add: Priority: 0.2, Value: value1 Priority: 0.3, Value: value2 Priority: 0.1, Value: value3 (shall be retrieved first automatically) Priority: 0.4, Value: value1 (shall not be added again, even though it has different priority)
Now provide the response and nothing else.
|
You could combine a priority queue with a set: import heapqclass PrioritySet(object): def __init__(self): self.heap = [] self.set = set() def add(self, d, pri): if not d in self.set: heapq.heappush(self.heap, (pri, d)) self.set.add(d) def get(self): pri, d = heapq.heappop(self.heap) self.set.remove(d) return d This uses the priority queue specified in one of your linked questions. I don't know if this is what you want, but it's rather easy to add a set to any kind of queue this way.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5997189', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/688161/']}
|
jdg_369520
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
55185601
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to get my variable from my .env file but I always get undefined This is my js code : require('dotenv').config();class Header extends React.Component{ constructor(props){...} render(){ console.log("NODE ENV", process.env.NODE_ENV); console.log("REACT_APP_MYAPP", process.env.REACT_APP_MYAPP); ... }} This prints : NODE_ENV development REACT_APP_MYAPP undefined In my package.json there is : "scripts":{ "start" : "webpack-dev-server --config webpack.dev.js", "build" : "webpack --config webpack.prod.js" } And in my webpack.dev.js: const webpack = require("webpack");const merge = require("webpack-merge");const path = require("path");const common = require("./webpack.common.js");module.exports = merge.smart(common, { devServer: { contentBase: path.resolve(__dirname, "dist"), hot: true, overlay: { warnings: true, errors: true }, inline :true, historyApiFallback: true, port: 8085 }, devtool: "inline-sourcemap", optimization: { namedModules: true }, plugins: [ new webpack.HotModulReplacementPlugin(), new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("development"), "process.env.REACT_APP_MYAPP": JSON.stringify(process.env.REACT_APP_MYAPP) }) ], mode: "development"}); And I placed my .env file at the root of my project, next to webpack.dev.js and package.json: REACT_APP_MYAPP= http://localhost:8080/ So I think, it doesn't success to get the variable in the file. How can I get the REACT_APP_MYAPP value in the code please ?
Now provide the response and nothing else.
|
Journeying through the deep, dark rabbit hole will lead you to the following facts: Webpack 5 no longer provides process or other Node.js variables . The role of DefinePlugin requires redefining. Values passed to DefinePlugin must be stringified , even if they're strings. EnvironmentPlugin makes things more confusing, given Webpack 5. process.env isn't really something you should be using in the frontend. You can use polyfills to re-add process and others back in, but there is a reason it's no longer available . dotenv-wepack is neither necessary nor the way to go. The reason for using process.env is to access variables globally. But it's a passenger on the wrong flight. We can drop it and instead just access the intended variable directly: plugins: [ new DefinePlugin({ // With dotenv (values must be stringified) ...Object.entries(dotenv.config().parsed).reduce((acc, curr) => ({...acc, [`${curr[0]}`]: JSON.stringify(curr[1]) }), {}), // Without dotenv 'myString': JSON.stringify('IAmAString') }) ] In the frontend: declare var myString: string;console.log(myString); // 'IAmAString' If you have several objects with variables it makes sense to abstract the stringification: // Create a function to stringify valuesfunction stringifyValues(object: {[key: string]: any;}){ return Object.entries(object).reduce((acc, curr) => ({...acc, [`${curr[0]}`]: JSON.stringify(curr[1]) }), {} as { [key: string]: string; });}// use with DefinePluginplugins: [ new DefinePlugin({ ...stringifyValues(dotenv.config().parsed), ...stringifyValues(dotenv.config({ path: '/.env.special' }).parsed), 'myObject': stringifyValues({ name: 'Object', description: 'to be an object' }) }) ] If you really want access to process.env : plugins: [ new DefinePlugin({ // this might expose confidential data about your environment 'process.env': JSON.stringify(process.env), // the correct way 'process.env.USERNAME': JSON.stringify('Donald Hump') }) ] In the frontend: declare var process: any;console.log(process) // will NOT work, because process hasn't been injectedconsole.log(process.env); // will work but riskyconsole.log(process.env.USERNAME); // correct: 'Donald Hump'
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55185601', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2215065/']}
|
jdg_369521
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
236124
|
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:
Suppose I have a list of Ingredients In My Fridge which are going off soon, and a list of Recipes which use up various Ingredients. (Some of which I don't currently have.) Is there an algorithm which produces the optimal set of Recipes, where an optimal set maximises the number of Ingredients In My Fridge used up and minimises the number of Ingredients I Have To Buy From The Store? (Alternate formulation: In a card game, I can combine some Cards according to various Rules; I can also obtain new Cards in various ways. How do I find the best set of Rules to use up the most Cards I have for the minimum effort in obtaining new Cards?)
Now provide the response and nothing else.
|
This is the Exact Cover problem , one of the original 21 problems shown by Karp to be NP-complete in his classic 1972 paper that established the importance of NP-completeness. Wikipedia's description is: given a collection S of subsets of a set X, an exact cover is a subcollection S* of S such that each element in X is contained in exactly one subset in S*. The basic problem is, given S and X, does S contain an exact cover of X? Here X is the set of contents of your refrigerator, and S is the collection of recipes. The task is to find a subset S* of recipes such that each ingredient from X is used by exactly one recipe. Exact Cover is known to remain NP-complete even when every recipe requires no more than 3 ingredients. If every recipe has 2 or fewer ingredients, there is a polynomial-time algorithm based on finding a maximal matching in a bipartite graph. The analogous problem, of whether there is a cover S* that covers at least n elements of X, is also NP-complete. Similarly, one can rephrase this as an optimization problem: find the subset S* that covers the maximum possible number of elements. An efficient solution to this optimization problem would solve the NP-complete decision problem, so is at least as difficult as the decision problem. As is usual with NP-complete problems, one can say the following: A good algorithm that works for all instances of the problem is certainly out of reach at present, and probably does not exist. Branch-and-bound tree search will find a good solution quickly for many instances of the problem, and for small instances. Straightforward approaches (say, always selecting the recipe with the greatest number of available ingredients) may produce results that are never too far from optimal. There is a lot of research on this sort of thing, and it should not be hard to uncover some. Wikipedia also mentions an algorithm of Donald Knuth which efficiently performs an exhaustive search of the solution space (which may be very large) by representing the recipes as rows of a matrix.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/236124', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/127131/']}
|
jdg_369522
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
392863
|
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:
Consider a simple situation like this- an object is sitting on a table. In classical mechanics, we say that the net force on the object is zero because gravity (treated as a force) and normal reaction force are equal and opposite to each other, and hence, it's acceleration is zero. But according to Einstein's General Theory of Relativity, gravity isn't a force at all, but instead curvature created in spacetime by a massive object, and objects near it tend to move towards it because they are just moving along the geodesic paths in that curved spacetime. So if an object kept on a table gets acted only by the normal reaction force (as gravity ain't a force), how is the net force on it zero?
Now provide the response and nothing else.
|
So if an object kept on a table gets acted only by the normal reaction force (as gravity ain't a force), how is the net force on it zero? I've quoted what I think is the key part of your question, and it's key because the net force is not zero. The object on the table experiences a net force of $mg$ and as a result it is experiencing an upwards acceleration of $g$ . The way you can tell if no force is acting on you is by whether you are weightless or not. If you were floating in space far from any other objects then there would be no forces acting upon you and you'd be weightless. If we fixed a rocket to you and turned it on then you'd no longer be weightless because now the rocket is exerting a force on you. Technically you have a non-zero proper acceleration . In general relativity your acceleration (your four-acceleration ) has two components. We write it as: $$ a^{\mu}= \frac{\mathrm du^\mu}{\mathrm d\tau}+\Gamma^\mu_{\alpha \beta}u^{\alpha}u^{\beta} $$ The first term $\mathrm du^\mu/\mathrm d\tau$ is the rate of change of your (coordinate) velocity with time, so it is what Newton meant by acceleration, and the second term is the gravitational acceleration. The key thing about general relativity is that we don't distinguish between the two - they both contribute to your acceleration. If you're falling freely then the two terms are equal and opposite so they cancel out and you''re left wit an acceleration of zero: $$ a^{\mu}= 0 $$ This is when the net force on you is zero. For the object on the table the coordinate bit of the acceleration is zero but the second term is not and the acceleration is: $$ a^{\mu}= \Gamma^{\mu}_{\alpha \beta}u^{\alpha}u^{\beta} $$ So the object sitting on the table has a non-zero acceleration and the net force on it is not zero. Maybe this sounds like I'm playing with words a bit, by defining what I do and don't mean by acceleration . But this is absolutely key to understanding how general relativity describes the motion of bodies. The key point is that gravitational and coordinate acceleration are treated on an equal footing, and if you are stationary in a gravitational field that means you are accelerating. If you're interested in pursuing this further there is a fuller description in How can you accelerate without moving? . There is more on why spacetime curvature makes you accelerate in How does "curved space" explain gravitational attraction? A footnote Given the attention this answer has received I think it is worth elaborating on exactly how relativists view this situation. The question gives an example of an object sitting stationary on a table, but let's start with an object a few metres above the table and falling freely towards it. It seems obvious that the apple is accelerating down towards the table. It seems obvious because we are used to taking the surface of the Earth as stationary because that's our rest frame (even though the surface of the Earth is most certainly not at rest :-). But if you were the apple then it would seem natural to take your rest frame as stationary, and in that case the apple is not accelerating downwards - the table is accelerating upwards to meet it. So which view is correct? The answer is that both are correct. Whether it's the apple or the table that is stationary is just a choice of rest frame, i.e. a choice of coordinates, and it is a fundamental principle in general relativity that all coordinates are equally good when it comes to describing physics. But if we can randomly choose our coordinates it seems hard to say anything concrete. We could choose frames accelerating at any rate, or rotating, or expanding or all sorts of bizarre frames. Isn't there something concrete we can say about the situation? Well there is. In relativity there are quantities called invariants that do not depend on the coordinates used. For example the speed of light is an invariant - all observers measuring the speed of light find it has the same value of $c$ . And in our example of the apple and table there is an important invariant called the proper acceleration. While the apple and the table disagree about which of them is accelerating towards the other, if they compute their respective proper accelerations they will both agree what those values are. In Newtonian mechanics acceleration is a vector $(a_x, a_y, a_z)$ , but in relativity spacetime is four dimensional so vectors have four components. The four-acceleration is the relativistic equivalent of the three dimensional Newtonian acceleration that we are all used to. While it's a bit more complicated, the four acceleration is just a vector in 4D spacetime, and like all vectors it has a magnitude – in relativity we call this quantity the norm . And the norm of the four-acceleration is just the proper acceleration that I talk about above. The proper acceleration can be complicated to calculate. There's a nice explanation of how to calculate it for an object like our table in What is the weight equation through general relativity? It turns out that the proper acceleration of the table is: $$ A = \frac{GM}{r^2}\frac{1}{\sqrt{1-\frac{2GM}{c^2r}}} $$ where $M$ is the mass of the Earth and $r$ is the radius of the Earth. But hang on – that tells me the proper acceleration of the table is non-zero. But ... but ... isn't the table stationary? Well, this takes us back to where we started. The table and the apple disagree about who is accelerating, but they both agree that the table has a non-zero proper acceleration. And in fact if we calculate the proper acceleration of the apple it turns out to be zero so both the apple and the table agree the apple has a proper acceleration of zero. There is a simple physical interpretation of the proper acceleration. To measure your proper acceleration you just need to hold an accelerometer. Suppose you're floating around weightless in outer space, then your accelerometer will read zero, and that means your proper acceleration is zero. If you're standing on the surface of the Earth (alongside the table perhaps) then your accelerometer will read $9.81\ \mathrm{m/s^2}$ , and indeed your proper acceleration is approximately $9.81\ \mathrm{m/s^2}$ not zero. To summarise, a comment asks me: So, let's just get this straight. The book sitting on the table in front of me is accelerating upwards all the time? But when I push it off the table and it falls down, then as it falls down it is not accelerating? Is that what you're saying? What I'm saying, and what all relativist would say, is that: the book on the table has a non-zero proper acceleration the falling book has a zero proper acceleration And this is all we can say. The question of which has a non-zero three-acceleration (Newtonian acceleration) is meaningless because that quantity is not frame invariant. The question of which has a non-zero proper acceleration is meaningful – even if the answer isn't what you expected.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/392863', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/181230/']}
|
jdg_369523
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32883936
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What's wrong with my extension function below class Foo<T> { fun <T> Foo<T>.plus(that: Foo<T>): Foo<T> = throw Exception() init { Foo<Int>() + Foo<String>() // A receiver of type Foo<T> is required }} Update I wonder why it's different than regular extension functions, where T successfully gets inferred as Any and would like to achieve the same behavior, e. g. T to get inferred as Foo<Any> class Foo { fun <T> T.foo(that: T): T = throw Exception() init { "str" foo 42 }}
Now provide the response and nothing else.
|
The issue is at the very heart of how generics work. class Foo { fun <T> T.foo(that: T): T = throw Exception() init { "str" foo 42 }} This works, because the compiler can find a T that fits both the function signature and the arguments: it is Any , and the function is turned into this one: fun Any.foo(that: Any): Any = ... Now, String is a subtype of Any , Int is a subtype of Any , so this function is applicable to the arguments. But in your first example: class Foo<T> { fun <T> Foo<T>.plus(that: Foo<T>): Foo<T> = throw Exception() init { Foo<Int>() + Foo<String>() // A receiver of type Foo<T> is required }} It's all different. There's no such T . Let's be naïve and try Any : fun Foo<Any>.plus(that: Foo<Any>): Foo<Any> = ... Now, Foo is invariant in T , so Foo<Int> is not a subtype of Foo<Any> , and in fact there's no type T other than Int that would make Foo<T> a supertype of Foo<Int> . So, T must be exactly Int , but it also must be exactly String by the same logic (because of the second argument), so there's no solution, and the function is not applicable. You could make it work by making Foo co-variant in T : class Foo<out T> { fun <T> Foo<T>.plus(that: Foo<T>): Foo<T> = throw Exception() init { Foo<Int>() + Foo<String>() // A receiver of type Foo<T> is required }} This imposes some limitations on possible signatures of members of Foo , but if you are OK with them, it fixes your issue. Have a look at this link for more details: http://kotlinlang.org/docs/reference/generics.html
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32883936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1351319/']}
|
jdg_369524
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30629974
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Bootstrap uses a custom attribute named data-toggle . How does this feature behave? Does using it require Bootstrap's JavaScript library? Also, which data-toggle options are available. So far, I count collapse tab modal dropdown What do each of these do? TLDR; What's the API for bootstrap's custom data-toggle attribute?
Now provide the response and nothing else.
|
I think you are a bit confused on the purpose of custom data attributes. From the w3 spec Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements. By itself an attribute of data-toggle=value is basically a key-value pair, in which the key is "data-toggle" and the value is "value". In the context of Bootstrap, the custom data in the attribute is almost useless without the context that their JavaScript library includes for the data. If you look at the non-minified version of bootstrap.js then you can do a search for "data-toggle" and find how it is being used. Here is an example of Bootstrap JavaScript code that I copied straight from the file regarding the use of "data-toggle". Button Toggle Button.prototype.toggle = function () { var changed = true var $parent = this.$element.closest('[data-toggle="buttons"]') if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') == 'radio') { if ($input.prop('checked') && this.$element.hasClass('active')) changed = false else $parent.find('.active').removeClass('active') } if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change') } else { this.$element.attr('aria-pressed', !this.$element.hasClass('active')) } if (changed) this.$element.toggleClass('active')} The context that the code provides shows that Bootstrap is using the data-toggle attribute as a custom query selector to process the particular element. From what I see these are the data-toggle options: collapse dropdown modal tab pill button(s) You may want to look at the Bootstrap JavaScript documentation to get more specifics of what each do, but basically the data-toggle attribute toggles the element to active or not.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30629974', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/712526/']}
|
jdg_369525
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
44806076
|
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 use a calculator, 2/3 is 0.6666666667 which is about 67% . However if I try to do the same thing with css calc I get an error. width: calc(2 / 3); Is there a working way for this? I don't think it looks that good writing it like 0.666666666667 . Any ideas are welcome.
Now provide the response and nothing else.
|
The problem is with calc(2 / 3) you will just get a number without an unit. CSS can't display just a number as width. This would be like if you set width: 3 which obviously doesn't work. If you want the percentage you will need to muliply it by 100% width: calc(2 / 3 * 100%); and if you really want the result in pixels multiply it by 1px width: calc(2 / 3 * 1px);
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44806076', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/148496/']}
|
jdg_369526
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
121778
|
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:
From Polymorphism on WIkipedia In computer science, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface. From duck typing on Wikipedia In computer programming with object-oriented programming languages, duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface. My interpretation is that based on duck typing, the objects methods/properties determine the valid semantics. Meaning that the objects current shape determines the interface it upholds. From polymorphism you can say a function is polymorphic if it accepts multiple different data types as long as they uphold an interface. So if a function can duck type, it can accept multiple different data types and operate on them as long as those data types have the correct methods/properties and thus uphold the interface. (Usage of the term interface is meant not as a code construct but more as a descriptive, documenting construct) What is the correct relationship between ducktyping and polymorphism ? If a language can duck type, does it mean it can do polymorphism ?
Now provide the response and nothing else.
|
I say that polymorphism is a generic trait, that can be implemented several ways: class based inheritance. prototype based objects (with or without inheritance) duck typing interface compliance (as done by Go's interfaces and implicitly on C++ templates) each of them allows the programmer to use a single code with different types, so all embody the concept of polymorphism.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/121778', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/4642/']}
|
jdg_369527
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
49218599
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Rust's std::process::Command allows configuring the process' stdin via the stdin method, but it appears that that method only accepts existing files or pipes. Given a slice of bytes, how would you go about writing it to the stdin of a Command ?
Now provide the response and nothing else.
|
You can create a stdin pipe and write the bytes on it. As Command::output immediately closes the stdin, you'll have to use Command::spawn . Command::spawn inherits stdin by default. You'll have to use Command::stdin to change the behavior. Here is the example ( playground ): use std::io::{self, Write};use std::process::{Command, Stdio};fn main() -> io::Result<()> { let mut child = Command::new("cat") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn()?; let child_stdin = child.stdin.as_mut().unwrap(); child_stdin.write_all(b"Hello, world!\n")?; // Close stdin to finish and avoid indefinite blocking drop(child_stdin); let output = child.wait_with_output()?; println!("output = {:?}", output); Ok(())}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49218599', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/836390/']}
|
jdg_369528
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
529
|
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to find stock pairs that exhibit low correlation. If the correlation between A and B is 0.9 and the correlation between A and C is 0.9 is there a minimum possible correlation for B and C? I'd like to save on search time so if I know that it is mathematically impossible for B and C to have a correlation below some arbitrary level based on A to B and A to C's correlations I obviously wouldn't have to waste time calculating the correlation of B and C. Is there such a "law"? If not, what are other methods of decreasing the search time?
Now provide the response and nothing else.
|
Yes, there is such a rule and it is not too hard to grasp. Consider the 3-element correlation matrix $$\left(\begin{matrix} 1 & r & \rho \\ r & 1 & c \\ \rho & c & 1\end{matrix}\right)$$ which must be positive semidefinite . In simpler terms, that means all its eigenvalues must be nonnegative. Assuming that $\rho$ and $r$ are known positive values, we find that the eigenvalues of this matrix go negative when \begin{equation} c<\rho r-\sqrt{1-\rho ^2+\rho ^2 r^2-r^2}.\end{equation} Therefore the right hand side of this expression is the lower bound for the AC correlation $c$ that you seek, with $\rho$ being the AB correlation and $r$ being the BC correlation.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://quant.stackexchange.com/questions/529', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/352/']}
|
jdg_369529
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1610862
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So, I'd like to know how many results I'll be getting back from a RESTful uri GET request. I don't know of any way to do that at this point. Is there a way to do that? Since REST just throws out properties, I don't know if it is able to take a count of its results, but it can skip results and take a subset of results. Anybody have any suggestions? Oh my setup is a LINQ to SQL that populates a queriable generic List. The data service makes that list available. I've tried getting a count on the list, but I always get the max rows of the database back, and that isn't what I'm looking for.
Now provide the response and nothing else.
|
Other people might have objections to this concept, but, this seems reasonable to me: HEAD /your/api HTTP/1.1HTTP/1.1 200 OKDate: Fri, 23 Oct 2009 00:58:17 GMTContent-Type: application/xml; charset=UTF-8Content-Length: 89X-Result-Count: 100000000 And then: GET /your/api HTTP/1.1HTTP/1.1 200 OKDate: Fri, 23 Oct 2009 00:58:17 GMTContent-Type: application/xml; charset=UTF-8Content-Length: 89X-Result-Count: 100000000<?xml version="1.0" encoding="UTF-8"?><results> 100000000 results go here.</results> Note: A HEAD request is used here to obtain the count without having to pull the full data set. HEAD requests retrieve only the HTTP headers, not the body of the response. This would be the most RESTful way I can think of indicating how many results you're gonna get back before you send it over the wire. The main trick is just coming up with the best header name for it. X-Result-Count is decent, but if you can find prior art and reuse their header name choice, that would be even better (as long as they didn't name it something really dumb). That said, I don't expect you'll have much luck, so you should probably stick with X-Result-Count . Also, I think you may have misunderstood what "REST" actually entails. There's no reason you can't give a representation by range. For example: GET /your/api?page=1&perpage=10 HTTP/1.1HTTP/1.1 200 OKDate: Fri, 23 Oct 2009 00:58:17 GMTContent-Type: application/xml; charset=UTF-8Content-Length: 101X-Result-Count: 10<?xml version="1.0" encoding="UTF-8"?><results> First 10 results of 100000000 go here.</results> However, to be RESTful, you need to be able to tell the client about the representation identified by /your/api?range=0-9 or /your/api?page=1&perpage=10 without using out-of-band information. For example, if your /your/api page would return too many results, do a temporary redirect to /your/api?page=1&perpage=10 , and include hyperlinks to /your/api?page=2&perpage=10 . Note that a hyperlink in this context could be something simple like: <?xml version="1.0" encoding="UTF-8"?><results> <result> This is a result. </result> <result> This is also a result. </result> <link rel="next" href="/your/api?page=3&perpage=2" /> <link rel="prev" href="/your/api?page=1&perpage=2" /></results> Now the information to navigate the results of your API calls is in-band and actually RESTful. Essentially, REST is plain-old-HTTP with caching done right and usually sensible URIs thrown in for good measure. It's also "hypertext as the engine of application state" (i.e. resources should link to other resources). It is not a protocol, it's an architectural style. Anyone who tells you differently had better be named Roy Fielding. http://roy.gbiv.com/untangled/2009/it-is-okay-to-use-post http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven#comment-718 Addenda: If you want to indicate the total count versus the page count, you can define the header like so: X-Result-Count: 0-9/100000000 Or adjust as necessary.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1610862', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/173464/']}
|
jdg_369530
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31418005
|
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 increase the timeout for mocha tests as they are web requests that form part of an automated UI test suite and therefore can take longer than the default 2000ms. The code itself works great if I call mocha with the --timeout set to 5000ms or so but the default 2000ms is not enough. I want to be able to set the timeout per test suite so that the timeout becomes part of the success criteria which might be different on a case by case basis. before(()=>{ var sw = require('selenium-webdriver'); this.driver = new sw.Builder().withCapabilities(sw.Capabilities.chrome()).build(); var c = require('chai'); c.use(require('chai-webdriver')(this.driver)); this.expect = c.expect; return this.driver.getWindowHandle();})after(() => { return this.driver.quit();})describe('Looking at github', () => { beforeEach(() => { this.driver.get('http://stackoverflow.com/'); }) describe('When we take a look at the stack overflow home page', () => { return it('It does not have crazy cat text in it!', () => { return this.expect('#h-top-questions').dom.to.not.contain.text("Just cats here!"); }); });})
Now provide the response and nothing else.
|
Use function intead of an arrow and then just call this.timeout(5000); e.g. describe('When we take a look at the stack overflow home page', () => { return it('It does not have crazy cat text in it!', function() { this.timeout(5000); return this.expect('#h-top-questions').dom.to.not.contain.text("Just cats here!"); }); }); This is because ()=> captures the surrounding this . More http://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31418005', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/184383/']}
|
jdg_369531
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
47823639
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Readings: From this answer : This is what the accepted answer suggests to animate your view changes: _addBannerDistanceFromBottomConstraint.constant = 0UIView.animate(withDuration: 5) { self.view.layoutIfNeeded()} Why do we call layoutIfNeeded when we aren't changing the frames. We are changing the constraints, so (according to this other answer ) shouldn't we instead be calling setNeedsUpdateConstraints ? Similarly this highly viewed answer says: If something changes later on that invalidates one of your constraints, you should remove the constraint immediately and call setNeedsUpdateConstraints Observations: I actually did try using them both.Using setNeedsLayout my view animates correctly to the left import UIKitclass ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBAction func animate(_ sender: UIButton) { UIView.animate(withDuration: 1.8, animations: { self.centerXConstraint.isActive = !self.centerXConstraint.isActive self.view.setNeedsLayout() self.view.layoutIfNeeded() }) } @IBOutlet weak var centerYConstraint: NSLayoutConstraint! @IBOutlet var centerXConstraint: NSLayoutConstraint!} However using setNeedsUpdateConstraints doesn't animate, It just moves the view rapidly to the left . import UIKitclass ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBAction func animate(_ sender: UIButton) { UIView.animate(withDuration: 1.8, animations: { self.centerXConstraint.isActive = !self.centerXConstraint.isActive self.view.setNeedsUpdateConstraints() self.view.updateConstraintsIfNeeded() }) } @IBOutlet weak var centerYConstraint: NSLayoutConstraint! @IBOutlet var centerXConstraint: NSLayoutConstraint!} If I don't want animation then using either of view.setNeedsLayout or view.setNeedsUpdateConstraints move it to the left. However: with view.setNeedsLayout , after my button is tapped, my viewDidLayoutSubviews breakpoint is reached. But the updateViewConstraints breakpoint is never reached. This leaves me baffled as to how the constraints are getting updated... with view.setNeedsUpdateConstraints , after the button is tapped my updateViewConstraints breakpoint is reached and then the viewDidLayoutSubviews breakpoint is reached. This does make sense, the constraints are updated, then the layoutSubviews is called. Questions: Based on my readings: if you change constraints then for it to become effective you MUST call setNeedsUpdateConstraints , but based on my observations that's wrong. Having the following code was enough to animate: self.view.setNeedsLayout()self.view.layoutIfNeeded() WHY? Then I thought maybe somehow under the hoods it's updating the constraints through other means. So I placed a breakpoint at override func updateViewConstraints and override func viewDidLayoutSubviews but only the viewDidLayoutSubviews reached its breakpoint. So how is the Auto Layout engine managing this?
Now provide the response and nothing else.
|
This is a common misunderstanding among iOS developers. Here's one of my "golden rules" for Auto Layout: Don't bother about "updating constraints" . You never need to call any of these methods: setNeedsUpdateConstraints() updateConstraintsIfNeeded() updateConstraints() updateViewConstraints() except for the very rare case that you have a tremendously complex layout which slows down your app (or you deliberately choose to implement layout changes in an atypical way). The Preferred Way to Change Your Layout Normally, when you want to change your layout, you would activate / deactivate or change layout constraints directly after a button tap or whichever event triggered the change, e.g. in a button's action method: @IBAction func toggleLayoutButtonTapped(_ button: UIButton) { toggleLayout()}func toggleLayout() { isCenteredLayout = !isCenteredLayout if isCenteredLayout { centerXConstraint.isActive = true } else { centerXConstraint.isActive = false }} As Apple puts it in their Auto Layout Guide : It is almost always cleaner and easier to update a constraint immediately after the affecting change has occurred. Deferring these changes to a later method makes the code more complex and harder to understand. You can of course also wrap this constraint change in an animation: You first perform the constraint change and then animate the changes by calling layoutIfNeeded() in the animation closure: @IBAction func toggleLayoutButtonTapped(_ button: UIButton) { // 1. Perform constraint changes: toggleLayout() // 2. Animate the changes: UIView.animate(withDuration: 1.8, animations: { view.layoutIfNeeded() }} Whenever you change a constraint, the system automatically schedules a deferred layout pass, which means that the system will recompute the layout in the near future. No need to call setNeedsUpdateConstraints() because you just did update (change) the constraint yourself! What needs to be updated is the layout i.e. the frames of all your views, not any other constraint. The Principle of Invalidation As previously stated, the iOS layout system usually doesn't react immediately to constraint changes but only schedules a deferred layout pass. That's for performance reasons. Think of it like this: When you go shopping groceries, you put an item in your cart but you don't pay it immediately. Instead, you put other items in your cart until you feel like you got everything you need. Only then you proceed to the cashier and pay all your groceries at once. It's way more efficient. Due to this deferred layout pass there is a special mechanism needed to handle layout changes. I call it The Principle of Invalidation . It's a 2-step mechanism: You mark something as invalid. If something is invalid, you perform some action to make it valid again. In terms of the layout engine this corresponds to: setNeedsLayout() layoutIfNeeded() and setNeedsUpdateConstraints() updateConstraintsIfNeeded() The first pair of methods will result in an immediate (not deferred) layout pass: First you invalidate the layout and then you recompute the layout immediately if it's invalid (which it is, of course). Usually you don't bother if the layout pass will happen now or a couple of milliseconds later so you normally only call setNeedsLayout() to invalidate the layout and then wait for the deferred layout pass. This gives you the opportunity to perform other changes to your constraints and then update the layout slightly later but all at once (→ shopping cart). You only need to call layoutIfNeeded() when you need the layout to be recomputed right now . That might be the case when you need to perform some other calculations based on the resulting frames of your new layout. The second pair of methods will result in an immediate call of updateConstraints() (on a view or updateViewConstraints() on a view controller). But that's something you normally shouldn't do. Changing Your Layout in a Batch Only when your layout is really slow and your UI feels laggy due to your layout changes you can choose a different approach than the one stated above: Rather than updating a constraint directly in response to a button tap you just make a "note" of what you want to change and another "note" that your constraints need to be updated. @IBAction func toggleLayoutButtonTapped(_ button: UIButton) { // 1. Make a note how you want your layout to change: isCenteredLayout = !isCenteredLayout // 2. Make a note that your constraints need to be updated (invalidate constraints): setNeedsUpdateConstraints()} This schedules a deferred layout pass and ensures that updateConstraints() / updateViewConstraints() will be called during the layout pass. So you may now even perform other changes and call setNeedsUpdateConstraints() a thousand times – your constraints will still only be updated once during the next layout pass. Now you override updateConstraints() / updateViewConstraints() and perform the necessary constraint changes based on your current layout state (i.e. what you have "noted" above in "1."): override func updateConstraints() { if isCenteredLayout { centerXConstraint.isActive = true } else { centerXConstraint.isActive = false } super.updateConstraints()} Again, this is only your last resort if the layout is really slow and you're dealing will hundreds or thousands of constraints. I have never needed to use updateConstraints() in any of my projects, yet. I hope this make things a little clearer. Additional resources: Auto Layout – From Leading to Trailing : my talk from UIKonf 2017, topics: "The Layout Pass" and "Updating Constraints" The Auto Layout Comprehendium™ : scroll down to section "Updating Constraints", maintained by me The Auto Layout Guide by Apple: sections "Changing Constraints" "The Deferred Layout Pass"
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/47823639', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5175709/']}
|
jdg_369532
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28126314
|
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 understand that this is NOT the standard use case, but I need to dynamically add elements to a IntEnum derived class in Python. Notice that dynamically creating the Enum using the functional API is not enough. I need to add elements to an existing enum. How can I do this? Background: For those of you wondering why would somebody want to do this. I am wrapping a library and the values for the enum are defined within the library. I can query the names and values using the library API. But I cannot do it upon initialization as it depends on components which are dynamically loaded by the library upon user request. I could load all components at start up and use the functional API to create the enum upon import but this is time consuming and has side effects.
Now provide the response and nothing else.
|
Enums are immutable , that's rather the point. You can create a new enum that replaces the original instead: from enum import Enumnames = [m.name for m in ExistingEnum] + ['newname1', 'newname2']ExistingEnum = Enum('ExistingEnum', names) but any existing references (say, in other modules) would continue to use the old definition. names can be: A string containing member names, separated either with spaces or commas. Values are incremented by 1 from start (which can be set as a keyword argument and defaults to 1). An iterable of member names (as in the code above). Values are incremented by 1 from start . An iterable of (member name, value) pairs. A mapping of member name -> value pairs.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28126314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/482819/']}
|
jdg_369533
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48263334
|
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 having trouble setting the timeout properly on nanomsg python in the PUSH/PULL schema. I use the set socket option function and passing in a ctype object. Both set_sock_options return a success. Am I missing something? The sockets work to receive and send, but have an infinite timeout. When I use get_sock_option it returns the value I just set, so it seems my inputs have some sort of an effect. NN_RCVTIMEO = 5NN_SNDTIMEO = 4NN_SOL_SOCKET = 0message = ""timeout = ctypes.create_string_buffer(b'500');#Bind input socketsocket_in = nn_wrapper.nn_socket(AF_SP, PULL)sucess = nn_wrapper.nn_setsockopt(socket_in, NN_SOL_SOCKET, NN_RCVTIMEO, timeout)nn_wrapper.nn_bind(socket_in, 'tcp://127.0.0.1:64411')time.sleep(0.2)print("SUCESS?" + str(sucess))#Send inquirysocket_out = nn_wrapper.nn_socket(AF_SP, PUSH)sucess = nn_wrapper.nn_setsockopt(socket_out, NN_SOL_SOCKET, NN_SNDTIMEO, timeout)nn_wrapper.nn_connect(socket_out, 'tcp://127.0.0.1:64400')time.sleep(0.2)print("SUCESS?" + str(sucess))nn_wrapper.nn_send(socket_out, b'HELLO',0)#Received...bytes, message = nn_wrapper.nn_recv(socket_in, 0)nn_wrapper.nn_close(socket_in)nn_wrapper.nn_close(socket_out)
Now provide the response and nothing else.
|
You can get the status of each download by visiting chrome://downloads/ with the driver. To wait for all the downloads to finish and to list all the paths: def every_downloads_chrome(driver): if not driver.current_url.startswith("chrome://downloads"): driver.get("chrome://downloads/") return driver.execute_script(""" var items = document.querySelector('downloads-manager') .shadowRoot.getElementById('downloadsList').items; if (items.every(e => e.state === "COMPLETE")) return items.map(e => e.fileUrl || e.file_url); """)# waits for all the files to be completed and returns the pathspaths = WebDriverWait(driver, 120, 1).until(every_downloads_chrome)print(paths) Was updated to support changes till version 81.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/48263334', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7377501/']}
|
jdg_369534
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
46431762
|
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 classes which are usually using standard containers as underlying fields. For example, I have a class template <typename T>class Vec_3D{public: /* ... */ std::array<T, 3> vec; /* ... */}; which has only one variable vec and the rest are just functions I need when working with vectors. I want to be able to use range-based for loop such as Vec_3D<double> vec;for (double val : vec) {/*...*/} which should obviusly iterate over std::array<double, 3> . How to implement iterators in my class which should in turn call iterators of std::array<T, 3> ? I started with this question and tried to define iterators in my class as typedef std::iterator<std::random_access_iterator_tag, T, ptrdiff_t, T*, T&> iterator;typedef std::iterator<std::random_access_iterator_tag, const T, ptrdiff_t, const T*, const T&> const_iterator;inline iterator begin() noexcept { return vec.begin(); }inline const_iterator cbegin() const noexcept { return vec.cbegin(); }inline iterator end() noexcept { return vec.end(); }inline const_iterator cend() const noexcept { return vec.end(); } but got compiling errors error: no match for ‘operator!=’ (operand types are ‘Vec_3D<double>::iterator {aka std::iterator<std::random_access_iterator_tag, double, long int, double*, double&>}’ and ‘Vec_3D<double>::iterator {aka std::iterator<std::random_access_iterator_tag, double, long int, double*, double&>}’) and operator++, operator*
Now provide the response and nothing else.
|
A range-based for loop only requires that your class have begin() and end() methods (or overloads of std::begin() and std::end() ) that return iterators. It doesn't care where those iterators come from. So, the simplest solution is to just use the array's own iterators instead of trying to define your own, eg: template <typename T>class Vec_3D{public: typedef typename std::array<T, 3> array_type; typedef typename array_type::iterator iterator; typedef typename array_type::const_iterator const_iterator; // or: // using array_type = std::array<T, 3>; // using iterator = array_type::iterator; // using const_iterator = array_type::const_iterator; ... inline iterator begin() noexcept { return vec.begin(); } inline const_iterator cbegin() const noexcept { return vec.cbegin(); } inline iterator end() noexcept { return vec.end(); } inline const_iterator cend() const noexcept { return vec.cend(); } ...private: array_type vec;};
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46431762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4732666/']}
|
jdg_369535
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10898873
|
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 got many lines in a row which may throw an exception, but no matter what, it should still continue the next line. How to do this without individually try catching every single statement that may throw an exception? try: this_may_cause_an_exception() but_I_still_wanna_run_this() and_this() and_also_this()except Exception, e: logging.exception('An error maybe occured in one of first occuring functions causing the others not to be executed. Locals: {locals}'.format(locals=locals())) Let's see above code, all functions may throw exceptions, but it should still execute the next functions no matter if it threw an exception or not. Is there a nice way of doing that? I dont wanna do this: try: this_may_cause_an_exception()except: passtry: but_I_still_wanna_run_this()except: passtry: and_this()except: passtry: and_also_this()except: pass I think code should still continue to run after an exception only if the exception is critical (The computer will burn or the whole system will get messed up, it should stop the whole program, but for many small things also exceptions are thrown such as connection failed etc.)I normally don't have any problems with exception handling, but in this case I'm using a 3rd party library which easily throws exceptions for small things. After looking at m4spy's answer, i thought wouldn't it be possible, to have a decorator which will let every line in the function execute even if one of them raises an exception. Something like this would be cool: def silent_log_exceptions(func): @wraps(func) def _wrapper(*args, **kwargs): try: func(*args, **kwargs) except Exception: logging.exception('...') some_special_python_keyword # which causes it to continue executing the next line return _wrapper Or something like this: def silent_log_exceptions(func): @wraps(func) def _wrapper(*args, **kwargs): for line in func(*args, **kwargs): try: exec line except Exception: logging.exception('...') return _wrapper@silent_log_exceptionsdef save_tweets(): a = requests.get('http://twitter.com) x = parse(a) bla = x * x
Now provide the response and nothing else.
|
for func in [this_may_cause_an_exception, but_I_still_wanna_run_this, and_this, and_also_this]: try: func() except: pass There are two things to notice here: All actions you want to perform have to represented by callables with the same signature (in the example, callables that take no arguments). If they aren't already, wrap them in small functions, lambda expressions, callable classes, etc. Bare except clauses are a bad idea, but you probably already knew that. An alternative approach, that is more flexible, is to use a higher-order function like def logging_exceptions(f, *args, **kwargs): try: f(*args, **kwargs) except Exception as e: print("Houston, we have a problem: {0}".format(e))
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10898873', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/376445/']}
|
jdg_369536
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26271
|
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:
How can a Population III star have a mass of several hundred solar masses? Normally the limit is about 100 solar masses.
Now provide the response and nothing else.
|
I think there are really three questions that need to be answered for this to make sense: is there a "normal" limit to how large a star can be? how can population III stars form with such large masses? how can population III stars retain their large masses? An answer to the first question is tricky. We expect large stars to be rare, and the largest stars to be the rarest. On top of this, they'll lead the shortest lives. Getting observational constraints has thus been tricky. There might be a limit to the amount of mass that is available to turn into stars when they form. As for the "normal" limits on the masses of stars, most (as far as I know) involve around pulsational instability. But the recent discovery of massive stars in and near the cluster R136a suggests that stars with masses over 150 solar can form even in material that has a non-negligible metal content. So whether there is a "normal" limit is open question. The second question is much better understood, thanks to a lot of numerical work. Tom Abel recently wrote an article for Physics Today that summarizes current understanding of pop III star formation. Basically, the smallest amount of gas unstable to collapse under its own gravity, the Jeans Mass , increases with temperature (like T 3/2 ). So the cooler the gas can become, the smaller the fragments we expect to see. What determines how cool the gas can become? The atoms and molecules that radiate within it, and whether this radiation can escape. In metal-polluted gas, various molecular and atomic lines allow the gas to cool to tens of K. In metal-free material, the most effective coolant (in terms of the low temperatures it can achieve) is molecular hydrogen, which will only cool to around 200 K. This is a higher temperature, so we expect more massive fragments. This is a gross simplification! The situation really involves complex dynamics, shock formation, and all sorts of other stuff. Even the question of whether or not molecular hydrogen can form is contested. Finally, if a massive pop III star formed, would it keep its mass? We know that the some massive stars in the local universe, like Eta Carinae , are violent beasts. This kind of episodic, pulsational mass loss could be present in Pop III stars, but since such mass loss is so poorly understood, this is often ignored. More generally, we expect that the metals in the atmospheres of massive stars absorb enough of the radiation created inside the star to be driven away in a wind. Again, there aren't any metals in metal-free gas, so we expect this effect to be much smaller in Pop III stars. So, we expect Pop III stars to be larger because there is more gas available, because the gas fragments less owing to its higher temperature, and because we don't think the stars lose as much mass as modern stars do. And, we aren't even sure that there's a limit on how massive stars can be in the first place!
|
{}
|
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/26271', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/174/']}
|
jdg_369537
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
429660
|
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:
Dave Thomas, the author of the Don't Repeat Yourself principle said : DRY says that every piece of system knowledge should have oneauthoritative, unambiguous representation. Every piece of knowledge inthe development of something should have a single representation. Asystem's knowledge is far broader than just its code. It refers todatabase schemas, test plans, the build system, even documentation. I have difficulty to understand how it applies to programming code documentation. Java API has the java.util.Arrays class with the copyOf method that is overloaded 7 times. The 8 methods can be documented in two ways containing the same information. The first way describes all overloaded methods using a single description, highlighting the differences between overloads. The second way describes each overloaded method using a separate description. Below are both ways - I bolded the differences in the content. The second way was literally copied from the API documentation of the java.util.Arrays class. Is the second way compliant with the DRY principle? In my opinion it isn't, because it contains text which was copied multiple times, then, additionally, minor modifications were made to each copy. The same information can be provided in one text, which is almost eight times shorter. But I am not sure if I understand correctly the definition of the DRY principle. What are the "pieces of system knowledge" in this case? Do they have single, unambiguous, authoritative representation in the quoted documentation? Documentation of the overloaded copyOf() methods - 1st way public static byte[] copyOf(byte[] original, int newLength)public static short[] copyOf(short[] original, int newLength)public static int[] copyOf(int[] original, int newLength)public static long[] copyOf(long[] original, int newLength)public static float[] copyOf(float[] original, int newLength)public static double[] copyOf(double[] original, int newLength)public static char[] copyOf(char[] original, int newLength)public static boolean[] copyOf(boolean[] original, int newLength) Copies the specified array, truncating or padding with the defaultvalues (if necessary) so the copy has the specified length. For allindices that are valid in both the original array and the copy, thetwo arrays will contain identical values. For any indices that arevalid in the copy but not the original, the copy will contain thedefault value . Such indices will exist if and only if the specifiedlength is greater than that of the original array. The following table lists default values for given type of array elements: type the default value of type byte , short , int , long 0 float , double 0.0 char null character ('\u0000') boolean false Parameters: original - the array to be copied newLength - the length of the copy to be returned Returns: a copy of the original array, truncated or padded with thedefault values to obtain the specified length Throws: NegativeArraySizeException - if newLength is negative NullPointerException - if original is null Since: 1.6 Documentation of the overloaded copyOf() methods - 2nd way public static byte[] copyOf(byte[] original, int newLength) Copies the specified array, truncating or padding with zeros (ifnecessary) so the copy has the specified length. For all indices thatare valid in both the original array and the copy, the two arrays willcontain identical values. For any indices that are valid in the copybut not the original, the copy will contain (byte)0 . Such indiceswill exist if and only if the specified length is greater than that ofthe original array. Parameters: original - the array to be copied newLength - the length of the copy to be returned Returns: a copy of the original array, truncated or padded with zeros to obtain the specified length Throws: NegativeArraySizeException - if newLength is negative NullPointerException - if original is null Since: 1.6 public static short[] copyOf(short[] original, int newLength) Copies the specified array, truncating or padding with zeros (ifnecessary) so the copy has the specified length. For all indices thatare valid in both the original array and the copy, the two arrays willcontain identical values. For any indices that are valid in the copybut not the original, the copy will contain (short)0 . Such indiceswill exist if and only if the specified length is greater than that ofthe original array. Parameters: original - the array to be copied newLength - the length of the copy to be returned Returns: a copy of the original array, truncated or padded with zeros to obtain the specified length Throws: NegativeArraySizeException - if newLength is negative NullPointerException - if original is null Since: 1.6 and so on for: int, long, float, double, char, boolean. It is exactly the same text, eight times, where only the bold parts are different.
Now provide the response and nothing else.
|
About this specific problem: From a technical perspective for me, the documentation of Array.copyOf is DRY, from my Developer perspective it is not. The relevant information of each method are the input parameters, the output, the special behavior for different lengths, the possible errors. Those are nearly identical over all overloaded implementations. From a technical perspective, each overloaded method could in theory behave differently. That means even if that is not the case now, it could in the future. Therefore those information are the same, but not identical. Therefor "repeating" it is absolutely correct and is not violating the DRY principle. On the other side, the intention of the whole method is to provide the absolutely same functionality for different data types. That means, the intention is, that those functions will evolve equally. Then those information are not just the same, but identical. Therefore from this perspective the documentation is violating the DRY principle. When WE are in such a situation to decide how to write a documentation and should we follow DRY or not: The question is what we want to achieve.DRY is not a goal. It's a strategy to achieve a goal. If you want that you don’t have to change much in the documentation, when your code changes, then use DRY. But , as in code, this comes with a cost. It means you will have to write more "generic" documentation. Generics are in most cases more complex, that means harder to understand. Hmm that is violating the KISS (keep it simple, stupid) principle now? Yep :-( Therefore the first question is, what do you want to achieve. And then you have to balance the principles. For example, if I have some code that will change very rarely, and people will often need some functions of it, but rarely all of them, then I would prefer the approach with describing each function independently. It makes understanding easier and the additional maintaining effort is not that important, because my expectation is that there will not be so many changes. If my code changes often, and/or most people will need the whole thing and not only parts, then a more condensed, generic style would be appropriate. Therefore, in my eyes we should know those principles. And never completely ignore them. But it's not about following a principle blindly, but about realising which principle will support me in the current context the best to achieve my specific goals. In my experience, the hardest part is to determine good, precise, goals. But that's another topic. :-) Updated (added the initial part) because the question was sharpened. Thanks @iwis for the question.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/429660', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/354706/']}
|
jdg_369538
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4414768
|
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 section of a webpage that I only want people to be able to access after clicking a Facebook Like button. How do I hide that particular area and then display it only after someone clicks the Like button. As for the Facebook Like code it looks like this: <script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="www.oursite.com" show_faces="false" width="330" font="verdana"></fb:like><div id="hidden-area">Hidden Content</div>
Now provide the response and nothing else.
|
Use 'edge.create': http://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe really simple... can even couple it with jQuery. <script> window.fbAsyncInit = function() { FB.init({ appId : '<?php echo $facebook->getAppId(); ?>', session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true // parse XFBML }); // whenever the user logs in, we refresh the page FB.Event.subscribe('auth.login', function() { window.location.reload(); }); FB.Event.subscribe('edge.create', function(response) { $.get('URLlink?uid=' + <?php echo $uid; ?>, function(data) { $('#id').html(data); }); }); }; (function() { var e = document.createElement('script'); e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; e.async = true; document.getElementById('fb-root').appendChild(e); }());</script>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4414768', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/64346/']}
|
jdg_369539
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12632834
|
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 answer to this question does not appear to work on xcode 4.5. To summarise it, is there a way for XCode to warn about classes, methods and procedures that are only available a later version than the deployment target?
Now provide the response and nothing else.
|
There is a correct answer inside of the question that you linked too. With some experimentation, I came up with this (from mattjgalloway's answer): #define __AVAILABILITY_TOO_NEW __attribute__((deprecated("TOO NEW!"))) __attribute__((weak_import))#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_6_0#undef __AVAILABILITY_INTERNAL__IPHONE_6_0#define __AVAILABILITY_INTERNAL__IPHONE_6_0 __AVAILABILITY_TOO_NEW#endif Then repeat for all the versions that make sense (i.e. 4.3 and above for Xcode 4.5). The __IPHONE_OS_VERSION_MIN_REQUIRED macro will check the deployment target.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12632834', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/89806/']}
|
jdg_369540
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.