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
1614938
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have the fraction:$$\frac{\left(2 \left(\frac {a}{\sqrt{2}}\right) + a \right) a} {2(1 + \sqrt{2})a^2}$$ Using Mathematica, I've found that this simplifies to $\frac{1}{2}$, but how did it achieve the result? How can I simplify that fraction to $\frac12$? Now provide the response and nothing else.
$$\frac{(2(\frac {a}{\sqrt{2}})+a)a} {2(1+\sqrt{2})a^2}=\frac{(\sqrt{2}a+a)a} {2(1+\sqrt{2})a^2}=\frac{(\sqrt{2}+1)a^2} {2(1+\sqrt{2})a^2}={1\over2}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1614938', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/305676/']}
jdg_371541
stackexchange
llm_judgeable_groundtruth_similarity
25442595
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 built a multi filter search for my website but I cant seem to find any documentation on multiple if statements inside of where for my search. Returns Lots of Results $data = Scrapper::paginate(15); Returns none.. need it to be this way to have where statements with IF see bellow. $database = new Scrapper;$database->get(); Example of what I want to do.. $database = new Scrapper; if (isset($_GET['cat-id'])) { $database->where('cat_id', '=', $_GET['cat-id']); } if (isset($_GET['band'])) { $database->where('price', 'BETWEEN', $high, 'AND', $low); } if (isset($_GET['search'])) { $database->where('title', 'LIKE', '%'.$search.'%'); } $database->get(); Now provide the response and nothing else.
Very similar to this: Method Chaining based on condition You are not storing each query chains. $query = Scrapper::query();if (Input::has('cat-id')) { $query = $query->where('cat_id', '=', Input::get('cat-id'));}if (Input::has('band')) { $query = $query->whereBetween('price', [$high, $low]);}if (Input::has('search')) { $query = $query->where('title', 'LIKE', '%' . Input::get($search) .'%');}// Get the results// After this call, it is now an Eloquent model$scrapper = $query->get();var_dump($scrapper);
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25442595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1583972/']}
jdg_371542
stackexchange
llm_judgeable_groundtruth_similarity
63563
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am working in a lab and have configured a series of /125 subnets between routers. Lets ignore the best practice for this discussion of using /64 for everything. When I assign fd00:f9a8:ffff::257 to an interface, there is no issue with the configuration, however when I assign fd00:f9a8:ffff::254 the OS reports that DAD has failed and does not permanently assign the interface. I've seen a number of sources indicate that the all zero address fd00:f9a8:feed:beef::/64 is just as valid as a host address as fd00:f9a8:feed:beef::1/64. Is this inaccurate and if so, what would cause DAD to fail with the first address in this /125 subnet? Now provide the response and nothing else.
The first IPv6 address in a network is assignable, but it is the router anycast address, one of several required anycast addresses. (Anycast addresses are unicast addresses that are assigned to multiple hosts.) This is defined by RFC 4291, IP Version 6 Addressing Architecture : 2.6.1 . Required Anycast Address The Subnet-Router anycast address is predefined. Its format is asfollows: | n bits | 128-n bits |+------------------------------------------------+----------------+| subnet prefix | 00000000000000 |+------------------------------------------------+----------------+ The "subnet prefix" in an anycast address is the prefix thatidentifies a specific link. This anycast address is syntactically thesame as a unicast address for an interface on the link with theinterface identifier set to zero. Packets sent to the Subnet-Router anycast address will be delivered toone router on the subnet. All routers are required to support theSubnet-Router anycast addresses for the subnets to which they haveinterfaces. The Subnet-Router anycast address is intended to be used forapplications where a node needs to communicate with any one of the setof routers. Some devices, e.g. Cisco routers, require special handling of the router anycast address. Cisco requires the anycast keyword be placed on the address, but you also assign another address to the interface because the anycast address is shared among the routers. There are also some reserved subnet anycast addresses: They MUST NOT be used for unicast addresses assigned to any interface. See RFC 2526, Reserved IPv6 Subnet Anycast Addresses : 2 . Format of Reserved Subnet Anycast Addresses Within each subnet, the highest 128 interface identifier values arereserved for assignment as subnet anycast addresses. The construction of a reserved subnet anycast address depends on thetype of IPv6 addresses used within the subnet, as indicated by theformat prefix in the addresses. In particular, for IPv6 address typesrequired to have 64-bit interface identifiers in EUI-64 format, theuniversal/local bit MUST be set to 0 (local) in all reserved subnetanycast addresses, to indicate that the interface identifier in theaddress is not globally unique. IPv6 addresses of this type arecurrently specified to be those having format prefixes 001 through111, except for Multicast Addresses (1111 1111) [3]. Specifically, for IPv6 address types required to have to have 64-bitinterface identifiers in EUI-64 format, these reserved subnet anycastaddresses are constructed as follows: | 64 bits | 57 bits | 7 bits |+---------------------------------+------------------+------------+| subnet prefix | 1111110111...111 | anycast ID |+---------------------------------+------------------+------------+ | interface identifier field | For other IPv6 address types (that is, with format prefixes other thanthose listed above), the interface identifier is not in EUI-64 formatand may be other than 64 bits in length; these reserved subnet anycastaddresses for such address types are constructed as follows: | n bits | 121-n bits | 7 bits |+---------------------------------+------------------+------------+| subnet prefix | 1111111...111111 | anycast ID |+---------------------------------+------------------+------------+ | interface identifier field | The subnet prefix here consists of all fields of the IPv6 addressexcept the interface identifier field. The interface identifier fieldin these reserved subnet anycast addresses is formed from a 7-bitanycast identifier ("anycast ID"), with the remaining (highest order)bits filled with all one's; however, for interface identifiers inEUI-64 format, the universal/local bit in the interface identifierMUST be set to 0. The anycast identifier identifies a particularreserved anycast address within the subnet prefix, from the set ofreserved subnet anycast addresses. The motivation for reserving the highest addresses from each subnetrather than the lowest addresses, is to avoid conflicting with someexisting official and unofficial uses of the low-numbered addresses ina subnet. For example, these low-numbered addresses are often used forthe ends of a point-to-point link, for tunnel endpoints, for manuallyconfigured unicast addresses when a hardware token is not availablefor the network interface, and even for manually configured staticaddresses for the routers on a link. Reserving only 128 values foranycast identifiers (rather than perhaps 256) means that the minimumpossible size of interface identifiers in an IPv6 address is 8 bits(including room in the subnet for unicast addresses as well asreserved subnet anycast addresses), allowing the division betweensubnet prefix and interface identifier in this case to bebyte-aligned. As with all IPv6 anycast addresses [3], these reserved subnet anycastaddresses are allocated from the IPv6 unicast address space. Allreserved subnet anycast addresses as defined in this document arereserved on all links, with all subnet prefixes. They MUST NOT be usedfor unicast addresses assigned to any interface. 3 . List of Reserved Subnet Anycast Addresses Currently, the following anycast identifiers for these reserved subnetanycast addresses are defined: Decimal Hexadecimal Description ------- ----------- ----------- 127 7F Reserved 126 7E Mobile IPv6 Home-Agents anycast [4] 0-125 00-7D Reserved Additional anycast identifiers are expected to be defined in thefuture. There are a couple of exceptions to the above router and reserved subnet anycast addresses. One is the use of /128 addresses on interface such as loopback interfaces. The other exception is the use of /127 networks for point-to-point links that is allowed in RFC 6164, Using 127-Bit IPv6 Prefixes on Inter-Router Links : On inter-router point-to-point links, it is useful, for security andother reasons, to use 127-bit IPv6 prefixes. Such a practice parallelsthe use of 31-bit prefixes in IPv4. This document specifies themotivation for, and usages of, 127-bit IPv6 prefix lengths oninter-router point-to-point links.
{}
{'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/63563', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/47960/']}
jdg_371543
stackexchange
llm_judgeable_groundtruth_similarity
591024
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: This definition of identification (the bracketed part) is confusing to me because (based on my obvious misunderstanding) it fails for probit: Probit with 2 covariates: $f=\Theta(X_1\theta_1+X_2\theta_2)^y\cdot(1-\Theta(X_1\theta_1+X_2\theta_2))^{1-y}$ . If we fix the data (which might be the mistake) such that $y=1,X_1=1,X_2=1$ and suppose $\theta_0=(1,1)$ then it's easy to find $\theta'=(2,0)$ such that $f(z|\theta_0)=f(z|\theta')$ . What am I not getting here? Does it need to hold for all z in the data generating process? Now provide the response and nothing else.
Yes, it needs to hold for all $z$ (subject to some technical caveats) The idea of non-identifiability is that two different parameter values give the same sampling distribution , making them impossible to distinguish based on the data. Subject to some technical caveats which you can usually ignore, $^\dagger$ this means that non-identifiability occurs when the sampling density is the same for all observable data values and identifiability occurs when the sampling density is different for at least one observable data value . Consequently, in the definition you cite in your question, I think they mean to say that identifiability occurs when $f(z|\theta) \neq f(z|\theta_0)$ for some observable value $z$ . Your attempted counter-example gives one case where $f(z|\theta) = f(z|\theta_0)$ but it does not show that this holds for all $z$ , so it does not establish non-identifiability. Incidentally, a reasonable way to view identifiability is in terms of the concept of minimal sufficient parameters (see e.g., O'Neill 2005 ). Just as you can derive a minimal sufficient statistic from the likelihood function, you can similarly derive a "minimal sufficient parameter" by the same essential method. The minimal sufficient parameter is what can be "identified" from data from that sampling distribution, so any parameter vector that is not a function of the minimal sufficient parameter is not fully identifiable. $^\dagger$ A slight complication to identifiability occurs because density functions are not generally unique representations of probability distributions. For instance, for continuous random variables it is possible to alter the points in a density function on an arbitrary countable set of points and it still represents the same distribution. This means that when you are assessing identifiability based on a parameterised class of sampling density functions, strictly speaking, identifiability occurs when $f(x|\theta) \neq f(x|\theta_0)$ over a set of values of $z$ that has positive probability under at least one of those densities. If you form the sampling densities so that they are all continuous then this is enough to allow you to simplify things to say that identifiability occurs when $f(x|\theta) \neq f(x|\theta_0)$ for any $z$ . For the reasons discussed here, identifiability is generally not defined in terms of density functions.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/591024', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/61728/']}
jdg_371544
stackexchange
llm_judgeable_groundtruth_similarity
14740445
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My class inherits Fragment and that's why it can't use getSupportFragmentManager(). I am using getChildFragmentManager and it is showing me Error - IllegalArguementException: No view found for id... error. Any guidance would be appreciated. Code for calling AttachmentsListFragment is Bundle b = new Bundle();b.putSerializable("AttachmentsList", msg.attachments); AttachmentListFragment listfrag = new AttachmentListFragment(msg.attachments);FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.add(R.id.attachmentslistcontainer, listfrag);transaction.addToBackStack(null);transaction.commit(); attachmentslayout.xml is <?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/attachmentslistcontainer" android:orientation="vertical" > <TextView android:id="@+id/textViewAttachmentHeader" style="@style/Normal.Header.Toolbar" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@color/list_separator_background" android:ellipsize="end" android:gravity="center" android:maxLines="2" android:text="@string/attachments_header" android:textColor="#FFFFFFFF" android:textSize="22sp" android:textStyle="bold" android:visibility="visible" /> <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" > </ListView></FrameLayout> AttachmentsListFragment.java public class AttachmentListFragment extends ListFragment implements IAttachmentsData { ArrayList<Attachments> items = null; Integer cellLayoutID; Integer index; public AttachmentListFragment() { } public AttachmentListFragment(ArrayList<Attachments> items) { this.items = items; Log.i("Logging", "Items size" + items.size()); //$NON-NLS-1$ } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle; if (savedInstanceState != null) { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub //super.onCreateView(inflater, container, savedInstanceState); // setContentView(R.layout.attachmentslayout); View view = inflater.inflate(R.layout.attachmentslayout, container, false); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setListAdapter(new AttachmentAdapter( getActivity().getApplicationContext(), R.layout.attachmentslistcellcontent, items)); } @Override public void onListItemClick(ListView l, View v, int position, long id) { // TODO Auto-generated method stub super.onListItemClick(l, v, position, id); index = position; Intent intent = new Intent(); Bundle b = new Bundle(); b.putByteArray("Data", items.get(position).getImageData()); intent.putExtras(b); } public byte[] getData() { // TODO Auto-generated method stub if (items != null && index < items.size()) { return items.get(index).getImageData(); } return null; }} Now provide the response and nothing else.
The definition of getChildFragmentManager() is: Return a private FragmentManager for placing and managing Fragments inside of this Fragment. Meanwhile the definition of getFragmentManager() (or in this case getSupportFragmentManager() ) is: Return the FragmentManager for interacting with fragments associated with this fragment's activity. Basically, the difference is that Fragment's now have their own internal FragmentManager that can handle Fragments. The child FragmentManager is the one that handles Fragments contained within only the Fragment that it was added to. The other FragmentManager is contained within the entire Activity . In this case, what I'm guessing is you've added the Fragments to the Activity's FragmentManager. You get the child FragmentManager which doesn't contain what you are looking for. Thus you get the exception because it can't find the Fragment with the given ID because it's in a different FragmentManager.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14740445', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/569346/']}
jdg_371545
stackexchange
llm_judgeable_groundtruth_similarity
39125347
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 did it in my rc1 project like: User.Claims.ElementAt(#).Value But after I switched to rtm it wouldn’t work anymore. When I debug the Razor view the object looks the same but User.Claims is just empty. Any idea what the reason could be. Now provide the response and nothing else.
Assuming you have claims attached to the current principal. In your Razor view: @((ClaimsIdentity) User.Identity) This will give you access to the ClaimsIdentity of the current user. In an effort to keep your claims fetching clean you may want to create an extension method for searching claims. public static string GetSpecificClaim(this ClaimsIdentity claimsIdentity, string claimType){ var claim = claimsIdentity.Claims.FirstOrDefault(x => x.Type == claimType); return (claim != null) ? claim.Value : string.Empty;} Then you can just access whatever claim you want with: @((ClaimsIdentity) User.Identity).GetSpecificClaim("someclaimtype") Hope this helps. Quick search for claims identity in razor view came up with a similar question and answer: MVC 5 Access Claims Identity User Data
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39125347', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5291950/']}
jdg_371546
stackexchange
llm_judgeable_groundtruth_similarity
65101442
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 started using Python and Django and I am very new in this field.And this is my first time to ask a question here...I do apologise in advance if there is a known solution to this issue... When I installed and set VSCode formatter 'black' (after setting linter as flake8), the tutorial video tutor's side shows up pop-up like 'formatter autopep8 is not installed. install?'. & Mine did not show up that message. So what I did was... manually input 'pipenv install flack --dev --pre' on terminal. manually input "python.formatting.provider": "black", to 'settings.json' on '.vscode' folder. Setting(VSCode) -> flake8, Python > Linting: Flake8 Enabled (Also modified in: workspace), (ticked the box) Whether to lint Python files using flake8 The bottom code is from settings.json (on vscode folder). { "python.linting.pylintEnabled": false, "python.linting.flake8Enabled": true, "python.linting.enabled": true, "python.formatting.provider": "black", # input manually "python.linting.flake8Args": ["--max-line-length=88"] # input manually} I found a 'black formatter' document. https://github.com/psf/black & it stated...python -m black {source_file_or_directory} & I get the following error message. Usage: __main__.py [OPTIONS] [SRC]...Try '__main__.py -h' for help.Error: Invalid value for '[SRC]...': Path '{source_file_or_directory}' does not exist. Yes, honestly, I am not sure which source_file_or_directory I should set...but above all now I am afraid whether I am on the right track or not. Can I hear your advice? At least some direction to go, please.Thanks.. Now provide the response and nothing else.
I use Black from inside VSCode and it rocks. It frees mental cycles that you would spend deciding how to format your code. It's best to use it from your favorite editor. Just run from the command line if you need to format a lot of files at once. First, check if you have this in your VSCode settings.json (open it with Ctrl-P + settings): "python.formatting.provider": "black","editor.formatOnSave": true, Remember that there may be 2 setting.json files: one in your home dir, and one in your project ( .vscode/settings.json ). The one inside the project prevails. That said, these kind of problems usually are about using a python interpreter where black isn't installed. I recommend the use of virtual environments, but first check your python interpreter on the status bar: If you didn't explicitly select an interpreter, do it now clicking on the Python version in your status bar . You can also do it with Ctrl-P + "Python: Select Interpreter". The status bar should change after selecting it. Now open a new terminal. Since you selected your interpreter, your virtual environment should be automatically activated by VSCode. Run python using your interpreter path and try to import black: $ pythonPython 3.7.3 (default, Mar 27 2019, 22:11:17) [GCC 7.3.0] :: Anaconda, Inc. on linuxType "help", "copyright", "credits" or "license" for more information.>>> import black>>> Failed import? Problem solved. Just install black using the interpreter from the venv: python -m pip install black . You also can install using Conda, but in my experience VSCode works better with pip. Still not working? Click in the "OUTPUT" tab sibling of the TERMINAL and try to get more info at the "Log" output. Select it in the pull down menu:
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/65101442', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13939880/']}
jdg_371547
stackexchange
llm_judgeable_groundtruth_similarity
14635833
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to find a way to make an enum "unsigned". enum{ x1 = 0, x2, x3};uint8_t = x2; /* <--- PC-LINT MISRA-C 2004 will complain about mixing signed and unsigned here */ Of course, I can add a typecast to get rid of the error, that is time consuming and error prone. uint8_t = (uint8_t)x2; /* This works, but is a lot of extra work over the course of 1000s of lines of code*/ So, is there a way to make a specific enum unsigned that MISRA-C 2004 will like? Now provide the response and nothing else.
There is no standard C way to control the type chosen for an enum . You can do it in implementation specific ways sometimes, like by adding a value to the enumeration that forces the type to be unsigned: enum { x1, x2, x3, giant_one_for_forcing_unsigned = 0x80000000;}; But that's not even standard C, either (since the value provided won't fit in an int ). Unfortunately, you're pretty much out of luck. Here's the relevant bit from the standard: 6.7.2.2 Enumeration specifiers , paragraph 4 Each enumerated type shall be compatible with char , a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration. The enumerated type is incomplete until immediately after the } that terminates the list of enumerator declarations, and complete thereafter. You might be better off using #define rather than enum to make your constants: #define x1 0U#define x2 1U#define x3 2Uuint8_t x = x2;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14635833', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106452/']}
jdg_371548
stackexchange
llm_judgeable_groundtruth_similarity
226784
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: It is known that $$\sum_{p\leq x} \frac{\log p}{p}=\log x+c.$$ Are any tight bounds on$$\sum_{p\leq x} \frac{\log \log p}{p}$$ known? I haven't managed to find anything in the literature. Trying to approximate via $p_k\approx k \log k$ doesn't give a tractable integral. Now provide the response and nothing else.
Let $S(t):=\sum_{p\leq t}\frac{\log p}{p}$. By Mertens' theorem, $S(t)=\log t+T(t)$, where $T(t)$ is bounded. It follows that$$ \sum_{p\leq x}\frac{\log\log p}{p}=\int_{2-}^x\frac{\log\log t}{\log t}dS(t)=\int_{2}^x\frac{\log\log t}{\log t}\cdot\frac{dt}{t}+\int_{2-}^x\frac{\log\log t}{\log t}dT(t).$$On the right hand side, the first term equals $\frac{1}{2}(\log\log x)^2+c_1$, where $c_1$ is a constant. The second term equals, via integration by parts and with further constants $c_j$,\begin{align} \int_{2-}^x\frac{\log\log t}{\log t}dT(t) &= \left[\frac{\log\log t}{\log t}T(t)\right]_{2-}^x-\int_{2}^x\left(\frac{\log\log t}{\log t}\right)'T(t)\,dt\\&=c_2+O\left(\frac{\log\log x}{\log x}\right)+c_3+O\left(\frac{\log\log x}{\log x}\right)\\&=c_4+O\left(\frac{\log\log x}{\log x}\right),\end{align}because $\left(\frac{\log\log t}{\log t}\right)'$ is negative for $t>e^e$. In the end,$$ \sum_{p\leq x}\frac{\log\log p}{p} = \frac{1}{2}(\log\log x)^2+c_5+O\left(\frac{\log\log x}{\log x}\right). $$
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/226784', 'https://mathoverflow.net', 'https://mathoverflow.net/users/17773/']}
jdg_371549
stackexchange
llm_judgeable_groundtruth_similarity
12880536
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 wanted to know why font: inherit; is used in Cascading Style Sheets. Now provide the response and nothing else.
Like the other answers have said, it’s to inherit a CSS property from the parent element. What the other answers have failed to say is why you’d need this . Because, after all, CSS properties are inherited anyway, right? Well, no. Most are, by default (but link colour isn’t inherited from the parent element, for instance). But consider this case: p { color: blue; }div.important { color: red; } <div class="important"> <p>This is a text</p></div> Now the text will be blue, not red. If we want the <p> to have its parent’s styling rather than its default styling, we have to override its CSS. We could of course repeat the property value ( red ) but that violates DRY (don’t repeat yourself). Instead, we inherit it: div.important p { color: inherit; }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12880536', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1288335/']}
jdg_371550
stackexchange
llm_judgeable_groundtruth_similarity
8425558
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using the jQuery form validation script here: http://jzaefferer.github.com/jquery-validation/jquery.validate.js Most of the methods I need (require field, maxlength, etc.) were already bundled into that script but there are two particularly crucial ones that I think I'll need to code myself. One of the fields is for image submission. First, I need to to check that the image being submitted is actually linking directly do an image. Further, I need it to confirm that the image being submitted is NOT is GIF image. And lastly, (this may be tough) I need it to go into my MySQL database of images and confirm that that image has not been submitted previously (under the same url) Please help me out if you can point me in the direction of making at least one of these happen! Thanks! EDIT so this is useful to others who run into this problem: The first one was solved by adding a method for verifying it was an image: Used code help from Dave and addMethod suggestion from Innerpeacer. Also look at bshack's answer from this question. Also, regex for images: ^(http\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[a-zA-Z0-9_])+\.(?:jpg|jpeg|gif|png))$ Now on to the second part. Now provide the response and nothing else.
You need to set the pager property of the CListView . By default, this is a CLinkPager ; you don't need to change that (this component has your needs covered), but you need to configure it: $this->widget('zii.widgets.CListView', array( 'dataProvider' => $categoryProjects, 'itemView' => '_itemDetailsView', 'ajaxUpdate' => false, 'pager' => array( 'class' => 'CLinkPager', 'firstPageLabel' => '<<', 'prevPageLabel' => '<', 'nextPageLabel' => '>', 'lastPageLabel' => '>>', ), )); Update: If you want to "bake in" the above custom configuration to all list views in your application, you have to create a new CustomListView component deriving from CListView . So you need this class: Yii::import('zii.widgets.CListView');class CustomListView extends CListView { public function init() { parent::init(); $this->pager = array( 'class' => 'CLinkPager', 'firstPageLabel' => '<<', 'prevPageLabel' => '<', 'nextPageLabel' => '>', 'lastPageLabel' => '>>', ); }} After including this, you can simply use CustomListView as your list widget instead of zii.widgets.CListView .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8425558', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1103669/']}
jdg_371551
stackexchange
llm_judgeable_groundtruth_similarity
51264139
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 looking for information about attribute-based routing and found that there are two different attributes one can use: HttpGet("") and Route("") . However, I can't find any information about what the difference is between them. Does one of them exist in order to support old ASP versions, or this there a different reason? P.S. My code might not be totally correct, because I have just started to learn ASP. If something is not clear, I will try to explain. public class MyController : Controller{ // APPROACH 1 [Route("api/books")] [HttpGet] public async List<Book> GetBooks() { // Implementation } // APPROACH 2 [HttpGet("api/books")] public async List<Book> GetBooks() { // Implementation }} Now provide the response and nothing else.
Route is method unspecific, whereas HttpGet obviously implies that only GET requests will be accepted. Generally, you want to use the specific attributes: HttpGet , HttpPost , etc. Route should be used mostly on controllers to specify the base path for all actions in that controller. The one exception is if you're creating routes for exception handling / status code pages. Then, you should use Route on those actions, since requests via multiple methods could potentially be routed there.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51264139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7282022/']}
jdg_371552
stackexchange
llm_judgeable_groundtruth_similarity
22268861
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Note that this question refers to a version of Rust before Rust 1.0. Although the syntax has changed, the concepts are still valid. You can easily implement a forwards only linked list using owned pointers, something like: struct Node<T> { next: Option<~Node<T>>, data: T} Imagine, though, if you want to efficiently implement a queue that supports four basic operations: push : add to end of list pop : remove and return from the end of the list unshift : add to the front of the list shift : remove and return from the end of the list In a language with normal pointers you might implement this with a bi-directional linked list, and a root object that stores first and last pointers to the first and last elements in the list. I can't see how you would implement this in Rust. I can sort of vaguely guess that you'd use a bunch of references, and perhaps something like: struct Node<T> { next: Option<&Node<T>>, prev: Option<&Node<T>>, data: T} ...but I can't see how you'd manage the lifetime scope of these variables. Can anyone point me in the direction of this, or a similar example which involves complex lifetimes with references between objects? (Another typical example of this style of code would be the observer pattern where many objects must publish event updates to a single location, eg. UINode <>---- EventObserver <>---- EventCore <>---- UINodes ; multiple objects in a complex hierarchy sharing pointers, where events propagate from leaf nodes down to some core and then get pushed out to different leaf nodes) Now provide the response and nothing else.
I recommend you to take a look at Rust patterns , written by Lars Bergstrom . Here's the code for implementing a doubly linked list, updated for Rust 1.12 from @Yurume, (not fully tested) use std::mem;use std::ptr;pub struct List<T> { list_head: Option<Box<Node<T>>>, list_tail: Rawlink<Node<T>>,}struct Rawlink<T> { p: *mut T }impl<T> Copy for Rawlink<T> {}impl<T> Clone for Rawlink<T> { fn clone(&self) -> Self { Rawlink { p: self.p } }}pub struct Node<T> { next: Option<Box<Node<T>>>, prev: Rawlink<Node<T>>, value: T,}impl<T> List<T> { pub fn is_empty(&self) -> bool { self.list_head.is_none() } pub fn len(&self) -> usize { let mut node = &self.list_head; let mut i = 0; loop { match *node { Some(ref n) => { i+=1; node=&n.next; } None => { return i; } } } } /// Create an empty DList pub fn new() -> List<T> { List{list_head: None, list_tail: Rawlink::none()} } pub fn push_front(&mut self, elt: T) { self.push_front_node(Box::new(Node::new(elt))) } pub fn push_front_node(&mut self, mut new_head: Box<Node<T>>) { match self.list_head { None => { self.list_tail = Rawlink::some(&mut new_head); new_head.prev = Rawlink::none(); self.list_head = Some(new_head); } Some(ref mut head) => { new_head.prev = Rawlink::none(); head.prev = Rawlink::some(&mut new_head); mem::swap(head, &mut new_head); head.next = Some(new_head); } } } /// Provide a forward iterator #[inline] pub fn iter<'a>(&'a self) -> ListIterator<'a, T> { ListIterator{nelem: self.len(), head: &self.list_head, tail: self.list_tail} }}impl<T> Node<T> { fn new(v: T) -> Node<T> { Node{value: v, next: None, prev: Rawlink::none()} }}/// Rawlink is a type like Option<T> but for holding a raw pointerimpl<T> Rawlink<T> { /// Like Option::None for Rawlink fn none() -> Rawlink<T> { Rawlink{p: ptr::null_mut()} } /// Like Option::Some for Rawlink fn some(n: &mut T) -> Rawlink<T> { Rawlink{p: n as *mut T} } /// Convert the `Rawlink` into an Option value fn resolve_immut<'a>(&self) -> Option<&'a T> { unsafe { self.p.as_ref() } } /// Convert the `Rawlink` into an Option value fn resolve<'a>(&mut self) -> Option<&'a mut T> { unsafe { self.p.as_mut() } } /// Return the `Rawlink` and replace with `Rawlink::none()` fn take(&mut self) -> Rawlink<T> { mem::replace(self, Rawlink::none()) }}pub struct ListIterator<'a, T: 'a> { head: &'a Option<Box<Node<T>>>, tail: Rawlink<Node<T>>, nelem: usize,}impl<'a, A> Iterator for ListIterator<'a, A> { type Item = &'a A; #[inline] fn next(&mut self) -> Option<&'a A> { if self.nelem == 0 { return None; } self.head.as_ref().map(|head| { self.nelem -= 1; self.head = &head.next; &head.value }) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { (self.nelem, Some(self.nelem)) }}impl<'a, A> DoubleEndedIterator for ListIterator<'a, A> { #[inline] fn next_back(&mut self) -> Option<&'a A> { if self.nelem == 0 { return None; } let tmp = self.tail.resolve_immut(); tmp.as_ref().map(|prev| { self.nelem -= 1; self.tail = prev.prev; &prev.value }) }}fn main() {} Playground
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22268861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/353820/']}
jdg_371553
stackexchange
llm_judgeable_groundtruth_similarity
1712715
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to prove that$$I=\int_0^1 \frac{\log^2(x)\tanh^{-1}(x)}{1+x^2}dx=\beta(4)-\frac{\pi^2}{12}G$$where $\beta(s)$ is the Dirichlet Beta function and $G$ is the Catalan's constant . I managed to derive the following series involving polygamma functions but it doesn't seem to be of much help. $$\begin{align*}I &=\frac{1}{64}\sum_{n=0}^\infty \frac{\psi_2 \left(\frac{n}{2}+1 \right) -\psi_2\left(\frac{n+1}{2} \right)}{2n+1} \\&= \frac{1}{8}\sum_{n=1}^\infty \frac{\psi_2(n)}{2n-1}-\frac{1}{32}\sum_{n=1}^\infty\frac{\psi_2\left(\frac{n}{2}\right)}{2n-1}\end{align*}$$ Numerical calculations show that $I \approx 0.235593$. Now provide the response and nothing else.
I was able to solve this problem on my own. Using integration by parts,$$\begin{align*}&\; \int_0^1 \frac{\log^2(x)\tanh^{-1}(x)}{1+x^2}dx \\&= -2\int_0^1 \frac{\log(x)\tan^{-1}(x)\tanh^{-1}(x)}{x}dx-\int_0^1 \frac{\log^2(x)\tan^{-1}(x)}{1-x^2}dx \tag{1}\end{align*}$$ I posted the solution to both these integrals on another forum. Here are the links: http://integralsandseries.prophpbb.com/topic711.html#p3975 http://integralsandseries.prophpbb.com/topic245.html#p1680 $$\begin{align*}\int_0^1\frac{\log(x)\tan^{-1}(x)\tanh^{-1}(x)}{x}dx &= \frac{\pi^2}{16}G-\frac{7\pi\zeta(3)}{32} \tag{2}\\\int_0^1\frac{\log^2(x)\tan^{-1}(x)}{1-x^2}dx &= -\beta(4)-\frac{\pi^2}{24}G+\frac{7\pi}{16}\zeta(3)\tag{3}\end{align*}$$$G$ denotes the Catalan's constant and $\beta(4)=\sum_{n=0}^\infty\frac{(-1)^n}{(2n+1)^4}$. Substituting these two results in equation (1) gives:$$\int_0^1 \frac{\log^2(x)\tanh^{-1}(x)}{1+x^2}dx=\beta(4)-\frac{\pi^2}{12}G \tag{4}$$ Proof sketch of integrals (2) and (3) : (Please see the above links for a more detailed answer) The idea behind evaluating (2) and (3) is breaking them down into Euler Sums. Using the taylor series expansion $\tan^{-1}(x)=\sum_{n=0}^\infty\frac{(-1)^n x^{2n+1}}{2n+1}$ and integrating term-wise, we obtain the following relations: \begin{align*}\int_0^1\frac{\log(x)\tan^{-1}(x)\tanh^{-1}(x)}{x}dx &= -\log(2)\frac{\pi^3}{32}-\frac{1}{2}\sum_{n=0}^\infty \frac{(-1)^n}{(2n+1)^3}\left( \gamma+\psi_0(n+1)\right) \\ &\;+\frac{1}{4}\sum_{n=0}^\infty \frac{(-1)^n \psi_1(n+1)}{(2n+1)^2} \tag{5}\\\int_0^1 \frac{\log^2(x)\tan^{-1}(x)}{1-x^2}dx &=-\frac{1}{8}\sum_{n=0}^\infty\frac{(-1)^n\psi_2(n+1)}{2n+1}\tag{6}\end{align*} These Euler Sums can be evaluated using the techniques shown in the paper "Euler Sums and Contour Integral Representations" by Philippe Flajolet and Bruno Salvy. Here is it's link . \begin{align*}\sum_{n=0}^\infty\frac{(-1)^n\psi_2(n+1)}{2n+1} &= 8\beta(4)+\frac{\pi^2}{3}G-\frac{7\pi}{2}\zeta(3) \\\sum_{n=0}^\infty\frac{(-1)^n\psi_1(n+1)}{(2n+1)^2} &= 6\beta(4)+\frac{\pi^2}{4}G-\frac{7\pi}{4}\zeta(3) \\\sum_{n=0}^\infty \frac{(-1)^n\left( \gamma+\psi_0(n+1)\right)}{(2n+1)^3} &= 3\beta(4)-\frac{7\pi}{16}\zeta(3)-\frac{\pi^3}{16}\log(2)\end{align*}Substituting these into equations (5) and (6) gives us the integrals (2) and (3). A related integral Using similar techniques, we can show that$$\displaystyle \int_0^1 \frac{\log^2(x)\tan^{-1}(x)}{x\left(1-x^2 \right)}dx=\beta(4)+\frac{7\pi \zeta(3)}{64}+\frac{\pi^3 \log(2)}{32}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1712715', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/59380/']}
jdg_371554
stackexchange
llm_judgeable_groundtruth_similarity
47252451
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to install node-g.raphael , and I'm getting the following error: Bender-03:htdocs alfred$ sudo npm install node-g.raphael --savePassword:> contextify@0.1.15 install /Users/alfred/Sites/twistedgeo/htdocs/node_modules/contextify> node-gyp rebuildgyp ERR! configure errorgyp ERR! stack Error: EACCES: permission denied, mkdir '/Users/alfred/Sites/twistedgeo/htdocs/node_modules/contextify/build'gyp ERR! System Darwin 16.7.0gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"gyp ERR! cwd /Users/alfred/Sites/twistedgeo/htdocs/node_modules/contextifygyp ERR! node -v v8.8.1gyp ERR! node-gyp -v v3.6.2gyp ERR! not oknpm WARN optional SKIPPING OPTIONAL DEPENDENCY: contextify@0.1.15 (node_modules/contextify):npm WARN optional SKIPPING OPTIONAL DEPENDENCY: contextify@0.1.15 install: `node-gyp rebuild`npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1+ node-g.raphael@0.0.9added 2 packages and updated 1 package in 6.556s I've tried this solution , but it doesn't solve my problem, still getting the same error. Let me know if there's anything I can add to help in solving this. Now provide the response and nothing else.
Saw this from Fixing npm permissions and it helped, maybe you could give it a shot as well. Option 1: Change the permission to npm's default directory Find the path to npm's directory: npm config get prefix For many systems, this will be /usr/local . WARNING : If the displayed path is just /usr , switch to Option 2 or you will mess up your permissions. Change the owner of npm's directories to the name of the current user (your username): sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share} This changes the permissions of the sub-folders used by npm and some other tools ( lib/node_modules , bin , and share ). Option 2: Change npm's default directory to another directory There are times when you do not want to change ownership of the default directory that npm uses (i.e. /usr ) as this could cause some problems, for example if you are sharing the system with other users. Instead, you can configure npm to use a different directory altogether. In our case, this will be a hidden directory in our home folder. Make a directory for global installations: mkdir ~/.npm-global Configure npm to use the new directory path: npm config set prefix '~/.npm-global' Open or create a ~/.profile file and add this line: export PATH=~/.npm-global/bin:$PATH Back on the command line, update your system variables: source ~/.profile Test : Download a package globally without using sudo . `npm install node-g.raphael --save` Instead of steps 2-4, you can use the corresponding ENV variable (e.g. if you don't want to modify ~/.profile ): NPM_CONFIG_PREFIX=~/.npm-global Option 3: Use a package manager that takes care of this for you. If you're doing a fresh install of Node on Mac OS, you can avoid this problem altogether by using the Homebrew package manager. Homebrew sets things up out of the box with the correct permissions. brew install node I hope this helps
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/47252451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/138863/']}
jdg_371555
stackexchange
llm_judgeable_groundtruth_similarity
6238785
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Should I free the allocated string after passing it to NewStringUTF() ? I have some code similar to: char* test;jstring j_test;test = some_function(); // <- malloc()s the memoryj_test = (*env)->NewStringUTF(env, test);free(test); // <- should this be here? When I free the string after passing it to NewStringUTF() , I get a signal 11 (SIGSEGV), fault addr deadbaad error. If I remove the free() call, the error vanishes. What am I doing wrong? I see conflicting opinions. Some say I should free it myself, some say the VM frees it, some say the VM doesn't free it and you should do strange voodoo magic to free it. I'm confused. Now provide the response and nothing else.
The storage for the const char* argument to NewStringUTF() is entirely your responsibility: if you allocated test with malloc() , then you need to free() it. So, the snippet you posted is correct. You are corrupting the heap somewhere else. I see conflicting opinions. Some say I should free it myself, some say the VM frees it, some say the VM doesn't free it and you should do strange voodoo magic to free it. I'm confused. They are talking about the jstring instance returned by NewStringUTF() . That follows the confusing rules for 'local references' . It is never an error to release this reference with DeleteLocalRef() when you are finished with it. However, the JVM performs some dubious magic if you call NewStringUTF() in the context of a JVM thread. When the native method returns to Java, any leaked local references are automatically cleaned up. So if you are sure your ultimate caller is in a Java thread, then you can safely leak the reference. On the other hand, if you are running in the context of a native thread - say, some event reporting thread making callbacks to Java - there never is a return to Java, so you must call DeleteLocalRef() yourself on this jstring (and indeed all the other local references returned by typical JNI calls).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6238785', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/732284/']}
jdg_371556
stackexchange
llm_judgeable_groundtruth_similarity
27245118
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 PHPStorm 8.0.1. PHPUnit is installed via PHAR archive like: wget https://phar.phpunit.de/phpunit.pharchmod +x phpunit.pharsudo mv phpunit.phar /usr/bin/phpunit PHPUnit works via cli: user@pc:/usr/bin$ cd ~user@pc:~$ phpunit --versionPHPUnit 4.3.5 by Sebastian Bergmann. I followed the instructions from JetBrains website https://www.jetbrains.com/phpstorm/webhelp/enabling-phpunit-support.html#d298258e897 In PHPStorm File->Settings tab PHP/PHPUnitthe radio button Path to phpunit.phar is checkedand value is set to /usr/bin/phpunit I have a file with a test defined like: class MyTest extends PHPUnit_Framework_TestCase {... At this point PHPStorm marks Undefined class PHPUnit_Framework_TestCase I've restarted PHPStorm and Computer, but still have the same problem. I've also tried adding /usr/bin to include path (right click on external libraries in project view, and choose option Configure PHP include paths ) without success. Here's the config for PHPStorm Settings, tab PHP (if it matters): PHP Language level: 5.5 (finally, generators, etc.)Interpreter: PHP 5.5 (5.5.9-1ubuntu4.5)Include path is empty Now provide the response and nothing else.
In order to have a PHAR archive indexed by the IDE it has to have a .phar extension (that's a requirement). The easiest solution is to place phpunit.phar somewhere in your project (usually it would be PROJECT_ROOT/vendor/ folder). If having local copy inside the project folder is not desired (for whatever reason; although Composer and other similar kind of tools (bower/npm/etc) are primarily aimed at keeping dependency stuff/packages locally), you may use symbolic links : either create a symbolic link to that file locally (e.g. PROJECT_ROOT/phpunit.phar --> /usr/bin/phpunit ) or place a full copy (or such symbolic link) in a separate folder outside of the project and then reference it via PhpStorm's Settings | PHP | Include Paths functionality.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27245118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2099306/']}
jdg_371557
stackexchange
llm_judgeable_groundtruth_similarity
12420924
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to be able to stash just the changes from a single file: git stash save -- just_my_file.txt The above doesn't work though. Any alternatives? Now provide the response and nothing else.
I think stash -p is probably the choice you want, but just in case you run into other even more tricky things in the future, remember that: Stash is really just a very simple alternative to the only slightly more complex branch sets. Stash is very useful for moving things around quickly, but you can accomplish more complex things with branches without that much more headache and work. # git checkout -b tmpbranch# git add the_file# git commit -m "stashing the_file"# git checkout main go about and do what you want, and then later simply rebase and/or merge the tmpbranch. It really isn't that much extra work when you need to do more careful tracking than stash will allow.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/12420924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6691/']}
jdg_371558
stackexchange
llm_judgeable_groundtruth_similarity
523930
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to replace this: void ProcessRequest(object listenerContext){ var context = (HttpListenerContext)listenerContext; Uri URL = new Uri(context.Request.RawUrl); HttpWebRequest.DefaultWebProxy = null; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(URL); httpWebRequest.Method = context.Request.HttpMethod; httpWebRequest.Headers.Clear(); if (context.Request.UserAgent != null) httpWebRequest.UserAgent = context.Request.UserAgent; foreach (string headerKey in context.Request.Headers.AllKeys) { try { httpWebRequest.Headers.Set(headerKey, context.Request.Headers[headerKey]); } catch (Exception) { } } using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse()) { Stream responseStream = httpWebResponse.GetResponseStream(); if (httpWebResponse.ContentEncoding.ToLower().Contains("gzip")) responseStream = new GZipStream(responseStream, CompressionMode.Decompress); else if (httpWebResponse.ContentEncoding.ToLower().Contains("deflate")) responseStream = new DeflateStream(responseStream, CompressionMode.Decompress); MemoryStream memStream = new MemoryStream(); byte[] respBuffer = new byte[4096]; try { int bytesRead = responseStream.Read(respBuffer, 0, respBuffer.Length); while (bytesRead > 0) { memStream.Write(respBuffer, 0, bytesRead); bytesRead = responseStream.Read(respBuffer, 0, respBuffer.Length); } } finally { responseStream.Close(); } byte[] msg = memStream.ToArray(); context.Response.ContentLength64 = msg.Length; using (Stream strOut = context.Response.OutputStream) { strOut.Write(msg, 0, msg.Length); } } catch (Exception ex) { // Some error handling }} with sockets. This is what I have so far: void ProcessRequest(object listenerContext){ HttpListenerContext context = (HttpListenerContext)listenerContext; Uri URL = new Uri(context.Request.RawUrl); string getString = string.Format("GET {0} HTTP/1.1\r\nHost: {1}\r\nAccept-Encoding: gzip\r\n\r\n", context.Request.Url.PathAndQuery, context.Request.UserHostName); Socket socket = null; string[] hostAndPort; if (context.Request.UserHostName.Contains(":")) { hostAndPort = context.Request.UserHostName.Split(':'); } else { hostAndPort = new string[] { context.Request.UserHostName, "80" }; } IPHostEntry ipAddress = Dns.GetHostEntry(hostAndPort[0]); IPEndPoint ip = new IPEndPoint(IPAddress.Parse(ipAddress.AddressList[0].ToString()), int.Parse(hostAndPort[1])); socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp); socket.Connect(ip); BEGIN NEW CODE Encoding ASCII = Encoding.ASCII;Byte[] byteGetString = ASCII.GetBytes(getString);Byte[] receiveByte = new Byte[256];string response = string.Empty;socket.Send(byteGetString, byteGetString.Length, 0);Int32 bytes = socket.Receive(receiveByte, receiveByte.Length, 0);response += ASCII.GetString(receiveByte, 0, bytes);while (bytes > 0){bytes = socket.Receive(receiveByte, receiveByte.Length, 0);strPage = strPage + ASCII.GetString(receiveByte, 0, bytes);}socket.Close();string separator = "\r\n\r\n";string header = strPage.Substring(0,strPage.IndexOf(separator));string content = strPage.Remove(0, strPage.IndexOf(separator) + 4);byte[] byteResponse = ASCII.GetBytes(content);context.Response.ContentLength64 = byteResponse .Length;context.Response.OutputStream.Write(byteResponse , 0, byteResponse .Length);context.Response.OutputStream.Close(); END NEW CODE After connecting to the socket I don't know how to get the Stream response to decompress, and send back to context.Response.OutputStream Any help will be appreciated.Thanks.Cheers. EDIT 2: With this edit now seems to be working fine (same as HttpWebRequest at least). Do you find any error here? EDIT 3: False alarm... Still can't get this working EDIT 4: I needed to add the following lines to Scott's code ... because not always the first to bytes of reponseStream are the gzip magic number.The sequence seems to be: 0x0a (10), 0x1f (31), 0x8b (139). The last two are the gzip magic number. The first number was always before in my tests. if (contentEncoding.Equals("gzip")){ int magicNumber = 0; while (magicNumber != 10) magicNumber = responseStream.ReadByte(); responseStream = new GZipStream(responseStream, CompressionMode.Decompress);} Now provide the response and nothing else.
Here's some code that works for me. using System;using System.Collections.Generic;using System.IO;using System.Net;using System.Net.Sockets;using System.Text;using System.IO.Compression;namespace HttpUsingSockets { public class Program { private static readonly Encoding DefaultEncoding = Encoding.ASCII; private static readonly byte[] LineTerminator = new byte[] { 13, 10 }; public static void Main(string[] args) { var host = "stackoverflow.com"; var url = "/questions/523930/sockets-in-c-how-to-get-the-response-stream"; IPHostEntry ipAddress = Dns.GetHostEntry(host); var ip = new IPEndPoint(ipAddress.AddressList[0], 80); using (var socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { socket.Connect(ip); using (var n = new NetworkStream(socket)) { SendRequest(n, new[] {"GET " + url + " HTTP/1.1", "Host: " + host, "Connection: Close", "Accept-Encoding: gzip"}); var headers = new Dictionary<string, string>(); while (true) { var line = ReadLine(n); if (line.Length == 0) { break; } int index = line.IndexOf(':'); headers.Add(line.Substring(0, index), line.Substring(index + 2)); } string contentEncoding; if (headers.TryGetValue("Content-Encoding", out contentEncoding)) { Stream responseStream = n; if (contentEncoding.Equals("gzip")) { responseStream = new GZipStream(responseStream, CompressionMode.Decompress); } else if (contentEncoding.Equals("deflate")) { responseStream = new DeflateStream(responseStream, CompressionMode.Decompress); } var memStream = new MemoryStream(); var respBuffer = new byte[4096]; try { int bytesRead = responseStream.Read(respBuffer, 0, respBuffer.Length); while (bytesRead > 0) { memStream.Write(respBuffer, 0, bytesRead); bytesRead = responseStream.Read(respBuffer, 0, respBuffer.Length); } } finally { responseStream.Close(); } var body = DefaultEncoding.GetString(memStream.ToArray()); Console.WriteLine(body); } else { while (true) { var line = ReadLine(n); if (line == null) { break; } Console.WriteLine(line); } } } } } static void SendRequest(Stream stream, IEnumerable<string> request) { foreach (var r in request) { var data = DefaultEncoding.GetBytes(r); stream.Write(data, 0, data.Length); stream.Write(LineTerminator, 0, 2); } stream.Write(LineTerminator, 0, 2); // Eat response var response = ReadLine(stream); } static string ReadLine(Stream stream) { var lineBuffer = new List<byte>(); while (true) { int b = stream.ReadByte(); if (b == -1) { return null; } if (b == 10) { break; } if (b != 13) { lineBuffer.Add((byte)b); } } return DefaultEncoding.GetString(lineBuffer.ToArray()); } }} You could substitute this for the Socket/NetworkStream and save a bit of work. using (var client = new TcpClient(host, 80)) { using (var n = client.GetStream()) { }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/523930', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4386/']}
jdg_371559
stackexchange
llm_judgeable_groundtruth_similarity
7123599
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 div with ajax-loader gif image <div id="mydiv" style="height: 400px; text-align: center;"> <img src="/Content/ajax-loader.gif" class="ajax-loader"/></div> .ajax-loader{ /*hidden from IE 5-6 */ margin-top: 0; /* to clean up, just in case IE later supports valign! */ vertical-align: middle; margin-top: expression(( 150 - this.height ) / 2); } But could not get it displayed in the center (both vertically and horizontally). Need help with that. Now provide the response and nothing else.
The following assumes that the width and height of the image is known: #mydiv { height: 400px; position: relative; background-color: gray; /* for demonstration */}.ajax-loader { position: absolute; left: 50%; top: 50%; margin-left: -32px; /* -1 * image width / 2 */ margin-top: -32px; /* -1 * image height / 2 */} <div id="mydiv"> <img src="http://dummyimage.com/64x64/000/fff.gif&text=LOADING" class="ajax-loader"></div> UPDATE : in modern browsers margin: auto will produce the desired result withing knowing the width/height of the image: #mydiv { height: 400px; position: relative; background-color: gray; /* for demonstration */}.ajax-loader { position: absolute; left: 0; top: 0; right: 0; bottom: 0; margin: auto; /* presto! */} <div id="mydiv"> <img src="http://dummyimage.com/64x64/000/fff.gif&text=LOADING" class="ajax-loader"></div>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7123599', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/733323/']}
jdg_371560
stackexchange
llm_judgeable_groundtruth_similarity
19982
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 need to solve a non-linear set of three equations using scipy. However, I do not have any clue on which algorithm is suitable for my problem from a mathematical point of view (stability, convergence behaviour), since scipy provides a huge variety of different algorithms in the scipy.optimize module such as: scipy.optimize.root scipy.optimize.fsolve nonlinear solvers Here is my non-linear set (two linear, and a non-linear) of equations with 3 unknown variables: $$Q(t_k)=m_Sc_S\left(\vartheta_S(t_k)-\vartheta_S(t_{k-1})\right)\\Q(t_k)=\dot{m}_Gc_{pG}\big(\vartheta_{GE}-\vartheta_{GA}(t_{k})\big)\Delta t\\Q(t_k)=A\alpha\frac{\big(\vartheta_S(t_k)-\vartheta_{GE}\big)-\big(\vartheta_S(t_k)-\vartheta_{GA}(t_k)\big)}{\ln{\left(\frac{\vartheta_S(t_k)-\vartheta_{GE}}{\vartheta_S(t_k)-\vartheta_GA(t_k)}\right)}}\Delta t$$ where unknown variables are: $\vartheta_S(t_k)$ $\vartheta_{GA}(t_k)$ $Q(t_k)$ and $m_S = 6.868\,\mathrm{kg}$ $\dot{m}_G = 0.007\,\mathrm{kg/s}$ $c_S = 500\,\mathrm{J/kg K}$ $c_{pG} = 1005\,\mathrm{J/kg K}$ $\vartheta_S(0) = 273\,\mathrm{K}$ $\vartheta_{GA}(0) = 293\,\mathrm{K}$ $\vartheta_{GE} = 353\,\mathrm{K}$ $A = 3.733\,\mathrm{m}^2$ $\alpha = 99\,\mathrm{W/m}^2\mathrm{K}$ $\Delta t = t_k-t_{k-1} = 1\,\mathrm{s}$ Which algorithm is probably the best one for my problem? Now provide the response and nothing else.
Since your problem is small, you're probably best off trying fsolve or root . Both of these are interfaces to MINPACK and call HYBRD or HYBRJ . Since calculating a Jacobian matrix for your system shouldn't be hard (either do it by hand, or use your favorite computer algebra system, like SymPy, Sage, Maple, or Mathematica), you should supply a Jacobian matrix. The HYBR functions in MINPACK use "Powell's hybrid method", which uses Newton's method and checks if Newton steps will be descent steps by comparing against least-squares minimization (specifically, does the Newton step also decrease the sum-of-squared-residuals). If Newton steps are not descent steps, then it falls back to the gradient of the sum-of-squared-residuals. I think you're probably better off ignoring all of the alternatives for now. All of these other alternatives, broadly speaking, try to find low-dimensional structure in high-dimensional problems. Your problem has dimension 3, so the comparative savings of finding lower-dimensional structure aren't that great compared to, say, PDE discretizations that might have tens of thousands of variables.
{}
{'log_upvote_score': 4, 'links': ['https://scicomp.stackexchange.com/questions/19982', 'https://scicomp.stackexchange.com', 'https://scicomp.stackexchange.com/users/16692/']}
jdg_371561
stackexchange
llm_judgeable_groundtruth_similarity
5511
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 are you handling the entry of numeric values in WPF applications? Without a NumericUpDown control, I've been using a TextBox and handling its PreviewKeyDown event with the code below, but it's pretty ugly. Has anyone found a more graceful way to get numeric data from the user without relying on a third-party control? private void NumericEditPreviewKeyDown(object sender, KeyEventArgs e){ bool isNumPadNumeric = (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal; bool isNumeric = (e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod; if ((isNumeric || isNumPadNumeric) && Keyboard.Modifiers != ModifierKeys.None) { e.Handled = true; return; } bool isControl = ((Keyboard.Modifiers != ModifierKeys.None && Keyboard.Modifiers != ModifierKeys.Shift) || e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Insert || e.Key == Key.Down || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Up || e.Key == Key.Tab || e.Key == Key.PageDown || e.Key == Key.PageUp || e.Key == Key.Enter || e.Key == Key.Return || e.Key == Key.Escape || e.Key == Key.Home || e.Key == Key.End); e.Handled = !isControl && !isNumeric && !isNumPadNumeric;} Now provide the response and nothing else.
How about: protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e){ e.Handled = !AreAllValidNumericChars(e.Text); base.OnPreviewTextInput(e);}private bool AreAllValidNumericChars(string str){ foreach(char c in str) { if(!Char.IsNumber(c)) return false; } return true;}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5511', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/615/']}
jdg_371562
stackexchange
llm_judgeable_groundtruth_similarity
22137778
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 recently ran npm install (npm 1.4.3) with the --save-dev flag and the package entries it added to my package.json all began with a ^ , e.g. "^2.5.0" . I have never seen this before with the earlier versions of npm I have used, and I cannot find any documentation for this notation, only for the notations I'm already familiar with, e.g. ~ , >= etc.. What does it mean? Now provide the response and nothing else.
Quoting from isaacs/node-semver : ^1.2.3 := >=1.2.3-0 <2.0.0-0 "Compatible with 1.2.3". When using caret operators, anything from the specified version (including prerelease) will be supported up to, but not including, the next major version (or its prereleases). 1.5.1 will satisfy ^1.2.3, while 1.2.2 and 2.0.0-beta will not. ^0.1.3 := >=0.1.3-0 <0.2.0-0 "Compatible with 0.1.3". 0.x.x versions are special: the first non-zero component indicates potentially breaking changes, meaning the caret operator matches any version with the same first non-zero component starting at the specified version. ^0.0.2 := =0.0.2 "Only the version 0.0.2 is considered compatible" That said, I would recommend to use "~" instead because it has more intuitive semantics, see discussion in npm/npm#4587 .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/22137778', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2128319/']}
jdg_371563
stackexchange
llm_judgeable_groundtruth_similarity
15199292
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an Outer class which has a private Inner class. In my Outer class method, I instantiate the Inner class as follows: Outer outer = new Outer();Inner inner = outer.new Inner(); The compiler converts this code to: Outer outer = new Outer();Inner inner = new Inner(outer, null); Using reflection shows that the Inner class has the following synthesized constructors: private Outer$Inner(Outer)Outer$Inner(Outer,Outer$Inner) Since the Inner class is private , the compiler adds that private constructor to it so nobody can instantiate that class. But obviously the Outer class should be able to instantiate it, so the compiler adds that other package private constructor which in turn calls the private constructor. Also, since the package-private constructor has that $ in its name, normal Java code can't call it. Question: why synthesize one private and one package-private constructor? Why not synthesize only the package-private constructor and be done with it? Now provide the response and nothing else.
If you write the code like, public class Outer { private class Inner {}} You will note that there is only one constructor private Outer$Inner(Outer) This constructor is required by Section 8.8.9 of the JLS , which says that if no constructor is defined a default constructor must be generated, and in this case the default constructor must be private, In a class type, if the class is declared public, then the default constructor is implicitly given the access modifier public (§6.6); if the class is declared protected, then the default constructor is implicitly given the access modifier protected (§6.6); if the class is declared private, then the default constructor is implicitly given the access modifier private (§6.6); otherwise, the default constructor has the default access implied by no access modifier. However, when you you instantiate an instance of Inner inside Outer with code like, public class Outer { private class Inner {} public String foo() { return new Inner().toString(); }} The compiler has to generate a constructor that Outer can legally call (you can't legally call the private default constructor because it is private). So a new synthetic constructor must be generated by the compiler. The new constructor must be synthetic, according to section 13.1 of the JLS Any constructs introduced by the compiler that do not have a corresponding construct in the source code must be marked as synthetic, except for default constructors and the class initialization method. This second constructor has no corresponding construct in the source code, so this new constructor must be synthetic. The first private constructor must still be generated, since the JLS requires a private default constructor.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15199292', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/266103/']}
jdg_371564
stackexchange
llm_judgeable_groundtruth_similarity
639111
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: According to my probably antiquated knowledge I shouldn't be able to listen to anything if I plug my 300 Ω headphones (Sennheiser HD60) in my laptop or my phone, but it does play at a decent volume. Does it use a different technology from decades ago? Now provide the response and nothing else.
For a given applied voltage on the headphone speaker (say 1 volt RMS) the power into an 8 Ω speaker will be 125 mW. Into a 300 Ω speaker it will be 3.333 mW. That's a decibel reduction in sound of nearly 16 dB. A human is capable of perceiving a range of 90 dB before getting into things being too loud hence a 16 dB reduction between two relative sounds is not that troublesome. Images from here . And, it's quite possible that the higher impedance coils will be more efficient in a typical headphone socket that has dropper resistors to prevent acoustic shock on receiving speaker level voltages on your headphones.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/639111', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/39863/']}
jdg_371565
stackexchange
llm_judgeable_groundtruth_similarity
16509414
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 not, what is the standard way to free up cudaMalloc ed memory when an exception is thrown? (Note that I am unable to use Thrust.) Now provide the response and nothing else.
You can use RAII idiom and put your cudaMalloc() and cudaFree() calls to the constructor and destructor of your object respectively. Once the exception is thrown your destructor will be called which will free the allocated memory. If you wrap this object into a smart-pointer (or make it behave like a pointer) you will get your CUDA smart-pointer.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16509414', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1681681/']}
jdg_371566
stackexchange
llm_judgeable_groundtruth_similarity
1855408
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 trying to find interesting proofs that Student's T Distribution converges to the Regularized Normal Distribution when $k$ (the number of desgrees of freedom) grows without bounds (i.e. $= \infty$). One of the ways I tried involved trying to find an expansion for $\frac{\Gamma\left(\frac{v+1}{2}\right)}{\Gamma\left(\frac{v}{2}\right)}$ about $v=\infty$, though I could not make any headway on finding the expansion and I feared it would be extremely complicated. However, when I asked Wolfram Alpha I got a beautiful Puiseux Series, which is expressed as:$$\frac{\Gamma\left(\frac{v+1}{2}\right)}{\Gamma\left(\frac{v}{2}\right)}\simeq \frac{v^{1/2}}{\sqrt2}-\frac{v^{-1/2}}{4\sqrt2}+\frac{v^{-3/2}}{32\sqrt2}+5\frac{v^{-5/2}}{128\sqrt2}-21\frac{v^{-5/2}}{2048\sqrt2}+\cdots$$(more terms can be found in the link provided if desired). I can't help but notice that the denominators are simply $2^n \sqrt{2}$ for $n\in(0,2,5,7,11,\ldots)$ However, I can't find any pattern in $n$, nor can I explain the additional coefficients that appear starting on the fourth term, so I can't think of a way to work backward to find a proof. Regardless, all I need is the first term for the purpose of taking a limit, as all the other terms will vanish anyway. Does anyone know how to prove the expansion? Edit: I should note that I have already attacked the problem using Stirlings Series, but I found that to be somewhat brute force for such a simple summation and I hoped for a more clever argument (it does however some light on where the coefficients come from). Again, I only need to know the series up to $\frac{v^{1/2}}{\sqrt2} + O(v^{-1/2})$ Now provide the response and nothing else.
Powers of $\boldsymbol{2}$ in the denominator This is only an observational guess, but I have computed the asymptotic series for$$\frac{\Gamma\left(x+\frac12\right)}{\Gamma(x)\sqrt{x}}$$out a large number of terms and the exponents of $2$ in the denominators seem to be$$3n+\sum_{k=1}^\infty\left\lfloor\frac{n}{2^k}\right\rfloor$$Thus, the exponents of $2$ in the denominators of the asymptotic series for$$\frac{\Gamma\left(\frac{v+1}2\right)}{\Gamma\left(\frac{v}2\right)\sqrt{\frac{v}2}}$$would be$$\bbox[5px,border:2px solid #C0A000]{2n+\sum_{k=1}^\infty\left\lfloor\frac{n}{2^k}\right\rfloor}$$This gives denominators of$$2^0,2^2,2^5,2^7,2^{11},2^{13},2^{16},2^{18},2^{23},2^{25},2^{28},\dots$$ The Asymptotic Series To compute the asymptotic series, we can compute the series at infinity$$\begin{align}&\textstyle\log\left(x-\tfrac12\right)-\log(x-1)\\&\textstyle=\log\left(1-\tfrac1{2x}\right)-\log\left(1-\tfrac1x\right)\\&\textstyle=\frac1{2x}+\frac3{8x^2}+\frac7{24x^3}+\frac{15}{64x^4}+\frac{31}{160x^5}+\frac{21}{128x^6}+\frac{127}{896x^7}+\frac{255}{2048x^8}+\frac{511}{4608x^9}+\frac{1023}{10240x^{10}}\\&\textstyle+\frac{2047}{22528x^{11}}+\frac{1365}{16384x^{12}}+\frac{8191}{106496x^{13}}+\frac{16383}{229376x^{14}}+\frac{32767}{491520x^{15}}+\frac{65535}{1048576x^{16}}+\frac{131071}{2228224x^{17}}\\&\textstyle+\frac{29127}{524288x^{18}}+\frac{524287}{9961472x^{19}}+\frac{209715}{4194304x^{20}}+\frac{299593}{6291456x^{21}}+\frac{4194303}{92274688x^{22}}+\frac{8388607}{192937984x^{23}}+O\!\left(\frac1{x^{24}}\right)\tag{1}\end{align}$$Then we can apply the Euler-Maclaurin Sum Formula to get$$\begin{align}&\textstyle\log\left(\frac{\large\Gamma\left(x+\frac12\right)}{\large\Gamma\left(x\right)\vphantom{\frac12}}\right)\\&\textstyle=\frac12\log(x)-\frac1{8x}+\frac1{192x^3}-\frac1{640x^5}+\frac{17}{14336x^7}-\frac{31}{18432 x^9}+\frac{691}{180224x^{11}}-\frac{5461}{425984x^{13}}\\&\textstyle+\frac{929569}{15728640x^{15}}-\frac{3202291}{8912896x^{17}}+\frac{221930581}{79691776x^{19}}-\frac{4722116521}{176160768x^{21}}+O\!\left(\frac1{x^{23}}\right)\tag{2}\end{align}$$Then we can exponentiate to get$$\begin{align}&\textstyle\frac{\large\Gamma\left(x+\frac12\right)}{\large\Gamma\left(x\right)\vphantom{\frac12}\sqrt{x}}\\&\textstyle=1-\frac1{8x}+\frac1{128x^2}+\frac5{1024x^3}-\frac{21}{32768x^4}-\frac{399}{262144x^5}+\frac{869}{4194304x^6}+\frac{39325}{33554432x^7}\\&\textstyle-\frac{334477}{2147483648x^8}-\frac{28717403}{17179869184x^9}+\frac{59697183}{274877906944x^{10}}+\frac{8400372435}{2199023255552x^{11}}-\frac{34429291905}{70368744177664x^{12}}\\&\textstyle-\frac{7199255611995}{562949953421312x^{13}}+\frac{14631594576045}{9007199254740992x^{14}}+\frac{4251206967062925}{72057594037927936x^{15}}-\frac{68787420596367165}{9223372036854775808x^{16}}\\&\textstyle-\frac{26475975382085110035}{73786976294838206464x^{17}}+\frac{53392138323683746235}{1180591620717411303424x^{18}}+\frac{26275374869163335461975}{9444732965739290427392x^{19}}\\&\textstyle-\frac{105772979046693606062363}{302231454903657293676544x^{20}}-\frac{64759060397977041632277937}{2417851639229258349412352x^{21}}+\frac{130175508110590141461339987}{38685626227668133590597632x^{22}}\\&\textstyle+O\!\left(\frac1{x^{23}}\right)\tag{3}\end{align}$$Then we can substitute $x=\frac v2$ to get$$\begin{align}&\textstyle\frac{\large\Gamma\left(\frac{v+1}2\right)}{\large\Gamma\left(\frac{v}2\right)\sqrt{\frac{v}2}}\\&\textstyle=1-\frac1{4v}+\frac1{32v^2}+\frac5{128v^3}-\frac{21}{2048v^4}-\frac{399}{8192v^5}+\frac{869}{65536v^6}+\frac{39325}{262144v^7}\\&\textstyle-\frac{334477}{8388608v^8}-\frac{28717403}{33554432x^9}+\frac{59697183}{268435456v^{10}}+\frac{8400372435}{1073741824v^{11}}-\frac{34429291905}{17179869184v^{12}}\\&\textstyle-\frac{7199255611995}{68719476736v^{13}}+\frac{14631594576045}{549755813888v^{14}}+\frac{4251206967062925}{2199023255552v^{15}}-\frac{68787420596367165}{140737488355328v^{16}}\\&\textstyle-\frac{26475975382085110035}{562949953421312v^{17}}+\frac{53392138323683746235}{4503599627370496v^{18}}+\frac{26275374869163335461975}{18014398509481984v^{19}}\\&\textstyle-\frac{105772979046693606062363}{288230376151711744v^{20}}-\frac{64759060397977041632277937}{1152921504606846976v^{21}}+\frac{130175508110590141461339987}{9223372036854775808v^{22}}\\&\textstyle+O\!\left(\frac1{v^{23}}\right)\tag{4}\end{align}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1855408', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/269764/']}
jdg_371567
stackexchange
llm_judgeable_groundtruth_similarity
7353218
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to find out if a vector of pointers contains an entry that is NULL, preferably using code in the STL and not writing a loop. I've tried this expression: std::find(dependent_events.begin(), dependent_events.end(), NULL) But I get errors telling me that I have a "comparison between a pointer and an integer." Is there a better way to do this? Now provide the response and nothing else.
NULL in C++ is just an integer constant. The pointer conversion is implicit in appropriate contexts, but this isn’t one. You need to cast explicitly: std::find(dependent_events.begin(), dependent_events.end(), static_cast<P>(0)); Where P is the appropriate type of the pointers in the collection. Alternatively, Eddie has correctly pointed out the C++11 solution which should work in modern compilers (if C++11 has been enabled). The reason that plain NULL doesn’t work is the following: C++ forbids implicit conversion of an integer to a pointer. There is one exception only, a literal value 0 is treated as a null pointer in initialisations and assignments to pointers (literal 0 acts as the “null pointer constant”, §4.10), and NULL is just 0 (§18.1.4). But when used in a template instantiation (such as in the above call to find ), C++ needs to infer a template type for each of its parameters and the type inferred for 0 is always the same : int . So find is called with an int argument (which, inside the function, is no longer a literal ) and as mentioned above, there is no implicit conversion between int and a pointer.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7353218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/250096/']}
jdg_371568
stackexchange
llm_judgeable_groundtruth_similarity
1240057
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking for suggestions to improve the process of automating functional testing of a website. Here's what I've tried in the past. I used to have a test project using WATIN . You effectively write what look like "unit tests" and use WATIN to automate a browser to click around your site etc. Of course, you need a site to be running. So I made the test actually copy the code from my web project to a local directory and started a web server pointing to that directory before any of the tests run. That way, someone new could simply get latest from our source control and run our build script, and see all the tests run. They could also simply run all the tests from the IDE. The problem I ran into was that I spent a lot of time maintaining the code to set up the test environment more than the tests. Not to mention that it took a long time to run because of all that copying. Also, I needed to test out various scenarios including installation, meaning I needed to be able to set the database to various initial states. I was curious on what you've done to automate functional testing to solve some of these issues and still keep it simple. MORE DETAILS Since people asked for more details, here it is. I'm running ASP.NET using Visual Studio and Cassini (the built in web server). My unit tests run in MbUnit (but that's not so important. Could be NUnit or XUnit.NET). Typically, I have a separate unit test framework run all my WATIN tests. In the AssemblyLoad phase, I start the webserver and copy all my web application code locally. I'm interested in solutions for any platform, but I may need more descriptions on what each thing means. :) Now provide the response and nothing else.
Phil, Automation can just be hard to maintain, but the more you use your automation for deployment, the more you can leverage it for test setup (and vice versa). Frankly, it's easier to evolve automation code, factoring it and refactoring it into specific, small units of functionality when using a build tool that isn't just driving statically-compiled, pre-factored units of functionality, as is the case with NAnt and MSBuild. This is one of the reasons that many people who were relatively early users of toole like NAnt have moved off to Rake. The freedom to treat build code as any other code - to cotinually evolve its content and shape - is greater with Rake. You don't end up with the same stasis in automation artifacts as easily and as quickly with Rake, and it's a lot easier to script in Rake than NAnt or MSBuild. So, some part of your struggle is inherently bound up in the tools. To keep your automation sensible and maintained, you should be wary of obstructions that static build tools like NAnt and MSBuild impose. I would suggest that you not couple your test environment boot-strapping from assembly load. That's an inside-out coupling that only serves brief convenience. There's nothing wrong (and, likely everything right) with going to the command line and executing the build task that sets up the environment before running tests either from the IDE or from the command line, or from an interactive console, like the C# REPL from the Mono Project, or from IRB. Test data setup is simply just a pain in the butt sometimes. It has to be done. You're going to need a library that you can call to create and clean up database state. You can make those calls right from your test code, but I personally tend to avoid doing this because there is more than one good use of test data or sample data control code. I drive all sample data control from HTTP. I write controllers with actions specifically for controlling sample data and issue GETs against those actions through Selenium. I use these to create and clean up data. I can compose GETs to these actions to create common scenarios of setup data, and I can pass specific values for data as request parameters (or form parameters if needs be). I keep these controllers in an area that I usually call "test_support". My automation for deploying the website does not deploy the test_support area or its routes and mapping. As part of my deployment verification automation, I make sure that the test_support code is not in the production app. I also use the test_support code to automate control over the entire environment - replacing services with fakes, turning off subsystems to simulate failures and failovers, activating or deactivating authentication and access control for functional testing that isn't concerned with these facets, etc. There's a great secondary value to controlling your web app's sample data or test data from the web: when demoing the app, or when doing exploratory testing, you can create the data scenarios you need just by issuing some gets against known (or guessable) urls in the test_support area. Really making a disciplined effort to stick to restful routes and resource-orientation here will really pay off. There's a lot more to this functional automation (including test, deployment, demoing, etc) so the better designed these resources are, the better the time you'll have maintaining them over the long hall, and the more opportunities you'll find to leverage them in unforseen but beneficial ways. For example, writing domain model code over the semantic model of your web pages will help create much more understandable test code and decrease the brittleness. If you do this well, you can use those same models with a variety of different drivers so that you can leverage them in stress tests and load tests as well as functional test as well as using them from the command line as exploratory tools. By the way, this kind of thing is easier to do when you're not bound to driver types as you are when you use a static language. There's a reason why many leading testing thinkers and doers work in Ruby, and why Watir is written in Ruby. Reuse, composition, and expressiveness is much easier to achieve in Ruby than C# test code. But that's another story. Let's catch up sometime and talk more about the other 90% of this stuff :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1240057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/598/']}
jdg_371569
stackexchange
llm_judgeable_groundtruth_similarity
7208383
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 MSChart that looks like the following. http://11.a.hostable.me/images/june2007.JPG What I would like to do is adjust the x axis labels: I want to label every column, not every 5 I want to specify what each label is. What I don't understand, is when I have it on the "all years" view (as seen below), the number I assign as the XValue using oDataPoint_PV.SetValueXY(Year, Views) makes it so the year I specify shows as the label, but for some reason when on the Months view, it starts at 1 instead of the first value I set, which happens to be 13 for this example. oDataPoint_PV.SetValueXY(Day, Views) In the chart for June 2007, it should start at 13, and go to july 12th. http://11.a.hostable.me/images/years.JPG Now provide the response and nothing else.
To answer your first question: "I want to label every column, not every 5"You can specify how frequently the label is displayed using the interval property. chart1.ChartAreas[0].AxisX.Interval = [desired interval]; or to set the interval just for the labels use: chart1.ChartAreas[0].AxisX.LabelStyle.Interval = [desired interval]; If I follow the end of your question correctly where you don't want your chart to start at zero, you can use a label offset. chart1.ChartAreas[0].AxisX.LabelStyle.Offset = 1; This will skip the first label which you mention is zero. The second objective "I want to specify what each label is" can be solved in several ways One method is to display the (x or y) value on the (x or y) axis, which I believe is the method you are using based on information you provide in your question Another way is to set the axis label manually for each data point chart1.Series[0].Points[0].AxisLabel = "your label" You can also add the label info when you are adding data points chart1.Series[0].Points.Add(new DataPoint(4, 4) { AxisLabel = "your label" }); Lastly, you can micromanage your labels using custom labels, but that can be more complicated, and based on what you have typed you probably don't need to use those so I won't go into them. Also, are you setting your xvalue using a string or a DateTime object? Something like this: Chart1.Series[0].XValueType = ChartValueType.DateTime;System.DateTime x = new System.DateTime(2008, 11, 21);Chart1.Series[0].Points.AddXY(x.ToOADate(), 34); If so, when working with date time labels, Microsoft chart objects have additional features you can set to manipulate how it displays. Here is some additional information you might find helpful. http://msdn.microsoft.com/en-us/library/dd456614.aspx You can then utilize properties such as these (and I am sure more, but I don't often work with dates) chart1.ChartAreas[0].AxisX.LabelStyle.IntervalType = System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Days;chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Days; If I have not properly answered your questions due to a misunderstanding, please let me know and revise your question to guide me in the right direction (Code examples with actual data you use to generate the plots, with resulting images + what you want it to do instead of what is displayed in the image is helpful - you have part of this but it is incomplete) Good luck!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7208383', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/914499/']}
jdg_371570
stackexchange
llm_judgeable_groundtruth_similarity
16751643
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Just covered out some strage specs regarding ARIA roles . Why does ul have ARIA role menu but menuitem is forbidden for li ? I would like to describe a navigation bar using ul , li and HTML5's nav element in combination with the ARIA roles navigation , menu and menuitem . <!DOCTYPE html><html> <head><title>ARIA role bug?</title></head> <body> <nav role="navigation"> <ul role="menu"> <li role="menuitem"><a href="http://example.com/">example.com</a></li> </ul> </nav> </body></html> W3's HTML5 validator nag me here: Bad value menuitem for attribute role on element li. Now provide the response and nothing else.
Jukka is incorrect here . The W3C validator does not check against the WHATWG LS, instead it checks against the W3C HTML specification . The W3C HTML spec is the authoritative source for conformance checking requirements for the W3C Validator. In regards to menuitem not being allowed as per the HTML spec, I believe this is a bug. And as such I have filed a bug . It is now in my bug queue to be resolved. I have filed a bug against the W3C validator and wai-aria in HTML doc as well.Until such times the validator is fixed, I suggest you use the roles as per the WAI-ARIA spec and ignore the validator. addendum: I looked back at history of ARIA integration into HTML could not find any reason why menuitem was not allowed, so believe it was an oversight. I fixed and resolved the bug I referenced above.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16751643', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1016105/']}
jdg_371571
stackexchange
llm_judgeable_groundtruth_similarity
19304165
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to create new log files on an hourly basis. I am using TimeBasedTriggerringPolicy of lo4j2 in RollingFileAppender. Below is the sample xml configuration code i have taken from log4j2 official site. <?xml version="1.0" encoding="UTF-8"?><Configuration status="warn" name="MyApp" packages=""> <Appenders> <RollingFile name="RollingFile" fileName="logs/app.log" filePattern="logs/$${date:yyyy-MM}/app-%d{yyyy-MM-dd-HH}-%i.log.gz"> <PatternLayout> <Pattern>%d %p %c{1.} [%t] %m%n</Pattern> </PatternLayout> <Policies> ** <TimeBasedTriggeringPolicy interval="1" modulate="true" /> ** <SizeBasedTriggeringPolicy size="250 MB" /> </Policies> </RollingFile> </Appenders> <Loggers> <Root level="error"> <AppenderRef ref="RollingFile" /> </Root> </Loggers></Configuration> In the interval attribute I have set 1 which signifies 1 hour.But still my file does not roll every 1 hour. Please help me find any mistake. Note : I have included beta9 of log4j2 (which is the latest) Now provide the response and nothing else.
1 here indicates 1 day and not 1 hour. I have manually tested with below configuration. <RollingFile name="T" fileName="/data_test/log/abc.log" filePattern="/data_test/log/abc-%d{MM-dd-yyyy}-%i.log"> <PatternLayout> <Pattern>%d{ISO8601} %-5p [%t] (%F:%L) - %m%n</Pattern> </PatternLayout> <Policies> <TimeBasedTriggeringPolicy interval="1" modulate="true"/> <SizeBasedTriggeringPolicy size="100 KB" /> </Policies> </RollingFile> For manual testing, I change the system date and time.First, try with increasing 1 hour. The log files will be generated but not as per the expectation.Then change the system date, increase by 1 day and then see the results. Suppose the last log file (abc.log) on day 29-Oct is of 50 KB. Configuration size is 100 KB. If we change the day (increase by 1 day) and then run.Then, last file will be renamed 29-Oct-(some sequence number).log (50 KB file as it is copied) and new file will be created with abc.log I have tried this with simple servlet with below configuration in web.xml <context-param> <param-name>log4jConfiguration</param-name> <param-value>log4j2.xml</param-value></context-param> keep log4j2.xml in src folder. log4j2.xml is not loaded if we keep it in classpath.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19304165', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1890780/']}
jdg_371572
stackexchange
llm_judgeable_groundtruth_similarity
2443867
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 Windows Service written in C# that handles all of our external hardware I/O for a kiosk application. One of our new devices is a USB device that comes with an API in a native DLL. I have a proper P/Invoke wrapper class created. However, this API must be initialized with an HWnd to a windows application because it uses the message pump to raise asynchronous events. Besides putting in a request to the hardware manufacturer to provide us with an API that does not depend on a Windows message pump, is there any way to manually instantiate a message pump in a new thread in my Windows Service that I can pass into this API? Do I actually have to create a full Application class, or is there a lower level .NET class that encapsulates a message pump? Now provide the response and nothing else.
Thanks all for your suggestions. Richard & overslacked, the link you provided in the comments was very helpful. Also, I did not have to allow the service to interact with the desktop in order to manually start a message pump with Application.Run. Apparently, you only need to allow the service to interact with the desktop if you want Windows to start a message pump automatically for you. For everyone's edification, here is what I ended up doing to manually start a message pump for this 3rd party API: internal class MessageHandler : NativeWindow{ public event EventHandler<MessageData> MessageReceived; public MessageHandler () { CreateHandle(new CreateParams()); } protected override void WndProc(ref Message msg) { // filter messages here for your purposes EventHandler<MessageData> handler = MessageReceived; if (handler != null) handler(ref msg); base.WndProc(ref msg); }}public class MessagePumpManager{ private readonly Thread messagePump; private AutoResetEvent messagePumpRunning = new AutoResetEvent(false); public StartMessagePump() { // start message pump in its own thread messagePump = new Thread(RunMessagePump) {Name = "ManualMessagePump"}; messagePump.Start(); messagePumpRunning.WaitOne(); } // Message Pump Thread private void RunMessagePump() { // Create control to handle windows messages MessageHandler messageHandler = new MessageHandler(); // Initialize 3rd party dll DLL.Init(messageHandler.Handle); Console.WriteLine("Message Pump Thread Started"); messagePumpRunning.Set(); Application.Run(); }} I had to overcome a few hurdles to get this to work. One is that you need to make certain to create the Form on the same thread that you execute Application.Run. You also can only access the Handle property from that same thread, so I found it easiest to simply initialized the DLL on that thread as well. For all I know, it is expecting to be initialized from a GUI thread anyway. Also, in my implementation, the MessagePumpManager class is a Singleton instance, so that only one message pump runs for all instances of my device class. Make sure that you truly lazy-initialize your singleton instance if you start the thread in your constructor. If you start the thread from a static context (such as private static MessagePumpManager instance = new MessagePumpManager();) the runtime will never context switch into the newly created thread, and you will deadlock while waiting for the message pump to start.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2443867', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/54406/']}
jdg_371573
stackexchange
llm_judgeable_groundtruth_similarity
102
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I see a lot of people (extension authors and others) give configuration examples with setq : (setq foo 'bar) These parameters are often defined with defcustom , making them available for customization through custom.el . I typically use custom.el to set them. Would there be any advantage to using setq instead or are the two methods roughly equivalent? Now provide the response and nothing else.
Some people might think it is simpler to use setq . Some people might think it is more lispy. In reality, it is naive in the general case. It is true that for some user options it does not matter. But for others, it does matter, and setq is the wrong approach for those options. So as a general rule, setq is the wrong approach. If you use custom-set-variables or customize-set-variable instead of setq , or if you use the Customize user interface (e.g. M-x customize-option ), then you are sure that any intended initialization or updating code that is needed for the option value will be automatically triggered and run as needed. If you use setq , this will not be done. Now, it is also the case that most user options, especially many of them written for 3rd-party libraries, do not make use of the defcustom keywords :set and :initialize , and using setq does not matter for them. But lots of vanilla Emacs options do use such keywords, and for those that do, setq is not the right thing.So if you want to use Lisp code and not the Customize UI to set your options, then you are better off using custom-set-variables or customize-set-variable instead of setq . It never hurts and it sometimes helps (a lot). But what I recommend is to do both of these things: Use the Customize UI instead of writing Lisp code for this. Define variable custom-file , so that Customize writes customizations to that file and not to your init file ( ~/.emacs ). IOW, keep your hand-written initialization code separate from the automatic code written by Customize.
{}
{'log_upvote_score': 8, 'links': ['https://emacs.stackexchange.com/questions/102', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/147/']}
jdg_371574
stackexchange
llm_judgeable_groundtruth_similarity
140991
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have to backup my hard disk. I want to use dd and put the image on an external hdd. Can I do this using dd from the OS that resides on the hdd itself or do I have to boot from another device, for example a LiveCD? Is it safe, in general, to take the image of a device, if the device is mounted and working? What if the device is mounted, but I'm sure there's no other I/O operation, while dd is running? I'm sure that rsync is the best tool to use for backups, specially the incremental ones. But I'm interested in dd , because I want to backup up also other storage devices, and it copies also data stored on unpartitioned space. For example, my e-book reader use an unpartitioned space to store uboot, kernel and other data. Now provide the response and nothing else.
In general it is not safe. The FS assumes that operations are written in certain order so it can write new data of file and then make a pointer to it from other data, the exact details depend on filesystem. Imagine if following happens: dd reads from location X which contains garbage or some data Filesystem writes to location X Filesystem writes to location X+1 pointer to location X dd reads from location X+1 link to location X From the point of view of backup you get a garbage data. However there are several ways to workaround it: Freeze filesystem by filesystem specific command (I believe xfs_freeze is one and I don't know any other - but such option exists at least in theory) Create a lvm snapshot and copy from it. The copy will be as-if you rebooted the computer (minus the HDD reordering) so it will be a dirty filesystem but the copy will be atomic. Note that some filesystems like XFS needs to be frozen first. Use rsync as suggested by others. Now the copy is safe and you don't need LVM but the copy is not atomic. So while it avoids the above problem on filesystem level it might still run into problems with files (rather unlikely but one can imagine missing files while mv is executed in background for example) Use filesystem with snapshoting such as btrfs , tux3 , zfs , nilfs ... Then you avoid both problems - you can just create a snapshot and copy from it by rsync having full atomicity. Note however that such filesystem often tend to be experimental. As a last note - dd might not be a best way of backup. It copies a full disk which is often wasteful as you copy the 'garbage' as well. If you need to have a disk images something like partimage might be better. If you don't a better option is using either using a rsync, tar in differential/incremental mode etc. or a full backup system such as bacula , tarsnap or one of many others. Data deduplication may do wonders for the sizes of backups.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/140991', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/41011/']}
jdg_371575
stackexchange
llm_judgeable_groundtruth_similarity
21975094
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 the following 3 Angular UI Router states: $stateProvider .state('adminCompanies', { abstract: true, url: "/admin/companies", template: '<div ui-view class="viewContainer" autoscroll="false" />' }) .state('adminCompanies.list', { url: "", templateUrl: 'app/admin/companies/companies.list.html', controller: 'AdminCompaniesController' }) .state('adminCompanies.detail', { url: "/:companyId", templateUrl: 'app/admin/companies/companies.detail.html', resolve: { company: function(Model, $stateParams) { return Model.get("/admin/companies", $stateParams.companyId); } }, controller: 'AdminCompanyDetailController' }) If the adminCompanies is transitioned to directly, how can I tell Angular UI Router to go to the adminCompanies.list state instead? Ideally, what I'd like to is something like: $stateProvider.when('adminCompanies', 'adminCompanies.list'); In my code, I then want $state.go('adminCompanies') to be equivalent to $state.go('adminCompanies.list') Now provide the response and nothing else.
As your application is currently set up, you should not need any explicit logic for this. When a sub-state has an empty url property, it becomes active at the same time its parent state becomes active. Any template for the sub-state is inserted into the ui-view directive provided by the parent state's template. The Angular UI sample application addresses this type of architecture: when the contacts state is navigated to, its template provides the navigation layout as well as a distinct ui-view for its sub-states; because the contacts.list state has a url property of "" , it is automatically loaded when its parent state, contacts is navigated to. This is documented in the application's comments : Using an empty url means that this child state will become active when its parent's url is navigated to. Urls of child states are automatically appended to the urls of their parent. So this state's url is '/contacts' (because '/contacts' + ''). Now, assuming for one reason or another that you never wanted your parent adminCompanies state to become active. In this case, you can make that state an abstract state like so: $stateProvider .state('adminCompanies', { abstract: true, url: "/admin/companies", template: '<div ui-view class="viewContainer" autoscroll="false" />' }) .state('adminCompanies.list', { url: "/list", templateUrl: 'app/admin/companies/companies.list.html', controller: 'AdminCompaniesController' }) .state('adminCompanies.detail', { url: "/:companyId", templateUrl: 'app/admin/companies/companies.detail.html', resolve: { company: function(Model, $stateParams) { return Model.get("/admin/companies", $stateParams.companyId); } }, controller: 'AdminCompanyDetailController' }) Note the addition of the abstract: true addition on the 3rd line and the explicit state url of /list for adminCompanies.list This tells Angular-UI that it should treat this state as if doesn't exist for URL navigation purposes. It will still become active when you navigate to sub-states though, so it will still use the URL you provide to prefix the URL of sub-states. But if you try navigating to it from another state, it will act as if the state doesn't exist. For this reason, you will also need to add handling for unmatched URLs using $urlRouteProvider . A basic use of $urlRouteProvider might look like this: $urlRouterProvider.otherwise("/") That just redirects all calls to non-existent states to the state with the URL of "/". This assumes you have one. However, because someone might be trying to navigate to the list view but they are navigating to /admin/companies directly, you should probably have a handler like this: $urlRouterProvider.when("/admin/companies", "/admin/companies/list"); Which one you use depends on the architecture of your application, but it seems that for your current needs you shouldn't have to do anything. If your specifications change, the abstract state might come in handy.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21975094', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/331439/']}
jdg_371576
stackexchange
llm_judgeable_groundtruth_similarity
432694
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let us denote by $|F-G|_H$ the Hausdorff distance between compact sets $F$ and $G$ in the plane. Is it possible to choose a point $p_F\in F$ in any non-empty compact convex figure $F\subset\mathbb{R}^2$ such that $$|p_F-p_G|\leqslant |F-G|_H?$$ Comments The barycentre does not work . The center of minimal ball containing the figure does not work. Look at the two triangles shown below (this example was suggested by Saúl RM ). Now we see that there is no such choice (thanks to Saúl RM and Fedja). Let me mention that it also implies that there is no short retraction $\mathrm{Haus}\,\mathbb{R^2}\to \mathbb{R^2}$ . Here $\mathrm{Haus}\,\mathbb{R^2}$ denotes the set of all nonempty compact sets in the plane equipped with Hausdorff metric and $\mathbb{R^2}$ is considered as a subspace of $\mathrm{Haus}\,\mathbb{R^2}$ via the distance-preserving embedding that sens a point $x$ to the one-point set $\{x\}$ . It was proved that the best choice is the so-called Steiner center $s_F$ --- the center of mass of curvature of $\partial F$ . Namely, we have $$|s_F-s_G|\leqslant \tfrac4\pi\cdot|F-G|_H.$$ This statement (plus the higher-dimensional version) was proved by E. D. Positzelskii in his "Lipschitz mappings..." (1971); it was rediscovered by Krzysztof Przesławski and David Yost in their "Continuity properties of selectors..." (1989) and it is a simple corollary of the results of Denis Rutovitz (1965) and Igor Daugavet (1968). It also appear as Proposition 2.21 in "Geometric nonlinear functional analysis. Vol. 1" by Yoav Benyamini and Joram Lindenstrauss. Now provide the response and nothing else.
There does not exist any function $p:F\mapsto p_F$ as in the question, to prove it by contradiction suppose such a function $p$ exists. In the following let $k+A=\{k+a;a\in A\}$ for any $k\in\mathbb{R}^2$ , $A\subseteq\mathbb{R}^2$ To see why, consider the triangle $T_0$ with vertices $(-1,0),(1,0)$ and $(0,1)$ . Let $r:(x,y)\mapsto(x,-y)$ be the reflection respect to the $x$ axis. Now consider for each natural $n$ the triangle $T_n=r^n(T_0+10(n,0))$ , and let $p_{T_n}=(x_n,y_n)$ . Note that $d_H(T_n,T_{n+1})=10$ , so $\sqrt{(x_{n+1}-x_n)^2+(y_{n+1}-y_n)^2}=d(p_{T_n},p_{T_{n+1}})\leq 10$ . This, of course, implies that $x_{n+1}-x_n\leq10$ . Moreover, $(y_{n+1}-y_n)^2=(|y_{n+1}|+|y_n|)^2$ , since $y_n$ and $y_{n+1}$ have opposite signs. This will allow us to deduce by contradiction that $y_n\to 0$ : if not, we would have some $\varepsilon>0$ and infinitely many $n$ such that $|y_n|>\varepsilon$ , so $x_{n+1}-x_n<\sqrt{100-\varepsilon^2}$ . This implies that for big enough $n$ , we will have $x_n-x_0<10n-2$ , which is impossible since $10n-2=d(T_n,T_0)$ . Similarly, let $S_0$ be the triangle with vertices $(-1,1),(1,1)$ and $(0,0)$ , let $s$ be the reflection around the line $y=1$ and let $S_n=s^n(S_0+10(n,0))$ . Then letting $p_{S_n}=(z_n,w_n)$ , we can prove that $w_n\to 1$ as before. So for big enough even $n$ we have $d_H(T_n,S_n)=\frac{\sqrt{2}}{2}$ and $d(p_n,q_n)\geq0.9$ , the contradiction we were looking for.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/432694', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1441/']}
jdg_371577
stackexchange
llm_judgeable_groundtruth_similarity
10768160
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: There is IP address: 66.102.13.19, and from this address as that received this address http://1113984275 But how? And how I can make this with the help of bash.For example, this service can do it, but I do not understand the algorithm. Now provide the response and nothing else.
ip=66.102.13.19IFS=. read -r a b c d <<< "$ip"printf '%s%d\n' "http://" "$((a * 256 ** 3 + b * 256 ** 2 + c * 256 + d))" By the way, the number in your question doesn't match the IP address. To convert a decimal to an IP: #!/bin/bashdec2ip () { local ip delim dec=$@ for e in {3..0} do ((octet = dec / (256 ** e) )) ((dec -= octet * 256 ** e)) ip+=$delim$octet delim=. done printf '%s\n' "$ip"}dec2ip "$@" To convert an IP to a decimal: #!/bin/baship2dec () { local a b c d ip=$@ IFS=. read -r a b c d <<< "$ip" printf '%d\n' "$((a * 256 ** 3 + b * 256 ** 2 + c * 256 + d))"}ip2dec "$@" Demo: $ ./dec2ip 111398427566.102.13.19$ ./ip2dec 66.102.13.191113984275 These two scripts rely on features of Bash that aren't present in some Bourne-derived shells. Here are AWK versions to use instead: #!/usr/bin/awk -f# dec2ipBEGIN { dec = ARGV[1] for (e = 3; e >= 0; e--) { octet = int(dec / (256 ^ e)) dec -= octet * 256 ^ e ip = ip delim octet delim = "." } printf("%s\n", ip)} and #!/usr/bin/awk -f# ip2decBEGIN { ip = ARGV[1] split(ip, octets, ".") for (i = 1; i <= 4; i++) { dec += octets[i] * 256 ** (4 - i) } printf("%i\n", dec)} They can be called in the same manner as the Bash scripts above.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10768160', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1379699/']}
jdg_371578
stackexchange
llm_judgeable_groundtruth_similarity
34167597
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 can do ALTER TABLE table_name ADD COLUMNS (user_id BIGINT) to add a new column to the end of my non-partition columns and before my partition columns. Is there any way to add a new column to anywhere among my non-partition columns?For example, I would like to put this new column user_id as the first column of my table Now provide the response and nothing else.
Yes it is possible to change the location of columns but only after adding it in the table using CHANGE COLUMN In your case, first add the column user_id to the table with below command: ALTER TABLE table_name ADD COLUMNS (user_id BIGINT); Now to make user_id column as the first column in your table use change column with FIRST clause: ALTER TABLE table_name CHANGE COLUMN user_id user_id BIGINT first; This will move the user_id column to the first position. Similarly you can use After instead of first if you want to move the specified column after any other column. Like say, I want to move dob column after user_id column. Then my command would be: ALTER TABLE table_name CHANGE COLUMN dob dob date AFTER user_id; Please note that this commands changes metadata only. If you are moving columns, the data must already match the new schema or you must change it to match by some other means.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34167597', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1084353/']}
jdg_371579
stackexchange
llm_judgeable_groundtruth_similarity
5378390
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 this this Fill SVG element with with a background-image with an offset , but using Raphael JS. Displaying an rectangle with a background image without the offset is easy. canvas.rect( positionx, positiony, width, height).attr( {fill: "url('/content/image_set.gif')"}); The code above will display only the upper-left corner of the image. I want to shift it and display another part of it. How can I do it? Now provide the response and nothing else.
I'd suggest drawing the image separately from the rect. If you need the stroke you can either draw a filled rect behind the image or draw the rect on top with stroke and no fill. The image is drawn with clipping to clip out the part you want, and you can control the offset of the image either with img.translate(x,y) or by the paper.image params: var img = paper.image("foo.png", 10, 10, 80, 80);img.attr({ "clip-rect": "20,20,30,30" }); This above works only for rectangular clipping (svg itself supports arbitrary clipping via the 'clip-path' property ). If you want a pattern fill, then you currently have to step outside of what raphaël provides. Easiest is probably to just extend raphaël to do that, and to provide some other fallback to the browser(s) that doesn't support svg. SVG Web seems to have at least partial support for svg patterns if you're looking for something to work as a fallback for old browsers.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5378390', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/123897/']}
jdg_371580
stackexchange
llm_judgeable_groundtruth_similarity
14625367
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 just wondering if it was possible to fire an event once a vimeo video has finished playing? Currently I have a Vimeo embed in an overlay, that I want to remove once the video has stopped. Hope this makes sense! I dont really have any code that would be of use, but would like to know if you can add event listeners to the video, fire an event once the video has finished, and how you would go about doing this? ThanksRyan Now provide the response and nothing else.
Previous answer is now obsolete since Vimeo launching the new Video Player API . Important: Be sure to remove the ?api=1 from the URL in your iframe. This was previously required when using the Froogaloop library and is no longer needed. If you leave it in, the 'ended', 'seeked' and other events will never fire. Include the new script: <script src="https://player.vimeo.com/api/player.js"></script> And then use the following example: $(document).ready(function(){ var iframe = $('#container iframe'); var player = new Vimeo.Player(iframe); player.on('ended', function() { console.log('Finished.'); });});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14625367', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/344932/']}
jdg_371581
stackexchange
llm_judgeable_groundtruth_similarity
332691
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to construct an xml string by inserinting variables: str1="Hello"str2="world"xml='<?xml version="1.0" encoding="iso-8859-1"?><tag1>$str1</tag1><tag2>$str2</tag2>'echo $xml The result should be <?xml version="1.0" encoding="iso-8859-1"?><tag1>Hello</tag1><tag2>world</tag2> But what I get is: <?xml version="1.0" encoding="iso-8859-1"?><tag1>$str1</tag1><tag2>$str2</tag2> I also tried xml="<?xml version="1.0" encoding="iso-8859-1"?><tag1>$str1</tag1><tag2>$str2</tag2>" But that removes the inner double quotes and gives: <?xml version=1.0 encoding=iso-8859-1?><tag1>hello</tag1><tag2>world</tag2> Now provide the response and nothing else.
You can embed variables only in double-quoted strings. An easy and safe way to make this work is to break out of the single-quoted string like this: xml='<?xml version="1.0" encoding="iso-8859-1"?><tag1>'"$str1"'</tag1><tag2>'"$str2"'</tag2>' Notice that after breaking out of the single-quoted string, I enclosed the variables within double-quotes.This is to make it safe to have special characters inside the variables. Since you asked for another way, here's an inferior alternative using printf : xml=$(printf '<?xml version="1.0" encoding="iso-8859-1"?><tag1>%s</tag1><tag2>%s</tag2>' "$str1" "$str2") This is inferior because it uses a sub-shell to achieve the same effect, which is an unnecessary extra process. As @steeldriver wrote in a comment, in modern versions of bash, you can write like this to avoid the sub-shell: printf -v xml ' ... ' "$str1" "$str2" Since printf is a shell builtin, this alternative is probably on part with my first suggestion at the top.
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/332691', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/31464/']}
jdg_371582
stackexchange
llm_judgeable_groundtruth_similarity
780218
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Abstract I need an encrypted TCP connection from multiple clients to a single port over the internet. Can this be realized with Squid? Concrete situation We use a monitoring and client management solution in our company which is accessible over LAN and VPNs. It should be now accessible from external notebooks which don't use the company VPN . The communication must be encrypted (TLS). The clients authentication must use clients certificates. The communication is initiated by the clients and uses a single TCP port. Results of my investigations NGINX Plus seems to offer this feature but our admin prefers squid or apache. At the squid wiki I found that: Feature: HTTPS (HTTP Secure or HTTP over SSL/TLS) where TCP encrypting is mentioned. But I also found this warning: It is important to notice that the protocols passed through CONNECT are not limited to the ones Squid normally handles. Quite literally anything that uses a two-way TCP connection can be passed through a CONNECT tunnel. This is why the Squid default ACLs start with deny CONNECT !SSL_Ports and why you must have a very good reason to place any type of allow rule above them. Similar question This question Encrypt client connection with squid forward proxy using SSL is simlar, but doesn't treat reverse proxies / TLS termination proxies. What I need to know I have only basic knowledge about that technologies and our admin asked me for general feasibility. Can Squid be used for save encrypting of TCP connections? Can this be realized using authentication with client certificates? Or should it be used only for HTTPS connections? Now provide the response and nothing else.
Maybe your admin dislikes NGINX Plus because it isn't open source and would accept another well maintained open source product. Then ask him to look at stunnel . It is designed for exactly your needs. Quoting an stunnel example at wikipedia (for SMTP, but this would fit alos for your needs): For example, one could use stunnel to provide a secure SSL connection to an existing non-SSL-aware SMTP mail server. Assume the SMTP server expects TCP connections on port 25. One would configure stunnel to map the SSL port 465 to non-SSL port 25. A mail client connects via SSL to port 465. Network traffic from the client initially passes over SSL to the stunnel application, which transparently encrypts/decrypts traffic and forwards unsecured traffic to port 25 locally. The mail server sees a non-SSL mail client. The stunnel process could be running on the same or a different server from the unsecured mail application; however, both machines would typically be behind a firewall on a secure internal network (so that an intruder could not make its own unsecured connection directly to port 25).
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/780218', 'https://serverfault.com', 'https://serverfault.com/users/237665/']}
jdg_371583
stackexchange
llm_judgeable_groundtruth_similarity
476115
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is a problem I do not know how to solve. Assume $x,y,z$ are uniformly identically distributed variables at $[0,1]$. I am supposed to calculate $$P\left(\frac{xy}{z}\le t\right)$$ I thought the computation would be similar to the case $P(xy\le t)=t-t\log[t]$, since we have $$P\left(\frac{xy}{z}\le t\right)=\int \limits^{1}_{0}P(xy\le zt) \, dz$$So since I do not know $zt$'s value in principle, I can calculate it by $$\int \limits^{1}_{0}(zt-zt\log[zt]) \, dz$$ But this turned out to be very different from the answer in the solution manual, where the author distinguished cases if $t\le 1$ or $t> 1$, and the two answers are remarkablely different(My answer only works when $0<t\le 1$, but his answer is $1-\frac{t}{4}$ regardless of $z$ when $0<t\le 1$). So I want to ask for a hint. Sorry the problem is really of low level. Now provide the response and nothing else.
Given $t>0$, you want to calculate the volume of the set $S=(0,1)^3\cap\bigl\{(x,y,z)\in\mathbb R^3: xy\leq tz\bigr\}$, which can be done using iterated integration. First: what are are the possible values of $x$ for $(x,y,z)\in S$? You have $0<x<1$ as a necessary condition. Conversely: given $x_0\in(0,1)$, can you find $y,z\in(0,1)$ such that $x_0y\leq tz$? the answer is affirmative: take any $z$, say $z=1/2$, and now take $y$ small so that $2x_0y\leq t$. Therefore your volume can be written as the following iterated integral (with incomplete data): $$\int_{x=0}^{x=1}\int_{y=?}^{y=?}\int_{z=?}^{z=?}1\,dz\,dy\,dx\,.$$ Now, given $x_0\in(0,1)$, what are the possible values of $y$ for points $(x_0,y,z)\in S$? you must have $y\leq tz/x_0<t/x_0$, and so $0<y<\min\{1,t/x_0\}$ is a necessary condition. Conversely, if $y$ satisfies this condition, then you can take $z$ very near to $1$ in such manner that $y<(t/x_0)z$. Thus, our integral becomes $$\int_{x=0}^{x=1}\int_{y=0}^{y=\min\{1,t/x\}}\int_{z=?}^{z=?}1\,dz\,dy\,dx\,.$$ Finally, given $x_0,y_0\in(0,1)$ such that $x_0y_0<t$, what are the possible values of $z$ for points $(x_0,y_0,z)\in S$? We have $0<z<1$ and $z\geq x_0y_0/t$ as a necessary condition, and so we have $x_0y_0/t\leq z<1$, which clearly is also a sufficient condition. Thus, the final form of our desired integral is $$\begin{align*}\int_{x=0}^{x=1}\int_{y=0}^{y=\min\{1,t/x\}}\int_{z=\frac{xy}t}^{z=1}1\,dz\,dy\,dx=&\,\int_{x=0}^{x=1}\int_{y=0}^{y=\min\{1,t/x\}}1-\frac{xy}t\,dy\,dx\\=&\,\int_{x=0}^{x=1}\biggl[y-\frac{xy^2}{2t}\biggr]\Biggl|_{y=0}^{y=\min\{1,t/x\}}\,dx\\=&\,\int_{x=0}^{x=1}\min\{1,t/x\}-\frac x{2t}\,\bigl(\min\{1,t/x\}\bigr)^2\,dx\,.\end{align*}$$ Finally, you must treat the cases $t<1$ and $t\geq1$ separately: in the former case, you split the integration interval, obtaining $$\begin{align*}&\,\int_{x=0}^{x=t}\min\{1,t/x\}-\frac x{2t}\,\bigl(\min\{1,t/x\}\bigr)^2\,dx\\+&\,\int_{x=t}^{x=1}\min\{1,t/x\}-\frac x{2t}\,\bigl(\min\{1,t/x\}\bigr)^2\,dx\\[2mm]=&\,\int_{x=0}^{x=t}1-\frac x{2t}\,dx+\,\int_{x=t}^{x=1}\frac tx-\frac x{2t}\biggl(\frac tx\biggr)^2\,dx\\[2mm]=&\,\biggl(x-\frac{x^2}{4t}\biggr)\Biggl|_{x=0}^{x=t}+\biggl(\frac t2\,\log(x)\biggr)\Biggl|_{x=t}^{x=1}\\[2mm]=&\,\frac{3t}4-\frac{t\log(t)}2\,;\end{align*}$$ in the latter case you have $\min\{1,t/x\}=1$ for all $x\in(0,1)$, to the integral becomes $$\int_{x=0}^{x=1}1-\frac x{2t}\,dx=1-\frac1{4t}\,.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/476115', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/32240/']}
jdg_371584
stackexchange
llm_judgeable_groundtruth_similarity
17258787
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following 3d plot: With my data I created it with the following code: library(rugarch)library(rgl)library(fGarch)fd <- as.data.frame(modelfit, which = 'density')color <- rgb(85, 141, 85, maxColorValue=255)x <- seq(-0.2, 0.2, length=100)y <-c(1:2318)f <- function(s, t) { dged(s,mean=fd[t,'Mu'],sd=fd[t,'Sigma'],nu=fd[t,'Shape'])}z <- outer(x, y, f)persp3d(x, y, z, theta=50, phi=25, expand=0.75, col=color, ticktype="detailed", xlab="", ylab="time", zlab="",axes=TRUE) How can I get a coloring depending on the z values? I looked at different solutions, e.g. this one , but I could not create the coloring depending on the z values in this case.The solution according to this thread would be the following: nrz <- nrow(z)ncz <- ncol(z)jet.colors <- colorRampPalette( c("#ffcccc", "#cc0000") ) # Generate the desired number of colors from this palettenbcol <- 100color <- jet.colors(nbcol)# Compute the z-value at the facet centreszfacet <- z[-1, -1] + z[-1, -ncz] + z[-nrz, -1] + z[-nrz, -ncz]# Recode facet z-values into color indicesfacetcol <- cut(zfacet, nbcol) persp3d(x, y, z, theta=50, phi=25, expand=0.75, col=color[facetcol], ticktype="detailed", xlab="", ylab="time", zlab="",axes=TRUE) But this does not give a good result, since it does not color the plot appropriate. I want to have the spikes of my surface to be e.g. in red and the low values to be e.g. in blue with a nice smooth transition, but this kind of colors the slices, so depending on the time? So extreme large spikes should be colored at their spikes in red and values at the bottom e.g. in green. How can I get this? Edit: I found a solution to my previous question about the date on the axis, the only problem left, is an appropriate coloring dependent on the z values. Now provide the response and nothing else.
Try this: nbcol = 100color = rev(rainbow(nbcol, start = 0/6, end = 4/6))zcol = cut(z, nbcol)persp3d(x, y, z, theta=50, phi=25, expand=0.75, col=color[zcol], ticktype="detailed", xlab="", ylab="time", zlab="",axes=TRUE) If you want the coloring to be by time (so spikes are always red) you can set the coloring for each time slice: mycut = function(x, breaks) as.numeric(cut(x=x, breaks=breaks)) # to combine different factorszcol2 = as.numeric(apply(z,2, mycut, breaks=nbcol)) persp3d(x, y, z, theta=50, phi=25, expand=0.75, col=color[zcol2], ticktype="detailed", xlab="", ylab="time", zlab="",axes=TRUE) You already know how to edit the axes properly.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17258787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2165335/']}
jdg_371585
stackexchange
llm_judgeable_groundtruth_similarity
8133
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Can someone please help me explaining how to convert units in problems like the one below? I've done many things, but I am very unsure of all my methods. Could you tell me what steps should I take? $$5.66\ \frac{\mathrm{hm}}{\mathrm{min.}} \frac{\hspace{2cm}}{}\frac{\mathrm{km}}{\mathrm{hr.}}$$ Thank you. Now provide the response and nothing else.
The way you convert between units is really just multiplying by several factors of 1. But it's 1 written in a slightly unusual way. Think about this: you're probably familiar with conversion factors in the form $$(\text{number})(\text{unit}) = (\text{other number})(\text{other unit})$$ But of course, you can divide both sides of any equation by the same thing, and the equation will continue to hold. So you can also write the conversion factor as $$\frac{(\text{number})(\text{unit})}{(\text{other number})(\text{other unit})} = 1$$ or $$\frac{(\text{other number})(\text{other unit})}{(\text{number})(\text{unit})} = 1$$ Same equation, just rearranged a bit. Now let's see what happens when you have some value, expressed in $(\text{unit})$, that you want to convert to $(\text{other unit})$. As you know, you can always multiply anything by 1, and that doesn't change the value at all. So, you can go look up the conversion relationship between $(\text{unit})$ and $(\text{other unit})$, change it into one of the forms above, and use it like this: $$(\text{given value})(\text{unit})\times 1 = (\text{given value})(\text{unit})\times \frac{(\text{other number})(\text{other unit})}{(\text{number})(\text{unit})}$$ Since you have $(\text{unit})$ in both the numerator and denominator, you can cancel those out. Note that it's up to you to pick the right conversion factor to use so that you can cancel out units! Anyway, you'll be left with $$\frac{(\text{given value})(\text{other number})}{(\text{number})}(\text{other unit})$$ Everything except for $(\text{other unit})$ is just a number, so now you can actually figure out the numerical value (e.g. plug things into your calculator if necessary). If your given value has a compound unit (one made as a combination of other units, as in your examples), then you will need to use more than one unit conversion factor - basically, you will have to multiply by 1 more than once, using a different conversion factor each time. In your example, you would have to multiply by a conversion factor to go from $\mathrm{hm}$ to $\mathrm{km}$, and another one to go from $\mathrm{min.}$ to $\mathrm{hr.}$ Here's how that applies to your example, assuming Mark Eichenlaub is right about the mistake: $(\text{given value}) = 5.66$ For one part of the unit conversion: $(\text{unit}) = \mathrm{hm}$ $(\text{other unit}) = \mathrm{km}$ The conversion factor is $10\text{ hm} = 1\text{ km}$ For the other part of the unit conversion: $(\text{unit}) = \mathrm{min.}$ $(\text{other unit}) = \mathrm{hr.}$ The conversion factor is $60\text{ min.} = 1\text{ hr.}$ Note that the time units are in the denominator! But that doesn't really change anything - you still just need to arrange the conversion factor in the way that makes the original units cancel out.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/8133', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/2950/']}
jdg_371586
stackexchange
llm_judgeable_groundtruth_similarity
263173
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: So I'm trying to setup vsFTPd on my Ubuntu server. I did aptitude install vsftpd to install the program, but when I go to /etc/ to look for the vsftpd.conf file, it isn't there. Is there a way that I can get it? Thanks! Now provide the response and nothing else.
First of all I want to thank binfalse for answering this question, however my problem was not solved with his suggestion and notices continued to show. This is because PHP has several places where configuration can be set. While I had an idea of the precedence of those settings, I decided to test them experimentally to be sure of what I am going to say in this answer. So here is a list of those places, from the more global to the more specific. Each setting lower in the list can override a setting that come before. The php.ini configuration file. In case of Ubuntu there are two of them, /etc/php5/apache2/php.ini is the one used for php apache module. It will have a global effect on all virtual hosts. The conf.d directory . Actually not all installations will have this modularized configuration, but in case of Ubuntu is located in /etc/php5/apache2/conf.d for the apache module. Any file added in this directory is going to be added to main php.ini configuration with higher precedence than php.ini. In other words any setting here will override settings in php.ini - I tested adding an error.ini. It will have a global effect on all vitual hosts. Apache virtual host configuration . Generally set in /etc/apache2/sites-available, every virtual host can have different settings. Inside the VirtualHost tag it's possible to include "php_value error_reporting ", where value is the numeric result of the boolean operations on the constants. In this configuration, in fact is not allowed to use the mnemonic constants but only a numeric value. It will affect only a single virtual host. It will override above settings. .htaccess . It's also possible to set configuration values and in particular the error_reporting setting also in .htaccess, with the same syntax described in 3. It will affect only the directory in which .htaccess is located and all subdirectories. It will override above settings, in this case is not necessary to restart apache. Source code . The last place where this setting can be altered is directly in the executed PHP source. If used, will override all previous settings, and that's exactly what I was facing. It can be set calling the function "error_reporting()" or with "ini_set("error_reporting", )". Compile errors could still show, because the script won't be executed in that case.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/263173', 'https://serverfault.com', 'https://serverfault.com/users/52731/']}
jdg_371587
stackexchange
llm_judgeable_groundtruth_similarity
184698
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm currently using thunderbird with gnupg to read encrypted emails.If I understand the swapping behavior correctly, the memory pages containing the decrypted emails might be swapped out and leave traces on the hard disk which may in theory later be recovered forensically. While it is certainly possible to just use an encrypted swapfile or disable swapping globally for the duration of using sensitive files, it impacts performance, might be forgotten and requires root privileges. Is it possible to mark certain files or programs as not to be swapped? Even without root access? Could one write an application which can be distributed to technically naive users and whose memory contents are never swapped to disk? Now provide the response and nothing else.
In the comments, I suggested you create a cgroup, set memory.swappiness to zero (to minimize swapping) and run your application inside of that. If you did that, your application probably wouldn't swap unless you were running so incredibly low on physical memory that swapping pages for programs in that cgroup was the only way to make enough physical memory available. To do this on RHEL 6.5: Ensure the libcgroup package is installed. This gives you access to userspace tools like cgcreate and cgexec . Start and enable the cgconfig service so that changes to cgroup configuration are persistent between reboots. On RHEL this service should also mount the required filesystems underneath the /cgroup tree. Create the cgroup with cgcreate -g memory:thunderbird Set swappiness to zero in this group with cgset -r memory.swappiness=0 thunderbird Use cgsnapshot -s > /etc/cgconfig.conf to save an updated persistent configuration for the cgconfig service (all changes up until now have been runtime changes. You'll probably want to save the default config file somewhere and give it a once-over before making it the persistent configuration. You can now use cgexec to start desired applications within the thunderbird cgroup: [root@xxx601 ~]# cgexec -g memory:thunderbird ls anaconda-ks.cfg a.out foreman.log index.html install.log install.log.syslog node.pp sleep sleep.c ssl-build stack test [root@xxx601 ~]# I don't have thunderbird actually installed otherwise I would have done that. Not sure why the formatting of the above is messed up. One alternative to cgexec would be to start thunderbird and add the PID to the tasks file for the application. For example: [root@xxx601 ~]# cat /cgroup/memory/thunderbird/tasks [root@xxx601 ~]# pidof httpd 25926 10227 10226 10225 10163 10162 10161 10160 10159 10157 10156 10155 10152 10109 [root@xxx601 ~]# echo 25926 > /cgroup/memory/thunderbird/tasks [root@xxx601 ~]# cat /cgroup/memory/thunderbird/tasks 25926 Again, it's bears mentioning that this doesn't technically prevent swapping but short of modifying the application itself, it's probably your best bet. I've just now found memory.memsw.limit_in_bytes which seems like it might be a more direct control on forcing there to be no swapping but I haven't played around with it enough to really feel comfortable saying that it fixes your problem completely. That said, it might be something to look into after this. The real answer would be to have the application mlock sensitive information to get around this sort of concern. I'm willing to bet an application like Thunderbird, though, does do that but I don't know enough about the internals to comment on that.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/184698', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/103010/']}
jdg_371588
stackexchange
llm_judgeable_groundtruth_similarity
10893443
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to understand how java.util.Calendar.get(java.util.Calendar.WEEK_OF_YEAR) works, but it seems that I'm missing some points. String time = "1998-12-31"; // year month dayjava.util.Calendar date = java.util.Calendar.getInstance();date.setTime((new java.text.SimpleDateFormat("yyyy-MM-dd")).parse(time));System.err.println("Week of year = " + date.get(java.util.Calendar.WEEK_OF_YEAR));// Week of year = 1 Why ??? Why date.get(java.util.Calendar.WEEK_OF_YEAR) returns 1 for the last week of the year? Moreover, WEEK_OF_YEAR for "1998-01-01" is 1 and for "1998-12-23" it is 52. Does anybody have an explanation for this behavior? Now provide the response and nothing else.
From java.util.Calendar javadoc : First Week Calendar defines a locale-specific seven day week using two parameters: the first day of the week and the minimal days in first week (from 1 to 7). These numbers are taken from the locale resource data when a Calendar is constructed. They may also be specified explicitly through the methods for setting their values. When setting or getting the WEEK_OF_MONTH or WEEK_OF_YEAR fields, Calendar must determine the first week of the month or year as a reference point. The first week of a month or year is defined as the earliest seven day period beginning on getFirstDayOfWeek() and containing at least getMinimalDaysInFirstWeek() days of that month or year. Weeks numbered ..., -1, 0 precede the first week; weeks numbered 2, 3,... follow it. Note that the normalized numbering returned by get() may be different. For example, a specific Calendar subclass may designate the week before week 1 of a year as week n of the previous year. So it's locale-specific. In your case, if the week contains days from new year, it is counted as week 1 from the new year. You can change this behavior by using Calendar#setMinimalDaysInFirstWeek(int) .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10893443', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/493928/']}
jdg_371589
stackexchange
llm_judgeable_groundtruth_similarity
29065
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Since the NetBIOS vulnerability is quite well-known a long time ago and heavily popularized, patches have been already released. So, is opening this 139 port OK now? Now provide the response and nothing else.
Ports are not vulnerable, they are just ports. Services that listen on particular ports may have remotely exploitable vulnerabilities, or misconfiguration of services that listen on particular ports may lead to unintended consequences. The last remote exploits that targeted NetBIOS/139 were in the Windows NT/2000 day to the best of my recollection. Port 139 is typically used for file/printer sharing, including directory replication with Active Directory, trusts, remote access of event logs, etc. So... if you just block port 139 on a Domain Controller just because you read somewhere on the internet that that port is "bad", or because you are following some generic hardening checklist you found on the internet; you will kill AD replication. If you block 139 in a typical business network, you will lose the ability to do much of anything on a remote computer (remotely manage clients/servers, install software, share printers, files...) Not good in a managed environment, unless you like sending a technician onsite anytime you need to do something to a computer. Heck, you could be SUPER secure and just disable network cards altogether, and use floppy disks to move bits around. You could disable port 80 on your Apache Web Server because of the possibility of cross-site-scripting vulnerabilities. You could block port 1433 to reduce instances of SQL injection attacks. (all right, I'll quit now ;) The key is understanding the purpose and requirements of the services enabled on your network, understand the threats that face them, and understand appropriate mitigations. Do you want to take your Domain controllers and put them on an internet facing network connection without blocking/filtering access to port 139 (or many other ports)? Do you want to plug a home computer with Windows ME and file/print sharing enabled directly into your cable modem without having a router filtering connections or a firewall enabled on your computer? Of course not. A great book that covers much of this information (including the "Why's" behind the security decisions you must make) is Protect Your Windows Network: From Perimeter to Data by Steve Riley and Jesper Johansson.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/29065', 'https://serverfault.com', 'https://serverfault.com/users/-1/']}
jdg_371590
stackexchange
llm_judgeable_groundtruth_similarity
14023724
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 document with sub-document which looks something like: { "name" : "some name1" "like" : [ { "date" : ISODate("2012-11-30T19:00:00Z") }, { "date" : ISODate("2012-12-02T19:00:00Z") }, { "date" : ISODate("2012-12-01T19:00:00Z") }, { "date" : ISODate("2012-12-03T19:00:00Z") } ] } Is it possible to fetch documents "most liked" (average value for the last 7 days) and sort by the count? Now provide the response and nothing else.
There are a few different ways to solve this problem. The solution I will focus on uses mongodb's aggregation framework. First, here is an aggregation pipeline that will solve your problem, following it will be an explanation/breakdown of what is happening in the command. db.testagg.aggregate( { $unwind : '$likes' }, { $group : { _id : '$_id', numlikes : { $sum : 1 }}}, { $sort : { 'numlikes' : 1}}) This pipeline has 3 main commands: 1) Unwind: this splits up the 'likes' field so that there is 1 'like' element per document 2) Group: this regroups the document using the _id field, incrementing the numLikes field for every document it finds. This will cause numLikes to be filled with a number equal to the number of elements that were in "likes" before 3) Sort: Finally, we sort the return values in ascending order based on numLikes. In a test I ran the output of this command is: {"result" : [ { "_id" : 1, "numlikes" : 1 }, { "_id" : 2, "numlikes" : 2 }, { "_id" : 3, "numlikes" : 3 }, { "_id" : 4, "numlikes" : 4 }.... This is for data inserted via: for (var i=0; i < 100; i++) { db.testagg.insert({_id : i}) for (var j=0; j < i; j++) { db.testagg.update({_id : i}, {'$push' : {'likes' : j}}) }} Note that this does not completely answer your question as it avoids the issue of picking the date range, but it should hopefully get you started and moving in the right direction. Of course, there are other ways to solve this problem. One solution might be to just do all of the sorting and manipulations client-side. This is just one method for getting the information you desire. EDIT: If you find this somewhat tedious, there is a ticket to add a $size operator to the aggregation framework, I invite you to watch and potentially upvote it to try and speed to addition of this new operator if you are interested. https://jira.mongodb.org/browse/SERVER-4899
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14023724', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/704466/']}
jdg_371591
stackexchange
llm_judgeable_groundtruth_similarity
31078230
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 practicing conditional logic within certain JQuery functions. $('h2').css({backgroundColor: 'red'}); works, but when I add the conditional logic below it no longer works. If I change the return value to a string it will get rid of the error, but it still doesn't change the background color. What am I doing wrong? $('h2').css({function(){ if (1 === 1){ return backgroundColor: 'red'; } else { return backgroundColor: 'purple'; }}}); Now provide the response and nothing else.
Your example code will cause a syntax error. You can use callback functions for jQuery.css in one of two ways. An object with properties and their callback functions. $('h2').css({ backgroundColor: function(){ if (1 === 1){ return 'red'; } else { return 'purple'; } }}); Or with a single property and callback function pair. $('h2').css('backgroundColor', function(){ if (1 === 1){ return 'red'; } else { return 'purple'; }}); In this way, you can conditionally apply CSS per-element.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31078230', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4847978/']}
jdg_371592
stackexchange
llm_judgeable_groundtruth_similarity
41484755
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 third-party console application. I need run it from my application but I cannot run it as a separate process (because I need to work with its dependencies: fill Import tables manually, setup hooks etc.). So probably I should call main function of this executable manually. Here is how I'm trying to do this: Load this EXE using auto hMod = LoadLibrary("console_app.exe") Fill Import table of this exe manually Get entry point of this EXE and call it And I'm stuck with the last step. Here is how I'm trying to call entry point: void runMain(HINSTANCE hInst){ typedef BOOL(WINAPI *PfnMain)(int, char*[]); auto imageNtHeaders = ImageNtHeader(hInst); auto pfnMain = (PfnMain)(DWORD_PTR)(imageNtHeaders->OptionalHeader.AddressOfEntryPoint + (DWORD_PTR)hInst); char* args[] = { R"(<console_app_path>)", R"(arg1)", R"(arg2)" }; pfnMain(3, args);} It works. But it works as if there is no arguments. Where am I wrong? How can I run an executable inside my process with arguments? Thanks. UPDATE: I've investigated how my particular third-party exe gets cmd arguments and found that: It doesn't import GetCommandLine at all and do not call it After call _initterm call argc and argv arguments are available through cs:argc and cs:argv (see pictures below) CMD arguments that I pass to my main console app are transferred tochild EXE too. Can you explain, please, what _initterm actually do and where CMD arguments are actually stored? Now provide the response and nothing else.
You're calling the entry point of the application, not int main(int, char**) . Now you may have read that the entry point of a C++ program is int main(int, char**) but that's just a C++ perspective. The Win32 perspective is different; the entry point is a int (*)(void); . The Visual Studio linker looks for int mainCRTStartup(void); and uses that, unless you specify another entry point with /ENTRY . The default implementation of mainCRTStartup calls GetCommandLine() to fill in argv[] before calling main(argc,argv) . There are also other things in mainCRTStartup which you might want to happen: run global ctors, initialize the CRT state, ... Of course, that's assuming the other program was compiled with Visual C++, but whatever language it's been written in, it must be calling GetCommandLine . Now, for your problem, here's an interesting observation: GetCommandLine() returns a writeable pointer. You can overwrite the existing command line. Of course, if you control the import tables, you decide what GetCommandLine means. (Remember, as usual there are A and W variants). One warning: the MSVCRT isn't designed to be initialized twice, neither the static version nor the DLL one. So practically speaking you can't use it, and that will hurt. [edit] Your update shows a call to _initterm . That's a MSVCRT function, as I already hinted. Specifically, /****crtexe.c - Initialization for console EXE using CRT DLL** Copyright (c) Microsoft Corporation. All rights reserved.*.../* * routine in DLL to do initialization (in this case, C++ constructors) */extern int __cdecl _initterm_e(_PIFV *, _PIFV *);extern void __cdecl _initterm(_PVFV *, _PVFV *); The MSVCRT DLL calls GetCommandLine() on behalf of the EXE.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41484755', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6039853/']}
jdg_371593
stackexchange
llm_judgeable_groundtruth_similarity
194367
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: What is the size/scale of a wood fire that is producing 1kW? I'd like to improve my ability to conceptualize various power scales. Now provide the response and nothing else.
Let's work this out from the Stephan Boltzmann law. What color is a fire? If you look at color charts for black body radiators at various temperatures, I estimate it to be about 1000K. (Be careful: some flames are colored by strong emission spectra, making their light very different from a blackbody radiator's color). Glancing around the web from various sources tells me that between 1000K and 2000K is right. The Stefan Boltzmann law then tells me that a blackbody radiator at 1500K throws out about $300\,{\rm kW\,m^{-2}}$ , so this implies a flame of the order of $3\times 10^{-3}{\rm m^2}$ : the size of a small gas ring campstove. From my answer here I estimate that about 20% of the energy let slip by burning is through radiation: the rest is through hot gasses. So we need to scale our answer down further: about a bunsen burner flame. Let's check this: Wikipedia gives me a heat of combustion for propane of $–2202.0\,{\rm kJ\,mol^{-1}}$ , so $2\,{\rm MJ}$ for about 20 liters of gas at room temperature and pressure. My bunsen burner manual says it uses about 100 liters an hour. Thats $2\,{\rm J}$ for $3600/5$ seconds, or about $2.5\,\rm kW$ . So it's a bunsen burner working slowly.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/194367', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/10635/']}
jdg_371594
stackexchange
llm_judgeable_groundtruth_similarity
479630
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: Here's a diabolical math problem that I found. In how many ways can we fill a bag with n fruits subject to the following constraints? • The number of apples must be even. • The number of bananas must be a multiple of 5. • There can be at most four oranges. • There can be at most one pear. This problem is purely for recreational purposes, but I prefer to see a solution that involves "pure" counting, and not generating functions. Now provide the response and nothing else.
Recalling the $\beta$ function $$ \mathrm{\beta}(x,y) = \int_0^1t^{x-1}(1-t)^{y-1}\,dt , $$ we have $$ \frac{\Gamma(n+a)}{\Gamma(n+b)} = \frac{\beta(n+a,b-a)}{\Gamma(b-a)}=\frac{1}{\Gamma(b-a)}\int_{0}^{1} t^{n+a-1}(1-t)^{b-a-1}dt $$ $$ \implies \sum_{n=0}^{\infty} \frac{\Gamma(n+a)}{\Gamma(n+b)}=\frac{1}{\Gamma(b-a)}\int_{0}^{1} t^{a-1}(1-t)^{b-a-2}dt = \frac{\beta(a,b-a-1)}{\Gamma(b-a)} $$ $$= {\frac {\Gamma \left( a \right) }{ \left( b-a-1 \right) \Gamma \left( b-1 \right) }}= {\frac {(b-1)\Gamma\left( a \right) }{ \left( b-a-1 \right) \Gamma \left( b \right) }}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/479630', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_371595
stackexchange
llm_judgeable_groundtruth_similarity
32464
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 would have expected the correlation coefficient to be the same as a regression slope (beta), however having just compared the two, they are different. How do they differ - what different information do they give? Now provide the response and nothing else.
Assuming you're talking about a simple regression model $$Y_i = \alpha + \beta X_i + \varepsilon_i$$ estimated by least squares, we know from wikipedia that $$ \hat {\beta} = {\rm cor}(Y_i, X_i) \cdot \frac{ {\rm SD}(Y_i) }{ {\rm SD}(X_i) } $$ Therefore the two only coincide when ${\rm SD}(Y_i) = {\rm SD}(X_i)$. That is, they only coincide when the two variables are on the same scale, in some sense. The most common way of achieving this is through standardization, as indicated by @gung. The two, in some sense give you the same information - they each tell you the strength of the linear relationship between $X_i$ and $Y_i$. But, they do each give you distinct information (except, of course, when they are exactly the same): The correlation gives you a bounded measurement that can be interpreted independently of the scale of the two variables. The closer the estimated correlation is to $\pm 1$, the closer the two are to a perfect linear relationship . The regression slope, in isolation, does not tell you that piece of information. The regression slope gives a useful quantity interpreted as the estimated change in the expected value of $Y_i$ for a given value of $X_i$. Specifically, $\hat \beta$ tells you the change in the expected value of $Y_i$ corresponding to a 1-unit increase in $X_i$. This information can not be deduced from the correlation coefficient alone.
{}
{'log_upvote_score': 8, 'links': ['https://stats.stackexchange.com/questions/32464', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/12492/']}
jdg_371596
stackexchange
llm_judgeable_groundtruth_similarity
33877623
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Im trying to do a setter and getter for an arraylist. what am i doing wrong // Method to add employee public void addEmployee(Employee newGuy) { this.employee = newGuy; }// Method to get new employee public Employee getEmployees() { return employee; } Now provide the response and nothing else.
You can implement this: mMap.animateCamera(CameraUpdateFactory.zoomTo(16), 3000, new GoogleMap.CancelableCallback() { @Override public void onFinish() { //Here you can take the snapshot or whatever you want } @Override public void onCancel() { } }); The most detailed form of this method, GoogleMap.animateCamera(cameraUpdate, duration, callback), offers three arguments: cameraUpdate The CameraUpdate describing where to move the camera.callbackAn object that implements GoogleMap.CancellableCallback. This generalized interface for handling tasks defines two methods onCancel() and onFinished() . For animation, the methods are called in the following circumstances: onFinish() Invoked if the animation goes to completion without interruption. onCancel() Invoked if the animation is interrupted by calling stopAnimation() or starting a new camera movement. Alternatively, this can also occur if you call GoogleMap.stopAnimation(). Source: Google Maps Android API Guides
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33877623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_371597
stackexchange
llm_judgeable_groundtruth_similarity
27867137
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an exercise that needs to be done with O(n) time complexity, however, I can only solve it with an O(n^2) solution. You have an array and you need to count the longest contiguous sequence such that it's sum can be divided to 3 without any remainder. For example for array {1,2,3,-4,-1) , the function will return 4 because the longest sequence that its sum(0) can be divided to 3 is {2,3,-4,-1} . My solution O(n^2) is based on arithmetic progression . Is there any way to do it with O(n) complexity? Please, I only want a clue or a theoretical explanation. Please don't write the full solution :) Now provide the response and nothing else.
Let's take a look at prefix sums. A [L, R] subarray is divisble by 3 if and only if prefixSum[L - 1] mod 3 = prefixSum[R] mod 3 . This observation gives a very simple linear solution(because there are only 3 possible values of a prefix sum mod 3, we can simply find the first and the last one). For example, if the input array is {1, 2, 3, -4, -1}, the prefix sums are {0, 1, 0, 0, 2, 1}. (there are n + 1 prefix sums because of an empty prefix). Now you can just take a look at the first and last occurrence of 0, 1 and 2.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27867137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4340793/']}
jdg_371598
stackexchange
llm_judgeable_groundtruth_similarity
571302
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: Suppose $f \in L^1(\mathbb{R})$. I am wondering what conditions on $\hat f = \left[ s \mapsto \int e^{its} f(t) \ dt \right] \in C_0(\mathbb{R})$ suffice to make $f$ continuous (or, more accurately, equal almost everywhere to some unique continuous function). Example : If $\hat f \in L^1(\mathbb{R})$, then $f$ is, almost everywhere, equal to the inverse transform of $\hat f$ (Fourier inversion) so $f$ is continuous. However, it is possible for $f$ to be continuous, even to have $f \in C_c(\mathbb{R})$, and still not have $\hat f$ integrable. Examples: In his answer here , robjohn says that function $$f(t) = \begin{cases}\frac{-1}{\log(t) + \log(1-t)} & \text{ if } 0 < t < 1 \\0 & \text{ otherwise } \\\end{cases}$$ (see this plot ) has $\hat f \notin L^1(\mathbb{R})$. The problem of finding an $f \in C_c(\mathbb{R})$ such that $\hat f \notin L^1(\mathbb{R})$ is also discussed here . So, I'm wondering about other ways in which $\hat f$ can "see" continuity of $f$. Specifically: Question: If $\hat f \geq 0$, is $f$ continuous? If this is false, or even if it's true, I am also interested in the more general question: Question: In what ways can continuity of $f$ manifest itself as some property of the Fourier transform $\hat f$? Thanks. Now provide the response and nothing else.
I think your assertion is probably false. The "triangle" $f(x) = \max(1-|x|,0)$ has positive Fourier transform. If you take some linear combination of these:$$ g(x) = \sum a_n f(x/b_n) $$where $a_n,b_n>0$, you will end up with a function satisfying $f(x) = f(-x)$, and the function is convex and decreasing on $[0,\infty)$ (and probably any such function can be written as a limit of these). I think in this way you should be able to construct a function in $L^1$ whose Fourier transform is positive, but the function is discontinuous (that is, unbounded) at $x=0$. Details: Let $f$ be the above triangle wave. Notice $\| f\|_1 = 1$ and $\hat f \geq 0$. For each nonnegative integer $n$, define $f_n(x) = 2^n f(2^n x)$. Notice$$ \|f_n \|_1 = \int |f(2^n x)| d(2^n x) = \|f\|_1 = 1$$and $\hat f_n(x) = f(x/2^n) \geq 0$. The series $\sum_{n=0}^\infty \frac{1}{2^n} f_n$ converges $\| \cdot \|_1$-absolutely a function $g \in L^1(\mathbb{R})$. Since the Fourier transform is a contractive linear mapping from $L^1(\mathbb{R}) \to C_0(\mathbb{R})$ we get that $\sum_{n=0}^\infty \frac{1}{2^n} \hat f_n$ converges absolutely in the uniform norm to $\hat g$. Since $\hat f_n \geq 0$, it follows that $\hat g \geq 0$. Lastly, we must argue that $g$ is not equal almost everywhere to a continuous function. By monotonicity, the sum defining $g$ converges pointwise. On the other hand, since the series converges in $L^1$, a subsequence of the partial sums must converge almost everywhere. Thus $g$ equals, almost everywhere, the pointwise limit of its series. For any $N > 0$, there is an $\epsilon > 0$ such that $f_n(y) > 2^{n-1}$ whenever $|y| < \epsilon$ and $n<N$. It follows that $g$ is, unbounded on a neighbourhood of $0$, so $g$ cannot be equal, almost everwhere, to a continuous function.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/571302', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/6608/']}
jdg_371599
stackexchange
llm_judgeable_groundtruth_similarity
11833061
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is CSRF possible with PUT or DELETE methods? Or does the use of PUT or DELETE prevent CSRF? Now provide the response and nothing else.
Great question! In a perfect world, I can't think of a way to perform a CSRF attack. You cannot make PUT or DELETE requests using HTML forms. Images, Script tags, CSS Links etc all send GET requests to the server. XmlHttpRequest and browser plugins such as Flash/Silverlight/Applets will block cross-domain requests. So, in general, it shouldn't be possible to make a CSRF attack to a resource that supports PUT/DELETE verbs. That said, the world isn't perfect. There may be several ways in which such an attack can be made possible : Web Frameworks such as Rails have support for "pseudo method". If you put a hidden field called _method , set its value to PUT or DELETE, and then submit a GET or POST request, it will override the HTTP Verb. This is a way to support PUT or DELETE from browser forms. If you are using such a framework, you will have to protect yourself from CSRF using standard techniques You may accidentally setup a lax response headers for CORS on your server. This would allow arbitrary websites to make PUT and DELETE requests. At some point, HTML5 had planned to include support for PUT and DELETE in HTML Forms. But later, they removed that support. There is no guarantee that it won't be added later. Some browsers may actually have support for these verbs, and that can work against you. There may just be a bug in some browser plugin that could allow the attacker to make PUT/DELETE requests. In short, I would recommend protecting your resources even if they only support PUT and DELETE methods.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11833061', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/839199/']}
jdg_371600
stackexchange
llm_judgeable_groundtruth_similarity
119561
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Clearly Very important results in Math require the Axiom of choice, for example "any vector space has a base". But in the absence of AC (i.e., only in ZF) it is possible that a vector space has no basis. In another direction append the negation of AC to ZF . What happens to algebra or analysis now ? If you know any Theorem in this new system (other than those that can be drived in ZF alone) please let me know. A fine reference would also be helpful. Now provide the response and nothing else.
The negation of the axiom of choice only allows us to prove that there is some set which cannot be well-ordered. There is some family of non-empty sets whose product is empty. There is some partially ordered set in which every chain is bounded, but there is no maximal element. And so on. Of course, from a family without a choice function we can easily construct a set which cannot be well-ordered, and with it a partial order witnessing the failure of Zorn's lemma, and other examples. But we cannot really say much about this family. Is it a family of finite sets? Is it a family of countable sets? Is this family well-orderable? And so on. It turns out that mathematics is not just "you either love someone or you hate them". If you have no choice, you can still have plenty of degrees of choice, and without pointing out how much choice you have, or don't have, it's very hard to say much. Furthermore it is possible that the axiom of choice fails so very very far up the cumulative hierarchy that no set used by any mathematician (except set theorists, maybe) is a witness for this failure. In such universe it is true that some theorems will fail (e.g. there will be a commutative unital ring without a maximal ideal, and there will be a vector space without a basis), but their failure occurs so far beyond our interest that it's just as well possible to assume that it doesn't happen. All we can say, in case we assume the negation of AC, that all those principles equivalent to the axiom of choice fail somewhere , but we cannot possible give an intelligent answer about where these failures occur. You may also be interested in this math.SE answer of mine , which discusses a similar question.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/119561', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']}
jdg_371601
stackexchange
llm_judgeable_groundtruth_similarity
8359566
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to create a Regex test in JavaScript that will test a string to contain any of these characters: !$%^&*()_+|~-=`{}[]:";'<>?,./ More Info If You're Interested :) It's for a pretty cool password change application I'm working on. In case you're interested here's the rest of the code. I have a table that lists password requirements and as end-users types the new password, it will test an array of Regexes and place a checkmark in the corresponding table row if it... checks out :) I just need to add this one in place of the 4th item in the validation array. var validate = function(password){ valid = true; var validation = [ RegExp(/[a-z]/).test(password), RegExp(/[A-Z]/).test(password), RegExp(/\d/).test(password), RegExp(/\W|_/).test(password), !RegExp(/\s/).test(password), !RegExp("12345678").test(password), !RegExp($('#txtUsername').val()).test(password), !RegExp("cisco").test(password), !RegExp(/([a-z]|[0-9])\1\1\1/).test(password), (password.length > 7) ] $.each(validation, function(i){ if(this) $('.form table tr').eq(i+1).attr('class', 'check'); else{ $('.form table tr').eq(i+1).attr('class', ''); valid = false } }); return(valid);} Yes, there's also corresponding server-side validation! Now provide the response and nothing else.
The regular expression for this is really simple. Just use a character class. The hyphen is a special character in character classes, so it needs to be first: /[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]/ You also need to escape the other regular expression metacharacters. Edit: The hyphen is special because it can be used to represent a range of characters. This same character class can be simplified with ranges to this: /[$-/:-?{-~!"^_`\[\]]/ There are three ranges. '$' to '/', ':' to '?', and '{' to '~'. the last string of characters can't be represented more simply with a range: !"^_`[]. Use an ACSII table to find ranges for character classes.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/8359566', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/152054/']}
jdg_371602
stackexchange
llm_judgeable_groundtruth_similarity
1949455
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: Prove by induction that : $\left [ \left (3+\sqrt{5} \right )^{n} + \left (3-\sqrt{5} \right )^{n} \right ]$ is multiple of $ 2^{n}$ My proof is : At $n=1$ $$\frac{\left ( 3+\sqrt{5} \right )+\left ( 3-\sqrt{5} \right )}{2} = \frac{6}{2} = 3 \in \mathbb{Z}$$ Assume $P(k)$ is true $$\frac{\left ( 3+\sqrt{5} \right )^{k}+\left ( 3-\sqrt{5} \right )^{k}}{2^{k}} = m \in \mathbb{Z}$$ $$\Rightarrow \left ( 3+\sqrt{5} \right )^{k}+\left ( 3-\sqrt{5} \right)^{k} = 2^{k}.m \rightarrow (*)$$ At $n=k+1$ $$\left ( 3+\sqrt{5} \right )^{k+1}+\left ( 3-\sqrt{5} \right )^{k+1} = \left [ \left ( 3+\sqrt{5} \right )^{k}+\left ( 3-\sqrt{5} \right )^{k} \right ]\left [ \left ( 3+\sqrt{5} \right )+\left ( 3-\sqrt{5} \right ) \right ]-\left [ \left ( 3+\sqrt{5} \right )^{k}\left ( 3-\sqrt{5} \right )+\left ( 3-\sqrt{5} \right )^{k}\left ( 3+\sqrt{5} \right ) \right ]$$ from $(*) $: $$\left ( 3+\sqrt{5} \right )^{k+1}+\left ( 3-\sqrt{5} \right )^{k+1} =2^{k}.m.6-\left ( 3+\sqrt{5} \right )\left ( 3-\sqrt{5} \right ) \left [ \left ( 3+\sqrt{5} \right )^{k-1}+\left ( 3-\sqrt{5} \right )^{k-1} \right ] $$ but i can't resume my proof .. i can't do any thing with $\left [ \left ( 3+\sqrt{5} \right )^{k-1}+\left ( 3-\sqrt{5} \right )^{k-1} \right ]$ . Now provide the response and nothing else.
Another way to solve this problem is to define $a_n = (3 + \sqrt{5})^n + (3-\sqrt{5})^n$ and note that the characteristic equation of this sequence is $x^2 - 6x + 4 = 0$. Therefore $a_{n+2} = 6a_{n+1} - 4a_n$ Obviously we have that $2 \mid a_1$ and $4 \mid a_2$. Now assume that $2^n \mid a_n$ for all $n \le k$ for some integer $k$. Then we have: $$2^{k+1} \mid 6a_{k} - 4a_{k-1} = a_{k+1}$$ Hence the proof.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1949455', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/196610/']}
jdg_371603
stackexchange
llm_judgeable_groundtruth_similarity
1092243
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been playing with pyglet . It's very nice. However, if I run my code, which is in an executable file (call it game.py) prefixed with the usual #!/usr/bin/env python by doing ./game.py then it's a bit clunky. But if I run it with python -O ./game.py or PYTHONOPTIMIZE=1 ./game.py then its super-smooth. I'm don't care much why it runs slow without optimization; pyglet's documentation mentions that optimizing disables numerous asserts and also OpenGL's error checking, and I'm happy to leave it at that. My question is: how do people distributing Python code make sure the end users (with zero interest in debugging or modifying the code) run the optimized version of the code. Surely there's some better way than just telling people to make sure they use optimization in the release notes (which they probably won't read anyway) ? On Linux I can easily provide a ./game script to run the file for end users: #!/bin/shPYTHONOPTIMIZE=1 ./game.py $* but that's not very cross-platform. I have an idea I ought to be able to change the #! line to #!/usr/bin/env PYTHONOPTIMIZE=1 python or #!/usr/bin/env python -O but those don't seem to work as expected, and I'm not sure what they'd do on Windows. Is there some way of controlling optimization from within the code I'm unaware of ?Something like: import runtime runtime.optimize(True) What's considered best-practice in this area by people shipping multi-platform python code ? Now provide the response and nothing else.
"On Linux I can easily provide a ./game script to run the file for end users:" Correct. "but that's not very cross-platform." Half-correct. There are exactly two shell languages that matter. Standard Linux "sh" and Non-standard Windows "bat" (a/k/a cmd.exe) and that's all there is nowadays. [When I was a kid, there was Open VMS DCL and Data General's weird shell language and RSX-11 and all kinds of great stuff. Thank God for the Posix standard.] game.sh python -O game.py game.bat python -O game.py Interestingly the files are the same, only the extension (and the file format) had to be changed to make the various OS's happy. If you want true one-size-fits-all cross platform, you have to remember that Python is a shell language. This kind of thing works, also. game-startup.py import subprocesssubprocess.Popen( "python -O game.py" )
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1092243', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/24283/']}
jdg_371604
stackexchange
llm_judgeable_groundtruth_similarity
183973
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: To be holomorphic require to have derivative at $z\to0$ but $f(z)$ is undefined.Does it mean $z/z$ is not holomorphic at $z=0$? Now provide the response and nothing else.
Generally in complex analysis texts, after we are exposed to Riemann's Removable singularity theorem, every function written down that has a removable singularity is assumed to already have it removed, to avoid unnecessary extra clauses "and equal to $1$ at $z=0$" and the like. For example, $\displaystyle f(z) = \frac{\sin z}{z}$ may be written down and it may be written that $f(0)=1.$ Similarly, if we define $g(z)=z/z$ then without anything extra, one would normally go ahead and declare $g$ is holomorphic in $\mathbb{C}.$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/183973', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/25175/']}
jdg_371605
stackexchange
llm_judgeable_groundtruth_similarity
5118965
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: var num = 0;for(var i = 0; i < 10; i++){ for(var j = 0; j < 10 ; j++){ if(i == 5 && j == 5){ break; } num++; }}console.log(num) In the above code, I expect the result to be 55 but why the result is 95. But why if I added the label, the result become 55? var num = 0;outermost:for(var i = 0; i < 10; i++){ for(var j = 0; j < 10 ; j++){ if(i == 5 && j == 5){ break outermost; } num++; }}console.log(num); Now provide the response and nothing else.
when used without label, break only break the current loop, in your case the innermost for. So now j = 6, the condition is now wrong, and the loops continues for 40 more incrementation. When you put a label, break go to the "level" of the label, so the two for loops are skipped.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5118965', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/551404/']}
jdg_371606
stackexchange
llm_judgeable_groundtruth_similarity
32329268
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 checking for the existence of a file bu cannot find it, regardless of whether it is there or not if (System.IO.File.Exists("~/files/downloads/" + fileCode + ".pdf")) { return File("~/files/downloads/" + fileCode, "application/pdf", Server.UrlEncode(fileCode)); } else { return View("ErrorNotExistsView"); } How can I amend the code to check for the existence of the file correctly? Now provide the response and nothing else.
System.IO.File will work if you provide an absolute path or a relative path. A relative path will not be relative to the HTML root folder, but the current working directory . The current working directory will be a value like C:\Program Files (x86)\IIS Express . The ~ character at the beginning of the file path is only interpreted as part of the current ASP.NET context, which the File methods know nothing about. The method to help you here is HttpServerUtility.MapPath If you are in a controller method, you can invoke this method on the object HttpContext.Server , otherwise (e.g. in a View) you can use HttpContext.Current.Server . var relativePath = "~/files/downloads/" + fileCode + ".pdf"; var absolutePath = HttpContext.Server.MapPath(relativePath); if(System.IO.File.Exists(absolutePath)) ....
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/32329268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/715540/']}
jdg_371607
stackexchange
llm_judgeable_groundtruth_similarity
11205927
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I reinstall the AppFabric 1.1 , Why I'm getting this error "AppFabric installation failed because installer MSI returned with error code : 1603" .? I did run it with administrative rights. Below is the error log. 2012-06-26 18:20:07, Information Setup ===== Logging started: 2012-06-26 18:20:07+08:00 =====2012-06-26 18:20:07, Information Setup File: c:\a0ddcd54d09ca070ef\setup.exe2012-06-26 18:20:07, Information Setup InternalName: Setup.exe2012-06-26 18:20:07, Information Setup OriginalFilename: Setup.exe2012-06-26 18:20:07, Information Setup FileVersion: 1.1.2106.322012-06-26 18:20:07, Information Setup FileDescription: Setup.exe2012-06-26 18:20:07, Information Setup Product: Microsoft(R) Windows(R) Server AppFabric2012-06-26 18:20:07, Information Setup ProductVersion: 1.1.2106.322012-06-26 18:20:07, Information Setup Debug: False2012-06-26 18:20:07, Information Setup Patched: False2012-06-26 18:20:07, Information Setup PreRelease: False2012-06-26 18:20:07, Information Setup PrivateBuild: False2012-06-26 18:20:07, Information Setup SpecialBuild: False2012-06-26 18:20:07, Information Setup Language: Language Neutral2012-06-26 18:20:07, Information Setup 2012-06-26 18:20:07, Information Setup OS Name: Windows 7 Ultimate2012-06-26 18:20:07, Information Setup OS Edition: Ultimate2012-06-26 18:20:07, Information Setup OSVersion: Microsoft Windows NT 6.1.7601 Service Pack 12012-06-26 18:20:07, Information Setup CurrentCulture: en-US2012-06-26 18:20:07, Information Setup Processor Architecture: x862012-06-26 18:20:07, Information Setup Event Registration Source : AppFabric_Setup2012-06-26 18:20:07, Information Setup 2012-06-26 18:20:07, Information Setup Microsoft.ApplicationServer.Setup.Upgrade.V1UpgradeSetupModule : Initiating V1.0 Upgrade module.2012-06-26 18:20:07, Information Setup Microsoft.ApplicationServer.Setup.Upgrade.V1UpgradeSetupModule : V1.0 is not installed.2012-06-26 18:20:33, Information Setup Microsoft.ApplicationServer.Setup.Upgrade.V1UpgradeSetupModule : Initiating V1 Upgrade pre-install.2012-06-26 18:20:33, Information Setup Microsoft.ApplicationServer.Setup.Upgrade.V1UpgradeSetupModule : V1.0 is not installed, not taking backup.2012-06-26 18:20:33, Information Setup Enumerating Windows features2012-06-26 18:20:36, Information Setup Executing c:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe with commandline -iru.2012-06-26 18:20:46, Information Setup Return code from aspnet_regiis.exe is 02012-06-26 18:20:46, Information Setup Windows features successfully enabled.2012-06-26 18:20:46, Information Setup Process.Start: C:\Windows\system32\msiexec.exe /quiet /norestart /i "c:\a0ddcd54d09ca070ef\Packages\AppFabric-1.1-for-Windows-Server-32.msi" ADDDEFAULT=Worker,WorkerAdmin,CacheClient,Setup /l*vx "C:\Users\COMPUTER-Name\AppData\Local\Temp\AppServerSetup1_1(2012-06-26 18-20-46).log" LOGFILE="C:\Users\COMPUTER-Name\AppData\Local\Temp\AppServerSetup1_1_CustomActions(2012-06-26 18-20-46).log" INSTALLDIR="C:\Program Files\AppFabric 1.1 for Windows Server" LANGID=en-US2012-06-26 18:21:46, Information Setup Process.ExitCode: 0x000006432012-06-26 18:21:46, Error Setup AppFabric installation failed because installer MSI returned with error code : 16032012-06-26 18:21:46, Error Setup 2012-06-26 18:21:46, Error Setup AppFabric installation failed because installer MSI returned with error code : 16032012-06-26 18:21:46, Error Setup 2012-06-26 18:21:46, Information Setup Microsoft.ApplicationServer.Setup.Core.SetupException: AppFabric installation failed because installer MSI returned with error code : 16032012-06-26 18:21:46, Information Setup at Microsoft.ApplicationServer.Setup.Installer.WindowsInstallerProxy.GenerateAndThrowSetupException(Int32 exitCode, LogEventSource logEventSource)2012-06-26 18:21:46, Information Setup at Microsoft.ApplicationServer.Setup.Installer.WindowsInstallerProxy.Invoke(LogEventSource logEventSource, InstallMode installMode, String packageIdentity, List`1 updateList, List`1 customArguments)2012-06-26 18:21:46, Information Setup at Microsoft.ApplicationServer.Setup.Installer.MsiInstaller.InstallSelectedFeatures()2012-06-26 18:21:46, Information Setup at Microsoft.ApplicationServer.Setup.Installer.MsiInstaller.Install()2012-06-26 18:21:46, Information Setup at Microsoft.ApplicationServer.Setup.Client.SetupWorkflow.StartActionPhase()2012-06-26 18:21:46, Information Setup at Microsoft.ApplicationServer.Setup.Client.ProgressPage.StartAction()2012-06-26 18:21:46, Information Setup 2012-06-26 18:21:46, Information Setup === Summary of Actions ===2012-06-26 18:21:46, Information Setup Required Windows components : Completed Successfully2012-06-26 18:21:46, Information Setup Microsoft .NET Framework 3.5.1 : Completed Successfully2012-06-26 18:21:46, Information Setup Windows Communication Foundation Non-HTTP Activation : Completed Successfully2012-06-26 18:21:46, Information Setup IIS Management Console : Completed Successfully2012-06-26 18:21:46, Information Setup AppFabric 1.1 for Windows Server : Failed2012-06-26 18:21:46, Information Setup Hosting Services : Failed2012-06-26 18:21:46, Information Setup Cache Client : Failed2012-06-26 18:21:46, Information Setup Hosting Administration : Failed2012-06-26 18:21:46, Information Setup Microsoft Update : Skipped2012-06-26 18:21:46, Information Setup Microsoft Update : Skipped2012-06-26 18:21:46, Information Setup 2012-06-26 18:21:46, Information Setup ===== Logging stopped: 2012-06-26 18:21:46+08:00 ===== Now provide the response and nothing else.
I had a similar problem 9/21/2012 11:28:01 AM EXEPATH=powershell.exe PARAMS=-command "$str = [System.Environment]::GetEnvironmentVariable(\"PSModulePath\", [System.EnvironmentVariableTarget]::Machine); $str = $str+\";c:\Program Files\AppFabric 1.1 for Windows Server\PowershellModules\"; c:\Windows\system32\setx.exe /M PSModulePath \"$str\"" LOGFILE=C:\Users\XXXXXXX\AppData\Local\Temp\AppServerSetup1_1_CustomActions(2012-09-21 11-27-26).logError: ERROR: Invalid syntax. Default option is not allowed more than '2' time(s).Error: Type "SETX /?" for usage. My issue was the PSModulePath having an improper " in it it was: C:\Windows\system32\WindowsPowerShell\v1.0\Modules\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\PowerShell\Modules" removing the extraneous " corrected the issue To change this go to Control Panel -> System -> Advanced System Settings -> On the Advanced Tab Select Enviroment Variables -> Under System Variables there is a Variable named PSModulePath , select it -> Click Edit -> Remove trailing "
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11205927', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1170573/']}
jdg_371608
stackexchange
llm_judgeable_groundtruth_similarity
30614279
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 just starting with a small tkinter tree program in python 3.4. I'm stuck with returning the first value of the row selected .I have multiple rows with 4 columns and I am calling a function on left-click on a item: tree.bind('<Button-1>', selectItem) The function: def selectItem(a): curItem = tree.focus() print(curItem, a) This gives me something like this: I003 <tkinter.Event object at 0x0179D130> It looks like the selected item gets identified correctly.All I need now is how to get the first value in the row. tree-creation: from tkinter import *from tkinter import ttkdef selectItem(): passroot = Tk()tree = ttk.Treeview(root, columns=("size", "modified"))tree["columns"] = ("date", "time", "loc")tree.column("date", width=65)tree.column("time", width=40)tree.column("loc", width=100)tree.heading("date", text="Date")tree.heading("time", text="Time")tree.heading("loc", text="Loc")tree.bind('<Button-1>', selectItem)tree.insert("","end",text = "Name",values = ("Date","Time","Loc"))tree.grid()root.mainloop() Now provide the response and nothing else.
To get the selected item and all its attributes and values, you can use the item method: def selectItem(a): curItem = tree.focus() print tree.item(curItem) This will output a dictionary, from which you can then easily retrieve individual values: {'text': 'Name', 'image': '', 'values': [u'Date', u'Time', u'Loc'], 'open': 0, 'tags': ''} Also note that the callback will be executed before the focus in the tree changed, i.e. you will get the item that was selected before you clicked the new item. One way to solve this is to use the event type ButtonRelease instead. tree.bind('<ButtonRelease-1>', selectItem)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30614279', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3770204/']}
jdg_371609
stackexchange
llm_judgeable_groundtruth_similarity
22882347
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: when trying to extract some values from the database using the model object User I get the following error : BadMethodCallException Method [find] does not exist Here are my files : Model User <?phpuse Illuminate\Auth\UserInterface;use Illuminate\Auth\Reminders\RemindableInterface;class User extends Eloquent implements UserInterface, RemindableInterface { /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = array('password'); public function projects() { return $this->belongsToMany('Project'); } public function trys() { return $this->hasMany('Try'); } /** * Get the unique identifier for the user. * * @return mixed */ public function getAuthIdentifier() { return $this->getKey(); } /** * Get the password for the user. * * @return string */ public function getAuthPassword() { return $this->password; } /** * Get the e-mail address where password reminders are sent. * * @return string */ public function getReminderEmail() { return $this->email; }} Controller user : <?phpclass user extends BaseController { public function showWelcome($id) { $user1 = User::find($id); return View::make('users.index', array('user' => $user1)); // }} View users/index.php <!doctype html><html lang="en"><head> <meta charset="UTF-8"> <title>first page</title></head><body> <?php echo 'Hello'; ?></body></html> and the routes.php : <?phpRoute::get('user/{id}', 'user@showWelcome');Route::get('/', function(){ return View::make('hello');}); Thanks for the help Now provide the response and nothing else.
You should not get this error, because it seems like you are using Eloquent and there is a find() method on it. But you are getting this error and there are some possible reasons: 1) The User:: you are calling is not the same you are showing here, to check execute in your controller: $reflector = new ReflectionClass("User");$fn = $reflector->getFileName();dd($fn); It must show you the full path of your class. 2) There's is something wrong with autoloading, you can run: composer dumpautoload To try to fix it. 3) There is something wrong with Laravel sources, you can delete Laravel code: rm -rf vendor/laravel and install it again composer update
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22882347', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/891623/']}
jdg_371610
stackexchange
llm_judgeable_groundtruth_similarity
392476
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 was just wondering, out of curiosity, do we know if there are more primes with even leading digits or odd leading digits? For example, primes with even leading digits would be $23$ or $29$ and primes with odd leading digits would be $31$ or $97$. If we haven't figured it out then how do we do something like that? Thanks Now provide the response and nothing else.
The Prime Number Theorem can be used to find the supremum and infimum of the relative densities. In particular for primes starting with odd digits the upper bound is 7/9 = 0.777... (if you sample numbers starting 1999...) and the lower bound is 41/81 = 0.506... (if you sample numbers starting 8999...). The supremum of a set is its least upper bound. For a finite set, a supremum is its maximum. For infinite sets, though, the supremum may be ("slightly") greater than all the members of the set. For example, the set $\{x:x<3\}$ has supremum 3 even though all members are less than 3. You can see that there is no maximum for this set, since if you choose some $y$ in the set it is less than $(3+y)/2$ which is less than 3, and so also in the set. Similarly, the infimum is the greatest lower bound of the set, the generalization of the minimum. What you might like in a situation like this would be the relative density of the primes starting with odd digits in the set of primes. This would be$$\lim_{x\to\infty}\frac{\text{# of primes}\le x\text{ starting with an odd digit}}{\text{# of primes}\le x}$$ But what happens if this limit does not exist? For example, it might go up to 70%, then back down to 55%, then back up to 70%, and repeat ad infinitum . In fact this is precisely what happens! So instead of looking for the limit, which does not exist (just like the maximum of $\{x:x<3\}$ does not exist), we look for the limit supremum and limit infimum. These always exist, and they are equal exactly when the limit exists (in which case they are equal to the limit). But what is a limit supremum (lim sup for short)? In this case, it is$$\lim_{y\to\infty}\sup_{x\ge y}\frac{\text{# of primes}\le x\text{ starting with an odd digit}}{\text{# of primes}\le x}$$or in other words, the largest value that the function becomes arbitrarily close to infinitely often. (If it happened only finitely often, then it happens for the last time at some $y_0$, and the limit goes beyond $y_0$ to $\infty.$) Of course the limit inferior (lim inf) is defined similarly with $\inf$ in place of $\sup.$ So much for the preliminaries. Now it's time to look at the Prime Number Theorem. It says that there are $(1+o(1))(x/\log x)$ primes below $x.$ The meaning of $o(1)$ is technical, but basically it's just some number that becomes arbitrarily small as $x$ increases. Now for some constant $0<\alpha<1$ the number of primes between $\alpha x$ and $x$ is $(1+o(1))(x/\log x) - (1+o(1))(\alpha x/\log(\alpha x))=(1+o(1))(1-\alpha)x/\log x.$ (The different $o(1)$ are actually different numbers, so they don't cancel the way you'd expect. The notation is funny, but that's the way it's usually written.) So basically there are just the number of primes you'd expect between $\alpha x$ and $x$ since the logarithm in the density grows so slowly. Now we can use this to derive the densities we need. First, let's look at the relative density of the odd-starting primes between $10^{n-1}$ and $10^n.$ 5/9 start with an odd digit and 4/9 start with an even digit, since by the above use of the Prime Number Theorem the densities are what we'd expect. Now you can do the same with the primes between $10^{n-2}$ and $10^{n-1}$, etc., so for the primes below $10^n$ you have 5/9 starting with an odd digit. But we don't want to restrict ourselves to looking just at powers of 10. What if we looked at numbers below $2\cdot10^n$? Then half would be below $10^n$ of which 5/9 would start with an odd digit, and the half between $10^n$ and $2\cdot10^n$ all start with odd digits. Thus (5/9+1)/2 = 7/9 start with odd digits. It's not hard to see that this is the best you can do. Similarly, on the other side, if you look at $9\cdot10^n$ you have nine groups: the ones below $10^n$ have 5/9 odd first digits, the $n-$digit ones starting with 1, 3, 5, or 7 are all odd-initial, and the $n-$digit ones starting 2, 4, 6, 8 are all even-initial. Overall that's (5/9+4)/9 = 41/81. And we're done!
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/392476', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/38296/']}
jdg_371611
stackexchange
llm_judgeable_groundtruth_similarity
46814260
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 stuck with a weird issue. I'm trying to locally connect Spark to MongoDB using mongodb spark connector. Apart from setting up spark I'm using the following code: val readConfig = ReadConfig(Map("uri" -> "mongodb://localhost:27017/movie_db.movie_ratings", "readPreference.name" -> "secondaryPreferred"), Some(ReadConfig(sc)))val writeConfig = WriteConfig(Map("uri" -> "mongodb://127.0.0.1/movie_db.movie_ratings"))// Load the movie rating data from Mongo DBval movieRatings = MongoSpark.load(sc, readConfig).toDF()movieRatings.show(100) However, I get a compilation error: java.lang.IllegalArgumentException: Missing database name. Set via the 'spark.mongodb.input.uri' or 'spark.mongodb.input.database' property. On line where I set up readConfig. I don't get why it's complaining for not set uri when I clearly have a uri property in the Map.I might be missing something. Now provide the response and nothing else.
You can do it from SparkSession as mentioned here val spark = SparkSession.builder() .master("local") .appName("MongoSparkConnectorIntro") .config("spark.mongodb.input.uri", "mongodb://localhost:27017/movie_db.movie_ratings") .config("spark.mongodb.input.readPreference.name", "secondaryPreferred") .config("spark.mongodb.output.uri", "mongodb://127.0.0.1/movie_db.movie_ratings") .getOrCreate() create dataframe using the config val readConfig = ReadConfig(Map("uri" -> "mongodb://localhost:27017/movie_db.movie_ratings", "readPreference.name" -> "secondaryPreferred"))val df = MongoSpark.load(spark) Write df to mongodb MongoSpark.save(df.write .option("spark.mongodb.output.uri", "mongodb://127.0.0.1/movie_db.movie_ratings") .mode("overwrite")) In your code: prefixes are missing in config val readConfig = ReadConfig(Map( "spark.mongodb.input.uri" -> "mongodb://localhost:27017/movie_db.movie_ratings", "spark.mongodb.input.readPreference.name" -> "secondaryPreferred"), Some(ReadConfig(sc)))val writeConfig = WriteConfig(Map( "spark.mongodb.output.uri" -> "mongodb://127.0.0.1/movie_db.movie_ratings"))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46814260', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7179862/']}
jdg_371612
stackexchange
llm_judgeable_groundtruth_similarity
20271123
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 does Go want for the second param in this SQL query.I am trying to use the IN lookup in postgres. stmt, err := db.Prepare("SELECT * FROM awesome_table WHERE id= $1 AND other_field IN $2")rows, err := stmt.Query(10, ???) What I really want: SELECT * FROM awesome_table WHERE id=10 AND other_field IN (this, that); Now provide the response and nothing else.
Query just takes varargs to replace the params in your sqlso, in your example, you would just do rows, err := stmt.Query(10) say, this and that of your second example were dynamic, then you'd do stmt, err := db.Prepare("SELECT * FROM awesome_table WHERE id=$1 AND other_field IN ($2, $3)")rows, err := stmt.Query(10,"this","that") If you have variable args for the "IN" part, you can do ( play ) package mainimport "fmt"import "strings"func main() { stuff := []interface{}{"this", "that", "otherthing"} sql := "select * from foo where id=? and name in (?" + strings.Repeat(",?", len(stuff)-1) + ")" fmt.Println("SQL:", sql) args := []interface{}{10} args = append(args, stuff...) fakeExec(args...) // This also works, but I think it's harder for folks to read //fakeExec(append([]interface{}{10},stuff...)...)}func fakeExec(args ...interface{}) { fmt.Println("Got:", args)}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/20271123', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/292789/']}
jdg_371613
stackexchange
llm_judgeable_groundtruth_similarity
13214809
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a simple, built-in way to print a 2D Python list as a 2D matrix? So this: [["A", "B"], ["C", "D"]] would become something like A BC D I found the pprint module, but it doesn't seem to do what I want. Now provide the response and nothing else.
To make things interesting, let's try with a bigger matrix: matrix = [ ["Ah!", "We do have some Camembert", "sir"], ["It's a bit", "runny", "sir"], ["Well,", "as a matter of fact it's", "very runny, sir"], ["I think it's runnier", "than you", "like it, sir"]]s = [[str(e) for e in row] for row in matrix]lens = [max(map(len, col)) for col in zip(*s)]fmt = '\t'.join('{{:{}}}'.format(x) for x in lens)table = [fmt.format(*row) for row in s]print '\n'.join(table) Output: Ah! We do have some Camembert sir It's a bit runny sir Well, as a matter of fact it's very runny, sirI think it's runnier than you like it, sir UPD: for multiline cells, something like this should work: text = [ ["Ah!", "We do have\nsome Camembert", "sir"], ["It's a bit", "runny", "sir"], ["Well,", "as a matter\nof fact it's", "very runny,\nsir"], ["I think it's\nrunnier", "than you", "like it,\nsir"]]from itertools import chain, izip_longestmatrix = chain.from_iterable( izip_longest( *(x.splitlines() for x in y), fillvalue='') for y in text) And then apply the above code. See also http://pypi.python.org/pypi/texttable
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/13214809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/363078/']}
jdg_371614
stackexchange
llm_judgeable_groundtruth_similarity
50786482
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 code (Java 8) snippet below drops the seconds part of my date time when the seconds value is zero within the date parsed using LocalDateTime.parse , like 2018-07-10 00:00: 00 : final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");final LocalDateTime localDateTime = LocalDateTime.parse("2018-07-06 00:00:00", dateTimeFormatter);final String lexicalDate = localDateTime.toString();System.out.println("Lexical Date : "+ lexicalDate);final XMLGregorianCalendar gregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(lexicalDate);System.out.println("Gregorian Calendar : "+ gregorianCalendar); The Lexical Date is printed as : Lexical Date : 2018-07-10T00:00 instead of : Lexical Date : 2018-07-10T00:00:00 Now this is affecting the date value of the gregorian calendar which returns null when the second is dropped. Other cases when the seconds value is greater than Zero, it works perfectly. javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar(lexicalDate) The above code is returning null whenever the seconds value is dropped because of 00 seconds value within the parsed string. Can someone assist with a better way that handles this issue using LocalDate time, otherwise it might be a bug/funny control in Java 8 LocalDateTime. Please note I do not have control over this date value, it's coming from a third party platform. Now provide the response and nothing else.
Feature, not a bug You are seeing the documented behavior of the particular DateTimeFormatter used by the LocalDateTime::toString method. Excerpt, my emphasis: The output will be one of the following ISO-8601 formats: uuuu-MM-dd'T'HH:mm uuuu-MM-dd'T'HH:mm:ss uuuu-MM-dd'T'HH:mm:ss.SSS uuuu-MM-dd'T'HH:mm:ss.SSSSSS uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero . If you want other behavior when generating a String to represent the value of you LocalDateTime , use a different DateTimeFormatter and pass it to LocalDateTime::format . String output = myLocalDateTime.format( someOtherFormatter ) ; The LocalDateTime has no “format” as it is not text. It is the job of the DateTimeFormatter to parse or generate String objects of a particular format.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50786482', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7137209/']}
jdg_371615
stackexchange
llm_judgeable_groundtruth_similarity
38272128
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 web application that is written with React and bundled with Webpack. The application has a JSON config file that I want to include at runtime and not to be bundled with webpack. In my entry point for the application I am importing the contents using the json-loader but doing that forces the file to be embedded in the application and I can't update the config file once it's been bundled. How can I configure my webpack.config.js file to exclude my config.json file but still let me import it in my application? It's not a module so I don't know if it can be included in the externals section of my webpack.config.js I tried using require.ensure but all I see now is the contents of config.json bundled into a 1.1.bundle.js file and changing the config file does nothing. app.js let config;require.ensure(['./config.json'], require => { config = require('./config.json');}); Now provide the response and nothing else.
use current library <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script> add put legend: { labels: { usePointStyle: true, }, } inside options and not inside var XPData = {...} fiddle var ctx = document.getElementById("myChart");class DataPoint { constructor(x, y) { this.x = x; this.y = y; }}var days = 85;var chillax = 72.5;// XP DATA SET var XPData = { label: 'XP Earned', fill: false, backgroundColor: "#444", borderColor: "#444", pointBorderColor: "#444", pointBackgroundColor: "#444", data: [], showLine: false,};// XP Data generationvar total = 0;for (var i = 0; i < 35; i++) { total += 10 * Math.floor(Math.random() + 0.5); total += 5 * Math.floor(Math.random() + 0.5); total += 5 * Math.floor(Math.random() + 0.5); var p = new DataPoint(i + 1, total); XPData.data.push(p);}// XP Trend Data var XPTrendData = { label: 'XP Trend', fill: false, pointRadius: 0, lineTension: 0, borderDash: [5, 5], borderColor: "#ccc", backgroundColor: "rgba(0,0,0,0)", data: [],};// XP Trend calculaionvar total = 0;var days_so_far = XPData.data.length;total = XPData.data[days_so_far - 1].y;var average_per_day = total / days_so_far;var trend_total = total;for (i = days_so_far; i < days; i++) { p = new DataPoint(i, trend_total); XPTrendData.data.push(p); trend_total += average_per_day;}// Chillax Line Data Setvar ChillaxLineData = { label: 'Chillax Line', pointRadius: 0, backgroundColor: "rgba(0,0,0,0)", borderColor: "#337AB7", data: [],};// Chill Line Generationfor (i = 1; i < days; i++) { p = new DataPoint(i, Math.floor(i * chillax * 10 / days)); ChillaxLineData.data.push(p);}var options = { scaleUse2Y: true, scales: { xAxes: [{ type: 'linear', position: 'bottom', ticks: { max: days, min: 0, stepSize: 5, }, scaleLabel: { display: true, labelString: 'Days of Class' }, }], yAxes: [{ id: "y-axis-XP", position: 'right', ticks: { max: 1000, min: 0, stepSize: 50, }, scaleLabel: { display: true, labelString: 'XP' }, gridLines: {}, }, { id: "y-axis-percent", position: 'left', ticks: { max: 100, min: 0, stepSize: 5, }, scaleLabel: { display: true, labelString: 'Percent' }, gridLines: { /*show: true, color: "rgba(255, 255, 255, 1)", lineWidth: 1, drawOnChartArea: true, drawTicks: true, zeroLineWidth: 1, zeroLineColor: "rgba(255,255,255,1)", */ }, } ], }, title: { text: 'A Map of Your Progress', display: true, }, legend: { labels: { usePointStyle: true, }, }};var data = { datasets: [XPData, XPTrendData, ChillaxLineData, ]};var myChart = new Chart(ctx, { type: 'line', data: data, options: options,}); <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script><canvas id="myChart" width="400" height="250"></canvas>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38272128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3005637/']}
jdg_371616
stackexchange
llm_judgeable_groundtruth_similarity
3785561
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: When $2^x - 2^{-x} = 4$ , then $2^{2x} + 2^{-2x} =\hbox{ ?}$ and $2^{3x} - 2^{-3x} =\hbox{ ?}$ I have a doubt with this one. I assume I should use some kind of formula to solve it because if I solve the first equation I get that $x = \log_2(1 + \sqrt5)$ and then I just solve the other two equations and get that the result of the second one is $18$ and the last one is $76$ . The thing is that this exercise is supposed to be done quickly but this method takes a lot of time to calculate. Is there another way to solve it that I'm missing? Now provide the response and nothing else.
hint Let $$X=2^x$$ then $$2^x-2^{-x}=X-\frac 1X=4$$ $$(X-\frac 1X)^2=X^2+\frac{1}{X^2}-2$$ $$=4^2=16$$ thus $$2^{2x}+2^{-2x}=X^2+\frac{1}{X^2}=16+2=18$$ Now do the same with $(X-\frac {1}{X})^3$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3785561', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/815073/']}
jdg_371617
stackexchange
llm_judgeable_groundtruth_similarity
288049
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have done one with $\displaystyle\int_0^{\infty}\frac{x-\sin x}{x^3}\ \text{d}x$, but I have no ideas with these:$$\begin{align*}I&=\int_{0}^{\infty }{\frac{\sin x}{\cosh x+\cos x}\cdot \frac{{{x}^{n}}}{n!}\ \text{d}x}\tag1 \\ J&= \int_{0}^{\infty }{\frac{x-\sin x}{\left( {{\pi }^{2}}+{{x}^{2}} \right){{x}^{3}}}\ \text{d}x}\tag2 \\ \end{align*}$$ Now provide the response and nothing else.
I can address the second integral: $$\int_{0}^{\infty }{dx \: \frac{x-\sin x}{\left( {{\pi }^{2}}+{{x}^{2}} \right){{x}^{3}}}}$$ Hint: We can use Parseval's Theorem $$\int_{-\infty}^{\infty} dx \: f(x) \bar{g}(x) = \frac{1}{2 \pi} \int_{-\infty}^{\infty} dk \: \hat{f}(k) \bar{\hat{g}}(k) $$ where $f$ and $\hat{f}$ are Fourier transform pairs, and same for $g$ and $\bar{g}$. The FT of $1/(x^2+\pi^2)$ is easy, so we need the FT of the rest of the integrand, which turns out to be possible. Define $$\hat{f}(k) = \int_{-\infty}^{\infty} dx \: f(x) e^{i k x} $$ It is straightforward to show using the Residue Theorem that, when $f(x) = (x^2+a^2)^{-1}$, then $$\hat{f}(k) = \frac{\pi}{a} e^{-a |k|} $$ Thus we need to compute, when $g(x) = (x-\sin{x})/x^3$, $$\begin{align} \hat{g}(k) &= \int_{-\infty}^{\infty} dx \: \frac{x-\sin{x}}{x^3} e^{i k x} \\ &= \frac{\pi}{2}(k^2-2 |k|+1) \mathrm{rect}(k/2) \\ \end{align}$$ where $$\mathrm{rect}(k) = \begin{cases} 1 & |k|<\frac{1}{2} \\ 0 & |k|>\frac{1}{2} \end{cases} $$ Then we can write, using the Parseval theorem, $$\begin{align} \int_{0}^{\infty }{dx \: \frac{x-\sin x}{\left( {{\pi }^{2}}+{{x}^{2}} \right){{x}^{3}}}} &= \frac{1}{8} \int_{-1}^1 dk \: (k^2-2 |k|+1) e^{-\pi |k|} \\ &= \frac{\left(2-2 \pi +\pi ^2\right)}{4 \pi ^3}-\frac{ e^{-\pi }}{2 \pi ^3} \\ \end{align}$$ NOTE Deriving $\hat{g}(k)$ from scratch is challenging; nevertheless, it is straightforward (albeit, a bit messy) to prove that the expression is correct by performing the inverse transform on $\hat{g}(k)$ to obtain $g(x)$. I did this out and proved it to myself; I can provide the details to those that want to see them.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/288049', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/58196/']}
jdg_371618
stackexchange
llm_judgeable_groundtruth_similarity
7952154
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have been using the Spring RestTemplate for a while and I consistently hit a wall when I'am trying to debug it's requests and responses. I'm basically looking to see the same things as I see when I use curl with the "verbose" option turned on. For example : curl -v http://twitter.com/statuses/public_timeline.rss Would display both the sent data and the received data (including the headers, cookies, etc.). I have checked some related posts like : How do I log response in Spring RestTemplate? but I haven't managed to solve this issue. One way to do this would be to actually change the RestTemplate source code and add some extra logging statements there, but I would find this approach really a last resort thing. There should be some way to tell Spring Web Client/RestTemplate to log everything in a much friendlier way. My goal would be to be able to do this with code like : restTemplate.put("http://someurl", objectToPut, urlPathValues); and then to get the same type of debug information (as I get with curl) in the log file or in the console.I believe this would be extremely useful for anyone that uses the Spring RestTemplate and has problems. Using curl to debug your RestTemplate problems just doesn't work (in some cases). Now provide the response and nothing else.
Just to complete the example with a full implementation of ClientHttpRequestInterceptor to trace request and response: import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.HttpRequest;import org.springframework.http.client.ClientHttpRequestExecution;import org.springframework.http.client.ClientHttpRequestInterceptor;import org.springframework.http.client.ClientHttpResponse;public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor { final static Logger log = LoggerFactory.getLogger(LoggingRequestInterceptor.class); @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { traceRequest(request, body); ClientHttpResponse response = execution.execute(request, body); traceResponse(response); return response; } private void traceRequest(HttpRequest request, byte[] body) throws IOException { log.info("===========================request begin================================================"); log.debug("URI : {}", request.getURI()); log.debug("Method : {}", request.getMethod()); log.debug("Headers : {}", request.getHeaders() ); log.debug("Request body: {}", new String(body, "UTF-8")); log.info("==========================request end================================================"); } private void traceResponse(ClientHttpResponse response) throws IOException { StringBuilder inputStringBuilder = new StringBuilder(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8")); String line = bufferedReader.readLine(); while (line != null) { inputStringBuilder.append(line); inputStringBuilder.append('\n'); line = bufferedReader.readLine(); } log.info("============================response begin=========================================="); log.debug("Status code : {}", response.getStatusCode()); log.debug("Status text : {}", response.getStatusText()); log.debug("Headers : {}", response.getHeaders()); log.debug("Response body: {}", inputStringBuilder.toString()); log.info("=======================response end================================================="); }} Then instantiate RestTemplate using a BufferingClientHttpRequestFactory and the LoggingRequestInterceptor : RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();interceptors.add(new LoggingRequestInterceptor());restTemplate.setInterceptors(interceptors); The BufferingClientHttpRequestFactory is required as we want to use the response body both in the interceptor and for the initial calling code. The default implementation allows to read the response body only once.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7952154', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/619596/']}
jdg_371619
stackexchange
llm_judgeable_groundtruth_similarity
283761
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: Usually our compass is hold horizontally, and in the northern hemisphere it will point in the direction of to the north of the earth (actually to the South pole of the Earth's 'magnet'). But looking closer at some points, the magnetic field is not only horizontally aligned but also vertically. So in some point of view, the direction is not the north or the south of the Earth, but in or out of the earth. But does this influence a compass the same as when it is held vertically? Now provide the response and nothing else.
The north end of the compass needle is pulled down towards Earth when you hold it in the normal horizontal position in the northern hemisphere. So much so, in fact, that the south end needs to be slightly heavier to balance it. If you bring that same compass to Australia, the south end, already weighted, will be pulled down even further, perhap even dragging on the base of the compass. So you need to reverse the weights in any compass used in the southern hemisphere. A chart of magnetic dip contour lines along which the dip measured at the Earth's surface is equal. These are called  isoclinic lines. Magnetic inclination, or dip angle, is the angle that the Earth's magnetic field makes with the horizontal. If you hold the compass vertically in the northern hemisphere, the North Pole end should be pulled downwards. Image Source: How Magnets Work A dip needle is just like a conventional compass, but instead of holding it horizontally, it is held vertically. It is a magnetic needle used for navigational purposes just like a compass, but is used predominantly when traveling around the north and south poles. Instead of measuring horizontal magnetic deflection, the dip needle measures vertical magnetic inclination. When over the equator, the magnetic field of Earth is parallel to the surface of the Earth. At the poles, or near them, a conventional compass is very unreliable.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/283761', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/103999/']}
jdg_371620
stackexchange
llm_judgeable_groundtruth_similarity
31575659
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 pycharm and it lists out all the errors/warnings associated with the code. While I understand most of them I am not sure of this one "Shadows name xyz from outer scope". There are a few SO posts regarding this: How bad is shadowing names defined in outer scopes? but then they seem to be accessing a global variable. In my case, my __main__ function has a few variable names and then it is calling another function sample_func which uses those variable names again (primarily the loop variable names). I am assuming because I am in a different function, the scope for these variables will be local, however the warning seem to suggest otherwise. Any thoughts? For your reference here is some code: def sample_func(): for x in range(1, 5): --> shadows name x from outer scope print xif __name__ == "__main__": for x in range(1, 5): sample_func() Now provide the response and nothing else.
The warning is about the potential danger you are introducing by re-using these names at inner scopes. It can cause you to miss a bug. For example, consider this def sample_func(*args): smaple = sum(args) # note the misspelling of `sample here` print(sample * sample)if __name__ == "__main__": for sample in range(1, 5): sample_func() Because you used the same name, your misspelling inside the function does not cause an error. When your code is very simple, you will get away with this type of thing with no consequences. But it's good to use these "best practices" in order to avoid mistakes on more complex code.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31575659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3742823/']}
jdg_371621
stackexchange
llm_judgeable_groundtruth_similarity
29245239
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 there is no difference, then I can just install Cygwin on my Windows 7 PC, and seems there's no need to buy a Macbook (as I can use UNIX command line already). Now provide the response and nothing else.
(Bind-mounted) volumes in Docker will maintain the permissions that are set onthe Docker host itself. You can use this to set the permissions on thosefiles and directories before using them in the container. Some background ; Permissions in Linux are based on user and group ids ( 'uid' / 'gid' ). Eventhough you see a user- and group name as owner, those names aren't actuallyimportant in Linux, they are only there to make it easier for you to see who's the owner of a file (they are looked up from the /etc/passwd file). You can set any uid / gid on a file; a user doesn't have to exist when setting those permissions. For example; touch foobar && sudo chown 1234:5678 foobar && ls -la foobar# UID and GID are set to 1234 / 5678, even though there's no such user-rw-rw-r-- 1 1234 5678 0 Mar 25 19:14 foobar Checking permissions (inside and outside a container) As mentioned above, Docker maintains ownership of the host when usinga volume. This example shows that permissions and ownership in the volume are the same outside and inside a container; # (First create a dummy site)mkdir -p volume-example/site && cd volume-exampleecho "<html><body>hello world</body></html>" > site/index.html# Permissions on the Docker host;ls -n site# total 4# -rw-rw-r-- 1 1002 1002 38 Mar 25 19:15 index.html# And, permissions inside a nginx container, using it as volume;sudo docker run --rm -v $(pwd)/site:/var/www nginx ls -n /var/www# total 4# -rw-rw-r-- 1 1002 1002 38 Mar 25 19:15 index.html Setting the permissions As explained, a user doesn't have to exist in order to use them, so even if we don't have a www-data user on the Docker host, we can still set the correct permissions if we know the "uid" and "gid" of that user inside the container; Let's see what the uid and gid of the www-data user is inside the container; sudo docker run --rm nginx id www-data# uid=33(www-data) gid=33(www-data) groups=33(www-data) First check the state before changing the permissions. This time werun the nginx container as user www-data ; sudo docker run \ --rm \ --volume $(pwd)/site:/var/www \ --user www-data nginx touch /var/www/can-i-write.txt# touch: cannot touch `/var/www/can-i-write.txt': Permission denied Next, set the permissions on the local directory, and see if we are able to write; sudo chown -R 33:33 sitesudo docker run \ --rm \ --volume $(pwd)/site:/var/www \ --user www-data nginx touch /var/www/can-i-write.txt Success!
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/29245239', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4656683/']}
jdg_371622
stackexchange
llm_judgeable_groundtruth_similarity
46226073
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 group of commands that inherit from a base class. The base class has the following declaration: public virtual async Task Execute(object parameter){} Inheriting classes provide an override of this method and not all of them await tasks. In these cases the compiler generates a warning: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. Is it correct to explicitly provide a task complete return value? public override async Task Execute(object parameter) { //code containing no await statements... await Task.CompletedTask;} Now provide the response and nothing else.
You should avoid the use of the async keyword inside overridden methods which do not await on anything, and instead just return Task.CompletedTask : public override Task Execute(object parameter) { //code containing no await statements... return Task.CompletedTask; // or Task.FromResult(0) for older .NET versions} This is one of the (few) use cases for such "mocked" tasks, as you may understand by looking at this question about Task.FromResult . Those considerations are still valid for Task.CompletedTask .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46226073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/650027/']}
jdg_371623
stackexchange
llm_judgeable_groundtruth_similarity
232762
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 was checking a Linux box and found a perl process running and taking a good share of cpu usage. With top, i could only perl in process name. When i pressed c , to view the command-line, it showed /var/spool/mail. Which does not make sense, since this is directory. My questions are: 1) Why did this happen? How this perl process could mask its command-line?2) What is the most reliable way of finding out where and how a process was started? Thanks! Now provide the response and nothing else.
In most cases just running ps is usually sufficient, along with your favorite flags to enable wide output. I lean towards ps -feww , but the other suggestions here will work. Note that if a program was started out of someone's $PATH , you're only going to see the executable name, not the full path. For example, try this: $ lftp &$ ps -feww | grep ftplars 9600 9504 0 11:30 pts/10 00:00:00 lftplars 9620 9504 0 11:31 pts/10 00:00:00 grep ftp It's important to note that the information visible in ps can be completely overwritten by the running program. For example, this code: int main (int argc, char **argv) { memset(argv[0], ' ', strlen(argv[0])); strcpy(argv[0], "foobar"); sleep(30); return(0);} If I compile this into a file called "myprogram" and run it: $ gcc -o myprogram myprogram.c$ ./myprogram &[1] 10201 And then run ps , I'll see a different process name: $ ps -f -p 10201UID PID PPID C STIME TTY TIME CMDlars 10201 9734 0 11:37 pts/10 00:00:00 foobar You can also look directly at /proc/<pid>/exe , which may be a symlink to the appropriate executable. In the above example, this gives you much more useful information than ps : $ls -l /proc/9600/exelrwxrwxrwx. 1 lars lars 0 Feb 8 11:31 /proc/9600/exe -> /usr/bin/lftp
{}
{'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/232762', 'https://serverfault.com', 'https://serverfault.com/users/58461/']}
jdg_371624
stackexchange
llm_judgeable_groundtruth_similarity
2619102
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have created users for my unit tests in two ways: 1) Create a fixture for "auth.user" that looks roughly like this: { "pk": 1, "model": "auth.user", "fields": { "username": "homer", "is_active": 1, "password": "sha1$72cd3$4935449e2cd7efb8b3723fb9958fe3bb100a30f2", ... } } I've left out the seemingly unimportant parts. 2) Use 'create_user' in the setUp function (although I'd rather keep everything in my fixtures class): def setUp(self): User.objects.create_user('homer', 'ho...@simpson.net', 'simpson') Note that the password is simpson in both cases. I've verified that this info is correctly being loaded into the test database time and time again. I can grab the User object using User.objects.get. I can verify the password is correct using 'check_password.' The user is active. Yet, invariably, self.client.login(username='homer', password='simpson') FAILS. I'm baffled as to why. I think I've read every single Internet discussion pertaining to this. Can anybody help? The login code in my unit test looks like this: login = self.client.login(username='homer', password='simpson') self.assertTrue(login) Thanks. Now provide the response and nothing else.
The code that doesn't work: from django.contrib.auth.models import Userfrom django.test import Clientuser = User.objects.create(username='testuser', password='12345')c = Client()logged_in = c.login(username='testuser', password='12345') Why doesn't it work? In the snippet above, when the User is created the actual password hash is set to be 12345 . When the client calls the login method, the value of the password argument, 12345 , is passed through the hash function, resulting in something like hash('12345') = 'adkfh5lkad438....' This is then compared to the hash stored in the database, and the client is denied access because 'adkfh5lkad438....' != '12345' The Solution The proper thing to do is call the set_password function, which passes the given string through the hash function and stores the result in User.password . In addition, after calling set_password we must save the updated User object to the database: user = User.objects.create(username='testuser')user.set_password('12345')user.save()c = Client()logged_in = c.login(username='testuser', password='12345')
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2619102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44440/']}
jdg_371625
stackexchange
llm_judgeable_groundtruth_similarity
268873
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: Need some help with this, i'm a bit stuck: Show that if $G$ is a finite group of even order, then $G$ has an odd number of elements of order $2$. Note that $e$ is the only element of order $1$. Now provide the response and nothing else.
Let $A$ be the set of all elements of order greater than $2$, and recall that $x$ and $x^{-1}$ have the same order. So convince yourself$$A=\bigcup_{x\in A}\{x,x^{-1}\}.$$ Conclude that $|A|$ is even. Now why does that imply that there are an odd number of elements of order $2$?
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/268873', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/54030/']}
jdg_371626
stackexchange
llm_judgeable_groundtruth_similarity
2811141
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: During the last years I always thought that in Java, Reflection is widely used during Unit testing. Since some of the variables/methods which have to be checked are private, it is somehow necessary to read the values of them. I always thought that the Reflection API is also used for this purpose. Last week i had to test some packages and therefore write some JUnit tests. As always i used Reflection to access private fields and methods. But my supervisor who checked the code wasn't really happy with that and told me that the Reflection API wasn't meant to use for such "hacking". Instead he suggested to modifiy the visibility in the production code. Is it really bad practice to use Reflection? I can't really believe that- Edit: I should have mentioned that i was required that all tests are in a separate package called test (so using protected visibilty e.g. wasn't a possible solution too) Now provide the response and nothing else.
IMHO Reflection should really only be a last resort, reserved for the special case of unit testing legacy code or an API you can't change. If you are testing your own code, the fact that you need to use Reflection means your design is not testable, so you should fix that instead of resorting to Reflection. If you need to access private members in your unit tests, it usually means the class in question has an unsuitable interface, and/or tries to do too much. So either its interface should be revised, or some code should be extracted into a separate class, where those problematic methods / field accessors can be made public. Note that using Reflection in general results in code which, apart from being harder to understand and maintain, is also more fragile. There are a whole set of errors which in the normal case would be detected by the compiler, but with Reflection they crop up as runtime exceptions only. Update: as @tackline noted, this concerns only using Reflection within one's own test code, not the internals of the testing framework. JUnit (and probably all other similar frameworks) uses reflection to identify and call your test methods - this is a justified and localized use of reflection. It would be difficult or impossible to provide the same features and convenience without using Reflection. OTOH it is completely encapsulated within the framework implementation, so it does not complicate or compromise our own testing code.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2811141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/329637/']}
jdg_371627
stackexchange
llm_judgeable_groundtruth_similarity
22158063
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an input field, where I want to apply the variant of ngChange . The input field is sort of binding with an ajax call, when user changes the input, the server side will process the data, however, I don't wanna make the call too often. Say the user wanna input a really string, I want the call be made only after user finishes the word he is about to type. Nevertheless, I don't wanna use event such as blur. What would be a better way to implement this, rather than setTimeout ? Now provide the response and nothing else.
Use ng-model-options in Angular > 1.3 <input type="text" ng-model="vm.searchTerm" ng-change="vm.search(vm.searchTerm)" ng-model-options="{debounce: 750}" /> Without ng-model-options -- In markup: <input ng-change="inputChanged()"> In your backing controller/scope var inputChangedPromise;$scope.inputChanged = function(){ if(inputChangedPromise){ $timeout.cancel(inputChangedPromise); } inputChangedPromise = $timeout(taskToDo,1000);} Then your taskToDo will only run after 1000ms of no changes.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/22158063', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2821224/']}
jdg_371628
stackexchange
llm_judgeable_groundtruth_similarity
1652545
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am wonder how to standardize multivariate normal value . Normal standard multivariate distribution of $q$ variables is $z\sim N_q(0,I_q)$. I have found that $a+Bz\sim N_q(Ba,BB^T)$ and based on this fact normalization could be performed throught two ways: 1) Substracting mean vector and then taking $B=\Sigma^{-0.5}$ (as it gives $\Sigma^{-0.5} \Sigma (\Sigma^{-0.5})^T=I_q$) we get normalized value: $z=\Sigma^{-0.5}(x-a)$. 2) Using Cholesky decomposition $\Sigma=U^TU$ we get normalization rule $z=(U^T)^{-1}(x-a)$ But both strategies does not work! So you can check it using matlab code below: MU=[0.1333,-0.1];SIGMA=[0.95,0.19;0.19,0.97];x=[0.5, 0.7];mvncdf(x,MU,SIGMA)z=(SIGMA^(-0.5))*transpose(x-MU);mvncdf(z)z=transpose(chol(SIGMA))^(-1)*transpose(x-MU);mvncdf(z) I also add code for R that gives the same results proving that the problem is not due to programm but due to incorrect appoach: SIGMA=matrix(c(0.95,0.19,0.19,0.97), ncol=2)MU=c(0.1333, -0.1)x=c(0.5,0.7)pmvnorm(mean = MU, sigma=SIGMA, lower=-Inf, upper=x)z=as.numeric((solve(sqrtm(SIGMA)))%*%(x-MU))pmvnorm(mean = MU, sigma=SIGMA, lower=-Inf, upper=z) As the difference is rather big I am sure that such standardization approach is incorrect. But it is the only technicks I have found despite it is a hot and applied subject. Will be very greatful for help! PS: I also performed Jordan form approach but the result is still wrong : [v,j]=jordan(SIGMA)B=v*j^(-0.5)*v^(-1)z=B*transpose(x-MU);mvncdf(z) Now provide the response and nothing else.
If $X\sim N_q(a,\Sigma)$ (so $X$ is a random vector taking values in $\mathbb R^{q\times1}$) and $B\in\mathbb R^{p\times q}$ then $BX\sim N_p(Ba,B\Sigma B^T)$. The matrix $\Sigma^{-1/2}$ should be taken to be the positive-definite symmetric square root of $\Sigma^{-1}$. Then we have $\Sigma^{-1/2}(X-a)\sim N_q(0,I_q)$. Where I'm sitting I don't have access to MATLAB. Maybe if you could post some output I could say something about that. My initial suspicion is that MATLAB may be taking $\Sigma^{-1/2}$ to be something other than the positive-definite symmetric square root of $\Sigma^{-1}$. If you could tell us what MATLAB tells you is the value of $\Sigma^{-1/2}$ that would tell us whether that is what is happening.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1652545', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/308848/']}
jdg_371629
stackexchange
llm_judgeable_groundtruth_similarity
17845366
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two files app.py and mod_login.py app.py from flask import Flaskfrom mod_login import mod_loginapp = Flask(__name__)app.config.update( USERNAME='admin', PASSWORD='default') mod_login.py # coding: utf8from flask import Blueprint, render_template, redirect, session, url_for, requestfrom functools import wrapsfrom app import appmod_login = Blueprint('mod_login', __name__, template_folder='templates') And python return this error: Traceback (most recent call last): File "app.py", line 2, in <module> from mod_login import mod_login File "mod_login.py", line 5, in <module> from app import app File "app.py", line 2, in <module> from mod_login import mod_loginImportError: cannot import name mod_login If I delete from app import app , code will be work, but how I can get access to app.config ? Now provide the response and nothing else.
The problem is that you have a circular import:in app.py from mod_login import mod_login in mod_login.py from app import app This is not permitted in Python. See Circular import dependency in Python for more info. In short, the solution are either gather everything in one big file delay one of the import using local import
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17845366', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1430313/']}
jdg_371630
stackexchange
llm_judgeable_groundtruth_similarity
36729150
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have been running Android Studio 1.5.1 doing development on a WMWare copy of Windows 2012 R2 and everything works fine. I've been able to run the device emulator with no problems and start various versions of Android running in AVD. Android Studio 2.x Change I recently installed Android Studio 2.0 (see image below for exact version). Now when I attempt to run the emulator nothing happens.Well, actually I do see a message in the status bar of Studio when I attempt to start the device, but then that message disappears and nothing happens after that. There is a warning that I need to turn off Hyper-V (see image below), but I don't believe that is possible since this is a VM. No Longer Possible? Is it not possible to run the emulator on the VM any more? Now provide the response and nothing else.
I just installed Android Studio 2.1 on my Windows 2008 R2 VM (running VMWare) and I'm happy to report that it is possible to run ARM based AVD (Android Virtual Devices) on the VM. Steps To Run Arm-based Virtual Device on VMWare Go to location where you've installed the Android SDKs (in my case it is at %appdata%\Android2\SDK\ If you are in the right place you should see a directory structure and directories like the ones shown in the first image below. Start the AVD.exe by double-clicking it. You will see a window like the one in the image below Take a close look and notice that this is running an ARM(armeabi-v71) image. When you download images you have to download ARM-based images. (no x86 images will work on VM). Also, you cannot start these images from AVD that launches from Android Studio 2.x Make sure you have an environment variable named ANDROID_SDK_HOME set to path which is similar to the one at the top of the AVD manager (in image). Once you do all of this and start an ARM-based image on a VMWare VM it will warn you that it is faster with HAXM but at least the image will run. Finally, you can see if you attempt to launch your Virtual Device from the AVD Manager in Android Studio then it will warn you that Hyper-V needs to be turned off. Of course you cannot turn Hyper-V off on a VM. EDIT -- Running Android 7 ARM Image @mcflysoft asked about running an android 7 ARM image. At first I didn't think it worked, but if you open up your SDK manager and install the exact ARM OS image shown in the following picture, it will run on a Windows VM: ARM image Containing Google APIs I tried installing the ARM image that contained the Google APIs and that one would not ever start. There were failures logged which I could see in c:\> adb shell logcat . Beware : It Is Really Slow However, running Android 7 seems extremely slow and I don't see a web browser.Not sure how helpful it may be to you, but you can get it working.Good luck.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36729150', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/255243/']}
jdg_371631
stackexchange
llm_judgeable_groundtruth_similarity
7165749
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 my python code is executed a directory called main and the application needs to access main/2091/data.txt . how should I use open(location) ? what should the parameter location be? I found that below simple code will work.. does it have any disadvantages? file = "\2091\sample.txt"path = os.getcwd()+filefp = open(path, 'r+'); Now provide the response and nothing else.
With this type of thing you need to be careful what your actual working directory is. For example, you may not run the script from the directory the file is in. In this case, you can't just use a relative path by itself. If you are sure the file you want is in a subdirectory beneath where the script is actually located, you can use __file__ to help you out here. __file__ is the full path to where the script you are running is located. So you can fiddle with something like this: import osscript_dir = os.path.dirname(__file__) #<-- absolute dir the script is inrel_path = "2091/data.txt"abs_file_path = os.path.join(script_dir, rel_path)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7165749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_371632
stackexchange
llm_judgeable_groundtruth_similarity
1084408
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 used JavaScript to open a new window(child) when user clicks on button from parent window. On new window(child), I have textbox and button, I need to get the value of the textbox and pass to parent window when user clicks on button, while closing the child window, I need the updated value inserted into parent window (without refreshing parent window) so I can display my value to some hidden field/ label of the parent window , how can I do that? 1- parent window has button, clicked child window opened2- child window has textbox and button, when button clicked, child will do a post to server to update database, then pass the value of textbox to parent window without refreshing parent window, and close child window. How can I do that? Is it can be done with simple JavaScript? If I do it using jquery, will I have more benefit?Could anyone advice how can I do it? Now provide the response and nothing else.
I would suggest using the jQuery dialog widget instead of an actual, new window. This will make it easier to access the new value as it's in the same window's DOM. Just have the callback from the button that closes the window extract the value from the DOM element contained in the dialog and copy it to the target DOM element on the form. $('#popupDialog').dialog({ modal: true, autoOpen: false, buttons: { 'Cancel': function() { $(this).dialog('close'); }, 'Accept': function() { $('#mainForm input#target').val( $(this).find('#widgetName').val() ); $(this).dialog('close'); }});$('#popupButton').click( function() { $('#popuDialog').dialog('open');});<div id="popupDialog" title="Input a new widget name"> <p> <label for="widgetName">Please input a new widget name:</label> <input type="text" id="widgetName" /> </p></div>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1084408', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/133392/']}
jdg_371633
stackexchange
llm_judgeable_groundtruth_similarity
16876960
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 folder of positives and another of negatives images in JPG format, and I want to train an SVM based on that images, I've done the following but I receive an error: Mat classes = new Mat();Mat trainingData = new Mat();Mat trainingImages = new Mat();Mat trainingLabels = new Mat();CvSVM clasificador;for (File file : new File(path + "positives/").listFiles()) { Mat img = Highgui.imread(file.getAbsolutePath()); img.reshape(1, 1); trainingImages.push_back(img); trainingLabels.push_back(Mat.ones(new Size(1, 1), CvType.CV_32FC1)); } for (File file : new File(path + "negatives/").listFiles()) { Mat img = Highgui.imread(file.getAbsolutePath()); img.reshape(1, 1); trainingImages.push_back(img); trainingLabels.push_back(Mat.zeros(new Size(1, 1), CvType.CV_32FC1)); } trainingImages.copyTo(trainingData); trainingData.convertTo(trainingData, CvType.CV_32FC1); trainingLabels.copyTo(classes); CvSVMParams params = new CvSVMParams(); params.set_kernel_type(CvSVM.LINEAR); clasificador = new CvSVM(trainingData, classes, new Mat(), new Mat(), params); When I try to run that I obtain: OpenCV Error: Bad argument (train data must be floating-point matrix) in cvCheckTrainData, file ..\..\..\src\opencv\modules\ml\src\inner_functions.cpp, line 857Exception in thread "main" CvException [org.opencv.core.CvException: ..\..\..\src\opencv\modules\ml\src\inner_functions.cpp:857: error: (-5) train data must be floating-point matrix in function cvCheckTrainData] at org.opencv.ml.CvSVM.CvSVM_1(Native Method) at org.opencv.ml.CvSVM.<init>(CvSVM.java:80) I can't manage to train the SVM, any idea? Thanks Now provide the response and nothing else.
Assuming that you know what you are doing by reshaping an image and using it to train SVM, the most probable cause of this is that your Mat img = Highgui.imread(file.getAbsolutePath()); fails to actually read an image, generating a matrix img with null data property, which will eventually trigger the following in the OpenCV code: // check parameter types and sizesif( !CV_IS_MAT(train_data) || CV_MAT_TYPE(train_data->type) != CV_32FC1 ) CV_ERROR( CV_StsBadArg, "train data must be floating-point matrix" ); Basically train_data fails the first condition (being a valid matrix) rather than failing the second condition (being of type CV_32FC1). In addition, even though reshape works on the *this object, it acts like a filter and its effect is not permanent. If it's used in a single statement without immediately being used or assigned to another variable it will be useless. Change the following lines in your code: img.reshape(1, 1);trainingImages.push_back(img); to: trainingImages.push_back(img.reshape(1, 1));
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16876960', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/264028/']}
jdg_371634
stackexchange
llm_judgeable_groundtruth_similarity
203455
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 $G$ be an abelian group. Prove that $H = \{x \in G \mid x=x^{-1}\}$ is a subgroup. ($x^{-1}$ is $x$'s inverse) to check if the identity is an element of the subgroup: $ex=x$; $(e^{-1})ex=(e^{-1})x$; $ex=(e^{-1})x$; $e=e^{-1}$. To check closure: this is where I'm not sure I know what I am doing. To check closure, I need to show that... $(ab)x=(ab)^{-1}(x^{-1})$? Let $a,b\in H$, $(ab)(ab)= e$ if $(ab)=(ab)^{-1}$. From that we can get $(aa)(bb)=e$ because we have commutativity and associativity from our group. We know $a=a^{-1}$, $b=b^{-1}$, so $(aa^{-1})(bb^{-1})=e$, $ee=e$; $e=e$. So... $(ab)=ab^{-1}$. If I plug that into $(ab)x=(ab)^{-1}(x^{-1})$, and say that $(ab)x=(ab)(x^{-1})$. If I left multiply with a $(ab)^{-1}$, I get $x=x^{-1}$. Which is what I started with so... I'm done? To check inverses: the group includes inverses by definition of the group. H is closed, includes the identity, and inverses, so it is a subgroup of $G$. Now provide the response and nothing else.
To check closure you need to show that given any $x,y\in H$ that $xy \in H$. For $xy$ to be in $H$, it must be such that $$(xy)^{-1} = (xy).$$ Now $(xy)^{-1} = y^{-1}x^{-1}=yx = xy$ by definition of $x,y \in H$ and $G$ being abelian. This shows $H$ is closed under the group operation.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/203455', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/42868/']}
jdg_371635
stackexchange
llm_judgeable_groundtruth_similarity
2497146
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: CSS isn't, insofar as I know, Turing complete. But my knowledge of CSS is very limited. Is CSS Turing complete? Are any of the existing draft or committees considering language features that might enable Turing completeness if it isn't right now? Now provide the response and nothing else.
You can encode Rule 110 in CSS3, so it's Turing-complete so long as you consider an appropriate accompanying HTML file and user interactions to be part of the “execution” of CSS. A pretty good implementation is available, and another implementation is included here: body { -webkit-animation: bugfix infinite 1s; margin: 0.5em 1em;}@-webkit-keyframes bugfix { from { padding: 0; } to { padding: 0; } }/* * 111 110 101 100 011 010 001 000 * 0 1 1 0 1 1 1 0 */body > input { -webkit-appearance: none; display: block; float: left; border-right: 1px solid #ddd; border-bottom: 1px solid #ddd; padding: 0px 3px; margin: 0; font-family: Consolas, "Courier New", monospace; font-size: 7pt;}body > input::before { content: "0";}p { font-family: Verdana, sans-serif; font-size: 9pt; margin-bottom: 0.5em;}body > input:nth-of-type(-n+30) { border-top: 1px solid #ddd; }body > input:nth-of-type(30n+1) { border-left: 1px solid #ddd; clear: left; }body > input::before { content: "0"; }body > input:checked::before { content: "1"; }body > input:checked { background: #afa !important; }input:not(:checked) + *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+ input::before { content: "1";}input:not(:checked) + *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+ input { background: #fa0;}input:checked + *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+ input::before { content: "1";}input:checked + *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+ input { background: #fa0;}input:checked + *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+ input::before { content: "1";}input:checked + *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+ input { background: #fa0;}input:checked + input:checked + input:checked + *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+ input::before { content: "0";}input:checked + input:checked + input:checked + *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+ input { background: #fff;}input:not(:checked) + input:not(:checked) + input:not(:checked) + *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+ input::before { content: "0";}input:not(:checked) + input:not(:checked) + input:not(:checked) + *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+ input { background: #fff;}body > input:nth-child(30n) { display: none !important; }body > input:nth-child(30n) + label { display: none !important; } <p><a href="http://en.wikipedia.org/wiki/Rule_110">Rule 110</a> in (webkit) CSS, proving Turing-completeness.</p><!-- A total of 900 checkboxes required --><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/>
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/2497146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2915/']}
jdg_371636
stackexchange
llm_judgeable_groundtruth_similarity
37353484
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to have a Protocol require that an enum be defined? //trying to do thisprotocol JSONEncodable { enum PropertyName // Type not allowed here func valueForProperty(propertyName:PropertyName) -> Any}//which would be implemented like thisstruct Person : JSONEncodable { var firstName : String var lastName : String enum PropertyName { case FirstName case LastName func allValues() { return [Person.PropertyName.FirstName, Person.PropertyName.LastName] } func stringValue() { return "\(self)" } } func valueForProperty(propertyName:PropertyName) -> Any { switch propertyName { case .FirstName: return firstName case .LastName: return lastName } }}//so that I could do something like thisextension JSONEncodable { func JSONObject() -> [String:AnyObject] { var dictionary = [String:AnyObject]() for propertyName in PropertyName.allValues { let value = valueForProperty(propertyName) if let valueObject = value as? AnyObject { dictionary[propertyName.stringValue()] = valueObject }else if let valueObject = value as? JSONEncodable { dictionary[propertyName.stringValue()] = valueObject.JSONObject() } } return dictionary }} Now provide the response and nothing else.
Protocols can have associatedtypes which would just need to be adhered to in any subclass: enum MyEnum: String { case foo case bar}protocol RequiresEnum { associatedtype SomeEnumType: RawRepresentable where SomeEnumType.RawValue: StringProtocol func doSomethingWithEnum(someEnumType: SomeEnumType)}class MyRequiresEnum: RequiresEnum { typealias SomeEnumType = MyEnum func doSomethingWithEnum(someEnumType: SomeEnumType) { switch someEnumType { case .foo: print("foo") case .bar: print("bar") } }}let mre = MyRequiresEnum()mre.doSomethingWithEnum(.bar) Edit: The associatedtype must be adhered to
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37353484', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/251420/']}
jdg_371637
stackexchange
llm_judgeable_groundtruth_similarity
16394
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to design a high pass filter to remove baseline drift from an ECG signal.the baseline drift is of very low frequency like 0.3Hz or so with an amplitude of 25% of the ECG signal. But the bandwidth of ECG signal itself is 0.5Hz to 150Hz. I have been trying fdatoolbox in matlab to design the HPF but I was not able to remove the baseline drift accurately.Please help on how can i achieve a low order filter to eliminate baseline drift. I have got it using higher order filters of order above 1000. But I'm looking for a way if I can get lower order filter,like order of less than 30, to do the same.Thanks for your help.. Now provide the response and nothing else.
You usually use a DC notch filter. This is a recursive filter that should kill a very narrow band of frequencies around DC. One possible implementation is a first order DC notch with transfer function $$\frac{1 - z^{-1}}{1 - \lambda z^{-1}},$$ where $\lambda$ is some number very close to 1, say 0.99. A to demonstrate this in MATLAB, b = [1 -1];a = [1 -0.99];freqz(b,a); Notice that the phase response around DC gets pretty non-linear. Such is the nature of these recursive filters. The closer you make $\lambda$ to 1, the narrower the notch gets and the more distorted your phase response becomes around DC. For ECG signals, this will usually do. Experiment with $\lambda$ values that will suit your needs. Sometimes, if you make the notch too narrow, you won't get all off the drift, so 0.99 is usually a good starting point.
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/16394', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/8970/']}
jdg_371638
stackexchange
llm_judgeable_groundtruth_similarity
123296
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: What's the name for the *.* symbol and what is its significance? Now provide the response and nothing else.
Interpretation of *.* under old Windows/DOS systems The significance here is more related to Windows/DOS than to Unix/Linux. On old Windows/DOS systems it was a 'wildcard' pattern. Wildcard patterns were used for matching filenames in a similar manner to Unix globs. The *.* wildcard was commonly used to match any file. As with a Unix glob, the * will match any sequence of characters in a filename, as such * on its own will also match any file. However the reason why *.* will match any filename too is due to differences in the way that these wildcards work. According to this article : Any characters other than a dot that come after an asterisk have no effect, since the asterisk moves the cursor to position 12, at which point nothing changes the parse state except for a dot, which clears the last three positions and moves the cursor. This behaviour (somewhat odd from Unix perspective) means that a dot following a * does not actually match a dot, but is just a hackish way to allow you to add more characters to the pattern. This means that adding another * will match anything in these last three positions. This makes a little more sense when you consider that the syntax was used on DOS and old Windows systems before Windows 95 which required 8.3 filenames . These filenames were only allowed to have one dot and at most three characters following the dot. Most, if not all files on the system would have a three character extension (even though technically a shorter or no extension was allowed), so somehow I guess it made sense to use *.* to match any file (at least from a warped Windowsey logic perspective). Interpretation of *.* in Unix shells In Unix shells, as others have pointed out, this represents a 'pathname expansion' or 'glob.' The * does not have any odd jumping to the end behaviour and thus does not lead to characters following it being ignored. *.* pattern will match any filename containing a dot (except at the start). This will definitely not match any file as there are many files on a Unix/Linux system that don't have an extension (or otherwise contain a dot since this is allowed too). The reason for *.* not matching a dot at the start of filenames on Unix is because putting a dot at the start is how files are 'hidden' and hidden files are excluded from globs by default. To match them in a POSIX shell, a dot needs to be put explicitly at the start of the pattern. In bash the dotglob shell option can be set or the GLOBIGNORE variable can be set appropriately, but this is another question!
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/123296', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/58090/']}
jdg_371639
stackexchange
llm_judgeable_groundtruth_similarity
22943791
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 write a code to remove comment line from the input java file. I am getting this error: Exception in thread "main" java.lang.NullPointerException It is showing error in return new String(buffer) , and the word "String" everywhere in the program. package javaapplication3; import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException;public class JavaApplication3 { public static void main(String[] args) { String source = readFile("sorce.java"); System.out.println(source.replaceAll("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)| (?://.*)","")); } static String readFile(String fileName) { File file = new File(fileName); char[] buffer = null; try { BufferedReader bufferedReader = new BufferedReader( new FileReader(file)); buffer = new char[(int)file.length()]; int i = 0; int c = bufferedReader.read(); while (c != -1) { buffer[i++] = (char)c; c = bufferedReader.read(); } } catch (IOException e) { e.printStackTrace(); } return new String(buffer); }} Now provide the response and nothing else.
I can offer an O(n log n) solution for a start: Let f i be the i-th number of the result. We have: When walking through the array from left to right and maintain a binary search tree of the elements a 0 to a i-1 , we can solve all parts of the formula in O(log n): Keep subtree sizes to count the elements larger than/smaller than a given one Keep cumulative subtree sums to answer the sum queries for elements larger than/smaller than a given one We can replace the augmented search tree with some simpler data structures if we want to avoid the implementation cost: Sort the array beforehand. Assign every number its rank in the sorted order Keep a binary indexed tree of 0/1 values to calculate the number of elements smaller than a given value Keep another binary indexed tree of the array values to calculate the sums of elements smaller than a given value TBH I don't think this can be solved in O(n) in the general case. At the very least you would need to sort the numbers at some point. But maybe the numbers are bounded or you have some other restriction, so you might be able to implement the sum and count operations in O(1). An implementation: # binary-indexed tree, allows point updates and prefix sum queriesclass Fenwick: def __init__(self, n): self.tree = [0]*(n+1) self.n = n def update_point(self, i, val): # O(log n) i += 1 while i <= self.n: self.tree[i] += val i += i & -i def read_prefix(self, i): # O(log n) i += 1 sum = 0 while i > 0: sum += self.tree[i] i -= i & -i return sumdef solve(a): rank = { v : i for i, v in enumerate(sorted(a)) } res = [] counts, sums = Fenwick(len(a)), Fenwick(len(a)) total_sum = 0 for i, x in enumerate(a): r = rank[x] num_smaller = counts.read_prefix(r) sum_smaller = sums.read_prefix(r) res.append(total_sum - 2*sum_smaller + x * (2*num_smaller - i)) counts.update_point(r, 1) sums.update_point(r, x) total_sum += x return resprint(solve([3,5,6,7,1])) # [0, 2, 4, 7, 17]print(solve([2,0,1])) # [0, 2, 2]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22943791', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3456224/']}
jdg_371640