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
13580075
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 new nested fragment API that Android includes in the support library. The problem that I am facing with nested fragments is that, if a nested fragment (that is, a fragment that has been added to another fragment via the FragmentManager returned by getChildFragmentManager() ) calls startActivityForResult() , the nested fragment's onActivityResult() method is not called. However, both the parent fragment's onActivityResult() and activity's onActivityResult() do get called. I don't know if I am missing something about nested fragments, but I did not expect the described behavior. Below is the code that reproduces this problem. I would very much appreciate if someone can point me in the right direction and explain to me what I am doing wrong: package com.example.nestedfragmentactivityresult;import android.media.RingtoneManager;import android.os.Bundle;import android.content.Intent;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentActivity;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.Toast;public class MainActivity extends FragmentActivity{ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.getSupportFragmentManager() .beginTransaction() .add(android.R.id.content, new ContainerFragment()) .commit(); } public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // This is called Toast.makeText(getApplication(), "Consumed by activity", Toast.LENGTH_SHORT).show(); } public static class ContainerFragment extends Fragment { public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View result = inflater.inflate(R.layout.test_nested_fragment_container, container, false); return result; } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getChildFragmentManager().beginTransaction() .add(R.id.content, new NestedFragment()) .commit(); } public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // This is called Toast.makeText(getActivity(), "Consumed by parent fragment", Toast.LENGTH_SHORT).show(); } } public static class NestedFragment extends Fragment { public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Button button = new Button(getActivity()); button.setText("Click me!"); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER); startActivityForResult(intent, 0); } }); return button; } public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // This is NOT called Toast.makeText(getActivity(), "Consumed by nested fragment", Toast.LENGTH_SHORT).show(); } }} test_nested_fragment_container.xml is: <?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/content" android:layout_width="match_parent" android:layout_height="match_parent" ></FrameLayout> Now provide the response and nothing else.
Yes, the onActivityResult() in nested fragment will not be invoked by this way. The calling sequence of onActivityResult (in Android support library) is Activity.dispatchActivityResult() . FragmentActivity.onActivityResult() . Fragment.onActivityResult() . In the 3rd step, the fragment is found in the FragmentMananger of parent Activity . So in your example, it is the container fragment that is found to dispatch onActivityResult() , nested fragment could never receive the event. I think you have to implement your own dispatch in ContainerFragment.onActivityResult() , find the nested fragment and invoke pass the result and data to it.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13580075', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1847017/']}
jdg_75141
stackexchange
llm_judgeable_groundtruth_similarity
52039
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I'm wondering about the question "If we have a finitely presented __, is it necessarily finitely presented with respect to any finite generating set for it?" I know this is true for groups and for $R$ -modules . Does anyone know whether this is true for $A$ -algebras? Commutative $A$ -algebras? Other things people might happen to know about it for? Now provide the response and nothing else.
It is true for any algebras (sets with operations) satisfying any set of identities (laws). Indeed, if $X, Y$ are finite generating sets $R=\{u_i,v_i\mid i\in I\}$ be a finite set of defining relations over $X$, $Q$ is any set of defining relations over $Y$, then for every relation from $R$ there exists a proof of that relation using relations from $Q$. The proof involves a finite number of elements of $Q$. If $Q'$ is the (finite) collection of all elements of $Q$ involved, then the algebra has a finite presentation $\langle Y, Q'\rangle$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/52039', 'https://mathoverflow.net', 'https://mathoverflow.net/users/5583/']}
jdg_75142
stackexchange
llm_judgeable_groundtruth_similarity
47697761
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Problem On MacOS, I get linking problems at runtime for a CMake project that depends on dynamically linked resources – but only after installing the project! The problem does not occur when I only build the binary without installing it. $ ./testappHello world!$ $INSTALLDIR/testappdyld: Library not loaded: @rpath/libvtkDomainsChemistryOpenGL2-7.1.1.dylib Referenced from: /Users/normanius/workspace/installdir/testapp Reason: image not found[1] 76964 trace trap /Users/normanius/workspace/installdir/testapp Minimum example I am able to reproduce the problem in a minimal setup consisting of CMakeLists.txt and main.cpp . The library I am linking to is called VTK (v7.1.1) which has been built with shared libs (see below for further details). # CMakeLists.txtcmake_minimum_required(VERSION 2.8 FATAL_ERROR)project(test)# Test application.add_executable(testapp main.cpp)# Find vtk (library that has to be linked to dynamically).find_package(VTK REQUIRED)include(${VTK_USE_FILE})target_link_libraries(testapp ${VTK_LIBRARIES}) # <---- this causes the problem# Install instructions.install(TARGETS testapp DESTINATION "${CMAKE_INSTALL_PREFIX}") The main.cpp not even makes use of any VTK objects. // main.cpp#include <iostream>int main (int argc, char* argv[]){ std::cout << "Hello world!" << std::endl; return 0;} I build the project with the following commands. The flag CMAKE_PREFIX_PATH I set to give CMake a hint about where to find the VTK library. $ INSTALLDIR="path/to/installation"$ mkdir build && cd build$ cmake .. -DCMAKE_PREFIX_PATH="$DEVPATH/lib/vtk/cmake" \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX="$INSTALLDIR" $ make$ make install When executing the testapp in the build folder, everything looks fine: $ ./testappHello world!$ cp testapp $INSTALLDIR/testapp$ $INSTALLDIR/testappHello world! However, if I run the executable in the INSTALLDIR I get a run-time error: $ $INSTALLDIR/testappdyld: Library not loaded: @rpath/libvtkDomainsChemistryOpenGL2-7.1.1.dylib Referenced from: /Users/normanius/workspace/installdir/testapp Reason: image not found[1] 76964 trace trap /Users/normanius/workspace/installdir/testapp Naturally, the problem goes away if I remove the target_link_libraries() instruction in the CMakeLists.txt . So what exactly happens when installing a CMake project? And what goes wrong in my case? I tested different CMake versions (3.5, 3.9 and 3.10) - but the behaviour is the same. Details Apparently, the RPATH mechanism on MacOS is not properly set up for the example. This is an excerpt of the linking structure of the testapp binary: $ otool -L testapptestapp: @rpath/libvtkDomainsChemistryOpenGL2-7.1.1.dylib (compatibility version 0.0.0, current version 0.0.0) @rpath/libvtkFiltersFlowPaths-7.1.1.dylib (compatibility version 0.0.0, current version 0.0.0) @rpath/libvtkFiltersGeneric-7.1.1.dylib (compatibility version 0.0.0, current version 0.0.0) @rpath/libvtkFiltersHyperTree-7.1.1.dylib (compatibility version 0.0.0, current version 0.0.0)... Because it may play a role how the VTK library (another CMake project) was built: For python support, one has to set the project flags VTK_WRAP_PYTHON=ON and BUILD_SHARED_LIBS=ON . The installation prefix was set to CMAKE_INSTALL_PREFIX="$VTK_INSTALL_DIR" . To make sure that the resources are found at runtime, one has to additionally enable RPATH support via CMAKE_MACOSX_RPATH=ON and CMAKE_INSTALL_RPATH="$VTK_INSTALL_DIR/lib" . Wrap-up What do I conceptually get wrong? What happens when installing the project with make install ? Can this problem be solved within CMake? Or is it related only to VTK and how the shared libs were built? Now provide the response and nothing else.
CMake changes the RPATH for all installed targets upon running make install . Imagine building both a shared library and an executable as part of the same CMake project. In order to be able to run the executable, it has to be able to dynamically load the shared library at runtime. Therefore, CMake by default adds the full (absolute) path to the dynamic library in the build tree to the executable's rpath. This is very convenient for developing, as we can run the executable straight from the build tree, but we probably would not want to ship the executable that way. That's why CMake will change the rpath upon install to only contain portable paths (ie. remove the entry pointing to the build tree). That is, unless you put your shared library into one of the system default locations, the executable won't find it anymore after installing. CMake does allow you though to specify an install rpath that will replace the removed build tree entry with your specified one. See the INSTALL_RPATH and INSTALL_RPATH_USE_LINK_PATH target properties for details. Since all of this rpath stuff is 100% platform-dependent, OSX comes with its own, special rules. A pretty comprehensive explanation can be found on the (unfortunately rather outdated) CMake wiki : Unlike other UNIXes, the Darwin linker, dyld, locates dependentdynamic libraries using the full path to each dylib. For example, inan executable "foo", the full paths recorded are the install names foreach dependent dylib. And the library "/usr/lib/libSystem.dylib" hasan install name of "/usr/lib/libSystem.B.dylib" as given by "otool-D". When linked into "foo", "foo" has a dependency on "/usr/lib/libSystem.B.dylib". This dependency can be seen with "otool-L foo". For relocatable binaries, @executable_path, @loader_path and @rpath are available to use. In the "foo" example, @executable_pathand @loader_path are substituted for the location of "foo". @rpath issubstituted with the RPATHs in "foo" to locate dependent dylibs. Thusthe RPATH mechanism comes into play. The linker will search for@rpath/ dependencies in the following order: DYLD_LIBRARY_PATH - anenvironment variable which holds a list of directories RPATH - a listof directories which is linked into the executable. These can contain@loader_path and @executable_path. builtin directories - /lib /usr/lib DYLD_FALLBACK_LIBRARY_PATH - an environment variable which holds alist of directories You should be able to solve this by tuning the respective target properties, but it is rather fiddly and can be quite a pain to get right.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47697761', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3388962/']}
jdg_75143
stackexchange
llm_judgeable_groundtruth_similarity
15653924
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: guys. I have the following script <?php$result = mysql_query("SELECT * FROM players") or die(mysql_error());echo "<table class=\"table table-bordered table-hover\" border='1' cellpadding='10'>";echo "<tr> <th>ID</th> <th>Place</th> <th>Name</th> <th>Points</th> <th></th> <th></th></tr>";// loop through results of database query, displaying them in the tablewhile($row = mysql_fetch_array( $result )) { // echo out the contents of each row into a table echo "<tr>"; echo '<td>' . $row['id'] . '</td>'; echo '<td>' . $row['place'] . '</td>'; echo '<td>' . $row['name'] . '</td>'; echo '<td>' . $row['points'] . '</td>'; echo '<td><a href="wtawomenedit.php?id=' . $row['id'] . '">Edit</a></td>'; echo '<td><a href="deleter.php?id=' . $row['id'] . '">Delete</a></td>'; echo "</tr>"; } // close table>echo "</table>";?> This script is showing all the content from the MySQL table, but the rows are mixed, and as I'm using it for a rang list, I would like to show the rows, filtered by points. The row with the higher point to be first and so on. Thank you in advance, I've not done something. like that before, so I've got no idea, how to make it work. Now provide the response and nothing else.
You should not use Directory.GetCurrentDirectory() in your case, as the current directory may differ from the execution folder, especially when you execute the program through a shortcut. It's better to use Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); for your purpose. This returns the pathname where the currently executing assembly resides. While my suggested approach allows you to differentiate between the executing assembly, the entry assembly or any other loaded assembly, as Soner Gönül said in his answer, System.IO.Path.GetDirectoryName(Application.ExecutablePath); may also be sufficient. This would be equal to System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/15653924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2211030/']}
jdg_75144
stackexchange
llm_judgeable_groundtruth_similarity
4976636
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I always wondered what's the purpose of the rotate instructions some CPUs have (ROL, RCL on x86, for example). What kind of software makes use of these instructions? I first thought they may be used for encryption/computing hash codes, but these libraries are written usually in C, which doesn't have operators that map to these instructions. (Editor's note: see Best practices for circular shift (rotate) operations in C++ for how to write C or C++ that will compile to a rotate instruction. Also, optimized crypto libraries often do have asm for specific platforms.) Has anybody found an use for them? Why where they added to the instructions set? Now provide the response and nothing else.
Rotates are required for bit shifts across multiple words. When you SHL the lower word, the high-order bit spills out into the carry. To complete the operation, you need to shift the higher word(s) while bringing in the carry to the low-order bit. RCL is the instruction that accomplishes this. High word Low word CFInitial 0110 1001 1011 1001 1100 0010 0000 1101 ?SHL low word 0110 1001 1011 1001 1000 0100 0001 1010 1RCL high word 1101 0011 0111 0011 1000 0100 0001 1010 0 ROL and ROR are useful for examining a value bit-by-bit in a way that is (ultimately) non-destructive. They can also be used to shunt a bitmask around without bringing in garbage bits.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4976636', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/121557/']}
jdg_75145
stackexchange
llm_judgeable_groundtruth_similarity
7051062
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What's the best way to include a LIKE clause in a Rails query i.e. something along the lines of (the completely incorrect): Question.where(:content => 'LIKE %farming%') Now provide the response and nothing else.
If this is Rails 3 you can use Arel's matches . This has the advantage of being database agnostic. For example: Question.where(Question.arel_table[:content].matches("%#{string}%")) This is somewhat clunky, but easily extracted to scopes, e.g.: class Question def self.match_scope_condition(col, query) arel_table[col].matches("%#{query}%") end scope :matching, lambda {|*args| col, opts = args.shift, args.extract_options! op = opts[:operator] || :or where args.flatten.map {|query| match_scope_condition(col, query) }.inject(&op) } scope :matching_content, lambda {|*query| matching(:content, *query) }endQuestion.matching_content('farming', 'dancing') # farming or dancingQuestion.matching_content('farming', 'dancing', :operator => :and) # farming and dancingQuestion.matching(:other_column, 'farming', 'dancing') # same thing for a different col Of course to join with "AND" you could just chain the scopes. Edit: +1 to metawhere and squeel though (haven't tried latter but it looks cool) They both add this type of functionality and much more.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7051062', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/400790/']}
jdg_75146
stackexchange
llm_judgeable_groundtruth_similarity
1968594
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $[k] = \{0,\dots,k-1\}$. Consider the set $F(n,m)$ of functions $f:[n]\times[m]\rightarrow[m]$. The cardinality of $F(n,m)$ is $|F(n,m)| = m^{nm}$. Consider the equivalence relation $f \simeq g$ between functions $f,g \in F(n,m)$ iff there are permutations $\pi:[n]\rightarrow [n]$ and $\tau:[m]\rightarrow [m]$ such that $\tau(f(n,m)) = g(\pi(n),\tau(m))$ (see Harary/Palmer: Enumeration of Finite Automata ). Harary/Palmer give an explicit formula to count the number $a(n,m)$ of orbits (equivalence classes) of $\simeq$. And they show that $a(2,2) = 7$ (compared to $|F(2,2)|=2^4=16$). But I find it hard to get a number for $a(4,4)$ to be compared to $|F(4,4)| = 4^{16} \sim 4\cdot10^9 $, even given Harary/Palmer's formulas. Is there a easy way to get this number? Now provide the response and nothing else.
[Add-on 2016-10-30]: Case n=4 added. We calculate the number $a(n,n)$ of equivalent functions $$f:[n]\times[n]\rightarrow[n]$$ for $n=2,3$ and $n=4$ according to the paper of F. Harary and E. Palmer and show \begin{align*}a(2,2)&=7\\a(3,3)&=638\\a(4,4)&=7643021\end{align*} The formula to be applied is stated as formula (14) in the paper. In fact we can use a simplified version of it, which is given in connection with the calculation of $a(2,2,1)=7$ at the end of page 505. The third parameter is not of interest for us and so we instead write $a(2,2)$. Here I follow the notation of the authors and use $[p,q]:=\operatorname{lcm}(p,q)$ and $\langle p,q\rangle:=\operatorname{gcd}(p,q)$. [Harary, Palmer]: The following is valid \begin{align*}a(n,n)=\frac{1}{\left(n!\right)^2}\sum_{(\alpha,\beta)\in S_n^2}\prod_{p=1}^n\prod_{q=1}^n\left(\sum_{s|[p,q]}sj_s(\alpha)\right)^{j_p(\alpha)j_q(\beta)\langle p,q\rangle}\tag{1}\end{align*} where the sum is taken over all pairs of permutations $(\alpha,\beta)$ of degree $n$ and $j_p(\alpha)$ is denoting the number of cycles of $\alpha$ of length $p$. Hint: Observe the terms in the sum (1) do not make use of $\alpha$ but instead of $j_p(\alpha)$ only. So, it is not necessary to sum over all $\left(n!\right)^2$ pairs of permutations, as we can conveniently use the cycle index of the permutation group $S_n$ and considerably reduce the number of summands. Preparatory work: Cycle index We calculate for $n=2,3,4$ the cycle index based upon the recursion formula \begin{align*}Z(S_0)&=1\\Z(S_n)&=\frac{1}{n}\sum_{j=1}^nz_jZ(S_{n-j})\qquad\qquad n>0\end{align*} We obtain \begin{align*}Z(S_1)&=z_1Z(S_0)=z_1\\Z(S_2)&=\frac{1}{2}\left(z_1Z(S_1)+z_2\right)\\&=\frac{1}{2}\left(z_1^2+z_2\right)\\Z(S_3)&=\frac{1}{3}\left(z_1\cdot\frac{1}{2}\left(z_1^2+z_2\right)+z_2z_1+z_3\right)\\&=\frac{1}{6}\left(z_1^3+3z_1z_2+2z_3\right)\\Z(S_4)&=\frac{1}{4}\left(z_1\cdot\frac{1}{6}\left(z_1^3+3z_1z+2z_3\right)+z_2\cdot\frac{1}{2}\left(z_1^2+z_2\right)+z_3z_1+z_4\right)\\&=\frac{1}{24}\left(z_1^4+6z_1^2z_2+8z_1z_3+3z_2^2+6z_4\right)\end{align*} $$ $$ Case: $n=2$: We show the following is valid \begin{align*}\color{blue}{a(2,2)=7}\end{align*} In order to calculate $a(2,2)$ we consider according to (1) \begin{align*}a(2,2)=\frac{1}{4}\sum_{(\alpha,\beta)\in S_2^2}\prod_{p=1}^2\prod_{q=1}^2\left(\sum_{s|[p,q]}sj_s(\alpha)\right)^{j_p(\alpha)j_q(\beta)\langle p,q\rangle}\tag{2}\end{align*} It it convenient to do some bookkeeping by use of tables. We list the permutations of $S_2=\{\operatorname{id},(12)\}$ in cycle notation and write a table with the number of cycles of each length for each permutation. We also write the corresponding monomial from the cycle index.\begin{array}{l|ccc}\pi&Z(S_2)&j_1(\pi)&j_2(\pi)\\\hline\operatorname{id}& z_1^2& 2& 0\\(12)& z_2^1& 0 &1\\\end{array} Since it is too cumbersome to write each summand from (2) in one long line we use instead a table description as follows: \begin{array}{cc|cccc|cc|cc|rr}\alpha&\beta&p&q&[p,q]&<p,q>&s&j_s(\alpha)&j_p(\alpha)&j_q(\beta)&\text{factors}&\text{result}\\\hlineid&id&1&1&1&1&1&2&2&2&16&16\\&&1&2&2&1&1&2&2&0&1&\\&&&&&&2&0&&&&\\&&2&1&2&1&1&2&0&0&1&\\&&&&&&2&0&&&&\\&&2&2&2&2&1&2&0&2&1&\\&&&&&&2&0&&&&\\\hlineid&(12)&1&1&1&1&1&2&2&0&1&4\\&&1&2&2&1&1&2&2&1&4&\\&&&&&&2&0&&&&\\&&2&1&2&1&1&2&0&0&1&\\&&&&&&2&0&&&&\\&&2&2&2&2&1&2&0&1&1&\\&&&&&&2&0&&&&\\\hline(12)&id&1&1&1&1&1&0&0&2&1&4\\&&1&2&2&1&1&0&0&0&1&\\&&&&&&2&1&0&0&&\\&&2&1&2&1&1&0&1&2&4&\\&&&&&&2&1&1&2&&\\&&2&2&2&2&1&0&1&0&1&\\&&&&&&2&1&1&0&&\\\hline(12)&(12)&1&1&1&1&1&0&0&0&1&4\\&&1&2&2&1&1&0&0&1&1&\\&&&&&&2&1&0&1&&\\&&2&1&2&1&1&0&1&0&1&\\&&&&&&2&1&1&0&&\\&&2&2&2&2&1&0&1&1&4&\\&&&&&&2&1&1&1&&\\\hline&\color{blue}{\text{Total}}&&&&&&&&&&\color{blue}{28}\end{array} Comment: The table is organised in blocks for pairs of permutation. Although here not eye-catching since we list all $\left(2!\right)^2=4$ pairs, we need in fact only for each cycle type one representative, since we are only interested in the length of cycles of a permutation. The column result gives the summands in (2). Here are the gory details: Columns: $\alpha,\beta$ correspond to a pair of permutations $(\alpha,\beta)$ which is used as index in the outer sum of (2). Columns: $p,q$ are the indices of the products in (2) Column: $s$ gives the divisors of $\operatorname{lcm}(p,q)$ Columns: $j_s(\alpha),j_p(\alpha),j_q(\beta)$ list the cycle lengths Column: $\text{factor}$ gives $$\left(\sum_{s|[p,q]}sj_s(\alpha)\right)^{j_p(\alpha)j_q(\beta)\langle p,q\rangle}$$ Column: $\text{result}$ calculates finally the product $$\prod_{p=1}^2\prod_{q=1}^2\left(\sum_{s|[p,q]}sj_s(\alpha)\right)^{j_p(\alpha)j_q(\beta)\langle p,q\rangle}$$ Since the total of the table is $28$ we finally conclude according to (2) \begin{align*}\color{blue}{a(2,2)=\frac{1}{4}\cdot 28=7}\end{align*} and the claim follows. $$ $$ Case: $n=3$: We do the calculation similar to above and show the following is valid \begin{align*}\color{blue}{a(3,3)=638}\end{align*} In order to calculate $a(3,3)$ we consider according to (1) \begin{align*}a(3,3)=\frac{1}{\left(3!\right)^2}\sum_{(\alpha,\beta)\in S_3^2}\prod_{p=1}^3\prod_{q=1}^3\left(\sum_{s|[p,q]}sj_s(\alpha)\right)^{j_p(\alpha)j_q(\beta)\langle p,q\rangle}\tag{3}\end{align*} We list the permutations of $S_3=\{\operatorname{id},(12),(13),(23),(123),(132)\}$ in cycle notation and write a table with the number of cycles of each length for each permutation. We also write the corresponding monomial from the cycle index. \begin{array}{l|cccc}\pi&Z(S_3)&j_1(\pi)&j_2(\pi)&j_3(\pi)\\\hlineid&z_1^3&3&0&0\\(12)&3z_1z_2&1&1&0\\(123)&2z_3&0&0&1\\\end{array} Note: The factors $1,3$ and $2$ in the column $Z(S_3)$ indicate the number of different permutations of the corresponding cycle type. We will use this fact to considerably reduce the calculation of the number of summands in (3). In the following it is sufficient to calculate tables for the nine pairs\begin{align*}\{id,(12),(123)\}\times\{id,(12),(123)\}\end{align*}the cycle index provides the supplementary information we need to calculate the complete sum. Note that in the main table above there is some redundancy to ease traceability. We now use a somewhat more compact notation to ease readability and keep the space small. Table: $j_s(\pi), j_p(\pi),j_q(\pi)$ \begin{array}{cc|cc|ccc|ccc|ccc}&&&&&\pi=id&&&\pi=(12)&&&\pi=(123)&\\p&q&[p,q]&s&j_s&j_p&j_q&j_s&j_p&j_q&j_s&j_p&j_q\\\hline1&1&1&1&3&3&3&1&1&1&0&0&0\\&2&2&1&3&3&0&1&1&1&0&0&0\\&&&2&0&&&1&&&0&&\\&3&3&1&3&3&0&1&1&0&0&0&1\\&&&3&0&&&0&&&1&&\\2&1&2&1&3&0&3&1&1&1&0&0&0\\&&&2&0&&&1&&&0&&\\&2&2&1&3&0&0&1&1&1&0&0&0\\&&&2&0&&&1&&&0&&\\&3&6&1&3&0&0&1&1&0&0&0&1\\&&&2&0&&&1&&&0&&\\&&&3&0&&&0&&&1&&\\3&1&3&1&3&0&3&1&0&1&0&1&0\\&&&3&0&&&0&&&1&&\\&2&6&1&3&0&0&1&0&1&0&1&0\\&&&2&0&&&1&&&0&&\\&&&3&0&&&0&&&1&&\\&3&3&1&3&0&0&1&0&0&0&1&1\\&&&3&0&&&0&&&1&&\\\end{array} The table above provides all information necessary to calculate the summands in (3) for each of the nine pairs of permutations. An example of a typical block is given here for $((12),(12))$ as it was done for all four blocks in the case $n=2$ and a summary table follows below. Table: $\{(12)\}\times\{(12)\}$ \begin{array}{cc|cccc|cc|cc|rr}\alpha&\beta&p&q&[p,q]&<p,q>&s&j_s(\alpha)&j_p(\alpha)&j_q(\beta)&\text{factors}&\text{result}\\\hline(12)&(12)&1&1&1&1&1&1&1&1&1&81\\&&&2&2&1&1&1&1&1&3&\\&&&&&&2&1&&&&\\&&&3&3&1&1&1&1&0&1&\\&&&&&&3&0&&&&\\&&2&1&2&1&1&1&1&1&3&\\&&&&&&2&1&&&&\\&&&2&2&2&1&1&1&1&9&\\&&&&&&2&1&&&&\\&&&3&6&1&1&1&1&0&1&\\&&&&&&2&1&&&&\\&&&&&&3&0&&&&\\&&3&1&3&1&1&1&0&1&1&\\&&&&&&3&0&&&&\\&&&2&6&1&1&1&0&1&1&\\&&&&&&2&1&&&&\\&&&&&&3&0&&&&\\&&&3&3&3&1&1&0&0&1&\\&&&&&&3&0&&&&\\\end{array} $$ $$ Summary: In order to respect all summands of (3) we write the results of the tables above together with the multiplicity of each permutation according to its cycle type. So, e.g. the permutation $(12)$ has cycle type $z_1z_2$ and there are three permutations of this type $\{(12),(13),(23)\}$, we take a factor $3$. \begin{array}{ll|r|cc|r}\alpha&\beta&\text{res}&\text{m}_{\alpha}&\text{m}_{\beta}&\text{res}\cdot \text{m}_{\alpha}\cdot \text{m}_{\beta}\\\hlineid&id&19683&1&1&19683\\id&(12)&729&1&3&2187\\id&(123)&27&1&2&54\\\hline(12)&id&27&3&1&81\\(12)&(12)&81&3&3&729\\(12)&(123)&3&3&2&18\\\hline(123)&id&27&2&1&54\\(123)&(12)&9&2&3&54\\(123)&(123)&27&2&2&108\\\hline\color{blue}{\text{Total}}&&&&&\color{blue}{22968}\\\end{array} Since the total of the table is $22968$ we finally conclude according to (3) \begin{align*}\color{blue}{a(3,3)=\frac{1}{36}\cdot 22968=638}\end{align*} and the claim follows. $$ $$ Case: $n=4$: We do the calculation similar to above and show the following is valid \begin{align*}\color{blue}{a(4,4)=7643021}\end{align*} In order to calculate $a(4,4)$ we consider according to (1) \begin{align*}a(4,4)=\frac{1}{\left(4!\right)^2}\sum_{(\alpha,\beta)\in S_4^2}\prod_{p=1}^4\prod_{q=1}^4\left(\sum_{s|[p,q]}sj_s(\alpha)\right)^{j_p(\alpha)j_q(\beta)\langle p,q\rangle}\tag{4}\end{align*} We list the permutations of $S_4$ in cycle notation and write a table with the number of cycles of each length for each permutation. We also write the corresponding monomial from the cycle index. \begin{array}{l|ccccc}\pi&Z(S_4)&j_1(\pi)&j_2(\pi)&j_3(\pi)&j_3(\pi)\\\hlineid&z_1^4&4&0&0&0\\(12)&6z_1^2z_2&1&1&0&0\\(123)&8z_1z_3&0&0&1&0\\(12)(34)&3z_2^2&0&2&0&0\\(1234)&6z_4&0&0&0&1\\\end{array} Note: The factors $1,6,8,3$ and $6$ in the column $Z(S_4)$ indicate the number of different permutations of the corresponding cycle type. We will use this fact to considerably reduce the calculation of the number of summands in (4). In the following it is sufficient to calculate tables for the $25$ pairs\begin{align*}\{id,(12),(123),(12)(34),(1234)\}\times\{id,(12),(123),(12)(34),(1234)\}\end{align*}the cycle index provides the supplementary information we need to calculate the complete sum. Note that in the main table of $n=2$ above there is some redundancy to ease traceability. We now use analogously to $n=3$ above a somewhat more compact notation to ease readability and keep the space small. Table: $j_s(\pi), j_p(\pi),j_q(\pi)$ \begin{array}{cc|cc|ccc|ccc|ccc}&&&&&\pi=id&&&\pi=(12)&&&\pi=(123)&\\p&q&[p,q]&s&j_s&j_p&j_q&j_s&j_p&j_q&j_s&j_p&j_q\\\hline1&1&1&1&4&4&4&2&2&2&1&1&1\\1&2&2&1&4&4&0&2&2&1&1&1&0\\&&&2&0&&&1&&&0&&\\1&3&3&1&4&4&0&2&2&0&1&1&1\\&&&3&0&&&0&&&1&&\\1&4&4&1&4&4&0&2&2&0&1&1&0\\&&&2&0&&&1&&&0&&\\&&&4&0&&&0&&&0&&\\2&1&2&1&4&0&4&2&1&2&1&0&1\\&&&2&0&&&1&&&0&&\\2&2&2&1&4&0&0&2&1&1&1&0&0\\&&&2&0&&&1&&&0&&\\2&3&6&1&4&0&0&2&1&0&1&0&1\\&&&2&0&&&1&&&0&&\\&&&3&0&&&0&&&1&&\\2&4&4&1&4&0&0&2&1&0&1&0&0\\&&&2&0&&&1&&&0&&\\&&&4&0&&&0&&&0&&\\3&1&3&1&4&0&4&2&0&2&1&1&1\\&&&3&0&&&0&&&1&&\\3&2&6&1&4&0&0&2&0&1&1&1&0\\&&&2&0&&&1&&&0&&\\&&&3&0&&&0&&&1&&\\3&3&3&1&4&0&0&2&0&0&1&1&1\\&&&3&0&&&0&&&1&&\\3&4&12&1&4&0&0&2&0&0&1&1&0\\&&&2&0&&&1&&&0&&\\&&&3&0&&&0&&&1&&\\&&&4&0&&&0&&&0&&\\4&1&4&1&4&0&4&2&0&2&1&0&1\\&&&2&0&&&1&&&0&&\\&&&4&0&&&0&&&0&&\\4&2&4&1&4&0&0&2&0&1&1&0&0\\&&&2&0&&&1&&&0&&\\&&&4&0&&&0&&&0&&\\4&3&12&1&4&0&0&2&0&0&1&0&1\\&&&2&0&&&1&&&0&&\\&&&3&0&&&0&&&1&&\\&&&4&0&&&0&&&0&&\\4&4&4&1&4&0&0&2&0&0&1&0&0\\&&&2&0&&&1&&&0&&\\&&&4&0&&&0&&&0&&\\&&&&&&&&&&&&\\&&&&&&&&&&&&\\\end{array} $$ $$ Table (cont.): $j_s(\pi), j_p(\pi),j_q(\pi)$ \begin{array}{cc|cc|ccc|cccccc}&&&&&\pi=(12)(34)&&&\pi=(1234)&\\p&q&[p,q]&s&j_s&j_p&j_q&j_s&j_p&j_q\\\hline1&1&1&1&0&0&0&0&0&0&&&\\1&2&2&1&0&0&2&0&0&0&&&\\&&&2&2&&&0&&&&&\\1&3&3&1&0&0&0&0&0&0&&&\\&&&3&0&&&0&&&&&\\1&4&4&1&0&0&0&0&0&1&&&\\&&&2&2&&&0&&&&&\\&&&4&0&&&1&&&&&\\2&1&2&1&0&2&0&0&0&0&&&\\&&&2&2&&&0&&&&&\\2&2&2&1&0&2&2&0&0&0&&&\\&&&2&2&&&0&&&&&\\2&3&6&1&0&2&0&0&0&0&&&\\&&&2&2&&&0&&&&&\\&&&3&0&&&0&&&&&\\2&4&4&1&0&2&0&0&0&1&&&\\&&&2&2&&&0&&&&&\\&&&4&0&&&1&&&&&\\3&1&3&1&0&0&0&0&0&0&&&\\&&&3&0&&&0&&&&&\\3&2&6&1&0&0&2&0&0&0&&&\\&&&2&2&&&0&&&&&\\&&&3&0&&&0&&&&&\\3&3&3&1&0&0&0&0&0&0&&&\\&&&3&0&&&0&&&&&\\3&4&12&1&0&0&0&0&0&1&&&\\&&&2&2&&&0&&&&&\\&&&3&0&&&0&&&&&\\&&&4&0&&&1&&&&&\\4&1&4&1&0&0&0&0&1&0&&&\\&&&2&2&&&0&&&&&\\&&&4&0&&&1&&&&&\\4&2&4&1&0&0&2&0&1&0&&&\\&&&2&2&&&0&&&&&\\&&&4&0&&&1&&&&&\\4&3&12&1&0&0&0&0&1&0&&&\\&&&2&2&&&0&&&&&\\&&&3&0&&&0&&&&&\\&&&4&0&&&1&&&&&\\4&4&4&1&0&0&0&0&1&1&&&\\&&&2&2&&&0&&&&&\\&&&4&0&&&1&&&&&\\\end{array} The table above provides all information necessary to calculate the summands in (4) for each of the $25$ pairs of permutations. Hint: Observe, that we only need to consider $25$ pairs of permutations instead of $\left(4!\right)^2=576$ pairs which are summed up in (4). We will consider all other permutations by respecting multiplicities given by the cycle-index $Z(S_4)$. An example of a typical block is given here for $((123),(123))$ as it was done for all four blocks in the case $n=2$ and a summary table follows below. Table: $\{(123)\}\times\{(123)\}$ \begin{array}{cc|cccc|cc|cc|rr}\alpha&\beta&p&q&[p,q]&<p,q>&s&j_s(\alpha)&j_p(\alpha)&j_q(\beta)&\text{factors}&\text{result}\\\hline(123)&(123)&1&1&1&1&1&1&1&1&1&1024\\&&1&2&2&1&1&1&1&0&1&\\&&&&&&2&0&&&&\\&&1&3&3&1&1&1&1&1&4&\\&&&&&&3&1&&&&\\&&1&4&4&1&1&1&1&0&1&\\&&&&&&2&0&&&&\\&&&&&&4&0&&&&\\&&2&1&2&1&1&1&0&1&1&\\&&&&&&2&0&&&&\\&&2&2&2&2&1&1&0&0&1&\\&&&&&&2&0&&&&\\&&2&3&6&1&1&1&0&1&1&\\&&&&&&2&0&&&&\\&&&&&&3&1&&&&\\&&2&4&4&2&1&1&0&0&1&\\&&&&&&2&0&&&&\\&&&&&&4&0&&&&\\&&3&1&3&1&1&1&1&1&4&\\&&&&&&3&1&&&&\\&&3&2&6&1&1&1&1&0&1&\\&&&&&&2&0&&&&\\&&&&&&3&1&&&&\\&&3&3&3&3&1&1&1&1&64&\\&&&&&&3&1&&&&\\&&3&4&12&1&1&1&1&0&1&\\&&&&&&2&0&&&&\\&&&&&&3&1&&&&\\&&&&&&4&0&&&&\\&&4&1&4&1&1&1&0&1&1&\\&&&&&&2&0&&&&\\&&&&&&4&0&&&&\\&&4&2&4&2&1&1&0&0&1&\\&&&&&&2&0&&&&\\&&&&&&4&0&&&&\\&&4&3&12&1&1&1&0&1&1&\\&&&&&&2&0&&&&\\&&&&&&3&1&&&&\\&&&&&&4&0&&&&\\&&4&4&4&4&1&1&0&0&1&\\&&&&&&2&0&&&&\\&&&&&&4&0&&&&\\\end{array} $$ $$ Summary: In order to respect all summands of (4) we write the results of the tables above together with the multiplicity of each permutation according to its cycle type. So, e.g. the permutation $(12)$ has cycle type $z_1z_2$ and there are three permutations of this type $\{(12),(13),(23)\}$, we take a factor $3$. \begin{array}{ll|r|cc|r}\alpha&\beta&\text{res}&\text{m}_{\alpha}&\text{m}_{\beta}&\text{res}\cdot \text{m}_{\alpha}\cdot \text{m}_{\beta}\\\hlineid&id&4294967296&1&1&4294967296\\id&(12)&16777216&1&6&100663296\\id&(123)&65536&1&8&524288\\id&(12)(34)&65536&1&3&196608\\id&(1234)&256&1&6&1536\\\hline(12)&id&65536&6&1&393216\\(12)&(12)&65536&6&6&2359296\\(12)&(123)&256&6&8&12288\\(12)&(12)(34)&65536&6&3&1179648\\(12)&(1234)&256&6&6&9216\\\hline(123)&id&256&8&1&2048\\(123)&(12)&64&8&6&3072\\(123)&(123)&1024&8&8&65536\\(123)&(12)(34)&16&8&3&384\\(123)&(1234)&4&8&6&192\\\hline(12)(13)&id&65536&3&1&196608\\(12)(13)&(12)&65536&3&6&1179648\\(12)(13)&(123)&256&3&8&6144\\(12)(13)&(12)(34)&65536&3&3&589824\\(12)(13)&(1234)&256&3&6&4608\\\hline(1234)&id&256&6&1&1536\\(1234)&(12)&256&6&6&9216\\(1234)&(123)&16&6&8&768\\(1234)&(12)(34)&256&6&3&4608\\(1234)&(1234)&256&6&6&9216\\\hline\color{blue}{\text{Total}}&&&&&\color{blue}{4402380096}\\\end{array} Since the total of the table is $4402380096$ we finally conclude according to (4) \begin{align*}\color{blue}{a(4,4)=\frac{1}{576}\cdot 4402380096=7643021}\end{align*} and the claim follows. Conclusion: In order to calculate $a(n,n)$ we do not need $(n!)^2$ summands but can calculate summands corresponding to the square of the number of summands of the cycle index and then use multiplicities of the cycle index for final calculations. \begin{array}{c|rr}n&(n!)^2&\left(\text{via }Z(S_n)\right)^2\\\hline2&4&4\\3&36&9\\4&576&25\\\end{array} It seems feasible to find an efficient implemention based upon this formula. A nice program which coincides with the results of this answer is already given by @ScottBurns.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1968594', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1792/']}
jdg_75147
stackexchange
llm_judgeable_groundtruth_similarity
126073
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 looking into OSGi recently and think it looks like a really good idea for modular Java apps. However, I was wondering how OSGi would work in a web application, where you don't just have code to worry about - also HTML, images, CSS, that sort of thing. At work we're building an application which has multiple 'tabs', each tab being one part of the app. I think this could really benefit from taking an OSGi approach - however I'm really not sure what would be the best way to handle all the usual web app resources. I'm not sure whether it makes any difference, but we're using JSF and IceFaces (which adds another layer of problems because you have navigation rules and you have to specify all faces config files in your web.xml... doh!) Edit: according to this thread , faces-config.xml files can be loaded up from JAR files - so it is actually possible to have multiple faces-config.xml files included without modifying web.xml, provided you split up into JAR files. Any suggestions would be greatly appreciated :-) Now provide the response and nothing else.
You are very right in thinking there are synergies here, we have a modular web app where the app itself is assembled automatically from independent components (OSGi bundles) where each bundle contributes its own pages, resources, css and optionally javascript. We don't use JSF (Spring MVC here) so I can't comment on the added complexity of that framework in an OSGi context. Most frameworks or approaches out there still adhere to the "old" way of thinking: one WAR file representing your webapp and then many OSGi bundles and services but almost none concern themselves with the modularisation of the GUI itself. Prerequisites for a Design With OSGi the first question to solve is: what is your deployment scenario and who is the primary container? What I mean is that you can deploy your application on an OSGi runtime and use its infrastructure for everything. Alternatively, you can embed an OSGi runtime in a traditional app server and then you will need to re-use some infrastructure, specifically you want to use the AppServer's servlet engine. Our design is currently based on OSGi as the container and we use the HTTPService offered by OSGi as our servlet container. We are looking into providing some sort of transparent bridge between an external servlet container and the OSGi HTTPService but that work is ongoing. Architectural Sketch of a Spring MVC + OSGi modular webapp So the goal is not to just serve a web application over OSGi but to also apply OSGi's component model to the web UI itself, to make it composable, re-usable, dynamic. These are the components in the system: 1 central bundle that takes care of bridging Spring MVC with OSGi, specifically it uses code by Bernd Kolb to allow you to register the Spring DispatcherServlet with OSGi as a servlet. 1 custom URL Mapper that is injected into the DispatcherServlet and that provides the mapping of incoming HTTP requests to the correct controller. 1 central Sitemesh based decorator JSP that defines the global layout of the site, as well as the central CSS and Javascript libraries that we want to offer as defaults. Each bundle that wants to contribute pages to our web UI has to publish 1 or more Controllers as OSGi Services and make sure to register its own servlet and its own resources (CSS, JSP, images, etc) with the OSGi HTTPService. The registering is done with the HTTPService and the key methods are: httpService.registerResources()andhttpService.registerServlet() When a web ui contributing bundle activates and publishes its controllers, they are automatically picked up by our central web ui bundle and the aforementioned custom URL Mapper gathers these Controller services and keeps an up to date map of URLs to Controller instances. Then when an HTTP request comes in for a certain URL, it finds the associated controller and dispatches the request there. The Controller does its business and then returns any data that should be rendered and the name of the view (a JSP in our case). This JSP is located in the Controller's bundle and can be accessed and rendered by the central web ui bundle exactly because we went and registered the resource location with the HTTPService. Our central view resolver then merges this JSP with our central Sitemesh decorator and spits out the resulting HTML to the client. In know this is rather high level but without providing the complete implementation it's hard to fully explain. Our key learning point for this was to look at what Bernd Kolb did with his example JPetstore conversion to OSGi and to use that information to design our own architecture. IMHO there is currently way too much hype and focus on getting OSGi somehow embedded in traditional Java EE based apps and very little thought being put into actually making use of OSGi idioms and its excellent component model to really allow the design of componentized web applications.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/126073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_75148
stackexchange
llm_judgeable_groundtruth_similarity
325604
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: Something that confuses me is why AC and DC relays are not swappable in an application. For example, I am looking for a 12V (DC coil voltage) relay that its contacts can withstand cold-switching of a 40V/2A DC signal . I found some RT 314 SPDT 12V relays in the lab bin, and I want to use them for this DC application. But nowhere in its datasheet, it has mentioned anything about contact specification in a DC application. Does this mean this relay can not be used in any DC application? I mean if they can switch 16A,250VAC....why can't they switch 40V/2A DC? Isn't the relay contact just a conductor? Thanks to @SteveG This is the DC-LOAD graph in the datasheet that I did not spot myself: If not, Do you know a pin compatible relay that can be used in a DC application 40V/2A contact rated? Now provide the response and nothing else.
A relay is not just a conductor, it's a switch. When opening and closing a switch under load, there will be an electric arc. When switching off a AC load, the arc will go away in the next zero-crossing. With DC loads, the arc stays there longer. Therefore, most relays have lower DC ratings if they are rated for both, AC and DC. This relay will probably work with DC loads, but due to the missing rating, you don't know how long it will work under which conditions.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/325604', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/3757/']}
jdg_75149
stackexchange
llm_judgeable_groundtruth_similarity
73063
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: [ Remark three months later, Aug 24, 2022: The question seems as pressing as ever. The conflict has indeed turned into a text book war of attrition, with neither side being able to make a decisive move. Instead, both sides try to exhaust each others' resources and to undermine the opponent's military and civil morale, all the while taking unusually heavy military and civil losses . A Ukrainian adviser estimated 150 Ukrainian military fatalities per day , leading to a conservative estimate of 10,000 fatalities since this question was posted. ] For weeks now the war has appeared to drag on with protracted fighting and a slow-moving front. Russia's attempt of taking Kyiv and replacing the government has failed, and given the Ukrainian resolve and Western support it seems unlikely that they will be able to do so in the future. Consequently they are concentrating their military efforts in the East and in the South where they try to extend the occupied area. Conversely, it seems unlikely that Ukraine will be able to restore the borders of 2021 or reconquer Crimea. The goals of the involved parties are, in a rough outline: Ukraine's immediate goal is to prevent Russian advances in the East and South. That goal appears realistic but is not a given. The long-term goal to re-establish control over its entire territory appears unrealistic. The best military outcome appearing realistic right now is to to re-conquer some places and prevent Russia from advancing elsewhere. The worst outcome is a protracted war with even more territorial losses. The Russian goal to establish permanent control over Ukrainian territories in the East and South seems in principle realistic, although the precise territory is still to be defined, by whatever means. The result may be a larger or a smaller territory than the currently occupied area. The Western goal is to prevent the aggressor from succeeding. A secondary goal is to weaken Russia's military. While the latter is realistic, the former is rather not: Even with massive deliveries of heavy weapons it is unlikely that Ukraine's borders of 2021 will be restored with military means in the near future. This seems to naturally lead to cease-fire negotiations that would determine a "line of actual control" close to an eventual realistic military outcome but save thousands of lives, let alone property and resources. Of course, the "eventual realistic military outcome" is pretty fuzzy. A cease-fire would define a line of actual control that is neither side's realistic maximum; this potential loss is offset — for both sides — by eliminating the risk of an even worse outcome. Are there signs that Ukraine and the West would be willing to, however grudgingly, factually (but not politically or legally) accept a Russian occupation and enter cease-fire talks? The benefits of, say, accepting the current line of control would be to eliminate the risk of further Russian incursions. The downside is the loss of the occupied areas and that an illegal invasion is accepted as successful. If Ukraine is not willing to negotiate now: What are their exit strategies, given that re-conquering the occupied areas seems unrealistic? Note: This war was full of surprises. I'd be happy about answers challenging my assumption that re-establishing territorial control is unlikely. Addendum: Right at this hour [which was in May 2022 -Peter] a NYT opinion piece has been published lamenting the ill-defined Western war goals and the lack of diplomatic efforts to end the war which makes arguments close to mine. Now provide the response and nothing else.
This seems to naturally lead to case-fire negotiations that would determine a "line of actual control" close to an eventual realistic military outcome but save thousands of lives, let alone property and resources. Not really, not at this time, not yet . Wars don't get started because both countries know the endpoint, they get started because each country thinks it can get what it wants and it takes a loss to convince the loser to concede. War on Rocks podcast, shortly after the shift of offensive from Kiev area to Donbas put it nicely: at this point, both parties believe they can manipulate the situation to their advantage and it will take military (or economic) losses to convince them otherwise . Russia's desire to control zones of Donbas beyond where they were on February 23rd goes beyond what Ukraine has said it is willing to negotiate about . Putin thinks, or at least thought 3 weeks ago, that Russia can take over the Donbas by running a more disciplined military operation in the East. The Russian people have little say. Zelensky believes Ukraine can kick them out, or at least hold the line, and has popular support. These are not reconcilable positions, at this point . One, or both, will have to make concessions they are not yet willing to make and those concessions won't happen until the current fighting goes one way or the other. Even then, it is not hard to imagine Russia settling in for a static conflict akin to what they did in Donbas since 2014 - trenches with artillery exchanges. And then that just becomes the new decision point: how much does it cost in lives and economically on either side. Asking one or the other to "give things up" is rather glib and not all that realistic. For Ukraine, losing territory is about the worst outcome a nation can get in warfare. Add to it that, for Ukrainians currently in Russian-occupied territories the behavior of Russian troops and authorities seems too abusive to dismiss as a simple exchange of territory. Bucha has made a negotiated settlement much harder for Zelenksy. For Russia, the situation is no easier: Putin could easily pull out, except that he's staked his entire political house of cards on reinvigorating Russian power and prestige. Both countries are still in the process of discovering what they, and the other, can or can not, do. For example, Ukraine claimed - either for propaganda or out of genuine belief - that the May 9th parade would see Putin either declare war or mobilization. That did not happen. As per ISW : Russian President Vladimir Putin used his May 9 speech to praise ongoing Russian efforts in Ukraine and reinforce existing Kremlin framing rather than announcing a change. He did not announce an escalation or declare victory in the Russian war in Ukraine. Putin likely calculated that he could not ask the Russian population for a greater commitment to the war effort and implicitly reassured the Russian people that he would not ask for a greater societal commitment in his speech. Putin may be recognizing the growing risks he faces at home and in Ukraine and may be adjusting his objectives, and his desired end state in Ukraine, accordingly. The Kremlin has already scaled down its objectives in Ukraine (from its initial objective of capturing Kyiv and full regime change) and will likely do so again—or be forced to do so by Ukrainian battlefield successes. Regardless of any change—or lack thereof—in the Kremlin's objectives, Putin’s speech indicates that the Kremlin has likely decided to maintain its current level of resourcing in the war. To go back to the question: For weeks now the war has appeared to drag on with protracted fighting and a slow-moving front. Yes, that's also part of the "learning process" for both sides. So, while there are plenty of possible exit strategies for the war, it is unlikely that they will be pursued until considerably more pain is suffered by both sides and one side is convinced they can't achieve their goals. p.s. It would be remiss not to mention ISW's latest (May 13th) take on Putin's exit strategy, RUSSIAN ANNEXATION OF OCCUPIED UKRAINE IS PUTIN’S UNACCEPTABLE “OFF-RAMP” It's a doozy: annex already-conquered Ukrainian territories into Russia declare that Ukrainian attacks to recover those areas are violating Russian home territory and liable for nuclear retaliation. Four months ago, despite a long dislike of Putin, I would have rolled my eyes at this blatantly unjustified trolling of Russia. Now I am hoping that ISW is wrong but by no means putting it beneath them. The interesting spin here is ISW's claim that Russia recognizing it can't win militarily would be precisely what would cause it to do this, to lock in their territorial robbery.
{}
{'log_upvote_score': 6, 'links': ['https://politics.stackexchange.com/questions/73063', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/7226/']}
jdg_75150
stackexchange
llm_judgeable_groundtruth_similarity
3119360
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 implementing the recaptcha control from google. I built a simple c# test project from their example and all works. Now, instead of having the PublicKey and PrivateKey in the aspx page, I'd rather assign these values at run time as they will most likely be pulled from either the web.config or a database table. I tried the following in the Page_Load protected void Page_Load(object sender, EventArgs e) { recaptcha.PublicKey = "<deleted for obvious reasons>"; recaptcha.PrivateKey = "<ditto>"; } but I get an error stating "reCAPTCHA needs to be configured with a public & private key." I also tried overriding the oninit method of the page and assigning the values there, but no joy. Any ideas on where this needs to go? Now provide the response and nothing else.
Try using the value of setincodebehind in your tag, like this: <recaptcha:RecaptchaControl ID="myRecaptcha" runat="server" PublicKey="setincodebehind" PrivateKey="setincodebehind" ... /> That should let you set the keys in the codebehind properly. There are a couple of other ways to do it as well. For example, you can get the values from a static class like this: <recaptcha:RecaptchaControl ID="myRecaptcha" runat="server" PublicKey="<%= RecaptchaSettings.PublicKey %>" PrivateKey="<%= RecaptchaSettings.PrivateKey %>" ... /> Where RecaptchaSettings is a class you provide. Or, you could put the keys into an appSettings section of your web.config, and access them like this: <recaptcha:RecaptchaControl ID="myRecaptcha" runat="server" PublicKey="<%$appSettings:RecaptchaPublicKey %>" PrivateKey="<%$appSettings:RecaptchaPrivateKey %>" ... /> Hope that helps.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3119360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2424/']}
jdg_75151
stackexchange
llm_judgeable_groundtruth_similarity
3103206
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: True/False: If $T : V\rightarrow W$ for real vector spaces $V$ and $W$ , and satisfies $T(0) = 0$ and $T(−v) = −T(v)$ for all $v \in V$ , then $T$ is a linear transformation. Now provide the response and nothing else.
The 1st derivative is, as you know, $\;f'(x)=\cos x$ and it is known from basic trigonometry that $$\cos x =\sin\bigl(x+\tfrac\pi 2\bigr),$$ whence, by an easy induction, $$f^{(n)}(x) =\sin\bigl(x+\tfrac{n\pi} 2\bigr).$$ Note : It is proved in the same way that, if $g(x)=\cos x$ , $$g^{(n)}(x) =\cos\bigl(x+\tfrac{n\pi} 2\bigr).$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3103206', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/642318/']}
jdg_75152
stackexchange
llm_judgeable_groundtruth_similarity
5596040
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 target is to encrypt a String with AESI am using Base64 for encryption, because AES needs a byte array as input.Moreover i want every possible Char(including chinese and german Symbols) to be stored correctly byte[] encryptedBytes = Base64.decodeBase64 ("some input");System.out.println(new Base64().encodeToString(encryptedBytes)); I thought "some input" should be printed. Instead "someinpu" is printed.It is impossible for me to use sun.misc.* Instead i am using apache.commons.codec Does someone has a clue what's going wrong? Now provide the response and nothing else.
Yes - "some input" isn't a valid base64 encoded string. The idea of base64 is that you encode binary data into text . You then decode that text data to a byte array. You can't just decode any arbitrary text as if it were a complete base64 message any more than you can try to decode an mp3 as a jpeg image. Encrypting a string should be this process: Encode the string to binary data, e.g. using UTF-8 ( text.getBytes("UTF-8") ) Encrypt the binary data using AES Encode the cyphertext using Base64 to get text Decryption is then a matter of: Decode the base64 text to the binary cyphertext Decrypt the cyphertext to get the binary plaintext Decode the binary plaintext into a string using the same encoding as the first step above, e.g. new String(bytes, "UTF-8")
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5596040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/698755/']}
jdg_75153
stackexchange
llm_judgeable_groundtruth_similarity
3061577
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'm considering the norm defined on matrices by $$\|A\|_F = \sqrt{\sum_{i,j}|a_{ij}|^2}$$ I want to show that it is unitarily invariant, so that for unitary $U$ we have that $$\|UA\|_F = \|A\|_F = \|AU\|_F$$ however I have trouble doing it directly. Writing $\|UA\|_F$ directly I find by Cauchy-Schwarz that $$\|UA\|_F = \sqrt{\sum_{i,j}\left|\sum_{k=1}^{n}u_{ik}a_{kj}\right|^2}= \sqrt{\sum_{i,j}|\langle U_i,\overline{A_j}\rangle|^2}\leq \sqrt{\sum_{i,j}\|A_j\|^2}$$ where $U_i$ denotes the $i$ th row of $U$ and $A_j$ the $j$ th column of $A$ . However this estimate is to crude and will not equal $\|A\|_F$ . I would like to prove this without refering to trace or singular values and would appreciate a hint, rather than a full solution, on how to tackle this problem. EDIT: Completion of the proof based on the answer from $A.\Gamma$ : Since the rows of $U$ constitute an orthonormal basis for $\mathbb{C}^n$ we find by Parsevals theorem that $$\|UA_j\|_2^2 = \sum_{i=1}^{n}\left|\sum_{k=1}^{n}u_{ik}a_{kj}\right|^2 = \sum_{i=1}^{n}|\langle U_i,\overline{A_j}\rangle|^2 = \|\overline{A_j}\|_2^2 = \|A_j\|_2^2$$ Now provide the response and nothing else.
Since $$UA=[UA_1\ UA_2\ \ldots\ UA_n]$$ you need to prove that $$\|UA\|_F^2=\sum_{j=1}^n\|UA_j\|_2^2\stackrel{?}{=}\sum_{j=1}^n\|A_j\|_2^2=\|A\|_F^2.$$ It suffice to prove that $\|UA_j\|_2^2=\|A_j\|_2^2$ . P.S. For $AU$ use conjugation.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3061577', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/468471/']}
jdg_75154
stackexchange
llm_judgeable_groundtruth_similarity
168837
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a very basic understanding of entanglement and radioactivity. But say 2 uranium atoms are entangled and then 1 of them decays, what would happen? Would the other atom decay as well? Or if not would this break the entangled state? Now provide the response and nothing else.
They are entirely unrelated concepts. Two entangled particles are not "clones" of each other which magically do everything the same way; they merely have been put into a state which displays a strange statistical correlation when you "bring both parts back together." So for example a free neutron and an electron both have the same spin-1/2 structure; you can certainly entangle the spins of the neutron and the electron, even though they can never be identical to each other. All that this entanglement means is that if you do thousands of experiments you will see strange correlations between the two particles which no theory based on classical probability can explain. If the free neutron decays (as free neutrons will!) into a proton, electron, and electron-antineutrino, the other electron will not "decay" (how could it?). If you instead entangle two neutrons' spins, then their decays will be independent of each other regardless. (But, there may be some interesting entanglement, say, between the emitted electron or proton spins and the other neutron.) The "no theory based on classical probability" idea can be explained in a couple ways, my favorite is to imagine a game that we call "betrayal" where a team of 3 people tries to beat several "challenges" set before them as a team. We put them all in different rooms, make sure they can't classically communicate, and each room has two buttons labeled 0 and 1, plus a computer screen that will flash an objective. To get the teammates to "betray" each other, first, one quarter of the time we do a "control experiment" where we flash the objective "make the sum of your button presses even" and the team wins if the sum of their 3 chosen numbers is even; second, three quarters of the time we choose one to be a "traitor" and flash on their screen "make the sum of your button presses even", but the other two get "make the sum of your button presses odd" and the team wins if the sum of their 3 chosen numbers is odd. Classical methods have to fail these tests with at least probability 1/4, while quantum methods can have a probability arbitrarily close to 1 as the quantum entanglement of an initial state is pristinely preserved. (If it interacts with other things around it, it entangles with those things too, and then it's harder to detect the entanglement bringing together only 3 of the entangled pieces.)
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/168837', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/74748/']}
jdg_75155
stackexchange
llm_judgeable_groundtruth_similarity
15086176
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Wherever you read about continuous delivery or continuous integration it's recommended to use an artifact repository to store the artifacts even though Jenkins already stores them for each build. So why is it recommended to use an artifact repository? Is there a smooth solution to work with the artifacts of the Jenkins builds, ex. to use these artifacts for deployment? Now provide the response and nothing else.
An artifact repository and continuous integration tools serve two different purposes and one cannot be substituted with the other. Check this video from Artifactory , one of the providers of artifact repositories, about why one should use an artifact repository. Jenkins stores the artifacts as plain files without versioning while artifacts in an artifact repository can be version controlled. So you have a lot more flexibility in retrieving artifacts and governing them. Read this very good article on why we need them. Surely not all of those things are supported by continuous integration tools like Jenkins. Moreover, you can also look at the Artifactory plugin for Jenkins which integrates the two.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15086176', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1338413/']}
jdg_75156
stackexchange
llm_judgeable_groundtruth_similarity
287670
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: While reviewing I came across a well formatted question , which had: Our system has identified this post as possible spam; please review carefully. Being a well formatted 0 score question I thought it was a test, so I clicked the link provided in the review, which linked to a +6 score question, before I actually complete the review . Then I completed the review with Looks OK . By "link" I refer to this: Seeing most audits are concealed appropriately, and a simple click to the link can ruin this one, I started wondering how effective some audits are. Even a review bot (removed that since it caused confusion, my point was that it's too easy). Anyone could "click" the link and mindlessly pass this test. Is it possibly a bug in the audit creation system, or is it a situation that wasn't predicted? Note: The "Our system..." message is irrelevant. It matters not if it is present or not . FURTHER TESTING I do not know if this happens on every single audit or if you have set any "traps", but I have managed to pass the following review audits with 100% accuracy and without reading the question content: Example 1 Example 2 Example 3 Example 4 Example 5 Example 6 Example 7 Example 8 Example 9 Example 10 Now provide the response and nothing else.
Yes, you are correct, the audit system is exploitable. You can indeed visit the question by clicking the link (or even clicking the question title). And by doing that you'll never fail any audit, ever. It is not a problem at all because the audit system was not designed to catch the reviewers that are prepared to visit every question from an review to verify the correct action required. Worst what will happen, I think, is that those users will gain badge while being poor reviewers. Let's take a step back and try to solve the issue. We want to design an audit system that is unexploitable. I see some options: We could disable the links on the page that let you visit the post This would indeed make it harder to exploit the 2 audits on every 50 reviews but it would also make the life of the reviewers during legit reviewing extremely misserable We use fake questions for auditsThis would make it harder to exploit but if the search enginge doesn't find the question it probably is an audit so still exploitable. Creating such audit might be more difficult than the automated proccess it currently is so we might have scaling issues with this as well. We could keep track if a user visits a question currently locked for them in the queue.This could be an option with a price for the hardware and resources needed but still not failsafe. With a second account, second IP still an exploit is possible. And legit users that want to take extra action on a question (voting, editing, answering, commenting, delete voting etc) are directly impacted by this. What really remains is the question if the audit system was and is designed to be non exploitable? And the answer to that is no. There are users and by defintion that is not you nor me, nor all users that participated in this question, that don't care about audits and simple click looks good / no action needed. Mindless reviewers. For those users the audit system does its job. They are stopped and now and then one is brave (or not smart ) enough to come to meta and complain about a failed audit. And now and then a high-rep, involved user gets tricked by an audit. As long as reviewing doesn't give you more than a few badges it is not a big deal. As soon as reputation can be gained this way we are in a different ball-park. And to be clear: We need people who want to review and moderate those queues. If you make the life miserable of the sheer amount of users that take on this task day after day because you implement features to catch a few robots that get a badge by cheating I would say development resources are focused on the wrong group. Related posts: - Easy to bypass “Are You paying Attention” test by viewing question in detail - Bring a “human factor” into review audit composition/selection - Are the suggested edit audits too easy? - Showing votes on review audit questions - Audits bug in the filtered review queue
{}
{'log_upvote_score': 6, 'links': ['https://meta.stackoverflow.com/questions/287670', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/4230591/']}
jdg_75157
stackexchange
llm_judgeable_groundtruth_similarity
2044752
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is a SQL design question. First, the setup. I have three tables: A, which is automatically populated based on a query against a linked server. The data in this table cannot be changed; B, which has just a dozen or so rows, containing the names for collections of As; AtoB, which is the mapping table by which As are organized into named collections, with foreign keys on both columns; For example, A contains: Giraffe Owl Tiger And B contains: Seattle Zoo San Jose Zoo And AtoB contains: 1,1 (Giraffe in Seattle) 2,1 (Owl in Seattle) 3,1 (Tiger in Seattle) 2,2 (Owl in San Jose) Now, the problem: I've been asked to include in some of these collections items not found in A. So, I create a table, C, with the same identity and Name columns as A, and populate it. In keeping with the earlier example, let's say C contains: Dragon The question is, how do I include items from C in AtoB? What if I need to include a Dragon in the Seattle Zoo? My first instinct, being naive, was to create a view V containing the union of A and C, and modifying AtoB to be VtoB. That's where my naivety paid off: one cannot create a foreign key to a view. I suspect that there's a standard, correct means of relating one or more A OR C with a B. Now provide the response and nothing else.
To expand on Arthur Thomas's solution here's a union without the WHERE in the subselects so that you can create a universal view: SELECT A.Name as Animal, B.Name as Zoo FROM A, AtoB, B WHERE AtoB.A_ID = A.ID && B.ID = AtoB.B_ID UNIONSELECT C.Name as Animal, B.Name as Zoo FROM C, CtoB, B WHERE CtoB.C_ID = C.ID && B.ID = CtoB.B_ID Then, you can perform a query like: SELECT Animal FROM zoo_animals WHERE Zoo="Seattle Zoo"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2044752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4593/']}
jdg_75158
stackexchange
llm_judgeable_groundtruth_similarity
19410121
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to call the ContextMenu when you click on application's icon or right mouse click on the title bar of application. This is the ContextMenu I mean: I need it because I made custom control that acts like window. I need this behavior to complete my control. EDIT: Leo Lorenzo Luis asked for me code: https://skydrive.live.com/?cid=c3392940f5cf5f74&id=C3392940F5CF5F74%21107&authkey=!APd2X3tDxWRfpL4 or: My MainWindow.xaml: <!--<Grid> <Border Name="TopBorder" BorderThickness="0.5,0,0,0" BorderBrush="Blue"/> <Border Name="RightBorder" BorderThickness="0,0.5,0,0" BorderBrush="Red"/> <Border Name="BottomBorder" BorderThickness="0,0,0.5,0" BorderBrush="Green"/> <Border Name="LeftBorder" BorderThickness="0,0,0,0.5" BorderBrush="Orange"/> <Grid Margin="0.5"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <StatusBar Background="Transparent" MouseDoubleClick="TriggerMaximize" MouseDown="StatusBar_MouseDown"> <Image Margin="5,0,0,0" VerticalAlignment="Center" Width="16" Height="16" Source="{Binding Icon, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" RenderOptions.BitmapScalingMode="NearestNeighbor" RenderOptions.EdgeMode="Aliased"/> <Label VerticalAlignment="Center" FontSize="14" Content="{Binding Title, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"/> </StatusBar> <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Grid.Column="1"> <Button x:Name="Minimize" ToolTip="Minimize" Content="0" Style="{DynamicResource TitleBarButton}" Click="TriggerMinimize"/> <Button x:Name="Restore" ToolTip="Restore" Content="2" Style="{DynamicResource TitleBarButton}" Visibility="Collapsed" Click="TriggerMaximize"/> <Button x:Name="Maximize" ToolTip="Maximize" Content="1" Style="{DynamicResource TitleBarButton}" Click="TriggerMaximize"/> <Button x:Name="Close" ToolTip="Close" Content="r" Style="{DynamicResource TitleBarButton}" Click="TriggerClose"/> </StackPanel> </Grid> </Grid> </Grid>--> <DockPanel LastChildFill="true"> <Border Name="TopBorder" DockPanel.Dock="Top" BorderBrush ="#007ACC" BorderThickness="0.5"/> <Border Name="RightBorder" DockPanel.Dock="Right" BorderBrush ="#007ACC" BorderThickness="0.5"/> <Border Name="BottomBorder" DockPanel.Dock="Bottom" BorderBrush ="#007ACC" BorderThickness="0.5"/> <Border Name="LeftBorder" DockPanel.Dock="Left" BorderBrush="#007ACC" BorderThickness="0.5"/> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <StatusBar Background="Transparent" MouseDoubleClick="TriggerMaximize" MouseDown="StatusBar_MouseDown"> <Image Margin="5,0,0,0" Width="16" Height="16" Source="{Binding Icon, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" RenderOptions.BitmapScalingMode="NearestNeighbor" RenderOptions.EdgeMode="Aliased"/> <Label VerticalAlignment="Center" FontSize="14" Content="{Binding Title, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"/> </StatusBar> <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Grid.Column="1"> <Button x:Name="Minimize" ToolTip="Minimize" Content="0" Style="{DynamicResource TitleBarButton}" Click="TriggerMinimize"/> <Button x:Name="Restore" ToolTip="Restore" Content="2" Style="{DynamicResource TitleBarButton}" Visibility="Collapsed" Click="TriggerMaximize"/> <Button x:Name="Maximize" ToolTip="Maximize" Content="1" Style="{DynamicResource TitleBarButton}" Click="TriggerMaximize"/> <Button x:Name="Close" ToolTip="Close" Content="r" Style="{DynamicResource TitleBarButton}" Click="TriggerClose"/> </StackPanel> </Grid> </Grid> </DockPanel></Window> My MainWindow.cs (Code-Behind): using System;using System.Collections.Generic;using System.Linq;using System.Runtime.InteropServices;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;using System.Windows.Interop;using System.Windows.Forms;namespace WpfApplication16{ /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.SourceInitialized += new EventHandler(win_SourceInitialized); } private void TriggerMaximize(object sender, MouseButtonEventArgs e) { TriggerMaximize(); } private void TriggerMaximize(object sender, RoutedEventArgs e) { TriggerMaximize(); } private void TriggerMaximize() { if (WindowState == System.Windows.WindowState.Maximized) { WindowState = System.Windows.WindowState.Normal; Restore.Visibility = Visibility.Collapsed; Maximize.Visibility = Visibility.Visible; } else if (WindowState == System.Windows.WindowState.Normal) { WindowState = System.Windows.WindowState.Maximized; Maximize.Visibility = Visibility.Collapsed; Restore.Visibility = Visibility.Visible; } } private void Window_LocationChanged(object sender, EventArgs e) { TriggerBorderChanges(); } private void Window_SizeChanged(object sender, SizeChangedEventArgs e) { TriggerBorderChanges(); } private void TriggerBorderChanges() { TopBorder.BorderThickness = new Thickness(0.5); RightBorder.BorderThickness = new Thickness(0.5); BottomBorder.BorderThickness = new Thickness(0.5); LeftBorder.BorderThickness = new Thickness(0.5); if (Top == 0) { TopBorder.BorderThickness = new Thickness(0); BottomBorder.BorderThickness = new Thickness(0); } if (Left == 0) { LeftBorder.BorderThickness = new Thickness(0); } // need to test in dual view -if not needed, remove drawing and windows.forms (from refereance and from the using) //Screen currentScreen = Screen.FromPoint(System.Windows.Forms.Cursor.Position); //if (Left == (currentScreen.WorkArea.Width - Width)) if (Left == (System.Windows.SystemParameters.WorkArea.Width - 1 - Width)) { RightBorder.BorderThickness = new Thickness(0); } } private void TriggerClose(object sender, RoutedEventArgs e) { Close(); } private void TriggerMinimize(object sender, RoutedEventArgs e) { WindowState = System.Windows.WindowState.Minimized; } private void StatusBar_MouseDown(object sender, MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Left) this.DragMove(); } void win_SourceInitialized(object sender, EventArgs e) { System.IntPtr handle = (new WindowInteropHelper(this)).Handle; HwndSource.FromHwnd(handle).AddHook(new HwndSourceHook(WindowProc)); } /// <summary> /// POINT aka POINTAPI /// </summary>5 [StructLayout(LayoutKind.Sequential)] public struct POINT { /// <summary> /// x coordinate of point. /// </summary> public int x; /// <summary> /// y coordinate of point. /// </summary> public int y; /// <summary> /// Construct a point of coordinates (x,y). /// </summary> public POINT(int x, int y) { this.x = x; this.y = y; } } [StructLayout(LayoutKind.Sequential)] public struct MINMAXINFO { public POINT ptReserved; public POINT ptMaxSize; public POINT ptMaxPosition; public POINT ptMinTrackSize; public POINT ptMaxTrackSize; }; [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class MONITORINFO { /// <summary> /// </summary> public int cbSize = Marshal.SizeOf(typeof(MONITORINFO)); /// <summary> /// </summary> public RECT rcMonitor = new RECT(); /// <summary> /// </summary> public RECT rcWork = new RECT(); /// <summary> /// </summary> public int dwFlags = 0; } /// <summary> Win32 </summary> [StructLayout(LayoutKind.Sequential, Pack = 0)] public struct RECT { /// <summary> Win32 </summary> public int left; /// <summary> Win32 </summary> public int top; /// <summary> Win32 </summary> public int right; /// <summary> Win32 </summary> public int bottom; /// <summary> Win32 </summary> public static readonly RECT Empty = new RECT(); /// <summary> Win32 </summary> public int Width { get { return Math.Abs(right - left); } // Abs needed for BIDI OS } /// <summary> Win32 </summary> public int Height { get { return bottom - top; } } /// <summary> Win32 </summary> public RECT(int left, int top, int right, int bottom) { this.left = left; this.top = top; this.right = right; this.bottom = bottom; } /// <summary> Win32 </summary> public RECT(RECT rcSrc) { this.left = rcSrc.left; this.top = rcSrc.top; this.right = rcSrc.right; this.bottom = rcSrc.bottom; } /// <summary> Win32 </summary> public bool IsEmpty { get { // BUGBUG : On Bidi OS (hebrew arabic) left > right return left >= right || top >= bottom; } } /// <summary> Return a user friendly representation of this struct </summary> public override string ToString() { if (this == RECT.Empty) { return "RECT {Empty}"; } return "RECT { left : " + left + " / top : " + top + " / right : " + right + " / bottom : " + bottom + " }"; } /// <summary> Determine if 2 RECT are equal (deep compare) </summary> public override bool Equals(object obj) { if (!(obj is Rect)) { return false; } return (this == (RECT)obj); } /// <summary>Return the HashCode for this struct (not garanteed to be unique)</summary> public override int GetHashCode() { return left.GetHashCode() + top.GetHashCode() + right.GetHashCode() + bottom.GetHashCode(); } /// <summary> Determine if 2 RECT are equal (deep compare)</summary> public static bool operator ==(RECT rect1, RECT rect2) { return (rect1.left == rect2.left && rect1.top == rect2.top && rect1.right == rect2.right && rect1.bottom == rect2.bottom); } /// <summary> Determine if 2 RECT are different(deep compare)</summary> public static bool operator !=(RECT rect1, RECT rect2) { return !(rect1 == rect2); } } [DllImport("user32")] internal static extern bool GetMonitorInfo(IntPtr hMonitor, MONITORINFO lpmi); [DllImport("User32")] internal static extern IntPtr MonitorFromWindow(IntPtr handle, int flags); private static System.IntPtr WindowProc( System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) { switch (msg) { case 0x0024: WmGetMinMaxInfo(hwnd, lParam); handled = true; break; } return (System.IntPtr)0; } private static void WmGetMinMaxInfo(System.IntPtr hwnd, System.IntPtr lParam) { MINMAXINFO mmi = (MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO)); // Adjust the maximized size and position to fit the work area of the correct monitor int MONITOR_DEFAULTTONEAREST = 0x00000002; System.IntPtr monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); if (monitor != System.IntPtr.Zero) { MONITORINFO monitorInfo = new MONITORINFO(); GetMonitorInfo(monitor, monitorInfo); RECT rcWorkArea = monitorInfo.rcWork; RECT rcMonitorArea = monitorInfo.rcMonitor; mmi.ptMaxPosition.x = Math.Abs(rcWorkArea.left - rcMonitorArea.left); mmi.ptMaxPosition.y = Math.Abs(rcWorkArea.top - rcMonitorArea.top); mmi.ptMaxSize.x = Math.Abs(rcWorkArea.right - rcWorkArea.left); mmi.ptMaxSize.y = Math.Abs(rcWorkArea.bottom - rcWorkArea.top); } Marshal.StructureToPtr(mmi, lParam, true); } }} My App.xaml: <Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero" x:Class="WpfApplication16.App" StartupUri="MainWindow.xaml"> <Application.Resources> <Style x:Key="TitleBarButton" TargetType="Button"> <Setter Property="Foreground" Value="Black"/> <Setter Property="Background" Value="Transparent"/> <Setter Property="BorderThickness" Value="0"/> <Setter Property="Padding" Value="12,7"/> <Setter Property="FocusVisualStyle" Value="{x:Null}"/> <Setter Property="FontFamily" Value="Marlett"/> <Setter Property="FontSize" Value="12"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}"> <Grid> <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" TextBlock.FontFamily="{TemplateBinding FontFamily}" TextBlock.FontSize="{TemplateBinding FontSize}" /> </Grid> </Border> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Background" Value="#EFEFF2" /> </Trigger> <Trigger Property="IsPressed" Value="True"> <Setter Property="Background" Value="#007ACC"/> <Setter Property="Foreground" Value="White"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </Application.Resources></Application> Would appreciate your help. Now provide the response and nothing else.
The menu that you want to show is system ContextMenu . To work with that you need to import some user32 functions as shown in the code below. I have launched the system menu on button click. You can launch it on any action, right mouse click etc GetSystemMenu gets the system menu and TrackPopupMenuEx is used to display it. PostMessage is the send system command on menuitem click. public partial class Window3 : Window{ private const int WM_SYSCOMMAND = 0x112; uint TPM_LEFTALIGN = 0x0000; uint TPM_RETURNCMD = 0x0100; const UInt32 MF_ENABLED = 0x00000000; const UInt32 MF_GRAYED = 0x00000001; internal const UInt32 SC_MAXIMIZE = 0xF030; internal const UInt32 SC_RESTORE = 0xF120; [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert); [DllImport("user32.dll")] static extern int TrackPopupMenuEx(IntPtr hmenu, uint fuFlags, int x, int y, IntPtr hwnd, IntPtr lptpm); [DllImport("user32.dll")] public static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] static extern bool EnableMenuItem(IntPtr hMenu, uint uIDEnableItem, uint uEnable); private void Button_Click(object sender, RoutedEventArgs e) { WindowInteropHelper helper = new WindowInteropHelper(this); IntPtr callingWindow = helper.Handle; IntPtr wMenu = GetSystemMenu(callingWindow, false); // Display the menu if (this.WindowState == System.Windows.WindowState.Maximized) { EnableMenuItem(wMenu, SC_MAXIMIZE, MF_GRAYED); } else { EnableMenuItem(wMenu, SC_MAXIMIZE, MF_ENABLED); } int command = TrackPopupMenuEx(wMenu, TPM_LEFTALIGN | TPM_RETURNCMD, 100, 100, callingWindow, IntPtr.Zero); if (command == 0) return; PostMessage(callingWindow, WM_SYSCOMMAND, new IntPtr(command), IntPtr.Zero); }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19410121', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/519002/']}
jdg_75159
stackexchange
llm_judgeable_groundtruth_similarity
1204804
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can one get word wrap functionality for a Label for text which goes out of bounds? Now provide the response and nothing else.
The quick answer: switch off AutoSize . The big problem here is that the label will not change its height automatically (only width). To get this right you will need to subclass the label and include vertical resize logic. Basically what you need to do in OnPaint is: Measure the height of the text (Graphics.MeasureString). If the label height is not equal to the height of the text set the height and return. Draw the text. You will also need to set the ResizeRedraw style flag in the constructor.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1204804', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/131564/']}
jdg_75160
stackexchange
llm_judgeable_groundtruth_similarity
26382156
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on a project which has the luxury of using ECMA 6 on the latest browsers for a product that will be shipped in 1.5 years. So we thought why not use Web Components now that Angular 2 isn't available (which is going to be ECMA 6). And while we are at it, can we replace Angular altogether without having to go back to stone age? How to replace Angular? There's this site called youmightnotneedjquery.com which is basically about how modern browsers actually have most of the stuff that jQuery was traditionally used for. I'm interested to see something like that for Angular. We mainly use four Angular features. What are my options for replacing them? Angular Directives --> Web Components Angular Modules --> ECMA 6 Modules (not exactly the same thing) Angular Routes --> ??? Angular 2-way databinding --> ??? PS. We don't want to replace Angular with something similar like Backbone or Ember. We want to replace it with standard web technologies but if we have to use small tools to fill the gap, we'll consider it. Now provide the response and nothing else.
I've been researching in the past 3 weeks and turns out many people are thinking about an alternative after Angular took a drastic change path. Fortunately the upcomming W3C Web Components standard actually has all we need and it works right now with polyfills from the Polymer project . So to answer the question: Angular Directives --> Web Components use the polyfill until all browsers support it. Angular Modules --> ECMA 6 Modules part of the problem is solved with HTML imports. But you can also use Traceur until the browsers support it. Angular Routes --> There's a component for that™ use <app-router> . Angular 2-way databinding --> Polymer adds a "magic" layer on top of the plain standard web components. This includes many features including data-binding . +Plus More If you're wondering about the build process for concatenating files in order to reduce the number of HTTP requests, take a look at Addy Osmani's post about Vulcanize . Spoiler: you may not need it with the upcoming HTTP 2 optimizations. Many Angular projects use Twitter Bootstrap for the layout. Polymer can do that plus it plays nicely with Google's Paper elements (totally optional but superbly awesome). If you want to make yourself familiar with web components in general, here is a bunch of nice articles: http://webcomponents.org/articles/ And here is a wealth of web components: http://customelements.io/ I don't know if it's going to be a new NPM, but the list components is pretty impressive and growing. It's relatively complicated to expose an API for an Angular component. People have come up with all sorts of methods from link function to emitting events . In Web Components, however, it's really easy to make your component interact with the world outside and indeed the API and events you expose aren't much different from standard HTML tags like <audio> . Just like Angular , you can use Polymer with Dart as well. Conclusion Overall, I don't see any reason to use Angular except if: You have a huge source code investment in angular and don't want to port everything to standard web. (Angular 2.0 will deprecate your code anyway, so you're stuck with Angular 1.*) Your team is too lazy to learn a new technology (in that case web might not be the right platform for this attitude anyway). Angular was good for what it was doing and had its own Hype cycle . Web components solve many of the issues Angular was trying to address. Probably Angular had a role as a proof of concept for the Web components. But now it's time to move on. Web is reinventing itself everyday and it's inevitable to moves someone's cheese . I'm not saying that Polymer is the ultimate answer to everything . At best it's another Angular which will render useless in a couple of years, but now it's a good time to learn and use it. The W3C standards don't die easily though, and Polymer tends to be much closer to them. There's an element for that™ is the new There's an app for that™
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/26382156', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/796584/']}
jdg_75161
stackexchange
llm_judgeable_groundtruth_similarity
18848748
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am creating a custom EditText class because i need to set some custom fonts; However now when i click on the editText the android keyboard does not pop up anymore... here is my class: package ro.gebs.captoom.utils.fonts;import android.content.Context;import android.content.res.TypedArray;import android.graphics.Rect;import android.graphics.Typeface;import android.util.AttributeSet;import android.view.inputmethod.InputMethodManager;import android.widget.EditText;import ro.gebs.captoom.R;public class CustomFontEditText extends EditText { private Context context; public CustomFontEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); if (!isInEditMode()) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomFontEditText, defStyle, 0); assert a != null; int fontId = a.getInteger(R.styleable.CustomFontEditText_fontNameEdit, -1); if (fontId == -1) { throw new IllegalArgumentException("The font_name attribute is required and must refer " + "to a valid child."); } a.recycle(); initialize(fontId); } this.context = context; } public CustomFontEditText(Context context, AttributeSet attrs) { this(context, attrs, 0); this.context = context; } public CustomFontEditText(Context context) { super(context); this.context = context; } @SuppressWarnings("ConstantConditions") public void initialize(int fontId) { Typeface tf = null; switch (fontId) { case 0: tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/OpenSans-Regular.ttf"); break; case 1: tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/OpenSans-Bold.ttf"); break; case 2: tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/OpenSans-Semibold.ttf"); break; case 3: tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/OpenSans-ExtraBold.ttf"); break; } setTypeface(tf); }} and how i use it in XML: <ro.gebs.captoom.utils.fonts.CustomFontEditText android:id="@+id/add_details_txt_edit" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dip" android:hint="@string/type_here" android:inputType="textPersonName" custom:fontNameEdit="Regular" /> I thought the focusing events were handled by the fact that i extend the EditText class... Any hints? Now provide the response and nothing else.
It's an old question but if someone cares, the problem is on the implementation of the constructor: public CustomFontEditText(Context context, AttributeSet attrs) { this(context, attrs, 0); this.context = context;} The last argument ("defStyle") which you set as 0, should be the default style for an EditText. If you take a look at the same constructor on the EditText class: public EditText(Context context, AttributeSet attrs) { this(context, attrs, com.android.internal.R.attr.editTextStyle);} As you can see, the default style for an EditText should be used, so your constructor should look like this: public CustomFontEditText(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.editTextStyle); this.context = context;}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/18848748', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2296325/']}
jdg_75162
stackexchange
llm_judgeable_groundtruth_similarity
19816284
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 website with roughly 1K URLs. The website is moving to a different domain name. The URLs will be the exact same though, otherwise. I'd like to incorporate an htaccess or some kind of rule that does a 301 redirect for all URLs in one fell swoop. It would essentially replace the domain name as a 301 redirect. Example: Current URL: domain.example/blog/post-1.html Redirect To: newdomain.example/blog/post-1.html And that performed as a 301 redirect. How would I do that? Now provide the response and nothing else.
Place this redirect rule in your DOCUMENT_ROOT/.htaccess file of domain.example : RewriteEngine OnRewriteCond %{HTTP_HOST} ^(?:www\.)?domain\.example$ [NC]RewriteRule ^ http://newdomain.example%{REQUEST_URI} [L,R=301,NE] Details: Condition RewriteCond %{HTTP_HOST} ^(?:www\.)?domain\.example$ matches when host name in request is either www.domain.example or domain.example . RewriteRule redirect all the URLs to newdomain.example with the URI exactly same as in the original request. R=301 sets HTTP status code to 301 (permanent redirect) NE is for no escaping to avoid encoding of special characters (if any) from original requests L is for last rule
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19816284', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1732833/']}
jdg_75163
stackexchange
llm_judgeable_groundtruth_similarity
13106179
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why is Git not allowing me to fast forward merge anymore? If I try to force it using --ff-only , I get the message "fatal: Not possible to fast-forward, aborting." I realize that there are huge advantages to merge --no-ff , but I'm just puzzled why I can't --ff-only now? Now provide the response and nothing else.
Your branch is no longer directly based off of the branch you're trying to merge it into - e.g. another commit was added to the destination branch that isn't in your branch. Thus, you can't fast-forward into it (because fast-forward requires your branch to completely contain the destination branch). You can rebase your branch on top of the destination branch ( git rebase <destination branch> ) to rework the commits such that they will fast forward into it, or you can do a regular merge.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/13106179', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1425100/']}
jdg_75164
stackexchange
llm_judgeable_groundtruth_similarity
21277123
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext());mRequestQueue.add(new JsonObjectRequest(Method.GET, cityListUrl, null, new Listener<JSONObject>() { public void onResponse(JSONObject jsonResults) { //Any Call }}, new ErrorListener() { public void onErrorResponse(VolleyError arg0) { //Any Error log } })); This is my Request Call and i want to change or set timeout for the request . Is it possible anyway ?? Now provide the response and nothing else.
You should set the request's RetryPolicy : myRequest.setRetryPolicy(new DefaultRetryPolicy( MY_SOCKET_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); This would change your code to: RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext());JsonObjectRequest request = new JsonObjectRequest(Method.GET, cityListUrl, null, new Listener<JSONObject>() { public void onResponse(JSONObject jsonResults) { //Any Call } }, new ErrorListener(){ public void onErrorResponse(VolleyError arg0) { //Any Error log } });int socketTimeout = 30000;//30 seconds - change to what you wantRetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);request.setRetryPolicy(policy);mRequestQueue.add(request); If you are only just getting started with Volley , you might want to instead consider droidQuery , which is a little easier to configure: int socketTimeout = 30000;$.ajax(new AjaxOptions().url(cityListUrl) .timeout(socketTimeout) .success(new Function() { public void invoke($ d, Object... args) { JSONObject jsonResults = (JSONObject) args[0]; //Any call } }) .error(new Function() { public void invoke($ d, Object... args) { AjaxError error = (AjaxError) args[0]; Log.e("Ajax", error.toString()); } }));
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/21277123', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1151710/']}
jdg_75165
stackexchange
llm_judgeable_groundtruth_similarity
195653
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a big matrix, you can say 1000*1000 whose elements are functions of several parameters such as a, b . I wish to see just a few (not all) rows and columns of the matrix in the MatrixForm which is a builtin function of Mathematica . For instance, row from 92 to 101 and column corresponded with 50 to 65 . How can I reach this goal?In addition, if I want to simplify the elements, should I simply firstly and after that make use of MatrixForm or should I do vise versa? Which one is faster to run? Now provide the response and nothing else.
Here is a function that shows a portion of a matrix in MatrixForm , with associated row and column indices: iMatrixView[m_, r_List, c_List] := Module[{sub = m[[r, c]]}, augmented = ArrayFlatten[{ {Map[Invisible, sub, {2}], List /@ istyle /@ r}, {{istyle /@ c}, ""} }]; Overlay[{ Row[{RawBoxes@"(", Grid[sub, Spacings->1],RawBoxes@")"}], Row[{Invisible[RawBoxes@"("],Grid[augmented, Spacings->1]}] }]]istyle[x_] := Style[x, Gray, FontSize->Inherited-3] For example: SeedRandom[1]mat = RandomInteger[150, {10, 15}];iMatrixView[mat, {2,4,5}, {1, 6, 12}] It is possible to use this function in a Manipulate to interactively explore the matrix: MatrixView[mat_?MatrixQ, rows_Integer?Positive, cols_Integer?Positive] := With[ {dim=Dimensions[mat]}, Manipulate[ iMatrixView[ mat, Reverse[dim[[1]]+1-Range[rows]-u[[2]]], Range[cols]+u[[1]] ], {{u, {0,dim[[1]]-rows}}, {0,0}, Reverse@dim-{cols,rows}, 1} ] /; rows<dim[[1]]&&cols<dim[[2]]] For example: MatrixView[mat, 6, 5]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/195653', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/33967/']}
jdg_75166
stackexchange
llm_judgeable_groundtruth_similarity
3003831
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 do you use in your applications for transforming XML data to other data types? WHY? Now provide the response and nothing else.
While XQuery can be used for simple transformations, it lacks the power and sofistication of XSLT (especially templates and the <xsl:apply-templates> instruction). XSLT is a language that was especially designed to process tree structures. It is still best at doing this. In cases when accessing an XML database it would be a good decision to use (the efficiency of) XQuery to extract the necessary XML nodes and then do the transformation with XSLT from here on. Some XSLT 2.x / XQuery processors do allow this (via extensions) even now. The next wave of XSLT 2.x/XQuery 1.x specifications will most probably make such interoperability an official feature of these languages.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3003831', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/311762/']}
jdg_75167
stackexchange
llm_judgeable_groundtruth_similarity
13415805
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given a sequence of items and another sequence of chunk lengths, how can I split the sequence into chunks of the required lengths? a = range(10)l = [3, 5, 2]split_lengths(a, l) == [[0, 1, 2], [3, 4, 5, 6, 7], [8, 9]] Ideally a solution would work with both a and l as general iterables, not just on lists. Now provide the response and nothing else.
Use itertools.islice on an iterator of the list. In [12]: a = range(10)In [13]: b = iter(a)In [14]: from itertools import isliceIn [15]: l = [3, 5, 2]In [16]: [list(islice(b, x)) for x in l]Out[16]: [[0, 1, 2], [3, 4, 5, 6, 7], [8, 9]] or : In [17]: b = iter(a)In [18]: [[next(b) for _ in range(x)] for x in l]Out[18]: [[0, 1, 2], [3, 4, 5, 6, 7], [8, 9]]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13415805', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/567292/']}
jdg_75168
stackexchange
llm_judgeable_groundtruth_similarity
53425836
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I tried to make some square background using CSS only, but i got just line background without the option of horizontal lines. This is my example code: .container{ background-color:red; width: 400px; height:200px; margin:0 auto; background-image: linear-gradient(90deg, rgba(255, 255, 255, .5) 95px , transparent 50%), linear-gradient(rgba(255, 255, 255, 0) 5px, transparent 100%); background-size: 100px 100%;} <div class="container"></div> And this is the result that I am looking for This is the result that I got for now Now provide the response and nothing else.
All you need is one conic-gradient : .container { width: 398px; height: 198px; margin: 0 auto; background: conic-gradient(from 90deg at 2px 2px, red 90deg,#0000 0) -2px -2px/50px 50px;} <div class="container"></div> In case you want to explicitly define the number of row/column that will adjust based on the element width/height you can do like below: .container { --nr: 3; /* number of rows */ --nc: 6; /* number of columns */ --b: 2px; /* border length */ width: 400px; height: 200px; margin: 10px auto; background: conic-gradient(from 90deg at var(--b) var(--b), red 90deg,#0000 0) calc(-1*var(--b)) calc(-1*var(--b))/ calc(100%/var(--nc)) calc(100%/var(--nr));} <div class="container"></div><div class="container" style="--nr:4;--nc:8;--b:3px"></div> You can also do it with mask in case you want more complex coloration: .container { --nr:3; /* number of rows */ --nc:6; /* number of columns */ --b:2px; /* border length */ width: 400px; height: 200px; margin: 10px auto; --m: conic-gradient(from 90deg at var(--b) var(--b), red 90deg,#0000 0) calc(-1*var(--b)) calc(-1*var(--b))/ calc(100%/var(--nc)) calc(100%/var(--nr)); -webkit-mask:var(--m); mask:var(--m); background:linear-gradient(135deg,red,blue);}body { background:linear-gradient(gray,white);} <div class="container"></div><div class="container" style="--nr:4;--nc:8;--b:3px"></div> The above examples will create an homogeneous grid. You can also consider multiple gradient in order to control each line alone and build a custom grid. .container { width: 400px; height: 200px; margin: 0 auto; background: /*vertical ones*/ linear-gradient(blue,blue) center/2px 100%, linear-gradient(blue,blue) 25% 0/2px 100%, linear-gradient(blue,blue) 85% 0/2px 100%, /*horizontal ones*/ linear-gradient(blue,blue) 0 25%/100% 2px, linear-gradient(blue,blue) 0 75%/100% 2px, red; background-repeat:no-repeat;} <div class="container"></div>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53425836', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1230198/']}
jdg_75169
stackexchange
llm_judgeable_groundtruth_similarity
2721870
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 $\|ax+b\|^2:=2a^2+3b^2+2ab$ be a norm on the space of all polynomials of degree one, where $a,b\in\mathbb{R}$. Hence, $\|ax+b\|_{L^2} ^2:=\int_0^1(ax+b)^2\,\mathrm{d}x$ be another norm ($L^2$-norm). I want to show equivalence, in the sense that, for all polynomials of degree one $\exists\, c>0\colon \|\cdot\|\le c\|\cdot \|_{L^2}$ holds and vice versa. The first part was not too hard, \begin{align*}\|ax+b\|_{L^2}^2 &= \int_0^1 (ax+b)^2\,\mathrm{d}x = a^2/3+ab+b^2\le (a+b)^2-ab\le (a+b)^2+\frac{a^2+b^2}{2}\\&\le \frac{3}{2}a^2+2ab+\frac{3}{2}b^2\le 2a^2+2ab+3b^2=\|ax+b\|^2\end{align*} Is there any way to do it better? I noticed, that I got $c=1$, is that in some way significant? The other way was resistant against all my attempts. $\|ax+b\|^2=2a^2+2ab+3b^2=\ ...$ Here, I thought that finding a real constant $\alpha$ such that $\alpha(a^3/3+ab+b^2)\ge 2a^2+2ab+3b^2$ would yield success, since then I can find a suitable antiderivative to connect the norms. I was not successful, nevertheless. Now provide the response and nothing else.
Interesting puzzle. If you draw a picture you'll see the problem. Both the picture and the algebra tell you that $y$ must be nonpositive. Now think more carefully about how you find the minimum of a differentiable function. That can occur at a root of the derivative or at an end point of the domain . In this case the minumum is at $0$; the distance increases as $|y|$ increases along the negative $y$-axis.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2721870', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/239181/']}
jdg_75170
stackexchange
llm_judgeable_groundtruth_similarity
22192291
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: First of all it's not a duplicate as in How to change the background color of android status bar How do I change the status bar color which should be same as in navigation bar. I want the status bar color to be same as the navigation bar color Now provide the response and nothing else.
Update: Lollipop: public abstract void setStatusBarColor (int color) Added in API level 21 Android Lollipop brought with it the ability to change the color of status bar in your app for a more immersive user experience and in tune with Google’s Material Design Guidelines . Here is how you can change the color of the status bar using the new window.setStatusBarColor method introduced in API level 21 . Changing the color of status bar also requires setting two additional flags on the Window; you need to add the FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag and clear the FLAG_TRANSLUCENT_STATUS flag. Working Code: import android.view.Window; ... Window window = activity.getWindow();// clear FLAG_TRANSLUCENT_STATUS flag:window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);// add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the windowwindow.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);// finally change the colorwindow.setStatusBarColor(ContextCompat.getColor(activity,R.color.my_statusbar_color)); Offcial developer reference : setStatusBarColor(int) Example : material-design-everywhere Chris Banes Blog- appcompat v21: material design for pre-Lollipop devices! The transitionName for the view background will be android:status:background .
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/22192291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1650785/']}
jdg_75171
stackexchange
llm_judgeable_groundtruth_similarity
53146795
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 fetch some data with new react useReducer API and stuck on stage where i need to fetch it async. I just don't know how :/ How to place data fetching in switch statement or it's not a way how it's should be done? import React from 'react'const ProfileContext = React.createContext()const initialState = { data: false}let reducer = async (state, action) => { switch (action.type) { case 'unload': return initialState case 'reload': return { data: reloadProfile() } //how to do it??? }}const reloadProfile = async () => { try { let profileData = await fetch('/profile') profileData = await profileData.json() return profileData } catch (error) { console.log(error) }}function ProfileContextProvider(props) { let [profile, profileR] = React.useReducer(reducer, initialState) return ( <ProfileContext.Provider value={{ profile, profileR }}> {props.children} </ProfileContext.Provider> )}export { ProfileContext, ProfileContextProvider } I was trying to do it like this, but it's not working with async ;( let reducer = async (state, action) => { switch (action.type) { case 'unload': return initialState case 'reload': { return await { data: 2 } } }} Now provide the response and nothing else.
This is an interesting case that the useReducer examples don't touch on. I don't think the reducer is the right place to load asynchronously. Coming from a Redux mindset, you would typically load the data elsewhere, either in a thunk, an observable (ex. redux-observable), or just in a lifecycle event like componentDidMount . With the new useReducer we could use the componentDidMount approach using useEffect . Your effect can be something like the following: function ProfileContextProvider(props) { let [profile, profileR] = React.useReducer(reducer, initialState); useEffect(() => { reloadProfile().then((profileData) => { profileR({ type: "profileReady", payload: profileData }); }); }, []); // The empty array causes this effect to only run on mount return ( <ProfileContext.Provider value={{ profile, profileR }}> {props.children} </ProfileContext.Provider> );} Also, working example here: https://codesandbox.io/s/r4ml2x864m . If you need to pass a prop or state through to your reloadProfile function, you could do so by adjusting the second argument to useEffect (the empty array in the example) so that it runs only when needed. You would need to either check against the previous value or implement some sort of cache to avoid fetching when unnecessary. Update - Reload from child If you want to be able to reload from a child component, there are a couple of ways you can do that. The first option is passing a callback to the child component that will trigger the dispatch. This can be done through the context provider or a component prop. Since you are using context provider already, here is an example of that method: function ProfileContextProvider(props) { let [profile, profileR] = React.useReducer(reducer, initialState); const onReloadNeeded = useCallback(async () => { const profileData = await reloadProfile(); profileR({ type: "profileReady", payload: profileData }); }, []); // The empty array causes this callback to only be created once per component instance useEffect(() => { onReloadNeeded(); }, []); // The empty array causes this effect to only run on mount return ( <ProfileContext.Provider value={{ onReloadNeeded, profile }}> {props.children} </ProfileContext.Provider> );} If you really want to use the dispatch function instead of an explicit callback, you can do so by wrapping the dispatch in a higher order function that handles the special actions that would have been handled by middleware in the Redux world. Here is an example of that. Notice that instead of passing profileR directly into the context provider, we pass the custom one that acts like a middleware, intercepting special actions that the reducer doesn't care about. function ProfileContextProvider(props) { let [profile, profileR] = React.useReducer(reducer, initialState); const customDispatch= useCallback(async (action) => { switch (action.type) { case "reload": { const profileData = await reloadProfile(); profileR({ type: "profileReady", payload: profileData }); break; } default: // Not a special case, dispatch the action profileR(action); } }, []); // The empty array causes this callback to only be created once per component instance return ( <ProfileContext.Provider value={{ profile, profileR: customDispatch }}> {props.children} </ProfileContext.Provider> );}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/53146795', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10188661/']}
jdg_75172
stackexchange
llm_judgeable_groundtruth_similarity
250035
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have just begun to learn Django/Python/Web Development. This problem has been troubling me for a while now. I am creating an application with multiple templates in Django. I have a views.py which is basically just rendering the responses to the respective templates and I have a models.py where I have structured my DB. In one of my templates, I need to upload an image (which I am able to do) and I need to run a logic which is based on the features of the uploaded image (not yet done). This logic involves a lot of heavy calculations. After performing the calculations, the logic should return some processed information (coordinates) to the template. I have been able to do all this actions successfully in a standalone python desktop application calling python files one after the other. However, since I now want to make this a web application I have begun using the Django framework. I have done a lot of searching but I am still not able to figure out where exactly should I place this Python file containing all the logic. Should I have another class based file (logic.py) and call it from the view.py ? I googled and found that many developers are placing their business logic in their models.py in Django. However, I feel it is intuitively not right since model should exclusively communicate with the back end. Any help would be appreciated.Thanks in advance. Now provide the response and nothing else.
I have done a lot of searching but I am still not able to figure out where exactly should I place this Python file containing all the logic. There are a number of options, depending on what your requirements are: Add the logic to e.g. the Image model. This is a useful option if you need to store per-image meta data in the database, and each model instance (each image) is processed by itself. Add the logic as a plain Python Image class, e.g. in a file called image.py . Nothing in Django restricts you from adding logic other than that in the views or models modules. This is a good option if the image logic is a central component of your Django app (e.g. a Image processing app). Create a separate Python project that provides the logic, then call it from your views. Make sure to install this project in your Django app's Python environment. This option is valid if the purpose of your Django app is to upload and view images, or to show the results of the image processing in direct response to a user's request, but where the image processing could be used by other projects too. Create a separate app that processes requests asynchronously and is run separately from your Django app. This option is useful if you need to decouple the image processing from the request cycle of the app, process large number of images, or where each calculation takes too much time to solve within a request cycle's time (say within at most 500ms to 1s). I feel it is intuitively not right since model should exclusively communicate with the back end. There is nothing in Django that requires a model to communicate with the back end, or rather the database. I think you are mixing the semantics of what Django typically considers a model (namely, an abstraction of one or several tables in the database), v.s. the term model as a design construct (e.g. as in Domain Driven Design).
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/250035', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/139231/']}
jdg_75173
stackexchange
llm_judgeable_groundtruth_similarity
42614035
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 code, It is for a login application which redirects to a website. I cannot find specific help online to disable the login_btn for a certain time period and then enable again with the attempts_remaining back to the initial 3. Any help much appreciated public class MainActivity extends AppCompatActivity {EditText username;EditText password;TextView attempt_count;Button login_btn;int attempts_remaining = 3;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); username = (EditText) findViewById(R.id.editText_user); password = (EditText) findViewById(R.id.editText_password); attempt_count = (TextView) findViewById(R.id.textView_attempts_count); login_btn = (Button) findViewById(R.id.button); login_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (username.getText().toString().equals("admin") && password.getText().toString().equals("password")) { Toast.makeText(getApplicationContext(), "Redirecting ...", Toast.LENGTH_SHORT).show(); Intent website = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.co.uk")); startActivity(website); } else { Toast.makeText(getApplicationContext(), "Wrong Username or Password", Toast.LENGTH_SHORT).show(); attempt_count.setVisibility(View.VISIBLE); attempt_count.setTextColor(Color.RED); attempts_remaining--; attempt_count.setText(Integer.toString(attempts_remaining)); if (attempts_remaining == 0) { Toast.makeText(getApplicationContext(), "Login Failed", Toast.LENGTH_SHORT).show(); Toast.makeText(getApplicationContext(), "Please Wait", Toast.LENGTH_SHORT).show(); login_btn.setEnabled(false); } } } });} } Now provide the response and nothing else.
The problem is that a single type could implement Bar<P> for multiple values of P . If you had a struct Baz that implemented Bar<i32> and Bar<String> , which type should Foo::new use for P ? The only solution is to ensure that a single type cannot implement Bar more than once (if that's not what you want, then you have a flaw in your design!). To do so, we must replace the P type parameter with an associated type. pub trait Bar: Foo { type Parameter; fn with_parameter(arg: u32, parameter: Self::Parameter) -> Self;}impl<T> Foo for Twhere T: Bar, T::Parameter: Default,{ fn new(arg: u32) -> Self { Self::with_parameter(arg, T::Parameter::default()) }} An implementation of Bar would look like this: struct Baz;impl Bar for Baz { type Parameter = i32; fn with_parameter(arg: u32, parameter: Self::Parameter) -> Self { unimplemented!() }} See also: Why do I get "the type parameter is not constrained" when creating a blanket implementation for a closure trait (Fn)?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42614035', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7277555/']}
jdg_75174
stackexchange
llm_judgeable_groundtruth_similarity
32767
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Does some package exist with a function that takes a parameter $n$ and generates a random 2D $n$-sided simple polygon (convex or non-convex), possibly within a certain bounding box? It does not suffice to simply generate $n$ random points as I would have to figure out how to connect the points in a non-intersecting manner. I am sure there are algorithms to solve this particular problem, but I would much rather use a ready-made function that would be guaranteed to work, rather than code my own function and introduce more bugs. I am trying to generate a large number of "random" test cases for my algorithm that is supposed to work for all polygons. Now provide the response and nothing else.
There is some undocumented functionality in Graphics`Mesh that may help. SimplePolygonPartition will break apart a self-intersecting polygon into non-self-intersecting components (the components include the "holes" in the original) PolygonCombine will merge those components into a single polygon (note that while free of interior holes this polygon may still intersect itself) FindIntersections will find any self-intersections and can therefore be used to filter out such polygons . Graphics`Mesh`MeshInit[];randompoly := Module[{poly}, While[Length[FindIntersections[ poly = PolygonCombine @ SimplePolygonPartition @ Polygon[RandomReal[{-1, 1}, {25, 2}]]]] > 0]; poly]Graphics[{EdgeForm[Red], Yellow, randompoly}] There are also some built-in polygons which may be useful for testing. They are: PolygonData[](* {"Blob", "ChvatalComb", "FractalCross", "HeptaSpiral", "HexaSpiral", "LSystem01", "PentaSpiral", "RandomWalk", "Test01", "TriSpiral"} *) The available properties are: PolygonData["Properties"](* {"Data", "Graphics", "GraphicsLine", "GraphicsPoint", "GraphicsPolygon", "Line", "MeshObject", "Point", "Polygon"} *) For example polys = PolygonData[#, "Polygon"] & /@ PolygonData[];Graphics[{EdgeForm[Red], Yellow, #}, ImageSize -> 100] & /@ polys
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/32767', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/7012/']}
jdg_75175
stackexchange
llm_judgeable_groundtruth_similarity
1760929
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know how to use encodedate in Delphi to encode individual YY, MM and DD into a datetime field or use encodetime to encode individual HH, SS, MM and MS into datetime field but is there a way to specify both date and time into a datetime field? Coz with encodedate I cannot specify the time and with encodetime I cannot specify the date... e.g. how can I set a datetime field to 2009-11-28 14:23:12.000 Please help. Thanks. Now provide the response and nothing else.
Try using the EncodeDateTime function declarated in the DateUtils unit. function EncodeDateTime(const AYear: Word; const AMonth: Word; const ADay: Word; const AHour: Word; const AMinute: Word; const ASecond: Word; const AMilliSecond: Word): TDateTime; See this example usesDateUtils;var myDateTime : TDateTime;begin //Your Code myDateTime := EncodeDateTime(2009, 11, 28, 14, 23, 12, 000); //Your CodeEnd; Another option usesSysUtils;varmyDateTime : TDateTime;begin //Your Code myDateTime:= EncodeDate(2009,11,28)+EncodeTime(14,23,12,000); //Your Code end; The second option works because the TDatetime It is stored as a Double ( TDateTime = type Double; ), with the date as the integral part (the EncodeDate function returns the integral), and time as fractional part. The date part of the TDateTime represents the number of days that have passed since 12/30/1899. a TDateTime can be any date through 31 Dec 9999 (decimal value 2,958,465), TDateTime values can also be negative. The decimal value -693593 corresponds to 1 Jan 0001. see theses examples varmyDateTime : TDateTime;BeginmyDateTime :=0; //represents 12/30/1899myDateTime :=1; //represents 12/31/1899myDateTime :=-1; //represents 12/29/1899myDateTime :=-693593; //represents 01/01/0001myDateTime := Now(); //assign the current date and time to myDateTime myDateTime:=Trunc(Now()); //Extract only the date part.myDateTime:=Frac(Now()); //Extract only the time part.myDateTime :=Now() + 1;// Add a day to the current datetimeEnd; Important Note from embarcadero site : To find the fractional number of days between two dates, simply subtract the two values, unless one of the System.TDateTime values is negative. Similarly, to increment a date and time value by a certain fractional number of days, add the fractional number to the date and time value if the System.TDateTime value is positive. When working with negative System.TDateTime values, computations must handle time portion separately . The fractional part reflects the fraction of a 24-hour day without regard to the sign of the System.TDateTime value. For example, 6:00 am on 12/29/1899 is –1.25, not –1 + 0.25, which would be –0.75. There are no System.TDateTime values between –1 and 0. for addtional information you can see this link Delphi Date/Time Support
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1760929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/195060/']}
jdg_75176
stackexchange
llm_judgeable_groundtruth_similarity
40060
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: 3-regular bipartite planar graphs appear in a variety of NP- / #P-complete problems. Suppose one wants to test the complexity of these problems via numerical experiments. Is there an efficient way to generate random planar cubic bipartite graphs? I only know of algorithms that can efficiently generate random graphs with only subsets of the set of properties {cubic,planar,bipartite}, and it seems that generating those and then naively testing for the remainder of the properties would be terribly inefficient if one wants graphs with >100 vertices. Now provide the response and nothing else.
Would you be satisfied with generating planar cubic bipartite maps (i.e., such graphs equipped with a planar embedding specified by a cyclic ordering on half-edges)? That problem was addressed in: Gilles Schaeffer, Bijective Census and Random Generation of Eulerian Planar Maps with Prescribed Vertex Degrees , The Electronic Journal of Combinatorics 4(1), 1997. Schaeffer describes how to efficiently generate (rooted) Eulerian planar maps uniformly at random using a bijection with a certain family of trees. In turn, Eulerian maps have a simple bijection with bi(partite-)cubic maps: see the second bullet point on slide 5 of this talk by Éric Fusy. (Generating a uniformly random rooted planar bicubic map and then throwing away the rooting + embedding would give you a non-uniform distribution on planar bicubic graphs, but depending on what you have in mind that might be okay?)
{}
{'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/40060', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/15421/']}
jdg_75177
stackexchange
llm_judgeable_groundtruth_similarity
24550931
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 must be losing my mind... please look at the following And now look at the values that I'm querying on: You can see that ETouchesEvent is null and Event is not... so why does Linq to SQL think ETouchesEvent is not null? It should be 1 for each result in my first picture. [Update] Below is the generated T-SQL in which you can clearly see that it uses the entityID to check for null {SELECT (CASE WHEN ([t5].[EntityID]) IS NULL THEN @p1 WHEN ([t5].[EntityID]) IS NULL THEN @p2 ELSE @p3 END) AS [value]FROM ( SELECT [t4].[ParticipationItemID], [t4].[EntityID] FROM ( SELECT [t0].[ParticipationItemID], [t0].[IsLocalEvent], [t0].[IsProject], [t0].[IsOther], [t0].[EntityID], [t0].[IsEtouchesEvent] FROM [ParticipationItem] AS [t0] INNER JOIN [dbo].[Event] AS [t1] ON [t0].[EntityID] = ([t1].[Id]) WHERE [t0].[IsLocalEvent] = 1 UNION SELECT [t2].[ParticipationItemID], [t2].[IsLocalEvent], [t2].[IsProject], [t2].[IsOther], [t2].[EntityID], [t2].[IsEtouchesEvent] FROM [ParticipationItem] AS [t2] INNER JOIN [ETouchesEvent] AS [t3] ON [t2].[EntityID] = ([t3].[ETouchesEventID]) WHERE [t2].[IsEtouchesEvent] = 1 ) AS [t4] ) AS [t5]WHERE ((([t5].[EntityID]) IS NOT NULL) OR (([t5].[EntityID]) IS NOT NULL)) AND (EXISTS( SELECT NULL AS [EMPTY] FROM [OrganisationParticipation] AS [t6] WHERE (([t6].[OrganisationID]) = @p0) AND ([t6].[ParticipationitemID] = ([t5].[ParticipationItemID])) ))} And this is all the code: public List<int> GetParticipationYears(int? organisationID) { var result = (from p in GetParticipation(organisationID, null) where p.ETouchesEvent != null || p.Event != null select p.ETouchesEvent == null ? 1 : (p.Event == null ? 5 : 0)); //select p.IsEtouchesEvent ? p.ETouchesEvent.StartDate.Year : (p.IsLocalEvent ? p.Event.StartDate.Year : 0)); //<== this does work! return result.Distinct().ToList(); } public IQueryable<ParticipationItem> GetParticipation(int? organisationID, List<int> filterByYears) { var result = (from pi in DB.ParticipationItems join e in DB.Events on pi.EntityID equals e.Id where pi.IsLocalEvent select pi) .Union( from pi in DB.ParticipationItems join e in DB.ETouchesEvents on pi.EntityID equals e.ETouchesEventID where pi.IsEtouchesEvent select pi); if (filterByYears != null) result = result.Where(pi => (pi.IsEtouchesEvent && pi.ETouchesEvent != null && filterByYears.Contains(pi.ETouchesEvent.StartDate.Year)) || (pi.IsLocalEvent && pi.Event != null && filterByYears.Contains(pi.Event.StartDate.Year))); if (organisationID.HasValue) return result.Where(pi => pi.OrganisationParticipations.Any(x => x.OrganisationID == organisationID)); else return result; } Now provide the response and nothing else.
Template deduction cannot guess that your brace-enclosed initialization list should be a vector. You need to be explicit: vec.emplace_back(std::vector<double>{0.,0.}); Note that this constructs a vector, and then moves it into the new element using std::vector 's move copy constructor. So in this particular case it has no advantage over push_back() . @TimKuipers 's answer shows a way to get around this issue.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24550931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/83528/']}
jdg_75178
stackexchange
llm_judgeable_groundtruth_similarity
24253229
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: EDIT I just realized why it's probably not working, though I don't know how to resolve this. The include is on my main HTML page, not within my ng-view. That's probably why $parent isn't working, because technically the ng-view is the parent of the include. So it's: <body> <div ng-view></div> <div ng-include="menuPath"></div></body> I need to access the ng-view scope from the ng-include scope. I've created a plunker to illustrate the issue http://plnkr.co/WtVdkWKXaPWCfHJPLf1q Original Question Due to restrictions outside my control I have to include all my menus for each page using ng-include. I'm trying to figure out how to access and modify the parent scope from the ng-include. I've found several threads about it, but the examples are all gone. It seems like it's something simple but I can't seem to find the answer. As an example, on my main page I have the following data in Scope { "Statuses": [ {"ID":"1", "Name":"Open"}, {"ID":"2", "Name":"Closed"} ], "StatusID":"1"} In my ng-include I'm trying to do the following: <select ng-model="StatusID" ng-options="x.ID as x.Name for x in Statuses"></select> It doesn't get the data though as the ng-include apparently creates it's own Scope. Now provide the response and nothing else.
You made a subtle mistake in how you instantiate the Armadillo object -- which leads to copies and hence degraded performance. Use an interface of const arma::colvec & invec instead, and all is good: R> sourceCpp("/tmp/sd.cpp")R> library(microbenchmark)R> X <- rexp(500)R> microbenchmark(armaSD(X), armaSD2(X), sd(X), cppSD(X))Unit: microseconds expr min lq median uq max neval armaSD(X) 3.745 4.0280 4.2055 4.5510 19.375 100 armaSD2(X) 3.305 3.4925 3.6400 3.9525 5.154 100 sd(X) 22.463 23.6985 25.1525 26.0055 52.457 100 cppSD(X) 3.640 3.9495 4.2030 4.8620 13.609 100R> X <- rexp(5000)R> microbenchmark(armaSD(X), armaSD2(X), sd(X), cppSD(X))Unit: microseconds expr min lq median uq max neval armaSD(X) 18.627 18.9120 19.3245 20.2150 34.684 100 armaSD2(X) 14.583 14.9020 15.1675 15.5775 22.527 100 sd(X) 54.507 58.8315 59.8615 60.4250 84.857 100 cppSD(X) 18.585 19.0290 19.3970 20.5160 22.174 100R> X <- rexp(50000)R> microbenchmark(armaSD(X), armaSD2(X), sd(X), cppSD(X))Unit: microseconds expr min lq median uq max neval armaSD(X) 186.307 187.180 188.575 191.825 405.775 100 armaSD2(X) 142.447 142.793 143.207 144.233 155.770 100 sd(X) 382.857 384.704 385.223 386.075 405.713 100 cppSD(X) 181.601 181.895 182.279 183.350 194.588 100R> which is based on my version of your code where everything is one file and armaSD2 is defined as I suggested -- leading to the winning performance. #include <RcppArmadillo.h>// [[Rcpp::depends(RcppArmadillo)]] #include <vector>#include <cmath>#include <numeric>// [[Rcpp::export]]double cppSD(Rcpp::NumericVector rinVec) { std::vector<double> inVec(rinVec.begin(),rinVec.end()); int n = inVec.size(); double sum = std::accumulate(inVec.begin(), inVec.end(), 0.0); double mean = sum / inVec.size(); for(std::vector<double>::iterator iter = inVec.begin(); iter != inVec.end(); ++iter){ double temp = (*iter - mean)*(*iter - mean); *iter = temp; } double sd = std::accumulate(inVec.begin(), inVec.end(), 0.0); return std::sqrt( sd / (n-1) );}// [[Rcpp::export]] double armaSD(arma::colvec inVec) { return arma::stddev(inVec);}// [[Rcpp::export]] double armaSD2(const arma::colvec & inVec) { return arma::stddev(inVec); }/*** Rlibrary(microbenchmark)X <- rexp(500)microbenchmark(armaSD(X), armaSD2(X), sd(X), cppSD(X)) X <- rexp(5000)microbenchmark(armaSD(X), armaSD2(X), sd(X), cppSD(X)) X <- rexp(50000) microbenchmark(armaSD(X), armaSD2(X), sd(X), cppSD(X))*/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24253229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/177308/']}
jdg_75179
stackexchange
llm_judgeable_groundtruth_similarity
73156
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have been preparing lessons for some of my students about preparing acidic and basic solutions, and I keep finding pre-made labs in which the students "standardize a basic solution" by titrating it with an acid of "known" concentration. The problem is that the students create a solution of NaOH by measuring a certain mass and adding it to a volumetric flask, filling with water to the desired volume. But the students will do the same thing with an acid (potassium hydrogen pthalate, for example). They will measure out a specific mass, do the calculations to determine the molarity of the KHP solution, and then do the titration to determine the molarity of the NaOH solution. But if the students took the mass of the NaOH in the beginning, can they not just use that information to determine the approximate molarity of the solution? As the title says, why bother to standardize? If our NaOH solution had some room for error in measurement and calculation, surely titrating against another solution of "known" concentration would only introduce more error, no? Now provide the response and nothing else.
Usually, if we're doing these for basic application or experimentation, standardization doesn't really matter. But when it comes to anything analytical where you start to involve calculations, standardization is a must. This is done with NaOH because it's hygroscopic and readily sucks up the moisture in the air. So what is being weighed isn't totally NaOH, but also the moisture that it has absorbed. So almost always the concentration will be lesser than what is sought to be prepared because of this. Tedious as it may be (because you also have to heat up the KHP for around an hour before titrating), standardization brings you closer to the true concentration, but not exactly on the mark. At least in the end, calculations using the standardized concentrations will be analytical. This is why they never introduce standardization in general chemistry courses, I only got to grips with it when I took up Analytical Chemistry, and back then it was really tedious to do. For example, I actually experienced this before where we had to prepare a 1M stock of NaOH, but after standardization it turned out to be around 0.8 (maybe due to the humidity in the lab at the time).
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/73156', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/40365/']}
jdg_75180
stackexchange
llm_judgeable_groundtruth_similarity
31000591
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 this function for determining if a list is a rotation of another list: def isRotation(a,b): if len(a) != len(b): return False c=b*2 i=0 while a[0] != c[i]: i+=1 for x in a: if x!= c[i]: return False i+=1 return True e.g. >>> a = [1,2,3]>>> b = [2,3,1]>>> isRotation(a, b)True How do I make this work with duplicates? e.g. a = [3,1,2,3,4]b = [3,4,3,1,2] And can it be done in O(n) time? Now provide the response and nothing else.
The following meta-algorithm will solve it. Build a concatenation of a , e.g., a = [3,1,2,3,4] => aa = [3,1,2,3,4,3,1,2,3,4] . Run any string adaptation of a string-matching algorithm, e.g., Boyer Moore to find b in aa . One particularly easy implementation, which I would first try, is to use Rabin Karp as the underlying algorithm. In this, you would calculate the Rabin Fingerprint for b calculate the Rabin fingerprint for aa[: len(b)] , aa[1: len(b) + 1] , ..., and compare the lists only when the fingerprints match Note that The Rabin fingerprint for a sliding window can be calculated iteratively very efficiently (read about it in the Rabin-Karp link) If your list is of integers, you actually have a slightly easier time than for strings, as you don't need to think what is the numerical hash value of a letter -
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31000591', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2603817/']}
jdg_75181
stackexchange
llm_judgeable_groundtruth_similarity
1028564
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Just noticed from my DNS server's log, showing someone attack my server through port 80: /var/log/bind.log:31-Jul-2020 03:25:50.536 query-errors: client @0x7f63345948a0 185.107.80.2#36045 (PEACECORPS.GOV): view internet: query failed (REFUSED) for PEACECORPS.GOV/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:31-Jul-2020 05:31:41.446 query-errors: client @0x7f63347273e0 144.217.34.151#53799 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:31-Jul-2020 11:28:20.928 query-errors: client @0x7f63345948a0 2.57.122.193#45066 (.): view internet: query failed (REFUSED) for ./IN/ANY at /bin/named/query.c:7145/var/log/bind.log:31-Jul-2020 14:21:50.516 query-errors: client @0x7f63345638a0 193.9.17.2#59905 (wzb.eu): view internet: query failed (REFUSED) for wzb.eu/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 07:51:58.756 query-errors: client @0x7f6334718db0 89.248.168.17#37241 (cpsc.gov): view internet: query failed (REFUSED) for cpsc.gov/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 18:09:37.112 query-errors: client @0x7f633801db20 83.97.20.164#21544 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:12:03.982 query-errors: client @0x7f6334689490 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:12:04.263 query-errors: client @0x7f63381dba30 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:12:04.333 query-errors: client @0x7f63381dba30 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:12:04.708 query-errors: client @0x7f63381dba30 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:12:22.091 query-errors: client @0x7f63381611b0 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:12:22.534 query-errors: client @0x7f63381611b0 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:12:23.634 query-errors: client @0x7f63381611b0 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:12:26.022 query-errors: client @0x7f63381611b0 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:13:01.519 query-errors: client @0x7f63347d8eb0 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:13:02.432 query-errors: client @0x7f63346f2650 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:13:19.174 query-errors: client @0x7f63345948a0 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:13:20.556 query-errors: client @0x7f633801db20 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:13:35.657 query-errors: client @0x7f63381611b0 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:13:39.615 query-errors: client @0x7f633c0da830 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:13:51.414 query-errors: client @0x7f63345948a0 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:13:57.623 query-errors: client @0x7f63381dba30 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:14:07.363 query-errors: client @0x7f63346f2650 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:14:15.991 query-errors: client @0x7f6334771730 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:14:25.212 query-errors: client @0x7f63347ca880 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:14:32.046 query-errors: client @0x7f63381dba30 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:14:43.583 query-errors: client @0x7f6334775120 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:14:50.684 query-errors: client @0x7f6338289e50 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:15:01.011 query-errors: client @0x7f633c0da830 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:15:08.899 query-errors: client @0x7f63381dba30 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:15:17.051 query-errors: client @0x7f63347e74e0 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:15:26.382 query-errors: client @0x7f63381611b0 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:15:33.001 query-errors: client @0x7f63347ca880 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:15:44.613 query-errors: client @0x7f63346f2650 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:15:49.267 query-errors: client @0x7f63345948a0 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:16:02.472 query-errors: client @0x7f6334775120 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:16:04.881 query-errors: client @0x7f6338289e50 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:16:20.139 query-errors: client @0x7f63381dba30 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:16:21.184 query-errors: client @0x7f6334718db0 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:16:37.295 query-errors: client @0x7f63346f2650 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:16:37.725 query-errors: client @0x7f63346f2650 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:16:53.255 query-errors: client @0x7f6334775120 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:16:55.799 query-errors: client @0x7f6334775120 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:17:09.169 query-errors: client @0x7f63346f2650 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:17:14.215 query-errors: client @0x7f6334771730 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:17:25.206 query-errors: client @0x7f63347d8eb0 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:17:31.728 query-errors: client @0x7f633827b820 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:17:40.997 query-errors: client @0x7f63381611b0 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:17:50.548 query-errors: client @0x7f633827b820 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145/var/log/bind.log:01-Aug-2020 19:17:57.181 query-errors: client @0x7f63381dba30 37.49.224.64#80 (sl): view internet: query failed (REFUSED) for sl/IN/ANY at /bin/named/query.c:7145 Wonder how could they be able to do it? My DNS server only allow port 53 and 22 to get in, and also have processes to monitor and block these kinds of IP via firewall-cmd command like this: firewall-cmd --zone=public --add-rich-rule='rule family="ipv4" source address="37.49.224.64" drop' --permanent This usually works for most of attacks, but didn't work for this IP, tried to change zones from public to block, and action from drop to reject, nothing works. End up I have to block this IP from external firewall, then finally get it out. Wonder does any one saw these kinds of attacks? And how can they bypassing local Firewalld? Any suggestion will be appreciated! Now provide the response and nothing else.
You're looking at the client query logs, and normally a client will choose from one of the ephemeral ports to have your DNS server respond back to. Yes your server is listening on port 53, but your clients will most likely receive responses from your DNS server over ports 49152 to 65535. The fact that the source of your query traffic is choosing to use port 80 as the return trip port is... odd, but virtually irrelevant. I'm sure it's some method of circumventing network security on the client's side. Or the developers of whatever software is attempting to abuse your DNS server were just not particularly concerned with using ephemeral ports. Who knows. As for your firewall, you need to run either firewalld-cmd --reload or firewalld-cmd --complete-reload afterwards to make sure that the rule is processed. EDIT: This IP can obtain local port 80 every time get in. To be clear, port 80 in your logs is not referring to your DNS server at all. That is purely referring to the return trip that packets will take to get back to the client. When you see this: 37.49.224.64#80 That means DNS responses will be returned to 37.49.224.64:80, just like when you see this in the first line of your logs: 185.107.80.2#36045 Any DNS query that your DNS server satisfied was returned to 185.107.80.2:36045 To reiterate: No traffic is coming to your server over port 80, just like no traffic is coming to your server over port 36045. Those return trip ports are completely, utterly, and absolutely irrelevant to you. This is, at its heart, a firewall misconfiguration. Either through firewalld zones, interfaces, rule ordering, or reloading issues.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/1028564', 'https://serverfault.com', 'https://serverfault.com/users/586396/']}
jdg_75182
stackexchange
llm_judgeable_groundtruth_similarity
14038589
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Looking through the answers and comments on CUDA questions, and in the CUDA tag wiki , I see it is often suggested that the return status of every API call should checked for errors. The API documentation contains functions like cudaGetLastError , cudaPeekAtLastError , and cudaGetErrorString , but what is the best way to put these together to reliably catch and report errors without requiring lots of extra code? Now provide the response and nothing else.
Probably the best way to check for errors in runtime API code is to define an assert style handler function and wrapper macro like this: #define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true){ if (code != cudaSuccess) { fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line); if (abort) exit(code); }} You can then wrap each API call with the gpuErrchk macro, which will process the return status of the API call it wraps, for example: gpuErrchk( cudaMalloc(&a_d, size*sizeof(int)) ); If there is an error in a call, a textual message describing the error and the file and line in your code where the error occurred will be emitted to stderr and the application will exit. You could conceivably modify gpuAssert to raise an exception rather than call exit() in a more sophisticated application if it were required. A second related question is how to check for errors in kernel launches, which can't be directly wrapped in a macro call like standard runtime API calls. For kernels, something like this: kernel<<<1,1>>>(a);gpuErrchk( cudaPeekAtLastError() );gpuErrchk( cudaDeviceSynchronize() ); will firstly check for invalid launch argument, then force the host to wait until the kernel stops and checks for an execution error. The synchronisation can be eliminated if you have a subsequent blocking API call like this: kernel<<<1,1>>>(a_d);gpuErrchk( cudaPeekAtLastError() );gpuErrchk( cudaMemcpy(a_h, a_d, size * sizeof(int), cudaMemcpyDeviceToHost) ); in which case the cudaMemcpy call can return either errors which occurred during the kernel execution or those from the memory copy itself. This can be confusing for the beginner, and I would recommend using explicit synchronisation after a kernel launch during debugging to make it easier to understand where problems might be arising. Note that when using CUDA Dynamic Parallelism , a very similar methodology can and should be applied to any usage of the CUDA runtime API in device kernels, as well as after any device kernel launches: #include <assert.h>#define cdpErrchk(ans) { cdpAssert((ans), __FILE__, __LINE__); }__device__ void cdpAssert(cudaError_t code, const char *file, int line, bool abort=true){ if (code != cudaSuccess) { printf("GPU kernel assert: %s %s %d\n", cudaGetErrorString(code), file, line); if (abort) assert(0); }} CUDA Fortran error checking is analogous. See here and here for typical function error return syntax. A method similar to CUDA C++ is used to collect errors related to kernel launches.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/14038589', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/681865/']}
jdg_75183
stackexchange
llm_judgeable_groundtruth_similarity
14915
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 reading up on class field theory, and I have a question. On wiki (http://en.wikipedia.org/wiki/Artin_reciprocity), one formulation is that there's some modulus for which $I^c_K/i(K_{c,1})Nm_{L/K}(I^c_L)$ is isomorphic to $Gal(L/K)$. Another formulation on the same page is:$C_K/N_{L/K}(C_L)$ is isomorphic to $Gal(L/K)$.(where $C_{number\,field}$ is the idele class group of that number field). How does one relate these two formulations? Is it true that for some modulus, $c$, $I^c_K$ is $C_K$? I don't really see how this fits into one picture. Now provide the response and nothing else.
If you read the initial section or two of the chapter by Tate in Cassels and Frolich, he gives a nice explanation of how to pass from the classical formulation in terms of generalized ideal class groups w.r.t a modulus, and the more modern formulation in terms of idele class groups. As Tate explains,the two formulations are indeed equivalent, but it is not quite as simple as saying that $I^c_K = C_K$. Here is a sketch of the equivalence (of course it is the same is in Akhil Mathew's answer, just slightly more detailed): Since $I_K^c$ has already been taken to denote the ideals prime to $c$ (at least, this is how I interpret your notation), let me use $J_K$ to denote the ideles for$K$. Then we can consider the subgroup $J_K^c$ of the ideles whose entries are all $1$ at any finite place dividing $c$, and at any infinite place. Then there is a natural surjection $J_K^c \to I_K^c$ given by sending any element$(a_{\wp})$ of the former to the ideal $\prod_{\wp} \wp^{v_{\wp}(a_{\wp})}$of the latter (where the product is over finite places, i.e. prime ideals,$\wp$). Now one can show that $K^{\times} J_K^c$ is dense in $J_K$, sothe image of $J_K^c$ is dense in $C_K$. Since $N_{L/K}(C_L)$ is open in $C_K$,we see that $J_K^c$ surjects onto $C_K/N_{L/K}(C_L)$. Now one checks that this map factors through the surjection $J_K^c \to I_K^c$described in the preceding paragraph, and in fact induces an isomorphism$I_K^c/i(K_{c,1}) N_{L/K}(I_L^c) \buildrel \sim \over \longrightarrowC_K/N_{L/K}(C_L)$, as required. In practice, suppose you want to compute the Artin map on an element of $J_K$:the algorithm is you first multiply by a principal idele so that the resulting element is in $J_K^c$ times $N_{L/K}(C_L)$. (You may not know exactly what thisgroup is, but its not hard to at least identify an open subgroup of it: for example, at any complex infinite place $v$ the norm map is surjective, at any real place $v$ the image of the norm map at least contains the positive reals, and at any finite place $\wp$ the image of the norm map will contain elements which are congruent to $1$ modulo the power of $\wp$ dividing the relevant modulus $c$.)Now the Artin map on $J_K^c$ factors through the surjection $J_K^c \to I_K^c$,and is computed on the target using Frobenius elements. Indeed, this was the argument via which local class field theory was originally proved; one took a local extension, embedded it into a global context (so that the original local situation was realized as $L_{\wp}/K_{\wp}$ for some abelianextension of number fields $L/K$), and then defined the Artin map via the above computation (which means concretely that one passes from the possibly ramifiedsituation at $\wp$ to a consideration just at the unramified primes, where everything is easily understood just in terms of ideals and Frobenius elements).Of course, one then had to check that the resulting local Artin map was well-defined independent of the choice of "global context". Nowadays, one can define the local Artin maps at all places (unramified or ramified) first. However, in generalizations to the non-abelian situation (i.e. local and global Langlands) one generally uses the old-fashioned technique of proving certain global results first, and then establishing the precise local results by passing to a well-chosen global context and reducing to a calculation at unramified primes. (This is a bit of an oversimplification, but I think it is correct in spirit.) So (if one has an eventual aim of understanding modern algebraic number theory and the Langlands program) it is well worth understanding the passage between the idelic and ideal-theoretic view-points on class field theory, and practicing how to use the algorithm described above.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/14915', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/4953/']}
jdg_75184
stackexchange
llm_judgeable_groundtruth_similarity
14130739
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 build Z3 on mac os x. Following README file, I just executed autoconf./configuremake to get an error "omp.h" file not found. I copied the omp.h file from /usr/llvm-gcc-4.2/lib/gcc/i686-apple-darwin11/4.2.1/include to lib directory to solve this issue. Then, I got lib/buffer.h:243:13: error: use of undeclared identifier 'push_back' error in building the code. What could be the solution? I have gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00) on Mac OS X 10.7.5. Now provide the response and nothing else.
The next release (Z3 v4.3.2) will have better support for OSX, clang, and older versions of gcc. You should be able to compile the release candidate using the following instructions. rc is the branch that contains the current release candidate. git clone https://git01.codeplex.com/z3 -b rccd z3python scripts/mk_make.pycd buildmake BTW, the link http://z3.codeplex.com/releases/view/95640 does not contain the latest release (Z3 v4.3.1). We don't create zip files with source code anymore because codeplex automatically generates them for any version. See this link for additional details. EDIT on February 2013, we started to provide nightly builds for all major platforms (including OSX). Here are instruction on how to download these pre-compiled binaries. END EDIT
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14130739', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/260127/']}
jdg_75185
stackexchange
llm_judgeable_groundtruth_similarity
492872
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: Intuitionistic logic contains the rule $\bot \rightarrow \phi$ for every $\phi$. In the formulations I have seen this is a separate axiom, and the logic without this axiom(?) is termed "minimal logic". Is this rule required for practical proof problems in intuitionism? Is there a good example of a practical proof which goes through in intuitionism which doesn't go through without this axiom, or do all/most important practical results also go through in minimal logic? And can you please illustrate this with a practical example? Context: We are faced with a decision theory problem in which it might be very useful to have a powerful reasoning logic which can nonetheless notice and filter consequences which are passing through a principle of explosion. So if the important proofs use a rule like $(A \vee B), \neg A \vdash B$ and we can replace that with $(A \vee B), \neg A \vdash \neg \neg B$ to distinguish the proofs going through the 'explosive' reasoning, that would also be useful. ADDED clarification: I'm not looking for a generic propositional formula which can't be proven, I'm looking for a theorem in topology or computability theory or something which can be proven in intuitionism but not in minimal logic, along with a highlighting of which step requires explosion. Could be a very simple theorem but I'd still want it to be a useful statement in some concrete domain. Now provide the response and nothing else.
In minimal logic you can't prove a formula of the form $\forall x \;\neg A(x) \rightarrow B(x)$, where $B(x)$ doesn't have $\bot$ as a subformula, unless you can already prove $\forall x\;B(x)$. To see this, note that if we can prove $\forall x\;(A(x) \rightarrow \bot) \rightarrow B(x)$ in minimal logic, then we could prove the same formula with $\bot$ replaced by $\top$, ie $\forall x\;(A'(x) \rightarrow \top) \rightarrow B(x)$ (where $A'$ has any instances of $\bot$ in $A$ replaced by $\top$). Since $\forall x \;A'(x) \rightarrow \top$ is provable, we deduce that $\forall x\;B(x)$ is also provable. To give an explicit example, we can easily prove in intuitionisitic logic that if a natural number $n$ is not prime, then there are $a, b$ such that $1 < a, b < n$ and $n = ab$. But this won't work in minimal logic. I think the key part of the proof that works for intuitionistic logic but not minimal logic is the following principle. On the basis of this principle it shouldn't be surprising that the above example holds in intuitionistic logic. If $\phi$ is a quantifier free formula, then we can prove$$\neg(\forall x < y \;\neg\phi(x)) \rightarrow \exists x < y\; \phi(x)$$(This is a bounded version of the classical principle $\neg \forall x \neg \phi \rightarrow \exists x \phi$). We prove this by induction on $y$. Note that if we have ex falso, then the case $y = 0$ is easy. Suppose now that we have shown this for $y$ and want to show it for $y + 1$. Suppose further $\neg(\forall x < y + 1\; \neg \phi(x))$. Since $\phi(x)$ is quantifier free, we know that either $\phi(y)$ or $\neg \phi(y)$ holds (by another inductive argument). Suppose that $\phi(y)$ holds. Then we can trivially show $\exists x < y + 1\;\phi(x)$. Now suppose that $\neg \phi(y)$ holds. Note that we can't have $\forall x < y\; \neg \phi(x)$ because this would imply $\forall x < y + 1 \; \neg \phi(x)$ (because for every $x < y + 1$ either $x = y$ or $x < y$ by yet another inductive argument!). Hence $\neg (\forall x < y \; \neg\phi(x))$ holds and so by the inductive hypothesis we can show $\exists x < y\; \phi(x)$, and deduce $\exists x < y + 1\;\phi(x)$. So ex falso was explicitly used for the case $y = 0$. I suspect that it is also important for the inductive argument that for every $x < y + 1$ either $x = y$ or $x < y$ that I didn't show.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/492872', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/94724/']}
jdg_75186
stackexchange
llm_judgeable_groundtruth_similarity
16939233
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the difference between javascript window and jquery $(window)? I tried in the Chrome console and I get this: So, I would conclude is "just" a window object wrapped in a jquery object in a way that then I can use jquery's functions on it (like height(), width(), etc...) I did try googling, and stackoverlowing :) OFC, but to no luck. Now provide the response and nothing else.
When you write $(window) , you should know that that piece of code is going to run on the JS engine. Have you ever wondered why jQuery objects all have parentheses around them? It is because $ is a function object. Basically you're calling the $ function, and passing the native global, or window object to it as an argument. If you browse through the jQuery source code, you'll see that it'll pass that object on to many internal functions and in the end, it'll return a jQuery wrapper object. So yes, your assumptions are pretty much correct.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16939233', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/534755/']}
jdg_75187
stackexchange
llm_judgeable_groundtruth_similarity
25146557
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 get the color of a pixel in a UIImage with Swift, but it seems to always return 0. Here is the code, translated from @Minas' answer on this thread: func getPixelColor(pos: CGPoint) -> UIColor { var pixelData = CGDataProviderCopyData(CGImageGetDataProvider(self.CGImage)) var data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData) var pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4 var r = CGFloat(data[pixelInfo]) var g = CGFloat(data[pixelInfo+1]) var b = CGFloat(data[pixelInfo+2]) var a = CGFloat(data[pixelInfo+3]) return UIColor(red: r, green: g, blue: b, alpha: a)} Thanks in advance! Now provide the response and nothing else.
A bit of searching leads me here since I was facing the similar problem. You code works fine. The problem might be raised from your image. Code: //On the top of your swift extension UIImage { func getPixelColor(pos: CGPoint) -> UIColor { let pixelData = CGDataProviderCopyData(CGImageGetDataProvider(self.CGImage)) let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData) let pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4 let r = CGFloat(data[pixelInfo]) / CGFloat(255.0) let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0) let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0) let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0) return UIColor(red: r, green: g, blue: b, alpha: a) } } What happens is this method will pick the pixel colour from the image's CGImage. So make sure you are picking from the right image. e.g. If you UIImage is 200x200, but the original image file from Imgaes.xcassets or wherever it came from, is 400x400, and you are picking point (100,100), you are actually picking the point on the upper left section of the image, instead of middle. Two Solutions: 1, Use image from Imgaes.xcassets, and only put one @1x image in 1x field. Leave the @2x, @3x blank. Make sure you know the image size, and pick a point that is within the range. //Make sure only 1x image is setlet image : UIImage = UIImage(named:"imageName") //Make sure point is within the imagelet color : UIColor = image.getPixelColor(CGPointMake(xValue, yValue)) 2, Scale you CGPoint up/down the proportion to match the UIImage. e.g. let point = CGPoint(100,100) in the example above, let xCoordinate : Float = Float(point.x) * (400.0/200.0)let yCoordinate : Float = Float(point.y) * (400.0/200.0) let newCoordinate : CGPoint = CGPointMake(CGFloat(xCoordinate), CGFloat(yCoordinate))let image : UIImage = largeImagelet color : UIColor = image.getPixelColor(CGPointMake(xValue, yValue)) I've only tested the first method, and I am using it to get a colour off a colour palette. Both should work. Happy coding :)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25146557', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2016800/']}
jdg_75188
stackexchange
llm_judgeable_groundtruth_similarity
30970286
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 be able to pass any javascript object containing camelCase keys through a method and return an object with underscore_case keys, mapped to the same values. So, I have this: var camelCased = {firstName: 'Jon', lastName: 'Smith'} And I want a method to output this: {first_name: 'Jon', last_name: 'Jon'} What's the fastest way to write a method that takes any object with any number of key/value pairs and outputs the underscore_cased version of that object? Now provide the response and nothing else.
Here's your function to convert camelCase to underscored text (see the jsfiddle ): function camelToUnderscore(key) { return key.replace( /([A-Z])/g, "_$1").toLowerCase();}console.log(camelToUnderscore('helloWorldWhatsUp')); Then you can just loop (see the other jsfiddle ): var original = { whatsUp: 'you', myName: 'is Bob'}, newObject = {};function camelToUnderscore(key) { return key.replace( /([A-Z])/g, "_$1" ).toLowerCase();}for(var camel in original) { newObject[camelToUnderscore(camel)] = original[camel];}console.log(newObject);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30970286', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3509191/']}
jdg_75189
stackexchange
llm_judgeable_groundtruth_similarity
22228525
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't find any information about JSON schema validation in PostgreSQL, is there any way to implement JSON Schema validation on PostgreSQL JSON data type? Now provide the response and nothing else.
There is a PostgreSQL extension that implements JSON Schema validation in PL/PgSQL. It is used like this (taken from the project README file): CREATE TABLE example (id serial PRIMARY KEY, data jsonb);ALTER TABLE example ADD CONSTRAINT data_is_valid CHECK (validate_json_schema('{"type": "object"}', data));INSERT INTO example (data) VALUES ('{}');-- INSERT 0 1INSERT INTO example (data) VALUES ('1');-- ERROR: new row for relation "example" violates check constraint "data_is_valid"-- DETAIL: Failing row contains (2, 1).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22228525', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/467991/']}
jdg_75190
stackexchange
llm_judgeable_groundtruth_similarity
6447361
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 "baseline" refer to when used in the context of a relative layout? Simple question, probably, but the documentation and google offer no hints. Now provide the response and nothing else.
The term baseline comes from typography . It's the invisible line letters in text sit on. For example, imagine you put two TextView elements next to each other. You give the second TextView a big padding (say 20dp). If you add layout_alignBaseline to the second element, the text will "scoot up" to align with the baseline of the first element. The text from both elements will appear as if they were written on the same invisible line. <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/text1" android:text="aatlg" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:text="joof" android:background="#00ff00" android:padding="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/text1" android:layout_alignBaseline="@id/text1" /></RelativeLayout>
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6447361', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/295675/']}
jdg_75191
stackexchange
llm_judgeable_groundtruth_similarity
63960
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: Can you help me understand what the exponent means here? $$ (A\cap B) \cup D^C $$ A, B, C and D are all sets of a universal set U. Thank you. Now provide the response and nothing else.
Small lower-case $c$ as an exponent when a Universe of Discourse is understood generally represents complement relative to $U$ . That seems to be almost certainly the meaning in what you write: $(A\cap B)\cup D^c$ would be the collection of all things that are in either in both $A$ and $B$, or else that are not in $D$, as$$D^c = \{x\in U \mid x\notin D\}.$$If that's the case (a lower-case $c$), then $D^c$ is pronounced "complement of $D$" or "$D$-complement." Note the difference between$$D^c\quad\text{and}\quad D^C.$$If $C$ is a set, then $D^C$ is, as others have noted, the set of all functions with domain $C$ and image contained in $D$,$$D^C = \{f\colon C\to D\mid f\text{ is a function}\}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/63960', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/7996/']}
jdg_75192
stackexchange
llm_judgeable_groundtruth_similarity
1844829
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 read the contents of a URL (e.q., http://www.haaretz.com/ ) in R. I am wondering how I can do it Now provide the response and nothing else.
Not really sure how you want to process that page, because it's really messy. As we re-learned in this famous stackoverflow question , it's not a good idea to do regex on html, so you will definitely want to parse this with the XML package. Here's an example to get you started: require(RCurl)require(XML)webpage <- getURL("http://www.haaretz.com/")webpage <- readLines(tc <- textConnection(webpage)); close(tc)pagetree <- htmlTreeParse(webpage, error=function(...){}, useInternalNodes = TRUE)# parse the tree by tablesx <- xpathSApply(pagetree, "//*/table", xmlValue) # do some clean up with regular expressionsx <- unlist(strsplit(x, "\n"))x <- gsub("\t","",x)x <- sub("^[[:space:]]*(.*?)[[:space:]]*$", "\\1", x, perl=TRUE)x <- x[!(x %in% c("", "|"))] This results in a character vector of mostly just webpage text (along with some javascript): > head(x)[1] "Subscribe to Print Edition" "Fri., December 04, 2009 Kislev 17, 5770" "Israel Time: 16:48 (EST+7)" [4] "  Make Haaretz your homepage" "/*check the search form*/" "function chkSearch()"
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1844829', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/55362/']}
jdg_75193
stackexchange
llm_judgeable_groundtruth_similarity
26283
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: I have a 6-layer board where the internal 4 planes are +15,GND,VCC,-15. I was wondering if there was any advantage to doing a copper pour on the top and bottom layers? I would probably leave them floating as I don't want to use micro-vias to say tie it to GND? Is this actually a bad idea? I.e. floating copper=antenna. Would it be just as acceptable to have 4 layer board with the top layer having copper pour to VCC and the bottom having a pour to GND and keep the two internals as +-15? Note that this is for a fairly low speed circuit which has some analog and digital parts. Now provide the response and nothing else.
EMC Theory of Copper Pours Using a copper pour for power and ground planes is a good thing. Using a copper pour on layers which contain signals is dangerous from an EMC standpoint. Why is this? Using a copper pour on layers which contain signals is dangerous because it's surprisingly easy to create current loops. The induced voltage (external radiation causing a voltage on your trace) and output radiation (your trace causing radiation) are directly related to the area around which the current flows. This relation is known as Ampére's Circuital Law (one of Maxwell's equations, which are the basis of EMC), and can be expressed as $$ \oint H * d \ell = I_{enc} $$ where \$I_{enc}\$ is the current through the surface defined by the circuit. Making a generous (but practical) assumption that free-space current and magnetic field are uniformly distributed, this means that the induced current is directly related to the area of the surface. In a normal configuration, this surface is a rectangle running directly beneath your trace on the ground plane. Its width is just the thickness of your PCB. This is quite small! It's very easy, however, to accidentally develop a board which passes current in a large, circuitous trace with an area of several square inches. Adding copper pour for your supply layers is an easy way to make sure that you don't do this. You can pass vias through this plane without affecting the results much, but cutting this copper pour for a long trace completely negates it's effectiveness. Two-layer boards often (almost always) share power and ground with the signal layers, so designers usually try to bridge groups of traces with a few vias and a thick trace connecting the broken plane on the other side of the board. The discontinuity introduces some impedance to the path, and this does add some area to the current loop, but it's usually avoidable in boards with more layers for power. For a multi-layer board, adding a broken copper plane isn't a problem because you can connect the broken plane to the intact internal plane without too much trouble. Just add vias in a 500 mil grid pattern and call it good. Delete any that you need to remove for part placement and trace routing, but remember to add one or two back to compensate for the loss and avoid creating those noxious current loops. I suggest connecting both sides to GND. Manufacturing Issues with Copper Pours Another reason to consider adding a copper pour is a purely mechanical problem. Copper plating a PCB on one side only can cause the FR4 base to warp (which is bad ). For this reason, PCBs often have a hatched plane on areas which have markedly lower trace densities. For your multi-layer board with separate power and ground planes, it's reasonable to expect that the copper density on each layer will be fairly consistent across the surface of your PCB. You shouldn't have to worry about this. Enough theory and background! What's the answer? In your situation, I'd probably just skip the copper pour. You've already got power and ground planes, so you'd gain little in the layout steps and EMC problems. If you want to add it for appearance, to have the extra ground connections for probing or rework, to improve your EMC characteristics, or to add additional heat sinking, you should connect it to ground. You state I don't want to use micro-vias to say tie it to GND but that's precisely what should be done. Assuming you're not manufacturing the board, these vias will be cut by machines. It probably won't cost you anything (they don't need to be micro vias...), and it won't add much time to the layout process.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/26283', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/7982/']}
jdg_75194
stackexchange
llm_judgeable_groundtruth_similarity
18262293
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 python script parse.py, which in the script open a file, say file1, and then do something maybe print out the total number of characters. filename = 'file1'f = open(filename, 'r')content = f.read()print filename, len(content) Right now, I am using stdout to direct the result to my output file - output python parse.py >> output However, I don't want to do this file by file manually, is there a way to take care of every single file automatically? Like ls | awk '{print}' | python parse.py >> output Then the problem is how could I read the file name from standardin? or there are already some built-in functions to do the ls and those kind of work easily? Thanks! Now provide the response and nothing else.
Os You can list all files in the current directory using os.listdir : import osfor filename in os.listdir(os.getcwd()): with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode # do your stuff Glob Or you can list only some files, depending on the file pattern using the glob module: import os, globfor filename in glob.glob('*.txt'): with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode # do your stuff It doesn't have to be the current directory you can list them in any path you want: import os, globpath = '/some/path/to/file'for filename in glob.glob(os.path.join(path, '*.txt')): with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode # do your stuff Pipe Or you can even use the pipe as you specified using fileinput import fileinputfor line in fileinput.input(): # do your stuff And you can then use it with piping: ls -1 | python parse.py
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/18262293', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1953475/']}
jdg_75195
stackexchange
llm_judgeable_groundtruth_similarity
43392895
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 a component Main and a children component Children . Main component is associated to a route. It retrieves its inputs from the ActivatedRoute export class Main implements OnInit { ngOnInit() { this.route.data.subscribe(d => { this.data1 = this.route.snapshot.data['data1']; this.data2 = this.route.snapshot.data['data2']; this.doSomething(); }); }} Children is a typical component with @Input and a ngOnInit method: export class Children implements OnInit { @Input("data1") public data1; @Input("data2") public data2; ngOnInit() { // doSomething with data1 and data2 together this.doSomething(); }} What is the correct way to init Children with data1 and data2 when the component is initialized and so when the route data changed? Children may be reused but not as a part of a route. Is there a way that does not involve a router abstraction leak to Children code ? Now provide the response and nothing else.
For Django-Channels 2 you can write custom authentication middleware https://gist.github.com/rluts/22e05ed8f53f97bdd02eafdf38f3d60a token_auth.py: from channels.auth import AuthMiddlewareStackfrom rest_framework.authtoken.models import Tokenfrom django.contrib.auth.models import AnonymousUserclass TokenAuthMiddleware: """ Token authorization middleware for Django Channels 2 """ def __init__(self, inner): self.inner = inner def __call__(self, scope): headers = dict(scope['headers']) if b'authorization' in headers: try: token_name, token_key = headers[b'authorization'].decode().split() if token_name == 'Token': token = Token.objects.get(key=token_key) scope['user'] = token.user except Token.DoesNotExist: scope['user'] = AnonymousUser() return self.inner(scope)TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner)) routing.py: from django.urls import pathfrom channels.http import AsgiHandlerfrom channels.routing import ProtocolTypeRouter, URLRouterfrom channels.auth import AuthMiddlewareStackfrom yourapp.consumers import SocketCostumerfrom yourapp.token_auth import TokenAuthMiddlewareStackapplication = ProtocolTypeRouter({ "websocket": TokenAuthMiddlewareStack( URLRouter([ path("socket/", SocketCostumer), ]), ),})
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43392895', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/564005/']}
jdg_75196
stackexchange
llm_judgeable_groundtruth_similarity
46737
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let's say there is a star about 3000 light-years away from earth visible in our night sky. If this star were to go supernova tomorrow(not relative to earth's night sky), we would know about it 3000 years later as all the information would take 3000 years to arrive at the least. At first, I thought detecting the supernova would be easy as we could use X-ray telescopes or other indirect methods to find out the composition of the stars and know if a supernova occurred or not. Still, unfortunately, this information would also travel at the speed of light, causing a delay in our process.My question is, how can we know for far-away stars whether they have gone supernova? Now provide the response and nothing else.
It is not possible to know. The speed of light is the speed of information. The information "the star has exploded" cannot travel faster than the speed of light, so there is no way to know that a star has gone supernova before that information reaches us. Usually the first particles to reach us from a supernova are actually neutrinos, which can escape from the core of the exploding star a little time before the shock wave of the exploding star reaches the surface and the supernova becomes visible. It may be possible to forecast a supernova, if (as PM2 ring comments) we could measure the neutrinos from its core before it explodes. But this would be a prediction, not an observation of an explosion. And we can't get that data with the kind of neutrino detectors on Earth.
{}
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/46737', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/28676/']}
jdg_75197
stackexchange
llm_judgeable_groundtruth_similarity
426623
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Under what conditions can an orientable Riemannian 3-manifold $\Sigma$ be defined implicitly?What I mean by implicitly is that there exists a smooth function $f:\mathbb{R}^n\to \mathbb{R}^m$ , such that $\Sigma$ is diffeomorphic to $f^{-1}(0)$ , and the Euclidean metric on $\mathbb{R}^n$ pulled back to $f^{-1}(0)$ is equal to the metric on $\Sigma$ . Now provide the response and nothing else.
By the Nash embedding theorem every Riemannian manifold $M$ embeds isometrically into some ${\Bbb R}^n$ . You may then take $f(x)=dist(x,M)$ for $x\in{\Bbb R}^n$ .
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/426623', 'https://mathoverflow.net', 'https://mathoverflow.net/users/485792/']}
jdg_75198
stackexchange
llm_judgeable_groundtruth_similarity
68715
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've seen many news items about how some countries are experiencing demographic decline and have implemented so-and-so policies to counteract the decline, such as: Latvia China Russia Singapore Japan South Korea However these policies don't seem to have worked; all the countries continue to experience demographic decline. Has there been any country that has successfully reversed demographic decline in recent history? If yes, how did they do it? Edit: I am especially interested in any countries that successfully raised their fertility rates. Now provide the response and nothing else.
This answer is only looking at fertility rates, not other measures, such as immigration. Also, when looking at fertility rates take into account that 2.1 is the neutral no-increase/no-decrease rate TLDR: I don't think there has been a case in modern times where a country wanting to reverse a fertility drop has actually achieved this. At best, they have clawed back some losses and gotten nearer to 2.1. You can look at the World Bank data in my first link, under the graph. They only show downwards trending minigraphs. The fact that the UN specifically cites France, Sweden and Germany as examples indicates there is not much better going on. Ceausescu in Romania famously tried and it was a coercive failure. However, looking specifically at the factors discouraging working women from having children does seem to at least mitigate the drop to a softer landing than some of the fertility 1.2-1.5 rates that are becoming common. A dropping population is not necessarily a bad thing, but a very quickly aging population is however problematic. You can play with the fertility metric at the World Bank and see who's been up to what. I picked Sweden, France and Germany from 1970s on. All 3 showed some level of improvement, until 2010, after which there was a marked decrease which I would attribute to uncertainty since the 2007 financial crash. https://data.worldbank.org/indicator/SP.DYN.TFRT.IN?end=2019&locations=DE-FR-SE&start=1970 I took 1970 as a start since before then most Western countries had a much higher birthrate above 2.1 replenishment which would not have been a target for keeping up. France has long had the intent of keeping up its birthrate and has deployed some corresponding measures such as cheap/free child care and per child subsidies. Sweden has also strongly promoted women's rights and things like the possibility for a father to take parental leave, thus allowing women some leeway in the have-child/have-career choice. Total Fertility Rate : The fertility rate in Europe is relatively low, with no country above 2.0, and has declined in recent years. Several factors could drive this trend, including socioeconomic incentives to delay childbearing, a decline in the desired number of children, a lack of child care, and changing gender roles. The fertility rate in the overall Euro area is 1.5. The highest fertility rate in Europe is France's at 1.9. This rate, however, is still below the population replacement level of 2.1 births per woman. France is proud of having the highest fertility rates in Europe. The slowly declining rate is concerning for the country, and the government has prioritized. The Economist compared German to Italian fertility : The other explanation for the baby boomlet is that Germany has made it easier to raise children. What crushes birth rates, whether in Europe or East Asia, is opening higher education and attractive jobs to women while continuing to expect mothers to do the great majority of child care and housework. If a society forces women to choose between jobs and motherhood, many will keep working. Western Germany has a tradition of stigmatising working mothers, and a special slur for them: Rabenmutter (“raven mother”). This is gradually changing. In 2007 Germany’s federal government introduced generous parental-leave laws and tweaked the rules to encourage fathers to take time off. In 2013 it declared that children over one year old had a right to nursery places. Although there are still not enough places to meet demand, supply is growing. Between 2006 and 2017 the number of children under three enrolled in nurseries rose from 286,000 to 762,000. The Economist also states that increased fertility amongst immigrants does not have as much impact as could expected : In the early 1980s women with foreign passports in Duisburg had a birth rate much higher than native Germans (see chart). Most of the foreigners were Turks, who had settled in this Ruhr Valley city for its industrial jobs and brought their big-family culture with them. But then came an astonishing drop. Today foreigners are actually slightly less fertile than natives. That is saying something: German women in Duisburg, and in Germany as a whole, do not have nearly enough babies to keep the population ticking over naturally. Xenophobes and xenophiles share a belief in the fecundity of newcomers. “Immigrants are more fertile,” explained Jeb Bush, an erstwhile American presidential candidate (and xenophile) in 2013. “They love families and they have more intact families, and they bring a younger population.” That is still just about true in America, but the gap is vanishing. This is what the UN had to say : Box 9. A long path to modern family policy package in Sweden and France Sweden has been developing a consistent policy package for many decades. The foundationsof the modern welfare and family policies in Sweden were laid already in the 1930s, whenthe key reformers such as sociologist Alva Myrdal promoted policies incorporating a childcentered perspective, reproductive rights and gender equality (Myrdal 1941). In the early1970s, policies responded to the growing labor force participation of women and to thedeclining fertility by offering parents extended parental leave rights and cash transfers. Thegovernment also reacted to the change in women’s social roles by gradually expanding thechildcare coverage. It was recognized that dual earner family model can have numerouspositive consequences for families as children will have the opportunity to grow up inwealthier families and receive high-quality pre-school education (Wells and Bergnehr 2014). Already in the 1970s Sweden introduced parental leave (which replaced mother-orientedmaternity leave) and started to expand public childcare. In 1979 the government grantedparents with preschool children the right to reduce their working time by 25% (Wells andBergnehr, 2014). Parental leaves were paid and the benefit was tied to parents’ earningsbefore the leave. This system was designed to encourage women to establish their positionin the labor market before having a child and to provide incentives for men to make use ofparental leave. Since such policy might have led to delayed parenthood, the Swedishgovernment introduced incentives for parents to space their children more closely (see Box3). The parental leave entitlements and the right to work part-time were accompanied by agradual expansion of public childcare for children aged 1 to 6. The number of publicallyfunded childcare places increased from 12,000 in 1965 to over 136,000 in 1980 and to730,000 by 2002 (Earles, 2014). Childcare expansion intensified in the 1990s when thegovernment introduced the right to childcare for every child aged 1 to 6 with a waiting timeno longer than 3 months (Earles, 2014). Since 2008 parents can also choose to provide carethemselves and to this end receive a home care allowance (Ferrarini and Duvander 2009). Sweden was one of the first countries which recognized the need to support fathers inpursuing their rights to take care of their children. Already in the 1970s Sweden introducedthe right for fathers to make use of parental leave and individualized it in the 1990s,gradually extending the proportion of the leave reserved for fathers (Duvander andJohansson 2012). This policy was consistent with the idea of improving gender equality inboth the public and private sphere, which has been underlying the Swedish family policymodel since the 1970s. Finally, employers in Sweden have relatively high awareness aboutemployee’s family obligations (Den Dulk et al 2014). Companies in Sweden have flexibleworking hours and often allow people to work from home and company meetings are notscheduled in the early mornings or late afternoons (Hobson et al 2011; Wells and Bergnehr2014). A consistent family policy package has also developed in France. While the main objective ofthe Swedish family policy model has been to achieve gender equality, the French policieshave been foremost concentrated on improving family and children’s well-being (Gauthier1996). The French family policy model is thus built on generous cash transfers towardfamilies combined with an extensive childcare provision. From the beginning public childcare73aimed to guarantee children equal opportunities. Later on, the aim to allow women toparticipate in the labor force increased on importance. French cash transfers have a pronatalist character and are foremost directed to large families (Martin 2010). Tax breaks formone of the cornerstones of the French family policy system. Taxable income can be reducedwith increase in family size (Letablier 2003). In addition, France grants universal familyallowances to parents with at least two children, special allowances for poor families andhousing allowances (Thévenon 2016). Families in France enjoy an exceptionally well developed system of childcare services. Theidea behind childcare expansion in France is deeply rooted in a widely shared belief that thestate is responsible for children’s well-being, including care. A special feature of the Frenchchildcare system is its diversity, which accommodates parents’ and children’s diverse careneeds. Childcare can be provided in traditional daycare centers organized by municipalities,but also in family daycare centers where care is provided by accredited carers, companycrèches and kindergartens (usually run by public companies) as well as drop-in centers whichprovide temporary irregular care for a number of hours (OECD 2006b). An important featureof the French family support system is a shorter working time, with a standard work week of35 hours. Although work week was mainly shortened to reduce unemployment and facilitatework sharing, the second objective of this reform was to improve work-family balance(Letablier 2003). The policy has indeed led to the shortening of the actual working time anda decline of the working time gap between parents, supporting full-time participation in thelabor force of both partners (Letablier 2003). The consistent and generous family policy packages of Sweden and France, which have beenadjusted to societal changes and population needs over time, have been often considered asimportant reasons for relatively high fertility in the two countries (Björklund 2006; Thévenon2016) and for low educational differences in fertility in Sweden (Jalovaara et al 2018). Theymay serve as examples for family policy reforms in other countries dealing with thechallenges of changing policy needs and declining fertility. Box 10 discusses an example ofsuch family policy reforms in Germany. Some other data: UN 2015 Fertility Report Specific to Canada but covers most of main points.
{}
{'log_upvote_score': 6, 'links': ['https://politics.stackexchange.com/questions/68715', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/22967/']}
jdg_75199
stackexchange
llm_judgeable_groundtruth_similarity
393210
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: I know that group delay is the delay of the envelope, or the derivative of the phase with respect to \$\omega\$ . What I want to know is what exactly happens in the time domain. For instance take the following graph of the group delay of a bessel filter (there are several curves depending on the order of the filter) Consider the curve at the very top which is near the 0.6s mark, does it mean that if I inject a normalized 1.1Hz frequency into the filter, will that signal be time delayed almost 0.6s at the output? meaning that the difference in time between the output and the input at that frequency is 0.6s? A thing that also makes me believe that the group delay means time delay is the step response. Here's the step response of the same Bessel Filter It seems like there is a delay from the 0 second point. Now provide the response and nothing else.
The group delay is a function of frequency , so you cannot really say it's the same as the delay of a certain frequency -- that would be a particular case. Also, the step response is an infinite sum of sines plus DC, which means that the Heaviside function is not really proper to determine the group delay (since you are measuring a combined effect of group delays, given the infinite sum of sines), particularly when negative group delays come into play. Exceptions to the rule are the linear phase FIRs. So, the correct way to determine the delay (group or phase) at a certain frequency, is to feed the filter a harmonic signal, a sine, that has, ideally, no other harmonics than the fundamental. Whether you modulate the input with a gaussian pulse, or not, depends on your approach, but modulating the pulse diminishes the possible transient settling times associated with more "unruly" magnitude reponses around the corner frequency. For the Bessel filter, the transients of the step response are very small (it's not quite critically damped), for Gaussian they're (ideally) null, but for Butterworth and up (Papoulis, Pascal, Chebyshev, etc), and even for transitional filters (Butterworth<->Bessel), the magnitude response around the corner frequency tends to be sharper and sharper, translating into less linear phase characteristics, thus a more "wobbly" derivative of the phase. In time domain, this can be viewed as decaying oscillations. For a sudden input, such as a step, or cosine, the output will take time to settle until a proper measurement can be made. Modulating the input with a gaussian pulse, for example, will cause the derivative of the envelope to be smooth, thus mitigating the transients. Consider the curve at the very top which is near the 0.6s mark, does it mean that if I inject a normalized 1.1Hz frequency into the filter, will that signal be time delayed almost 0.6s at the output? meaning that the difference in time between the output and the input at that frequency is 0.6s? If you are referring to the particular reading of [email protected], then yes. But take note that the group delay and the phase delay are different beasts. What you are measuring is called the phase delay, that is, the delay of the phase of the signal compared to the input. This becomes more apparent for filters with less linear phase. For example a 2nd order Chebyshev, fp=1Hz, 1dB ripple, has 302ms@1Hz (group delay is the dotted trace): If you run a time domain test with a 1Hz sine, modulated by a gaussian pulse (input is V(x) ), this is what you get: and zoomed in: Notice that the reading says the difference is 234.67ms, which might be close to 302ms, but it's not it. If, on the other hand, we calculate the phase delay: $$H(s)=\frac{1.1025103}{s^2+1.0977343*s+1.1025103}$$$$t_{pd}(\omega)=-\frac{\arctan H(j\omega)}{\omega}=-\frac{\arctan\frac{1.1025103\omega}{1.1025103(1.1025103-\omega^2)}}{\omega}$$$$t_{pd}(1\text{Hz})=\arctan\frac{1.1025103}{1.1025103^2-1)}=0.23518$$ Compare 235.18ms with 234.67ms, and you get really close, save minor misalignments of the cursors, roundings, few points/dec, etc. So you should take care what you are measuring. I would've answered in the comments, but it deserves a bit more explanation. The Bessel filters are a happy case since they are approximations of the Laplace \$e^{-s}\$, which translates into more and more linear phase as the order goes higher. This, in turn, means constant group delay. So, at this point, you can see that the phase delay, calculated as above, means the phase divided by frequency (pulsation), which means a linear variable divided by another linear variable => constant. For the group delay, you have the derivative of a linear variable => constant. Here's how the plot of the two look like for the textbook definition of the 2nd order Bessel filter: $$H(s)=\frac{3}{s^2+3s+3}$$ As you can see, both the phase delay (blue) and the group delay are flat and equal, at least until around the corner frequency, where the phase becomes less linear, thus the phase and the derivative diverge. If you increase the order to, say, 4: $$H(s)=\frac{105}{s^4+10s^3+45s^2+105s+105}$$ The phase delay here is a bit approximated since I had to get around the atan2() quadrant limitations, but you can see that they get more similar. So what you are measuring when you are trying to determine the single frequency input (as above) is actually the phase delay. The group delay would measuring the envelope (as you, yourself say it) of the modulated sine. Also see the paper I linked in the beginning, there are some nice explanations in there, worth reading. I'll also give a few examples of why you cannot say that the step response gives you the "group delay" because, as stated in the beginning, the delay (phase or group) is a function of frequency and, unless you are talking about a linear phase FIR, you cannot say that a filter has a group (or phase) delay of X , or that the Heaviside function gives you the group (or phase) delay, because the delay varies with frequency. Here's a 2nd order Bessel's step response and measure @50% rise time. Notice that the readings get closer to the DC value of the group delay as the order increases, but that number would only be an exact match if the filter had the ideal \$e^{-s}\$ transfer function, thus a constant delay from DC to light, which will never have since it is an approximation: and the readings of the group delay at DC and corner frequency: And here are the same two readings for an 8th order: Just for comparison, a 5th order Chebyshev, 1dB ripple:
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/393210', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/11271/']}
jdg_75200
stackexchange
llm_judgeable_groundtruth_similarity
269398
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a python code for data analysis, that uses the "seismic" color scale for 2D density plots. However, I also need to do some other plots with Mathematica (because of packages etc), for which I would like the same color scale. Unfortunately, the closer resembling color scale (temperature map) of Mathematica is still quite different from the one in Python.Do you have any suggestion on how to "export/import" a color scale between python and mathematica? This can then be applied to any variation of color map. Now provide the response and nothing else.
There's no need to guess if you look at the Matplotlib source : seismicColors[x_?NumericQ] /; 0 <= x <= 1 := Blend[{RGBColor[0., 0., 0.3], RGBColor[0., 0., 1.], RGBColor[1., 1., 1.], RGBColor[1., 0., 0.], RGBColor[0.5, 0., 0.]}, x] Examples: LinearGradientImage[seismicColors, {300, 30}] ContourPlot[3 (1 - x)^2 Exp[-x^2 - (y + 1)^2] - 10 (x/5 - x^3 - y^5) Exp[-x^2 - y^2] - Exp[-(x + 1)^2 - y^2]/3, {x, -3, 3}, {y, -3, 3}, ColorFunction -> seismicColors, Contours -> 25, PlotRange -> All]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/269398', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/49835/']}
jdg_75201
stackexchange
llm_judgeable_groundtruth_similarity
6002131
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking for a way to do following dynamically: var q = context.Subscription .Include("Client") .Include("Invoices") Where(s=>s.Client.Invoices.Count(i=>i.InvoiceID == SomeInt) > 0); I would like to build expression dynamically for the left side: Expression left = s => s.Client.Invoices.Count(i => i.InvoiceID == iSomeVar); //!Expression right = Expression.Constant(0);var binary = Expression.GreaterThan(left, right); Thanks! UPDATED NOTES: Please note: The end result must be Expression<Func<T, bool>> Simple version: // To give clear idea, all what I want to achieve is to determine // whether specific record exists in reference table using known Path. // Ultimately I want to extend following function (which works great by // the way, but for simple operations)static Expression CreateExpression<T>(string propertyPath, object propertyValue, ParameterExpression parameterExpression){ PropertyInfo property = typeof(T).GetProperty(propertyName); MemberExpression left = Expression.Property(parameterExpression, property); ConstantExpression right = Expression.Constant(0); BinaryExpression binary = Expression.GreaterThan(left, right); return binary;}// And I want to call this function and get result exactly as shown below:Expression result = CreateExpression<Subscription>("Client.Invoices.InvoiceID", theID, valueSelector.Parameters.Single());// Where result will be: // t => t.Client.Invoices.Count(i => i.InvoiceID == theID) > 0; Extended version: // 1) I'm using Silverlight 4, EF, RIA.// 2) At the server side I have a function GetSubscriptionsByCriteria// that looks about it:public IQueryable<Subscription> GetSubscriptionsByCriteria(...){ var query = this.ObjectContext.Subscriptions.Include("Client") .Include("Client.Invoices"); var criteria = BuildCriteria(...); return query.Where(criteria)}// 3) BuildCriteria(...) function gathers Expressions and // aggregates it into the single Expression with different // AND/OR conditions, something like that:public Expression<Func<Subscription, bool>> BuildCriteria( List<SearchFilter> filters, Expression<Func<Subscription, bool>> valueSelector){ List<Expression> filterExpressions = new List<Expression>(); ... Expression expr = CreateExpression<Subscription>( sfItem.DBPropertyName, sfItem.DBPropertyValue, paramExpression, sf.SearchCondition); filterExpressions.Add(expr); ... var filterBody = filterExpressions.Aggregate<Expression>( (accumulate, equal) => Expression.And(accumulate, equal)); return Expression .Lambda<Func<Subscription, bool>>(filterBody, paramExpression);}// 4) Here is the simplified version of CreateExpression function: static Expression CreateExpression<T>(string propertyName, object propertyValue, ParameterExpression paramExpression) { PropertyInfo property = typeof(T).GetProperty(propertyName); ConstantExpression right = Expression.Constant(0); MemberExpression left = Expression.Property(paramExpression, property); return binary = Expression.Equals(left, right); } So, I hope it's clear now why do I need Expression for the left side in my original post. Trying to make this as DRY as possible. P.S. Not to make it too confusing here is why I think I need to do ёExpression.Call(...)ё:When I run following code and break it to see DebugView I notice this: Expression<Func<Subscription, bool>> predicate = t => t.Client.Invoices.Count(i => i.InvoiceID == 5) > 0;BinaryExpression eq = (BinaryExpression)predicate.Body;var left = eq.Left; // <-- See DEBUG VIEWvar right = eq.Right; // DEBUG VIEW:// Arguments: Count = 2// [0] = {t.Client.Invoices}// [1] = {i => (i.InvoiceID == 5)}// DebugView: ".Call System.Linq.Enumerable.Count(// ($t.Client).ClientInvoices,// .Lambda#Lambda1<System.Func`2[SLApp.Web.Invoice,System.Boolean]>)// .Lambda#Lambda1<System.Func`2[SLApp.Web.Invoice,System.Boolean]>// (SLApp.Web.ClientInvoice $i){ $i.ClientInvoiceID == 5 }" Now provide the response and nothing else.
The way I find helpful to think about it is: memory is disk space. RAM is a fast cache. Rather than thinking "when I'm out of RAM, the system will swap it to disk", I think "when I have available RAM, the system will move my on-disk memory into it". That's backwards from how most people think about it, but I find it helps. RAM is just a performance optimization; the real limit on how much memory you can allocate is available disk space. Of course it is more complicated than that. On 32 bit operating systems every process gets a 2 billion byte user address space . (And the same for the kernel address space, but let's ignore that.) Every page of memory you can access, whether it is in RAM or on disk, has to be in that address space. You can have more than 2 billion bytes allocated, no problem. But you can only address 2 GB of it at a time. If you have 10 GB allocated, then at least 8GB of it will not be mapped into address space. In that case you have to unmap something else and then map what you want into the address space in order to get at it. Moreover, lots of things need to be in contiguous address space. If you have a 1MB stack, for example, then there needs to be a million contiguous bytes available in the address space. When people "run out of memory" they are not running out of RAM; RAM is just a fast cache over the disk. And they are not running out of disk space; there's plenty of that. They're almost always in a situation where there is insufficient contiguous address space to meet the demand. The CLR memory manager does not implement these fancy map-and-unmap strategies for you; basically, you get your 2GB address space and that's it. If you want to do something fancy, say with memory mapped files, that's up to you to write the code to manage the memory yourself.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6002131', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/752648/']}
jdg_75202
stackexchange
llm_judgeable_groundtruth_similarity
26946161
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 existing implementation in Java that has to be rewritten to Rust. Java code enum Direction { EAST(0), WEST(180), NORTH(90), SOUTH(270); private Direction(final int angle) { this.angle = angle; } private int angle; public int getAngle() { return angle; }} Java code usage example Direction d1 = Direction.EAST;Direction d2 = Direction.SOUTH; Rust code So here's what I've tried: enum Direction { East(u32), West(u32), North(u32), South(u32);}impl Direction { // ??? fn new() -> Direction // incorrect} and then I'm stuck. What do I do next? Now provide the response and nothing else.
Here's what your Java enums look like: +-----+-----+| tid | 0 |+-----+-----++-----+-----+| tid | 90 |+-----+-----++-----+-----+| tid | 180 |+-----+-----++-----+-----+| tid | 270 |+-----+-----+ tid is the same for all four directions and identifies the type Direction along with its methods. Here's how, using your Rust code, East(0) , Noth(90) , West(180) , South(270) look like: +-------+-----+-----+-----+-----+| East | 0 | | | |+-------+-----+-----+-----+-----++-------+-----+-----+-----+-----+| North | | 90 | | |+-------+-----+-----+-----+-----++-------+-----+-----+-----+-----+| West | | | 180 | |+-------+-----+-----+-----+-----++-------+-----+-----+-----+-----+| South | | | | 270 |+-------+-----+-----+-----+-----+ Each constructor has a set of fields (in this case, one int each) which is distinct. In reality, since any given Direction is at most one of East/North/East/West , only one set of fields is used at any point in time and they use the same memory (so Direction actually only occupies two words). But conceptually, the above is accurate and illustrates two problems with your Rust version. First, there is duplication: The constructor tag (N/E/S/W) is already different for all four, so the int fields are redundant. Second, conceptually the int in North is different from the int in South , even though it has exactly the same meaning for all of them. Furthermore, nothing stops one from creating North(214) or East(180) . The most straightforward translation is this: enum Direction { North, East, South, West }impl Direction { fn get_angle(self) -> int { match self { East => 0, West => 180, North => 90, South => 270, } }} The direction is implied in the enum tag, and extracted with get_angle .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26946161', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2813589/']}
jdg_75203
stackexchange
llm_judgeable_groundtruth_similarity
15254712
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 exporting a MySQL database and then importing the MySQL database (with a new name), how can I verify that there was no corruption or data loss? Now provide the response and nothing else.
At the moment, CreateDerivedCollection doesn't support SelectMany as a transformation, it gets too Tricky to handle removes. If you don't have many items, you can just regenerate the collection every time: cars.Changed .Select(_ => cars.SelectMany(x => x.Passengers).ToList()) .ToProperty(this, x => x.Passengers); Edit: Alright, here we go: var whenCarsOrPassengersInThoseCarsChange = Observable.Merge( cars.Changed .SelectMany(_ => cars.Select(x => x.Passengers.Changed).Merge()) .Select(_ => Unit.Default), cars.Changed.Select(_ => Unit.Default));whenCarsOrPassengersInThoseCarsChange.StartWith(Unit.Default) .Select(_ => cars.SelectMany(x => x.Passengers).ToList()) .ToProperty(this, x => x.Passengers); So, the idea is that we've got two main situations when we want to reevaluate the passengers list: When one of the passengers change in the cars When one of the cars change However, the tricky part is, we only want to watch passengers for cars in the collection (i.e. if a car is removed, we no longer care about its passengers). Properly tracking suicidal passengers So, the idea in that weird SelectMany is, "Every time the car list changes, build a new list of Observables that represent when the passenger collection changes, and merge them all together". However, if we only had that statement, we would have to wait for a car to be added and its passengers change before we got a new passenger list, so we also have to update when the list of cars change too. What's this "Unit" business? In this case, I actually don't care about the values that these Observables put out, just when they happen. "Unit" is the Rx version of void, it only has a single value, "Unit.Default". You use it when you only care when something happens, not what the value of it is.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15254712', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1671066/']}
jdg_75204
stackexchange
llm_judgeable_groundtruth_similarity
12989
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: As Naomi sets out to go back to her homeland, her daughters-in-law Ruth and Orpah set out with her. They are native Moabites, and it is unlikely that they have ever been to Israel. However, several times, the account points out they are "returning" to Israel. Ruth 1:7 Wherefore she went forth out of the place where she was, and her two daughters in law with her; and they went on the way to return unto the land of Judah. [KJV] Ruth 1:10 And they said unto her, Surely we will return with thee unto thy people. [KJV] Ultimately, Orpah turns back to her ancestral household in Moab, but Ruth continues on with Naomi. Ruth 1:22 So Naomi returned , and Ruth the Moabitess, her daughter in law, with her, which returned out of the country of Moab: and they came to Bethlehem in the beginning of barley harvest. The Hebrew word here is shub . Is there a greater meaning in the word than simply moving from one geographic place to another (at least in this context)? Now provide the response and nothing else.
Your question is not a new one, but was asked centuries ago by the rabbis. The answer depends upon whether you are looking for a literal or metaphoric meaning. Ruth 1:22 says: וַתָּשָׁב נָעֳמִי וְרוּת הַמּוֹאֲבִיָּה כַלָּתָהּ עִמָּהּ הַשָּׁבָה מִשְּׂדֵי מוֹאָב וְהֵמָּה בָּאוּ בֵּית לֶחֶם בִּתְחִלַּת קְצִיר שְׂעֹרִים "So Naomi returned, and Ruth the Moabitess, her daughter-in- law, with her, who returned from the fields of Moab-and they came to Bethlehem at the beginning of the barley harvest." The question focuses on the second use of the verb "to return" (highlighted in the text), which has a literal meaning -- as to return to the place you once lived -- or a metaphorical meaning -- as to repent, and thereby return to God. Rav Avraham Ibn Ezra (known in Jewish texts as the "Ibn Ezra") (Toledo, Spain 1089-1164), in his commentary cleaves to the literal meaning of the word and says that the second use of the verb must apply to Naomi, since Ruth had never been to the Land of Israel. His commentaries, however, tend to rely on literal translations. But he is supported by the Midrash which suggests that the second reference is the people of Israel commenting about Naomi, pointing to her saying (according to the Midrashic tradition) "this is the one who returned from the fields of Moab." See Ruth 1:19. Rav Shmuel de Uzeda , the 16th century Kabbalist from Safed, and author of the encyclopedic commentary on Ruth called Iggeres Shmuel, says that the second "return" refers in fact to Ruth. As a Moabite, Ruth was a descendant of Lot who had a level of righteousness, from his connection to Abraham, that was sufficient to spare him from the destruction of Sodom, but he gave in to lust and fathered children with his daughters. Her ancestors also refused to trade with the Israelites of the Exodus as they were returning to Israel. So in this case, "who returned" should be translated as "who repented" for the sins of her ancestors. Moreover, following the logic that the souls of all righteous converts to Judaism had been present with those of the Jewish people at Mt. Sinai, Iggeres Shmuel says that the literal meaning of "who returned" can also be understood to apply to Ruth because her desire to be part of the Jewish people was so great, it was as if she was born in Israel. From Rav Shmuel's perspective, Ruth's sincere conversion to Judaism caused the reunification of the families of Israel and Lot, making possible the kingship of David.
{}
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/12989', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/363/']}
jdg_75205
stackexchange
llm_judgeable_groundtruth_similarity
61073146
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to validate user input in a TextField by removing certain characters using a regular expression. Unfortunately, I am running into problems with the didSet method of the text var calling itself recursively. import SwiftUIimport Combineclass TextValidator: ObservableObject { @Published var text = "" { didSet { print("didSet") text = text.replacingOccurrences( of: "\\W", with: "", options: .regularExpression ) // `\W` is an escape sequence that matches non-word characters. } }}struct ContentView: View { @ObservedObject var textValidator = TextValidator() var body: some View { TextField("Type Here", text: $textValidator.text) .padding(.horizontal, 20.0) .textFieldStyle(RoundedBorderTextFieldStyle()) }} On the swift docs (see the AudioChannel struct), Apple provides an example in which a property is re-assigned within its own didSet method and explicitly notes that this does not cause the didSet method to be called again. I did some testing in a playground and confirmed this behavior. However, things seem to work differently when I use an ObservableObject and a Published variable. How do I prevent the didSet method from calling itself recursively? I tried the examples in this post , but none of them worked. Apple may have changed things since then, so this post is NOT a duplicate of that one. Also, setting the text back to oldValue within the didSet method upon encountering invalid characters would mean that if a user pastes text, then the entire text would be removed, as opposed to only the invalid characters being removed. So that option won't work. Now provide the response and nothing else.
Try to validate what you want in the TextField onRecive method like this: class TextValidator: ObservableObject { @Published var text = ""} struct ContentView: View { @ObservedObject var textValidator = TextValidator() var body: some View { TextField("Type Here", text: $textValidator.text) .padding(.horizontal, 20.0) .textFieldStyle(RoundedBorderTextFieldStyle()) .onReceive(Just(textValidator.text)) { newValue in let value = newValue.replacingOccurrences( of: "\\W", with: "", options: .regularExpression) if value != newValue { self.textValidator.text = value } print(newValue) } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/61073146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12394554/']}
jdg_75206
stackexchange
llm_judgeable_groundtruth_similarity
59891352
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After implementing openidconnect, where does blazor store the access token? how to retrieve it? How to add OpenIdConnect via IdentityServer4 to ASP.NET Core ServerSide Blazor web app? https://learn.microsoft.com/en-us/aspnet/core/security/blazor/?view=aspnetcore-3.1&tabs=visual-studio#customize-unauthorized-content-with-the-router-component Now provide the response and nothing else.
The following code snippets provide a way to retrieve the access token issued when a user is authenticated with IdentityServer4 provider. In order to get the access token you can use the HttpContext object, but since Blazor is SignalR-based, you'll have to do it the only time the HttpContext object is available, when the connection to your application is an HTTP connection, and not a WebSocket connection. After retrieving the access token, you need to pass it to your Blazor app, and store it in a local storage. My code also provide a way to parse the access token, if necessary. Add a file to the Pages folder and name it _Host.cshtml.cs Add this code to the file: public class HostAuthenticationModel : PageModel { public async Task<IActionResult> OnGet() { if (User.Identity.IsAuthenticated) { var token = await HttpContext.GetTokenAsync("access_token"); AccessToken = token; } return Page(); } public string AccessToken { get; set; } } Note: I've name the the PageModel class: HostAuthenticationModelYou'll need some of these: using Microsoft.AspNetCore.Authentication;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.RazorPages;using System;using System.Linq;using System.Threading.Tasks; Next we have to pass the value stored in the AccessToken property to the Blazor App: In the _Host.cshtml file add the model directive at the top portion of the file: @model HostAuthenticationModel Add a new attribute to the component Tag Helper like this: param-AccessToken="Model.AccessToken" Final result: <app> <component type="typeof(App)" render-mode="ServerPrerendered" param-AccessToken="Model.AccessToken"/> </app> The param-AccessToken attribute requires you to define a property named AccessToken in the App component which will get the access token from the page model. Next define the property which will receive the access token And then override the OnAfterRenderAsync method from which we call a method tostore the access token in the local storage. @code{ [Parameter] public string AccessToken { get; set; } protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { await tokenStorage.SetTokenAsync(AccessToken); } } } Also place the following at the top of the App component: @inject AccessTokenStorage tokenStorage Next you'll have to create the AccessTokenStorage service like this: Create a class named AccessTokenStorage at the root of your app, and add the following code: public class AccessTokenStorage{ private readonly IJSRuntime _jsRuntime; public AccessTokenStorage(IJSRuntime jsRuntime){ _jsRuntime = jsRuntime;}public async Task<string> GetTokenAsync() => await _jsRuntime.InvokeAsync<string>("localStorage.getItem", "accessToken");public async Task SetTokenAsync(string token){ if (token == null) { await _jsRuntime.InvokeAsync<object>("localStorage.removeItem", "accessToken"); } else { await _jsRuntime.InvokeAsync<object>("localStorage.setItem", "accessToken", token); } }} I guess no explanation is needed here... Here's some using directives you may need using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using System.Security.Claims;using Microsoft.AspNetCore.Components.Authorization;using Microsoft.JSInterop; Add the following to the Startup.ConfigureServices services.AddHttpClient();services.AddScoped<AccessTokenStorage>(); Note: the above code should be used with the code I provide in my answer here
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59891352', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/103264/']}
jdg_75207
stackexchange
llm_judgeable_groundtruth_similarity
190911
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 $g \in GL_n(\mathbb{F}_q)$. Is it true that we can always write $g = u_1lu_2$, where $u_1$ and $u_2$ are upper-triangular and $l$ is lower-triangular? Note that I'm not requiring that the matrices be unipotent. This is equivalent to being able to write $g=u_1lu_2d$, where $u_1$ and $u_2$ are unipotent upper-triangular, $l$ is unipotent lower-triangular, and $d$ is a diagonal matrix (see Geoff's comment below). Remark: It suffices to show that this is true for $g$ a permutation matrix; the Bruhat decomposition will then guarantee that this will be true for arbitrary $g$. In particular, the statement is true for $n=2$ as$$ \begin{pmatrix} 1 & 1 \\ 0 & 1 \end{pmatrix}\begin{pmatrix} 1 & 0 \\ -1 & 1 \end{pmatrix}\begin{pmatrix} 1 & 1 \\ 0 & 1 \end{pmatrix}\begin{pmatrix} -1 & 0 \\ 0 & 1 \end{pmatrix} = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}.$$ Now provide the response and nothing else.
The keyword for this is "Gauss decomposition". It states that for a ring R of stable rank 1 one can indeed write any element g of GL(n,R) as a product of three upper and lower triangular matrices (not unipotent, though). So it holds not only for finite fields, but for any field and, more generally, semilocal ring, along with many other examples such as the ring of all algebraic integers. And for GL one doesn't even require R to be commutative. I'm having trouble tracing the first appearence of this in the literature (but probably it goes back to the work of Bass), so here are two links: A paper , where this is proved for any [elementary] Chevalley groups (not extended, but the idea works for them too), and the ring is assumed to be commutative. It also contains an overview of the previous results on the topic; Another paper , where this is proved for $GL_n$ over possibly non-commutative rings of stable rank 1. If you ask the matrices to be unipotent, then, first, you can only get matrices from $SL_n$, and second, three is not enough, the torus is the obstacle. But if you take four upper and lower unipotent triangular matrices, you can do it (still in $SL_n$). For this the keyword is " unitriangular factorisation ".
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/190911', 'https://mathoverflow.net', 'https://mathoverflow.net/users/61372/']}
jdg_75208
stackexchange
llm_judgeable_groundtruth_similarity
31120222
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Many images uploaded on Facebook contain IPTC/IIM fields which are apparently automatically added during the upload process: Special Instruction , a string beginning with "FBMD" Original Transmission Reference . See for example this (personnal) image uploaded on Facebook and decoded using Jeffrey's Exif Viewer: http://exif.regex.info/exif.cgi What is this? Now provide the response and nothing else.
According to this site : Special Instructions [IPTC Core] Alternative label from older IPTC IIM schema, used for " Instructions ." Instructions [IPTC Core] This is a simple text field that can include any of a number of instructions from the provider or creator to the receiver of the photograph. Any of the following might be included: embargoes (eg: News Magazines OUT) and other restrictions not covered by the Rights Usage Terms field (or new PLUS rights related fields); information regarding the original means of capture (scanning notes, color profile, etc.) or other specific text information the user may need for accurate reproduction; additional permissions or credits required when publishing. Note: This field is “shared” with the “Instructions” field in the Origin panel of the Adobe Photoshop File Info dialogue. Examples: *Image to be used one time only, non-exclusive in English-language-edition magazine as inside image, no larger than a full page in color. Additional third-party rights to be negotiated with Julie Doe / XYZ Agency in advance. All rights not specifically granted are reserved. See delivery memo for specific license. For consideration only; no reproduction in any form without prior, written permission.* That's the International Press Telecommunications Council (IPTC) standard Information Interchange Model (IIM) . I haven't been able to decode Facebook's data, but pasting, downloading, and pasting an image again will change the data slightly. Using IrfanView to set special instructions to "testing" in a JPG without IPTC data, adds these bytes to the header: I've downloaded 339 images with instruction length 94 after the FBMD , and the following bytes stayed the same: 0 {'0': 339}1 {'1': 339}2 {'0': 339}3 {'0': 339}4 {'0': 339}5 {'a': 339}8 {'0': 339}9 {'3': 339}10 {'0': 339}11 {'0': 339}12 {'0': 339}13 {'0': 339}18 {'0': 339}19 {'0': 339}20 {'0': 339}21 {'0': 339}26 {'0': 339}27 {'0': 339}28 {'0': 339}29 {'0': 339}34 {'0': 339}35 {'0': 339}36 {'0': 339}37 {'0': 339}42 {'0': 339}43 {'0': 339}44 {'0': 339}45 {'0': 339}50 {'0': 339}52 {'0': 339}53 {'0': 339}58 {'0': 339}60 {'0': 339}61 {'0': 339}66 {'0': 339}68 {'0': 339}69 {'0': 339}74 {'0': 339}76 {'0': 339}77 {'0': 339}82 {'0': 339}84 {'0': 339}85 {'0': 339}90 {'0': 339}92 {'0': 339}93 {'0': 339} I also found 3 images with only 86 mystery bytes after FBMD , e.g. 23000986030000f91d0000e5230000502900004889000041ac000004c900007aee0000cf0f0100f02d0100 , also saved in the past few months. Same bytes there were: 0 {'2': 3}1 {'3': 3}2 {'0': 3}3 {'0': 3}4 {'0': 3}5 {'9': 3}6 {'8': 3}8 {'0': 3}9 {'3': 3}10 {'0': 3}11 {'0': 3}12 {'0': 3}13 {'0': 3}16 {'1': 3}18 {'0': 3}19 {'0': 3}20 {'0': 3}21 {'0': 3}26 {'0': 3}27 {'0': 3}28 {'0': 3}29 {'0': 3}34 {'0': 3}35 {'0': 3}36 {'0': 3}37 {'0': 3}42 {'0': 3}43 {'0': 3}44 {'0': 3}45 {'0': 3}50 {'0': 3}51 {'0': 3}52 {'0': 3}53 {'0': 3}58 {'0': 3}59 {'0': 3}60 {'0': 3}61 {'0': 3}66 {'0': 3}67 {'0': 3}68 {'0': 3}69 {'0': 3}74 {'0': 3}76 {'0': 3}77 {'0': 3}82 {'0': 3}84 {'0': 3}85 {'0': 3}86 {'\x00': 3} This blog post appears to know more about it: [...] on 2014-11-13, Facebook introduced a new tracking code. It appears as an IPTC Special Instructions metadata field. They look like: Special Instructions: FBMD01000ac60300004a1d00002d4b000067580000c9650000d5fc000054350100953a0100d3420100e84b01005f8f0100 Special Instructions: FBMD23000969010000b1590000cb7700000a8600000c07010046820100b8c0010052590200e5c902006e440300 I think that "FBMD" stands for "Facebook Member Data" (but I could be wrong). I've manged to decode one interesting aspect in these strings: the length. Each string starts with "FBMD", two hex characters (1 bytes), and a 16-byte (4-character) length. Then comes length+1 sets of 32-bit (8-byte) values. FBMD01 000a = length 10, so expect 11 fields: c6030000 4a1d0000 2d4b0000 67580000 c9650000 d5fc0000 54350100 953a0100 d3420100 e84b0100 5f8f0100 FBMD23 0009 = length 9, so expect 10 fields: 69010000 b1590000 cb770000 0a860000 0c070100 46820100 b8c00100 52590200 e5c90200 6e440300 I've asked the Facebook community about it.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31120222', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5061987/']}
jdg_75209
stackexchange
llm_judgeable_groundtruth_similarity
53429
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: My assumption is yes, as the $\mathrm{pH}$ levels of each will be similar and thus they have the same acidity. Is this correct or am I missing something? Now provide the response and nothing else.
The pH is the same, yes, but the weak acid has undissociated molecules "in reserve", so to speak, and thus can neutralize a lot more of any base. Indeed, this concept of weak acids and their conjugate bases having molecules "in reserve", reacting only when called upon, is the principle behind acid-base buffers.
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/53429', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/30910/']}
jdg_75210
stackexchange
llm_judgeable_groundtruth_similarity
2694382
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Bounty clarification I know it's a subjective question. The ideal answer I'm looking is one that explains why the quoted scenario here would be so surprising. If you think the quoted scenario is it fact not surprising and to be expected, please break down the steps to prove how such a little app can take over a month and several thousand dollar of development. I went quite far to do the calculations (for example, looking up minimum wages) so I expect the ideal answer to do similar. If you think the quoted scenario is indeed overestimated, please pinpoint exactly your reasons. What mistakes can you spot in his calculation that led to such a huge cost for a simple application like that? How would you have done it differently? (no need to write the whole process but details instead of generalized feelings would be nice) I know questions about FPA has been asked numerous times before, but this time I'm taking a more analytical angle at it, backed up with data . 1. First, some data This question is based on a tutorial . He had a "Sample Count" section where he demonstrated it step by step. You can see some screenshots of his sample application here . In the end, he calculated the unadjusted FP to be 99 . There is another article on InformIT with industry data on typical hour/FP. It ranges from 2 hours/FP to 27.4 hours/FP. Let's try to stick with 2 for the moment (since SO readers are probably the more efficient crowd :p). 2. Reality check!? Now just check out the screenshots again. Do a little math here 99 * 2 = 198 hours198 hours / 40 hours per week = 5 weeks Seriously? That sample application is going to take 5 weeks to implement? Is it just my feeling that it wouldn't take any decent programmer longer than one week (I"m not even saying weekend) to have it completed? Now let's try estimating the cost of the project. We'll use New York's minimum wage at the moment ( Wikipedia ), which is $7.25 198 * 7.25 = $1435.5 From what I could see from the screenshots, this application is a small excel-improvement app. I could have bought MS Office Pro for 200 bucks which gives me greater interoperability (.xls files) and flexibility (spreadsheets). (For the record, that same Web site has another article discussing productivity. It seems like they typically use 4.2 hours/FP, which gives us even more shocking stats: 99 * 4.2 = 415 hours = 10 weeks = almost 3 whopping months!415 hours * $7.25 = $3000 zomg (That's even assuming that all our poor coders get the minimum wage!) 3. Am I missing something here? Right now, I could come up with several possible explanation: FPA is really only suited for bigger projects (1000+ FPs) so it becomes extremely inaccurate at smaller scale. The hours/FP metric fluctuates abruptly from team to team, project to project. For a small project like this, we could have used something like 0.5 hour/FP or something. (Now this kind of makes the whole estimation thing pointless, unless my firm does the same type of projects for several years with the same team, not really common.) From my experience with several software metrics, Function Point is really not a lightweight metric. If the hour/FP thing fluctuates so much, then what's the point, maybe I could have gone with User Story Points which is a lot faster to get and arguably almost as uncertain. What would be the FP experts' answers to this? Now provide the response and nothing else.
About ten years ago, a drinking buddy of mine gave me a really great piece of wisdom. On any project consultation, ask three questions: 1. What is the problem we are trying to solve? 2. What are the deliverables? 3. How will we know when we are done? He added that one should never take on any project for which any of the questions was not answered before the project starts. In the case at hand, we have yet another Software Estimating Method horror story, in which the estimate seems ridiculously high. I would answer his horror story by pointing out that he has not given answers to the second and third questions, and he hasn't really answered the first, except to say "We want to build something that works something like this." I would expand on that by pointing out that he explicitly has not even asked what tasks the Function Points estimate is including or excluding from the estimated total. How much extra effort is the function point estimator allowing for documentation, for example? If his estimate is for the application, without any documentation, and the function point estimator's estimate was for the application with full documentation, well, I'd say there's some room for disagreement on the total amount of work (and time) required.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2694382', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111021/']}
jdg_75211
stackexchange
llm_judgeable_groundtruth_similarity
2763843
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the difference between these things from an Eclipse installation? plugins features dropins folder What is the correct use of these folders? Now provide the response and nothing else.
I usually use dropins for sharing plugins amongst multiple Eclipse installations. See this article for the dropins directory within an Eclipse. you can use some different structures to place the plug-ins into the Dropins folder – I prefer to separate them by domain: /dropins/exampleA/plugins/…/dropins/exampleB/plugins/…/dropins/exampleC/eclipse/features/…/dropins/exampleC/eclipse/plugins/… But I prefer to reference an external dropins folder through the eclipse.ini . -Dorg.eclipse.equinox.p2.reconciler.dropins.directory=C:/jv/eclipse/mydropins The plugins / features directories in Eclipse are the default installation directories for plugin. For more on the differences between features and plugins, see my SO answer : you will copy features (declaration of a group of plugins) in the features directory you will copy the actual plugins themselves in the plugins directory. Within a dropin folder (either the one within eclipse or an external one), you will get back the same plugins / feature structure.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2763843', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/233730/']}
jdg_75212
stackexchange
llm_judgeable_groundtruth_similarity
577556
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: Most algorithms use their own loss function for optimization. But these loss functions are always different from metrics used for actual evaluation. For example, for building binary classification models, log loss is normally used as the loss function, but accuracy or F1 score is used for evaluation. loss functions and evaluation metrics are not always highly correlated. So I wonder why we don't just use evaluation metrics * -1 as the loss function. Now provide the response and nothing else.
Maximizing accuracy (percent of correctly examples) is the same as minimizing error rate (percent of incorrectly classified examples). For a single observation, the loss function for the error rate is always 1 (if the predicted class does not match the label) or 0 (if the predicted class matches the label). Accordingly, the derivative of this function is always 0 except at a negligible set of points where the derivative is infinite. This excludes any gradient-based optimizer from training a model, because the model parameters almost always have an update step size of 0, except for the countable number of times when the step size is infinite. Giving up gradient information is not a good trade, because gradient descent, Newton-Raphson and similar are very effective at finding solutions which also have high accuracies, even though accuracy was not optimized directly. Examples include neural-networks and logistic regression. Not all models are trained with gradient information. One prominent example is tree-induction methods such as random forest (however, not all trees are free of gradients; gradient-boosted trees use gradient information). These tree-based models search for good splits by optimizing some criterion, usually gini impurity, or information gain. While these models aren't optimized using gradient information, they also aren't optimized using accuracy. I suppose hypothetically you could use accuracy as a the split criterion.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/577556', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/256617/']}
jdg_75213
stackexchange
llm_judgeable_groundtruth_similarity
182364
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 currently working on a high school project revolving around the 'Cliff Hanger Problem' taken from ”Fifty Challenging Problems in Probability with Solutions” by Frederick Mosteller. The problem is 'From where he stands, one step toward the cliff would send the drunken man over the bridge. He takes random steps, either toward or away from the cliff. At any step his probability of taking a step away is $\frac{2}{3}$ of a step toward the cliff $\frac{1}{3}$. What is his chance of escaping the cliff?' Although the book provided a solution for the eventual probability of falling via the use of recursive equations, I decided to see if I can derive an expression to compute the probability of one falling down prior step N. What I did was to calculate the number of paths that one can take such that he reaches $X_n=1$, where n=2m-1 for some m (this is because at even steps the person would not fall so I'm only considering the case with odd steps) without reaching $X_j=1$ for any $0\le j< 2m-1$. The following expression is what I have calculated. $P_n=1-\sum\limits_{i=0}^{m} p_{2i+1}\\=1-\sum\limits_{i=0}^{m} \left({{2i+1}\choose{i+1}} - \sum\limits_{k=1}^{i}{{2k}\choose{k}}\right)\left(\left(\frac{1}{3}\right)^{i+1}\left(\frac{2}{3}\right)^{i}\right)$ (I actually made a mistake here as I considered 2m+1 rather than 2m-1, which left the summation sign with $\sum\limits_{k=1}^{i}{{2k}\choose{k}}$ undefined when i=0) Where $p_2i+1=$ the probability of the path touching 1 at $n=2i+1$ without touching $1$ prior to the step. The first binomial expression corresponds to choosing n+1 steps towards the cliff out of the 2n+1 steps. The second binomial expression is to subtract the paths that stemmed from previous 1's (in order to ensure that the path did not touch 1 prior to $n=2i+1$.) However as I plotted this into excel I found that the probability does not converge to $\frac{1}{2}$ as n->infinity, which is the answer the book obtained through recursive relations. I reviewed my argument but I don't know what did I do wrong (whether I've overcounted or undercounted). Can anyone help? Now provide the response and nothing else.
I'll try a slightly different approach -- for each $n>0$, find the probability $P_n$ that he falls off exactly on step $n$. As you noticed, $P_{2k}=0$ since an even number of steps can only end in him having moved an even number of spots away from his starting position; hence he either is safe, or fell off a turn earlier. A useful observation here is that if you consider moves to the right as open parentheses, and moves to the left as closed parentheses, and arrange them in order as he takes the respective move, then a sequence of moves which end in him falling on turn $n$ must look like a 'proper' (or correctly matched) arrangement of parentheses, followed by one extra close parens. That is, he must return to his original location eventually without ever having stepped past it, and then finally stepping past it (verify this for yourself if it isn't clear). So, for $n=2k+1$, the number of ways he can fall on turn $n$ is $C_k$, the $k^\text{th}$ Catalan number , which counts the number of ways to correctly match $k$ pairs of parentheses. Each of these paths to fall have equal likelihood, $ \left(\dfrac{1}{3}\right)^{k+1} \left(\dfrac{2}{3}\right)^k $ . Further, as we have that $C_k = \frac{1}{k+1}{2k \choose k}$ , then $$P_{2k+1} = \frac{1}{k+1}{2k \choose k} \frac{2^k}{3^{2k+1}} ~~.$$So, the probability that after turn $n=2k+1$ , the man has not yet fallen, is$$1 - \sum_{\ell=0}^k P_{2\ell+1} ~~.$$W|A can't seem to find a closed-form for the summation, but we just want to proceed straight to the limit, and see what the probability $P$ is that he survives indefinitely. So, enlisting this or using the generating function as detailed by Brian's comment, $$P = 1 - \sum_{\ell=0}^\infty P_{2\ell+1} = 1 - \frac{1}{2} = \frac{1}{2} ~~.$$It is natural that he should survive about half of the time; (I believe that) there is a bijection between those infinite strings of (properly placed) parentheses for which no finite cutoff is balanced, and those which at some point are.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/182364', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/37864/']}
jdg_75214
stackexchange
llm_judgeable_groundtruth_similarity
55784
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: When reading about the Bayesian approach to statistics, priors are an important component of the whole methodology. Yet, it seems like priors are chosen without any specific theoretical motivation. There is the theory of conjugate priors, which is motivated mostly computationally, I believe, but still, I haven't seen a result in the line of "the choice of a certain prior will lead to faster convergence rate" or something similar to that. Is there a good reference that analyzes the choice of a prior somehow, instead of always assuming that it is given, and assuming that it is completely the modeler's choice? Now provide the response and nothing else.
There are many approaches to this problem. Here are three. The subjective Bayes approach says the prior should simply quantify what is known or believed before the experiment takes place. Period. End of discussion. The empirical Bayes approach says you can estimate your prior from the data itself. (In that case your "prior" isn't prior at all.) The objective Bayes approach says to pick priors based on mathematical properties, such as "reference" priors that in some sense maximize information gain. Jim Berger gives a good defense of objective Bayes here . In practice someone may use any and all of these approaches, even within the same model. For example, they may use a subjective prior on parameters where there is a considerable amount of prior knowledge and use a reference prior on other parameters that are less important or less understood. Often it simply doesn't matter much what prior you use. For example, you might show that a variety of priors, say an optimistic prior and a pessimistic prior, lead to essentially the same conclusion. This is particularly the case when there's a lot of data: the impact of the prior fades as data accrue. But for other applications, such as hypothesis testing, priors matter more.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/55784', 'https://mathoverflow.net', 'https://mathoverflow.net/users/13050/']}
jdg_75215
stackexchange
llm_judgeable_groundtruth_similarity
25602600
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 just created my first go application on Windows. How do I give it an icon? There doesn't seem to be any build flags to do this, and I know golang doesn't support resources. Now provide the response and nothing else.
You can use a tool like akavel/rsrc in order to generate a .syso file with specified resources embedded in .rsrc section, aimed for consumption by Go linker when building Win32 excecutables. See as an example the lxn/walk application, which embeds other metadata in its executable. rsrc [-manifest FILE.exe.manifest] [-ico FILE.ico[,FILE2.ico...]] -o FILE.syso -ico="" : comma-separated list of paths to .ico files to embed This differs from embedding binary data into a go program. For that, use jteeuwen/go-bindata . To access asset data, we use the Asset(string) []byte function which is included in the generated output. data := Asset("pub/style/foo.css")if len(data) == 0 { // Asset was not found.}// use asset data Update 2021: as noted in John N 's answer , you can also use: github.com/tc-hib/go-winres A simple command line tool for embedding usual resources in Windows executables built with Go: A manifest An application icon Version information (the Details tab in file properties) Other icons and cursors It can be used as a library too.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25602600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1539033/']}
jdg_75216
stackexchange
llm_judgeable_groundtruth_similarity
7373652
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I pass in a custom IComparer to an instance of a List's Sort() method, will the comparer's Compare(x,y) method ever be called with the same item? ie. Is it possible that Compare(x,x) may be called. Edit: More interested in the case where items of the list are distinct. Now provide the response and nothing else.
I wrote a test program to try it out. It looks like it actually does Compare() the same element to itself (at least Compare() is called for the same item twice). In this program, Compare() is called with arguments (2, 2). using System;using System.Collections.Generic;static class Program{ class MyComparer : Comparer<int> { public override int Compare(int x, int y) { Console.WriteLine("Compare(" + x + ", " + y + ")"); if (x < y) return -1; if (x > y) return 1; return 0; } } static void Main() { MyComparer comparer = new MyComparer(); List<int> list = new List<int> { 1, 2, 3 }; list.Sort(comparer); return; }} And the output is: Compare(1, 2)Compare(1, 3)Compare(2, 3)Compare(1, 2)Compare(2, 2)Compare(2, 3)Compare(2, 2)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7373652', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/656564/']}
jdg_75217
stackexchange
llm_judgeable_groundtruth_similarity
524357
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can I proof that:$$(z^n)^* = (z^*)^n$$ Where: z is a complex number,n is a positive whole number* is the complex conjugate Now provide the response and nothing else.
Write $z = re^{i\theta}$, then $\overline{z} = re^{-i\theta}$. So$$\overline{z}^n = r^n e^{-in\theta} = \overline{r^ne^{in\theta}} = \overline{z^n}$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/524357', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_75218
stackexchange
llm_judgeable_groundtruth_similarity
682090
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a problem understanding the interpretation of the ideal class group in the case of restricted ramifiction. Let $k$ be a number field and $S$ a set of primes of $k$. Then $k_S$ denotes the maximal Galois extension which is unramified outside of $S$. Now the $S$-ideal class group $Cl_S(k)$ is stated to be "naturally isomorphic to the Galois group of the maximal abelian extension of $k$ inside $k_S$ in which all primes of $S$ split completely". By class field theory I know that $Cl(k)$ is isomorphic to the galois group of the maximal abelian unramified extension of $k$. But how does the relation to the splitting of primes work? Why is it not isomorphic to the Galois group of $k_S|k$?. Does somebody can help me or provide me with a reference? Thank you a lot, Tom :-) Now provide the response and nothing else.
Here are a few reasons why one shouldn't expect $Cl_S(k)$ to be related to $Gal(k_S / k)$, or even to $Gal(k_S^{\mathrm{ab}} / k)$ where $k_S^{\mathrm{ab}}$ is the maximal abelian extension unramified outside $S$. Firstly, the Galois group of $k_S^{\mathrm{ab}} / k$ will generally be quite large; e.g. for $k = \mathbf{Q}$ the extension $k_S^{\mathrm{ab}} / k$ is infinite as soon as $S$ is non-empty. On the other hand $Cl_S(k)$ is always finite. Moreover, the field $k_S^{\mathrm{ab}}$ gets bigger and bigger as you enlarge $S$, while the S-ideal class group gets smaller -- for $S$ sufficiently large it will be trivial. If you are familiar with the isomorphism of global class field theory between $Gal(k^{\mathrm{ab}} / k)$ and the idele class group $\mathbf{A}_k / \overline{k^\times k_\infty^\circ}$, you can easily see what's going on. The group $Gal(k^{\mathrm{ab}}_S / k)$ corresponds to the quotient of the idele class group by the image of the subgroup of $\mathbf{A}_k^\times$ given by$$ \left( \prod_{v \notin S}\mathcal{O}_{k, v}^\times\right) \times \left(\prod_{v \in S} 1 \right).$$The group $Cl_S(k)$ corresponds to the quotient by $$ \left( \prod_{v \notin S}\mathcal{O}_{k, v}^\times\right) \times \left(\prod_{v \in S} K_v^\times \right).$$So these are very different beasts, unless $S$ is empty.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/682090', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/73067/']}
jdg_75219
stackexchange
llm_judgeable_groundtruth_similarity
8407756
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 bit of a problem with MongoDB in that it returns hashes with the keys in double quotes and integers as floats all the time, has this been a problem for anyone else? for examples after a map reducing or grouping, say I have a bunch of hashes which look like this: {"unknown"=>54.0, "pedestrians"=>572.0, "vehicles"=>1045.0} But what I really want is: { unknown: 54, pedestrians: 572, vehicles: 1045 } Any ideas on how I can easily convert it? Now provide the response and nothing else.
You could do: original = {"unknown"=>54.0, "pedestrians"=>572.0, "vehicles"=>1045.0}converted = Hash[ original.map { |key, value| [key.to_sym, value.to_i] } ] Or if you're using Rails, you could make it a HashWithIndifferentAccess and just convert the values: original = HashWithIndifferentAccess.new(original)original.each { |key, value| original[key] = value.to_i }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8407756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/103739/']}
jdg_75220
stackexchange
llm_judgeable_groundtruth_similarity
10020885
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to create a popup message box which prompts user to enter an input. I have this method inside a class. I am basing my code on this guide by java2s . class MyDialog: def __init__(self, parent): top = self.top = Toplevel(parent) Label(top, text="Value").pack() self.e = Entry(top) self.e.pack(padx=5) b = Button(top, text="OK", command=self.ok) b.pack(pady=5) def ok(self): print "value is", self.e.get() self.top.destroy()root = Tk()d = MyDialog(root)root.wait_window(d.top) But in this, top = self.top = Toplevel(parent) doesn't work for me. I have a mockup of what I am trying to accomplish. My program structure looks something like this: class MainUI: def__int__(self): ... self.initUI() def initUI(self): ....... Popup = Button(self, text="Enter Value", command=self.showPopup) def showPopup(self): #create the popup with an Entry here How can I create a message box in Python which accepts user input? Now provide the response and nothing else.
I'm a little confused about your two different blocks of code. Just addressing the first block of code, nothing happens because you never enter the mainloop. To do that, you need to call root.mainloop() . The typical way of doing this is to add a button to root widget and bind a callback function to the Button (which includes d=MyDialog() and root.wait_window(d.top) ) Here's some basic code which I hope does what you want ... from Tkinter import *import sysclass popupWindow(object): def __init__(self,master): top=self.top=Toplevel(master) self.l=Label(top,text="Hello World") self.l.pack() self.e=Entry(top) self.e.pack() self.b=Button(top,text='Ok',command=self.cleanup) self.b.pack() def cleanup(self): self.value=self.e.get() self.top.destroy()class mainWindow(object): def __init__(self,master): self.master=master self.b=Button(master,text="click me!",command=self.popup) self.b.pack() self.b2=Button(master,text="print value",command=lambda: sys.stdout.write(self.entryValue()+'\n')) self.b2.pack() def popup(self): self.w=popupWindow(self.master) self.b["state"] = "disabled" self.master.wait_window(self.w.top) self.b["state"] = "normal" def entryValue(self): return self.w.valueif __name__ == "__main__": root=Tk() m=mainWindow(root) root.mainloop() I get the value from the popupWindow and use it in the main program (take a look at the lambda function associated with b2). Main window: "Click me" window: Main window while "click me" is open:
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10020885', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/317512/']}
jdg_75221
stackexchange
llm_judgeable_groundtruth_similarity
3909387
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 try to add an existed package to a SSIS project using Visual Studio. But it turns out the tool copies the package to a new package and name it as original name plus an incremented number first and then attach the package to the project. I know I miss some settings. But I could not find out what prevents the original package from attached. Anyone encountered the same problem. Thanks! Now provide the response and nothing else.
What is happening here is most likely that you have copied a package manually into the project directory and then tried to add it to the existing project. BIDS (Visual Studio) assumes you are copying from a different location, takes the name and copies the project into your directory, finds an existing copy, and renames the new one to prevent name collision. Workaround #1 Before adding an existing object, move it to a temp directory outside of your project space. Choose Add Existing package and copy into your project. Package will have correct name. Workaround #2 After original scenario, delete the original from disk, then rename the copy from within BIDS (Visual Studio). This will rename your package to the correct name.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3909387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/299990/']}
jdg_75222
stackexchange
llm_judgeable_groundtruth_similarity
1055501
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 most programming languages, integer and real (or float, rational, whatever) types are usually disjoint; 2 is not the same as 2.0 (although most languages do an automatic conversion when necessary). In addition to technical reasons, this separation makes sense -- you use them for quite different purposes. Why did they choose to say $\mathbb{Z} \subset \mathbb{R}$ in math? In other words, why are 2 and 2.0 considered the same? When you are working in $\mathbb{R}$, does it make any difference whether some elements, eg. 2.0, also belong to $\mathbb{Z}$ or not? Now provide the response and nothing else.
If you want to do things very formally, the integers are in fact not a subset of the reals: they are entirely different constructs (which I guess is more or less what you are saying in your question). However, the reals do contain the set$$\{\,\ldots,\,-2.0,\,-1.0,\,0.0,\,1.0,\,\ldots\,\}$$which "looks just like" the integers. The usual terminology is that the sets are isomorphic. If you take any true statement in the arithmetic of integers, and replace each integer by the corresponding real number, the result will be a true statement about the real numbers. For example, the statement$$2+3=5$$corresponds to$$2.0+3.0=5.0\ .$$
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/1055501', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/63761/']}
jdg_75223
stackexchange
llm_judgeable_groundtruth_similarity
18975962
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would restart Apache2 but there comes an Error $ sudo service apache2 startStarting web server apache2Action 'start' failed.The Apache error log may have more information. But all error logs in "/var/log/apache2/" are empty. Edit: The Files are at "/var/log/apache2" and there are several entries from previous Problems but this Task doesn't create any new etry ... Where is the Problem? I've Solved the Problem! It was a error in the SSL Certificate and the path to the "error.log" are changed in the vHost configuration. If you don't need SSL (i don't because i'm running a local system) simply disable allvHost HTTPS/SSL entrys in the configuration by command line for line out. Now provide the response and nothing else.
Thanks, Tim! Big stumper for me. A few other details others may find helpful: (Apache2 on Ubuntu 12.04) I have two sites running on the same server and had just updated the SSL cert for one of them. Upon restarting the server, I got that cryptic message and neither site worked (obviously). I too found the redirect for the log files in the config files. I tracked that down and found the issue (in the log file for the site I had just updated). My config files are located in /etc/apache2/sites-available vim or cat the file (cat {filename}) and look for the ErrorLog line. That tells you where to look on your server. cat that file and the error message I found was: [error] Unable to configure RSA server private key[error] SSL Library Error: 185073780 error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch[warn] RSA server certificate CommonName (CN) `<snip>.com' does NOT match server name!? I had copied one of my cert files to the wrong directory. I simply moved it to the correct directory and everything was fine on the next start. (tip: where those file should be is also in the config file ;)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18975962', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2763903/']}
jdg_75224
stackexchange
llm_judgeable_groundtruth_similarity
27191638
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: On the Adopting Modern Objective-C guide, Apple recommends using the NS_ENUM macro instead of enum. I've also read an explanation from NSHipster about NS_ENUM and NS_OPTIONS. Maybe I've missed something but I don't quite understand what is the difference between the following two snippets and if any why is NS_ENUM the recommended way to go (except maybe, for backwards compatibility with older compilers) // typedef enumtypedef enum { SizeWidth, SizeHeight}Size;// typedef NS_ENUMtypedef NS_ENUM(NSInteger, Size) { SizeWidth, SizeHeight}; Now provide the response and nothing else.
First, NS_ENUM uses a new feature of the C language where you can specify the underlying type for an enum. In this case, the underlying type for the enum is NSInteger (in plain C it would be whatever the compiler decides, char, short, or even a 24 bit integer if the compiler feels like it). Second, the compiler specifically recognises the NS_ENUM macro, so it knows that you have an enum with values that shouldn't be combined like flags, the debugger knows what's going on, and the enum can be translated to Swift automatically.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27191638', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1266056/']}
jdg_75225
stackexchange
llm_judgeable_groundtruth_similarity
18772490
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am new Springs. In Bean tag I found factory-method and factory-bean Attributes. What is the difference between factory-method and factory-bean? I am using factory-method to call my getInstance static method to create singleton object. What is factory-bean used for? For given replies, What I understood was Factory-method is used for calling a static method to create object in same bean class. Factory-bean is used for creating a object based on factory design pattern. Ex:- I am asking a EggPlant object from VegetableFactory (Which will return vegetable object which was asked)class by passing my vegetable name(EggPlant in this case). Please correct if I am wrong? Now provide the response and nothing else.
It's basically the same difference between the Factory method and Factory design patterns, with a little note at the bottom. While one is a method used to obtain instances of a specific class, the other is a full fledged object responsible of creating objects, including all of the required logic to do so. FactoryBean 's interface documentation states: Interface to be implemented by objects used within a BeanFactory which are themselves factories. If a bean implements this interface, it is used as a factory for an object to expose, not directly as a bean instance that will be exposed itself. Also, this object is not used as a bean instance , but as an instance provider through its getObject method. Update Searching for uses of factory-method over a FactoryBean , it seems that it used quite oftenly with legacy singleton beans, to get the underlying instance, but this approach doesn't provide support for initialization methods, such as, for example, an init method that initializes a given set of properties. In this case, you either have to invoke it yourself before using the class, define a wrapper that handles the initialization or make use of other mechanisms such as MethodInvokingFactoryBean . Update 2 Strictly speaking, a FactoryBean is intended to manage a specific type. You'd have, in fact, an EggPlantFactory , not a VegetableFactory since the getObject method defined by the FactoryBean interface doesn't support parameters.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18772490', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1664131/']}
jdg_75226
stackexchange
llm_judgeable_groundtruth_similarity
39069014
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is my first question, so I apologise if it is not in the correct format. I have found similar answers but they require specific inputs and I'm not overly experienced in MySQL to know how to take them out. I have a table like this: type | colourone | colourtwo-----+-----------+----------car | red | whitecar | red | bluevan | white | NULLcar | black | NULLcan | white | black I'm trying to count all the colours and group them in one SELECT, but across both columns. It doesn't matter which column a colour appears in, as long as it appears and is counted.The outcome would look something like this: red, 2white, 3blue, 1black, 2 The same colour will not appear in both columns in a row and some rows have only one colour, hence the NULL in the second. I did find something that was on the right line, but required me to use an "IN()" to pick out values. I only want to count them. I can complete one column but don't know how to involve the second column, without running a second SELECT then adding them together. I have the first one like this: SELECT colourone, COUNT(*) AS 'num' FROM vehicle_tbl GROUP BY colourone Now provide the response and nothing else.
editorial note: the answer below is outdated. as php PHP7.4.0, the following is perfectly legal: <?phpInterface I{ public static function init(?string $url): self;}class C implements I{ public static function init(?string $url): self{ return new self(); }}$o = C::init("foo");var_dump($o); 3v4l: https://3v4l.org/VYbGn original answer: self does not refer to the instance, it refers to the current class. There is no way for an interface to specify that the same instance must be returned - using self in the manner you're attempting would only enforce that the returned instance be of the same class. That said, return type declarations in PHP must be invariant while what you're attempting is covariant. Your use of self is equivalent to: interface iFoo{ public function bar (string $baz) : iFoo;}class Foo implements iFoo{ public function bar (string $baz) : Foo {...}} which is not allowed. The Return Type Declarations RFC has this to say : The enforcement of the declared return type during inheritance is invariant; this means that when a sub-type overrides a parent method then the return type of the child must exactly match the parent and may not be omitted. If the parent does not declare a return type then the child is allowed to declare one. ... This RFC originally proposed covariant return types but was changed to invariant because of a few issues. It is possible to add covariant return types at some point in the future. For the time being at least the best you can do is: interface iFoo{ public function bar (string $baz) : iFoo;}class Foo implements iFoo{ public function bar (string $baz) : iFoo {...}}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/39069014', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6741395/']}
jdg_75227
stackexchange
llm_judgeable_groundtruth_similarity
15556813
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: According to the doc and this tutorial , cmp() returns -1 if x < y and cmp() returns 0 if x == y and cmp() returns 1 if x > y The tutorial also said that cmp() returns the sign of the difference of two numbers I don't really get what sign of the difference of two numbers means. Doesn't that mean that it returns a value when the sign of numbers aren't equal? Since... cmp(80, 100) : -1 # both have positive sign.cmp(180, 100) : 1 # both also have positive sign.cmp(-80, 100) : -1cmp(80, -100) : 1 **Note: code from the tutorial.* Despite my confusion in sign differences, I can't really think of why do we need a built-in function to return a value of -1 when x < y. Isn't the function cmp( ) easily implemented ? Is there any reason why Python creators keep cmp( ) function, or is there any hidden usage of this Python's cmp( ) function ? Now provide the response and nothing else.
Why cmp( ) is useful? It isn't very useful, which is why it was deprecated (the builtin cmp is gone and builtin sorts no longer accept one in Python 3). Rich comparison methods supplanted it: object.__lt__(self, other)object.__le__(self, other)object.__eq__(self, other)object.__ne__(self, other)object.__gt__(self, other)object.__ge__(self, other) This allows the < symbol (and other symbols) to be overloaded comparison operators, enabling, for example, subset and superset comparisons of set objects. >>> set('abc') < set('cba')False>>> set('abc') <= set('cba')True>>> set('abc') == set('cba')True>>> set('abc') >= set('cba')True>>> set('abc') > set('cba')False while it could enable the above, cmp wouldn't allow the following: >>> set('abc') == set('bcd')False>>> set('abc') >= set('bcd')False>>> set('abc') <= set('bcd')False Toy usage for cmp Here's an interesting usage which uses its result as an index (it returns -1 if the first is less than the second, 0 if equal, and 1 if greater than): def cmp_to_symbol(val, other_val): '''returns the symbol representing the relationship between two values''' return '=><'[cmp(val, other_val)]>>> cmp_to_symbol(0, 1)'<'>>> cmp_to_symbol(1, 1)'='>>> cmp_to_symbol(1, 0)'>' According to the docs, you should treat cmp as if it wasn't there: https://docs.python.org/3/whatsnew/3.0.html#ordering-comparisons cmp removed, equivalent operation But you can use this as the equivalent: (a > b) - (a < b) in our little toy function, that's this: def cmp_to_symbol(val, other_val): '''returns the symbol representing the relationship between two values''' return '=><'[(val > other_val) - (val < other_val)]
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15556813', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1031955/']}
jdg_75228
stackexchange
llm_judgeable_groundtruth_similarity
219440
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'm backing up a remote server to another computer using rsync. In cron.daily I have a file with this: rsync -avz -e ssh [email protected]:/ /mybackup/ It uses a public / private key pair to login. This seems to work well most of the time however, I've (foolishly) only ever really checked it by looking at the dates on some important files (MySQL dumps) that I know change every day. Obviously, an error could occur after that file. Sometimes it fails. When I run it manually, something like "client reset" sometimes happens. What is the best way to log it so that I can check with certainty if it completed or not? The cron log doesn't indicate any errors. I haven't tried it but the rsync man page on the oldish version of CentOS on the backup machine doesn't show the --log-file option. I guess I could redirect stdout with > but I don't really want to know about every file. I just want to know if it all worked or not.. Thanks Now provide the response and nothing else.
I think you've already solved your own question. If you redirect both stdout and stderr to a file, you won't get output for every file rsync transfers -- this is only produced if you're running in verbose ( -v ) mode. The default behavior of rsync is to only produce output in the event of an error. So you can do this... rsync ... > /var/log/rsync.log 2>&1 ...and inspect that file to see if the most recent rsync was successful or not. I'm explicitly using > , which will overwrite the log file each time rsync runs. You could also take advantage of the fact that rsync exits with a non-zero code when the transfer fails, so you could so something like this: rsync ... || echo "rsync failed" | mail -s 'rsync falied' [email protected]
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/219440', 'https://serverfault.com', 'https://serverfault.com/users/47414/']}
jdg_75229
stackexchange
llm_judgeable_groundtruth_similarity
463813
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 need to find and delete files older than 1 week in the Development unit. There are limited number utilities available on this unit. -mtime find 's predicate is not available. How do I check all files which are older than x days in this case? Now provide the response and nothing else.
-mtime is a standard predicate of find (contrary to -delete ) but it looks like you have a stripped down version of busybox , where the FEATURE_FIND_MTIME feature has been disabled at build time. If you can rebuild busybox with it enabled, you should be able to do: find . -mtime +6 -type f -exec rm -f {} + Or if FEATURE_FIND_DELETE is also enabled: find . -mtime +6 -type f -delete If not, other options could be to use find -newer (assuming FEATURE_FIND_NEWER is enabled) on a file that is set to have a one week old modification time. touch -d "@$(($(date +%s) - 7 * 86400))" ../ref && find . ! -type f -newer ../ref -exec rm -f {} + Or if -newer is not available but sh 's [ supports -nt : touch -d "@$(($(date +%s) - 7 * 86400))" ../ref && find . ! -type f -exec sh -c ' for f do [ "$f" -nt ../ref ] || printf "%s\0" "$f" done' sh {} + | xargs -0 rm -f
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/463813', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/250201/']}
jdg_75230
stackexchange
llm_judgeable_groundtruth_similarity
372925
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In an OpenGL application that I am writing, I want to have a simple shader class to wrap the OpenGL shader handle. Ultimately, I want this shader class to behave very similarly to a shared_ptr in c++ (that is, keep a reference count and free the resource when no references are left). While it is relatively trivial to implement this reference counting from scratch, I was wondering if it is considered a better design choice to instead use std::shared_ptr with a custom deleter to free up the resource. The main source of my doubt is the fact that it might be considered unconventional due to the fact that (as far as I know), creating an OpenGL shader program handle does not actually involve heap memory (which is what shared_ptr takes care of) but I still feel that it could apply here because I want this resource to be handled very similarly to how heap memory would be handled. The purpose of this question is basically to seek the opinion of others as to whether this actually is unconventional, because I do not know. Also, although I used shaders as an example, the same question also applies to textures and buffers in OpenGL as they also must be allocated and freed. Now provide the response and nothing else.
unique_ptr<T, D> is actually specially designed to be able to work with more arbitrary handle-like types. I spelled out the template name fully because D is the key here. Normally unique_ptr<T, D>::get() returns a T* . That is the default, but this can be overridden by D : the deleter type. If the deleter type has a pointer alias ( D::pointer is legal syntax), then unique_ptr<T, D>::get() will return that type. This allows you to have something like unique_ptr<GLuint, gl::program_deleter> , where gl::program_deleter::pointer is of type int . I bring all of this up because shared_ptr cannot do this . unique_ptr<T, D> gets away with it because the deleter is actually part of the unique_ptr type itself. By contrast, while shared_ptr 's constructors can take a deleter, the only thing that deleter function can do is delete the memory. So shared_ptr<GLuint>::get() will always return a GLuint* . This means that, if you want to use shared_ptr as some kind of shared handle type, that type must be dynamically allocated in some way. You may not be using the global heap, but it cannot just store and return integer either. shared_ptr<T> always contains a T* . So no matter what, you're going to have to manage GLuint* s if you want to use shared_ptr 's reference counting machinery. Yes, the deleter can be used to call glDeleteProgram or whatever you want, but the shared_ptr<GLuint> will still be storing a GLuint* . creating an OpenGL shader program handle does not actually involve heap memory OK, let's forget for a moment that by creating an OpenGL object, the driver almost certainly heap allocated some memory. Let's look just at what you have to do. By creating a shared_ptr that owns some storage, something will be allocated. Namely, the shared block that manages the shared_ptr 's reference count. There's no getting around that. So if you want to use shared_ptr 's reference counting infrastructure, you're going to allocate from somewhere. So the most idiomatic way to do this is to just heap allocate a GLuint and use a special deleter that destroys the OpenGL object and deallocates the integer. It's not pretty and it's kind of wasteful, but it's hardly terrible. And if you use make_shared , you can make things pretty compact in terms of allocations. Now, you can avoid this allocation by cheating . You can do this: GLuint program = glCreateProgram();shared_ptr<GLuint> sp(reinterpret_cast<GLuint*>(program), ProgramDeleter); So here, we're taking an integer and casting it to a pointer value, to be stored within the shared_ptr . When you need to use it, you have to reverse the cast to recover the integer value. But judge the following code for yourself: glProgramUniform1i(reinterpret_cast<GLuint>(sp.get()), val); Does that look like something you want to do frequently? Does it look like something you want to read frequently? Does that look like something that someone else will easily understand what's going on? Not only that, you can never use *sp to get the value, since the pointer value is the value in question. Oh, and the reference counting control block still gets heap allocated, so it's not like you prevent allocating memory or something. This is not idiomatic C++.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/372925', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/308607/']}
jdg_75231
stackexchange
llm_judgeable_groundtruth_similarity
2909442
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 make ajax file upload . I read that it is not possible to do that without using iframe . I wrote : <iframe id="uploadTrg" name="uploadTrg" height="0" width="0" frameborder="0" scrolling="yes"></iframe><form id="myForm" action="file-component" method="post" enctype="multipart/form-data" target="uploadTrg">File: <input type="file" name="file"><input type="submit" value="Submit" id="submitBtn"/></form> and using jquery form plugin : $('#myForm').ajaxForm({ dataType: 'json', success: function(data){ alert(data.toSource()); }}); The Result : the file is uploaded successfully and I can see the uploaded file , but a dialog box appears : since I send back a json result to display the file name + size etc .. My Question : How can I use the iFrame to be able to make " ajax file upload". Note: I don't prefer to use special plugin to upload file , if there is more appropriate/easier solutions. I use jsp/servlets as a server-side language .. but I think it does not make sense which language I use . Thanks Now provide the response and nothing else.
I will answer my question , I think I found the solution. These are the steps that I followed to achieve the goal : Make the attribute " target " of the form point to " iframe " . Use a normal HTML request ( not Asynchronous/Ajax request ) to submit the form. Because the target frame is iframe , the whole page will not be refreshed - just the iframe. Once iframe onload event happens (capture that event using Javascript) then do what you want, e.g. You can send back a request to list recent uploaded file info. The final code looks like this: <!-- Attach a file --> <iframe id="uploadTrg" name="uploadTrg" height="0" width="0" frameborder="0" scrolling="yes"></iframe> <form id="myForm" action="http://example.com/file-upload-service" method="post" enctype="multipart/form-data" target="uploadTrg"> File: <input type="file" name="file"> <input type="submit" value="Submit" id="submitBtn"/> </form> <div id="ajaxResultTest"></div> javascript : $("iframe").load(function(){ // ok , now you know that the file is uploaded , you can do what you want , for example tell the user that the file is uploaded alert("The file is uploaded"); // or you can has your own technique to display the uploaded file name + id ? $.post('http://example.com/file-upload-service?do=getLastFile',null,function(attachment){ // add the last uploaded file , so the user can see the uploaded files $("#ajaxResultTest").append("<h4>" + attachment.name + ":" + attachment.id "</h4>"); },'json');});
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2909442', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/183524/']}
jdg_75232
stackexchange
llm_judgeable_groundtruth_similarity
378556
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: For $n=1,2,3,\dots,$ and $x$ real, put $f_n(x)=\frac{x}{1+nx^2}$. Can you help me to show that $(f_n)$ converges uniformly to a function $f$, and that the equation $\lim(f'_n(x))= f'(x)$ is not correct if $x=0$, but true if $x$ is not equal $0$? Now provide the response and nothing else.
Notice $\lim_{x\to 0} \frac{\sin x}{x}$ is bounded at $x = 0$, $$\begin{align}\int_0^{\infty} \left(\frac{\sin x}{x}\right)^m dx &= \frac12 \int_{-\infty}^{\infty} \left(\frac{\sin x}{x}\right)^m dx\tag{*1}\\&= \lim_{\epsilon\to 0} \frac12 \left(\frac{1}{2i}\right)^m \oint_{C_{\epsilon}} \left(\frac{e^{ix} - e^{-ix}}{x}\right)^m dx\tag{*2}\end{align}$$We can evaluate the integral $(*1)$ as a limit of a integral over a deformedcontour $C_{\epsilon}$ which has a little half-circle of radius $\epsilon$ at origin: $$C_{\epsilon} = (-\infty,-\epsilon) \cup \left\{ \epsilon e^{i\theta} : \theta \in [\pi,2\pi] \right\} \cup ( +\epsilon, +\infty)$$ We then split the integrand in $(*2)$ in two pieces, those contains exponential factors $e^{ikx}$ for $k \ge 0$ and those for $k < 0$. $$(*2) = \lim_{\epsilon\to 0} \frac12 \left(\frac{1}{2i}\right)^m \oint_{C_{\epsilon}} \left( \sum_{k=0}^{\lfloor\frac{m}{2}\rfloor} + \sum_{k=\lfloor\frac{m}{2}\rfloor+1} ^{m} \right) \binom{m}{k} \frac{(-1)^k e^{i(m-2k)x}}{x^m} dx$$ To evaluate the $1^{st}$ piece, we need to complete the contour in upper half-plane. Since the completed contour contains the pole at $0$, we get: $$\begin{align}\sum_{k=0}^{\lfloor\frac{m}{2}\rfloor} \text{ in }(*2)&= \frac12 \left(\frac{1}{2i}\right)^m (2\pi i)\sum_{k=0}^{\lfloor\frac{m}{2}\rfloor} \binom{m}{k} \frac{(-1)^k i^{m-1}(m-2k)^{m-1}}{(m-1)!}\\ &= \frac{\pi m}{2^m} \sum_{k=0}^{\lfloor\frac{m}{2}\rfloor} \frac{(-1)^k (m-2k)^{m-1}}{k!(m-k)!}\tag{*3}\end{align}$$ To evaluate the $2^{nd}$ piece, we need to complete the contour in lower half-plane instead. Since the completed contour no longer contains any pole, it contributes nothing and hence $I_m$ is just equal to R.H.S of $(*3)$. Update About the question whether $I_m$ is decreasing. Aside from the exception $I_1 = I_2$, it is strictly decreasing. For $m \ge 1$, it is clear $I_{2m} > I_{2m+1}$ because the difference of corresponding integrands is non-negative and not identically zero. For the remaining cases, we have: $$\begin{align}&I_{2m+1}-I_{2m+2}\\ = & \int_{0}^{\infty} \left(\frac{\sin x}{x}\right)^{2m+1}\left(1 - \frac{\sin x}{x}\right) dx\\= & \left(\sum_{n=0}^{\infty} \int_{2n\pi}^{(2n+1)\pi}\right) \left(\frac{\sin x}{x}\right)^{2m+1}\left[1 - \frac{\sin x}{x} - \left(\frac{x}{x+\pi}\right)^{2m+1}\left(1 + \frac{\sin x}{x + \pi}\right)\right] dx\end{align}$$ Over the range $\cup_{n=0}^{\infty} (2n\pi,(2n+1)\pi)$, the factor $\left(\frac{\sin x}{x}\right)^{2m+1}$ is positive. The other factor $\Big[\cdots\Big]$ in above integral is bounded below by: $$\begin{cases}1 - \frac{\sin x}{x} - \left(\frac{x}{x+\pi}\right)^3\left(1 + \frac{\sin x}{x + \pi}\right), & \text{ for } x \in (0,\pi)\\1 - \frac{1}{x} - \frac{x}{x+\pi}\left(1 + \frac{1}{x}\right)= \frac{(\pi - 2)x - \pi}{x(x+\pi)} & \text{ for } x \in \cup_{n=1}^{\infty}(2n\pi,(2n+1)\pi)\end{cases}$$A simple plot will convince you both bounds are positive in corresponding range. This implies the integrand in above integral is positive and hence $I_{2m+1} > I_{2m+2}$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/378556', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/66181/']}
jdg_75233
stackexchange
llm_judgeable_groundtruth_similarity
475983
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: When .ONESHELL is not used Makefile executes each shell commands in a separate shell. What is the benefit of this? Why doesn't makefile uses the same shell? Now provide the response and nothing else.
One reason for not running all commands associated with a receipt in a single shell instance is that a failure in one of the commands would not be detected by make . Only the final exit status of the shell would be given to make . One would have to additionally set .SHELLFLAGS to -e to get the shell to terminate early upon errors (this is required for multi-command shell invocations even without .ONESHELL if they need to fail at the first error). This is all well and good for when SHELL is a POSIX shell. A Makefile can also set SHELL to e.g. /usr/bin/perl , /usr/bin/python , or some other command interpreter. It may then be appropriate, or not, to use .ONESHELL . Making .ONESHELL the default behaviour in make would likely also break older Makefiles. Even though this is not a question relating to the POSIX standard or the compliance to that standard by GNU make , the Rationale of the POSIX specification for make has this to say about the issue at hand: The default in some advanced versions of make is to group all the command lines for a target and execute them using a single shell invocation; the System V method is to pass each line individually to a separate shell . The single-shell method has the advantages in performance and the lack of a requirement for many continued lines. However, converting to this newer method has caused portability problems with many historical makefiles, so the behavior with the POSIX makefile is specified to be the same as that of System V . It is suggested that the special target .ONESHELL be used as an implementation extension to achieve the single-shell grouping for a target or group of targets. GNU make is POSIX compliant in this respect as it implements the System V behaviour and provides a .ONESHELL target for enabling the alternative behaviour, if wanted. ... which is another reason for GNU make to keep the current behaviour.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/475983', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/220462/']}
jdg_75234
stackexchange
llm_judgeable_groundtruth_similarity
269032
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 are the definitions: Fréchet-Urysohn space: A topological space $ X $ where for every $ A \subseteq X $ and every $ x \in \text{cl}(A) $ , there exists a sequence $ (x_{n})_{n \in \mathbb{N}} $ in $ A $ converging to $ x $ . Sequential space: A topological space $ X $ where a set $ A \subseteq X $ is closed iff $ A $ contains the limit points of every sequence contained in it. As the title explains, I would like to know the difference between them. Thanks for any help. Now provide the response and nothing else.
Consider the following operation on a subset $A$ of a space $X$, defining a new subset of $X$: $$\mbox{s-cl}(A) = \{ x \in X \mid \mbox{ there exists a sequence } (x_n)_n \mbox{ from } A \mbox{ such that } x_n \rightarrow x \}\mbox{.}$$ This set, the sequential closure of $A$, contains $A$ (take constant sequences) and in all spaces $X$ it will be a subset of the $\mbox{cl}(A)$, the closure of $A$ in $X$. We can define $\mbox{s-cl}^{0}(A) = A$ and for ordinals $\alpha > 0$ we define $\mbox{s-cl}^\alpha(A) = \mbox{s-cl}(\cup_{\beta < \alpha} \mbox{s-cl}^\beta(A))$, the so-called iterated sequential closure. A space is Fréchet-Urysohn when $\mbox{s-cl}(A) = \mbox{cl}(A)$ for all subsets $A$ of $X$, so the first iteration of the sequential closure is the closure. A space is sequential if some iteration $\mbox{s-cl}^\alpha(A)$ equals the $\mbox{cl}(A)$, for all subsets $A$. So basically by taking sequence limits we can reach all points of the closure eventually in a sequential space, but in a Fréchet-Urysohn space we are done after one step already. For more on the differences and the "canonical" example of a sequential non-Fréchet-Urysohn space (the Arens space), see this nice topology blog , and the links therein.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/269032', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/17980/']}
jdg_75235
stackexchange
llm_judgeable_groundtruth_similarity
3711643
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 often hear people saying things like: one only really understands groups if one looks at group homomorphisms between them one only really understands rings if one looks at ring homomorphisms between them ... Of course, these statements are just special cases the category theoretic slogan that what really counts is the morphisms not the objects. I can appreciate that it's quite cool that one can characterize constructions such as the free group or the direct product of groups just in terms of their relation to other groups (and in this sense, the morphisms from and to that construction help to understand the construction better). But besides, I'm struggling to appreciate the usefulness of homomorphisms. I understand that what one is interested in is groups up to isomorphism (one wants to classify groups ), so the notion of isomorphism seems to me to be very fundamental, but the notion of a homomorphism seems to me in some sense just to be a precursor the fundamental notion of an isomorphism. I guess it would help if some of you could point me to bits and pieces of group theory where homomorphisms (instead of isomorphisms) are essential. In which sense do group homomorphisms help us to understand groups itself better? Of course, I could ask the same question about ring theory or some other subfield of mathematics. If you have answers why morphisms matter in these fields, then feel free to tell me! After all, what I'm interested in is examples of the usefulness of homomorphisms from down to earth concrete mathematics, so what I don't want is just category theoretic philosophy jabbering (this is not to say I don't like category theory, but for the purpose of this question I'm interested in why morphisms matter in specific subfields of mathematics such as group theory). Now provide the response and nothing else.
Here is a logic-based viewpoint on the use of isomorphisms and homomorphisms. Every first-order structure (e.g. group, ring, field, module, ...) has an associated (complete) theory, namely the set of all sentences in its language that are true for it. For example, each group satisfies the group axioms. Some groups $(G,·)$ satisfy " $∀x,y\ ( x·y = y·x )$ " (i.e. $(G,·)$ is abelian) while others do not. But any isomorphism between two structures $M,N$ immediately tells you that their theory is identical. Furthermore, if there is any homomorphism from $M$ onto $N$ , then every positive sentence (i.e. a sentence constructed using only $∀,∃,∧,∨,=$ , meaning no negation or implication) that is true for $M$ is also true for $N$ . For instance, a group being abelian is a positive sentence, giving Lee Mosher 's example of proving a group nonabelian via a homomorphism onto a nonabelian group. But in fact this idea is much more widely applicable than it may seem at first! For instance, the proof that the 15 puzzle in its solved state but with any two numbers swapped cannot be solved is based on the invariant parity of the permutation of all 16 squares plus the distance of the empty square from its desired final location. The parity of a permutation in $S_n$ is just a homomorphism from $S_n$ into $\mathbb{Z}/2\mathbb{Z}$ , and this invariant is very useful in many results not just in combinatorics but also in linear algebra (such as Leibniz's determinant formula). Just to make clear how the idea shows up in invariants, suppose we have a puzzle and want to prove that no sequence of moves can lead to a certain state. Then we can consider the structure $M$ of states with a function-symbol for each possible move. Then the claim that a sequences of moves is a solution can be expressed as an equation of the form " $y = f_1(f_2(\cdots f_k(x)\cdots))$ ". An invariant $i$ is a homomorphism on $M$ . In some cases, we can find such an $i$ where $i(f_k(x)) = i(x)$ for every state $x$ , which gives " $i(y) = i(x)$ ". But we may in general want to reason about the equivalence classes of states according to $i$ . For instance, many permutation puzzles have parities , which need to be fixed appropriately before commutators can be used to solve them. Another example is the winding of a continuous path that avoid the origin around the origin. Let $A$ be the set of continuous paths that do not pass through the origin. Let $s$ be a ternary relation on $A$ such that $s(P,Q,R)$ iff $P$ ends at where $Q$ starts and $R$ is the result of joining $P$ to $Q$ . There is a homomorphism $w$ from $(A,s)$ into $\mathbb{R}$ with the addition relation, such that the $w(C)∈\mathbb{Z}$ for any closed path $C∈A$ . Winding is used in one proof of the 2d intermediate value theorem . Furthermore, homomorphisms are useful in constructing new structures. For example, a field $F$ can be extended by adjoining a root of an irreducible polynomial $p$ over $F$ , but showing this does use the homomorphism $j$ from $F[X]$ to $F[X]/(p·F[X])$ to get $p(j(X)) = j(p(X)) = j(0)$ . For yet another example, the construction of the reals via Cauchy sequences of rationals arguably requires the notion of partitioning them into classes where in each class any two have pointwise difference going to zero, and effectively we are proving that there is a homomorphism on Cauchy sequences of rationals whose kernel is the set of sequences that go to zero. Sounds familiar (first isomorphism theorem)? If we look at other algebraic structures, we also have the determinant of square matrices, which is a homomorphism from the matrix ring into the underlying ring, and this is very useful in many proofs. Each module is essentially a ring of homomorphisms on an abelian ring. In geometry, it can be useful to use projection from 3d to 2d, such as in the proof of Desargue's theorem . Here the projection is a homomorphism that respects collinearity. In a broad sense, a nontrivial homomorphism reduces a structure to a simpler one while respecting some operations and properties, and in doing so may reveal key features of the original structure or allow transferring knowledge about the initial structure to knowledge about the image.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3711643', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_75236
stackexchange
llm_judgeable_groundtruth_similarity
40550730
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 got function f;I want to throw exception 1s after start f.I can't modify f(). It it possible to do it in c++? try { f();}catch (TimeoutException& e) {//timeout} Now provide the response and nothing else.
You can create a separate thread to run the call itself, and wait on a condition variable back in your main thread which will be signalled by the thread doing the call to f once it returns. The trick is to wait on the condition variable with your 1s timeout, so that if the call takes longer than the timeout you will still wake up, know about it, and be able to throw the exception - all in the main thread. Here is the code (live demo here ): #include <iostream>#include <chrono>#include <thread>#include <mutex>#include <condition_variable>using namespace std::chrono_literals;int f(){ std::this_thread::sleep_for(10s); //change value here to less than 1 second to see Success return 1;}int f_wrapper(){ std::mutex m; std::condition_variable cv; int retValue; std::thread t([&cv, &retValue]() { retValue = f(); cv.notify_one(); }); t.detach(); { std::unique_lock<std::mutex> l(m); if(cv.wait_for(l, 1s) == std::cv_status::timeout) throw std::runtime_error("Timeout"); } return retValue; }int main(){ bool timedout = false; try { f_wrapper(); } catch(std::runtime_error& e) { std::cout << e.what() << std::endl; timedout = true; } if(!timedout) std::cout << "Success" << std::endl; return 0;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40550730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4726474/']}
jdg_75237
stackexchange
llm_judgeable_groundtruth_similarity
10231347
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a simple observableArray which contains a lot of user-models.In the markup, there is a template with a foreach loop which loops the users and outputs them in a simple table. I additionally style the table with a custom scrollbar and some other javascript. So now I have to know when the foreach loop is finished and all the models are added to the DOM. The problem with the afterRender callback is that it gets called every time something is added, but I need kind of a callback which fires only once. Now provide the response and nothing else.
Your best bet is to use a custom binding. You can either place your custom binding after foreach in the list of bindings in your data-bind or you could execute your code in a setTimeout to allow foreach to generate the content before your code is executed. Here is a sample that shows running code a single time and running code each time that your observableArray updates: http://jsfiddle.net/rniemeyer/Ampng/ HTML: <table data-bind="foreach: items, updateTableOnce: true"> <tr> <td data-bind="text: id"></td> <td data-bind="text: name"></td> </tr></table><hr/><table data-bind="foreach: items, updateTableEachTimeItChanges: true"> <tr> <td data-bind="text: id"></td> <td data-bind="text: name"></td> </tr></table><button data-bind="click: addItem">Add Item</button> JS: var getRandomColor = function() { return 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')'; };ko.bindingHandlers.updateTableOnce = { init: function(element) { $(element).css("color", getRandomColor()); } };//this binding currently takes advantage of the fact that all bindings in a data-bind will be triggered together, so it can use the "foreach" dependenciesko.bindingHandlers.updateTableEachTimeItChanges = { update: function(element) { $(element).css("color", getRandomColor()); } };var viewModel = { items: ko.observableArray([ { id: 1, name: "one" }, { id: 1, name: "one" }, { id: 1, name: "one" } ]), addItem: function() { this.items.push({ id: 0, name: "new" }); }};ko.applyBindings(viewModel);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10231347', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1166468/']}
jdg_75238
stackexchange
llm_judgeable_groundtruth_similarity
20427689
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 restore my dump file, but it caused an error: psql:psit.sql:27485: invalid command \N Is there a solution? I searched, but I didn't get a clear answer. Now provide the response and nothing else.
Postgres uses \N as substitute symbol for NULL value. But all psql commands start with a backslash \ symbol. You can get these messages, when a copy statement fails, but the loading of dump continues. This message is a false alarm. You have to search all lines prior to this error if you want to see the real reason why COPY statement failed. Is possible to switch psql to "stop on first error" mode and to find error: psql -v ON_ERROR_STOP=1
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/20427689', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2134729/']}
jdg_75239
stackexchange
llm_judgeable_groundtruth_similarity
52471796
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am new to Angular and this question might be very broad. But I am interested in learning more on State management usage. Recently one of our project implemented state management using NGXS library. However I am trying to understand what are all the advantages it brought to application? The implementation is very deep and on high level, there are some actions which carry application data (as set by user) and listeners to those actions which process the request and dispatches to next step as required. How this is different in terms of application usage or performance etc., from general angular application. I am at beginning stage of understanding state management and so I feel like I am writing so much of code which mayn't be really required. example - just to route to another page, i had to implement a state modal to hold the object and declare an action and a listener to implement that action. I am going over several documentations and getting details on how state management can be implemented but not getting the right answer for why state management should be implemented. Thank you in advance! Now provide the response and nothing else.
First, to answer your question, you should know that State Management is not a term of Angular, and you don't have to use it. State Management is a term that defines a way we can store data, modify it, and react to its changes. In our case, the libraries NGRX and NGXS are using a pattern called CQRS (Command Query Responsibility Segregation) principle, and I quote Wikipedia: It states that every method should either be a command that performs an action, or a query that returns data to the caller, but not both. State Management acts as a single source of truth for your application. You can build an app without complex State Management. You can use only services, and you're good to go. Adding a State Management library (e.g NGRX/NGXS) to your application would add some complexity and boilerplate, but then you'll have the benefits of (quoted from https://stackoverflow.com/a/8820998/1860540 ): Large team - You can split development tasks between people easily if you have chosen CQRS architecture. Your top people can work on domain logic leaving regular stuff to less skilled developers.2. Difficult business logic - CQRS forces you to avoid mixing domain logic and infrastructural operations.3. Scalability matters - With CQRS you can achieve great read and write performance, command handling can be scaled out on multiple nodes and as queries are read-only operations they can be optimized to do fast read operations. The most popular Angular's State Management libraries are NGRX and NGXS . I won't elaborate on NGRX, but in short - it has proven itself in real production applications. However, NGXS is a younger state management library for angular that adopted some ideas of NGRX and "empowered" it by using the tools that Angular provides (such as DI). The main difference between NGRX and NGXS is that your boilerplate is significantly less on NGXS. If you're interested, you can read the main reason Why another state management for Angular . So to sum it up - If you're planning on building a large scaled application, then you should consider using State Management, although - you don't have to.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/52471796', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3367269/']}
jdg_75240