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 | 164967 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an Excel application in which I want to present the user with a list of the Data Source Names (ie: DSN's), whereby s/he can choose what data source to use. Hopefully once I've got the list, I can easily access the DSN properties to connect to the appropriate database. Please note, I do not want to use a DSN-less connection.
Now provide the response and nothing else.
| The DSN entries are stored in the registry in the following keys. HKEY_CURRENT_USER\Software\ODBC\ODBC.INI\ODBC Data SourcesHKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources This contains the list of all defined DSN. This acts as an global index and the specific details for each DSN are stored in a key with the DSN name under: HKEY_CURRENT_USER\Software\ODBC\ODBC.INIHKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI Create some entries in both User DSN and System DSN tabs from Data Sources (ODBC) control panel applet and check how these values are stored in the registry. The following example enumerate the DSN defined for the user trough Control Panel > Administrative Tools > Data Sources (ODBC) [User Dsn Tab]. http://support.microsoft.com/kb/178755 Option Explicit Private Declare Function RegOpenKeyEx Lib "advapi32.dll" _ Alias "RegOpenKeyExA" _ (ByVal hKey As Long, _ ByVal lpSubKey As String, _ ByVal ulOptions As Long, _ ByVal samDesired As Long, phkResult As Long) As Long Private Declare Function RegEnumValue Lib "advapi32.dll" _ Alias "RegEnumValueA" _ (ByVal hKey As Long, _ ByVal dwIndex As Long, _ ByVal lpValueName As String, _ lpcbValueName As Long, _ ByVal lpReserved As Long, _ lpType As Long, _ lpData As Any, _ lpcbData As Long) As Long Private Declare Function RegCloseKey Lib "advapi32.dll" _ (ByVal hKey As Long) As Long Const HKEY_CLASSES_ROOT = &H80000000 Const HKEY_CURRENT_USER = &H80000001 Const HKEY_LOCAL_MACHINE = &H80000002 Const HKEY_USERS = &H80000003 Const ERROR_SUCCESS = 0& Const SYNCHRONIZE = &H100000 Const STANDARD_RIGHTS_READ = &H20000 Const STANDARD_RIGHTS_WRITE = &H20000 Const STANDARD_RIGHTS_EXECUTE = &H20000 Const STANDARD_RIGHTS_REQUIRED = &HF0000 Const STANDARD_RIGHTS_ALL = &H1F0000 Const KEY_QUERY_VALUE = &H1 Const KEY_SET_VALUE = &H2 Const KEY_CREATE_SUB_KEY = &H4 Const KEY_ENUMERATE_SUB_KEYS = &H8 Const KEY_NOTIFY = &H10 Const KEY_CREATE_LINK = &H20 Const KEY_READ = ((STANDARD_RIGHTS_READ Or _ KEY_QUERY_VALUE Or _ KEY_ENUMERATE_SUB_KEYS Or _ KEY_NOTIFY) And _ (Not SYNCHRONIZE)) Const REG_DWORD = 4 Const REG_BINARY = 3 Const REG_SZ = 1 Private Sub Command1_Click() Dim lngKeyHandle As Long Dim lngResult As Long Dim lngCurIdx As Long Dim strValue As String Dim lngValueLen As Long Dim lngData As Long Dim lngDataLen As Long Dim strResult As String lngResult = RegOpenKeyEx(HKEY_CURRENT_USER, _ "SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources", _ 0&, _ KEY_READ, _ lngKeyHandle) If lngResult <> ERROR_SUCCESS Then MsgBox "Cannot open key" Exit Sub End If lngCurIdx = 0 Do lngValueLen = 2000 strValue = String(lngValueLen, 0) lngDataLen = 2000 lngResult = RegEnumValue(lngKeyHandle, _ lngCurIdx, _ ByVal strValue, _ lngValueLen, _ 0&, _ REG_DWORD, _ ByVal lngData, _ lngDataLen) lngCurIdx = lngCurIdx + 1 If lngResult = ERROR_SUCCESS Then strResult = strResult & lngCurIdx & ": " & Left(strValue, lngValueLen) & vbCrLf End If Loop While lngResult = ERROR_SUCCESS Call RegCloseKey(lngKeyHandle) Call MsgBox(strResult, vbInformation) End Sub | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/164967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1354/']} | jdg_86041 |
stackexchange | llm_judgeable_groundtruth_similarity | 37200 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm not a security expert, so I might be asking a silly question, but let me describe what I am thinking about. First, I know that a lot of web sites store hashed/encrypted passwords which could be decrypted by brute force attack once the table on db is hacked. Hackers might even be able to use the passwords in other websites and access other confidential info. Given that AES cannot be broken why can't we just use a logic similar to the authenticated encryption ? here is another relevant link.For example, Prepare 1kb random binary file as expected file. Encrypt the expected file using a hashed password When a user logs in the system, validate the password by decrypting the encrypted file and check against the expected file. If fails reject the log-in.I suppose we can use the same logic for secret questions and answers for resetting password without actually storing answers. If the confidential files are also encrypted using the password, then I guess the user will not be able to reset password. Is there any way to do it? While writing this, I found a very similar question , but they are talking about client side decryption and I'm talking about server side (or only within the local system). I'd really appreciate any comments and suggestions.
Now provide the response and nothing else.
| Actually your proposal is just a variation of a hashed password. Only in this case it is not the hash which is verified, rather an encrypted/decrypted blob. Hence it has mostly the same advantages and drawbacks of (reasonably implemented) hashed passwords. See PBKDF . When properly designed - like e.g. bcrypt (c.f. Do any security experts recommend bcrypt for password storage? ) - it offers rather good security for most scenarios. The question you are referring to ( user authentication by decrypting a random blob ) actually covers it rather well, I'd say. As for user's data encrypted by the password - change in the password would of course require re-encrypting anything encrypted with the old one (i.e. decrypt with old one, encrypt with new one), which is generally performance expensive thing to do. This is usually circumvented in a layered manner: the data itself is encrypted with a randomly generated key, which in turn is encrypted with a password-derived one. If one decides to change the password, all that is needed is re-encrypting the real encryption key. It also allows one to use several passwords to access the same data (one example of this very way of encrypting data is LUKS ). That said, should you intend to create your own cryptography solutution, read Is my developer's home-brew password security right or wrong, and why? first. | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/37200', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/26968/']} | jdg_86042 |
stackexchange | llm_judgeable_groundtruth_similarity | 95794 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Suppose we have a (possibly infinite) group given by generators and relations. One way to prove some inequality is to construct the representation of the group and show inequality in the representation. Is there some other methods?
Now provide the response and nothing else.
| The most general way is to use the complete presentations. See the book by Sims, for example. The idea is this. Find a presentation of your group as a monoid, that is include inverses of generators in the generating set, include also all relations $aa^{-1}=1$. Then use the completion algorithm (called the Knuth-Bendix procedure) to produce a complete monoid presentation of your group. If you are lucky, the complete presentation will be finite or a least recursive. It will consist of relations $u=v$. Now if you want to check whether a word $w$ is 1 or not, you just apply relations $u=v$ from your complete presentation to $w$ (i.e. replace subword equal to $u$ in $w$ by $v$) until you get a word to which you cannot apply any relation. If that word is empty, $w=1$, if not, $w\ne 1$. Complete recursive presentations exist surprisingly often. For example, many Coxeter groups have them (also see Sims' book mentioned above). Of course, Coxeter groups are residually finite and even linear, so there are other procedures to solve the word problem. But even complicated, non-residually finite, groups, like the R. Thompson group $F$ , have nice recursive complete presentations. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/95794', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8381/']} | jdg_86043 |
stackexchange | llm_judgeable_groundtruth_similarity | 347666 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
My confusion stems from a an led that shows: Input(DC): 600mA-700mA / 3V-3.4V.the product suggests a constant current led driver (same brand as LED) that shows: Output: Current 600mA (Constant) ; Voltage 18-34V In researching I have read that excessive current will burn out the LED and over time as the battery drains the amps drawn gets smaller resulting in the need for a constant current led driver. I am having trouble finding information for my question : Can LEDs receive a voltage above their recommended value if the current is constant? Also, side question, if the current is constant at 600mA and the led's current takes 600mA, then I don't need a resistor? update: Thank you for all of your input. @mkeith was correct when saying "I think the point of confusion is that you don't understand the relationship between the power source and the load." I was under the impression that only the value of the Amps through an led mattered. I thought that since the company suggested the driver with a minimum output voltage of 18V, when the LED that it was referenced from, had a voltage of 3-3.3V, that that meant the constant current is what mattered. I was asking if the higher voltage (18V from the driver vs. 3.3V of the LED) with the correct Amps would be okay. I have com to realize why this driver was suggested. wiring the 3V LED in series to get about 18V maybe have been the intended use.additionally, I better understand the difference between constant current and constant voltage and how the LED will control the amps (when constant voltage is applied) and the Volts (when constant current is applied)
Now provide the response and nothing else.
| The driver is inappropriate for the LED because the minimum voltage from the driver (18V) is greater than the minimum LED voltage at 600mA (3V). The driver is likely designed for LED arrays that have at least 6 dice in series, so 18V. When you feed the particular LED die you mention with a constant current between 600 and 700mA you will get a voltage (assuming you have not destroyed the LED) that will be between 3V and 3.4V (or maybe the voltage is specified at a particular current). If you do not exceed the recommended current, the LED voltage should not exceed the range given (it will actually drop a bit as the LED heats up). You only get to pick either the voltage or the current. With an LED, you are expected to pick the current and the voltage across the LED will be a result of that current. If you tried to run the LED from a constant voltage supply you would have to find the voltage experimentally and it would not be stable (and could kill the LED). | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/347666', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/169864/']} | jdg_86044 |
stackexchange | llm_judgeable_groundtruth_similarity | 14035883 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have some columns type int, but value is empty. So I want to convert empty to null when I insert to database.I use code: function toDB($string) { if ($string == '' || $string == "''") { return 'null'; } else { return "'$string'"; }}//age,month,year is type integer.$name="Veo ve";$age='10';$month='';$year=''; $query="Insert Into tr_view(name,age,month,year) values ({toDB($name)},{toDB($age)},{toDB($month)},{toDB($year)}) $db->setQuery($query); $result= $db->query(); But it show error: pg_query(): Query failed: ERROR: syntax error at or near ";" LINE 153: {toDB(10)}, ^ in... Why?
Now provide the response and nothing else.
| There is the NULLIF() function: SELECT NULLIF(var, ''); If var equals the 2nd parameter, you get NULL instead. The example replaces the empty string '' with NULL . There is no "empty string" for the type integer . Both parameters must be of compatible type, so sanitize your input in PHP. If you did not define a column default, you can also just omit the column in the INSERT command and it will be filled with NULL (which is the default DEFAULT ). Check if the parameter is empty in PHP and don't include the column in the INSERT command if it is. Or use the PHP literal NULL instead like Quassnoi demonstrates here . The rest only makes sense for string types To make absolutely sure , nobody can enter an empty string add a CHECK constraint to the table: ALTER TABLE tr_viewADD CONSTRAINT tr_view_age_not_empty CHECK (age <> ''); To avoid exceptions caused by this, you could add a trigger that fixes input automatically: CREATE OR REPLACE FUNCTION trg_tr_view_avoid_empty() RETURNS trigger LANGUAGE plpgsql AS$func$BEGIN IF NEW.age = '' THEN NEW.age := NULL; END IF; IF NEW.month = '' THEN NEW.month := NULL; END IF; RETURN NEW;END$func$;CREATE TRIGGER tr_view_avoid_emptyBEFORE INSERT OR UPDATE ON tr_viewFOR EACH ROWWHEN (NEW.age = '' OR NEW.month = '')EXECUTE PROCEDURE trg_tr_view_avoid_empty(); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14035883', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1497597/']} | jdg_86045 |
stackexchange | llm_judgeable_groundtruth_similarity | 50344153 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
is it possible to retrieve the innermost type of stacked templates of the same type from within the template ? I'd like to retrieve the double type in the following example: template<typename T>struct is_a : std::false_type {};template<typename T>struct A{ using type = std::conditional_t< is_a<T>::value, T::type, // if it's an A, go deeper T>; // if not, we're done};template<typename T>struct is_a<A<T>> : std::true_type {};int main(){ A<A<A<A<A<double>>>>>::type d = 3.0; return 0;} It was motivated by this question . Also, I found this post , indicating that it may have something do to with typename or template keyword placing, but I couldn't get it to work myself.
Now provide the response and nothing else.
| Unless I'm missing something I'd just partially specialize a template to make things easier template<typename T>struct A{ using type = T;};template<typename T>struct A<A<T>>{ using type = typename A<T>::type;};int main(){ A<double>::type a = 5.0; A<A<double>>::type d = 3.0; A<A<A<double>>>::type c = 9.5; return 0;} Live sample | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50344153', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7925800/']} | jdg_86046 |
stackexchange | llm_judgeable_groundtruth_similarity | 402035 |
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've been challenged to "improve Skype performance" for calls within my organisation. Having read the Skype IT Administrators Guide I am wondering whether we might have a performance issue where the Skype Clients in a call are all on our WAN. The call is initiated by a Skype Client at our head office, and terminated on a Skype Client in a remote office connected via IPSEC VPN. Where this happens, I assume the trafficfrom Client A (encrypted by Skype) goes to our ASA 5510, where it is furtehr encrypted, sent to the remote ASA 5505 decrypted, then passed to Client B which decrypts the Skype encryption. Would the call quality benefit if the traffic didn't go over the VPN, but instead only relied on Skype's encryption? I imagine I could achieve this by setting up a SOCKS5 proxy in our HQ DMZ for Skype traffic. Then the traffic goes from Client A to Proxy, over the Skype relay network, then arrives at Cisco ASA 5505 as any other internet traffic, and then to Client B. Is there likely to be any performance benefit in doing this? If so, is there a way to do it that doesn't require a proxy? Has anyone else tackled this?
Now provide the response and nothing else.
| At first blush, it looks like Debian is stretching the boundaries for sending an ICMP redirect; quoting RFC 792 (Internet Protocol) . The gateway sends a redirect message to a host in the following situation. A gateway, G1, receives an internet datagram from a host on a network to which the gateway is attached. The gateway, G1, checks its routing table and obtains the address of the next gateway, G2, on the route to the datagram's internet destination network, X. If G2 and the host identified by the internet source address of the datagram are on the same network, a redirect message is sent to the host. The redirect message advises the host to send its traffic for network X directly to gateway G2 as this is a shorter path to the destination. The gateway forwards the original datagram's data to its internet destination. In this case, G1 is 10.1.2.1 ( eth1:0 above), X is 10.1.1.0/24 and G2 is 10.1.1.12 , and the source is 10.1.2.20 (i.e. G2 and the host identified by the internet source address of the datagram are **NOT** on the same network ). Maybe this has been historically interpreted differently in the case of interface aliases (or secondary addresses) on the same interface, but strictly speaking I'm not sure we should see Debian send that redirect. Depending on your requirements, you might be able to solve this by making the subnet for eth1 something like 10.1.0.0/22 (host addresses from 10.1.0.1 - 10.1.3.254 ) instead of using interface aliases for individual /24 blocks ( eth1 , eth1:0 , eth1:1 , eth1:2 ); if you did this, you'll need to change the netmask of all hosts attached and you wouldn't be able to use 10.1.4.x unless you expanded to a /21 . EDIT We're venturing a bit outside the scope of the original question, but I'll help work through the design/security issues mentioned in your comment. If you want to isolate users in your office from each other, let's step back for a second and look at some security issues with what you have now: You currently have four subnets in one ethernet broadcast domain. All users in one broadcast domain doesn't meet the security requirements you articulated in the comments (all machines will see broadcasts from other machines and could spontaneously send traffic to each other at Layer2, regardless of their default gateway being eth1 , eth1:0 , eth1:1 or eth1:2 ). There is nothing your Debian firewall can do to change this (or maybe I should say there is nothing your Debian firewall should do to change this :-). Acquire a managed ethernet switch which supports vlans and dot1q tagging Plug all your users into the ethernet switch Assign users into Vlans (in linux and on the ethernet switch) based on security policy stated in the comments. A properly-configured Vlan will go a long way to fixing the issues mentioned above. With respect to multiple security domains accessing 10.1.1.12 , you have a couple of options: Option 1 : Given the requirement for all users to access services on 10.1.1.12 , you could put all users in one IP subnet and implement security policies with Private Vlans (RFC 5517) , assuming your ethernet switch supports this. This option will not require iptables rules to limit intra-office traffic from crossing security boundaries (that is accomplished with private Vlans). Option 2 : You could put users into different subnets (corresponding to Vlans) and implement iptables rules to deploy your security policies After you have secured your network at the Vlan level, set up source-based routing policies to send different users out your multiple uplinks. FYI, if you have a router or Layer3 ethernet switch that supports VRFs , some of this gets even easier; IIRC, you have a Cisco IOS machine onsite. Depending on the model and software image you already have, that Cisco could do a fantastic job isolating your users from each other and implement source-based routing policies. | {} | {'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/402035', 'https://serverfault.com', 'https://serverfault.com/users/31143/']} | jdg_86047 |
stackexchange | llm_judgeable_groundtruth_similarity | 16064957 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider the following AppleScript: on is_running(appName) tell application "System Events" to (name of processes) contains appNameend is_runningset safRunning to is_running("Safari")if safRunning then tell application "Safari" -- Stuff I only want executed if Safari is running goes here. end tell return "Running"else return "Not running"end if The problem: when I run this via the osascript command line utility, if Safari is not running, it gets launched and the script reports "Running". This is not the behaviour I desire or would expect. Note that it works as desired/expected when run within AppleScript Editor. Is this an osascript bug / known issue? Or is it somehow intended behaviour for reasons I'm missing? Can anyone get it to work as desired? (BTW I'm running OSX 10.7.5; I can't see how to get osascript to report a version number). If you comment out the tell / end tell lines, it behaves as I'd expect: if Safari is not running, it doesn't launch it, and prints "Not running". So it seems to me like the tell is what's causing Safari to be launched, but it doesn't need to be actually executed, just present in the script...? For a while I wondered if maybe this was just how tell is supposed to work, but since it doesn't work like this in AppleScript Editor, I guess not... In fact, here's another, madder, version with similar behaviour: on is_running(appName) tell application "System Events" to (name of processes) contains appNameend is_runningset safRunning to is_running("Safari")return safRunningif false then tell application "Safari" end tellend if This still always launches Safari, even though tell is inside an if false block after the return statement! (But again, this is fine in AppleScript Editor.) BTW, this behaviour isn't limited to Safari, but it also isn't universal: Affected apps include: Safari, TextEdit, iPhoto, AppleScript Editor, iTerm, ... Non-affected apps include: Google Chrome, iTunes, Preview, Mail, Terminal, Address Book, Echofon, ... So, does anyone have any ideas about how I might fix or route around this? Is it an osascript bug? Or am I missing something about AppleScript's semantics? For context: I'm trying to write a script (to be embedded/called from some python) which queries open browsers for the URLs of any tabs they have open; I've got it all working fine except that it always launches Safari, whether it's open or not. I've boiled down that undesirable behaviour to the simple test case shown above. I'm not aware of any way to run this script from python without using osascript , other than appscript , which I don't want to use because it's no longer developed/supported/recommended . Many thanks for all inputs / insights!
Now provide the response and nothing else.
| I suspect the reason you are getting this is because each time you call the script from the command line with osascript the script is being compiled. The act of compiling on a tell application will afaik make the app launch. Calling the script from the command line with osascript from a pre-compiled file i.e . scpt does not cause this behaviour because the is no compiling to be done. But calling it from a plain text (.txt,.sh ) file will so the app will launch. If you do not want to use a .scpt file and want to use a plain text file then you could try the trick of putting a run script command in the applescript. on is_running(appName) tell application "System Events" to (name of processes) contains appNameend is_runningset safRunning to is_running("Safari")if safRunning then run script "tell application \"Safari\" open location \"http://google.com\" end tell" return "Running"else return "Not running"end if The script in the run script is only compiled when needed. You will need to escape any characters like quotes as in my example. It will be easier if you write the script in a normal applescript document first and compiled it to check for errors. Then copy it to the plain text file. UPDATE ** The method I used above was from a old script I had used to solved this issue a while before I answered here. The answer works and is not trying to be elegant. ;-) I actually like user1804762 method below. As it does work but feel the Answer is not clear enough so I will give an example on using it. set appName to "Safari"if application appName is running then tell application id (id of application appName) open location "http://google.com" end tell return "Running"else return "Not running"end if This script can be run from the command line with osascript example: osascript /Users/USERNAME/Desktop/foo.scpt Notice that the script is saved as a compiled script. This will work ok and you can also save and use it as a plain text script. i.e. osascript /Users/USERNAME/Desktop/foo.applescript | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/16064957', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/392743/']} | jdg_86048 |
stackexchange | llm_judgeable_groundtruth_similarity | 1129517 |
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 find out if an event is hooked up or not. I've looked around, but I've only found solutions that involved modifying the internals of the object that contains the event. I don't want to do this. Here is some test code that I thought would work: // Create a new event handler that takes in the function I want to execute when the event firesEventHandler myEventHandler = new EventHandler(myObject_SomeEvent);// Get "p1" number events that got hooked up to myEventHandlerint p1 = myEventHandler.GetInvocationList().Length;// Now actually hook an event upmyObject.SomeEvent += m_myEventHandler;// Re check "p2" number of events hooked up to myEventHandlerint p2 = myEventHandler.GetInvocationList().Length; Unfort the above is dead wrong. I thought that somehow the "invocationList" in myEventHandler would automatically get updated when I hooked an event to it. But no, this is not the case. The length of this always comes back as one. Is there anyway to determine this from outside the object that contains the event?
Now provide the response and nothing else.
| There is a subtle illusion presented by the C# event keyword and that is that an event has an invocation list. If you declare the event using the C# event keyword, the compiler will generate a private delegate in your class, and manage it for you. Whenever you subscribe to the event, the compiler-generated add method is invoked, which appends the event handler to the delegate's invocation list. There is no explicit invocation list for the event. Thus, the only way to get at the delegate's invocation list is to preferably: Use reflection to access the compiler-generated delegate OR Create a non-private delegate (perhaps internal) and implement the event's add/remove methods manually (this prevents the compiler from generating the event's default implementation) Here is an example demonstrating the latter technique. class MyType{ internal EventHandler<int> _delegate; public event EventHandler<int> MyEvent; { add { _delegate += value; } remove { _delegate -= value; } }} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1129517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/88364/']} | jdg_86049 |
stackexchange | llm_judgeable_groundtruth_similarity | 14279344 |
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 drawing several bar and pie charts using matplotlib.pyplot.bar() and matplotlib.pyplot.pie() . In both functions, I can change the colors of the bars and wedges. However, I need to print these charts in black and white. It would be much more useful to be able to put textures on the bars and wedges, similar to the Line2D marker property which is available for drawing lines. Can I maybe fill the bars and wedges with these markers in a consistent way? Or is there any other way to achieve something like that?
Now provide the response and nothing else.
| With bar() , you can directly use hatches (with some backends): http://matplotlib.org/examples/pylab_examples/hatch_demo.html : It works by adding the hatch argument to your call to bar() . As for pie() , it does not have a hatch keyword. You can instead get the individual pie chart patches and add hatches to them: you get the patches with: patches = pie(…)[0] # The first element of the returned tuple are the pie slices then you apply the hatches to each slice (patch): patches[0].set_hatch('/') # Pie slice #0 hatched. (hatches list at https://matplotlib.org/api/_as_gen/matplotlib.patches.Patch.html#matplotlib.patches.Patch.set_hatch ). And you apply the changes with: pyplot.draw() | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14279344', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1125413/']} | jdg_86050 |
stackexchange | llm_judgeable_groundtruth_similarity | 3332079 |
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 question is regarding the ASP.NET webservice that i am creating using the DAL-BLL architecture for my final school project. I have a stored procedure, which is a select query with an inner join for 2 tables. Hence the stored procedure returns multi-table value. One of my DAL tableAdapter methods accesses this stored procedure. How do i retrieve the return value in the BLL? Do i have to create a class structure similar to the one supposed to be returned by the stored proc? or is there a direct way to achieve the same? Help greatly appreciated. Please let me know if someone needs code applet to get a better understanding. Thanks Here is some more information:I am using the SQL dataset (.xsd) in DAL. So i have a datatable called "Insurance", which has a tableAdapter. One of the queries in the adapter references to a stored procedure, which has an inner join. So my SP looks like: ALTER PROCEDURE dbo.GetInsurancesPaged ( @startRowIndex int, @maximumRows int, @patientID int )AS select * from ( SELECT Insurance.insuranceID, Insurance.memberID, Insurance.groupID, Insurance.accountType, Insurance.comments, Insurance.patient, Insurance.company, InsuranceCompany.companyID, InsuranceCompany.companyName, InsuranceCompany.address, InsuranceCompany.phone, InsuranceCompany.fax, ROW_NUMBER() over (order by Insurance.dateModified DESC) as ROWRANKFROM Insurance INNER JOIN InsuranceCompany ON Insurance.company = InsuranceCompany.companyIDWHERE Insurance.patient = @patientID ) AS DataWithRowNumbersWHERE ROWRANK > @startRowIndex AND ROWRANK <= (@startRowIndex + @maximumRows) So this SP returns a datatable which will be a combination of the 2 tables in the inner join. Please correct me if i am wrong. Now in my BLL, i have: [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)] public mySys.InsuranceDataTable GetInsurancesPaged(int startRowIndex, int maximumRows, int patientID) { return insAdapter.GetInsurancesPaged(startRowIndex, maximumRows, patientID); } where insAdapter is an instance of insuranceTableAdapter This gives an error on execution. I can execute the SP successfully, so i think the problem is only bcz i am trying to return a wrong datatable from the BLL.Please help me solve this.
Now provide the response and nothing else.
| It isn't throwing an UnknownHostException . It's just appearing in the message of the exception you actually caught. It's likely the underlying root cause of the exception you caught. To determine the actual exception, you should print a bit more detail. E.g. } catch (Exception e) { logger.error("Caught Exception in login(): " + e.getClass().getName() + ": " + e.getMessage());} or just using Throwable#toString() which already includes both exception type and message: } catch (Exception e) { logger.error("Caught Exception in login(): " + e);} or just pass the Exception in as 2nd logger argument, if well configured its stacktrace will be printed: } catch (Exception e) { logger.error("Caught Exception in login(): " + e.getMessage(), e);} Update as per your comments: your best bet is to update the catch as follows: } catch (ClientTransportException e) { if (e.getCause() instanceof UnknownHostException) { // UHE. } else { // Other. }} You should absolutely not differentiate based on the message. It's receipe for portability trouble. The message is namely a sensitive subject for changes which may even be locale dependent! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3332079', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/214741/']} | jdg_86051 |
stackexchange | llm_judgeable_groundtruth_similarity | 55382596 |
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 seen that NLP models such as BERT utilize WordPiece for tokenization. In WordPiece, we split the tokens like playing to play and ##ing . It is mentioned that it covers a wider spectrum of Out-Of-Vocabulary (OOV) words. Can someone please help me explain how WordPiece tokenization is actually done, and how it handles effectively helps to rare/OOV words?
Now provide the response and nothing else.
| WordPiece and BPE are two similar and commonly used techniques to segment words into subword-level in NLP tasks.In both cases, the vocabulary is initialized with all the individual characters in the language, and then the most frequent/likely combinations of the symbols in the vocabulary are iteratively added to the vocabulary. Consider the WordPiece algorithm from the original paper (wording slightly modified by me): Initialize the word unit inventory with all the characters in the text. Build a language model on the training data using the inventory from 1. Generate a new word unit by combining two units out of the current word inventory to increment the word unit inventory by one. Choose the new word unit out of all the possible ones that increases the likelihood on the training data the most when added to the model. Goto 2 until a predefined limit of word units is reached or the likelihood increase falls below a certain threshold. The BPE algorithm only differs in Step 3, where it simply chooses the new word unit as the combination of the next most frequently occurring pair among the current set of subword units. Example Input text : she walked . he is a dog walker . i walk First 3 BPE Merges : w a = wa l k = lk wa lk = walk So at this stage, your vocabulary includes all the initial characters, along with wa , lk , and walk . You usually do this for a fixed number of merge operations. How does it handle rare/OOV words? Quite simply, OOV words are impossible if you use such a segmentation method. Any word which does not occur in the vocabulary will be broken down into subword units. Similarly, for rare words, given that the number of subword merges we used is limited, the word will not occur in the vocabulary, so it will be split into more frequent subwords. How does this help? Imagine that the model sees the word walking . Unless this word occurs at least a few times in the training corpus, the model can't learn to deal with this word very well. However, it may have the words walked , walker , walks , each occurring only a few times. Without subword segmentation, all these words are treated as completely different words by the model. However, if these get segmented as walk@@ ing , walk@@ ed , etc., notice that all of them will now have walk@@ in common, which will occur much frequently while training, and the model might be able to learn more about it. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/55382596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3711601/']} | jdg_86052 |
stackexchange | llm_judgeable_groundtruth_similarity | 287045 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm doing Analytics Edge course from EDX. The course is using R while I'm using Python. In linear regression, in order to improve the model, we have to figure out the most significant features. The course is using the summary function in R to look at the dots signifying the importance of the feature and the p-values. No such thing exists in sklearn. So I'm using coefficients to see the most significant features.But I'm not sure I should trust coefficients to select the most significant features (even though for this problem, they are in agreement) So is coefficients from linearRegression in sklearn reliable in determining the significance of the features?Are p-values themselves reliable in detecting the significant features? (I know of statsmodels and do not wish to use)
Now provide the response and nothing else.
| To begin with, just to put the issue aside: clearly, if the features are not normalized to 0 mean and unit variance, it's easy to build cases where the coefficient means very little. In general, if you take a feature and multiply it by $\alpha$, a regressor will divide the coefficient by $\alpha$, for example. Even when the variables are all normalized, large coefficients can mean very little. Say that $x$ is some hidden feature somewhat correlated with $y$, and $z$ and $w$ are observed featured which are slightly noisy versions of $x$, the regression matrix will be not very well defined, and you could get large-magnitude coefficients for $z$ and $w$ (perhaps with opposite signs). Regularization is usually used precisely to avoid this. Perhaps sklearn.feature_selection.f_regression is similar to what you're looking for. It summarizes, for each individual feature, both the f-score and the p-value. Alternatively, for any regression scheme, a "black box" approach could be to build the model for all features except $x$, and assess its performance (using cross validation). You could then rank the features based on the performance. Feature importance is a bit trick to define. In the above two schemes, if $x_i$ is the $i$the resulting "most important" feature, it does not necessarily mean that using $x_1, \ldots x_{i - 1}$, it is indeed the next most important one (perhaps its information is already contained in the preceding ones). | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/287045', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/159585/']} | jdg_86053 |
stackexchange | llm_judgeable_groundtruth_similarity | 29082794 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using languageTool with python. But it is quite slow when I want to proceed really long text or lot of texts. I keep on reading how long is the suggestion mechanism, I actually do not need any suggestion, I am interested only on rule_id and category. Does someone know how to turn off this suggestion mechanism in order to gain some processing power ?
Now provide the response and nothing else.
| Assuming GroupDetails as in orid's answer have you tried JPA 2.1 @ConstructorResult ? @SqlResultSetMapping( name="groupDetailsMapping", classes={ @ConstructorResult( targetClass=GroupDetails.class, columns={ @ColumnResult(name="GROUP_ID"), @ColumnResult(name="USER_ID") } ) })@NamedNativeQuery(name="getGroupDetails", query="SELECT g.*, gm.* FROM group g LEFT JOIN group_members gm ON g.group_id = gm.group_id and gm.user_id = :userId WHERE g.group_id = :groupId", resultSetMapping="groupDetailsMapping") and use following in repository interface: GroupDetails getGroupDetails(@Param("userId") Integer userId, @Param("groupId") Integer groupId); According to Spring Data JPA documentation , spring will first try to find named query matching your method name - so by using @NamedNativeQuery , @SqlResultSetMapping and @ConstructorResult you should be able to achieve that behaviour | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/29082794', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3036174/']} | jdg_86054 |
stackexchange | llm_judgeable_groundtruth_similarity | 26951812 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In my F# application I often need to perform a case-insensitive search of a string within a string, so I created a function with the appropriate comparison: let indexOf (str:string) (value:string) startIndex = match str.IndexOf(value, startIndex, StringComparison.OrdinalIgnoreCase) with | index when index >= 0 -> Some index | _ -> None I do not like the fact, that when I want to search from the beginning, I have to pass the redundant 0 as the start index. I am relatively new to both F# and the functional programming, so I would like to know what is the preferred (cleanest) solution from the functional point of view? Create two versions: let indexOfFrom (str:string) (value:string) startIndex = (...)let indexOf str value = indexOfFrom str value 0 Use Option type: let foundIndex = indexOf "bar foobar" "bar" (Some 4) Create a dedicated discriminated union: type Position = | Beginning | StartIndex of index : intlet foundIndex = indexOf "bar foobar" "bar" (Index 4) Place the 'indexOf' function inside a type and use the 'classic' overloading. Place the 'indexOf' function inside a type and use F# optional arguments.
Now provide the response and nothing else.
| If you are defining the functionality as F# functions, then I think that using two separate functions (with reasonably descriptive names) is probably the best option you have. So I'd go with your first option (I definitely prefer this option over defining a discriminated union just for this single purpose): let indexOfFrom (str:string) (value:string) startIndex = (...)let indexOf str value = indexOfFrom str value 0 The alternative is to define the functionality as members of a type - then you can use both overloading and F# optional arguments, but you'd have to access them using full name String.IndexOf . You could write something like: type String = static member IndexOf(str:string, value:string, startIndex) = (...) static member IndexOf(str, value) = String.IndexOf(str, value, 0) Or, using optional parameters: type String = static member IndexOf(str:string, value:string, ?startIndex) = (...) Which of the options is the best one? If you're designing functional API (e.g. domain-specific language), then your option with two separate functions is probably the best choice. If you're aiming to design a nice F# API, then I think your option (multiple functions) or optional parameters are quite reasonable. Functions are used quite heavily in Deedle and F# Charting relies on optional arguments. The benefit of using overloading is that the library will be also nicely usable from C#. So, if you're thinking of calling the library from C#, this is pretty much the only option. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26951812', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/603268/']} | jdg_86055 |
stackexchange | llm_judgeable_groundtruth_similarity | 33798447 |
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 project , just one module , but need to package two jar, with the different charset (just the config.yml file need two be differet, in the resources folder). I have been try these way : use maven-jar-plugin , to add a classifier, it can package more than one jar file, but need to have one folder per jar in /target/classes . maven-jar-plugin can package two jar file , need different folder,like **/server/** and **/client/** , but I just need to change one file's chartset : **/config.yml with UTF-8 , and **/config.yml with UTF-16 use maven-resources-plugins , try to change chartset, but the <encoding>UTF-8</encoding> seems not work.. and I try to use maven-resources-plugins 's copy-resources , to copy the same .class file and the different config.yml (I create two folder in the /src/main/ , for two chartsets, /src/main/chartA/config.yml and /src/main/chartB/config.yml ) to two new folder (on compile phase, copy to /target/ChartA and /target/ChartB ) but show mark invaild .. I don't know why.. and it seems following a zigzag course.. at last I try the <profiles> tag, but seems can not package two profiles at the same time.. so , is that any way to replace one resource file or change the resources's chartset when compile/package and make two different jar package?
Now provide the response and nothing else.
| Actually it works out of the box. I think my mistake was using an old version of the data binding framework. Using the latest, this is the procedure: View: <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/username" android:text="Enter username:" android:onTextChanged="@{data.onTextChanged}" /> Model: public void onTextChanged(CharSequence s, int start, int before, int count) { Log.w("tag", "onTextChanged " + s);} Make also sure that you have assigned model into DataBinding For ex. in your activity lateinit var activityMainDataBinding: ActivityMainBindingoverride fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) activityMainDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main) val dataViewModel = ViewModelProvider(this).get(DataViewModel::class.java) activityMainDataBinding.dataModel = dataViewModel} Make sure you are referncing gradle build tools v1.5.0 or higher and have enabled databinding with android.dataBinding.enabled true in your build.gradle. edit: Functioning demo project here . view . model . | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/33798447', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5573619/']} | jdg_86056 |
stackexchange | llm_judgeable_groundtruth_similarity | 327335 |
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 am trying to make a good layout for the Quad SPI NOR flash memory MT25QL256ABA1EW9-0SIT with the STM32 MCU.My problem is that I find the memory chip pinout quite inconvenient. I have managed to swap pins on the MCU side the way that the signals reside next to each other but it is still difficult. Following the Micron Quad spi layout guide I have managed to: Not split the underlying ground plane (this is a 2 layer PCB), Make the clock signal short and possibly with least bending, Use no VIAS for signals routing However, I did not manage to: Keep any sensible impedance by calculating striplines (there is realy not much space and many signals) Keep the signal lengths similar. Here is the layout: After enlarging the image one can see the net names on the memory chip pads.I would like to ask you either in your opinion this design is sufficient for up to 80 Mhz clock transfer. For the comparison purposes, the pink shape in which the chip is inside of is 18 x 8 mm. The GND polygon pours are shelved for visibility.I would appreciate all help.
Now provide the response and nothing else.
| For FR4, using effective epsilon of 3.25 we get the wavelength of a 80 MHz signal in the PCB at 80 by calculating wavelength = (c/f) * (1/sqrt(epsilon)) = (300000000 m/s / 80000000 1/s) * (1/sqrt(3.25) = 2.06 meters. Using 1/16 of wavelength as the "safe limit" below which we don't need to worry about reflections and relative signal timing, it's safe_length = (1/16)* wavelength = 2.06 / 16 = 12.8 centimeters = 5 inches. Your signal traces are well below that limit. Your routing is good enough. https://www.jlab.org/accel/eecad/pdf/050rfdesign.pdf | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/327335', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/59894/']} | jdg_86057 |
stackexchange | llm_judgeable_groundtruth_similarity | 620653 |
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 observed the following pattern: Take the number $21$, and write cubes of each digit and add it; then we have; $21$$......> 2^3 + 1^3 = 9$ Now the result $9^3$ = $729$ From the result; $729$$......> 7^3 + 2^3 + 9^3 = 1080$ From $1080$$......> 1^3 + 0^3 + 8^3 + 0^3 = 153$ From $153$$......> 1^3 +5^3+3^3 = 153$ Now we cannot write further, in case even if we write there is no use, as we end up with the same number. Now my question is, If we start up with any number like $21$, we will end at any stage like $153$. Why does this method works? Also, I observed that, this procedure is failed for number $13$ and $25$. Why the above cited method failed in case of $13$ and $25?$ Let us write $13$ = $1^3 + 3^3$= $28$ Now $28$ = $2^3 + 8^3$= $520$ Now $520$ = $5^3 + 2^3$= $133$$...(1)$ Now $133$ = $1^3 + 3^3+ 3^3$= $55$ Now $55$ = $5^3 + 5^3$= $250$ Now $250$ = $2^3 + 5^3$= $133$$...(2)$ From $(1) and (2),$ we can understand that, the same steps are repeating. However, our initial example is quite different. Why the story is not applicable for some numbers like $13$ and $25?$ . Also is there any use of this kind of procedures... Thank you so much for reading this much big paragraphs.
Now provide the response and nothing else.
| The reason for the occurence of such cycles is the following: You are considering the orbit of the map $$\begin{eqnarray}f: \Bbb N& \rightarrow &\Bbb N \\ a_1\dots a_d &\mapsto &a_1^3+\dots + a_d^3.\end{eqnarray}$$ As the highest value for a $d$-digit number is obtained for $10^d-1$ and as $f(9999) = 4 \cdot 9^3 \leq 9999$, $f(n) \leq n$ is decreasing for $n\geq 10^4$, and also $f(n)<10^4$ for $n\leq 10^4$. Thus, starting with any number, we will eventually arrive at a number $<10^4$ and the sequence never exceeds that bound again. So every orbit under $f$ must be eventually periodic. By checking all numbers below $10^4$ we can verify that the only possible cycles are: $$\begin{eqnarray}1&\to& 1\\55 &\to& 250 \to 133 \to 55 \\136& \to& 244 \to 136 \\ 153 &\to& 153 \\ 160& \to& 217 \to 352 \to 160 \\ 370 &\to &370 \\ 371 &\to &371 \\ 407& \to &407 \\919& \to& 1459 \to 919\end{eqnarray}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/620653', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/117257/']} | jdg_86058 |
stackexchange | llm_judgeable_groundtruth_similarity | 703989 |
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:
Let us suppose that Bob and Alice both have walkie-talkies. They are both 3m apart from one another. Alice pushes her walkie-talkie to speak but instead of speaking, she starts walking toward Bob. Both Alice's and Bob's walkie talkies are facing each other in the same general direction (speakers are in the same direction). Alice suddenly reaches a point along her path to which Bob's Walkie talkie creates a loud pitch screeching sound, Alice moves, even more, closer and the sound escalates in pitch, it becomes unbearable and she unclicks the speak button. What is the cause of this high pitched sound coming from Bob's walkie talkie? Why only at a certain distance from Bob does the sound start? Summary: Alice is 3 m from Bob when she presses the speak button and walks towards Bob, at a certain point a loud screeching sound can be heard from Bob's walkie talkie. She moves closer and the sound gets louder and higher in pitch. The walkies talkie speakers are facing each other the whole time. This was a problem I came up with just out of interest and something I experienced myself.
Now provide the response and nothing else.
| It's called feedback . Here is what happens: When Alice presses TRANSMIT, it turns on the microphone in her radio and hence begins to transmit any noise that hits the mic. With Bob's radio on RECEIVE, its speaker is turned on and it plays out anything that it receives at that moment- which in this case is the audio signal transmitted from the mic in Alice's radio, which responds to any sound source near Alice. As Alice approaches Bob, her mic begins to detect noises coming from Bob's speaker, which her radio then transmits to Bob's radio, which plays it through Bob's speaker, which is picked up by the mic in Alice's radio, etc., etc. and the signal gets looped around and around and around, getting stronger all the while as Alice gets closer to Bob. The critical case for best looping happens when a sound in the loop has a wavelength in air approximately equal to the distance between the two radios, which at 10 feet is about 100Hz, at 1 foot it is 1000Hz and at 1 inch it is about 12,000Hz, so the pitch of the feedback will go higher and higher as the radios approach one another. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/703989', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/329861/']} | jdg_86059 |
stackexchange | llm_judgeable_groundtruth_similarity | 36965507 |
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 dictionary and am trying to write it to a file. exDict = {1:1, 2:2, 3:3}with open('file.txt', 'r') as file: file.write(exDict) I then have the error file.write(exDict)TypeError: must be str, not dict So I fixed that error but another error came exDict = {111:111, 222:222}with open('file.txt', 'r') as file: file.write(str(exDict)) The error: file.write(str(exDict))io.UnsupportedOperation: not writable How do I resolve this issue?
Now provide the response and nothing else.
| First of all you are opening file in read mode and trying to write into it.Consult - IO modes python Secondly, you can only write a string or bytes to a file. If you want to write a dictionary object, you either need to convert it into string or serialize it. import json# as requested in commentexDict = {'exDict': exDict}with open('file.txt', 'w') as file: file.write(json.dumps(exDict)) # use `json.loads` to do the reverse In case of serialization import cPickle as picklewith open('file.txt', 'w') as file: file.write(pickle.dumps(exDict)) # use `pickle.loads` to do the reverse For python 3.x pickle package import would be different import _pickle as pickle | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/36965507', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6277504/']} | jdg_86060 |
stackexchange | llm_judgeable_groundtruth_similarity | 23406212 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The code: int main(void){ auto a=1; return 0;} gets compiled without errors by the MS Visual Studio 2012 compiler, when the file has the .c extension. I have always thought that when you use the .c extension, compilation should be according to the C syntax, and not C++. Moreover, as far as I know auto without a type is allowed only in C++ since C++11, where it means that the type is deduced from the initializer. Does that mean that my compiler isn't sticking to C, or is the code actually correct in C-language?
Now provide the response and nothing else.
| auto is an old C keyword that means "local scope". auto a is the same as auto int a , and because local scope is the default for a variable declared inside a function, it's also the same as int a in this example. This keyword is actually a leftover from C's predecessor B, where there were no base types: everything was int , pointer to int , array of int .(*) Declarations would be either auto or extrn [sic]. C inherited the "everything is int " as a default rule, so you could declare integers with auto a;extern b;static c; ISO C got rid of this, but many compilers still accept it for backward compatibility. If it seems unfamiliar, then you should realise that a related rule is at work in unsigned d; // actually unsigned int which is still common in modern code. C++11 reused the keyword, which few if any C++ programmers were using with the original meaning, for its type inference. This is mostly safe because the "everything is int " rule from C had already been dropped in C++98; the only thing that breaks is auto T a , which no-one was using anyway. (Somewhere in his papers on the history of the language , Stroustrup comments on this, but I can't find the exact reference right now.) (*) String handling in B was interesting: you'd use arrays of int and pack multiple characters in each member. B was actually BCPL with different syntax. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/23406212', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2893702/']} | jdg_86061 |
stackexchange | llm_judgeable_groundtruth_similarity | 30602442 |
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 working on a macro-heavy Excel file with many ActiveX controls. All functions of the file work perfectly on my PC and another, but I get the error 32809 when the Auto_Open macro tries to activate a sheet on other PCs. I know this problem has been posted many other times on many different forums, but none of the solutions I have found that worked for others have worked for me. I have tried all of the following possible solutions: Deleting all *.exd files from both the Temp\Excel8.0 and Temp\VBA Disabling all ActiveX controls Opening the file on the PC that does not work and saving with a different name Modifying the code slightly, recompiling and saving Deleting all ActiveX controls and re-creating them on a PC that did not work The only thing that stopped the 32809 error from occurring was deleting all of the ActiveX controls, but if I save the now functioning file on my PC and try to open it on the one that did not work the error comes back. While deleting all of the controls did stop the error, it is extremely inconvenient to have to recreate all of the controls on a different PC when I make an update to the file. I am open to just about any suggestion that might help with this extremely frustrating problem.
Now provide the response and nothing else.
| What would happen is that newly-hashed passwords will be using the new algorithm - obviously. However, you shouldn't be concerned about this, because the whole thing is designed with forward-compatibility in mind - your code won't be broken when the default algorithm changes, as long as you're using the password_*() functions correctly. By correctly, I mean use password_verify() . password_verify() accepts a plain-text password and a hash, and it can easily determine what the used algorithm is by looking at the hash that you feed it. Therefore, it would also still be able to verify a password that has been hashed using an old algorithm - not just the previous one, but any algorithm that is supported. In fact, the sole purpose of the PASSWORD_DEFAULT constant is that you can easily migrate older hashes to a new algorithm (once one is added). This happens the following way: When a user logs in, you verify their password via password_verify() (any hashing algorithm that has a PASSWORD_<name> constant will work). You call password_needs_rehash() , and if the password you just verified is using an older algorithm (or a lower 'cost' paramater) - it will return boolean TRUE. If boolean TRUE was indeed returned, you can now replace the old hash with one that uses the new algorithm; you can do that during a login, because the user just gave you the password and you verified that it is correct. In summary - it's a really, really well-designed API and it solves problems for you that you haven't even thought about. Don't worry about it. Edit (noted in the comments): It should be noted, however, that new algorithms will quite probly result in longer hash lengths, so if you're storing the passwords in a database - don't limit the field's length (i.e. use a varchar(255) field). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30602442', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4966176/']} | jdg_86062 |
stackexchange | llm_judgeable_groundtruth_similarity | 2368172 |
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:
$$x^4 -2x^3-6x^2-2x+1=0$$$\left[\text{Hint let } v = x + \frac{1}{x}\right]$ I am stumped, and have no idea how to proceed. I have tried solving it, but have had no success. P.S: This question is meant to be solved, using only techniques for solving quadratic equations.
Now provide the response and nothing else.
| I think you meant for $$x^4 -2x^3-6x^2-2x+1=0$$ Obviously $x=0$ is not a solution. So we divide by $x^2$ and get $$x^2 -2x-6-2x^{-1}+x^{-2}=0$$$$(x^2+2+x^{-2}) - 2(x+x^{-1}) -8=0$$$$v^2-2v-8=0$$$$(v-4)(v+2)=0$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2368172', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/390350/']} | jdg_86063 |
stackexchange | llm_judgeable_groundtruth_similarity | 780048 |
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 just want to know if, in general, $\inf A < 1 $ implies that at least an element of $A$ is less then $1$. $$ \inf A < 1 \rightarrow \exists\alpha \in A : \alpha < 1 ? $$ $A \subset \mathbb{R}$ and is obviously bounded from below.
Now provide the response and nothing else.
| A formal proof would be something like this. If $A$ and $B$ are countable (and disjoint) sets, then there exist injective functions $f$ and $g$ from $A$ and $B$, respectively, to $\mathbb{N}$. Let $C=A\cup B$ and define a function $h:C\rightarrow\mathbb{N}$ as follows: $$h(z) = \begin{cases}2f(z) & \text{if } z\in A\\ 2g(z)+1 & \text{if } z\in B\end{cases}$$ Then, if $x\neq y$, we clearly have $h(x)\neq h(y)$ since if $x,y\in A$ this follows from the fact that $f$ is injective (analogously for $x,y\in B$) and if $x\in A$ and $y\in B$, we have that $h(x)$ is even while $h(y)$ is odd (analogously for $x\in B$, $y\in A$). Hence $h$ is an injective function from $C$ to $\mathbb{N}$ and thus, by definition, $C$ is countable. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/780048', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/127189/']} | jdg_86064 |
stackexchange | llm_judgeable_groundtruth_similarity | 5132343 |
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 am using c++ files stream asynchronously. I mean never using std::flush nor std::endl. My application writes a lot of data to a file and abruptly crashes down.Is the data remaining in the cache system flushed to the disk, or discarded (and lost)?
Now provide the response and nothing else.
| Complicating this problem is that there are multiple 'caches' in play. C++ streams have their own internal buffering mechanism. Streams don't ask the OS to write to disk until either (a) you've sent enough data into the buffer that the streams library thinks the write wouldn't be wasted (b) you ask for a flush specifically (c) the stream is in line-buffering mode, and you've sent along the endl . Any data in these buffers are lost when the program crashes. The OS will buffer writes to make best use of the limited amount of disk IO available. Writes will typically be flushed within five to thirty seconds; sooner if the programmer (or libraries) calls fdatasync(2) or fsync(2) or sync(2) (which asks for all dirty data to be flushed). Any data in the OS buffers are written to disk (eventually) when the program crashes, lost if the kernel crashes. The hard drive will buffer writes to try to make the best use of its slow head, rotational latency, etc. Data arrives in this buffer when the OS flushes its caches. Data in these buffers are written to disk when the program crashes, will probably be written to disk if the kernel crashes, and might be written to disk if the power is suddenly removed from the drive. (Some have enough power to continue writing their buffers, typically this would take less than a second anyway.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5132343', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/83331/']} | jdg_86065 |
stackexchange | llm_judgeable_groundtruth_similarity | 9331863 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
As I know, if I want to use pthread library in linux environment I must include pthread.h and compile the source code with -lpthread option.But I don't understand why I should compile with -lpthread option. I think the option is redundant... because I already declared to include pthread.h header file so that gcc links pthread library. Why does gcc not link pthread library file automatically by reading #include? Thanks in advance.
Now provide the response and nothing else.
| Well linking and compilation are two separate phases. You include the header pthread.h so that the compiler understands the data types & symbol names, which you use in your source files but are defined/declared in the pthread library header file. You link to the pthread libray using -lpthread so that the linker can actually find those symbols in the pthread library during the linking stage. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9331863', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/678558/']} | jdg_86066 |
stackexchange | llm_judgeable_groundtruth_similarity | 1997358 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We are having a rather long discussion in our company about whether or not to put an autoincrement key on EVERY table in our database. I can understand putting one on tables that would have a FK reference to, but I kind-of dislike putting such keys on each and every one of our tables, even though the keys would never be used. Please help with pros and cons for putting autoincrement keys on every table apart from taking extra space and slowing everything a little bit (we have some tables with hundreds of millions of records). Thanks
Now provide the response and nothing else.
| I'm assuming that almost all tables will have a primary key - and it's just a question of whether that key consists of one or more natural keys or a single auto-incrementing surrogate key. If you aren't using primary keys then you will generally get a lot of advantages of using them on almost all tables. So, here are some pros & cons of surrogate keys. First off, the pros: Most importantly: they allow the natural keys to change. Trivial example, a table of persons should have a primary key of person_id rather than last_name, first_name. Read performance - very small indexes are faster to scan. However, this is only helpful if you're actually constraining your query by the surrogate key. So, good for lookup tables, not so good for primary tables. Simplicity - if named appropriately, it makes the database easy to learn & use. Capacity - if you're designing something like a data warehouse fact table - surrogate keys on your dimensions allow you to keep a very narrow fact table - which results in huge capacity improvements. And cons: They don't prevent duplicates of the natural values. So, you'll still usually want a unique constraint (index) on the logical key. Write performance. With an extra index you're going to slow down inserts, updates and deletes that much more. Simplicity - for small tables of data that almost never changes they are unnecessary. For example, if you need a list of countries you can use the ISO list of countries. It includes meaningful abbreviations. This is better than a surrogate key because it's both small and useful. In general, surrogate keys are useful, just keep in mind the cons and don't hesitate to use natural keys when appropriate. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1997358', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/242953/']} | jdg_86067 |
stackexchange | llm_judgeable_groundtruth_similarity | 199577 |
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 am new in learning Turing patterns. Is there any sample code available to generate such patterns in ecology model (Lotka–Volterra model)? The above figure is taken from this paper , and is based on the following equations: More information about how the system was solved:
Now provide the response and nothing else.
| I developed a reaction-diffusion-advection model of pattern formation in semi-arid vegetation ( tiger bush ) 20 years ago, which shows a type of Turing instability. Plants ( $n$ ) consume water ( $w$ ) and facilitate each other by increasing water infiltration ( $wn^2$ term). The model is set on a hillside so water advects downhill at speed $v$ and plants disperse as a diffusion term. $${\partial n \over \partial t}=wn^2-mn+\left({\partial^2 \over \partial x^2}+{\partial^2 \over \partial y^2}\right)n$$ $${\partial w \over \partial t}=a-w-wn^2+v{\partial w \over \partial x}$$ Here's a Mathematica implementation using NDSolve 's MethodOfLines . a = 0.3; (* nondimensional rainfall *)m = 0.1; (* nondimensional plant mortality *)v = 182.5; (* nondimensional water speed *)tmax = 1000; (* max time *)l = 200; (* nondimensional size of domain *)pts = 40; (* numerical spatial resolution *)(* random initial condition for plants *)n0 = Interpolation[Flatten[Table[ {x, y, RandomReal[{0.99, 1.01}]}, {x, 0, l, l/pts}, {y, 0, l, l/pts}] , 1], InterpolationOrder -> 0];(* solve it *)sol = NDSolve[{ D[n[x, y, t], t] == w[x, y, t] n[x, y, t]^2 - m n[x, y, t] + D[n[x, y, t], {x, 2}] + D[n[x, y, t], {y, 2}], D[w[x, y, t], t] == a - w[x, y, t] - w[x, y, t] n[x, y, t]^2 - v D[w[x, y, t], x], (* initial conditions *) n[x, y, 0] == n0[x, y], w[x, y, 0] == a, (* periodic boundary conditions *) n[0, y, t] == n[l, y, t], w[0, y, t] == w[l, y, t], n[x, 0, t] == n[x, l, t], w[x, 0, t] == w[x, l, t] }, {w, n}, {t, 0, tmax}, {x, 0, l}, {y, 0, l}, Method -> {"MethodOfLines", "SpatialDiscretization" -> {"TensorProductGrid", "MinPoints" -> pts, "MaxPoints" -> pts}}][[1]];(* look at final distribution *)DensityPlot[Evaluate[n[x, y, tmax] /. sol], {x, 0, l}, {y, 0, l}, FrameLabel -> {"x", "y"}, PlotPoints -> pts, ColorFunctionScaling -> False] Animated: Reference: Klausmeier CA, 1999. Regular and irregular patterns in semiarid vegetation. Science 284: 1826–1828 ( pdf version that's not behind a paywall ) | {} | {'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/199577', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/65934/']} | jdg_86068 |
stackexchange | llm_judgeable_groundtruth_similarity | 5587485 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For a project I need a dynamic way of loading partial views, preferably by jquery / ajax. Here's the functionality I require: User enters form. A dropdownlist is shown and a generic partial view is rendered with some input controls. User selects a different value in the dropdown The partial view refreshes. Based on the value of the dropdown, it should load the partial view. Some values have custom views associated with them (I could name them with the primary key for instance), others don't. When there's no custom view; it should load the default. When there is one, it should of course load the custom one. And this should all be ajaxified when possible. I have read some things about dynamically loading partials, but I wanted to repost the complete case so I can find the best solution for this specific case.
Now provide the response and nothing else.
| Assuming you have a dropdown: @Html.DropDownListFor( x => x.ItemId, new SelectList(Model.Items, "Value", "Text"), new { id = "myddl", data_url = Url.Action("Foo", "SomeController") }) you could subscribe for the .change() event of this dropdown and send an AJAX request to a controller action which will return a partial and inject the result into the DOM: <script type="text/javascript">$(function() { $('#myddl').change(function() { var url = $(this).data('url'); var value = $(this).val(); $('#result').load(url, { value: value }) });});</script> And place a DIV tag where you want the partial view to render in your host view: <div id="result"></div> and inside the Foo action you could return a partial view: public ActionResult Foo(string value){ SomeModel model = ... return PartialView(model);} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5587485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/122036/']} | jdg_86069 |
stackexchange | llm_judgeable_groundtruth_similarity | 35042128 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In Python, it is possible to check if a float contains an integer value using n.is_integer() , based on this QA: How to check if a float value is a whole number . Does numpy have a similar operation that can be applied to arrays? Something that would allow the following: >>> x = np.array([1.0 2.1 3.0 3.9])>>> mask = np.is_integer(x)>>> maskarray([True, False, True, False], dtype=bool) It is possible to do something like >>> mask = (x == np.floor(x)) or >>> mask = (x == np.round(x)) but they involve calling extra methods and creating a bunch of temp arrays that could be potentially avoided. Does numpy have a vectorized function that checks for fractional parts of floats in a way similar to Python's float.is_integer ?
Now provide the response and nothing else.
| From what I can tell, there is no such function that returns a boolean array indicating whether floats have a fractional part or not. The closest I can find is np.modf which returns the fractional and integer parts, but that creates two float arrays (at least temporarily), so it might not be best memory-wise. If you're happy working in place, you can try something like: >>> np.mod(x, 1, out=x)>>> mask = (x == 0) This should save memory versus using round or floor (where you have to keep x around), but of course you lose the original x . The other option is to ask for it to be implemented in Numpy, or implement it yourself. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35042128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2988730/']} | jdg_86070 |
stackexchange | llm_judgeable_groundtruth_similarity | 936847 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The following bit of C# code does not seem to do anything: String str = "{3}";str.Replace("{", String.Empty);str.Replace("}", String.Empty);Console.WriteLine(str); This ends up spitting out: {3}. I have no idea why this is. I do this sort of thing in Java all the time. Is there some nuance of .NET string handling that eludes me?
Now provide the response and nothing else.
| The String class is immutable ; str.Replace will not alter str , it will return a new string with the result. Try this one instead: String str = "{3}";str = str.Replace("{", String.Empty);str = str.Replace("}", String.Empty);Console.WriteLine(str); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/936847', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2170994/']} | jdg_86071 |
stackexchange | llm_judgeable_groundtruth_similarity | 6674753 |
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 stuck in a very complex situation.I am working on a PHP Web apps for Greeting card. For this, I am using some Linux tools and TCPDF and FPDI.Let me tell you how it all works: there is 4 page greeting card template PDF file. this is custom size 5x7 inches 300dpi PDF file.I have added custom size in TCPDF as well case 'STANDARD_CARD' : {$pf = array(1500.00,2100.00);break;} what i do is, i use: pdftk templateX.pdf burst output page_%2d.pdf to separate each page of temple. now I use : $pdf = new FPDI($cardDetails['ORIENTATION'],"mm",$cardDetails['SIZE']); //set source file for $pdf->setSourceFile($pdfFile); $templateIndex = $pdf->importPage(1); $pdf->AddPage($cardDetails['ORIENTATION'],$cardDetails['SIZE']); $pdf->useTemplate($templateIndex,0,0); other things like, writing message printing images. and at the end save the file using: $pdf->output("file_name.pdf","F"); original PDF file (1st page only): (5x7 inches) Original pdf file Modified PDF and some PDF operations : (29x20 inches) modified PDF now the output I am getting is not 5x7 pdf it is a 29 x 20 inches file and that destroying my calculation and PDF as well. Please tell me what I am doing wrong...
Now provide the response and nothing else.
| Hi Ravish, I encountered also this issue. Actually my scenario is this. I have an original file which is a Legal size (8.5mm x 14mmmm) . When I an displaying it using the FPDI output as you did, it only display a letter size(8.5mm x 11mm) . So the result is: CROPPED PDF file. I made several googling and found several answers too from different posts. Here is the most relevant solution that I found. First is this piece of function code below: useTemplate $this->useTemplate($templateIndex, null, null, 0, 0, true); Normally, some developers set this as TRUE for the last argument. Yes, it is correct if you dont set the width and lenght. However, I would like to emphasize that the 4th and 5th argument specifies the width and length of an imported PDF. So, if you will adopt or get the actual size of the imported document, set the last argument to FALSE as this will tell that it will take the actual or specific size you set. Please take this sample codes I did: $pdf = new FPDI();$pdf -> setSourceFile('birform2316.pdf');$tplIdx = $pdf -> importPage(1);$size = $pdf->getTemplateSize($tplIdx);$pdf -> AddPage();$pdf ->useTemplate($tplIdx, null, null, $size['w'], 310, FALSE);$pdf -> SetFont('Arial');$pdf -> SetTextColor(0, 0, 0);$pdf -> SetXY(18, 174);$pdf -> Write(0, $employer_address);$pdf -> Output('myOwn.pdf', 'D'); With this code, I have produced a new PDF WITHOUT CROPPING the imported file that I set. Meaning, all details of the template( the original file ) has been displayed. Please take note also that I observed something while setting the size of my PDF: First, my file has an original width of 215.6mm and its length is 350.9mm. Now when I set the size of my PDF using the functions getTemplateSize and useTemplate such as: $size = $pdf->getTemplateSize($tplIdx);$pdf ->useTemplate($tplIdx, null, null, $size['w'], $size['h'],FALSE); or simply: $pdf ->useTemplate($tplIdx, null, null, 215.6, 350.9,FALSE); The result is, my new PDF file is CROPPED at the bottom and I dont know why. With this observation, I made several tests to find out the reason. And the result that came up is, there is a limit of length in generating a PDF file using FPDI. As you can see in my code above, I did not use the actual length of my file. Instead of using 350.9mm which can be derived from $size[h'] , I did not use it as it will give a cropped file. I just passed a numeric value near to it and the actual width to produce the desired result. $pdf->useTemplate($tplIdx, null, null, $size['w'], 310, false); By the way, 310 mm (length) is the largest numeric value I have used to produce a new PDF file which is NOT CROPPED . I hope I have given some inputs to all developers using FPDI which encounters the problem of CROPPED PDF results. Thanks to all... Levi Palmer | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6674753', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/817097/']} | jdg_86072 |
stackexchange | llm_judgeable_groundtruth_similarity | 15971364 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
These are Codecademy's instructions: We have an array of strings we'd like to later use as hash keys, but we'd rather they be symbols. Create a new array, symbols. Use .each to iterate over the strings array and convert each string to a symbol, adding those symbols to symbols. This is the code I wrote (the strings array was provided): strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]symbols = []strings.each { |x| x.to_sym }symbols.push(strings) I know I'm probably doing multiple things wrong, but I've got through the ruby track this far with very little difficulty, so I'm not sure why this one is stumping me. Firstly, it's not converting the strings to symbols, and secondly, it's not pushing them to the symbols array.
Now provide the response and nothing else.
| The to_sym alone wasn't doing anything useful; it was converting the string, but not storing it anywhere or using it later. You want to keep adding to symbols array. strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]symbols = []strings.each { |s| symbols.push s.to_sym } Or more elegantly, you can skip setting symbols = [] and just use map to create it in one line: symbols = strings.map { |s| s.to_sym } map will walk through each item in the array and transform it into something else according to the map function. And for simple maps where you're just applying a function, you can take it a step further: symbols = strings.map &:to_sym (That's the same as symbols = strings.map(&:to_sym) , use whichever you find more tasteful.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15971364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2274324/']} | jdg_86073 |
stackexchange | llm_judgeable_groundtruth_similarity | 4535 |
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What kind of rate of return can an average, equities-focused algorithmic trading firm expect to achieve today? I come from a background of control and optimization, working in the industry in China, but I also work with a team to do investments and trading on the side. In our market, which has a very different set of rules, it seems that the most profitable investment strategies are medium-term in time horizon. The yearly rate of return, for skillful private investors with several million USD, can be about 50% or so, but this number does, of course, vary from year to year. Recently a trader working at an investment bank, with a mixed background working with investment funds and as a quant developing high-frequency trading models, tried to persuade us to try algorithmic trading in the western markets. He claims that with several million USD's investment he can achieve a yearly return rate of 100% in the US stock market with the strategies he developed recently. I just want to know if this is possible? I know his algorithm is quite different than those that can be found in the published journal papers on finance. Although this seems to be OK (I doubt any good strategies will ever be published and we sure won't publish ours), but he failed to explain his strategies in much detail. From his point of view this is understandable, but it has certainly created a lot of doubt on our part. One detail I learned from talking with him is that his method involves event-driven trades and requires a lot of text-mining.
Now provide the response and nothing else.
| Whether its possible? Absolutely. However, you should probably keep in mind a couple points: * Many people claim a lot while proving very little to none. This is fine if the issue is a small-talk conversation. Believe it or not, no harm done. However, this is about money, and from my experience I cannot stress enough how important it is to do a very intensive due diligence on your part. Ask him to prove that he is worthy of your investments. Ask him for audited broker statements which detail his past trades so that you can build a more credible risk/return profile and see whether the statistical results speak in favor of funding him. Ask him to somehow send you live execution notifications of his currently live running strategies. Its very simple to code up a small application, especially for people active in algorithmic trading. If he rejects to show any sort of proof or verification then I would be more than careful. * Should you ever invest with him then I recommend you make sure your funds are segregated from any other of his funds. Its very simple in a professional "umbrella fund structure". You basically open an account in your own name while giving him trading authorization in your account. In that way he is unable to withdraw or transfer funds out of your account. * Keep in mind China is still a very inexperienced wild-west market in terms of financial investments. I say this because I spent almost my entire career in East Asia, Tokyo, HK, Singapore, Shanghai, now Tokyo. Chinese investors are a very special kind of breed when it comes to investments. Most are still having completely irrational expectations. They want a guy to generate 50% return, if at year end he generates 45% then they kick him out, and move all their money overnight into real estate. Then when the real estate market cooled down they moved all their funds into commodities and gold, and such forth. There is no loyalty, no trust, no nothing in China when it comes to investments. Expectations of achievable returns are exaggerated and so are promised by those who manage funds. Thus, I would be very careful about claims of someone able to generate 100% returns. Its doable, sure, but the risk of blowup grows exponentially, and the draw downs in between may be a lot larger than you can stomach. Do you feel comfortable waking up one morning and reading in your email inbox that your investment overnight tanked by 15-20% just because your fund manager concentrated all in that "hot" stock that he got some secret tips about and invested in? Be my guest, but I would ask very hard and potentially challenging questions in terms of what his thoughts are on risk/reward. If I speak to someone managing money and he mentions "returns" earlier than "risk" then he is OUT, SIMPLY OUT. Believe me, someone who promises you something without first mentioning the risk behind it should be avoided int his particular industry. Why all those comments about China and Chinese investors? Because I get the sense that you also have slightly unrealistic expectations of achievable returns within the framework of sane and sound risk management. If you get all crazed up by someone promising 100% then something is wrong, or do most people get excited when they watch a telemarketer on TV promising that the USD 3.99 gem can really heal sicknesses? My advice to you: Be realistic what to expect. The US stock market is not the Chinese real estate market 10-15 years ago. Take my advise or leave it, its your choice, but I would be very careful about someone who says he can generate 100% returns. It sounds extremely fishy and unprofessional. Good luck!!! (i hope you dont need it) P.S.: After I finished writing this and read your question again, I smirked, then shrugged, then felt pain. I actually recommend you to run, do not invest with such person, I am almost willing to bet (not the farm but a significant amount) that currently its close to impossible to generate 100% returns on a significant investment in US stocks on event based strategies. The probability of me being wrong is probably somewhere between 0.02%-0.5%. Just my 2 cents. | {} | {'log_upvote_score': 4, 'links': ['https://quant.stackexchange.com/questions/4535', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/3264/']} | jdg_86074 |
stackexchange | llm_judgeable_groundtruth_similarity | 142456 |
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:
The denominator of the (unbiased) variance estimator is $n-1$ as there are $n$ observations and only one parameter is being estimated. $$\mathbb{V}\left(X\right)=\frac{\sum_{i=1}^{n}\left(X_{i}-\overline{X}\right)^{2}}{n-1}$$ By the same token I wonder why shouldn't the denominator of covariance be $n-2$ when two parameters are being estimated? $$\mathbb{Cov}\left(X, Y\right)=\frac{\sum_{i=1}^{n}\left(X_{i}-\overline{X}\right)\left(Y_{i}-\overline{Y}\right)}{n-1}$$
Now provide the response and nothing else.
| Covariances are variances. Since by the polarization identity $$\newcommand{\c}{\text{Cov}}\newcommand{\v}{\text{Var}}\c(X,Y) = \v\left(\frac{X+Y}{2}\right) - \v\left(\frac{X-Y}{2}\right),$$ the denominators must be the same. | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/142456', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/3903/']} | jdg_86075 |
stackexchange | llm_judgeable_groundtruth_similarity | 6048504 |
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 need to call 3 http API in sequential order, what would be a better alternative to the following code: http.get({ host: 'www.example.com', path: '/api_1.php' }, function(res) { res.on('data', function(d) { http.get({ host: 'www.example.com', path: '/api_2.php' }, function(res) { res.on('data', function(d) { http.get({ host: 'www.example.com', path: '/api_3.php' }, function(res) { res.on('data', function(d) { }); }); } }); }); } });});}
Now provide the response and nothing else.
| Using deferreds like Futures . var sequence = Futures.sequence();sequence .then(function(next) { http.get({}, next); }) .then(function(next, res) { res.on("data", next); }) .then(function(next, d) { http.get({}, next); }) .then(function(next, res) { ... }) If you need to pass scope along then just do something like this .then(function(next, d) { http.get({}, function(res) { next(res, d); }); }) .then(function(next, res, d) { }) ... }) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6048504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/365256/']} | jdg_86076 |
stackexchange | llm_judgeable_groundtruth_similarity | 281280 |
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:
Motivation + Problem: While doing some exercises in Aluffi's Algebra: Chapter 0, I came across a problem which asks the reader to prove that ${\mathbb Q}$ is not the product of two nontrivial groups. This is the standard product in the category of groups. My Question: Since the chapter delves into categorical arguments, I tried it this way. We suppose not, that ${\mathbb Q} \cong G\times H$ and note that for any group $Z$ and any appropriate mappings $f,g$, we have the following diagram (sorry for the awkward TeXing, xypic doesn't seem to work here...), $\displaystyle \begin{array}{ccccc} & & Z & & \\ & ^{f}\swarrow & \downarrow&_{\exists!\langle f,g\rangle} \searrow^{g} & \\ & G\longleftarrow_{\pi_{1}} & {\mathbb Q} & _{\pi_{2}}\longrightarrow H &\end{array}$ So, we find that there is always a unique mapping in the center if this is a product. The projections either inject an isomorphic copy of ${\mathbb Q}$ or are the zero mapping. We'd like to show that either $G$ or $H$ is trivial. I'm not sure how to show that at least one must be trivial. My Attempt: Suppose $G \neq \{0\}$. We need to show $H = \{0\}$. Letting $Z = G$ and let $f = id$, we find that $G \cong {\mathbb Q}$. Moreover, the unique map in the center must be some multiplication mapping (which takes $x\mapsto qx$ for rational $q$; this is because $\pi_{1}$ must be a multiplication mapping if it is not the zero mapping). My guess here is that if $H$ is not trivial, it must also be an isomorphic copy of ${\mathbb Q}$ and we can allow $g$ to be some multiplication map like above such that the unique center mapping does not allow the right-hand triangle to commute. Does this sort of argument work?
Now provide the response and nothing else.
| If $\mathbb Q$ was isomorphic to $G\times H$ then $G$ and $H$ must be abelian and so $\mathbb Q$ would be a product $\mathbb Q \cong G\prod H$ in the category $Ab$, and as in $Ab$ finite products and coproducts agree, $\mathbb Q \cong G\coprod H$ holds as well. Let $i:G\to \mathbb Q$ and $j:H\to \mathbb Q$ be the canonical injections. In $Ab$ the canonical injections are monos and monos are injective functions. So, $G$ and $H$ are canonically subobjects of $\mathbb Q$. Now, the special property of $\mathbb Q$ is that the intersection of any two non-trivial subobjects in it have a non-trivial intersection (with $\mathbb Z$). However, in $Ab$ the canonical injections $G\to G\coprod H$ and $H\to G\coprod H$ intersect at the $0$ object, contradiction. This is about as categorically as I could furnish the proof, I hope you like it. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/281280', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_86077 |
stackexchange | llm_judgeable_groundtruth_similarity | 19541 |
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In this paper (page 3 Theorem 1) the authors want to prove that their problem is NP-complete. Their method is as follows. Let their problem be known as $P$. They show that their problem can be written as a $0\text{-}1$ integer program. Then they claim that $0\text{-}1$ integer programs are NP-complete and therefore their problem $P$ is NP-complete. I find this proof hard to believe. For the problem $P$ to be NP-hard I think one has to reduce the $0\text{-}1$ integer program into an instance of problem $P$ and not the other way around. Please can someone explain if this proof in the paper is acceptable?
Now provide the response and nothing else.
| I think there are really three issues buried in your question. What's Simon's Problem? What's a plain english description of the function involved in Simon's Problem? Why isn't this problem a cryptographic primitive? I can't really speak to 3 as cryptography is not my area. I can take a crack at 1 and 2 for you though. The distinction between 1 and 2 is, I think, important. Simon's problem is one of discovering the parameter to a function given a black-box to that function and some basic information about the function. So, an algorithm to solve this problem takes as its input a black-box to a function and gives a output a binary string. Our goal is to reduce the number of queries to that black box. I think people tend to miss this point and focus on the internals of the function itself. All we know about the function $f$ is that our black-box can compute it for us in constant, $O(1)$, time, and that if $f(x) = f(y)$, then either $x=y$ or $x \oplus y = s$. We want to know the value of $s$. A brute force, classical computing solution might give you a better feel for the problem. Here it is: Feed all $n$ bit binary strings to the black-box and save each input-output pair to a table. If no two inputs produce the same output then it must be the case that the parameter $s$ is $n$ bit $0$. Otherwise, two inputs will produce the same output and $s$ is the result of XOR'ing those inputs together. In the worst case, we have to query all $2^n$ inputs leading to $O(2^n)$ query complexity. Querying the black-box is at the heart of Simon's problem. We need not concern ourselves with how to construct the black-box, i.e. how to compute $f$, as that is not what the problem is about. I don't believe that Simon's problem is practically useful beyond the fact that it helps establish some complexity results about Quantum Computers. It's main significance is that it was an inspiration for Peter Shor's factoring algorithm. | {} | {'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/19541', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/12321/']} | jdg_86078 |
stackexchange | llm_judgeable_groundtruth_similarity | 163568 |
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 calculate the following limit without using, as Wolfram Alpha does , without using l'Hôpital?$$\lim_{x\to 0}\frac{\log\cos x}{\log\cos 3x}$$
Now provide the response and nothing else.
| \begin{align}\dfrac{\log(\cos(x))}{\log(\cos(3x))} & = \dfrac{2\log(\cos(x))}{2\log(\cos(3x))} \\&= \dfrac{\log(\cos^2(x))}{\log(\cos^2(3x))}\\& =\dfrac{\log(1-\sin^2(x))}{\log(1-\sin^2(3x))}\\& =\dfrac{\log(1-\sin^2(x))}{\sin^2(x)} \times \dfrac{\sin^2(3x)}{\log(1-\sin^2(3x))} \times \dfrac{\sin^2(x)}{\sin^2(3x)}\\& =\dfrac{\log(1-\sin^2(x))}{\sin^2(x)} \times \dfrac{\sin^2(3x)}{\log(1-\sin^2(3x))} \times \dfrac{\sin^2(x)}{x^2} \times \dfrac{(3x)^2}{\sin^2(3x)} \times \dfrac19\end{align}Now recall the following limits$$\lim_{y \to 0} \dfrac{\log(1-y)}{y} = -1$$$$\lim_{z \to 0} \dfrac{\sin(z)}{z} = 1$$Also, note that as $x \to 0$, $\sin(kx) \to 0$.Hence,$$\lim_{x \to 0} \dfrac{\log(1-\sin^2(x))}{\sin^2(x)} = -1$$$$\lim_{x \to 0} \dfrac{\sin^2(3x)}{\log(1-\sin^2(3x))} = -1$$$$\lim_{x \to 0} \dfrac{\sin^2(x)}{x^2} = 1$$$$\lim_{x \to 0} \dfrac{(3x)^2}{\sin^2(3x)} = 1$$Hence, $$\lim_{x \to 0} \dfrac{\log(\cos(x))}{\log(\cos(3x))} = (-1) \times (-1) \times 1 \times 1 \times \dfrac19 = \dfrac19$$Hence, the limit is $\dfrac19$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/163568', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/34572/']} | jdg_86079 |
stackexchange | llm_judgeable_groundtruth_similarity | 224259 |
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 $X$ be a $\sigma$-compact topological space and $(Y,d)$ be a metric space. Let $\{K_n\}$ be a sequence of compact subsets of $X$ whose union is $X$. Define $\rho_n(f,g):=\sup \{d(f(z),g(z)): z\in K_n\}$ and $\rho(f,g)=\sum_{n=0}^\infty (\frac{1}{2})^n \frac{\rho_n(f,g)}{1+\rho_n(f,g)}$ for all $f,g\in C(X,Y)$. Then, it can be directly checked that $\rho$ is a metric on $C(X,Y)$. Assuming $K_n\subset int(K_{n+1})$ for all $n$ , it can be easily shown that $\rho$ induces the compact-open topology on $C(X,Y)$. However, this conditions seems too strong. In Conway's functions of one complex variable text, it's written there that if $X$ is Baire in addition, then it can be still shown that $\rho$ induces the compact-open topology. However, I don't underatand why. How is it so? Is there any reference for it?
Now provide the response and nothing else.
| Let $A$ be a finitely generated group, and let $\beta \colon A \to A$ be an injective homomorphism which is not surjective. Freely construct a group $G$ generated by $A$ and some formal element $t$ such that the equality $tat^{-1} = \beta(a)$ holds in $G$ for each $a \in A$. $G$ is called the strict ascending HNN extension of $(A, \beta)$. Set $$H := \bigcup_{n=0}^{\infty} t^{-n}At^n$$ where the union is taken in $G$. $H$ is a strictly ascending union of finitely generated subgroups of $G$ which are all isomorphic to $A$. It follows that $H$ is a subgroup of $G$ which is not finitely generated (if it were, the union could not be strictly ascending). On the other hand, every finite image of $H$ is clearly a finite image of one of the groups in the union (which is isomorphic to $A$) and can thus be generated by $d(A)$ elements. It follows that the profinite completion of $H$ is finitely generated. To answer my question it suffices to choose $A$ and $\alpha$ in a way that will make $G$ hyperbolic. Take $A$ to be the free group on $x,y$ and define $\beta$ by $\beta(x) = xy$ and $\beta(y) = yx$. It is easy to see that $\beta$ is injective but not surjective. In this case, $G$ is the Sapir group, and its hyperbolicity is established in Theorem 4.1 of http://arxiv.org/pdf/1302.5370.pdf If we want an answer to the extended question, i.e. with $G$ residually finite, then we can take $A$ to be the free group on $x,y$ and define $\beta$ by $\beta(x) = xy^{-1}x^2y$ and $\beta(y) = yx^{-1}y^2x$. Again, it is easy to see that $\beta$ is injective but not surjective. By Theorem 4.2 of http://arxiv.org/pdf/1302.5370.pdf the resulting $G$ is hyperbolic and linear over $\mathbb{Z}$, and thus, residually finite. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/224259', 'https://mathoverflow.net', 'https://mathoverflow.net/users/83098/']} | jdg_86080 |
stackexchange | llm_judgeable_groundtruth_similarity | 22737 |
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:
It is known that particles such as electrons and protons bear electric charge, but not a magnetic charge. When these particles are at rest, are they somehow affected by magnetic field? The similar question applies to neutrons: are they affected by electric field?
Now provide the response and nothing else.
| Depends on what how far you are willing to go. If you have a solenoid with a uniform time-varying magnetic field, then an electric field is induced by Faraday's law. It will be a circular field, and will make an electron at rest spiral. So the electron at rest is affected by a time-varying magnetic field, though indirectly--via an induced electric field. Without considering induced fields:An electron will align its spin with a uniform magnetic field, and if the field is nonuniform, it will move along with it. This is because the electron has a magnetic "spin" or dipole moment, As far as neutrons are concerned, it depends if they have an electric dipole moment(afaict unknown). But, they can be affected in a similar manner by time-varying nonuniform electric fields, since they also have a magnetic moment. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/22737', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/6089/']} | jdg_86081 |
stackexchange | llm_judgeable_groundtruth_similarity | 105840 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am starting my application in the background using nohup as mentioned below - root@phx5qa01c:/bezook# nohup java -jar ./exhibitor-1.5.1/lib/exhibitor-1.5.1-jar-with-dependencies.jar -c file --fsconfigdir /opt/exhibitor/conf --hostname phx5qa01c.phx.qa.host.com > exhibitor.out &[1] 30781root@phx5qa01c:/bezook# nohup: ignoring input and redirecting stderr to stdout But every time I see this message - nohup: ignoring input and redirecting stderr to stdout Will there be any problem if I see this message? What does it mean and how can I avoid it?
Now provide the response and nothing else.
| To make sure that your application is disassociated from its terminal - so that it will not interfere with foreground commands and will continue to run after you logout - nohup ensures that neither stdin nor stdout nor stderr are a terminal-like device. The documentation describes what actions it takes: If the standard output is a terminal, all output written by the named utility to its standard output shall be appended to the end of the file nohup.out in the current directory. If nohup.out cannot be created or opened for appending, the output shall be appended to the end of the file nohup.out in the directory specified by the HOME environment variable. If neither file can be created or opened for appending, utility shall not be invoked. If the standard error is a terminal, all output written by the named utility to its standard error shall be redirected to the same file descriptor as the standard output. You redirected stdout to a file when you typed > exhibitor.out in your command line. If you're OK with having your application's stderr be directed to the same file as its stdout, you don't need to do anything else. Or you can redirect stderr to a different file by adding an argument such as 2> exhibitor.err . (Thanks to an unknown user - my notifications didn't show a name - for suggesting inclusion of this alternative.) | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/105840', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/22434/']} | jdg_86082 |
stackexchange | llm_judgeable_groundtruth_similarity | 279 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Three problems from G.Rosenstein "Linear orderings" (from the end of Chapter 2 and beginning of Chapter 4): 1) Is there a nondecreasing function from irrationals onto reals? 2) Is there a nondecreasing function from reals onto irrationals? 3) Is there an increasing function from reals into irrationals? (In other words, are reals a subordering of irrationals?) Any hints would be appreciated. (Please tag the question set-theory order-theory)
Now provide the response and nothing else.
| (3) This is only a minute variant on Ilya's answer, but I think it looks a bit more perspicuous in continued fractions. In fact, there's a negative continued fraction expansion that Richard Guy told me about which have a nicer ordering than standard regular cfs. Every real is uniquely representable as an infinite continued fraction$x=a_{0}-1/\left(a_{1}-1/\left(a_{2}-1/\left(\ldots\right)\right)\right)$ with all $a_{n}$ in $\mathbb {Z}$ and $a_{n}\ge 2$ for $i\ge 1$. $x$ is rational iff the all $a_{n}$ are $2$ from some point on. And the negative continued fractions have the lexicographic order: $x\gt x^{\prime}$ iff $a_{i}\gt a^{\prime}_{i}$ for the first $i$ for which $a_{i}$ and $a^{\prime}_{i}$ differ. So just map $x$ to $\left(a_{0}+1\right)-1/\left(\left(a_{1}+1\right)-1/\left(\left(a_{2}+1\right)-1/\left(\ldots\right)\right)\right)$. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/279', 'https://mathoverflow.net', 'https://mathoverflow.net/users/158/']} | jdg_86083 |
stackexchange | llm_judgeable_groundtruth_similarity | 56613499 |
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 add a test to check if Node.js app is starting. for example it might crash after running npm start . and I want to verify it's able to start. I tried searching the web for such ways to tests but couldn't find anything useful
Now provide the response and nothing else.
| I am not familiar with formik and I just took a quick look on the implementation.But here's my two cents on the issue. Why are the values not updating after each call? You are trying to get the values before the rerendering is happening and the value you have is the old one always, because the component is not updated yet. To verify try to add console.log(values.fields[0]); in the App component before the getValue definition. Why is the call happening before the rerendering? The onChange implementation will trigger the handleChange in which it's a memoized function call that will not be triggered if you have the same value BUT you changed the value. handleChange will be triggered if the executeChange value is different and executeChange also memoized that depends on setFieldValue or the state.values . setFieldValue is an event callback that only update the ref after each render. That's from formik docs // we copy a ref to the callback scoped to the current state/props on each render and that didn't happen yet in your case - useEventCallback -. Once the state is updated by the action then your component will be updated but your function is not called yet. setFieldValue will try to validate the input and return a promise and bubble that up to executeChange and handleChange and it treats that as a low priority so it's not a blocking call. A quick solution might be is to use onKeyUp instead of onChange I think that will bypass the useCallback and actually updates the component with higher priority call function App({ values, setFieldValue }) { console.log("Rerendering",values.fields[0]) //------ HERE ---------- const getValues = () => console.log(values.fields[0]); //---------------------- return ( <div className="formik-wrapper"> <Form> <FieldArray name="fields" render={() => ( <Field type="text" name="fields.0" placeholder="Write something" onKeyUp={e => { setFieldValue("fields.0", e.target.value); getValues(); }} /> )} /> </Form> </div> );} I hope this can help or at least lead for some help. Check formik implementation | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56613499', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11523160/']} | jdg_86084 |
stackexchange | llm_judgeable_groundtruth_similarity | 5143286 |
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 newbie question. We can use contains to check if a map contain a specified key, as: val map = Map("a"->"1", "b"->"")map.contains("a") But now, I want to check if the map contains an empty string, is there any method to use?
Now provide the response and nothing else.
| Try map.values.exists(_ == "") Edit: I think the above is the clearest, but I can't resist showing two others. map.exists(_._2 == "") is more compact, but you have to remember that _2 is the value when you iterate through a map. map.values.exists(""==) is an alternative form of the original, where instead of explicitly comparing the argument with _ == "" , you supply an equality function "".equals _ or ""== for short. (Two ways of looking at the same thing--is it the empty string supplying its equals method for testing, or is it your closure testing the elements against the empty string? I think the latter (the original) is considerably clearer.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5143286', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/342235/']} | jdg_86085 |
stackexchange | llm_judgeable_groundtruth_similarity | 651978 |
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:
Here is my scenario.I have a txt file. emailADD.txt.it contains email ids every line [email protected]@[email protected] And i have files in a folder abc.pdfdef.pdfhij.pdf and so on i want a script to send email to the first id with the first attachment. then another email to second id with the second attachment and so on. both email ids and the attachments will be stored in alphabetical order. the number of email ids and attachments stored will be equal. Please suggest. I have this idea from jesse_b but it doesn't involve different attachments to each email id. #!/bin/bashfile=/location/of/emailAdd.txtwhile read -r email; do #printf '%s\n' 'Hello, world!' | sudo mail -s 'This is the email subject' "$email" done < "$file"
Now provide the response and nothing else.
| This is one of the few instances where NOT quoting a variable is useful. $ string="1.3.2 1.3.1 1.2.3 1.1.1.5"$ printf "%s\n" $string | sort -V1.1.1.51.2.31.3.11.3.2 This uses GNU sort's -V aka --version-sort option to sort the numbers. You can store that back into a variable, even the same variable ( $string ): $ string=$(printf "%s\n" $string | sort -V)$ echo $string 1.1.1.5 1.2.3 1.3.1 1.3.2 or an array: $ array=( $(printf "%s\n" $string | sort -V) )$ typeset -p arraydeclare -a array=([0]="1.1.1.5" [1]="1.2.3" [2]="1.3.1" [3]="1.3.2") BTW, you should almost certainly be using an array rather than a simple string with white-space separating multiple different values. The only real reason not to is if you're using a shell (like ash ) that doesn't support arrays. e.g. $ array=( 1.3.2 1.3.1 1.2.3 1.1.1.5 )$ typeset -p arraydeclare -a array=([0]="1.3.2" [1]="1.3.1" [2]="1.2.3" [3]="1.1.1.5")$ array=( $(printf "%s\n" "${array[@]}" | sort -V) )$ typeset -p arraydeclare -a array=([0]="1.1.1.5" [1]="1.2.3" [2]="1.3.1" [3]="1.3.2") | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/651978', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/117977/']} | jdg_86086 |
stackexchange | llm_judgeable_groundtruth_similarity | 35582809 |
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 reading the documentation for how ArrayList s in Java are grown. I don't understand why the hugeCapacity(int minCapacity) method chooses to return either Integer.MAX_VALUE or MAX_ARRAY_SIZE . From how MAX_ARRAY_SIZE is defined in the class, 244 | private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; It's almost the same as Integer.MAX_VALUE except off by the size of one integer ( 32 bits ). 264 | private static int hugeCapacity(int minCapacity) {265 | if (minCapacity < 0) // overflow266 | throw new OutOfMemoryError();267 | return (minCapacity > MAX_ARRAY_SIZE) ?268 | Integer.MAX_VALUE :269 | MAX_ARRAY_SIZE;270 | } Can anyone tell me what the subtle difference is in returning Integer.MAX_VALUE versus MAX_ARRAY_SIZE ? Either way, shouldn't an OutOfMemoryError occur?
Now provide the response and nothing else.
| The maximal array size is limited to some number which varies across different JVMs and usually is slightly less than Integer.MAX_VALUE . So allocating the array of Integer.MAX_VALUE elements you will have OutOfMemoryError on most of JVMs even if you have enough memory to do it. MAX_ARRAY_SIZE assumes to be valid array size on the most of existing JVMs. So when ArrayList size approaches to Integer.MAX_VALUE (for example, you have more than 1_500_000_000 elements and need to enlarge an array), it's enlarged to this MAX_ARRAY_SIZE , so it can be successfully performed (assuming you have enough memory). Only if number of elements exceeds MAX_ARRAY_SIZE , the ArrayList tries to allocate an array of Integer.MAX_VALUE elements (which will likely to fail on most of JVMs, but may succeed on some of them). This way you can safely add elements up to MAX_ARRAY_SIZE on almost any JVM and only after that will have problems. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35582809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2887564/']} | jdg_86087 |
stackexchange | llm_judgeable_groundtruth_similarity | 6247221 |
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 set up a simple test page to illustrate the problem I have encountered.Briefly, this works as expected (text is formatted in bold, underlined red): <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html> <head> <style> [abc=x1] { color: red; text-decoration: underline; font-weight: bold; } </style> </head> <body> <div abc=x1>hello</div> </body></html> And this does not (text stays black, no formatting applied): <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html> <head> <style> [abc=1] { color: red; text-decoration: underline; font-weight: bold; } </style> </head> <body> <div abc=1>hello</div> </body></html> The only thing I changed between the two examples is the attribute value (in both the CSS and HTML) from x1 to 1. So it seems that you cannot match against numerical attributes. Does anyone have any idea why this... very... useful... feature... exist?
Now provide the response and nothing else.
| Wrap the string to match in quotes... [abc="1"] { ...} jsFiddle . Attribute values must be CSS identifiers or strings. Source . When you wrap it in quotes, you are telling it to match a string . When you don't quote it, it is looking for an identifier . In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit , two hyphens, or a hyphen followed by a digit. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6247221', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/370786/']} | jdg_86088 |
stackexchange | llm_judgeable_groundtruth_similarity | 22600056 |
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 changing a field from CharField to IntegerField . The field name remains the same. The newly created field will be based off the old field. For example, if the old field was "L", it would have the number "1" instead. How can I accomplish this in the forwards() function?
Now provide the response and nothing else.
| The correct way to do it would be to break this into three migrations: A first schema migration to add the new IntegerField field. Followed by a data migration to convert the data originating from the CharField to the IntegerField And a final schema migration to remove the now unused CharField . A fourth one might be required if you want your newly added IntegerField to have the same name as the to-be-removed CharField . Given a project state where the IntegerField is not yet added to you model file you should proceed by following these steps: Add the IntegerField to you model. Create a schema migration for the application containing your model. You might need to specify a default value for your newly added field here if it's not null. Create a data migration (using datamigration ) for the application containing your model. In the forwards() method of the newly created DataMigration class write down your logic to convert your data. Try to use the update manager method instead of iterating overt all your database row if possible. If you declare your conversion logic using a dict (say {'L': 1, ...} ) it should be pretty easy to also implement backwards() at this time, given the operation is invertible. It's also a good exercise to make sure you've not overlooked an edged case in forwards() -- it helped me quite a few times in the past. Remove the CharField from your model. Create a schema migration for the application containing your model in order to DROP the now unused column. The fact that you broke this operation into three migrations instead of writing down your whole logic in a blank template have a couple advantages: Auto-generated DDL operations: The ADD / DROP logic have been automatically generated by South and you don't have to worry about introducing a typo in a database column. Completely reversible operation: Given you've taken the time to implement DataMigration.backwards() for the conversion step you should be able to completely reverse the whole operation. This can be handy for testing purpose, if you need to rollback to a previous revision of your code and as safe net when updating a production code base. Atomicity of operations: The fact that each operation is isolated and run in it's own transaction won't leave you in an inconsistent state between your database and your South migration. For example, if all operations were performed in a single migration (in the same forwards() method in this case) and an exception was raised during the data migration step (say a KeyError because of an unhandled value in your conversion dict ). If you're using a ORDBMS that doesn't support transactional schema alteration you wouldn't be able to re-run you migration immediately after fixing the data-migration part, you'd have to manually drop the newly added IntegerField column yourself. Again, that's the kind of thing you don't want to deal with when migrating a production database. Ability to perform a dry-run: Also quite handy when migrating a production database. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22600056', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2233706/']} | jdg_86089 |
stackexchange | llm_judgeable_groundtruth_similarity | 7012 |
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've read this question and in its comments it is said: LDO and IC heatsinks will generally have a very different answer then computer motherboard heat sink. This question really doesn't belong here What I'm asking is how to use coolers with IC packages. For example let's say I have a device in TO220 package which according to my calculations needs cooling. How would I cool it? Most obvious answer is of course using a cooler, but that part isn't very clear to me. I've seen that sometimes heatsink is directly connected to the package by a screw but sometimes insulator is used to prevent direct contact between screw and package. Some other times, heat conductive insulator is used together with insulator for screw to prevent direct contact between package and heatsink. Sometimes silicon paste is used and sometimes it isn't. How would I determine when it is needed and when it isn't needed? My experience with computers tells me to always use it. I've also seen silicon pastes marketed as for use in electronics. How are they different that ones used in computers? Would thermal pastes for computers work well with ICs?
Now provide the response and nothing else.
| When you see a heatsink with a screw, that is because the chip it is mounted to has a hole for a screw mount. Sometimes the plate that you have to heatsink is going to be a different voltage then the surrounding board, so you need to use something that is electrically isolating, but thermally conductive. These replace the need for conductive paste. If you have the area of the regulator/IC that generates heat at a voltage like ground, and the other connections for your heat-sink will be ground, you can connect them directly, and you normally want to use a form of thermal paste. I have attached a heatsink without thermal paste and still had a device temperate at almost 90 degrees C. After adding thermal paste it measured at 5 degrees C above room temperature. Often being able to connect your heatsink to ground via solder helps dissipation as it dissipates to the ground plane. In computers you have a very specific task, cooling the Processor. In electronics it can be a very large range of tasks, and often you are willing to pay more to cool something because you design calls for it, or you are willing to pay less because your design does not need some very nice thermal paste. In general, you are going to just want to use thermal paste, you do not have to worry about insulating your heat-sink if you leave it floating in the air, or ensure where it mounts to the board there is not a voltage connection. This keeps things simpler for a tinkerer. For any chip you get that you think needs heat-sinking, read what they suggest to do (on the datasheet), and follow it. Last but not least, thermal paste for computer processors will work for ICs. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/7012', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/1240/']} | jdg_86090 |
stackexchange | llm_judgeable_groundtruth_similarity | 4838890 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I've been creating my GUI with Qt for my Python application. I've now come to a situation where after a button has been pushed the appropriate deferred gets executed, we perform some tasks then I need to open up a separate window that contains one or two things. But I can't seem to figure out how to create this new separate window. Could anyone give me an example of how to create one?
Now provide the response and nothing else.
| A common error that can drive you crazy is forgetting to store the handle of the popup window you create in some python variable that will remain alive (e.g. in a data member of the main window). The following is a simple program that creates a main window with a button where pressing the button opens a popup #!/usr/bin/env python#-*- coding: utf-8 -*-import sysfrom PyQt4.Qt import *class MyPopup(QWidget): def __init__(self): QWidget.__init__(self) def paintEvent(self, e): dc = QPainter(self) dc.drawLine(0, 0, 100, 100) dc.drawLine(100, 0, 0, 100)class MainWindow(QMainWindow): def __init__(self, *args): QMainWindow.__init__(self, *args) self.cw = QWidget(self) self.setCentralWidget(self.cw) self.btn1 = QPushButton("Click me", self.cw) self.btn1.setGeometry(QRect(0, 0, 100, 30)) self.connect(self.btn1, SIGNAL("clicked()"), self.doit) self.w = None def doit(self): print "Opening a new popup window..." self.w = MyPopup() self.w.setGeometry(QRect(100, 100, 400, 200)) self.w.show()class App(QApplication): def __init__(self, *args): QApplication.__init__(self, *args) self.main = MainWindow() self.connect(self, SIGNAL("lastWindowClosed()"), self.byebye ) self.main.show() def byebye( self ): self.exit(0)def main(args): global app app = App(args) app.exec_()if __name__ == "__main__": main(sys.argv) What I think can be surprising for Python users and may be is the problem you are facing is the fact that if you don't store a reference to the new widget in the main e.g. by using w = MyPopup(...) instead of self.w = MyPopup(...) the window apparently doesn't appear (actually it's created and it's immediately destroyed). The reason is that when the local variable w goes out of scope as no one is explicitly referencing the widget the widget gets deleted. This can be seen clearly because if you press again the button you'll see that as the second popup appears the first one is closed. This also means that if you need to create several popups you have for example to put them in a python list and you should remove them from this list once the popups are closed by the user. The equivalent in the example could be changing to self.w = [] in constructor and then doing self.w.append(MyPopup(...)) . Doing that would allow you to open several popups. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4838890', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/558763/']} | jdg_86091 |
stackexchange | llm_judgeable_groundtruth_similarity | 24579896 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using Python and I have a JSON file in which I would like to update a value related to a given key. That is, I have the my_file.json containing the following data {"a": "1", "b": "2", "c": "3"} and I would like to just change the value related to the b key from 2 to 9 so that the updated file look as like: {"a": "1", "b": "9", "c": "3"} How can I make that? I tried the following but without success (the changes are not saved to the file): with open('my_file.json', 'r+') as f: json_data = json.load(f) json_data['b'] = "9" f.close()
Now provide the response and nothing else.
| You did not save the changed data at all. You have to first load, then modify, and only then save. It is not possible to modify JSON files in-place. with open('my_file.json', 'r') as f: json_data = json.load(f) json_data['b'] = "9"with open('my_file.json', 'w') as f: f.write(json.dumps(json_data)) You may also do this: with open('my_file.json', 'r+') as f: json_data = json.load(f) json_data['b'] = "9" f.seek(0) f.write(json.dumps(json_data)) f.truncate() If you want to make it safe, you first write the new data into a temporary file in the same folder, and then rename the temporary file onto the original file. That way you will not lose any data even if something happens in between. If you come to think of that, JSON data is very difficult to change in-place, as the data length is not fixed, and the changes may be quite significant. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24579896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/502052/']} | jdg_86092 |
stackexchange | llm_judgeable_groundtruth_similarity | 20964 |
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:
As an undergrad I was often confused over people's bafflement with Schodinger's cat thought experiment. It seemed obvious to me that the term "observation" referred to the Geiger counter, not the person opening the box. Over time, I have come to realize that the Copenhagen interpretation actually is ambiguous and that "observer" cannot be so easily defined. Nonetheless, an objective collapse theory (which is what I was unknowingly assuming) still seems to me the simplest explanation of wave collapse phenomena. I have read some of the objections cited in the Wikipedia article linked above, but it is still unclear to me why most physicists adopt the Copenhagen interpretation and reject objective collapse. For example, in this question on hidden observers, there was some discussion about the mechanism of wave collapse. It was suggested that perhaps the gravitational pull of a hidden observer would collapse the wave function. In response, it was pointed out that the gravitational pull would be negligible at the scales involved. Okay, then imagine the following: A hermetically sealed (i.e. isolated) box is balanced on a fulcrum. Inside the box is a radioactive isotope, a Geiger counter, and a trigger mechanism connected to a spring loaded with a mass on one side of the box. If the Geiger counter detects a decay, the trigger releases the spring and the mass shifts to the other side of the box. The shift in mass would, under observable conditions tilt the box on the fulcrum. According to the interpretation of Schrodinger's cat that I often hear (the cat is in a superposition) it seems that the box should slowly tilt over as the wave function of the system evolves with the half-life of the isotope. I can't imagine that anyone thinks this is a realistic expectation. I can see that people might object and say "But the contents of the box are interacting gravitationally with the outside system and observer so it is not really isolated!" Well, what of it? The same is true of the cat even if the interaction is less dramatic. The question, then, is: How isolated must a system be for it's wave function to be considered not collapsed?
Now provide the response and nothing else.
| ''How isolated must a system be for it's wave function to be considered not collapsed?'' Experimentally, a system whose collapse is observable must be so small that one can prepare it in a well-defined pure state. If this is not the case, one can only speculate about what happened, leaving much room to imagination. This means that even when the carrier of the system is fairly big, the wave function collapsed models only extremely few degrees of freedom, and the real system considered is the one with these few degrees of freedom, not the bigger one. For example, arXiv:1103.4081 discusses superposition and collapse of macroscopic objects. But prepared in a superposition is only a single degree of freedom, the distance; all other degrees of freedom are either uncontrolled (and hence presumably in a mixed state) or eliminated by extreme cooling. Thus the system measured is in effect a single quantum oscillator. Now a typical quantum oscillator decoheres rapidly unless isolated, and a quantum oscillator of some size is hard to isolate. The experimental art consists in maintaining a superposition of two distances by isolating this particular degree of freedom from the environment. This isolation must be almost perfect, as otherwise decoherence effects responsible for the collapse set in extremely rapidly. (No special observer is needed. The environment does the observing by itself.) ''why most physicists [...] reject objective collapse.'' The main reason is that they want to maintain the simplicity of the traditional quantum mechanical foundations that are based on the assumption that the dynamics of quantum states is exactly linear, which seems to suffice for all applications. Objective collapse theories would require a tiny nonlinear modification of the basic laws, and spoil simplicity for (so far) uncheckable philosophy. Note that ''no objective collapse'' doean't mean that collapse isn't observable (it is observed routinely), but only that the collapse is not due to decoherence (the approximation in which the collapse is derivable in terms of generally believed assumptions from statistical mechanics - needed already in classical physics) but to objective deviations from the Schroedinger equation.The latter has no observable basis, and hence is rejected by most physicists. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/20964', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/5020/']} | jdg_86093 |
stackexchange | llm_judgeable_groundtruth_similarity | 38923969 |
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 to convert non English number to English number like :"٣٤٨٦٩١٢٨٨١" to "3486912881" in Swiftor I want to accept just english numbers and obtain others. In Java Android this code is working for me: private static String arabicToDecimal(String number) { char[] chars = new char[number.length()]; for(int i=0;i<number.length();i++) { char ch = number.charAt(i); if (ch >= 0x0660 && ch <= 0x0669) ch -= 0x0660 - '0'; else if (ch >= 0x06f0 && ch <= 0x06F9) ch -= 0x06f0 - '0'; chars[i] = ch; } return new String(chars);}
Now provide the response and nothing else.
| do like let NumberStr: String = "٢٠١٨-٠٦-٠٤" let Formatter = NumberFormatter() Formatter.locale = NSLocale(localeIdentifier: "EN") as Locale! if let final = Formatter.number(from: NumberStr) { print(final) } output the alternate way Option 2 extension String { public var arToEnDigits : String { let arabicNumbers = ["٠": "0","١": "1","٢": "2","٣": "3","٤": "4","٥": "5","٦": "6","٧": "7","٨": "8","٩": "9"] var txt = self arabicNumbers.map { txt = txt.replacingOccurrences(of: $0, with: $1)} return txt }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38923969', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6453294/']} | jdg_86094 |
stackexchange | llm_judgeable_groundtruth_similarity | 4404228 |
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:
Problem: Let $x_1$ , $x_2$ and $x_3$ be integers such that $x_1 \geq 0$ , $x_2 \geq 0$ and $x_3 \geq 0$ . How many solutions does the following equation have: $$ x_1 + 2x_2 + 2x_3 = 200 $$ Answer: Let $c$ be the number of solutions of this equation. For the case where $x_1$ is odd, the equation has no solutions. Now I consider the smallest case of $x_1$ where $x_1 = 0$ . I nowhave the following equation: $$2x_2 + 2x_3 = 200 $$ or $$ x_2 + x_3 = 100 $$ This equation has $101$ solutions. Now I consider the case where $x_0 = 2$ . I nowhave the following equation: $$2 + 2x_2 + 2x_3 = 200 $$ or $$ x_2 + x_3 = 99 $$ This equation has $100$ solutions. Now I consider the case where $x_0 = 4$ . I nowhave the following equation: $$4 + 2x_2 + 2x_3 = 200 $$ or $$ x_2 + x_3 = 98 $$ This equation has $99$ solutions. Now I consider the case where $x_0 = 200$ . I nowhave the following equation: $$100 + 2x_2 + 2x_3 = 200 $$ or $$ x_2 + x_3 = 0 $$ This equation only has one solution. \begin{align*}c &= \sum_{i = 0}^{100} i+1 = \sum_{i = 1}^{100} i + \sum_{i = 0}^{100} 1 \\\sum_{i = 1}^{100} i &= \dfrac{ 100(101) }{2} = 50(101) \\\sum_{i = 0}^{100} 1 &= 101 \\c &= 50(101) + 101 \\c &= 5151\end{align*} Is my solution correct?
Now provide the response and nothing else.
| Your solution seems correct, but a quicker way would be the following: As you observed, $x_1$ has to be even, so the problem will have as many solutions as the number of solutions to the problem of $$2x_1+2x_2+2x_3=200,$$ i.e. $$x_1+x_2+x_3=100.$$ Now this problem is the same problem as the number of ways to split $100$ objects into $3$ containers, which can also be considered as the number of words with $100$ of one letter, and $2$ of another (think of the $100$ letters as your objects and the $2$ letters as sectioning them off into the containers). This problem is simple and gives you the number as $$\frac{102!}{100!\cdot 2!}=\frac{101\cdot 102}{2}=101\cdot 51=5151.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4404228', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/154155/']} | jdg_86095 |
stackexchange | llm_judgeable_groundtruth_similarity | 23044 |
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 am attempting, for the first time, to use Mathematica to do some serious linear algebra. I would like to solve systems of equations of the form $$U_{n n'} f_{n'} = b_n.$$ I have an expression for $U_{n n'}$ that is of the general form $U_{n n'} = f_1(n) \delta_{n n'} + f_2(n,n')$. Is using 2 nested Table commands the easiest/most efficient way to build this matrix in Mathematica? I am not entirely sure how large I will need to make the matrix (it results from discretizing an integral equation, so the number of rows/columns will be as many as I need to get an accurate solution). I guess that it could be as large as 10,000 x 10,000, maybe. Is LinearSolve efficient enough to handle these sized systems on a standard desktop PC? Is parallelization for this automatic or do I need to do something manually? After I have found the solution, I am going to need to feed the solution to another equation to find the quantity that I am actually interested in. Is there anything I should do at the outset to make my life easier later? I apologize for the general nature of my question, but this is all new ground for me, so I am not sure what general guidelines and practices are best.
Now provide the response and nothing else.
| Is this faster? CoefficientArrays[identity, basis][[2]] // MatrixForm $\left(\begin{array}{cccccc} 1 & 0 & 1 & 0 & 0 & -1 \\ 0 & 1 & 1 & 0 & 0 & 0 \\ -1 & 0 & 0 & 1 & -1 & 0\end{array}\right)$ Responding to Jens' elegant answer it should be noted that performance of CoefficientArrays is better optimized for this task as one would hope. basis = (# /. {List -> t}) & /@ Permutations[Range[8]];basis = basis /. {t[a___, 1, b___] -> t[1, b, a]} // Union;size = {5000, 30};identity = Total[RandomInteger[{-1, 1}, size]*RandomChoice[basis, size], {2}];(r1 = CoefficientArrays[identity, basis][[2]];) // RepeatedTiming // First(r2 = D[identity, {basis}];) // RepeatedTiming // Firstr1 == r2 0.05170.43True In this example the difference in memory consumption is far more significant: ByteCount /@ {r1, r2}Divide @@ % // N{1639856, 608080968}0.00269677 | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/23044', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/4386/']} | jdg_86096 |
stackexchange | llm_judgeable_groundtruth_similarity | 5841518 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The [Email] attribute was going to be built into ASP.NET MVC 3 as it was in futures? So is it now available or not? I guess it is quite a dumb question but I've spent some time googling and didn't find any normal answer. The email regex: "^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$"
Now provide the response and nothing else.
| If [Email] is supposed to be a data annotation for MVC models (like [Required] ), then it's not built into ASP.NET MVC 3. All the model data annotations are found in the namesace System.ComponentModel.DataAnnotations . There you find classes like RequiredAttribute . Update: It's pretty easy to add the Email attribute: using System.ComponentModel.DataAnnotations;namespace YourNamespace{ public class EmailAttribute : RegularExpressionAttribute { public EmailAttribute() : base("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?") { } }} What the best or correct regular expression for checking email addresses is, is a separate and long debate on the net. I'm not insisting that mine is either of it. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5841518', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/420555/']} | jdg_86097 |
stackexchange | llm_judgeable_groundtruth_similarity | 9913521 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am having a bit of trouble figuring out the exact syntax to use string.compare in the Where clause of a linq query. Below is what I have so far. filteredApplications = AllApplications.Where(x => x.Name.Contains(string.Compare(x.Name, txtSearch.Text, StringComparison.OrdinalIgnoreCase))).ToList(); Is this even possible or am I barking up the wrong tree? Rhonda
Now provide the response and nothing else.
| If you want to check to see if Name contains the search text: AllApplications.Where(x => x.Name.ToUpperInvariant().Contains(txtSearch.Text.ToUpperInvariant()))).ToList(); If you want to check for equality: AllApplications.Where(x => string.Equals(x.Name, txtSearch.Text, StringComparison.OrdinalIgnoreCase)).ToList(); In your original query, you were checking to see if x.Name contains the result of string.Compare . I assume you weren't trying to do this, since string.Compare returns an integer . string.Compare is used primarily for determining sort order. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9913521', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/661136/']} | jdg_86098 |
stackexchange | llm_judgeable_groundtruth_similarity | 41512237 |
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 file for my nodejs project FROM node:boron# Create app directoryRUN mkdir -p /usr/src/appWORKDIR /usr/src/app# Install app dependenciesCOPY package.json /usr/src/app/RUN npm install# Bundle app sourceCOPY . /usr/src/app# Replace with env variableRUN envsubs < fil1 > file2EXPOSE 8080CMD [ "npm", "start" ] I run the docker container with the -e flag providing the environment variable But I do not see the replacement. Will the Run ccommand be excuted when the env variable is available?
Now provide the response and nothing else.
| Images are immutable Dockerfile defines the build process for an image. Once built, the image is immutable (cannot be changed). Runtime variables are not something that would be baked into this immutable image. So Dockerfile is the wrong place to address this. Using an entrypoint script What you probably want to to do is override the default ENTRYPOINT with your own script, and have that script do something with environment variables. Since the entrypoint script would execute at runtime (when the container starts), this is the correct time to gather environment variables and do something with them. First, you need to adjust your Dockerfile to know about an entrypoint script. While Dockerfile is not directly involved in handling the environment variable, it still needs to know about this script, because the script will be baked into your image. Dockerfile: COPY entrypoint.sh /entrypoint.shRUN chmod +x /entrypoint.shENTRYPOINT ["/entrypoint.sh"]CMD ["npm", "start"] Now, write an entrypoint script which does whatever setup is needed before the command is run, and at the end, exec the command itself. entrypoint.sh: #!/bin/sh# Where $ENVSUBS is whatever command you are looking to run$ENVSUBS < file1 > file2npm install# This will exec the CMD from your Dockerfile, i.e. "npm start"exec "$@" Here, I have included npm install , since you asked about this in the comments. I will note that this will run npm install on every run . If that's appropriate, fine, but I wanted to point out it will run every time, which will add some latency to your startup time. Now rebuild your image, so the entrypoint script is a part of it. Using environment variables at runtime The entrypoint script knows how to use the environment variable, but you still have to tell Docker to import the variable at runtime. You can use the -e flag to docker run to do so. docker run -e "ENVSUBS=$ENVSUBS" <image_name> Here, Docker is told to define an environment variable ENVSUBS , and the value it is assigned is the value of $ENVSUBS from the current shell environment. How entrypoint scripts work I'll elaborate a bit on this, because in the comments, it seemed you were a little foggy on how this fits together. When Docker starts a container, it executes one (and only one) command inside the container. This command becomes PID 1, just like init or systemd on a typical Linux system. This process is responsible for running any other processes the container needs to have. By default, the ENTRYPOINT is /bin/sh -c . You can override it in Dockerfile, or docker-compose.yml, or using the docker command. When a container is started, Docker runs the entrypoint command, and passes the command ( CMD ) to it as an argument list. Earlier, we defined our own ENTRYPOINT as /entrypoint.sh . That means that in your case, this is what Docker will execute in the container when it starts: /entrypoint.sh npm start Because ["npm", "start"] was defined as the command, that is what gets passed as an argument list to the entrypoint script. Because we defined an environment variable using the -e flag, this entrypoint script (and its children) will have access to that environment variable. At the end of the entrypoint script, we run exec "$@" . Because $@ expands to the argument list passed to the script, this will run exec npm start And because exec runs its arguments as a command, replacing the current process with itself, when you are done, npm start becomes PID 1 in your container. Why you can't use multiple CMDs In the comments, you asked whether you can define multiple CMD entries to run multiple things. You can only have one ENTRYPOINT and one CMD defined. These are not used at all during the build process. Unlike RUN and COPY , they are not executed during the build. They are added as metadata items to the image once it is built. It is only later, when the image is run as a container, that these metadata fields are read, and used to start the container. As mentioned earlier, the entrypoint is what is really run, and it is passed the CMD as an argument list. The reason they are separate is partly historical. In early versions of Docker, CMD was the only available option, and ENTRYPOINT was fixed as being /bin/sh -c . But due to situations like this one, Docker eventually allowed ENTRYPOINT to be defined by the user. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/41512237', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3987161/']} | jdg_86099 |
stackexchange | llm_judgeable_groundtruth_similarity | 95388 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose $a$, $b$, and $c$ are the lengths of the sides of a triangle, and $R$ and $r$ are its circumradius and inradius respectively. How can one prove the following inequality? $$2r^2+8Rr \leq \frac{a^2+b^2+c^2}{2}$$
Now provide the response and nothing else.
| We know that $$\begin{align*}a+b+c&=2s,\\ab+bc+ca&=s^2+r^2+4rR,\end{align*}$$where $s$ is semiperimeter, $r$ is inradius and $R$ is circumradius; see e.g., Manfrino, Ortega, Delgado - Inequalities: A Mathematical Olympiad Approach, Section 2.5 . Using these inequalities we can rewrite the LHS as$$\begin{align*}2(r^2+4rR) &= 2(ab+bc+ca-s^2) \\ &= 2(ab+bc+ca)-\frac{(a+b+c)^2}2 \\ &= ab+bc+ca-\frac{a^2+b^2+c^2}2.\end{align*}$$ After this the inequality we want to prove becomes$$ab+bc+ca\le a^2+b^2+c^2,$$which follows easily from AM-GM inequality . (Simply add the inequalities $ab\le \frac{a^2+b^2}2$, $ac\le \frac{a^2+c^2}2$ and $bc\le \frac{b^2+c^2}2$. ) See also this question for more proofs of the last inequality. For the sake of completeness, let me copy here the proofs of these equalities as they are given in the book I mentioned above. (I hope that such a short excerpt still qualifies as a fair use. I tried to find a proof of them online, but I did not succeed.) $$\begin{align*}a + b + c &= 2s, \tag{2.5}\\ab + bc + ca &= s^2 + r^2 + 4rR, \tag{2.6}\\abc &= 4Rrs. \tag{2.7}\end{align*}$$ The first is the definition of $s$ and the third follows from the fact that the area of the triangle is $\frac{abc}{4R}=rs$. Using Heron’s formula for the area of a triangle, we have the relationship $s(s - a)(s - b)(s - c) = r^2s^2$, hence $$s^3 - (a + b + c)s^2 + (ab + bc + ca)s - abc = r^2s.$$ If we substitute $(2.5)$ and $(2.7)$ in this equality, after simplifying we get that $$ ab + bc + ca = s^2 + r^2 + 4Rr.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/95388', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/18839/']} | jdg_86100 |
stackexchange | llm_judgeable_groundtruth_similarity | 34619177 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was looking at the docs of tensorflow about tf.nn.conv2d here . But I can't understand what it does or what it is trying to achieve. It says on the docs, #1 : Flattens the filter to a 2-D matrix with shape [filter_height * filter_width * in_channels, output_channels] . Now what does that do? Is that element-wise multiplication or just plain matrix multiplication? I also could not understand the other two points mentioned in the docs. I have written them below : # 2: Extracts image patches from the the input tensor to form a virtual tensor of shape [batch, out_height, out_width, filter_height * filter_width * in_channels] . # 3: For each patch, right-multiplies the filter matrix and the image patch vector. It would be really helpful if anyone could give an example, a piece of code (extremely helpful) maybe and explain what is going on there and why the operation is like this. I've tried coding a small portion and printing out the shape of the operation. Still, I can't understand. I tried something like this: op = tf.shape(tf.nn.conv2d(tf.random_normal([1,10,10,10]), tf.random_normal([2,10,10,10]), strides=[1, 2, 2, 1], padding='SAME'))with tf.Session() as sess: result = sess.run(op) print(result) I understand bits and pieces of convolutional neural networks. I studied them here . But the implementation on tensorflow is not what I expected. So it raised the question. EDIT :So, I implemented a much simpler code. But I can't figure out what's going on. I mean how the results are like this. It would be extremely helpful if anyone could tell me what process yields this output. input = tf.Variable(tf.random_normal([1,2,2,1]))filter = tf.Variable(tf.random_normal([1,1,1,1]))op = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='SAME')init = tf.initialize_all_variables()with tf.Session() as sess: sess.run(init) print("input") print(input.eval()) print("filter") print(filter.eval()) print("result") result = sess.run(op) print(result) output input[[[[ 1.60314465] [-0.55022103]] [[ 0.00595062] [-0.69889867]]]]filter[[[[-0.59594476]]]]result[[[[-0.95538563] [ 0.32790133]] [[-0.00354624] [ 0.41650501]]]]
Now provide the response and nothing else.
| Ok I think this is about the simplest way to explain it all. Your example is 1 image, size 2x2, with 1 channel. You have 1 filter, with size 1x1, and 1 channel (size is height x width x channels x number of filters). For this simple case the resulting 2x2, 1 channel image (size 1x2x2x1, number of images x height x width x x channels) is the result of multiplying the filter value by each pixel of the image. Now let's try more channels: input = tf.Variable(tf.random_normal([1,3,3,5]))filter = tf.Variable(tf.random_normal([1,1,5,1]))op = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='VALID') Here the 3x3 image and the 1x1 filter each have 5 channels. The resulting image will be 3x3 with 1 channel (size 1x3x3x1), where the value of each pixel is the dot product across channels of the filter with the corresponding pixel in the input image. Now with a 3x3 filter input = tf.Variable(tf.random_normal([1,3,3,5]))filter = tf.Variable(tf.random_normal([3,3,5,1]))op = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='VALID') Here we get a 1x1 image, with 1 channel (size 1x1x1x1). The value is the sum of the 9, 5-element dot products. But you could just call this a 45-element dot product. Now with a bigger image input = tf.Variable(tf.random_normal([1,5,5,5]))filter = tf.Variable(tf.random_normal([3,3,5,1]))op = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='VALID') The output is a 3x3 1-channel image (size 1x3x3x1). Each of these values is a sum of 9, 5-element dot products. Each output is made by centering the filter on one of the 9 center pixels of the input image, so that none of the filter sticks out. The x s below represent the filter centers for each output pixel. ......xxx..xxx..xxx...... Now with "SAME" padding: input = tf.Variable(tf.random_normal([1,5,5,5]))filter = tf.Variable(tf.random_normal([3,3,5,1]))op = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='SAME') This gives a 5x5 output image (size 1x5x5x1). This is done by centering the filter at each position on the image. Any of the 5-element dot products where the filter sticks out past the edge of the image get a value of zero. So the corners are only sums of 4, 5-element dot products. Now with multiple filters. input = tf.Variable(tf.random_normal([1,5,5,5]))filter = tf.Variable(tf.random_normal([3,3,5,7]))op = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='SAME') This still gives a 5x5 output image, but with 7 channels (size 1x5x5x7). Where each channel is produced by one of the filters in the set. Now with strides 2,2: input = tf.Variable(tf.random_normal([1,5,5,5]))filter = tf.Variable(tf.random_normal([3,3,5,7]))op = tf.nn.conv2d(input, filter, strides=[1, 2, 2, 1], padding='SAME') Now the result still has 7 channels, but is only 3x3 (size 1x3x3x7). This is because instead of centering the filters at every point on the image, the filters are centered at every other point on the image, taking steps (strides) of width 2. The x 's below represent the filter center for each output pixel, on the input image. x.x.x.....x.x.x.....x.x.x And of course the first dimension of the input is the number of images so you can apply it over a batch of 10 images, for example: input = tf.Variable(tf.random_normal([10,5,5,5]))filter = tf.Variable(tf.random_normal([3,3,5,7]))op = tf.nn.conv2d(input, filter, strides=[1, 2, 2, 1], padding='SAME') This performs the same operation, for each image independently, giving a stack of 10 images as the result (size 10x3x3x7) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/34619177', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4341948/']} | jdg_86101 |
stackexchange | llm_judgeable_groundtruth_similarity | 51298539 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
While looking at the source code of the Comparators class, I came across these lines of code. class Comparators { //... enum NaturalOrderComparator implements Comparator<Comparable<Object>> { INSTANCE; @Override public int compare(Comparable<Object> c1, Comparable<Object> c2) { return c1.compareTo(c2); } @Override public Comparator<Comparable<Object>> reversed() { return Comparator.reverseOrder(); } } //...} I think I understand what this does.It's a Singleton instance which implements the Comparator interface.It uses the "compareTo" of classes that implement the Comparable interface for natural ordering (please correct me if I am wrong in any of this). What I do not understand however, why is it done using an enum. I really like enums for Singletons, don't get me wrong but in this case I personally think this would have been simpler: public static final Comparator<Comparable<Object>> NATURAL_ORDER_COMPARATOR = new Comparator<Comparable<Object>>() { @Override public int compare(Comparable<Object> c1, Comparable<Object> c2) { return c1.compareTo(c2); } //... } Are there any reasons to implement this using enums aside from personal preference?
Now provide the response and nothing else.
| It maybe due to Serializable . Based on your approach, if you create an object that holds the Comparators.NATURAL_ORDER_COMPARATOR , when you write to the object and read it back, a new NATURAL_ORDER_COMPARATOR will be created. Since the object cost is so small it breaks the singleton . Some evidence for that is Collections.ReverseComparator . It uses your approach: static final ReverseComparator REVERSE_ORDER = new ReverseComparator(); But the drawback is that the following code must be present to maintain the singleton private Object readResolve() { return Collections.reverseOrder(); } Now which one is easier? Personally, I prefer to use 'enum singleton' pattern as my first choice. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51298539', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5910064/']} | jdg_86102 |
stackexchange | llm_judgeable_groundtruth_similarity | 140352 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Suppose $\mu$ and $\nu$ are two probability measures on $[0,1]$. Let their $n$-th moments be denoted by $\mu_n$ and $\nu_n$, respectively, for $n \in \mathbb{N}$. If we know that $\mu_n=\nu_n$ for infinitely many $n$, can we conclude that $\mu=\nu$? One way to resolve this would be to see if the span of $\{ x^n \mid n \in S \}$ with $|S|=\infty$ is dense in the set of continuous functions $C[0,1]$. Is such a set always dense?
Now provide the response and nothing else.
| We actually have that $\mu=\nu$ is guaranteed if and only if $\sum_{n\in S}\frac 1n$ is divergent. It's a condition which translates the fact that the set of indexed $k$ such that $\mu_k=\nu_k$ has to be large enough. Recall Müntz-Szász theorem, which states (in particular) the following: Theorem: If $(n_k,k\geqslant 0)$ is an increasing sequence of integers with $n_0=0$ , then the following conditions are equivalent: the vector space generated by $\{x^{n_k},k\in\mathbb N\}$ is dense in $C[0,1]$ endowed with the uniform norm. the series $\sum_{k=1}^\infty\frac 1{n_k}$ is divergent. If $\sum_{n\in S}\frac 1n$ is divergent, we can conclude by density that $\mu$ and $\nu$ coincide. If the series is convergent, we can find $F\in (C[0,1])'$ such that $F(x^n)=0$ for all $n\in \{0\}\cup S$ , but $F$ is not identically vanishing (this comes from Hahn-Banach theorem). We represent $F$ as a (non-zero) signed measure $m:=m^+-m^-$ (Hahn decomposition). Since $m^+[0,1]=m^-[0,1]$ , we can rescale these measures in order to get probability measures. Then with the same notations as in the OP, $m^+_n=m^-_n$ for all $n\in \{0\}\cup S$ , but $m^+\neq m^-$ . | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/140352', 'https://mathoverflow.net', 'https://mathoverflow.net/users/37273/']} | jdg_86103 |
stackexchange | llm_judgeable_groundtruth_similarity | 15909978 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am getting the following error: Apr 09, 2013 12:24:26 PM com.sun.jersey.spi.inject.Errors processErrorMessagesSEVERE: The following errors and warnings have been detected with resource and/or provider classes:SEVERE: Missing dependency for method public javax.ws.rs.core.Response com.package.ImportService.specifyLocalFile(java.lang.String,java.lang.String,java.lang.String,java.lang.String) at parameter at index 0SEVERE: Missing dependency for method public javax.ws.rs.core.Response com.package.ImportService.specifyLocalFile(java.lang.String,java.lang.String,java.lang.String,java.lang.String) at parameter at index 1SEVERE: Missing dependency for method public javax.ws.rs.core.Response com.package.ImportService.specifyLocalFile(java.lang.String,java.lang.String,java.lang.String,java.lang.String) at parameter at index 2SEVERE: Missing dependency for method public javax.ws.rs.core.Response com.package.ImportService.specifyLocalFile(java.lang.String,java.lang.String,java.lang.String,java.lang.String) at parameter at index 3SEVERE: Method, public javax.ws.rs.core.Response com.package.ImportService.specifyLocalFile(java.lang.String,java.lang.String,java.lang.String,java.lang.String), annotated with POST of resource, class com.package.ImportService, is not recognized as valid resource method. I have a previously working POST method that takes a Multipart data (a file upload) and then some other String data fields from the submitted form, here's the code: @POST@Consumes(MediaType.MULTIPART_FORM_DATA)public Response uploadFile( @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("param1") String param1, @FormDataParam("param2") String param2, @FormDataParam("param3") String param3) { .... .... return Response.status(200).entity(getEntity()).build();} The error seems to be related to the way the form parameters are being interpreted by Jersey. here's the code that fails: @POST@Consumes(MediaType.APPLICATION_FORM_URLENCODED)@Path("/local")public Response specifyLocalFile( @FormDataParam("file") String fullFilePath, @FormDataParam("param1") String param1, @FormDataParam("param2") String param2, @FormDataParam("param3") String param3) { .... .... return Response.status(200).entity(getEntity()).build();}
Now provide the response and nothing else.
| After googling a little I end up reviewing some interesting cases, such as Failed unmarshalling issue with @FormParam , or Missing mulipart JAR dependency issue the most aproximate post for my problem was this: "Missing dependecy for method" , which I answer with a link to this POST, as I see no currenty solution for that particular one. The issue appeared to be related to the @FormDataParam annotation, when used with the method-level @Consumes annotation with the value MediaType.APPLICATION_FORM_URLENCODED . When I changed the Method signature to annotate each plain-text field with @FormParam , the exception was gone. Check the fixed code below: @POST@Consumes(MediaType.APPLICATION_FORM_URLENCODED)@Path("/local")public Response specifyLocalFile() @FormParam("file") String fullFilePath, @FormParam("param1") String param1, @FormParam("param2") String param2, @FormParam("param3") String param3) { .... If the type of the data being received does not have to deal with MIME-encodings, the @FormParam annotation will attempt to deal with the contents via serialization; in contrast, the @FormDataParam annotation requires some specific handling that is configured when the @Consumes annotation has the MediaType.MULTIPART_FORM_DATA . Hope this helps. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15909978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1339035/']} | jdg_86104 |
stackexchange | llm_judgeable_groundtruth_similarity | 25726709 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can somebody please give me advice on how to delete events from the FullCalendar Version 2 by dragging it out of the calendar, please? I saw some solution here: Remove Elements from fullcalendar (by dragging to trash can) but it seems to address the version 1.
Now provide the response and nothing else.
| My first approach would be: eventDragStop: function(event,jsEvent) { alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY); if( (300 <= jsEvent.pageX) & (jsEvent.pageX <= 500) & (130 <= jsEvent.pageY) & (jsEvent.pageY <= 170)){ alert('delete: '+ event.id); $('#MyCalendar').fullCalendar('removeEvents', event.id); }} This allows to drag events to the area (in pixels) corresponding to the if condition order to delete. Tested with fullcalendar 2.1.1. An improvement would be to check and compare jsEvent coordinates with $(window).height() and $(window).width() , this way would confirm/test dragging out of calendar area, much neat of course. Actually the improvement is (an elegant solution), based on the solution mentioned: Create a div element with the icon trash: <div id="calendarTrash" class="calendar-trash"><img src="path/to/static/images/trash.png" /></div> The eventDragStop is: eventDragStop: function(event,jsEvent) { var trashEl = jQuery('#calendarTrash'); var ofs = trashEl.offset(); var x1 = ofs.left; var x2 = ofs.left + trashEl.outerWidth(true); var y1 = ofs.top; var y2 = ofs.top + trashEl.outerHeight(true); if (jsEvent.pageX >= x1 && jsEvent.pageX<= x2 && jsEvent.pageY >= y1 && jsEvent.pageY <= y2) { alert('SIII'); $('#calendario').fullCalendar('removeEvents', event.id); }} Tested on Fullcalendar 2.1.1 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25726709', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4019594/']} | jdg_86105 |
stackexchange | llm_judgeable_groundtruth_similarity | 34370 |
Below is a question asked on the forum scicomp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In a code that I work with (written in python, but also tagging as matlab because numpy is so close and I could use it if need be), we use a transfer matrix method to compute the properties of a physical system. That is, for a particle at initial position $\vec{x}_i$ , we compute the final position as $$\vec{x}_f = \hat{M}(z)\cdot\vec{x}_i \approx \hat{M}(z_n)\cdots\hat{M}(z_1)\cdot\hat{M}(z_0)\cdot\vec{x}_i,$$ where for convergence reasons $n\sim 10^4$ . After profiling our code, something like 90% of of the CPU's time is spent in the final matrix multiplications. I am currently using the naive implementation of this which looks like: # The list of matricesMs = [M1, M2, M3, ..., Mn]# Start with the identity matrixresult = np.identity(2)# Multiply the matricesfor M in Ms: result = M @ result My question is: is there a clever way to speed up the matrix multiplication step? Alternatively, I would also be interested in less than clever ways to shave off time with numpy voodoo. Unfortunately, the matrices don't commute and so I can't take a logarithm, sum, and then take a matrix exponential which I assume would be faster. Edit: The matrices are generated as follows: # Calculate the constant matrices and edge matricesMs = get_M_const(E, B, gammas[:-1], delta_z)rising_Ms = np.concatenate((np.array([[[1.0,], [0.0,]], [[0.0,], [1.0,]]]), get_M_edge(E[1:], gammas[1:-1], 'rising')), axis=2)falling_Ms = get_M_edge(E, gammas[1:], 'falling')# Interleave the arraysc = np.empty((2,2, Ms.shape[-1]+rising_Ms.shape[-1]+falling_Ms.shape[-1],), dtype=Ms.dtype)c[:,:,0::3] = rising_Msc[:,:,1::3] = Msc[:,:,2::3] = falling_Ms There are technically three different types of the matrices $\hat{M}_{\text{total}} = \hat{M}_{\text{falling}}\cdot\hat{M}_{\text{const}}\cdot\hat{M}_{\text{rising}}$ that I compute using numpy functions to take advantage of vectorized routines. The variables E , B , and gammas are numpy arrays of shape (n) and delta_z is just a number. Those functions return (2,2,n) arrays which I then interleave to get the full (2,2,3n) array of matrices which get multiplied. I guess I simplified my code too much in the first code block by listing the matrices as being in a native python list. The rest of it is how I perform matrix multiplication, however. I run the for loop over the elements of the transpose of c .
Now provide the response and nothing else.
| In general, I agree with Chris's comment that using a compiled language with the allocation of the matrices on the stack can help significantly. Several possibilities if we are limited to Python and numpy: consider np.array vs np.matrix , it might happen that np.matrix is faster than np.array matrix-matrix product (it is unclear what you are using now, and how $2\times2$ size will influence the result) consider parallelizing computation of the final matrix as per comment from whpowell96 maybe, you do not need to compute the overall matrix $\hat{M}(z)$ . Instead of computing $(10^4-1)$ matrix-matrix products and $1$ matrix-vector products, the alternative is $10^4$ matrix-vector products that might be better if no other computations are needed. consider Cython and/or distributions of Python targeted at performance. | {} | {'log_upvote_score': 4, 'links': ['https://scicomp.stackexchange.com/questions/34370', 'https://scicomp.stackexchange.com', 'https://scicomp.stackexchange.com/users/34040/']} | jdg_86106 |
stackexchange | llm_judgeable_groundtruth_similarity | 6240207 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose I have a class with a virtual function and a derived class that implements the virtual function in a different way. Suppose I also have a vector of the base class used to store derived classes. How would I execute the virtual function of a derived class in the vector without knowing in advance what the derived class is? Minimal code that illustrates the problem: #include <iostream>#include <vector>class Foo {public: virtual void do_stuff (void) { std::cout << "Foo\n"; }};class Bar: public Foo {public: void do_stuff (void) { std::cout << "Bar\n"; }};int main (void) { std::vector <Foo> foo_vector; Bar bar; foo_vector.resize (1); foo_vector [0] = bar; bar.do_stuff (); /* prints Bar */ foo_vector [0].do_stuff (); /* prints Foo; should print Bar */ return 0;}
Now provide the response and nothing else.
| You can't. The objects in the vector will have been sliced -- any derived-class instance data will have been chopped off, so calling the method would be a super-bad idea. If, on the other hand, you have a vector of pointers to base, then you simply call the virtual method, and the derived-class version will be invoked. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6240207', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/780185/']} | jdg_86107 |
stackexchange | llm_judgeable_groundtruth_similarity | 2177630 |
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:
At first sight, this number will be considered a normal number. But the strange thing is 2520 is able to be divided at even or odd number. Like 1 =2520, 2 =1260 , 3 =840, 4 =630, 5 =504, 6 =420, 7 =360, 8 =315, 9 =280, and by 10 =252, which is hard to find integers with the same characteristics. Also, you can get this number by ( 7 * 30 * 12 = 2520 ) which I think is 7 days in the week, 30 days in a month and 12 months in a year! Nothing special, but it is a weird thing, right. Are there any numbers that can be divided from 1-10 without any fraction? If yes, what are they? And is there any mathematical explanation of such a phenomenon?
Now provide the response and nothing else.
| If you want a number divisible by $a, b,$ and $c$, you can just multiply them together. So one number that is divisible by $1$ through $10$, is the product $1\cdot 2\cdot \cdots \cdot 10 = 3628800.$ The smallest such number will be the least common multiple of $1, 2, \ldots, 10$ which is your $2520.$ Is it "weird" that $2520 = 7\cdot 30 \cdot 12$? Not really. Before metric ruined everything, we chose our units to be divisible by small numbers. There are lots of $12$'s and $30$'s (and $60$'s, etc) in our old measuring systems. And since this problem depends on having lots of small factors, it would be expected that the least common multiple of the first few numbers would contain the same factors as many of the ancient units. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2177630', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/410024/']} | jdg_86108 |
stackexchange | llm_judgeable_groundtruth_similarity | 10909902 |
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 following table projects . id title created_at claim_window1 Project One 2012-05-08 13:50:09.924 52 Project Two 2012-06-01 13:50:09.924 10 A) I want to find the deadline with calculation deadline = created_at + claim_window(No. of days) . Something like following. id title created_at claim_window deadline1 Project One 2012-05-08 13:50:09.924 5 2012-05-13 13:50:09.9242 Project Two 2012-06-01 13:50:09.924 10 2012-06-11 13:50:09.924 B) I also want to find the projects whose deadline is gone id title created_at claim_window deadline1 Project One 2012-05-08 13:50:09.924 5 2012-05-13 13:50:09.924 I try something like following. SELECT * FROM "projects" WHERE (DATE_PART('day', now()- created_at) >= (claim_window+1)) But for some reason it is not working.
Now provide the response and nothing else.
| This will give you the deadline : select id, title, created_at + interval '1' day * claim_window as deadlinefrom projects Alternatively the function make_interval can be used: select id, title, created_at + make_interval(days => claim_window) as deadlinefrom projects To get all projects where the deadline is over, use: select *from ( select id, created_at + interval '1' day * claim_window as deadline from projects) twhere localtimestamp at time zone 'UTC' > deadline | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/10909902', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/297087/']} | jdg_86109 |
stackexchange | llm_judgeable_groundtruth_similarity | 8504896 |
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 working on Project Euler and ran into an issue. I am unable to use a 1000 digit number and wanted to know if I am doing something wrong or am just going about this solution in the wrong way and if so what would be best approach be? C# namespace ToThePowerOf{ class Program { static void Main(string[] args) { BigInteger n = 1; int x = 0; BigInteger [] number; number = new BigInteger[149194]; number[x] = 1; number[x + 1] = 1; x = 3; ; BigInteger check = 10000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 00000000000000000000000; for (int i = 99; i > 0; i--) { n = (n - 1) + (n - 2); number[x] = n; x++; if (n > check) { Console.WriteLine(x); } } } }}
Now provide the response and nothing else.
| I'm guessing the 'issue' you ran into (would be helpful to include error message) is that the compiler doesn't like the integer literal with 1000 digits so you can't initialise it with a very large integer literal. As others have noted, breaking the integer literal into multiple lines isn't valid either. The number[x] = 1; lines work because the compiler can handle the integer literal 1 and because we're assigning it to a BigInteger it uses BigInteger 's implicit operator to convert it to a BigInteger . One simple method to get around your problem with the big integer literal is to use the BigInteger.Parse method to create your 1000 digit number. BigInteger check = BigInteger.Parse("10000....", CultureInfo.InvariantCulture); Another method could be to initialise it with a small int, then use maths to get to the number you want, as in Jon Skeet's answer . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8504896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1059578/']} | jdg_86110 |
stackexchange | llm_judgeable_groundtruth_similarity | 2857036 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a String list: List<String> listString = new ArrayList<String>();listString.add("faq");listString.add("general");listString.add("contact"); I do some processing on the list and I want to sort this list but I want "general" to always end up in first position.Thx ;)
Now provide the response and nothing else.
| I like @Petar's approach, but another approach would be to sort it using a custom Comparator that always said that "general" was before whatever it was being compared to. Collections.sort(list, new Comparator<String>() { int compare(String o1, String o2) { if (o1.equals(o2)) // update to make it stable return 0; if (o1.equals("general")) return -1; if (o2.equals("general")) return 1; return o1.compareTo(o2); }}); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2857036', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/296635/']} | jdg_86111 |
stackexchange | llm_judgeable_groundtruth_similarity | 33530726 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
To my understanding, the .toRx().subscribe( ... ) function is meant to RECEIVE messages and the .next() function is meant to BROADCAST messages In this plnkr ( http://plnkr.co/edit/MT3xOB?p=info ) , you invoke the .toRx().subscribe( ... ) function from a data object that seems to be defined/derived originally from the template: @Component({ selector : 'child-cmp', template : '', inputs : ['data']})class ChildCmp { afterViewInit() { this.data.toRx().subscribe((data) => { console.log('New data has arrived!', data); }); }} In this plnkr ( http://plnkr.co/edit/rNdInA?p=preview ) , you invoke the .toRx().subscribe( ... ) function from an evt object and its emitter function (originating from Service injected into the component's constructor) @Component({ selector : 'parent-cmp', template : ''})class ParentCmp { constructor(evt: EventService) { evt.emitter.subscribe((data) => console.log("I'm the parent cmp and I got this data", data)); }} Is is possible for the BROADCAST to take place in a function of the Service itself while at the same time, is it possible for the Component to RECEIVE the message without relying upon a returned Service object or Template data object to chain its .toRX().subscribe( ... ) function invokation? import {Injectable, EventEmitter} from 'angular2/angular2';@Injectable()export class DataService { items:Array<any>; dispatcher: EventEmitter = new EventEmitter(); constructor() { this.items = [ { name: 'AAAA' }, { name: 'BBBB' }, { name: 'CCCC' } ]; } getItems() { return this.items; } sendItems() { this.dispatcher.next( this.items ); } }export var DATA_BINDINGS: Array<any> = [ DataService];@Component({ selector: 'rabble'})@View({ ...})export class Rabble { items : Array<any>; constructor( public dataService : DataService) { console.log('this.routeParam', this.dataService.getItems()); } afterViewInit() { this.???.toRx().subscribe((data) => { console.log('New item data has arrived!', data); }); } handleClick() { this.dataService.sendItems(); }}
Now provide the response and nothing else.
| UPDATED TO 2.0 Stable: EventEmitter is now solely for component communication. This is a better use for Subjects and ReplaySubjects. I've updated the examples to 2.0 code. UPDATED TO BETA 1: You no longer need to call .toRx() on the emitter so I'm updating the code to match and added an example to unSubscribe. So right now (Alpha 45) The eventEmitter has that toRx() method which returns a RxJS SUBJECT You can google a bit what that is and what you can do with it but it's what you are actually messing with. When you call toRx() it just returns the internal subject from the eventEmitter so you can do that in your service constructor. Then I added the function you wanted to do the broadcast to the event service class EventService { //could be regular Subject but I like how ReplaySubject will send the last item when a new subscriber joins emitter: ReplaySubject<any> = new ReplaySubject(1); constructor() { } doSomething(data){ this.emitter.next(data); }} Then in your component you subscribe to the emitter class ParentCmp { myData: any; constructor(private evt: EventService) { //rx emitter this.evt.emitter.subscribe((data) => { this.myData = data; console.log("I'm the parent cmp and I got this data", data)); } }} And here is a expanded class with a built in unsubscribe(dispose) export class ParentCmp implements OnDestroy { myData: any; subscription: any; constructor(evt: EventService) { //rx emitter this.subscription = evt.emitter.subscribe((data) => { this.myData = data; console.log("I'm the parent cmp and I got this data", data)); } } ngOnDestroy() { this.subscription.dispose(); }} I'm a little confused about your last question but think of the term "receive a message." You have to be listening to something so thats what the subscribe method does and is required. Cool thing is now you can call that observable all over the place (even in other services) and IMO is the best way to communicate between components. They don't need to know their position in the tree or care if the other components exist or are listening. I Forked your Plunker with my way working HERE (still on Alpha45) RxJs source and info on subject Angular2 source and info on the subject inside the eventEmitter | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33530726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2621091/']} | jdg_86112 |
stackexchange | llm_judgeable_groundtruth_similarity | 1475635 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it safe to return the pointer to a local struct in C? I mean is doing this struct myStruct* GetStruct() { struct myStruct *str = (struct myStruct*)malloc(sizeof(struct myStruct)); //initialize struct members here return str;} safe? Thanks.
Now provide the response and nothing else.
| In your code, you aren't returning a pointer to a local structure. You are returning a pointer to a malloc()'d buffer that will reside upon the heap. Thus, perfectly safe. However, the caller (or the caller's caller or the caller's caller's callee, you get the idea) will then be responsible for calling free(). What isn't safe is this: char *foo() { char bar[100]; // fill bar return bar;} As that returns a pointer to a chunk of memory that is on the stack -- is a local variable -- and, upon return, that memory will no longer be valid. Tinkertim refers to "statically allocating bar and providing mutual exclusion". Sure: char *foo() { static char bar[100]; // fill bar return bar;} This will work in that it will return a pointer to the statically allocated buffer bar. Statically allocated means that bar is a global. Thus, the above will not work in a multi-threaded environment where there may be concurrent calls to foo() . You would need to use some kind of synchronization primitive to ensure that two calls to foo() don't stomp on each other. There are many, many, synchronization primitives & patterns available -- that combined with the fact that the question was about a malloc() ed buffer puts such a discussion out of scope for this question. To be clear: // this is an allocation on the stack and cannot be safely returnedchar bar[100];// this is just like the above; don't return it!!char *bar = alloca(100);// this is an allocation on the heap and **can** be safely returned, but you gotta free()malloc(100);// this is a global or static allocation of which there is only one per app session// you can return it safely, but you can't write to it from multiple threads without// dealing with synchronization issues!static char bar[100]; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1475635', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/178879/']} | jdg_86113 |
stackexchange | llm_judgeable_groundtruth_similarity | 81298 |
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Rip Van Winkle here -- is the fastest and least-footprint way to compute an arctan on an FPGA still to use CORDIC? Or is there a way to leverage block RAM and DSP blocks to speed and/or reduce the size of the process?
Now provide the response and nothing else.
| If you're willing to tolerate a possible absolute error of 0.26 degrees, you could use the following (from Chapter 13 of my "Understanding Digital Signal Processing" book): The product 0.28125 $Q^2$ is equal to (1/4+1/32) $Q^2$ , so you can implement the product by adding $Q^2$ shifted right by two bits to $Q^2$ shifted right by five bits. Here is the error curve, over the range of -45 degrees to +45 degrees | {} | {'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/81298', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/45593/']} | jdg_86114 |
stackexchange | llm_judgeable_groundtruth_similarity | 30196569 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am testing a new load balanced staging site and the https is set up at the load balancer level, not at the site level. Also, this site will be always https so i don't need remote require https attributes etc. The url displays https but it is not available in my code. I have a few issues due to this reason Request.Url.Scheme is always http: public static string GetProtocol() { var protocol = "http"; if (HttpContext.Current != null && HttpContext.Current.Request != null) { protocol = HttpContext.Current.Request.Url.Scheme; } return protocol; } Same thing with this base url, protocol is http public static string GetBaseUrl() { var baseUrl = String.Empty; if (HttpContext.Current == null || HttpContext.Current.Request == null || String.IsNullOrWhiteSpace(HttpRuntime.AppDomainAppPath)) return baseUrl; var request = HttpContext.Current.Request; var appUrl = HttpRuntime.AppDomainAppVirtualPath; baseUrl = string.Format("{0}://{1}{2}", request.Url.Scheme, request.Url.Authority, appUrl); if (!string.IsNullOrWhiteSpace(baseUrl) && !baseUrl.EndsWith("/")) baseUrl = String.Format("{0}/", baseUrl); return baseUrl; } Now the biggest issue is referencing js files and google fonts referenced in the style sheets. I am using // here without http or https but these are treated as http and i see mixed content blocked message in FireBug. How can i overcome this issue?
Now provide the response and nothing else.
| As you've said HTTPS termination is done at load balancer level ("https is set up at the load balancer level") which means original scheme may not come to the site depending on loadbalancer configuration. It looks like in your case LB is configured to talk to site over HTTP all the time. So your site will never see original scheme on HttpContext.Request.RawUrl (or similar properties). Fix: usually when LB, proxy or CDN configured such way there are additional headers that specify original scheme and likely other incoming request parameters like full url, client's IP which will be not directly visible to the site behind such proxying device. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30196569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/179531/']} | jdg_86115 |
stackexchange | llm_judgeable_groundtruth_similarity | 2356726 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose $f$ continuous on $\{z\in \mathbb{C}||z|\leq1\}$ and analytic on $\{z\in \mathbb{C}||z|<1\}$ and that $f$ is constant on $\{z\in \mathbb{C}||z|<1\}$. Is $f$ being continuous enough to say that $f$ has to be constant on all of $\{z\in \mathbb{C}||z|\leq1\}$ ?
Now provide the response and nothing else.
| Yes. If $f$ is constant on the open disk $\Bbb D$, then $f(\Bbb D)=c$ for some $c$. Since the set $\{c\}$ is closed and $f$ is continuous, $f^{-1}(c)$ is a closed set containing $\Bbb D$. As such, $f^{-1}(c)$ must also contain the closure of $\Bbb D$, which is the closed disk. Hence, $f$ is constant on $\overline{\Bbb D}$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2356726', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/81706/']} | jdg_86116 |
stackexchange | llm_judgeable_groundtruth_similarity | 43444333 |
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 setting up a piece of code to parallel processes some computations for N groups in my data using foreach . I have a computation that involves a call to h2o.gbm . In my current, sequential set-up, I use up to about 70% of my RAM. How do I correctly set-up my h2o.init() within the parallel piece of code? I am afraid that I might run out of RAM when I use multiple cores. My Windows 10 machine has 12 cores and 128GB of RAM. Would something like this pseudo-code work? library(foreach)library(doParallel)#setup parallel backend to use 12 processorscl<-makeCluster(12)registerDoParallel(cl)#loopdf4 <-foreach(i = as.numeric(seq(1,999)), .combine=rbind) %dopar% { df4 <- data.frame() #bunch of computations h2o.init(nthreads=1, max_mem_size="10G") gbm <- h2o.gbm(train_some_model) df4 <- data.frame(someoutput) }fwrite(df4, append=TRUE)stopCluster(cl)
Now provide the response and nothing else.
| The way your code is currently set up won't be the best option. I understand what you are trying to do -- execute a bunch of GBMs in parallel (each on a single core H2O cluster), so you can maximize the CPU usage across the 12 cores on your machine. However, what your code will do is try to run all the GBMs in your foreach loop in parallel on the same single-core H2O cluster. You can only connect to one H2O cluster at a time from a single R instance, however the foreach loop will create a new R instance. Unlike most machine learning algos in R, the H2O algos are all multi-core enabled so the training process will already be parallelized at the algorithm level, without the need for a parallel R package like foreach . You have a few options (#1 or #3 is probably best): Set h2o.init(nthreads = -1) at the top of your script to use all 12 of your cores. Change the foreach() loop to a regular loop and train each GBM (on a different data partition) sequentially. Although the different GBMs are trained sequentially, each single GBM will be fully parallelized across the H2O cluster. Set h2o.init(nthreads = -1) at the top of your script, but keep your foreach() loop. This should run all your GBMs at once, with each GBM parallelized across all cores. This could overwhelm the H2O cluster a bit (this is not really how H2O is meant to be used) and could be a bit slower than #1, but it's hard to say without knowing the size of your data and the number of partitions of you want to train on. If you are already using 70% of your RAM for a single GBM, then this might not be the best option. You can update your code to do the following (which most closely resembles your original script). This will preserve your foreach loop, creating a new 1-core H2O cluster at a different port on your machine. See below. Updated R code example which uses the iris dataset and returns the predicted class for iris as a data.frame: library(foreach)library(doParallel)library(h2o)h2o.shutdown(prompt = FALSE)#setup parallel backend to use 12 processorscl <- makeCluster(12)registerDoParallel(cl)#loopdf4 <- foreach(i = seq(20), .combine=rbind) %dopar% { library(h2o) port <- 54321 + 3*i print(paste0("http://localhost:", port)) h2o.init(nthreads = 1, max_mem_size = "1G", port = port) df4 <- data.frame() data(iris) data <- as.h2o(iris) ss <- h2o.splitFrame(data) gbm <- h2o.gbm(x = 1:4, y = "Species", training_frame = ss[[1]]) df4 <- as.data.frame(h2o.predict(gbm, ss[[2]]))[,1]} In order to judge which option is best, I would try running this on a few data partitions (maybe 10-100) to see which approach seems to scale the best. If your training data is small, it's possible that #3 will be faster than #1, but overall, I'd say #1 is probably the most scalable/stable solution. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43444333', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3587303/']} | jdg_86117 |
stackexchange | llm_judgeable_groundtruth_similarity | 56799906 |
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 created an app that connects successfully to our server using Ionic Native HTTP, testing it with Samsung Galaxy J7 Prime OS version Marshmallow and several others that were not yet under Android Pie. For some reason, when I tested it with a device under Android Pie, it won't work anymore and I'm receiving CORS policy issues. Has anybody encountered a similar issue? Is there a workaround for this? Unfortunately, modifications within the server config is not an option. I've also read some solutions about proxy but am not sure how to implement them. Versions:cordova-plugin-advanced-http: 2.1.1ionic-native/http: 5.8.0
Now provide the response and nothing else.
| Android P requires HTTPS by default. What this means is that if you are using unencrypted HTTP requests in your app, the app will work fine in all lower versions than Android P. To avoid this security exception, try below changes in your app code. In AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?><manifest ... > <application android:networkSecurityConfig="@xml/network_security_config" ... > ... </application></manifest> and in res/xml add file named : network_security_config.xml network_security_config.xml <?xml version="1.0" encoding="utf-8"?><network-security-config> <domain-config cleartextTrafficPermitted="true"> // Add host of your download URL in below line. // ie. if url is "https://www.google.com/search?source=...." // then just add "www.google.com" <domain includeSubdomains="true">www.google.com</domain> </domain-config></network-security-config> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56799906', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4814351/']} | jdg_86118 |
stackexchange | llm_judgeable_groundtruth_similarity | 9146395 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Assuming that we have a T myarray[100] with T = int, unsigned int, long long int or unsigned long long int, what is the fastest way to reset all its content to zero (not only for initialization but to reset the content several times in my program)? Maybe with memset? Same question for a dynamic array like T *myarray = new T[100] .
Now provide the response and nothing else.
| memset (from <string.h> ) is probably the fastest standard way, since it's usually a routine written directly in assembly and optimized by hand. memset(myarray, 0, sizeof(myarray)); // for automatically-allocated arraysmemset(myarray, 0, N*sizeof(*myarray)); // for heap-allocated arrays, where N is the number of elements By the way, in C++ the idiomatic way would be to use std::fill (from <algorithm> ): std::fill(myarray, myarray+N, 0); which may be optimized automatically into a memset ; I'm quite sure that it will work as fast as memset for int s, while it may perform slightly worse for smaller types if the optimizer isn't smart enough. Still, when in doubt, profile. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/9146395', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/882932/']} | jdg_86119 |
stackexchange | llm_judgeable_groundtruth_similarity | 5036971 |
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 find out the currency locale on user's iphone programmatically. That means, if user is in US Store, the currency locale should be USD, for Australia, it should be AUD. My purpose of this task is to try to convert the item price listed on our app to be nearly match with the price that AppStore ask. For example, if we sell a video 3 usd, and an Australian wants to buy it, then I should show 2.8 AUD in my app screen. It will reduce the calculation in the user over the real price in his country. Does anybody know how to do it?
Now provide the response and nothing else.
| In most cases the currency symbol won't be enough. For example, in Germany we write our prices like this: 1,99€ but people in the US use $1.99. There are three differences in the string. The currency symbol, the position of it and the separator. If you want to do it right you should use a NSNumberFormatter. It takes care of all the differences between currency formats. And it does it much better than you. Because it does it for all currencies, not just for the 4 main currencies you want to support. NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];[formatter setLocale:[NSLocale currentLocale]];NSString *localizedMoneyString = [formatter stringFromNumber:myCurrencyNSNumberObject]; If you want to use this for in app purchase you can't rely on the users current locale, because it is possible to use a US-based account on a device with a DE (german) locale. And the price of your item (actual price is 0,79€ in Germany) would show as 0,99€ (because it costs $0.99 in the US). This would be wrong. You get a localized price already from the app store, there is no need to do calculations on your own. And you get a price and a priceLocale for each of your SKProducts. You would get the correct formatted currency string like this: SKProduct *product = [self.products objectAtIndex:indexPath.row];NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];[formatter setLocale:product.priceLocale];currencyString = [formatter stringFromNumber:product.price]; EDIT: since you specifically asked for the currency code. You can get it with NSString *currencyCode = [formatter currencyCode]; This will give you the currency code according to ISO 4217. AUD, USD, EUR and so on. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5036971', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/227698/']} | jdg_86120 |
stackexchange | llm_judgeable_groundtruth_similarity | 3780 |
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:
How can I get the co-ordinates of the convex hull of a piece of Text ?
Now provide the response and nothing else.
| The question could be rephrased: how do we get a vector graphic from a bitmap?The solution is pretty simple by using the code we can find here . p = Image[Graphics[Text[Style["Get Convex Hull points.", Large]]]];img = Thinning@EdgeDetect@p;points = N@Position[ImageData[img], 1];pts = Union@Flatten[FindCurvePath[points] /. c_Integer :> points[[c]], 1];Needs["ComputationalGeometry`"]chp = ConvexHull[pts];Show[Graphics@{Red, Thick, Line[Append[pts[[chp]], pts[[chp]][[1]]]]},ListPlot[pts]] | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/3780', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/888/']} | jdg_86121 |
stackexchange | llm_judgeable_groundtruth_similarity | 57725 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Strassen Algoritm is a well-known matrix multiplication divide and conquer algorithm.The trick of the algorithm is reducing the number of multiplications to 7 instead of 8. I was wondering, can we reduce any further? Can we only do 6 multiplications? Also, what happens if we divide the NxN arrays into 9 arrays each of (N/3)x(N/3) instead of 4 arrays of (N/2)x(N/2). Can we then do less multiplications?
Now provide the response and nothing else.
| You may be interested to know that there's a way to multiply $3\times3$ matrices using only 23 multiplications (where the naive method uses $27$). See Julian D. Laderman, A noncommutative algorithm for multiplying $3\times3$ matrices using $23$ muliplications, Bull. Amer. Math. Soc. 82 (1976) 126–128, MR0395320 (52 #16117). As for doing $2\times2$ with fewer than $7$ multiplications, this was proved impossible just a few years ago. See J M Landsberg, The border rank of the multiplication of $2\times2$ matrices is seven, J. Amer. Math. Soc. 19 (2006), 447–459, MR2188132 (2006j:68034). EDIT: As Mariano points out, Landsberg acknowledged a gap in the proof. But don't panic. The review, and my preceding paragraph, were based on the electronic version of Landsberg's paper. The print version (which is freely available on the AMS website) is different. It says, "Hopcroft and Kerr [12] and Winograd [22] proved independently that there is no algorithm for multiplying $2\times2$ matrices using only six multiplications." Those references are J. E. Hopcroft and L. R. Kerr, On minimizing the number of multiplications necessary formatrix multiplication, SIAM J. Appl. Math. 20 (1971), 30–36, MR0274293 (43:58). S.Winograd, On multiplication of $2\times2$ matrices, Linear Algebra and Appl. 4 (1971), 381–388, MR0297115 (45:6173). | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/57725', 'https://mathoverflow.net', 'https://mathoverflow.net/users/13482/']} | jdg_86122 |
stackexchange | llm_judgeable_groundtruth_similarity | 25438172 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I use this script to find out the current folder with its .bat file: for /f %%i in ("%0") do set curpath=%%~dpi echo %curpath% it doesn't work correctly, if the path contains spaces(D:\Scripts\All Scripts -> retrieves only D:\Scripts\, if I place in the folder, whose path doesn't have spaces it retrieves the full path). How can I fix it?
Now provide the response and nothing else.
| 2015-03-30: Edited - Missing information has been added To retrieve the current directory you can use the dynamic %cd% variable that holds the current active directory set "curpath=%cd%" This generates a value with a ending backslash for the root directory, and without a backslash for the rest of directories. You can force and ending backslash for any directory with for %%a in ("%cd%\") do set "curpath=%%~fa" Or you can use another dynamic variable: %__CD__% that will return the current active directory with an ending backslash. Also, remember the %cd% variable can have a value directly assigned. In this case, the value returned will not be the current directory, but the assigned value. You can prevent this with a reference to the current directory for %%a in (".\") do set "curpath=%%~fa" Up to windows XP, the %__CD__% variable has the same behaviour. It can be overwritten by the user, but at least from windows 7 (i can't test it on Vista), any change to the %__CD__% is allowed but when the variable is read, the changed value is ignored and the correct current active directory is retrieved (note: the changed value is still visible using the set command). BUT all the previous codes will return the current active directory , not the directory where the batch file is stored . set "curpath=%~dp0" It will return the directory where the batch file is stored, with an ending backslash. BUT this will fail if in the batch file the shift command has been used shiftecho %~dp0 As the arguments to the batch file has been shifted, the %0 reference to the current batch file is lost. To prevent this, you can retrieve the reference to the batch file before any shifting, or change the syntax to shift /1 to ensure the shift operation will start at the first argument, not affecting the reference to the batch file. If you can not use any of this options, you can retrieve the reference to the current batch file in a call to a subroutine @echo off setlocal enableextensions rem Destroy batch file reference shift echo batch folder is "%~dp0" rem Call the subroutine to get the batch folder call :getBatchFolder batchFolder echo batch folder is "%batchFolder%" exit /b:getBatchFolder returnVar set "%~1=%~dp0" & exit /b This approach can also be necessary if when invoked the batch file name is quoted and a full reference is not used (read here ). | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25438172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3328286/']} | jdg_86123 |
stackexchange | llm_judgeable_groundtruth_similarity | 16823 |
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 have noticed that in Russia cyber criminals are rarely brought to justice or extradite (even non Russian citizens) except if their wrongdoing affects Russian citizens or some former USSR countries. What is the point of this ? Which laws are used to prosecute cyber criminals which "disturbs" Russia and why this is not used against other ones?
Now provide the response and nothing else.
| Please provide data for your assertion that Russia prosecutes computer crime less than other countries. That is, we have no reason to believe that what you assert is, if fact, true. As to extradition, Article 61 of the Russian constitution specifically forbids the extradition of Russian nationals. Further Article 62 states: The extradition of persons persecuted for their political views or any actions (or inaction), which are not qualified as criminal by the law of the Russian Federation, to other states shall not be allowed in the Russian Federation. The extradition of persons charged with crimes and also the hand-over of convicts for serving time in other countries shall be effected on the basis of the federal law or international treaty of the Russian Federation. So, even for foreign nationals, extradition must be on the basis of a law that a) makes the act a crime and b) allows extradition or is with a country with whom Russia has an extradition treaty. I cannot find a list of countries with which Russia has such treaties but I know the USA isn't one. Given the any such extradition treaty would be effectively one way (i.e. from the foreign state to Russia but not the other way); there is little incentive for any state to sign one with Russia. | {} | {'log_upvote_score': 4, 'links': ['https://politics.stackexchange.com/questions/16823', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/13310/']} | jdg_86124 |
stackexchange | llm_judgeable_groundtruth_similarity | 39133424 |
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 read in a book that "you can't create traditional 'classes' in julia with single-dispatch-style methods like obj.myfunc() " ... and I thought that sounded more like a challenge than a fact. So here's my JavaClass type with public / private fields and methods just for the sheer shock and horror factor of having something ugly like this in Julia, after all the trouble the devs have gone to to avoid it: type JavaClass # Public fields name::String # Public methods getName::Function setName::Function getX::Function getY::Function setX::Function setY::Function # Primary Constructor - "through Whom all things were made." function JavaClass(namearg::String, xarg::Int64, yarg::Int64) # Private fields - implemented as "closed" variables x = xarg y = yarg # Private methods used for "overloading" setY(yarg::Int64) = (y = yarg; return nothing) setY(yarg::Float64) = (y = Int64(yarg * 1000); return nothing) # Construct object this = new() this.name = namearg this.getName = () -> this.name this.setName = (name::String) -> (this.name = name; return nothing) this.getX = () -> x this.getY = () -> y this.setX = (xarg::Int64) -> (x = xarg; return nothing) this.setY = (yarg) -> setY(yarg) #Select appropriate overloaded method # Return constructed object return this end # a secondary (inner) constructor JavaClass(namearg::String) = JavaClass(namearg, 0,0)end Example use: julia> a = JavaClass("John", 10, 20);julia> a.name # public"John"julia> a.name = "Jim";julia> a.getName()"Jim"julia> a.setName("Jack")julia> a.getName()"Jack"julia> a.x # private, cannot accessERROR: type JavaClass has no field xjulia> a.getX()10julia> a.setX(11)julia> a.getX()11julia> a.setY(2) # "single-dispatch" call to Int overloaded methodjulia> a.getY()2julia> a.setY(2.0)julia> a.getY() # "single-dispatch" call to Float overloaded method2000julia> b = JavaClass("Jill"); # secondary constructorjulia> b.getX()0 Essentially, the constructor becomes a closure, which is how one creates "private" fields and methods / overloading.Any thoughts? (other than "OMG Why??? Why would you do this??" ) Any other approaches? Any scenarios you could envisage where this might fail spectacularly?
Now provide the response and nothing else.
| While of course this isn't the idiomatic way to create objects and methods in julia, there's nothing horribly wrong with it either. In any language with closures you can define your own "object systems" like this, for example see the many object systems that have been developed within Scheme. In julia v0.5 there is an especially slick way to do this due to the fact that closures represent their captured variables as object fields automatically. For example: julia> function Person(name, age) getName() = name getAge() = age getOlder() = (age+=1) ()->(getName;getAge;getOlder) endPerson (generic function with 1 method)julia> o = Person("bob", 26)(::#3) (generic function with 1 method)julia> o.getName()"bob"julia> o.getAge()26julia> o.getOlder()27julia> o.getAge()27 It's weird that you have to return a function to do this, but there it is. This benefits from many optimizations like the language figuring out precise field types for you, so in some cases we can even inline these "method calls". Another cool feature is that the bottom line of the function controls which fields are "public"; anything listed there will become a field of the object. In this case you get only the methods, and not the name and age variables. But if you added name to the list then you'd be able to do o.name as well. And of course the methods are also multi-methods; you can add multiple definitions for getOlder etc. and it will work like you expect. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39133424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4183191/']} | jdg_86125 |
stackexchange | llm_judgeable_groundtruth_similarity | 51487769 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using laravel 5.6 My script to insert big data is like this : ...$insert_data = [];foreach ($json['value'] as $value) { $posting_date = Carbon::parse($value['Posting_Date']); $posting_date = $posting_date->format('Y-m-d'); $data = [ 'item_no' => $value['Item_No'], 'entry_no' => $value['Entry_No'], 'document_no' => $value['Document_No'], 'posting_date' => $posting_date, .... ]; $insert_data[] = $data;}\DB::table('items_details')->insert($insert_data); I have tried to insert 100 record with the script, it works. It successfully insert data But if I try to insert 50000 record with the script, it becomes very slow. I've waited about 10 minutes and it did not work. There exist error like this : 504 Gateway Time-out How can I solve this problem?
Now provide the response and nothing else.
| As it was stated, chunks won't really help you in this case if it is a time execution problem. I think that bulk insert you are trying to use cannot handle that amount of data , so I see 2 options: 1 - Reorganise your code to properly use chunks, this will look something like this: $insert_data = [];foreach ($json['value'] as $value) { $posting_date = Carbon::parse($value['Posting_Date']); $posting_date = $posting_date->format('Y-m-d'); $data = [ 'item_no' => $value['Item_No'], 'entry_no' => $value['Entry_No'], 'document_no' => $value['Document_No'], 'posting_date' => $posting_date, .... ]; $insert_data[] = $data;}$insert_data = collect($insert_data); // Make a collection to use the chunk method// it will chunk the dataset in smaller collections containing 500 values each. // Play with the value to get best result$chunks = $insert_data->chunk(500);foreach ($chunks as $chunk){ \DB::table('items_details')->insert($chunk->toArray());} This way your bulk insert will contain less data, and be able to process it in a rather quick way. 2 - In case your host supports runtime overloads, you can add a directive right before the code starts to execute : ini_set('max_execution_time', 120 ) ; // time in seconds$insert_data = [];foreach ($json['value'] as $value){ ...} To read more go to the official docs | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51487769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5281051/']} | jdg_86126 |
stackexchange | llm_judgeable_groundtruth_similarity | 28688822 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
SELECT "dbo"."ClaimDataFormat"."AGE", "dbo"."ClaimDataFormat"."RELATION", "dbo"."ClaimDataFormat"."NAME", "dbo"."ClaimDataFormat"."ENTRY_DATE", "dbo"."ClaimDataFormat"."CLAIM_AMT", CASE WHEN "dbo"."ClaimDataFormat"."Gender" = 'F' THEN 'FEMALE' ELSE 'MALE' END AS GENDER, "dbo"."ClaimDataFormat"."STATUS", "dbo"."ClaimDataFormat"."APPROVED_AMT"FROM "dbo"."ClaimDataFormat"WHERE "dbo"."ClaimDataFormat"."AGE" = CASE WHEN ${TimeGran} = '0-10' THEN 0 WHEN ${TimeGran} = '0-10' THEN 1 WHEN ${TimeGran} = '0-10' THEN 2 WHEN ${TimeGran} = '0-10' THEN 3 WHEN ${TimeGran} = '0-10' THEN 4 WHEN ${TimeGran} = '0-10' THEN 5 WHEN ${TimeGran} = '0-10' THEN 6 WHEN ${TimeGran} = '0-10' THEN 7 WHEN ${TimeGran} = '0-10' THEN 8 WHEN ${TimeGran} = '0-10' THEN 9 WHEN ${TimeGran} = '0-10' THEN 10 WHEN ${TimeGran} = '11-20' THEN 11 WHEN ${TimeGran} = '11-20' THEN 12 WHEN ${TimeGran} = '11-20' THEN 13 WHEN ${TimeGran} = '11-20' THEN 14 WHEN ${TimeGran} = '11-20' THEN 15 WHEN ${TimeGran} = '11-20' THEN 16 WHEN ${TimeGran} = '11-20' THEN 17 WHEN ${TimeGran} = '11-20' THEN 18 WHEN ${TimeGran} = '11-20' THEN 19 WHEN ${TimeGran} = '11-20' THEN 20 ELSE 21 END if the age band is 0-10 the all values between 0 and 10 must be reflected
Now provide the response and nothing else.
| Adding internal member to a public abstract class makes it impossible to inherit that abstract class outside of assembly it was declared in. But the class itself as well as all derived classes can still be used (as the types are public ) outside of declaring assembly. Let's say you have an abstract class: public abstract AMyClass{ public string DoSomething() { return DoSomethingInternal(); } internal abstract string DoSomethingInternal();} And another public class that inherits it, declared in the same assembly public sealed MyClass : AMyClass{ internal override string DoSomethingInternal() { return "Hey from MyClass!"; }} You could still create an instance of MyClass in different assemblies, but you won't be able to implement your own class that derives from AMyClass , because you won't be able to implement abstract DoSomethingInternal method. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28688822', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4599778/']} | jdg_86127 |
stackexchange | llm_judgeable_groundtruth_similarity | 370433 |
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:
Here is a simplified sample. Basically, it does checks on a string from a string list. If the check passes, it will remove that string ( filterStringOut(i); ), and it is no longer necessary to continue any other checks. Thus continue to the next string. void ParsingTools::filterStrings(QStringList &sl){ /* Filter string list */ QString s; for (int i=0; i<sl.length(); i++) { s = sl.at(i); // Improper length, remove if (s.length() != m_Length) { filterStringOut(i); continue; // Once removed, can move on to the next string } // Lacks a substring, remove for (int j=0; j<m_Include.length(); j++) { if (!s.contains(m_Include.at(j))) { filterStringOut(i); /* break; and continue; */ } } // Contains a substring, remove for (int j=0; j<m_Exclude.length(); j++) { if (s.contains(m_Exclude.at(j))) { filterStringOut(i); /* break; and continue; */ } } }} How ought one continue the outer loop from inside a nested loop? My best guess is to use goto and place a label at the end of the outer loop. That prompted me to ask this question, given how taboo goto can be. In the c++ IRC chat, it was suggested that I place the for loops in bool functions, that return true if a check passed. thus if ( containsExclude(s)) continue;if (!containsInclude(s)) continue; or that I simply create a local boolean, set it to true break , check bool and continue if true. Given that I am using this in a parser, I actually do need to prioritize performance in this example. Is this a situation where goto is still useful, or is it a case where I need to restructure my code?
Now provide the response and nothing else.
| Don't nest: convert to functions instead. And have those functions return true if they perform their action and the subsequent steps can be skipped; false otherwise. That way you completely avoid the whole problem of how to break out of one level, continue within another, etc as you just chain the calls with || (this assumes C++ stops processing an expression on a true ; I think it does). So your code might end up looking like the following (I haven't written C++ in years, so it likely contains syntax errors, but should give you the general idea): void ParsingTools::filterStrings(QStringList &sl){ QString s; for (int i=0; i<sl.length(); i++) { s = sl.at(i); removeIfImproperLength(s, i) || removeIfLacksRequiredSubstring(s, i) || removeIfContainsInvalidSubstring(s, i); }}bool removeIfImproperLength(QString s, int i) { if (s.length() != m_Length) { filterStringOut(i); return true; } return false;} bool removeIfLacksSubstring(QString s, int i) { for (int j=0; j<m_Include.length(); j++) { if (!s.contains(m_Include.at(j))) { filterStringOut(i); return true; } } return false;}bool removeIfContainsInvalidSubstring(QString s, int i) { for (int j=0; j<m_Exclude.length(); j++) { if (s.contains(m_Exclude.at(j))) { filterStringOut(i); return true; } } return false;} | {} | {'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/370433', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/136084/']} | jdg_86128 |
stackexchange | llm_judgeable_groundtruth_similarity | 182160 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm new to Spring Security. How do I add an event listener which will be called as a user logs in successfully? Also I need to get some kind of unique session ID in this listener which should be available further on. I need this ID to synchronize with another server.
Now provide the response and nothing else.
| You need to define a Spring Bean which implements ApplicationListener . Then, in your code, do something like this: public void onApplicationEvent(ApplicationEvent appEvent){ if (appEvent instanceof AuthenticationSuccessEvent) { AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent; UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal(); // .... }} Then, in your applicationContext.xml file, just define that bean and it will automatically start receiving events :) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/182160', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/578/']} | jdg_86129 |
stackexchange | llm_judgeable_groundtruth_similarity | 2934161 |
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 kind of new to the Magento, so forgive me for my stupid question! As I understand the whole concept of Magento is base on overriding the basic components that's are available with in the Magento. So based on my understanding I've decided to update the layout of onepage checkout in Magento. I've created my own layout and in the config file set that my layout updates the checkout module layout. But the problem is it's actually does not update the base layout, it replaces it self with base layout! Should it be act like this or am I wrong?!
Now provide the response and nothing else.
| In fact, the node in your config.xml file doesn't do an "update".As a matter of fact, I think you have done that in your config.xml : <config> <frontend> <layout> <updates> <checkout> <file>mylayout.xml</file> </checkout> </updates> </layout> </frontend></config> and you have done your modifications in mylayout.xml. In fact, you have to do : <config> <frontend> <layout> <updates> <mymodule> <file>mylayout.xml</file> </mymodule> </updates> </layout> </frontend></config> And then, in mylayout.xml : <checkout_cart_index> <!-- this corresponds to the section where you want to add your block (or modify an existing block --> <reference name="content"> <reference name="checkout.cart"> <block type="mymodule/myblock" name="checkout.mymodule.myblock"></block> </reference> </reference></checkout_cart_index> By looking at my code and comparing the files to each other, you will understand better how it works. In fact, don't forget that all xml files are concatenated in magento.So that, all nodes in all config files, respecting the same order, will be concataneted. For example, in our case, the config.xml files of magento will be concatenated, and the result is ONE file containing : <config><!-- some nodes... --><!-- some nodes... --><!-- some nodes... --> <frontend> <layout> <updates> <mymodule> <file>mylayout.xml</file> </mymodule> <checkout> <!-- this is the node from the config.xml of the Checkout Module--> <file>checkout.xml</file> </checkout> <!-- some layout updates nodes from other config files... --> </updates> </layout> </frontend><!-- some nodes... --><!-- some nodes... --></config> If you had replaced <mymodule> by <checkout> the resulting file would have looked : <config><!-- some nodes... --><!-- some nodes... --><!-- some nodes... --> <frontend> <layout> <updates> <checkout> <file>mylayout.xml</file> </checkout> <!-- some layout updates nodes from other config files... --> </updates> </layout> </frontend><!-- some nodes... --><!-- some nodes... --></config> Note the mylayout.xml.This is the reason why the original layout file is completely replaced by your own layout :) Hope that's clear, in french it would have been easier for me to explain ;) Hugues. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2934161', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1125173/']} | jdg_86130 |
stackexchange | llm_judgeable_groundtruth_similarity | 48020746 |
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 totalcount as 585. Need options values (totalcount/10) based on totalcount dynamically. Like 1,2,3,4,5,6. Previously: <div class="form-inline pull-right"> <div class="form-group"> <label>Entries</label> <select ng-model="$ctrl.entries" class="input-sm border-radius-none form-control"> <option ng-value="10">10</option> <option ng-value="20">20</option> <option ng-value="30">30</option> <option ng-value="40">40</option> <option ng-value="50">50</option> </select> </div> <span> </span> </div>
Now provide the response and nothing else.
| With Java9 , you can do this using the newly added Optional::stream API : List<String> collect = list.stream() .flatMap(Optional::stream) .collect(Collectors.toList()); This method can be used to transform a Stream of optional elements to a Stream of present value elements . Sticking with Java8 , the Way1 in the question is good enough IMHO - List<String> collect = list.stream() .filter(Optional::isPresent) .map(Optional::get) // just a small update of using reference .collect(Collectors.toList()); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48020746', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8541686/']} | jdg_86131 |
stackexchange | llm_judgeable_groundtruth_similarity | 25103288 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm using the new gradle build system and I'm facing the following problem: UNEXPECTED TOP-LEVEL EXCEPTION:com.android.dex.DexException: Multiple dex files define Lcom/kibo/mobi/BuildConfig; at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:594) at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:552) at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:533) at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:170) at com.android.dx.merge.DexMerger.merge(DexMerger.java:188) at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:439) at com.android.dx.command.dexer.Main.runMonoDex(Main.java:287) at com.android.dx.command.dexer.Main.run(Main.java:230) at com.android.dx.command.dexer.Main.main(Main.java:199) at com.android.dx.command.Main.main(Main.java:103) Priniting the dependencies I can't see anything, here they are: firstDebugCompile - ## Internal use, do not manually configure ## \--- KiboGradle:KiboSDK:unspecified +--- KiboGradle:TextInputAPI:unspecified +--- KiboGradle:VoiceImeUtils:unspecified +--- com.google.android.gms:play-services:5.0.77 | \--- com.android.support:support-v4:19.1.0 +--- com.squareup.picasso:picasso:2.3.2 +--- com.google.code.gson:gson:2.2.4 \--- com.crittercism:crittercism-android-agent:4.5.1 I tried to verify that the problem is not a duplicate support library so I tried to add: compile ('com.google.android.gms:play-services:5.0.77'){ exclude module: 'support-v4'} Which resulted in errors that some of the support-v4 library classes can't be found, so this library not getting compiled from any other location. One thing I had in mind that could cause this problem is the fact that I using the Flavors feautre in oreder to create several versions of my application with different resourse files. And when I look at the file that is in the error I see this: *** Automatically generated file. DO NOT MODIFY*/package com.kibo.mobi;public final class BuildConfig { public static final boolean DEBUG = Boolean.parseBoolean("true"); public static final String PACKAGE_NAME = "com.kibo.mobi.test.official"; public static final String BUILD_TYPE = "debug"; public static final String FLAVOR = "liverpool"; public static final int VERSION_CODE = 1; public static final String VERSION_NAME = "1.0";} So the package in of the file and the package specified in String value are not the same. Can anyone see any issues in my configuration that could cause this problem?
Now provide the response and nothing else.
| In my case the similar error happened because there were 2 modules with the same package name in AndroidManifest.xml files. Using different package names in the modules solved the problem. Also the same thing happens when a library jar is being included twice (or more times) in several modules, as a dependency. In this case error message says about duplicate configs named after that library's package name. I solved it with including the library as a dependency in one module, and the second module had in dependencies the first module. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25103288', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1561247/']} | jdg_86132 |
stackexchange | llm_judgeable_groundtruth_similarity | 213695 |
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 an expr which has List at various levels and I want to display them nicely as a column inside a frame but my problem is that the search for List goes inside things like DateObject to ruin their structure. Replace[ expr, x_List/;!MatchQ[...[...x...],DateObject[x,__]]:>Framed[Column@x] All] So how should I define such a Rule ? Sample expr : {1->a,2->b,3->c,4->{5->d,6->e,7->Today},8->Yesterday,9->{10->f,11->{12->Tomorrow,13->g}}} Current output: Framed[Column[{1 -> a, 2 -> b, 3 -> c, 4 -> Framed[Column[{5 -> d, 6 -> e, 7 -> DateObject[Framed[Column[{2020, 1, 28}]], "Day", CalendarType -> "Gregorian", DateFormat -> Automatic]}]], 8 -> DateObject[Framed[Column[{2020, 1, 27}]], "Day", CalendarType -> "Gregorian", DateFormat -> Automatic], 9 -> Framed[Column[{10 -> f, 11 -> Framed[Column[{12 -> DateObject[Framed[Column[{2020, 1, 29}]], "Day", CalendarType -> "Gregorian", DateFormat -> Automatic], 13 -> g}]]}]]}]] Desired output: Framed[Column[{1 -> a, 2 -> b, 3 -> c, 4 -> Framed[Column[{5 -> d, 6 -> e, 7 -> DateObject[{2020, 1, 28}, "Day", CalendarType -> "Gregorian", DateFormat -> Automatic]}]], 8 -> DateObject[{2020, 1, 27}, "Day", CalendarType -> "Gregorian", DateFormat -> Automatic], 9 -> Framed[Column[{10 -> f, 11 -> Framed[Column[{12 -> DateObject[{2020, 1, 29}, "Day", CalendarType -> "Gregorian", DateFormat -> Automatic], 13 -> g}]]}]]}]]
Now provide the response and nothing else.
| You can use the fact that once an object is replaced, it doesn't get replaced by any further rules. So, just add a rule that replaces a DateObject with itself: expr = {1 -> a, 2 -> b, 3 -> c, 4 -> {5 -> d, 6 -> e, 7 -> Today}, 8 -> Yesterday, 9 -> {10 -> f, 11 -> {12 -> Tomorrow, 13 -> g}}}lexpr /. {a_DateObject :> a, List -> Framed@*Column@*List} | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/213695', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/13892/']} | jdg_86133 |
stackexchange | llm_judgeable_groundtruth_similarity | 56942462 |
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 class like this: public class SampleClass{ const string UnChangableUserName { get; private set; } string Password { get; private set; } public SampleClass(string UnChangableUserName, string Password) { this.Password = Password; this.UnChangableUserName = UnChangableUserName; }} I want the constructor to assign a value to the const, and not for the value to be set when the const is defined. How can I do it? I'm aware I can simply not use set but using const is more resource efficent and more elegant as well as clearer to other devs to understand, I don't want a set so they will not add it.
Now provide the response and nothing else.
| You can't. By definition, const s in C# are defined at compile-time , not at runtime. They can't be changed by any code, even constructor code, because they're not even there at runtime - they're replaced by their literal values at every point of usage. What you're looking for is either readonly fields or read only properties . Readonly fields are marked by the readonly modifier: private readonly string _username; Readonly fields are only assignable during construction, either directly assigned in the definition itself ( readonly string _username = "blah" ) or in the constructor. The compiler will enforce this limitation, and will not allow you to set a value anywhere else. Readonly properties are simply properties that don't expose a setter at all. Until C# 6, you could use them to return the value of a readonly field (as above), but you couldn't assign to them. As of C# 6, though, there's syntax supporting read-only auto-properties that can be assigned: even though there's no explicit setter, there's an implicit setter that can, again, only be called from the constructor, or from a field initializer: public string Username { get } = "Username" ; It may look strange that you're setting to a property with no setter, but that's simply an implicit part of the language - there's an implicit backing field that's readonly , and can be set at initialization. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56942462', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_86134 |
stackexchange | llm_judgeable_groundtruth_similarity | 536191 |
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:
Let me start with the definitions I'm used to. Let $I[\Phi^i]$ be the action for some collection of fields. A variation of the fields about the field configuration $\Phi^i_0(x)$ is a one-parameter family of field configurations $\Phi^i(\lambda,x)$ such that $\Phi^i(0,x)=\Phi^i_0(x)$ where $\lambda\in (-\epsilon,\epsilon)$ . We take the map $\lambda\mapsto \Phi^i(\lambda,x)$ to be differentiable. In that case the first variation is defined by $$\delta \Phi^i(x) \equiv \dfrac{\partial}{\partial \lambda}\bigg|_{\lambda =0}\Phi^i(\lambda,x)\tag{1}.$$ Likewise the first variation of the action is defined to be $$\delta I[\Phi^i]\equiv\dfrac{d}{d\lambda}I[\Phi^i_\lambda],\quad \Phi^i_\lambda\equiv \Phi^i(\lambda,\cdot)\tag{2}.$$ Now, as I understand, the variational principle is the statement that the physical classical field configuration should be $\Phi^i$ such that $\delta I[\Phi^i]=0$ for any first variation $\delta \Phi^i$ . It so happens that most of the time $I[\Phi^i]$ is the integral over spacetime of some Lagrangian density $d$ -form $\mathcal{L}[\Phi^i]$ . Then if $M$ has some sort of boundary $\partial M$ it may happen that $\delta I[\Phi^i]$ has boundary terms contributing to it. Now, in this paper the authors say that such boundary terms make the variational principle ill-defined (c.f. page 61): As stated by Regge and Teitelboim, the action must posssess well defined functional derivatives: this must be of the form $\delta I[\phi]=\int(\text{something})\delta \phi$ with no extra boundary terms spoiling the derivative. The action must be differentiable in order for the extremum principle to make sense. This is also alluded to in the WP page about the Gibbons-Hawking-York term in gravity: The Einstein–Hilbert action is the basis for the most elementary variational principle from which the field equations of general relativity can be defined. However, the use of the Einstein–Hilbert action is appropriate only when the underlying spacetime manifold ${\mathcal {M}}$ is closed, i.e., a manifold which is both compact and without boundary. In the event that the manifold has a boundary $\partial\mathcal{M}$ , the action should be supplemented by a boundary term so that the variational principle is well-defined. The boundary term alluded to above is introduced exactly to cancel one boundary term appearing when one varies the Einstein-Hilbert action. So again I take this as saying that if the variation of the EH action had such boundary term the variational principle wouldn't be well-defined. Now, although this seems such a basic thing I must confess I still didn't get it: Regarding the discussion in the linked paper, by repeated application of the Liebnitz rule, the variation of the Lagrangian density $\cal L$ always may be written as $${\delta \cal L} = E_i\delta \Phi^i +d\Theta\tag{3},$$ where $E_i$ are the equations of motion and $\Theta$ is the presympletic potential. The action thus is of the form $$\delta I[\Phi^i]=\int_M E_i \delta \Phi^i + \int_{\partial M}\Theta\tag{4},$$ I don't see how the presence of $\Theta$ stops us from defining $E_i$ as the functional derivatives. Moreover, for me the most reasonable notion of differentiability for the action is to say that $\lambda\mapsto I[\Phi^i_\lambda]$ is a differentiable mapping. I don't see how boundary terms affect this. So why boundary terms in $\delta I[\Phi^i]$ yields ill-defined functional derivatives? And in what sense this makes $I$ not differentiable? More importantly, both the paper and the WP page on the GHY term allude to the variational principle being ill-defined if $\delta I[\Phi^i]$ contains boundary terms. We have a mapping $\lambda\mapsto I[\Phi^i_\lambda]$ and we seek an extremum of such map. I don't see how the fact that $\delta I[\Phi^i]$ has boundary terms would make this optimization problem ill-defined. So why boundary terms make the variational principle ill-defined? In other words, why a well-defined variational principle demands $\delta I[\Phi^i]$ to be of the form $\delta I[\Phi^i]=\int({\text{something}})\delta \Phi^i$ as the authors of the paper seem to claim?
Now provide the response and nothing else.
| If we have non-vanishing boundary terms, then the map $\lambda \mapsto I[\Phi_\lambda^i]$ is not differentiable in the following sense. Using somewhat less sophisticated notation, let $$I[\Phi^i_\lambda:\eta] := \int_{\mathcal M} \mathcal L\left(\Phi^i_0(x)+\lambda\cdot \eta(x),\partial\Phi_0^i(x)+\lambda\cdot\partial\eta(x)\right) d^4x$$ for some arbitrary differentiable function $\eta$ . This map is certainly differentiable, and we find that $$\left.\frac{d}{d\lambda}I[\Phi^i_\lambda:\eta]\right|_{\lambda=0} = \int_{\mathcal M}\left(\frac{\partial \mathcal L}{\partial \Phi_0^i}-\partial_\mu \left[\frac{\partial \mathcal L}{\partial(\partial_\mu \Phi_0^i)}\right]\right)\cdot \eta(x) \ d^4x+ \oint_{\partial\mathcal M} n_\mu\frac{\partial \mathcal L}{\partial (\partial_\mu \Phi_0^i)}\eta(x) \ dS$$ where $n_\mu$ are the components of the surface normal vector. This is differentiability in the sense of Gateaux . However, this Gateaux derivative generically depends on which $\eta$ we choose. The ultimate goal is to demand that the variation in the action functional vanish regardless of our choice of $\eta$ . Assuming that the boundary term vanishes, this implies that $$\int_{\mathcal M}E[\Phi_0^i]\eta(x) d^4x = 0 \implies E[\Phi_0^i] = 0$$ However, in the presence of the boundary terms, no such implication is possible. For any particular field configuration, the variation in the action integral becomes $$\left.\frac{d}{d\lambda}I[\Phi^i_\lambda:\eta]\right|_{\lambda=0} = \int_{\mathcal M} f(x) \eta(x) d^4x + \oint_{\partial \mathcal M} n_\mu g^\mu(x)\eta(x) dS$$ For this to vanish for arbitrary $\eta$ , either both integrals need to vanish or they need to cancel each other. In the former case, the boundary terms are not present after all, while the latter case doesn't actually work. To see this, imagine that $$\int_{\mathcal M} f(x) \eta(x) d^4x =- \oint_{\partial \mathcal M} n_\mu g^\mu(x)\eta(x) dS = C \neq 0$$ for some choice of $\eta$ , and note that we can always add to $\eta$ a smooth function which vanishes on the boundary but has support at any region of the bulk that we choose. This would change the first integral but not the second, thus breaking the equality. Consequently, though the two integrals may cancel for some choices of $\eta$ , they cannot possibly cancel for all choices of $\eta$ (again, unless they both vanish in the first place). Even worse in a certain sense, the presence of the non-vanishing boundary terms implies, for reasons which follow immediately from those above, that the variation can be made to take any value in $\mathbb R$ by appropriate scaling of $\eta$ . One can think of this as rather analogous to multivariable calculus. The existence of partial (Gateaux) derivatives of some function (the action functional) along any particular direction (for arbitrary choice of $\eta$ ) is not sufficient to guarantee that the map is differentiable. In this case, with an eye toward our ultimate goal of having a vanishing functional derivative which independent of $\eta$ , we define a functional as differentiable if its Frechet derivative can be put in the form $$\left.\frac{d}{d\lambda}I[\Phi^i_\lambda:\eta]\right|_{\lambda=0} = \int_{\mathcal M} E[\Phi_0^i] \ \eta(x) d^4x$$ and define its functional derivative to be $E[\Phi_0^i]$ . I'd like to make a quick note on your statement I don't see how the presence of $\Theta$ stops us from defining $E_i$ as the functional derivatives. There's a good bit of truth in what you say. Indeed, if all you want is the Euler-Lagrange equations for the field, then you could argue that the correct formal prescription is to vary the action, throw away any boundary terms , and then demand that the variation vanish. It seems a bit inelegant, but it would give you the equations you're looking for. One runs into problems, however, when one moves to the Hamiltonian framework. Ambiguity in boundary terms leads to ambiguity when trying to define e.g. notions of total energy of a particular spacetime. In the absence of surface terms, the Hamiltonian vanishes for $g_{ij}, \pi^{ij}$ which obey the equations of motion; choosing a boundary term amounts to choosing a value for the integral of the Hamiltonian over all of spacetime, and the GHY term yields the ADM energy. Such boundary terms are apparently also quite important for quantum gravity, but this is an area with which I am wholly unfamiliar, so I cannot possibly comment intelligently on it. Let me ask something, you say "However, in the presence of the boundary terms, no such implication is possible". If we demand $\delta I[\Phi_0^i]=0$ wrt any variation, then in particular this would hold for compactly supported $\eta(x)$ . This would not imply $$\int_{\mathcal M}E[\Phi_0^i] \eta(x) d^4x = 0$$ for all compactly supported $\eta(x)$ and in turn imply $E[\Phi_0^i]=0$ even in the presence of boundary terms? What goes wrong here? It sounds like you are weakening the requirement that the action be stationary under arbitrary variation to the requirement that the action only be stationary under variations with compact support. If you do this, then you get the implication (and therefore the EL equations) back. However, this means that you are shrinking the space of "candidate" field configurations to those which are identical to the initial one at the boundary. If you are not interested in any kind of time evolution at the boundary, then this is fine; in general, this is too restrictive. One could imagine, for instance, a combination of initial condition and evolution equations which would necessarily change the field at the boundary. Imposing fixed (Dirichlet) boundary conditions in addition to the evolution equations and this particular initial condition would lead to no solutions at all. To make matters worse, in the particular case of gravity, the Lagrangian density actually contains second derivatives of the metric by way of a total derivative $$\partial_\mu (h^{\mu\nu} \partial_\nu \Phi_0^i)$$ which is a possibility I did not consider in the work I did above. In this case it follows that the boundary term becomes $$ \oint_{\partial M} n_\mu \big[g^\mu(x) \eta(x) + h^{\mu \nu}(x)\partial_\nu \eta(x)\big] dS$$ In this case, it would not suffice to hold the variation fixed at the boundary - we would also need to hold its derivatives fixed as well. This is unacceptable, as the equations of motion are themselves second-order; fixing both $\Phi_0^i$ and $\partial_\nu \Phi_0^i$ at the boundary would generically overdetermine the system, except in those serendipitous cases in which $n_\mu h^{\mu\nu} \rightarrow 0$ . | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/536191', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/21146/']} | jdg_86135 |
stackexchange | llm_judgeable_groundtruth_similarity | 49557637 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am having some docker container which listens on RabbitMQ and process the message received. I have a code pipeline which kicks off the rebuilding of the image and updating the tasks when there is a code commit. My problem here is the container will be killed abruptly during the message processing is there any way where I can stop the container killing until the process is finished and allow it to stop so that a new new container will be automatically created as I am ok with the current container processing the message with the old code. My container is running python code inside.
Now provide the response and nothing else.
| ECS by default sends a SIGTERM : StopTask Stops a running task. When StopTask is called on a task, the equivalent of docker stop is issued to the containers running in the task. This results in a SIGTERM and a default 30-second timeout, after which SIGKILL is sent and the containers are forcibly stopped. If the container handles the SIGTERM gracefully and exits within 30 seconds from receiving it, no SIGKILL is sent. Note The default 30-second timeout can be configured on the Amazon ECS container agent with the ECS_CONTAINER_STOP_TIMEOUT variable. For more information, see Amazon ECS Container Agent Configuration in the Amazon Elastic Container Service Developer Guide. Knowing this, you can add a simple check in your app to catch the SIGTERM, and react appropriately. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49557637', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4926141/']} | jdg_86136 |
stackexchange | llm_judgeable_groundtruth_similarity | 17409162 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an unsigned long long (or uint64_t ) value and want to convert it to a double . The double shall have the same bit pattern as the long value. This way I can set the bits of the double "by hand". unsigned long long bits = 1ULL;double result = /* some magic here */ bits; I am looking for a way to do this.
Now provide the response and nothing else.
| The portable way to do this is with memcpy (you may also be able to conditionally do it with reinterpret_cast or a union, but those aren't certain to be portable because they violate the letter of the strict-alias rules): // First, static assert that the sizes are the samememcpy(&result, &bits, sizeof(bits)); But before you do make sure you know exactly what you're doing and what floating point representation is being used (although IEEE754 is a popular/common choice). You'll want to avoid all kinds of problem values like infinity, NaN, and denormal numbers. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17409162', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/432354/']} | jdg_86137 |
stackexchange | llm_judgeable_groundtruth_similarity | 224910 |
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 list that looks like this: d= {{{"A5","I4","A2"}, {"A4","I5","A5"}}, {{"A2","A5","I4"}, {"A5","I5","A4"}}, {{"A2","A5","I4"}, {"A5","I4","A4"}}, {{"A2","A5","I4"}}, {{"A2","A5","I4"}}} How would I take list "d" and reorder the sublists so that they're all in the format of: {"A5","I(number)","A(number)"} The output I'm looking for would be: newd={{{"A5","I4","A2"},{"A5","I5","A4"}},{{"A5","I4","A2"},{"A5","I5","A4"}},{{"A5","I4","A2"},{"A5","I4","A4"}},{{"A5","I4","A2"}},{{"A5","I4","A2"}} Although some of the sublists in d are already in the correct form, I'm trying to find a generic way to put all of the sublists into that correct form.
Now provide the response and nothing else.
| One way: d /. x : {__String} :> SortBy[x, StringReplace[#, {"A5" -> 1, "I" ~~ _ -> 2, "A" ~~ _ -> 3}] &];% === newd True If you look at the output of StringReplace you will see remaining StringExpression heads, which is less than clean, but because they are all the same they do not affect the sort order. A variation: d /. x : {__String} :> SortBy[x, Characters@# /. {{"A", "5"} -> 1, {"I", _} -> 2, {"A", _} -> 3} &];% === newd True | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/224910', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/73552/']} | jdg_86138 |
stackexchange | llm_judgeable_groundtruth_similarity | 48082793 |
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 created a standard PubSub to BigQuery dataflow. However, in order to ensure I wasn't going to run up a huge bill while offline, I cancelled the dataflow. From the GCP console, there doesn't seem to be an option to restart it - is this possible, either through the console, or through the shell (and if so, how)?
Now provide the response and nothing else.
| Cloud Dataflow currently does not provide a mechanism to restart a Dataflow job that has been stopped or cancelled. However, for this Pub/Sub -> BigQuery flow, one way to approach this would be to use the Google-provided Pub/Sub to BigQuery template ; these templates provide code-free solutions for common data movement patterns using Cloud Dataflow. You can execute a streaming Dataflow job using this template, via the REST API , using a unique job name to ensure that there is only one instance of this Dataflow job running at any point in time. If the job were cancelled, you could (re)start this streaming Dataflow job by running the same command again. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48082793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/166556/']} | jdg_86139 |
stackexchange | llm_judgeable_groundtruth_similarity | 31336 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Just wanted to know if this would be considered a good way to handle login process. It doesn't matter which language it is written in. I will use this fellowing format. - Event (Where it happened) Connect to the server with user credentials. (Client) Verify if IP Address is blocked (by looking in a table on the database), if YES then send ERROR saying IP is blocked. (Server) Verify if account is active, if NO then send an ERROR to client saying account aren't active. (Server) Verify if account is blocked/banned from server, if YES then send ERROR saying account is blocked or banned from server. (Server) Compare password hash with database user account password hash, if the compare is NEGATIVE increase the number of attempts in the database associated to IP Address. If 3 are reached then ban the IP Address. (Server) Login are succesful at this point ! Additionnal Question : If you look at the point 5. I tried to find a good way to block the actual user which try to login (which doesn't mean its the user owner of the account) but without affecting the real user. What i mean is that if someone else than the owner of the account try to login more than 3 time on the specific account it will get his IP Address banned instead of the account in question. Would it be best to block the account aswell ? for a limited time or something ? Thanks!
Now provide the response and nothing else.
| In your process, people will get a distinct error code depending on whether the account exists or not. This is often considered somewhat inopportune. It is preferable if it is not possible, for outsider, to know whether a given account name exists; therefore, observable behaviour of your server should be the same in all situations which depend on the account name and lead to a failure: account does not exist, account is disabled, password is wrong. Note that "observable behaviour" includes not only the error code you return, but also the time taken by your server to respond (if you use slow-and-salted password hashing à la bcrypt -- and you really shoud do that -- then password verification can take a non-negligible time which can be measured from the outside). Banning an IP address after a few failures has the following caveats: The IP address you see could be shared between several people, in case of NAT . This is very common in organizations. Also common are HTTP proxies . You don't want three failures from one user to induce your server into banning a complete university, or even all the customers of a specific ISP. Sometimes, people forget their password. This happens a lot. So you will get "legitimate" login failures. Such users will want to use the "I forgot my password" process, and they will want to do it immediately . Therefore, the ban must not be long (say, ban for one minute at most). Attackers who are intent on trying a lot of potential login+password pairs will have relatively little trouble finding relay hosts to work around your IP-based banning. E.g. Tor , by construction, decreases the efficiency of IP banning. Therefore I do not recommend IP address banning on a general basis: it has a high risk of disrupting service for normal users, while not being very effective against average attackers. IP banning is useful against burst situations with crude attackers (e.g. automatic attacks from botnets trying to replicate), with tools like Fail2ban , but they can backfire, so caution must be exercised. Note that blocking accounts can also backfire: Blocking an account after too many failures means that anybody can block the accounts of other people. Attackers who try many login+password pairs can spread their attempts over a lot of distinct logins, avoiding the blocking feature. Reasonable solutions involve time-limited blocks (lock an account for one minute or so after a few wrong passwords) coupled with time-limited IP banning when a very suspicious access pattern is identified (a lot of connection attempts from the same IP). They will not give strong protection (only strong user passwords will), but they may help in reducing the noise from low-grade attackers and let you concentrate on the few cases where attackers exhibit an unusual amount of competence. | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/31336', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/21084/']} | jdg_86140 |
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.