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
11232474
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm working with strings that contain both digits and alphanumerics, or just digits, but not just alphas. In order to test for false matches, I need to check if the strings contain at least one digit, printing an error message if it doesn't. I have been using the following code: s = '0798237 sh 523-123-asdjlh'def contains_digits(s): for char in list(s): if char.isdigit(): return True break return Falseif contains_digits(s) == True: print selse: print 'Error' Is there a more pythonic or simpler way to do so, or does this suffice? Also, I can't just check to see if the string is alphanumeric, because the string may contain various symbols ('-', spaces, etc.) Now provide the response and nothing else.
This is one of those places where a regular expression is just the thing: _digits = re.compile('\d')def contains_digits(d): return bool(_digits.search(d)) Little demo: >>> _digits = re.compile('\d')>>> def contains_digits(d):... return bool(_digits.search(d))... >>> contains_digits('0798237 sh 523-123-asdjlh')True>>> contains_digits('sh asdjlh')False You could use the any method with .isdigit() as described in @Wallacolloo's answer , but that's slower than the simple regular expression: >>> import timeit>>> timeit.timeit("contains_digits('0798237 sh 523-123-asdjlh')", 'from __main__ import contains_digits')0.77181887626647949>>> timeit.timeit("contains_digits_any('0798237 sh 523-123-asdjlh')", 'from __main__ import contains_digits_any')1.7796030044555664 The if method is on par with the regular expression: >>> timeit.timeit("contains_digits_if('0798237 sh 523-123-asdjlh')", 'from __main__ import contains_digits_if')0.87261390686035156 But things get worse if the digits appear late in the text: >>> timeit.timeit("contains_digits('asdjlhtaheoahueoaea 11 thou')", 'from __main__ import contains_digits')1.202538013458252>>> timeit.timeit("contains_digits_any('asdjlhtaheoahueoaea 11 thou')", 'from __main__ import contains_digits_any')5.0348429679870605>>> timeit.timeit("contains_digits_if('asdjlhtaheoahueoaea 11 thou')", 'from __main__ import contains_digits_if')3.707183837890625 Timings tested on python 2.6 on Mac OS X 10.7.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11232474', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1459601/']}
jdg_375941
stackexchange
llm_judgeable_groundtruth_similarity
9845369
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 2 lists, both of which contain same number of dictionaries. Each dictionary has a unique key. There is a match for each dictionary of the first list in the second list, that is a dictionary with a unique key exists in the other list. But the other elements of such 2 dictionaries may vary. For example: list_1 = [ { 'unique_id': '001', 'key1': 'AAA', 'key2': 'BBB', 'key3': 'EEE' }, { 'unique_id': '002', 'key1': 'AAA', 'key2': 'CCC', 'key3': 'FFF' } ] list_2 = [ { 'unique_id': '001', 'key1': 'AAA', 'key2': 'DDD', 'key3': 'EEE' }, { 'unique_id': '002', 'key1': 'AAA', 'key2': 'CCC', 'key3': 'FFF' } ] I want to compare all elements of 2 matching dictionaries. If any of the elements are not equal, I want to print the none-equal elements. Would you please help? Now provide the response and nothing else.
Assuming that the dicts line up like in your example input, you can use the zip() function to get a list of associated pairs of dicts, then you can use any() to check if there is a difference: >>> list_1 = [{'unique_id':'001', 'key1':'AAA', 'key2':'BBB', 'key3':'EEE'}, {'unique_id':'002', 'key1':'AAA', 'key2':'CCC', 'key3':'FFF'}]>>> list_2 = [{'unique_id':'001', 'key1':'AAA', 'key2':'DDD', 'key3':'EEE'}, {'unique_id':'002', 'key1':'AAA', 'key2':'CCC', 'key3':'FFF'}]>>> pairs = zip(list_1, list_2)>>> any(x != y for x, y in pairs)True Or to get the differing pairs: >>> [(x, y) for x, y in pairs if x != y][({'key3': 'EEE', 'key2': 'BBB', 'key1': 'AAA', 'unique_id': '001'}, {'key3': 'EEE', 'key2': 'DDD', 'key1': 'AAA', 'unique_id': '001'})] You can even get the keys which don't match for each pair: >>> [[k for k in x if x[k] != y[k]] for x, y in pairs if x != y][['key2']] Possibly together with the associated values: >>> [[(k, x[k], y[k]) for k in x if x[k] != y[k]] for x, y in pairs if x != y][[('key2', 'BBB', 'DDD')]] NOTE: In case you're input lists are not sorted yet, you can do that easily as well: >>> from operator import itemgetter>>> list_1, list_2 = [sorted(l, key=itemgetter('unique_id')) for l in (list_1, list_2)]
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9845369', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/718762/']}
jdg_375942
stackexchange
llm_judgeable_groundtruth_similarity
6893302
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 currently busy with deferred shading in webgl and i need to decode 3 integer value's (in the range [0..256] = 256^3) to a single 32 bit float and encode it later. because this is for WebGL it has to be done without bitwise operations. precision is not important for me (But can be achieved i think). this is what i have but i think this is wrong because of the precision of the texture where i store the encoded value. float packColor(vec3 color) { return (color.r + (color.g*256.) + (color.b*256.*256.)) / (256.*256.*256.); }vec3 decodeColor(float f) { float b = floor(f * 256.0);float g = floor(f * 65536.0) - (b*256.);float r = (floor(f * 16777216.0) - (b*65536.)) - (g*256.);return vec3(r, g, b)/ 256.0;//vec3(r, g, b) / 256.0; } thanks.. Now provide the response and nothing else.
I know this is an old question, but i had the same problem, and i'll post the solution in case someone needs it in future float packColor(vec3 color) { return color.r + color.g * 256.0 + color.b * 256.0 * 256.0;}vec3 unpackColor(float f) { vec3 color; color.b = floor(f / 256.0 / 256.0); color.g = floor((f - color.b * 256.0 * 256.0) / 256.0); color.r = floor(f - color.b * 256.0 * 256.0 - color.g * 256.0); // now we have a vec3 with the 3 components in range [0..255]. Let's normalize it! return color / 255.0;} As long the float packed with packColor is not in the [0, 1] range but in the [0, 16777215] range, you shouldn't have any problem with precision. But if you normalize the float in the [0,1] range, you'll have precision problems! Note that you can't store alpha too(in this way), since highp floats are 24-bit long, and not 32 as the ones normally used.In vertex shader you can use this code without problems(default precision is highp), but in the fragment shader you must be sure to only use high precision!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6893302', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/872033/']}
jdg_375943
stackexchange
llm_judgeable_groundtruth_similarity
18194956
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 reading multi-level wild cards from AngelikaLangerGenericsFaq . I am pretty confusedabout the syntax. The document says The type Collection<Pair<String,?>> is a concrete instantiation of the generic Collection interface. It is a heterogenous collection of pairs of different types. It can contain elements of type Pair<String,Long> , Pair<String,Date> , Pair<String,Object> , Pair<String,String> , and so on and so forth. In other words, Collection<Pair<String,?>> contains a mix of pairs of different types of the form Pair<String,?> . The type Collection<? extends Pair<String,?>> is a wildcard parameterized type; it does NOT stand for a concrete parameterized type. It stands for a representative from the family of collections that are instantiations of the Collection interface, where the type argument is of the form Pair<String,?> . Compatible instantiations are Collection<Pair<String,Long>> , Collection<Pair<String,String>> , Collection<Pair<String,Object>> , or Collection<Pair<String,?>> . In other words, we do not know which instantiation of Collection it stands for. As a rule of thumb, you have to read multi-level wildcards top-down. I am confused about the following points. Can someone elaborate on these three quotes with example. I am totally lost into the syntax Document says, para-1 is the concrete instantiation of a generic type and other is not the concrete instantiation? How is that? What does it mean to read the wild-cards top down? What is the advantage of multi-level wild cards? Can someone elaborate these points. Thanks. Now provide the response and nothing else.
Can someone elaborate on these three quotes with example. I am totally lost into the syntax Well, it wouldn't make sense to write those 3 quotes again here, as I can't give a better explanation than that. Instead, I will try to answer your other questions below, then possibly you will understand the answer to this one too. If not, you can ask your query again and I'll try to elaborate a little further. Document says, para-1 is the concrete instantiation of a generic type and other is not the concrete instantiation? How is that? A concrete instantiation is the one in which all the type arguments are concrete types, and are known at compile time. For e.g., List<String> is a concrete instantiation, because String is a concrete type. Its type is known at compile time. Whereas, List<? extends Number> is not a concrete type, because ? extends Number can be any type that extends Number . So, its type is unknown at compile time. Similarly, Map<String, Integer> is a concrete instantiation of generic type Map<K, V> . In the case of multi-level type parameters, List<List<? extends Number>> , the outer List is a concrete instantiation of List<E> , because the type of elements is known to be a List at compile time, although the inner List is a wildcard instantiation, as the type of elements stored can be Integer , Double , any subclass of Number . But that paragraph is talking about the outer type only. And the outer type can only contain List type. That's why the first paragraph said, it's a heterogenous collection of Pair , because the actual type parameter of Pair can be anything, but that is certain to be Pair and nothing else. What does it mean to read the wild-cards top down? Talking in layman's term, it means from left-to-right. While determining the type of the parameterized type, you first see the outermost type parameter. Then if that type parameter is itself a parameterized type, then you move onto the type parameters of that parameterized type. So, we read the type parameters, from left-to-right. What is the advantage of multi-level wild cards? Suppose you want to create a List of List of Fruits . Now your inner List can contain any kind of of fruits. An apple is also a fruit , and a banana is also a fruit . So, you have to make sure that you get all of them. Now, since generic types are invariant, in the sense, List<Apple> is not the same as List<Fruit> , you can't add a List<Apple> if your type of list is List<List<Fruit>> . For that you would need to use wildcards like this - List<List<? extends Fruit>> , which can now take List<Apple> , List<Banana> , list of any fruit.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18194956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1377979/']}
jdg_375944
stackexchange
llm_judgeable_groundtruth_similarity
1444089
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 byte[] testKey = new byte[8]; This obviously starts with all bytes as 0. I want to go through all the bytes and increment by 1 on each iteration of the loop so eventually I go through all possibilities of the byte array. I also want to do this as FAST as possible. Yes I am trying to write a brute forcer. Update I got the unsafe method working, and it is the quickest. However, by my calculations, it is going to take 76,000,000 years to loop through doing DES encryption on each key using the .Net DESCryptoServiceProvider. 10,000 encryptions takes 1.3 seconds. Thanks for all the awesome answers to the most useless question ever! Now provide the response and nothing else.
btw; it takes a lot of processing to check 2^64 options... Well, the fastest way may be to just use an Int64 (aka long ) or UInt64 ( ulong ), and use ++ ? Do you really need the byte[] ? As a hacky alternative, how about: Array.Clear(data, 0, data.Length);while (true){ // use data here if (++data[7] == 0) if (++data[6] == 0) if (++data[5] == 0) if (++data[4] == 0) if (++data[3] == 0) if (++data[2] == 0) if (++data[1] == 0) if (++data[0] == 0) break;} The only other approach I can think of would be to use unsafe code to talk to an array as though it is an int64... messy. unsafe static void Test() { byte[] data = new byte[8]; fixed (byte* first = data) { ulong* value = (ulong*)first; do { // use data here *value = *value + 1; } while (*value != 0); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1444089', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/24108/']}
jdg_375945
stackexchange
llm_judgeable_groundtruth_similarity
46858026
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I change the default Open File... directory in Netbeans 8.2 for Java SE\ME\EE? I've edited my projectui.properties file line projectsFolder=DIRECTORY but that only works for projects. I am trying to open individual files without opening the entire project.File was found (Windows) under "C:\Users\MYNAME\AppData\Roaming\NetBeans\8.2\config\Preferences\org\netbeans\modules" Now provide the response and nothing else.
New answer I think you're looking exactly for L2 regularization. Just create a regularizer and add it in the layers: from keras.regularizers import l2#in the target layers, Dense, Conv2D, etc.:layer = Dense(units, ..., kernel_regularizer = l2(some_coefficient)) You can use bias_regularizer as well. The some_coefficient var is multiplied by the square value of the weight. PS: if val in your code is constant, it should not harm your loss. But you can still use the old answer below for val . Old answer Wrap the Keras expected function (with two parameters) into an outer function with your needs: def customLoss(layer_weights, val = 0.01): def lossFunction(y_true,y_pred): loss = mse(y_true, y_pred) loss += K.sum(val, K.abs(K.sum(K.square(layer_weights), axis=1))) return loss return lossFunctionmodel.compile(loss=customLoss(weights,0.03), optimizer =..., metrics = ...) Notice that layer_weights must come directly from the layer as a "tensor", so you can't use get_weights() , you must go with someLayer.kernel and someLayer.bias . (Or the respective var name in case of layers that use different names for their trainable parameters). The answer here shows how to deal with that if your external vars are variable with batches: How to define custom cost function that depends on input when using ImageDataGenerator in Keras?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46858026', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5565275/']}
jdg_375946
stackexchange
llm_judgeable_groundtruth_similarity
299422
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I have a basic (probably naive) question about Tits buildings. Let $G$ be a (connected) linear algebraic group over a field $k$ (I am interested in the case where $k$ is algebraically closed but I appreciate information for general $k$ also). When $G$ is a semisimple or reductive group, the (spherical Tits) building associated to $G$ is defined as the simplicial complex whose simplices correspond to parabolic subgroups of $G$ and apartments correspond to maximal tori. My question is, does this definition work for a general (connected) linear algebraic group as well? That is, does the collection of parabolic subgroups of $G$ form a building? If not, what is the main axiom that fails? Also, say when $G$ is reductive, is it correct to think of the apartment corresponding to a maximal torus $T$ as the cocharacter lattice of $T$ (or lattice of (algebraic) 1-parameter subgroups)? In other words, can one think of the total space of a building as the set of all (algebraic) 1-parameter subgroups in $G$? Now provide the response and nothing else.
Yes, the definition you make works for a general linear algebraic group $G$. The reason you haven't seen it mentioned is that the solvable radical $S$ of $G$ is contained in any of its parabolic subgroups, thus the building associated with $G$ coincides with the building associated its natural semisimple factor $G/S$. Your last paragraph is incorrect. Given a maximal torus $T$, the apartment associated with $T$ is the (finite) collection of all parabolic subgroups containing $T$ (while the set of cocharacters of $T$ is infinite) .
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/299422', 'https://mathoverflow.net', 'https://mathoverflow.net/users/21491/']}
jdg_375947
stackexchange
llm_judgeable_groundtruth_similarity
56614080
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 remove the left and right Padding of a List in SwiftUI?Every List i create has borders to the leading and trailing of a cell. What modifier should I add to remove this? Now provide the response and nothing else.
It looks like .listRowInsets doesn't work for rows in a List that is initialised with content . So this doesn't work: List(items) { item in ItemRow(item: item) .listRowInsets(EdgeInsets())} But this does: List { ForEach(items) { item in ItemRow(item: item) .listRowInsets(EdgeInsets()) }}
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/56614080', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/433073/']}
jdg_375948
stackexchange
llm_judgeable_groundtruth_similarity
24030348
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I programmatically create graphical elements (like a UIButton ) in Swift? I tried to create and add button into a view, but wasn't able to. Now provide the response and nothing else.
Here is a complete solution to add a UIButton programmatically with the targetAction . Swift 2.2 override func viewDidLoad() { super.viewDidLoad() let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50)) button.backgroundColor = .greenColor() button.setTitle("Test Button", forState: .Normal) button.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside) self.view.addSubview(button)}func buttonAction(sender: UIButton!) { print("Button tapped")} It is probably better to use NSLayoutConstraint rather than frame to correctly place the button for each iPhone screen. Updated code to Swift 3.1 : override func viewDidLoad() { super.viewDidLoad() let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50)) button.backgroundColor = .green button.setTitle("Test Button", for: .normal) button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside) self.view.addSubview(button)}func buttonAction(sender: UIButton!) { print("Button tapped")} Updated code to Swift 4.2 : override func viewDidLoad() { super.viewDidLoad() let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50)) button.backgroundColor = .green button.setTitle("Test Button", for: .normal) button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside) self.view.addSubview(button)}@objc func buttonAction(sender: UIButton!) { print("Button tapped")} The above still works if func buttonAction is declared private or internal .
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/24030348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3051809/']}
jdg_375949
stackexchange
llm_judgeable_groundtruth_similarity
16519744
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 match space chars or end of string in a text. import reuname='abc'assert re.findall('@%s\s*$' % uname, '@'+uname)assert re.findall('@%s\s*$' % uname, '@'+uname+' '+'aa')assert not re.findall('@%s\s*$' % uname, '@'+uname+'aa') The pattern is not right. How to use python? Now provide the response and nothing else.
\s*$ is incorrect: this matches "zero or more spaces followed by the end of the string", rather than "one or more spaces or the end of the string". For this situation, I would use (?:\s+|$) (inside a raw string, as others have mentioned).The (?:) part is just about separating that subexpression so that the | operator matches the correct fragment and no more than the correct fragment.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16519744', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/970319/']}
jdg_375950
stackexchange
llm_judgeable_groundtruth_similarity
11234630
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 not sure about how NSSet's anyObject work. What does it mean that "The object returned is chosen at the set’s convenience" (from the NSSet class reference ) ? Further, how can I best extract objects randomly from a NSSet? I was thinking about getting allObjects in an array and then myArray[arc4random_uniform(x)] where x is the number of objects in the array. Now provide the response and nothing else.
Usually, NSSet instances are created with a CFHash backing, so they almost always return the first object in that hash, as it is the fastest to look up. The reason it says The object returned is chosen at the set’s convenience—the selection is not guaranteed to be random. Is because you don't always know it will have a backing array. For all you know, the NSSet instance you have has a NSDictionary backing it, or some other similar data structure. So, in conclusion, if you need a random object from a NSSet , don't use -anyObject , instead use allObjects: and then shuffle that array.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11234630', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1003665/']}
jdg_375951
stackexchange
llm_judgeable_groundtruth_similarity
87839
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 read that the propagation delay of CMOS logic gate is longer than TTL; therefore they are not used where speed of processing is important. I thought computers or computer cpu is using CMOS. According to the text I read it says CMOS is not used in computers. Is that true? Now provide the response and nothing else.
First off, take that book, douse it in gasoline/petrol and burn it. Secondly, saying that something is CMOS is akin to saying that something is a circuit. There are so many variants ... Even 25 to 30 years ago CMOS ASIC flows (Gate arrays, or Sea of Gates) approaches were already way faster than any of the discrete forms of logic (AS, LS etc.). You first saw discrete logic chips that then integrated more transistors, these became known as MSI (Medium Scale integration) designs (like UARTS etc.) that may have been built on similar CMOS processes. But by the time that LSI (large scale integration) designs started to come out the processes for discrete and integrated CMOS had bifurcated and diverged. Probably at the 3 um node LSI and VLSI (Very large scale integration) design never looked back. Microprocessor processes (also CMOS) had their own design methodology and techniques. Even at the time of publishing that book had it wrong. We were in the midst of the latest 0.13um process technology, worrying about scaling effects and yield in these new radically smaller transistors. Going from 2 um to now 20 nm (arms fully waving now) which is a factor of 100X and a scaling according to Moore's law of sqrt(2) roughly translates into 14 generations of scaling /changes. Just to give to perspective, in 0.18 um process technology you can build a pretty sweet op-amp that has a unity gain bandwidth of about 1.2 GHz (0.8 ns) which is good for 14 bits SNR. This is CMOS technology that dates back to the late 1990's. If I recall correctly, you could build 2 GHz logic designs in 0.13um processes with full clock trees and fan out quite nicely.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/87839', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/16307/']}
jdg_375952
stackexchange
llm_judgeable_groundtruth_similarity
5467463
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 have multiple PyPI servers in my ~/.pypirc file so I can easily publish to different servers, depending on the project. My use-case is this, I have some internal projects that I want to publish to an internal PyPI server ( https://pypi.internal ), and I have some public projects that I want to publish to the public PyPI. This is my current attempt, but it doesn't work. I want to default to internal , and be required to add the -r pypi (to the setup.py command) if I want to publish to the public server. [distutils]index-servers = internal pypi[internal]repository: https://pypi.internalusername: brad[pypi]username: brad Where am I going wrong? Now provide the response and nothing else.
It's strange that there isn't built-in support for setting a default, but here are two options which may help you work around it. Option 1: Probably the simplest solution would be to leave your ~/.pypirc script intact and create shell aliases for your internal and public uploads. This may give you more control over customizing things for your workflow. Given this .pypirc file: [distutils]index-servers = pypi internal[pypi]repository: http://pypi.python.org/pypiusername: bradpassword: <pass>[internal]repository: http://localhost:8080username: bradpassword: <pass> Create some shell aliases (place these definitions in your shell's rcfile, e.g. ~/.bashrc ): alias ppup_internal='python setup.py bdist_egg sdist upload -r internal'alias ppup_public='python setup.py bdist_egg sdist upload' Usage: % ppup_internal...running uploadSubmitting dist/foo-0.0.0.tar.gz to http://localhost:8080Server response (200): OK Option 2: A hack: you can work around the default by patching the defaultrepository name at the top of your setup.py scripts. from distutils import configconfig.PyPIRCCommand.DEFAULT_REPOSITORY = 'internal'from setuptools import setupsetup( name='foo', ... Output: % python setup.py sdist upload ...running uploadSubmitting dist/foo-0.0.0.tar.gz to http://localhost:8080Server response (200): OK% python setup.py sdist upload -r pypi...running uploadSubmitting dist/foo-0.0.0.tar.gz to http://pypi.python.org/pypiServer response (200): OK Background: If you define the [distutils] key in .pypirc , the upload command defaults to the pypi url when the -r [repo] argument is omitted. The relevant code is in distutils.config.PyPIRCCommand : class PyPIRCCommand(Command): DEFAULT_REPOSITORY = 'http://pypi.python.org/pypi' def _read_pypirc(self): if os.path.exists(rc): self.announce('Using PyPI login from %s' % rc) repository = self.repository or self.DEFAULT_REPOSITORY realm = self.realm or self.DEFAULT_REALM The old format of .pypirc expected a [server-login] section, which was far less flexible since it only defines a single target repository. This isn't a workable option since the [pypi] section below will be unusable: [server-login]repository: http://localhost:8080username: bradpassword: <pass>[pypi]repository: http://pypi.python.org/pypiusername: bradpassword: <pass> Now by default distutils will use this target: % python setup.py sdist upload...running uploadSubmitting dist/foo-0.0.0.tar.gz to http://localhost:8080Server response (200): OK But you can't access the any other repos: it silently defaults to the [server-login] properties: % python setup.py sdist upload -r pypi...running uploadSubmitting dist/foo-0.0.0.tar.gz to http://localhost:8080Server response (200): OK
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5467463', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/253686/']}
jdg_375953
stackexchange
llm_judgeable_groundtruth_similarity
2446084
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've figured out the pattern for calculating the average distance from the centre of an n-cube; but I don't have a formula for the answer. Is there an easy way to figure this out? Average distance of points from the centre of a unit 0-cube (point) $$A_0 = 0$$ Average distance of points from the centre of a unit 1-cube (line) $$A_1 = \int_{x=-\frac{1}{2}}^{x=\frac{1}{2}}{x}\; dx = 0.250000$$ Average distance of points from the centre of a unit 2-cube (square) $$A_2 = \int_{x=-\frac{1}{2}}^{x=\frac{1}{2}}{\int_{y=-\frac{1}{2}}^{y=\frac{1}{2}}\sqrt{x^2+y^2}}\;dy \; dx \approx 0.382598$$ Average distance of points from the centre of a unit 3-cube (cube) $$A_3 = \int_{x=-\frac{1}{2}}^{x=\frac{1}{2}}{\int_{y=-\frac{1}{2}}^{y=\frac{1}{2}}\int_{z=-\frac{1}{2}}^{z=\frac{1}{2}}{\sqrt{x^2+y^2+z^2}}}\;dz\;dy \; dx \approx 0.480296$$ Average distance of points from the centre of a unit 4-cube (tesseract) $$A_4 \approx 0.560950$$ My gut instinct is that $A_n \rightarrow \infty$ as $n \rightarrow \infty$ as in my head higher dimensional cubes become more spiky and I expect the mass to become concentrated in the corners. I feel justified in saying this because the number of "corners" is $2^n$ with a potential distance of $\frac{\sqrt{n}}{2}$ If somehow it were to approach some limit, that would be cool (to me at least) Thanks in advance for any help, advice or answers Now provide the response and nothing else.
[ Note: Added values for five-dimensional hypercube. ] Consider that the space is a hypercube, so each coordinate is independently distributed. The square of that coordinate's difference from $\frac12$ has the pdf $$f(x) = \begin{cases}\frac{1}{\sqrt{x}} & 0 \leq x \leq \frac14 \\0 & \text{elsewhere}\end{cases}$$ This distribution has a mean of $\frac{1}{12}$ and a variance of $\frac{1}{180}$ . As $n$ increases without bound, the squared distance of the point from the hypercube's center is the sum of $n$ independent and identically distributed (i.i.d.) variables with that same distribution, and is thus asymptotically normally distributed (by the central limit theorem ) with mean $\frac{n}{12}$ and variance $\frac{n}{180}$ . For instance, for $n = 180$ , we would have a mean squared distance of $15$ and a variance of $1$ . That variance is small enough already that you could just take the square root of the mean squared distance and probably get a very good approximation of the mean distance. By that logic, the mean distance would be asymptotically $\sqrt{\frac{n}{12}}$ , approached from below , since the square root of a nearly normal distribution with a positive mean would be skewed that way. For $n = 1, 2, 3, 4, 5$ , this expression yields approximate mean distances of $0.289, 0.408, 0.500, 0.577, 0.645$ , which compares reasonably well with the more accurate values given in the OP ( $0.250, 0.383, 0.480, 0.561, 0.631$ ). These latter values appear to be approaching the asymptotic expression from below, as expected, but are already not too far off. ETA ( $2019$ - $02$ - $13$ , five-dimensional case added $2020$ - $04$ - $24$ ): A second-order analysis yields $\sqrt{\frac{5n-1}{60}}$ , for which the values for $n = 1, 2, 3, 4, 5$ are $0.258, 0.387, 0.483, 0.563, 0.632$ , respectively, showing even closer agreement.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2446084', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/354846/']}
jdg_375954
stackexchange
llm_judgeable_groundtruth_similarity
2933399
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, is there a way to, while waiting for a user input, count time so that after, say 30 seconds, the raw_input() function is automatically skipped? Now provide the response and nothing else.
The signal.alarm function, on which @jer's recommended solution is based, is unfortunately Unix-only. If you need a cross-platform or Windows-specific solution, you can base it on threading.Timer instead, using thread.interrupt_main to send a KeyboardInterrupt to the main thread from the timer thread. I.e.: import threadimport threadingdef raw_input_with_timeout(prompt, timeout=30.0): print(prompt, end=' ') timer = threading.Timer(timeout, thread.interrupt_main) astring = None try: timer.start() astring = input(prompt) except KeyboardInterrupt: pass timer.cancel() return astring this will return None whether the 30 seconds time out or the user explicitly decides to hit control-C to give up on inputting anything, but it seems OK to treat the two cases in the same way (if you need to distinguish, you could use for the timer a function of your own that, before interrupting the main thread, records somewhere the fact that a timeout has happened, and in your handler for KeyboardInterrupt access that "somewhere" to discriminate which of the two cases occurred). Edit : I could have sworn this was working but I must have been wrong -- the code above omits the obviously-needed timer.start() , and even with it I can't make it work any more. select.select would be the obvious other thing to try but it won't work on a "normal file" (including stdin) in Windows -- in Unix it works on all files, in Windows, only on sockets. So I don't know how to do a cross-platform "raw input with timeout". A windows-specific one can be constructed with a tight loop polling msvcrt.kbhit , performing a msvcrt.getche (and checking if it's a return to indicate the output's done, in which case it breaks out of the loop, otherwise accumulates and keeps waiting) and checking the time to time out if needed. I cannot test because I have no Windows machine (they're all Macs and Linux ones), but here the untested code I would suggest: import msvcrtimport timedef raw_input_with_timeout(prompt, timeout=30.0): print(prompt, end=' ') finishat = time.time() + timeout result = [] while True: if msvcrt.kbhit(): result.append(msvcrt.getche()) if result[-1] == '\r': # or \n, whatever Win returns;-) return ''.join(result) time.sleep(0.1) # just to yield to other processes/threads else: if time.time() > finishat: return None The OP in a comment says he does not want to return None upon timeout, but what's the alternative? Raising an exception? Returning a different default value? Whatever alternative he wants he can clearly put it in place of my return None ;-). If you don't want to time out just because the user is typing slowly (as opposed to, not typing at all!-), you could recompute finishat after every successful character input.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2933399', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/341683/']}
jdg_375955
stackexchange
llm_judgeable_groundtruth_similarity
20494132
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 dump a YUV420 data into the AVFrame structure of FFMPEG. From the below link: http://ffmpeg.org/doxygen/trunk/structAVFrame.html , i can derive that i need to put my data into data[AV_NUM_DATA_POINTERS] using linesize [AV_NUM_DATA_POINTERS]. The YUV data i'm trying to dump is YUV420 and the picture size is 416x240. So how do i dump/map this yuv data to AVFrame structures variable? Iknow that linesize represents the stride i.e. i suppose the width of my picture, I have tried with some combinations but do not get the output.I kindly request you to help me map the buffer. Thanks in advance. Now provide the response and nothing else.
AVFrame can be interpreted as an AVPicture to fill the data and linesize fields. The easiest way to fill these field is to the use the avpicture_fill function. To fill in the AVFrame's Y U and V buffers, it depends on your input data and what you want to do with the frame (do you want to write into the AVFrame and erase the initial data? or keep a copy). If the buffer is large enough (at least linesize[0] * height for Y data, linesize[1 or 2] * height/2 for U/V data), you can directly use input buffers: // Initialize the AVFrameAVFrame* frame = avcodec_alloc_frame();frame->width = width;frame->height = height;frame->format = AV_PIX_FMT_YUV420P;// Initialize frame->linesizeavpicture_fill((AVPicture*)frame, NULL, frame->format, frame->width, frame->height);// Set frame->data pointers manuallyframe->data[0] = inputBufferY;frame->data[1] = inputBufferU;frame->data[2] = inputBufferV;// Or if your Y, U, V buffers are contiguous and have the correct size, simply use:// avpicture_fill((AVPicture*)frame, inputBufferYUV, frame->format, frame->width, frame->height); If you want/need to manipulate a copy of input data, you need to compute the needed buffer size, and copy input data in it. // Initialize the AVFrameAVFrame* frame = avcodec_alloc_frame();frame->width = width;frame->height = height;frame->format = AV_PIX_FMT_YUV420P;// Allocate a buffer large enough for all dataint size = avpicture_get_size(frame->format, frame->width, frame->height);uint8_t* buffer = (uint8_t*)av_malloc(size);// Initialize frame->linesize and frame->data pointersavpicture_fill((AVPicture*)frame, buffer, frame->format, frame->width, frame->height);// Copy data from the 3 input buffersmemcpy(frame->data[0], inputBufferY, frame->linesize[0] * frame->height);memcpy(frame->data[1], inputBufferU, frame->linesize[1] * frame->height / 2);memcpy(frame->data[2], inputBufferV, frame->linesize[2] * frame->height / 2); Once you are done with the AVFrame, do not forget to free it with av_frame_free (and any buffer allocated by av_malloc ).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20494132', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2041850/']}
jdg_375956
stackexchange
llm_judgeable_groundtruth_similarity
8498738
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any way to do this? E.g., if a user starts the app with no internet connection, no remote scripts can be loaded, and the application basically can't run and I display a "No internet" page. But if the user gets internet later and the application is still running, is there any way to just "restart" ? Now provide the response and nothing else.
how about - document.location = "index.html" PhoneGap applications are just like an embedded website - you should be able to go to any hyperlink you wish (mind the whitelists). Of course, if you also want to detect when it's again online, you should use the PhoneGap Network API to bind to those online/offline events. In general thought, have you ever thought of using the HTML5 manifest functionality to actually let your local PhoneGap app cache those remote scripts? That way your app could still run, even when offline (except if it needs remote data to "do your thing")... Hope this helps!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8498738', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/994658/']}
jdg_375957
stackexchange
llm_judgeable_groundtruth_similarity
39481176
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Got this weird issue after upgrading to iOS 10. The BebasNeue font has been rendered weirdly. Please have a look at the 2 screenshots below. Smells like a webkit bug, happened with Chrome on iOS 10 too. Anyone is having the same problem? Any workaround? iOS 9 iOS 10 Now provide the response and nothing else.
It took 12 hours to figure this out, but this is what fixed it -- changing the ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES build setting like this: App target (main target) -- set to NO (mine was YES) Watch target -- set to YES (mine was NO) Watch App Extension target -- set to NO (mine was YES) Edit : I figured this out by creating a new, empty watch project in xcode 8, and cross-referencing the differences between build-settings in the new xcode 8 template project, and my crusty old ancient project. The settings above are what the xcode 8 template project has.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39481176', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1974153/']}
jdg_375958
stackexchange
llm_judgeable_groundtruth_similarity
1885084
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: Is $Z_{11}$ same as $\frac{Z}{11Z}$. I have been said in class that latter contains equivalence classes, but in assignment i have seen $Z_{11}$. Can someone clarify difference between two ? Thanks Now provide the response and nothing else.
Hint . One may set$$f(s):=\int_0^1 \frac{x^s-1}{(x+1)\log{x}}\: \text{d}x, \quad s>-1, \tag1$$ then one is allowed to differentiate under the integral sign, getting$$f'(s)=\int_{0}^{1}\frac{x^s}{x+1}\:dx=\frac12\psi\left(\frac{s}2+\frac12\right)-\frac12\psi\left(\frac{s}2+1\right), \quad s>-1, \tag2$$where we have used a standard integral representation of the digamma function. One may recall that $\psi:=\Gamma'/\Gamma$, then integrating $(2)$, observing that $f(0)=0$, one gets $$f(s)=\int_0^1 \frac{x^s-1}{(x+1)\log{x}}\: \text{d}x=\log \left(\frac{\sqrt{\pi}\cdot\Gamma\left(\frac{s}2+1\right)}{\Gamma\left(\frac{s}2+\frac12\right)}\right), \quad s>-1, \tag3$$ from which one deduces the value of the initial integral by putting $s:=1$, recalling that $$\Gamma\left(\frac12+1\right)=\frac12\Gamma\left(\frac12\right)=\frac{\sqrt{\pi}}2.$$ Edit. The result $(3)$ is more general than the given one.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1885084', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/301858/']}
jdg_375959
stackexchange
llm_judgeable_groundtruth_similarity
21862727
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 load some text files to Redshift. They are tab delimited, except for after the final row value. That's causing a delimiter not found error. I only see a way to set the field delimiter in the COPY statement, not a way to set a row delimiter. Any ideas that don't involve processing all my files to add a tab to the end of each row? Thanks Now provide the response and nothing else.
I don't think the problem is with missing <tab> at the end of lines. Are you sure that ALL lines have correct number of fields? Run the query: select le.starttime, d.query, d.line_number, d.colname, d.value,le.raw_line, le.err_reason from stl_loaderror_detail d, stl_load_errors lewhere d.query = le.queryorder by le.starttime desclimit 100 to get the full error report. It will show the filename with errors, incorrect line number, and error details. This will help to find where the problem lies.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21862727', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3187747/']}
jdg_375960
stackexchange
llm_judgeable_groundtruth_similarity
29971110
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to update my conditions table with the radio button's value on and off Here is the view = form_tag('/admin/save',:action => 'update') do = radio_button_tag("#{cols}_#{id}",1,checked = eval(check), options = {}) = radio_button_tag("#{cols}_#{id}",0,checked = eval(negcheck), options = {}) = submit_tag Here is the controller def updateCondition params.each do |keys , value| key ="#{keys}" condition = key.split("_")[0] hospitalid =key.split("_")[1] if condition == "utf8" || condition == "authenticity" || condition == "commit" next end Condition.find(hospitalid).update(:"#{condition}" => params["#{condition}_#{hospitalid}"]) end render nothing: true end Params are : {"utf8"=>"✓", "authenticity_token"=>"", "abc_10000"=>"1", "commit"=>"Save changes", "def_10000"=>"1", } Here is my question : 1) Why params is not showing all my radio button values ?2) Any way to handle utf8, authentication_token, commit other than if statement ? Now provide the response and nothing else.
Ok, let's build a simple math example. Building an AST is totally overkill for such a task but it's a nice way to show the principle. I'll do it in C# but the Java version would be very similar. The grammar First, let's write a very basic math grammar to work with: grammar Math;compileUnit : expr EOF ;expr : '(' expr ')' # parensExpr | op=('+'|'-') expr # unaryExpr | left=expr op=('*'|'/') right=expr # infixExpr | left=expr op=('+'|'-') right=expr # infixExpr | func=ID '(' expr ')' # funcExpr | value=NUM # numberExpr ;OP_ADD: '+';OP_SUB: '-';OP_MUL: '*';OP_DIV: '/';NUM : [0-9]+ ('.' [0-9]+)? ([eE] [+-]? [0-9]+)?;ID : [a-zA-Z]+;WS : [ \t\r\n] -> channel(HIDDEN); Pretty basic stuff, we have a single expr rule that handles everything (precedence rules etc). The AST nodes Then, let's define some AST nodes we'll use. These are totally custom and you can define them in the way you want to. Here are the nodes we'll be using for this example: internal abstract class ExpressionNode{}internal abstract class InfixExpressionNode : ExpressionNode{ public ExpressionNode Left { get; set; } public ExpressionNode Right { get; set; }}internal class AdditionNode : InfixExpressionNode{}internal class SubtractionNode : InfixExpressionNode{}internal class MultiplicationNode : InfixExpressionNode{}internal class DivisionNode : InfixExpressionNode{}internal class NegateNode : ExpressionNode{ public ExpressionNode InnerNode { get; set; }}internal class FunctionNode : ExpressionNode{ public Func<double, double> Function { get; set; } public ExpressionNode Argument { get; set; }}internal class NumberNode : ExpressionNode{ public double Value { get; set; }} Converting a CST to an AST ANTLR generated the CST nodes for us (the MathParser.*Context classes). We now have to convert these to AST nodes. This is easily done with a visitor, and ANTLR provides us with a MathBaseVisitor<T> class, so let's work with that. internal class BuildAstVisitor : MathBaseVisitor<ExpressionNode>{ public override ExpressionNode VisitCompileUnit(MathParser.CompileUnitContext context) { return Visit(context.expr()); } public override ExpressionNode VisitNumberExpr(MathParser.NumberExprContext context) { return new NumberNode { Value = double.Parse(context.value.Text, NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent) }; } public override ExpressionNode VisitParensExpr(MathParser.ParensExprContext context) { return Visit(context.expr()); } public override ExpressionNode VisitInfixExpr(MathParser.InfixExprContext context) { InfixExpressionNode node; switch (context.op.Type) { case MathLexer.OP_ADD: node = new AdditionNode(); break; case MathLexer.OP_SUB: node = new SubtractionNode(); break; case MathLexer.OP_MUL: node = new MultiplicationNode(); break; case MathLexer.OP_DIV: node = new DivisionNode(); break; default: throw new NotSupportedException(); } node.Left = Visit(context.left); node.Right = Visit(context.right); return node; } public override ExpressionNode VisitUnaryExpr(MathParser.UnaryExprContext context) { switch (context.op.Type) { case MathLexer.OP_ADD: return Visit(context.expr()); case MathLexer.OP_SUB: return new NegateNode { InnerNode = Visit(context.expr()) }; default: throw new NotSupportedException(); } } public override ExpressionNode VisitFuncExpr(MathParser.FuncExprContext context) { var functionName = context.func.Text; var func = typeof(Math) .GetMethods(BindingFlags.Public | BindingFlags.Static) .Where(m => m.ReturnType == typeof(double)) .Where(m => m.GetParameters().Select(p => p.ParameterType).SequenceEqual(new[] { typeof(double) })) .FirstOrDefault(m => m.Name.Equals(functionName, StringComparison.OrdinalIgnoreCase)); if (func == null) throw new NotSupportedException(string.Format("Function {0} is not supported", functionName)); return new FunctionNode { Function = (Func<double, double>)func.CreateDelegate(typeof(Func<double, double>)), Argument = Visit(context.expr()) }; }} As you can see, it's just a matter of creating an AST node out of a CST node by using a visitor. The code should be pretty self-explanatory (well, maybe except for the VisitFuncExpr stuff, but it's just a quick way to wire up a delegate to a suitable method of the System.Math class). And here you have the AST building stuff. That's all that's needed. Just extract the relevant information from the CST and keep it in the AST. The AST visitor Now, let's play a bit with the AST. We'll have to build an AST visitor base class to traverse it. Let's just do something similar to the AbstractParseTreeVisitor<T> provided by ANTLR. internal abstract class AstVisitor<T>{ public abstract T Visit(AdditionNode node); public abstract T Visit(SubtractionNode node); public abstract T Visit(MultiplicationNode node); public abstract T Visit(DivisionNode node); public abstract T Visit(NegateNode node); public abstract T Visit(FunctionNode node); public abstract T Visit(NumberNode node); public T Visit(ExpressionNode node) { return Visit((dynamic)node); }} Here, I took advantage of C#'s dynamic keyword to perform a double-dispatch in one line of code. In Java, you'll have to do the wiring yourself with a sequence of if statements like these: if (node is AdditionNode) { return Visit((AdditionNode)node);} else if (node is SubtractionNode) { return Visit((SubtractionNode)node);} else if ... But I just went for the shortcut for this example. Work with the AST So, what can we do with a math expression tree? Evaluate it, of course! Let's implement an expression evaluator: internal class EvaluateExpressionVisitor : AstVisitor<double>{ public override double Visit(AdditionNode node) { return Visit(node.Left) + Visit(node.Right); } public override double Visit(SubtractionNode node) { return Visit(node.Left) - Visit(node.Right); } public override double Visit(MultiplicationNode node) { return Visit(node.Left) * Visit(node.Right); } public override double Visit(DivisionNode node) { return Visit(node.Left) / Visit(node.Right); } public override double Visit(NegateNode node) { return -Visit(node.InnerNode); } public override double Visit(FunctionNode node) { return node.Function(Visit(node.Argument)); } public override double Visit(NumberNode node) { return node.Value; }} Pretty simple once we have an AST, isn't it? Putting it all together Last but not least, we have to actually write the main program: internal class Program{ private static void Main() { while (true) { Console.Write("> "); var exprText = Console.ReadLine(); if (string.IsNullOrWhiteSpace(exprText)) break; var inputStream = new AntlrInputStream(new StringReader(exprText)); var lexer = new MathLexer(inputStream); var tokenStream = new CommonTokenStream(lexer); var parser = new MathParser(tokenStream); try { var cst = parser.compileUnit(); var ast = new BuildAstVisitor().VisitCompileUnit(cst); var value = new EvaluateExpressionVisitor().Visit(ast); Console.WriteLine("= {0}", value); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine(); } }} And now we can finally play with it:
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/29971110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4851191/']}
jdg_375961
stackexchange
llm_judgeable_groundtruth_similarity
3506208
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here are two pages, test.php and testserver.php. test.php <script src="scripts/jq.js" type="text/javascript"></script><script> $(function() { $.ajax({url:"testserver.php", success:function() { alert("Success"); }, error:function() { alert("Error"); }, dataType:"json", type:"get" } )})</script> testserver.php <?php$arr = array("element1", "element2", array("element31","element32"));$arr['name'] = "response";echo json_encode($arr);?> Now my problem: when both of these files are on the same server (either localhost or web server), it works and alert("Success") is called; If it is on different servers, meaning testserver.php on web server and test.php on localhost, its not working, and alert("Error") is executing. Even if the URL inside AJAX is changed to http://domain.example/path/to/file/testserver.php Now provide the response and nothing else.
Use JSONP . jQuery: $.ajax({ url:"testserver.php", dataType: 'jsonp', // Notice! JSONP <-- P (lowercase) success:function(json){ // do stuff with json (in this case an array) alert("Success"); }, error:function(){ alert("Error"); } }); PHP: <?php$arr = array("element1","element2",array("element31","element32"));$arr['name'] = "response";echo $_GET['callback']."(".json_encode($arr).");";?> The echo might be wrong, it's been a while since I've used php. In any case you need to output callbackName('jsonString') notice the quotes. jQuery will pass it's own callback name, so you need to get that from the GET params. And as Stefan Kendall posted, $.getJSON() is a shorthand method, but then you need to append 'callback=?' to the url as GET parameter (yes, value is ?, jQuery replaces this with its own generated callback method).
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/3506208', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/423251/']}
jdg_375962
stackexchange
llm_judgeable_groundtruth_similarity
37470
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In the van der Waals equation of state $$\left[p + a\left(\frac{n}{V}\right)^2\right](V-nb) = nRT$$ the coefficient $b$ is supposed to represent the volume occupied by the particles. Why then is it equal to four times the volume and not simply the volume? Now provide the response and nothing else.
While most everything the previous answer states is correct, I would point out that taking four times the volume of a single particle has nothing to do with experiment and arises mathematically. In deriving the VDW equation, the particles are still assumed to be hard spheres, but this assumption is corrected for with the parameter $a$ . The hard sphere approximation forbids that two particles penetrate each other's radii. Thus, we find that two spheres in closest contact are surrounded by a sphere of radius $2r$ (or the diameter of one of the original spheres). (source: nyu.edu ) Thus, the volume excluded by the particles from the larger sphere surrounding the two spheres shown is $$b' = \frac{4}{3} \pi d^3 = 8 \cdot \frac{4}{3} \pi r^3$$ Thus, the excluded volume per particle $b$ is $b'/2$ or, $$b=4 \cdot \frac{4}{3}\pi r^3$$ which, as you point out, is four times the volume of a single particle. The interesting thing about this is that it does not represent the actual value of $b$ for any given atom, but represents the upper bound of $b$ for any given atom. What I mean by that is, $b$ could very well be correct by calculating four times the volume, but often experiment will show that it less than the calculated value of $b$ because atoms are not hard spheres. For instance, using helium, which is the closest we'll get to a hard sphere: $$b_{\ce{He},\mathrm{calc}} = 4 \cdot \frac{4}{3} \pi (140\ \mathrm{pm})^3 \cdot N_\mathrm{A} = 0.02767\ \mathrm{L\ mol^{-1}}$$ while, $$b_{\ce{He},\mathrm{exp}} = 0.0238\ \mathrm{L\ mol^{-1}}$$ So, the experimental value of $b$ is indeed smaller, but the calculated value gives a rough idea.
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/37470', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/21004/']}
jdg_375963
stackexchange
llm_judgeable_groundtruth_similarity
304886
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was discussing unit/integration testing with a colleague, and he made an interesting case against writing unit tests. I'm a big unit test (JUnit primarily) proponent, but am interested to hear others' takes, as he made some interesting points. To sum up his points: When major code changes occur (new set of POJOs, major applicationrefactoring, etc.), unit tests tend to be commented out rather thanreworked. Time is better spent on integration tests covering use cases,which make the smaller-scoped tests less/not-at-all important. Thoughts on this? I'm still pro-unit test (as I consistently see it producing improved code), although integration tests sound at least as valuable. Now provide the response and nothing else.
I tend to side with your friend because all too often, unit tests are testing the wrong things . Unit tests are not inherently bad. But they often test the implementation details rather than the input/output flow. You end up with completely pointless tests when this happens. My own rule is that a good unit test tells you that you just broke something; a bad unit test merely tells you that you just changed something. An example off the top of my head is one test that got tucked into WordPress a few years back. The functionality being tested revolved around filters that called one another, and the tests were verifying that callbacks would then get called in the correct order. But instead of (a) running the chain to verify that callbacks get called in the expected order, the tests focused on (b) reading some internal state that arguably shouldn't have been exposed to begin with. Change the internals and (b) turns red; whereas (a) only turns red if changes to the internals break the expected result while doing so. (b) was clearly a pointless test in my view. If you have a class that exposes a few methods to the outside world, the correct thing to test in my view are the latter methods only . If you test the internal logic as well, you may end up exposing the internal logic to the outside world, using convoluted testing methods, or with a litany of unit tests that invariably break whenever you want to change anything. With all that said, I'd be surprised if your friend is as critical about unit tests per se as you seem to suggest. Rather I'd gather he's pragmatic. That is, he observed that the unit tests that get written are mostly pointless in practice. Quoting: "unit tests tend to be commented out rather than reworked". To me there's an implicit message in there - if they tend to need reworking it is because they tend to suck. Assuming so, the second proposition follows: developers would waste less time writing code that is harder to get wrong - i.e. integration tests. As such it's not about one being better or worse. It's just that one is a lot easier to get wrong, and indeed very often wrong in practice.
{}
{'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/304886', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/150047/']}
jdg_375964
stackexchange
llm_judgeable_groundtruth_similarity
514914
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $D_N$ be the $N$th Dirichlet kernel, $D_N = \sum_{k = -N}^N w^k$, where $w = e^{ix}$. Define the Fejer kernel to be $F_N = \frac{1}{N}\sum_{k = 0}^{N-1}D_k$. Then $$F_N = \frac{1}{N}\frac{\sin^2(N x/2)}{\sin^2(x/2)}$$. So far I have $D_k = \frac{w^{k+1} - w^{-k}}{w-1}$, and so$$\begin{align*}F_N &= \frac{1}{N}\sum_{k=0}^{N-1} D_k \\&= \frac{1}{N(w-1)}\sum_{k=0}^{N-1} (w^{k+1} - w^{-k}) \\&= \frac{1}{N(w-1)}\left ( w\sum_{k=0}^{N-1} w^k - \sum_{k=-N+1}^0 w^k \right ) \\&= \frac{1}{N(w-1)}\left ( \frac{w(w^N - 1)}{w-1} - \frac{1-w^{-N + 1}}{w-1} \right ) \\&= \frac{1}{N(w-1)^2}\left ( w^{N+1} +w^{-N + 1} - (w + 1) \right )\end{align*}$$ Now provide the response and nothing else.
We can prove the equality for the Fejér kernel in the following way. Using the formula for the geometric progression and the fact that $e^{i\theta}-e^{-i\theta}=2i\sin\theta$ for each $\theta\in\mathbb R$,\begin{align*} D_k(x) &=e^{-ikx}\sum_{s=0}^{2k}e^{isx}\\ &=e^{-ikx}\frac{1-e^{ix(2k+1)}}{1-e^{ix}}\\ &=\frac{e^{-ix(k+1/2)}-e^{ix(k+1/2)}}{e^{-ix/2}-e^{ix/2}}\\ &=\frac{\sin(x(k+1/2))}{\sin(x/2)}.\end{align*}Using the product-to-sum identity and the power reduction formula,\begin{align*} F_n(x) &=\frac1{n\sin(x/2)}\sum_{k=0}^{n-1}\sin(x(k+1/2))\\ &=\frac1{2n\sin^2(x/2)}\sum_{k=0}^{n-1}2\sin(x(k+1/2))\sin(x/2)\\ &=\frac1{2n\sin^2(x/2)}\sum_{k=0}^{n-1}[\cos(kx)-\cos((k+1)x)]\\ &=\frac{1-\cos (nx)}{2n\sin^2(x/2)}\\ &=\frac1n\biggl[\frac{\sin(nx/2)}{\sin(x/2)}\biggr]^2.\end{align*}The trigonometric identities can be found here .
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/514914', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/26327/']}
jdg_375965
stackexchange
llm_judgeable_groundtruth_similarity
10747119
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 trim any spaces at the start of the text box and trim any spaces at the end of the textbox. So I have found this code on a website which is suppose to remove spaces at the start, end and multiple spaces in between: function trim(s) { s = s.replace(/(^\s*)|(\s*$)/gi,""); s = s.replace(/[ ]{2,}/gi," "); s = s.replace(/\n /,"\n"); return s;} My problem is though that first of all which one of the 3 lines of code is the one where it trims spaces in the middle because I don't need that one. But the main question is how do I get the textbox to access this function? I tried using onkeypress but this hasn't worked, below is what I have tried: <p>Search: <input type="text" name="questioncontent" onkeypress="return trim(s)" /></p> So what I want is that for example if this phrase is entered in textbox ' My Name is Pete '. Then it should remove the spaces at the start and end so it reads 'My Name is Pete'. But how do I get this to work? UPDATE: Found out that trim() is jQuery, so does anyone a javascript equivalent for this which can be hand coded to remove spaces at start and end of textbox? Now provide the response and nothing else.
You need to change your HTML : <p>Search: <input type="text" name="questioncontent" onchange="return trim(this)" /></p> Pass the input element as a parameter to trim and use onchange instead of onkeypress. Then trim needs to be : function trim (el) { el.value = el.value. replace (/(^\s*)|(\s*$)/gi, ""). // removes leading and trailing spaces replace (/[ ]{2,}/gi," "). // replaces multiple spaces with one space replace (/\n +/,"\n"); // Removes spaces after newlines return;} This modifies the value of the input element, removing leading and trailing spaces, replacing multiple spaces with a single space, and removing any spaces after newline characters. JSfiddle : http://jsfiddle.net/jstoolsmith/ZNQQm
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10747119', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1394925/']}
jdg_375966
stackexchange
llm_judgeable_groundtruth_similarity
44887576
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Currently, I am working with Python 3.5 GUI development using tkinter module. I want to be able to drag an image from one place to another within the application. Does tkinter support drag and drop within an application, and if so, how do you do it? from tkinter import *root = Tk()root.geometry("640x480")canvas = Canvas(root, height=480, width=640, bg="white")frame = Frame(root, height=480, width=640, bg="white")frame.propagate(0)image = PhotoImage(file="C:/Users/Shivam/Pictures/Paint/Body.png")label = Label(canvas, image=image)label.pack()label_2 = Label(frame, text="Drop Here !")label_2.pack()label_2.place(x=200, y=225, anchor=CENTER)canvas.pack(side=LEFT)frame.pack()root.mainloop() Now provide the response and nothing else.
Tkinter doesn't have any direct support for drag and drop within an application. However, drag and drop requires not much more than making suitable bindings for a button click ( <ButtonPress-1> ), the mouse moving while the button is clicked ( <B1-Motion> ), and when the button is released ( <ButtonRelease-1> ). Here is a very simplestic example which is designed to work with your code. First, we'll create a class that can manage the dragging and dropping. It's easier to do this as a class rather than a collection of global functions. class DragManager(): def add_dragable(self, widget): widget.bind("<ButtonPress-1>", self.on_start) widget.bind("<B1-Motion>", self.on_drag) widget.bind("<ButtonRelease-1>", self.on_drop) widget.configure(cursor="hand1") def on_start(self, event): # you could use this method to create a floating window # that represents what is being dragged. pass def on_drag(self, event): # you could use this method to move a floating window that # represents what you're dragging pass def on_drop(self, event): # find the widget under the cursor x,y = event.widget.winfo_pointerxy() target = event.widget.winfo_containing(x,y) try: target.configure(image=event.widget.cget("image")) except: pass To use it, all you need to do is call the add_draggable method, giving it the widget(s) you wish to drag. For example: label = Label(canvas, image=image)...dnd = DragManager()dnd.add_dragable(label)...root.mainloop() That's all it takes for the basic framework. It's up to you to create a floating draggable window, and to perhaps highlight the item(s) that can be dropped on. Other implementations For another implementation of the same concept, see https://github.com/python/cpython/blob/master/Lib/tkinter/dnd.py
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44887576', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_375967
stackexchange
llm_judgeable_groundtruth_similarity
256410
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 $C/S$ be a semistable curve, and $G$ a finite group acting faithfully on $C/S$, whose order is invertible on $S$. Let $P\in C$ be a geometric point with image $s\in S$, such that $P$ is a node in $C_s$. For short, let $A := \widehat{\mathcal{O}}_s$, and $R := \widehat{\mathcal{O}}_P$. Then, at $P$, we may fix "local coordinates" - ie, we fix an identification$$R = A[[X,Y]]/(XY-a)$$where $a\in m_A$ (the maximal ideal of $A$). Let $x,y$ be the images of $X,Y$, then relative to these coordinates, any $A$-linear automorphism $\sigma$ which fixes the ideals $(x),(y)\subset R$ (which are called the "branches" of the node) is determined uniquely by a pair $(u,\gamma)\in R^\times\times A^\times$ with $\gamma a = a$, where$$\sigma(x) = ux,\qquad \sigma(y) = \gamma u^{-1}y$$Now suppose that the stabilizer $G_P\le G$ of $P$ is cyclic and fixes the branches, so any $g\in G_P$ is described by $(u,\gamma)$ as above. On the bottom of page 44 of "Champs de Hurwitz" , the author deduces that "this description, together with theoreme 90, allows us to assume that the action of $G_P$ is given by a pair of opposite characters $\chi,\chi^{-1}$ of order $e > 1$, via:$$\sigma(x) = \chi(\sigma)x,\qquad \sigma(y) = \chi(\sigma)^{-1}y$$" It is not at all obvious to me why this should be true, or even how "theoreme 90" (presumably Hilbert's thm 90) would come in. EDIT: I should add that the action of $G_P$ on the cotangent space of $C$ at $P$ has determinant 1. Now provide the response and nothing else.
Such identities are often reduced to the Chu--Vandermonde's identity $\sum_{i+j=\ell} \binom{x}i\binom{y}j=\binom{x+y}\ell$ by using reflection formulae $\binom{x}k=\binom{x}{x-k}$, $\binom{x}k=(-1)^k\binom{k-x-1}k$. In your case you may write$$\sum_{k=m}^p(-1)^{k+m}\binom{k}{m}\binom{n+p+1}{n+k+1}=\sum_{k=m}^p \binom{-m-1}{k-m}\binom{n+p+1}{p-k}=\binom{n+p-m}{p-m}$$as you need, so it is Chu--Vandermonde for $x=-m-1$, $y=n+p+1$, $\ell=p-m$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/256410', 'https://mathoverflow.net', 'https://mathoverflow.net/users/88840/']}
jdg_375968
stackexchange
llm_judgeable_groundtruth_similarity
38646040
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been attempting to fit this data by a Linear Regression, following a tutorial on bigdataexaminer. Everything was working fine up until this point. I imported LinearRegression from sklearn, and printed the number of coefficients just fine. This was the code before I attempted to grab the coefficients from the console. import numpy as npimport pandas as pdimport scipy.stats as statsimport matplotlib.pyplot as pltimport sklearnfrom sklearn.datasets import load_bostonfrom sklearn.linear_model import LinearRegressionboston = load_boston()bos = pd.DataFrame(boston.data)bos.columns = boston.feature_namesbos['PRICE'] = boston.targetX = bos.drop('PRICE', axis = 1)lm = LinearRegression() After I had all this set up I ran the following command, and it returned the proper output: In [68]: print('Number of coefficients:', len(lm.coef_)Number of coefficients: 13 However, now if I ever try to print this same line again, or use 'lm.coef_', it tells me coef_ isn't an attribute of LinearRegression, right after I JUST used it successfully, and I didn't touch any of the code before I tried it again. In [70]: print('Number of coefficients:', len(lm.coef_))Traceback (most recent call last): File "<ipython-input-70-5ad192630df3>", line 1, in <module>print('Number of coefficients:', len(lm.coef_))AttributeError: 'LinearRegression' object has no attribute 'coef_' Now provide the response and nothing else.
The coef_ attribute is created when the fit() method is called. Before that, it will be undefined: >>> import numpy as np>>> import pandas as pd>>> from sklearn.datasets import load_boston>>> from sklearn.linear_model import LinearRegression>>> boston = load_boston()>>> lm = LinearRegression()>>> lm.coef_---------------------------------------------------------------------------AttributeError Traceback (most recent call last)<ipython-input-22-975676802622> in <module>() 7 8 lm = LinearRegression()----> 9 lm.coef_AttributeError: 'LinearRegression' object has no attribute 'coef_' If we call fit() , the coefficients will be defined: >>> lm.fit(boston.data, boston.target)>>> lm.coef_array([ -1.07170557e-01, 4.63952195e-02, 2.08602395e-02, 2.68856140e+00, -1.77957587e+01, 3.80475246e+00, 7.51061703e-04, -1.47575880e+00, 3.05655038e-01, -1.23293463e-02, -9.53463555e-01, 9.39251272e-03, -5.25466633e-01]) My guess is that somehow you forgot to call fit() when you ran the problematic line.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38646040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6626436/']}
jdg_375969
stackexchange
llm_judgeable_groundtruth_similarity
373780
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: According to Stoke's law, the retarding force acting on a body falling in a viscous medium is given by $$F=kηrv$$ where $k=6π$ . As far as I know, the $6π$ factor is determined experimentally. In that case, how is writing exactly $6π$ correct since we obviously cannot experimentally determine the value of the constant with infinite precision? Now provide the response and nothing else.
It is not determined experimentally, it is an analytical result. It is verified experimentally. As @Mick described it is possible to derive the velocity and pressure field of a flow around a sphere in the Stokes flow limit for small Reynolds numbers from the Navier-Stokes equations if the flow is further assumed to be incompressible and irrotational. Once the flow field is determined, the stress at the surface of the sphere can be evaluated: $$\left.\boldsymbol{\sigma}\right|_w = \left[p\boldsymbol{I}-\mu\boldsymbol{\nabla}\boldsymbol{v}\right]_w$$ from which follows the drag force as: $$\left.\boldsymbol{F}\right|_w = \int_\boldsymbol{A}\left.\boldsymbol{\sigma}\right|_w\cdot d\boldsymbol{A}$$ From this it follows that the normal contribution of the drag force (form drag) is $2\pi\mu R u_\infty$ , while the tangential contribution (friction drag) of the drag force is $4\pi\mu R u_\infty$ , where $u_\infty$ is the free-stream velocity measured far from the sphere. The combined effect of these contributions is evaluated as $6\pi\mu R u_\infty$ or the total drag force. This result is also found by evaluating the kinetic force by equating the rate of doing work on the sphere (force times velocity) to the rate of viscous dissipation within the fluid. This shows nicely there are often many roads to the same answer in science and engineering. For details i suggest you look at the Chapter 2.6 and 4.2 from Transport Phenomena by Bird, Steward & Lightfoot.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/373780', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/157583/']}
jdg_375970
stackexchange
llm_judgeable_groundtruth_similarity
34341656
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 code fragment is part of a method that gets a directory listing, calls an extract method on each file and serializes the resulting drug object to xml. try(Stream<Path> paths = Files.list(infoDir)) { paths .parallel() .map(this::extract) .forEachOrdered(drug -> { try { marshaller.write(drug); } catch (JAXBException ex) { ex.printStackTrace(); } });} Here is the exact same code doing the exact same thing but using a plain .list() call to get the directory listing and calling .parallelStream() on the resulting list. Arrays.asList(infoDir.toFile().list()) .parallelStream() .map(f -> infoDir.resolve(f)) .map(this::extract) .forEachOrdered(drug -> { try { marshaller.write(drug); } catch (JAXBException ex) { ex.printStackTrace(); }}); My machine is a quad core MacBook Pro, Java v 1.8.0_60 (build 1.8.0_60-b27). I am processing ~ 7000 files. The averages of 3 runs: First version:With .parallel() : 20 seconds. Without .parallel() : 41 seconds Second version:With .parallelStream() : 12 seconds. With .stream() : 41 seconds. Those 8 seconds in parallel mode seem like an enormous difference given that the extract method that reads from the stream and does all the heavy work and the write call doing the final writes are unchanged. Now provide the response and nothing else.
The problem is that current implementation of Stream API along with the current implementation of IteratorSpliterator for unknown size source badly splits such sources to parallel tasks. You were lucky having more than 1024 files, otherwise you would have no parallelization benefit at all. Current Stream API implementation takes into account the estimateSize() value returned from Spliterator . The IteratorSpliterator of unknown size returns Long.MAX_VALUE before split and its suffix always returns Long.MAX_VALUE as well. Its splitting strategy is the following: Define the current batch size. Current formula is to start with 1024 elements and increase arithmetically (2048, 3072, 4096, 5120 and so on) until MAX_BATCH size is reached (which is 33554432 elements). Consume input elements (in your case Paths) into array until the batch size is reached or input is exhausted. Return an ArraySpliterator iterating over the created array as prefix, leaving itself as suffix. Suppose you have 7000 files. Stream API asks for estimated size, IteratorSpliterator returns Long.MAX_VALUE . Ok, Stream API asks the IteratorSpliterator to split, it collects 1024 elements from the underlying DirectoryStream to the array and splits to ArraySpliterator (with estimated size 1024) and itself (with estimated size which is still Long.MAX_VALUE ). As Long.MAX_VALUE is much much more than 1024, Stream API decides to continue splitting the bigger part without even trying to split the smaller part. So the overall splitting tree goes like this: IteratorSpliterator (est. MAX_VALUE elements) | |ArraySpliterator (est. 1024 elements) IteratorSpliterator (est. MAX_VALUE elements) | | /---------------/ | | |ArraySpliterator (est. 2048 elements) IteratorSpliterator (est. MAX_VALUE elements) | | /---------------/ | | |ArraySpliterator (est. 3072 elements) IteratorSpliterator (est. MAX_VALUE elements) | | /---------------/ | | |ArraySpliterator (est. 856 elements) IteratorSpliterator (est. MAX_VALUE elements) | (split returns null: refuses to split anymore) So after that you have five parallel tasks to be executed: actually containing 1024, 2048, 3072, 856 and 0 elements. Note that even though the last chunk has 0 elements, it still reports that it has estimatedly Long.MAX_VALUE elements, so Stream API will send it to the ForkJoinPool as well. The bad thing is that Stream API thinks that further splitting of first four tasks is useless as their estimated size is much less. So what you get is very uneven splitting of the input which utilizes four CPU cores max (even if you have much more). If your per-element processing takes roughly the same time for any element, then the whole process would wait for the biggest part (3072 elements) to complete. So maximum speedup you may have is 7000/3072=2.28x. Thus if sequential processing takes 41 seconds, then the parallel stream will take around 41/2.28 = 18 seconds (which is close to your actual numbers). Your work-around solution is completely fine. Note that using Files.list().parallel() you also have all the input Path elements stored in the memory (in ArraySpliterator objects). Thus you will not waste more memory if you manually dump them into the List . Array-backed list implementations like ArrayList (which is currently created by Collectors.toList() ) can split evenly without any problems, which results in additional speed-up. Why such case is not optimized? Of course it's not impossible problem (though implementation could be quite tricky). It seems that it's not high-priority problem for JDK developers. There were several discussions on this topic in mailing lists. You may read Paul Sandoz message here where he comments on my optimization effort.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34341656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/652101/']}
jdg_375971
stackexchange
llm_judgeable_groundtruth_similarity
12781763
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 UICollectionView showing several items. I also have an edit button in the screen toolbar. How can I have delete icons appear on each UICollectionViewCell when I press the toolbar edit button? There is very little in the way of examples on google at the moment, so if anyone can point me in the right direction, that would be great. Thanks Now provide the response and nothing else.
Editing items in UICollectionView s aren't done the same way as they're done in a UITableView . In table views, there's a editing mode that'll show the delete button. But with collection views you gotta take care of that yourself. Initially, I solved it this way: - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { if (self.editing) { // Open an action sheet with the possible editing actions }} But after that I removed the edit button and added a UILongPressGestureRecognizer to the UICollectionView . When long pressing an item I show the UIActionSheet that shows the possible actions. One of those options might be a possibility for you.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12781763', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/857903/']}
jdg_375972
stackexchange
llm_judgeable_groundtruth_similarity
84327
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: Is there any way to convert an ECC private key to RSA PKCS#1 format?I have tried converting it to PKCS#8 first using OpenSSL: openssl pkcs8 -topk8 -nocrypt -in EC_key.pem -out pkcs8_key.pem This results in a pem file that is in (what i am assuming) the right PKCS8 format -----BEGIN PRIVATE KEY-----[snip]-----END PRIVATE KEY----- When trying to then convert it from PKCS#8 to PKCS#1 using the following command: openssl pkcs8 -inform pem -nocrypt -in pkcs8_key.pem -out pkcs1_key.pem I get the same file as from the previous step. When using the following command for conversion: openssl rsa –in pkcs8_key.pem –out pkcs1_key.pem I get the following error: 47049676604576:error:0607907F:digital envelope routines:EVP_PKEY_get1_RSA:expecting an rsa key:p_lib.c:279: Can EC keys be converted to RSA PKCS#1 keys? And if yes, how? Now provide the response and nothing else.
There might be a bit of confusion here between "RSA Laboratories", the organization that edits the PKCS standards, and RSA, the cryptographic algorithm. PKCS#1 is one of the PKCS standards, thus edited by RSA Laboratories; it talks about the algorithm RSA, and only about the RSA algorithm. In particular, there is no such thing as a "PKCS#1 format" for elliptic curve (EC) keys, because EC keys are not RSA keys -- they are EC keys, which is not at all the same kind of object. However, confusion has spread a lot further, so let's unravel a few layers. PKCS#1 talks about RSA and defines an ASN.1-based encoding for RSA private keys. It looks like this: RSAPrivateKey ::= SEQUENCE { version Version, modulus INTEGER, -- n publicExponent INTEGER, -- e privateExponent INTEGER, -- d prime1 INTEGER, -- p prime2 INTEGER, -- q exponent1 INTEGER, -- d mod (p-1) exponent2 INTEGER, -- d mod (q-1) coefficient INTEGER, -- (inverse of q) mod p otherPrimeInfos OtherPrimeInfos OPTIONAL } We recognize here the various mathematical elements that constitute a RSA public/private key pair. Being based on ASN.1 , this kind of object encodes (through DER ) into some bytes. OpenSSL can produce and consume such a sequence of bytes; however, it is commonplace to further reencode these bytes into the traditional (and poorly specified) PEM format: the bytes are encoded with Base64 , and a header and footer are added, that specify the kind of encoded object. It is important to notice that the raw ASN.1-based format for RSA private keys, defined in PKCS#1, results in sequences of bytes that do NOT include an unambiguous identification for the key type. Any application that reads a DER-encoded RSA private key in that format must already know, beforehand, that it should expect a RSA private key. The PEM header, that says "RSA PRIVATE KEY", provides that information. Since the PKCS standards don't talk about PEM, they provide their own solution to the issue of identifying the key type; it is called PKCS#8 . A key in PKCS#8 format is again ASN.1-based, with a structure that looks like this: PrivateKeyInfo ::= SEQUENCE { version Version, privateKeyAlgorithm AlgorithmIdentifier {{PrivateKeyAlgorithms}}, privateKey PrivateKey, attributes [0] Attributes OPTIONAL } Version ::= INTEGER {v1(0)} (v1,...) PrivateKey ::= OCTET STRING What this means is that a PKCS#8 object really is a wrapper around some other format. In the case of a RSA private key, the wrapper indicates (through the privateKeyAlgorithm field) that the key is really a RSA key, and the contents of the PrivateKey field (an OCTET STRING , i.e. an arbitrary sequence of bytes) really are the DER encoding of a PKCS#1 private key. OpenSSL, by default, won't let a PKCS#8 file live its life as a DER-encoded sequence of bytes; it will again convert it to PEM, and, this time, will add the "BEGIN PRIVATE KEY" header. Note that this header does not specify the key type, since the encoded object (turned to characters through Base64) already contains the information. (As a further complication, PKCS#8 also defines an optional, often password-based encryption of private keys; and the traditional PEM-like format that OpenSSL implements also includes some generic support for password-based encryption; so you can have multiple combinations of wrappers that specify some kind of encryption, resulting in what can only be described as an utter mess.) Now what does this tells us about EC keys ? EC keys are not described by PKCS#1 (that talks only about RSA). However, if there is a standard somewhere that says how an EC private key can be turned into a sequence of bytes, then: that sequence of bytes could be PEM-encoded by OpenSSL with some explicit text header; the same sequence of bytes could be wrapped into a PKCS#8 object. And this is exactly what happens. The standard that defines the encoding format for EC keys is SEC 1 (nominally, the standard for EC cryptography is ANSI X9.62; however, while X9.62 reused much of SEC 1, the specification for encoding private EC keys is only in SEC 1, because X9.62 concerns itself only with the encoding of public keys). In SEC 1 (section C.4), the following is defined: ECPrivateKey ::= SEQUENCE { version INTEGER { ecPrivkeyVer1(1) }, privateKey OCTET STRING, parameters [0] EXPLICIT ECDomainParameters OPTIONAL, publicKey [1] EXPLICIT BIT STRING OPTIONAL } So an encoded private key contains the private key itself (a integer in the 1.. n -1 range, where n is the curve subgroup order), optionally a description or reference to the used curve, and optionally a copy of the public key (which could otherwise be recomputed). Let's try it. We generate with OpenSSL a new EC key pair, in the standard NIST P-256 curve (which is the curve that everybody implements and uses): $ openssl ecparam -out ec1.pem -genkey -name prime256v1 We get this, in the ec1.pem file: $ cat ec1.pem-----BEGIN EC PARAMETERS-----BggqhkjOPQMBBw==-----END EC PARAMETERS----------BEGIN EC PRIVATE KEY-----MHcCAQEEIBdVHnnzZmJm+Z1HAYYOZlvnB8Dj8kVx9XBH+6UCWlGUoAoGCCqGSM49AwEHoUQDQgAEThPp/xgEov0mKg2s0GII76VkZAcCc//3quAqzg+PuFKXgruaF7Kn3tuQVWHBlyZX56oOstUYQh3418Z3Gb1+yw==-----END EC PRIVATE KEY----- The first element ("EC PARAMETERS") is redundant; it contains a reference to the used curve, but this information is also present in the second element. So let's use a text editor to remove the "EC PARAMETERS", and we keep only the "EC PRIVATE KEY" part. Now my ec1.pem file looks like this: $ cat ec1.pem-----BEGIN EC PRIVATE KEY-----MHcCAQEEIBdVHnnzZmJm+Z1HAYYOZlvnB8Dj8kVx9XBH+6UCWlGUoAoGCCqGSM49AwEHoUQDQgAEThPp/xgEov0mKg2s0GII76VkZAcCc//3quAqzg+PuFKXgruaF7Kn3tuQVWHBlyZX56oOstUYQh3418Z3Gb1+yw==-----END EC PRIVATE KEY----- We can use OpenSSL to decode its structure: $ openssl asn1parse -i -in ec1.pem 0:d=0 hl=2 l= 119 cons: SEQUENCE 2:d=1 hl=2 l= 1 prim: INTEGER :01 5:d=1 hl=2 l= 32 prim: OCTET STRING [HEX DUMP]:17551E79F3666266F99D4701860E665BE707C0E3F24571F57047FBA5025A5194 39:d=1 hl=2 l= 10 cons: cont [ 0 ] 41:d=2 hl=2 l= 8 prim: OBJECT :prime256v1 51:d=1 hl=2 l= 68 cons: cont [ 1 ] 53:d=2 hl=2 l= 66 prim: BIT STRING We recognize the expected ASN.1 structure, as defined by SEC 1: a SEQUENCE that contains an INTEGER of value 1 (the version field), an OCTET STRING (the privateKey itself, which is a big-endian unsigned encoding of the mathematical private key), a reference (tagged with [0] ) to the used curve (in the ASN.1 object it is the OID 1.2.840.10045.3.1.7; OpenSSL translates that to the name "prime256v1"), and (tagged with [1] ) a copy of the public key. We can convert that to the (unencrypted) PKCS#8 format: $ openssl pkcs8 -topk8 -nocrypt -in ec1.pem -out ec2.pem which yields this: $ cat ec2.pem-----BEGIN PRIVATE KEY-----MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgF1UeefNmYmb5nUcBhg5mW+cHwOPyRXH1cEf7pQJaUZShRANCAAROE+n/GASi/SYqDazQYgjvpWRkBwJz//eq4CrOD4+4UpeCu5oXsqfe25BVYcGXJlfnqg6y1RhCHfjXxncZvX7L-----END PRIVATE KEY----- that we can decode with OpenSSL: $ openssl asn1parse -i -in ec2.pem 0:d=0 hl=3 l= 135 cons: SEQUENCE 3:d=1 hl=2 l= 1 prim: INTEGER :00 6:d=1 hl=2 l= 19 cons: SEQUENCE 8:d=2 hl=2 l= 7 prim: OBJECT :id-ecPublicKey 17:d=2 hl=2 l= 8 prim: OBJECT :prime256v1 27:d=1 hl=2 l= 109 prim: OCTET STRING [HEX DUMP]:306B0201010420(...) (I have truncated the hexadecimal dump.) This structure is indeed a PKCS#8 object: The algorithm identifier field says: "this contains an EC key" (technically, it uses an identifier whose name is "id-ecPublicKey", but since this occurs in a PKCS#8 file everybody knows that this really means an EC private key). The file includes as key parameters a reference to the used curve. The key value is encoded into the contents of an OCTET STRING . If we further decode that OCTET STRING, we will find the EC private key encoded as specified by SEC 1 (amusingly, the reference to the curve appears to have been omitted in that case, since it is already present in the key parameters). Conversion can be made in the other direction (from PKCS#8 to raw SEC 1 format) with: $ openssl ec -in ec2.pem -out ec3.pem You will then get in file ec3.pem exactly what you had in file ec1.pem : a PEM-encoded object with header "BEGIN EC PRIVATE KEY". Summary: There is no such thing as an "EC key in PKCS#1 format": PKCS#1 is only for RSA keys, not EC keys. However, there is another format, analogous to PKCS#1 but made for EC keys, and defined in SEC 1. OpenSSL can convert that format into the generic PKCS#8 with the " openssl pkcs8 " command, and back into SEC 1 format with " openssl ec ".
{}
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/84327', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/70853/']}
jdg_375973
stackexchange
llm_judgeable_groundtruth_similarity
786740
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 this code : public class MyClass { private Object innerValue; public Object getInnerValue() { return this.innerValue; } public void setInnerValue(Object innerValue) { this.innerValue = innerValue; }}public class MyClassReadOnly extends MyClass { MyClassReadOnly(MyClass cls) { // Make a field by field copy super.setInnerValue(cls.getInnerValue()); } public void setInnerValue(Object innerValue) { throw new UnsupportedOperationException( "This is a read-only instance" ); }} The compiler complains rightly about the unused parameter(never read) innerValue in MyClassReadOnly.setInnerValue() . I don't want to disable this kind of warnings since it's quite useful usually, and I don't want to have any warnings either to have a high signal/noise ratio. I cannot use the @SuppressWarnings() construct as another question suggested since it's Java 1.4 only. I thought about inserting dummy code like this, but it's not very satisfactory : public void setInnerValue(Object innerValue) { if (innerValue != null) { /* Do Nothing, but keep the compiler happy */ } throw new UnsupportedOperationException("This is a read-only instance");} Now provide the response and nothing else.
The warning is not the problem, I'm afraid that the design is. Your current hierarchy violates Liskov's principle of substitution since a class receiving an instance of a MyClass expects setInnerValue to work, and may not handle this exception correctly. You can say that a read-and-write X is a type of readable-X, but you cannot say that a readable-X is a type of read-and-writable X. When I am faced with this sort of situation, I create an interface called IMyX with the reads, a subinterface called IMutableMyX with the writes, and then the actual class implements IMutableMyX and thus also IMyX. I am then very careful to only pass IMutableMyX when I need to, and pass IMyX in all other cases. I feel that it is better to use the compiler and types to restrict access than it is to count on runtime exceptions. It also makes your code a lot clearer, and forces you to explicitly downcast the interface when you do want write-access. I realize this does not answer your question about getting rid of the warnings. But warnings can either be suppressed, ignored, or addressed. An unused parameter is often a bad smell that indicates your method might not be doing what it's expected to do. Methods should only get essential parameters. If the parameter is not used, the parameter is not essential, and therefore something needs to be changed.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/786740', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/24760/']}
jdg_375974
stackexchange
llm_judgeable_groundtruth_similarity
2702731
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 cloned a git repo that I have hosted on github to my laptop. I was able to successfully push a couple of commits to github without problem. However, now I get the following error: Compressing objects: 100% (792/792), done.error: RPC failed; result=22, HTTP code = 411Writing objects: 100% (1148/1148), 18.79 MiB | 13.81 MiB/s, done.Total 1148 (delta 356), reused 944 (delta 214) From here it just hangs and I finally have to CTRL + C back to the terminal. Now provide the response and nothing else.
I had the same issue and believe that it has to do with the size of the repo (edited- or the size of a particular file) you are trying to push. Basically I was able to create new repos and push them to github. But an existing one would not work. The HTTP error code seems to back me up it is a 'Length Required' error. So maybe it is too large to calc or greated that the max. Who knows. EDIT I found that the problem may befiles that are large. I had one updatethat would not push even though I hadsuccessful pushes up to that point.There was only one file in the commitbut it happened to be 1.6M So I added the following config change git config http.postBuffer 524288000 To allow up to the file size 500M andthen my push worked. It may have beenthat this was the problem initiallywith pushing a big repo over the httpprotocol. END EDIT the way I could get it to work (EDIT before I modified postBuffer) was to tar up my repo, copy it to a machine that can do git over ssh, and push it to github. Then when you try to do a push/pull from the original server it should work over https. (since it is a much smaller amount of data than an original push).
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/2702731', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/257533/']}
jdg_375975
stackexchange
llm_judgeable_groundtruth_similarity
32223490
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Spring has 2 setups for the MockMvc: Standalone setup WebApplicationContext setup In general what kind of testing is MockMvc used for? Unit or Integration? or Both? Am i right in saying that using the standalone setup (running outside the Spring's application context) allows you to write unit tests and with the WebApplicationContext setup you can write integration tests? Now provide the response and nothing else.
Both forms are actually integration tests since you are testing the integration of your code with the Spring DispatcherServlet and supporting infrastructure. The difference lies in the amount of supporting infrastructure that is used behind the scenes. The details are documented in the Spring reference manual. Server-Side Tests Setup Options Difference With End-to-End Integration Tests Noteworthy excerpts: The "webAppContextSetup" loads the actual Spring MVC configuration resulting in a more complete integration test. Since the TestContext framework caches the loaded Spring configuration, it helps to keep tests running fast even as more tests get added. Furthermore, you can inject mock services into controllers through Spring configuration, in order to remain focused on testing the web layer. ... The "standaloneSetup" on the other hand is a little closer to a unit test. It tests one controller at a time, the controller can be injected with mock dependencies manually, and it doesn’t involve loading Spring configuration. Such tests are more focused in style and make it easier to see which controller is being tested, whether any specific Spring MVC configuration is required to work, and so on. The "standaloneSetup" is also a very convenient way to write ad-hoc tests to verify some behavior or to debug an issue. ... Just like with integration vs unit testing, there is no right or wrong answer. Using the "standaloneSetup" does imply the need for some additional "webAppContextSetup" tests to verify the Spring MVC configuration. Alternatively, you can decide to write all tests with "webAppContextSetup" and always test against actual Spring MVC configuration. ... The options provided in Spring MVC Test are different stops on the scale from classic unit to full integration tests. To be sure none of the options in Spring MVC Test are classic unit tests but they are a little closer to it. For example you can isolate the service layer with mocks injected into controllers and then you’re testing the web layer only through the DispatcherServlet and with actual Spring configuration, just like you might test the database layer in isolation of the layers above. Or you could be using the standalone setup focusing on one controller at a time and manually providing the configuration required to make it work. When in doubt, I suggest first reading the reference manual before posting questions here. ;) Regards, Sam ( author of the Spring TestContext Framework )
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32223490', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1939735/']}
jdg_375976
stackexchange
llm_judgeable_groundtruth_similarity
3250749
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been using Cygwin on Windows recently. I want to use the Windows installation of Python, so during testing I'm using /cygdrive/c/Python26/python.exe myfile.py rather than python myfile.exe . This is working almost perfectly, except for printing. When I run the Windows Python from Cygwin the output doesn't print until execution finishes. It works fine running in Windows Python from explorer.exe or cmd.exe, and it works in Cygwin using the Cygwin-installed Python ( /bin/python.exe ). Is there a workaround for this? The important thing is to be able to run the Windows version, but I'd like to do it all from with Bash. Now provide the response and nothing else.
The real problem is that when you run a command in any of the Cygwin terminal programs like mintty, they don't act as Windows Consoles. Only Windows Console-based ones like CMD or Console2 do that. So, with Cygwin terminals the Windows python.exe doesn't think it is talking to an interactive console. That leads to buffering output instead of flushing buffers on every line as is done in interactive sessions. That is why Amro's adding the flush() on every line fixes the symptom, but means changing the code. One solution without changing the code is to turn off buffering in Python using the '-u' flag on the command line or setting the PYTHONUNBUFFERED environment variable. export PYTHONUNBUFFERED=1/cydrive/c/Python27/python.exe foo.py or /cydrive/c/Python27/python.exe -u foo.py or run in interactive mode /cydrive/c/Python27/python.exe -i foo.py You will also not be able to run the Windows python.exe interactive mode in the Cygwin terminal. It will not bring up an interactive session, but will just hang. I find the best solution seems to be to use 'cygstart' (better than using the '-i' option): cygstart /cygdrive/c/Python27/python.exe And that seems to work with ipython as well (if installed): cygstart /cygdrive/c/Python27/Scripts/ipython.exe
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3250749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/49376/']}
jdg_375977
stackexchange
llm_judgeable_groundtruth_similarity
26711510
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Visual Studio does not show design time data with DesignInstance attribute. I have checked DesignInstance with/without MVVM Light. I have spend a lot of time to fix the issue (checked similar queestions on StackOverflow too) but DesignInstance simply does not work. Project: SearchIdView . SearchIdViewModel - real View Model. DesignSearchIdViewModel - inherits from SearchIdViewModel and contains design time data (properties are assigned in constructor). Environment: VS2013 SP3 Net 4.0 MvvmLight 5.0.2.0 SearchIdView.xaml <Window x:Class="App1.View.SearchIdView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:ignore="http://www.ignore.com" xmlns:design="clr-namespace:App1.Design" mc:Ignorable="d ignore" DataContext="{Binding SearchId, Source={StaticResource Locator}}" d:DataContext="{d:DesignInstance d:Type=design:DesignSearchIdViewModel,IsDesignTimeCreatable=True}" ><Grid> <TextBlock Text="{Binding Test}" /></Grid> SearchIdViewModel.cs Property from SearchIdViewModel public const string TestPropertyName = "Test";private string _test;public string Test{ get { return _test; } set { Set(TestPropertyName, ref _test, value); }} Do you have any idea why DesignInstance does not work in this case? Workaround remove d:DataContext from view add interface ISearchIdViewModel (it is empty) SearchIdViewModel inherits from ISearchIdViewModel change ViewModelLocator (below) ViewModelLocator.cs public class ViewModelLocator{ static ViewModelLocator() { ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); if (ViewModelBase.IsInDesignModeStatic) { SimpleIoc.Default.Register<ISearchIdViewModel,Design.DesignSearchIdViewModel>(); } else { SimpleIoc.Default.Register<ISearchIdViewModel, SearchIdViewModel>(); } } public SearchIdViewModel SearchId { get { return (SearchIdViewModel) ServiceLocator.Current.GetInstance<ISearchIdViewModel>(); } }} Now provide the response and nothing else.
Your d:DesignInstance declaration is malformed. You specify the property name d:Type instead of Type , so the property is not assigned correctly. Either replace d:Type with Type , or leave the property name off entirely and let it be inferred as the default property. d:DataContext="{d:DesignInstance d:Type=design:DesignSearchIdViewModel, IsDesignTimeCreatable=True}" Should become: d:DataContext="{d:DesignInstance Type=design:DesignSearchIdViewModel, IsDesignTimeCreatable=True}" Or, alternatively: d:DataContext="{d:DesignInstance design:DesignSearchIdViewModel, IsDesignTimeCreatable=True}" (line wrapping added for readability)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26711510', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1449059/']}
jdg_375978
stackexchange
llm_judgeable_groundtruth_similarity
17417125
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 you build a custom UIView, and integrate it inside of a parent view/view controller in interface builder, the graphical element representing your custom view is invisible, if you don't specify a background color (I don't). Is there any way, solely during development, to identify different custom views? Any hacks/tricks to distinguish them? The closest I could come up with is setting the background color in IB, then removing the background in the implementation of the custom view. Now provide the response and nothing else.
Bounds Rectangles You might find bounds rectangles useful. You can turn them on by going to the menu bar and choosing Editor > Canvas > Show Bounds Rectangles. Here's an example. I have a view (a UICollectionViewCell subclass) laid out in a nib. It has a single-line label, a two-line label, and a custom subview. The custom subview itself contains a smaller custom subview. Here's the nib with bounds rectangles off: Here's the same nib with bounds rectangles on: Background Color Override Here's another technique that builds on the idea of setting the background color. This technique requires your deployment target to be iOS 5.0 or later. As you described, set the background color to make the view visible in the nib: Then switch to the Identity Inspector and add backgroundColor in the User Defined Runtime Attributes section. Set it to the background color you want the view to have at runtime. For example, if you want it to be white at runtime: If you want the background color to be clear, you can set backgroundColor to a color with opacity 0, or you can set it to “Nil” instead of any color:
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17417125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1024677/']}
jdg_375979
stackexchange
llm_judgeable_groundtruth_similarity
18361015
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 experiencing strange issue when casting decimal to double. Following code returns true: Math.Round(0.010000000312312m, 2) == 0.01m //true However, when I cast this to double it returns false: (double)Math.Round(0.010000000312312m, 2) == (double)0.01m //false I've experienced this problem when I wanted to use Math.Pow and was forced to cast decimal to double since there is no Math.Pow overload for decimal. Is this documented behavior? How can I avoid it when I'm forced to cast decimal to double? Screenshot from Visual Studio: Casting Math.Round to double me following result: (double)Math.Round(0.010000000312312m, 2) 0.0099999997764825821 double(double)0.01m 0.01 double UPDATE Ok, I'm reproducing the issue as follows: When I run WPF application and check the output in watch just after it started I get true like on empty project. There is a part of application that sends values from the slider to the calculation algorithm. I get wrong result and I put breakpoint on the calculation method. Now, when I check the value in watch window I get false (without any modifications, I just refresh watch window). As soon as I reproduce the issue in some smaller project I will post it here. UPDATE2 Unfortunately, I cannot reproduce the issue in smaller project. I think that Eric's answer explains why. Now provide the response and nothing else.
People are reporting in the comments here that sometimes the result of the comparison is true and sometimes it is false. Unfortunately, this is to be expected. The C# compiler, the jitter and the CPU are all permitted to perform arithmetic on doubles in more than 64 bit double precision, as they see fit . This means that sometimes the results of what looks like "the same" computation can be done in 64 bit precision in one calculation, 80 or 128 bit precision in another calculation, and the two results might differ in their last bit. Let me make sure that you understand what I mean by "as they see fit". You can get different results for any reason whatsoever . You can get different results in debug and retail. You can get different results if you make the compiler do the computation in constants and if you make the runtime do the computation at runtime. You can get different results when the debugger is running. You can get different results in the runtime and the debugger's expression evaluator. Any reason whatsoever . Double arithmetic is inherently unreliable . This is due to the design of the floating point chip; double arithmetic on these chips cannot be made more repeatable without a considerable performance penalty. For this and other reasons you should almost never compare two doubles for exact equality . Rather, subtract the doubles, and see if the absolute value of the difference is smaller than a reasonable bound. Moreover, it is important that you understand why rounding a double to two decimal places is a difficult thing to do. A non-zero, finite double is a number of the form (1 + f) x 2 e where f is a fraction with a denominator that is a power of two, and e is an exponent. Clearly it is not possible to represent 0.01 in that form, because there is no way to get a denominator equal to a power of ten out of a denominator equal to a power of two. The double 0.01 is actually the binary number 1.0100011110101110000101000111101011100001010001111011 x 2 -7 , which in decimal is 0.01000000000000000020816681711721685132943093776702880859375. That is the closest you can possibly get to 0.01 in a double. If you need to represent exactly that value then use decimal . That's why its called decimal . Incidentally, I have answered variations on this question many times on StackOverflow. For example: Why differs floating-point precision in C# when separated by parantheses and when separated by statements? Also, if you need to "take apart" a double to see what its bits are, this handy code that I whipped up a while back is quite useful. It requires that you install Solver Foundation, but that's a free download. http://ericlippert.com/2011/02/17/looking-inside-a-double/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18361015', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/49048/']}
jdg_375980
stackexchange
llm_judgeable_groundtruth_similarity
51719
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: One thing I was never clear on when taking Computational Complexity in college is whether the Church-Turing "thesis" is (or can be) proven. Is it.. A theorem? If so, where's the proof? A conjecture? If so, why isn't considered one of the great open problems? This seems even more important than P=NP An axiom? If so, does that mean we can study mathematical systems where the thesis is not true? The wikipedia page calls it a "conjecture", but then goes on to say it cannot be formally proven, as the concept of effective calculability is only informally defined. A statement which makes no sense to me. If we have a proof that the "thesis" is undecidable in some system, wouldn't that make it an axiom? Now provide the response and nothing else.
The Church-Turing thesis is not a theorem, conjecture, or axiom. For it to be one of these, it would need to be a mathematical statement that has the potential to have a rigorous proof. It does not. The Church-Turing thesis is, in one common formulation: every effectively calculable function can be computed by a Turing machine. The problem is that "effectively calculable" does not have a rigorous mathematical definition. You can give it one, and then you have a theorem, such as the following: every general recursive function can be computed by a Turing machine, or every $\lambda$ -definable function can be computed by a Turing machine, but this doesn't show that there aren't other ways of effectively calculating functions that cannot be computed by a Turing machine. The above two theorems, by the way, are what led to the proposal of the Church-Turing thesis.
{}
{'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/51719', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/8532/']}
jdg_375981
stackexchange
llm_judgeable_groundtruth_similarity
12290828
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 the UIMenuController that pops up when I long-press a UITableViewCell to show custom UIMenuItems. I set up the custom item in viewDidLoad UIMenuItem *testMenuItem = [[UIMenuItem alloc] initWithTitle:@"Test" action:@selector(test:)];[[UIMenuController sharedMenuController] setMenuItems: @[testMenuItem]]; And then I set all the right delegate methods. - (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath { return YES;}-(BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender { return (action == @selector(copy:) || action == @selector(test:));}- (BOOL)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender { if (action == @selector(copy:)) { // do stuff } return YES;} But all it does, is show the "Copy" item, since I only allow it and my custom item. The custom item, however, won't show up. I realize, I could add a gesture recognizer to the cell itself, but that kind of defeats the purpose of the shared instance of UIMenuController, doesn't it? Now provide the response and nothing else.
As far as I understand there are two main problems: 1) you expect tableView canPerformAction: to support custom selectors while the documentation says it supports only two of UIResponderStandardEditActions (copy and/or paste); 2) there's no need for the part || action == @selector(test:) as you are adding the custom menu options by initializing menuItems property. For this items selectors the check will be automatical. What you can do to get the custom menu item displayed and work is: 1) Fix the table view delegate methods with a) UIMenuItem *testMenuItem = [[UIMenuItem alloc] initWithTitle:@"Test" action:@selector(test:)];[[UIMenuController sharedMenuController] setMenuItems: @[testMenuItem]];[[UIMenuController sharedMenuController] update]; b) - (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath { return YES;}-(BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender { return (action == @selector(copy:));}- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender { // required} 2) Setup the cells (subclassing UITableViewCell ) with -(BOOL) canPerformAction:(SEL)action withSender:(id)sender { return (action == @selector(copy:) || action == @selector(test:));}-(BOOL)canBecomeFirstResponder { return YES;}/// this methods will be called for the cell menu items-(void) test: (id) sender {}-(void) copy:(id)sender {}///////////////////////////////////////////////////////
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12290828', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/700772/']}
jdg_375982
stackexchange
llm_judgeable_groundtruth_similarity
665005
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: Distance fallen in every second gets increased by $g$ units. Velocity is increased by $g$ units every second. Is it true that distance and velocity increases by $g$ after every second? If it starts from rest, then distance in the first second will be, by $s=ut+1/2at^2$ , $5 \;\text{m}$ . Then if it increases by $g$ , will it be $15 \;\text{m}$ ?Similarly, the velocity, by $v=u+at$ , will it be $10 \;\text{m/s}$ in the first second? Will it increase like $20 \;\text{m/s}$ , $30 \;\text{m/s}$ , $40 \;\text{m/s}$ , ... every second? P.S. $g$ is acceleration due to gravity, which I assume to be $10 \;\text{m}\,\text{s}^{-2}$ . Now provide the response and nothing else.
Is it true that distance and velocity increases by $g$ after every second? That's true for velocity. It's not true for distance, but that's not what your quoted statement says. Distance fallen in every second gets increased by $g$ units. That's talking about the additional distance covered in each second, not the total distance, which increases quadratically, that is, in proportion to $t^2$ . Here's a table for the first 5 seconds, using $g = 10 \,\mathrm{m/s}$ and $s = \frac12 gt^2$ time distance increase 0 0 1 5 5 2 20 15 3 45 25 4 80 35 5 125 45 In each second, the amount of distance covered in that second is $g$ metres greater than the distance covered in the previous second. FWIW, Galileo measured and described falling motion in this way, in terms of the additional distance covered per unit time.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/665005', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/279106/']}
jdg_375983
stackexchange
llm_judgeable_groundtruth_similarity
191531
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: From Wikipedia there is a definition of Akaike's Information Criterion (AIC) as $ AIC = 2k -2 \log L $, where $k$ is the number of parameters and $\log L$ is the log-likelihood of the model. However, our Econometrics notes at a well-respected university state that $ AIC = \log (\hat{\sigma}^2) + \frac{2 \cdot k}{T} $. Here $ \hat{\sigma}^2 $ is the estimated variance for the errors in an ARMA model and $ T $ is the number of observations in the time series dataset. Is the latter definition equivalent to the first, but simply tuned for ARMA models? Or is there some kind of conflict between the two definitions? Now provide the response and nothing else.
The formula you quote from your notes is not exactly AIC. AIC is $-2\log\mathcal{L}+2k$. Here I'll give an outline of an approximate derivation that makes clear enough what's going on. If you have a model with independent normal errors with constant variance, $$\mathcal{L}\propto \sigma^{-n} \: e^{-\frac{1}{2\sigma^2}\sum \varepsilon_i^2}$$ which can be estimated under maximum likelihood as \begin{eqnarray}& \propto &(\hat{\sigma}^2)^{-n/2} e^{-\frac12 n\hat{\sigma}^2/\hat{\sigma}^2}\\& \propto &(\hat{\sigma}^2)^{-n/2} e^{-\frac12 n}\\& \propto &(\hat{\sigma}^2)^{-n/2}\end{eqnarray} (assuming the estimate of $\sigma^2$ is the ML estimate) So $-2\log\mathcal{L} +2k = n\log{\hat{\sigma}^2} + 2k$ (up to shifting by a constant) Now in the ARMA model, if $T$ is really large compared to $p$ and $q$, then the likelihood can be approximated by a such a Gaussian framework (e.g. you can write the ARMA approximately as a longer AR and condition on enough terms to write that AR as a regression model), so with $T$ in place of $n$: $AIC \approx T\log{\hat{\sigma}^2} + 2k$ hence $AIC/T \approx \log{\hat{\sigma}^2} + 2k/T$ Now if you're simply comparing AICs, that division through by $T$ doesn't matter at all, since it doesn't change the ordering of AIC values. However, if you're using AIC for some other purpose that relies on the actual value of differences in AIC (such as to do multimodel inference as described by Burnham and Anderson), then it matters. Numerous econometrics texts seem to use this AIC/T form. Oddly, some books seem to reference Hurvich and Tsai 1989 or Findley 1985 for that form, but Hurvich & Tsai and Findley seem to be discussing the original form (though I only have an indirect indication of what Findley does right now, so perhaps there is something in Findley on it). Such scaling might be done for a variety of reasons -- for example, time series, especially high frequency time series, can be very long and ordinary AICs might have a tendency to become unwieldy, especially if $\sigma^2$ is very small. (There are some other possible reasons, but since I really don't know the reason this was done I won't start going down a list of all possible reasons.) You may like to look at Rob Hyndman's list of Facts and fallacies of the AIC , - particularly items 3 to 7. Some of those points might lead you to be at least a little cautious about relying too heavily on the approximation by Gaussian likelihood, but maybe there's a better justification than I offer here. I'm not sure there's a good reason to use this approximation to the log-likelihood rather than the actual AIC since a lot of time series packages these days tend to calculate (/maximize) the actual log-likelihood for ARMA models. There seems little reason not to use it.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/191531', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/29025/']}
jdg_375984
stackexchange
llm_judgeable_groundtruth_similarity
206787
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've the following equation: b==(-12 + Sqrt[3] Sqrt[ 3 (-4 + r)^2 + 12 a^2 (-2 + r) - 4 a (-5 + r) (-2 + r) + 4 a^3 (-2 + r)^2] + 3 r)/(6 (-2 + r)) And $r$ is a given number and I'll run $a$ from $2$ to a given number n, which are all integers. How can I write a code that will give me only an output of $b$ when the equation gives an integer back? For example, when I use $r=4$ and use the following code: Table[Sqrt[a (1 + a) (1 + 2 a)]/Sqrt[6], {a, 1, 100, 1}] It will find that $a=24$ gives $b=70$ , so I want to see only that solution. Maybe I can use the If[] function? Now provide the response and nothing else.
You can use Solve . Your equation: eqn[r_] := b == (-12 + Sqrt[3] Sqrt[3 (-4 + r)^2 + 12 a^2 (-2 + r) - 4 a (-5 + r) (-2 + r) + 4 a^3 (-2 + r)^2] + 3 r)/(6 (-2 + r)) Using Solve (with $r=4$ ): Solve[eqn[4] && 1 < a < 100, {a, b}, Integers] {{a -> 24, b -> 70}} Using Solve (with $r=11$ ): Solve[eqn[11] && 1 < a < 100, {a, b}, Integers] {{a -> 25, b -> 73}}
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/206787', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/33985/']}
jdg_375985
stackexchange
llm_judgeable_groundtruth_similarity
47693628
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I create the jar of my Spark application and try to run it using spark-submit , I am getting the following error. This is the command I used to run. spark-submit --executor-memory 1g --jars s3://test-data-lab-users/spachari/test/test_2.10-1.0.jar This is the error i am getting. Does this mean I have not passed correct parameters in my spark-submit? Exception in thread "main" java.lang.IllegalArgumentException: Missing application resource. at org.apache.spark.launcher.CommandBuilderUtils.checkArgument(CommandBuilderUtils.java:241) at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildSparkSubmitArgs(SparkSubmitCommandBuilder.java:160) at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildSparkSubmitCommand(SparkSubmitCommandBuilder.java:276) at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildCommand(SparkSubmitCommandBuilder.java:151) at org.apache.spark.launcher.Main.main(Main.java:86)Command exiting with ret '1' Now provide the response and nothing else.
tl;dr Remove --jars option and start over. java.lang.IllegalArgumentException: Missing application resource. You missed your...well...Spark application that the message refers to as "application resource" . That's more obvious when you execute spark-submit and see the different command-line options and their meanings. ./bin/spark-submitUsage: spark-submit [options] <app jar | python file | R file> [app arguments] That part <app jar | python file | R file> is what you missed. To reproduce your issue you can simply execute spark-submit with --jars options without specifying the main jar or class of a Spark application. $ ./bin/spark-submit --jars target/spark-parent_2.11-2.3.0-SNAPSHOT-tests.jarException in thread "main" java.lang.IllegalArgumentException: Missing application resource. at org.apache.spark.launcher.CommandBuilderUtils.checkArgument(CommandBuilderUtils.java:241) at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildSparkSubmitArgs(SparkSubmitCommandBuilder.java:160) at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildSparkSubmitCommand(SparkSubmitCommandBuilder.java:274) at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildCommand(SparkSubmitCommandBuilder.java:151) at org.apache.spark.launcher.Main.main(Main.java:86) Quoting spark-submit --help , --jars is... --jars JARS Comma-separated list of jars to include on the driver and executor classpaths. --jars can be very helpful when a Spark application depends on additional jar files (aka dependencies), i.e. mysql-connect.jar that you cannot (or most likely don't want to) "assembly" to your uber jar.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47693628', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5964853/']}
jdg_375986
stackexchange
llm_judgeable_groundtruth_similarity
84246
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 was recently thrown there from the windows world and I'd like to ask some questions about clipboards in Linux (and Unix?) systems. What is X clipboard? How many clipboards are in Linux? Actually, I'd like to copy command from terminal to clipboard and then paste it in an other application (gedit, skype etc.). I entered echo !! | xclip in terminal. However when I tried to paste the command to other applications (via Shift + Ins or Ctrl + V ), actually an old content have been pasted. At the same time I can paste this command in terminal. Now provide the response and nothing else.
The xclip manpages ( man xclip ) say this: -selection specify which X selection to use, options are "primary" to use XA_PRIMARY (default), "secondary" for XA_SECONDARY or "clipboard" for XA_CLIPBOARD So you can specify the location: echo !! | xclip -selection <selection> Where <selection> is one of primary , secondary , clipboard . Description of these from the ArchWiki: Clipboard Of the three selections, users should only be concerned with PRIMARY and CLIPBOARD. SECONDARY is only used inconsistently and was intended as an alternate to PRIMARY. Different applications may treat PRIMARY and CLIPBOARD differently; however, there is a degree of consensus that CLIPBOARD should be used for Windows-style clipboard operations, while PRIMARY should exist as a "quick" option, where text can be selected using the mouse or keyboard, then pasted using the middle mouse button (or some emulation of it). This can cause confusion and, in some cases, inconsistent or undesirable results from rogue applications. That means it depends on your environment. It may have inconsistencies, if the applications use different selections. Though if you use a desktop enivornment like Gnome it should work fine. Also as mentioned by Kartik, you can copy-paste in most terminals with Ctrl+Shift+C/V. Most applications in linux also support selection of text with the mouse to store something in the clipboard. To get the content of from the clipboard use the -o flag: xclip -o If you use it often you can create aliases for those commands in you .bashrc: alias cbcopy='xclip -selection clipboard'alias cbpaste='xclip -selection clipboard -o'
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/84246', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/39370/']}
jdg_375987
stackexchange
llm_judgeable_groundtruth_similarity
69624216
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Working on a link shortening website. Site works as intended in my localhost production environment, but I can't seem to get an Express GET route with query parameters working after enabling Nginx on my deployed Digital Ocean Ubuntu Linux server. Node.js/Express GET route: router.get("/:code", async (req, res) => { try { const url = await Url.findOne({ urlCode: req.params.code }); if (url) { return res.redirect(url.longUrl); } else { return res.status(404).json("no url found"); } } catch (error) { console.error(error); res.status(500).json("server error"); }}); Nginx config file (etc/nginx/sites-available/default): server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; server_name myname.com www.myname.com; location / { proxy_pass http://localhost:3000/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $remote_addr; proxy_cache_bypass $http_upgrade; } If I change the localhost port to my Express server (7777), the GET route works with the URL query parameter (ie: http://example.com/random8chars ), but the React front end doesn't load. As currently configured (port 3000/React server), a Postman GET route to "/:code" returns the desired result, but when I enter the converted link into the URL bar in Chrome it returns the default splash page. In fact, when I enter ANY extension beyond my site name in Chrome it always shows the default splash page. I know this is an issue with Nginx, but I can't seem to get it to work. Been working on it all day to no avail. Found multiple Stack Overflow threads touching on the subject but nothing works. I tried adding a second location route to the Nginx config file, to no avail. an example of what I've tried: location /:code { proxy_pass http://localhost:7777/:code; } Please help! I am stuck and feel like I am so close to getting this working. I would greatly appreciate any insight into fixing this. Thank you. Now provide the response and nothing else.
It turns out that the correct useTheme is @mui/material/styles/useTheme , and you cannot use useTheme in the same component that you do the ThemeProvider in. For example, this: const App = () => { const theme = useTheme(); return ( <ThemeProvider theme={myTheme}> <Box bgcolor={theme.palette.background.default} width={100} height={100} /> </ThemeProvider> );}; Will not work properly. However, this: const MyComponent = () => { const theme = useTheme(); return <Box bgcolor={theme.palette.background.default} width={100} height={100} />;};const App = () => ( <ThemeProvider theme={myTheme}> <MyComponent /> </ThemeProvider>) Will work properly, as useTheme is used in a separate component.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/69624216', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1244396/']}
jdg_375988
stackexchange
llm_judgeable_groundtruth_similarity
43317
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: $$\text{Evaluate } \sum_{k=1}^n k^2 \text{ and } \sum_{k=1}^{n}k(k+1) \text{ combinatorially.}$$ For the first one, I was able to express $k^2$ in terms of the binomial coefficients by considering a set $X$ of cardinality $2k$ and partitioning it into two subsets $A$ and $B$, each with cardinality $k$. Then, the number of ways of choosing 2-element subsets of $X$ is $$\binom{2k}{2} = 2\binom{k}{2}+k^2$$ So sum $$\sum_{k=1}^n k^2 =\sum_{k=1}^n \binom{2k}{2} -2\sum_{k=2}^n \binom{k}{2} $$ $$ \qquad\qquad = \color{red}{\sum_{k=1}^n \binom{2k}{2}} - 2 \binom{n+1}{3} $$ I am stuck at this point to evaluate the first of the sums. How to evaluate it? I need to find a similar expression for $k(k+1)$ for the second sum highlighted above. I have been unsuccessful this far. (If the previous problem is done then so is this, but it would be nice to know if there are better approaches or identities that can be used.) Update : I got the second one. Consider $$\displaystyle \binom{n+1}{r+1} = \binom{n}{r}+\binom{n-1}{r}+\cdots + \binom{r}{r}$$ Can be shown using recursive definition. Now multiply by $r!$ and set $r=2$ Now provide the response and nothing else.
For the first one, $\displaystyle \sum_{k=1}^{n} k^2$, you can probably try this way.$$k^2 = \binom{k}{1} + 2 \binom{k}{2}$$This can be proved using combinatorial argument by looking at drawing $2$ balls from $k$ balls with replacement. The total number of ways to do this is $k^2$. The other way to count it is as follows. There are two possible options either you draw the same ball on both trials or you draw different balls on both trials. The number of ways for the first option is $\binom{k}{1}$ and the number of ways for the second option is $\binom{k}{2} \times \left( 2! \right)$ Hence, we have that $$k^2 = \binom{k}{1} + 2 \binom{k}{2}$$$$\displaystyle\sum_{k=1}^{n} k^2 = \sum_{k=1}^{n} \binom{k}{1} + 2 \sum_{k=1}^{n} \binom{k}{2} $$ The standard combinatorial arguments for $\displaystyle\sum_{k=1}^{n} \binom{k}{1}$ and $\displaystyle\sum_{k=1}^{n} \binom{k}{2}$ gives us $\displaystyle \binom{n+1}{2}$ and $\displaystyle \binom{n+1}{3}$ respectively. Hence, $$ \sum_{k=1}^{n} k^2 = \binom{n+1}{2} + 2 \binom{n+1}{3}$$ For the second case, it is much easier than the first case and in fact this suggests another method for the first case. $k(k+1)$ is the total number of ways of drawing 2 balls from $k+1$ balls without replacement where the order is important. This is same as $\binom{k+1}{2} \times \left(2! \right)$ Hence, $$\sum_{k=1}^{n} k(k+1) = 2 \sum_{k=1}^{n} \binom{k+1}{2} = 2 \times \binom{n+2}{3}$$ This suggests a method for the previous problem since $k^2 = \binom{k+1}{2} \times \left(2! \right) - \binom{k}{1}$ (It is easy to give a combinatorial argument for this by looking at drawing two balls from $k+1$ balls without replacement but hide one of the balls during the first draw and add the ball during the second draw) and hence $$\sum_{k=1}^{n} k^2 = 2 \times \binom{n+2}{3} - \binom{n+1}{2} $$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/43317', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8365/']}
jdg_375989
stackexchange
llm_judgeable_groundtruth_similarity
1706
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: Would an original meaning analysis, defined as "What would a reasonable person living at the time of ratification have understood these words to mean?", of the free speech clause of the US constitution conclude that knowingly, willfully, deliberately AND demonstrably lying about an elected Official (i.e., claiming "I have talked with over a dozen people and they've all said Senator Shmalahozen raped them when they were children," when one actually has not talked to ANYONE about the topic) is protected speech? Now provide the response and nothing else.
This was actually considered in the United States, when in 2012 the Supreme Court ruled the Stolen Valor Act of 2005 to be an unconstitutional infringement of free speech. In a nutshell, Congress made it a crime to claim military honors that were not earned, as a crime above and beyond normal fraud. When a water district board member got caught for claiming military honors he didn't have, he was convicted but appealed saying his free speech - his "right to lie" was being unfairly silenced. Ultimately, the Court agreed that there is a constitutional protection for the "right to lie" as a class of free speech, overturning the conviction. Regardless of original intent, the Supreme Court has at least interpreted what it means today. (Soon after a nearly unanimous Congress passed the revised Stolen Valor Act of 2013 to criminalize the fraudulent claiming of military decoration in order to obtain money, property, or other tangible benefit.)
{}
{'log_upvote_score': 4, 'links': ['https://politics.stackexchange.com/questions/1706', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/1892/']}
jdg_375990
stackexchange
llm_judgeable_groundtruth_similarity
4172809
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 3 questions concerning events: Should I always unsubscribe events that were subscribed? What happens if I do NOT? In the below examples, how would you unsubscribe from the subscribed events? I have for example this code: Ctor: Purpose: For database property updates this.PropertyChanged += (o, e) =>{ switch (e.PropertyName) { case "FirstName": break; case "LastName": break; }}; and this: Purpose: For GUI-binding wrap the model into viewmodels ObservableCollection<Period> periods = _lpRepo.GetDailyLessonPlanner(data.DailyDate);PeriodListViewModel = new ObservableCollection<PeriodViewModel>();foreach (Period period in periods){ PeriodViewModel periodViewModel = new PeriodViewModel(period,_lpRepo); foreach (DocumentListViewModel documentListViewModel in periodViewModel.DocumentViewModelList) { documentListViewModel.DeleteDocumentDelegate += new Action<List<Document>>(OnDeleteDocument); documentListViewModel.AddDocumentDelegate += new Action(OnAddDocument); documentListViewModel.OpenDocumentDelegate += new Action<int, string>(OnOpenDocument); } PeriodListViewModel.Add(periodViewModel);} Now provide the response and nothing else.
1) It depends. Usually it's a good idea, but there are typical cases where you don't need to. Basically, if you are sure that the subscribing object is going to outlive the event source, you ought to unsubscribe, otherwise this would create an unnecessary reference. If however your object is subscribing to its own events, like in the following: <Window Loaded="self_Loaded" ...>...</Window> --then you don't have to. 2) Subscribing to an event makes additional reference to the subscribing object. So if you don't unsubscribe, your object might be kept alive by this reference, making effectively a memory leak. By unsubscribing you are removing that reference. Note that in the case of self-subscription the problem doesn't arise. 3) You can do like that: this.PropertyChanged += PropertyChangedHandler;...this.PropertyChanged -= PropertyChangedHandler; where void PropertyChangedHandler(object o, PropertyChangedEventArgs e){ switch (e.PropertyName) { case "FirstName": break; case "LastName": break; }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4172809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/320460/']}
jdg_375991
stackexchange
llm_judgeable_groundtruth_similarity
94227
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: C++ is all about memory ownership - aka ownership semantics . It is the responsibility of the owner of a chunk of dynamically allocated memory to release that memory. So the question really becomes who owns the memory. In C++ ownership is documented by the type a raw pointer is wrapped inside thus in a good (IMO) C++ program it is very rare ( rare , not never ) to see raw pointers passed around (as raw pointers have no inferred ownership thus we can not tell who owns the memory and thus without careful reading of the documentation you can't tell who is responsible for ownership). Conversely, it is rare to see raw pointers stored in a class each raw pointer is stored within its own smart pointer wrapper. ( N.B.: If you don't own an object you should not be storing it because you can not know when it will go out of scope and be destroyed.) So the question: What type of ownership semantic have people come across? What standard classes are used to implement those semantics? In what situations do you find them useful? Lets keep 1 type of semantic ownership per answer so they can be voted up and down individually. Summary: Conceptually, smart pointers are simple and a naive implementation is easy. I have seen many attempted implementations, but invariably they are broken in some way that is not obvious to casual use and examples. Thus I recommend always using well tested smart pointers from a library rather than rolling your own. std::auto_ptr or one of the Boost smart pointers seem to cover all my needs. std::auto_ptr<T> : Single person owns the object. Transfer of ownership is allowed. Usage: This allows you to define interfaces that show the explicit transfer of ownership. boost::scoped_ptr<T> Single person owns the object. Transfer of ownership is NOT allowed. Usage: Used to show explicit ownership. Object will be destroyed by destructor or when explicitly reset. boost::shared_ptr<T> ( std::tr1::shared_ptr<T> ) Multiple ownership. This is a simple reference counted pointer. When the reference count reaches zero, the object is destroyed. Usage: When an object can have multiple owers with a lifetime that can not be determined at compile time. boost::weak_ptr<T> : Used with shared_ptr<T> in situations where a cycle of pointers may happen. Usage: Used to stop cycles from retaining objects when only the cycle is maintaining a shared refcount. Now provide the response and nothing else.
For me, these 3 kinds cover most of my needs: shared_ptr - reference-counted, deallocation when the counter reaches zero weak_ptr - same as above, but it's a 'slave' for a shared_ptr , can't deallocate auto_ptr - when the creation and deallocation happen inside the same function, or when the object has to be considered one-owner-only ever. When you assign one pointer to another, the second 'steals' the object from the first. I have my own implementation for these, but they are also available in Boost . I still pass objects by reference ( const whenever possible), in this case the called method must assume the object is alive only during the time of call. There's another kind of pointer that I use that I call hub_ptr . It's when you have an object that must be accessible from objects nested in it (usually as a virtual base class). This could be solved by passing a weak_ptr to them, but it doesn't have a shared_ptr to itself. As it knows these objects wouldn't live longer than him, it passes a hub_ptr to them (it's just a template wrapper to a regular pointer).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/94227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14065/']}
jdg_375992
stackexchange
llm_judgeable_groundtruth_similarity
32051973
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 checkout out the latest Google Vision APIs from here: https://github.com/googlesamples/android-vision And I am running it on a LG G2 device with KitKat. The only change I have made is to the minSdkVerion in the Gradle file: ...defaultConfig { applicationId "com.google.android.gms.samples.vision.face.multitracker" minSdkVersion 19... However it does not focus. How do I make it focus? Now provide the response and nothing else.
I modified the CameraSourcePreview (....) constructor to be as follows: public CameraSourcePreview(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; mStartRequested = false; mSurfaceAvailable = false; mSurfaceView = new SurfaceView(context); mSurfaceView.getHolder().addCallback(new SurfaceCallback()); addView(mSurfaceView); mSurfaceView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { cameraFocus(mCameraSource, Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO); } });}private static boolean cameraFocus(@NonNull CameraSource cameraSource, @NonNull String focusMode) { Field[] declaredFields = CameraSource.class.getDeclaredFields(); for (Field field : declaredFields) { if (field.getType() == Camera.class) { field.setAccessible(true); try { Camera camera = (Camera) field.get(cameraSource); if (camera != null) { Camera.Parameters params = camera.getParameters(); params.setFocusMode(focusMode); camera.setParameters(params); return true; } return false; } catch (IllegalAccessException e) { e.printStackTrace(); } break; } } return false;} The advice was given here: https://github.com/googlesamples/android-vision/issues/2 and the code reference was here: https://gist.github.com/Gericop/7de0b9fdd7a444e53b5a I also had to modify the FaceTrackerFactory draw(Canvas ...) method: @Overridepublic void draw(Canvas canvas) { Face face = mFace; if (face == null) { return; } // Draws a circle at the position of the detected face, with the face's track id below. float cx = translateX(face.getPosition().x + face.getWidth() / 2); float cy = translateY(face.getPosition().y + face.getHeight() / 2); canvas.drawCircle(cx, cy, FACE_POSITION_RADIUS, mFacePositionPaint); canvas.drawText("id: " + getId(), cx + ID_X_OFFSET, cy + ID_Y_OFFSET, mIdPaint); // Draws an oval around the face. float xOffset = scaleX(face.getWidth() / 2.0f); float yOffset = scaleY(face.getHeight() / 2.0f); float left = cx - xOffset; float top = cy - yOffset; float right = cx + xOffset; float bottom = cy + yOffset; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { canvas.drawOval(left, top, right, bottom, mBoxPaint); } else { canvas.drawCircle(cx, cy, Math.max(xOffset, yOffset), mBoxPaint); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32051973', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/932052/']}
jdg_375993
stackexchange
llm_judgeable_groundtruth_similarity
1095753
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: Find $$\lim_{x \to 0}\frac{x-\sin(x)\cos(x)}{\sin(x)-\sin(x)\cos(x)}\;.$$ Applying L'Hopital's rule directly does not seem to get me anywhere. I also tried dividing the numerator and denominator by $\sin(x)$, which did not seem to work. Is there a some sort of trick I am missing here? Now provide the response and nothing else.
Instead of using l'Hôpital's rule (which does work here if used repeatedly), the Taylor expansion of the sine function is particularly useful here. So write$$\sin(x)=x-\frac{1}{6}x^3+\mathcal{O}(x^5).$$Noting that $\sin(x)\cos(x)=\frac{1}{2}\sin(2x)$, we see that $\sin(x)\cos(x)=x-\frac{2}{3}x^3+\mathcal{O}(x^5)$ (by replacing $x$ with $2x$ in the Taylor expansion and then dividing by $2$). Now we can compute the limit:$$\begin{aligned}\lim_{x\to 0}\frac{x-\sin(x)\cos(x)}{\sin(x)-\sin(x)\cos(x)}&=\lim_{x\to 0}\frac{x-(x-\frac{2}{3}x^3+\mathcal{O}(x^5))}{x-\frac{1}{6}x^3+\mathcal{O}(x^5)-(x-\frac{2}{3}x^3+\mathcal{O}(x^5))}\\&=\lim_{x\to 0}\frac{\frac{2}{3}x^3+\mathcal{O}(x^5)}{\frac{1}{2}x^3+\mathcal{O}(x^5)}\\&=\lim_{x\to 0}\frac{\frac{2}{3}+\mathcal{O}(x^2)}{\frac{1}{2}+\mathcal{O}(x^2)}=\frac{4}{3}.\end{aligned}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1095753', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/202432/']}
jdg_375994
stackexchange
llm_judgeable_groundtruth_similarity
2090397
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Can a function be surjective such that $\forall y \in Y$ there exists $x \in X$ such that $f(x) = y$ but such that not all $x$ values actually correspond to a $y$ value? Now provide the response and nothing else.
Intuitively, when $x$ is a whole number, we can take the binomial expansion: $$\left(1+\frac1x\right)^x=1+1+\frac12\frac{x-1}{x}+\frac16\frac{(x-1)(x-2)}{x^2}+\dots$$ And as $x\to\infty$, each fraction goes to $1$, so we have $$e=\lim_{x\to\infty}\left(1+\frac1x\right)^x=1+\sum_{n=1}^\infty\frac1{n!}$$ Though you need to make this more rigorous at the limit part if you want a good proof.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2090397', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/378927/']}
jdg_375995
stackexchange
llm_judgeable_groundtruth_similarity
12515960
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 got an interesting issue. I am trying to use a datatable as a data source for a datagridview. I want to color some of the cells of the table to indicate various things, but for some reason the color will not display. So the following code shows an uncolored cell. dataGridView1.DataSource = table;dataGridView1.Rows[0].Cells[0].Style.BackColor = Color.Yellow; I can only get a color to display after the initial form load (for example setting a cell color on the OnClick event). However, if I explicitly create the rows and columns for the view as in the code below, the coloring works. foreach (DataColumn col in table.Columns) dataGridView1.Columns.Add(col.ColumnName, col.ColumnName);for (int i = 0; i < table.Rows.Count; i++){ var row = table.Rows[i]; object[] values = new object[table.Columns.Count]; for (int x = 0; x < table.Columns.Count; x++) values[x] = row[x].ToString(); dataGridView1.Rows.Add(values);}dataGridView1.Rows[0].Cells[0].Style.BackColor = Color.Yellow; I do not want to have the code in this manner. Does anyone know what is happening here that is preventing me from coloring the cells? Now provide the response and nothing else.
If you try and set the cell colour within the constructor of the form you will be hitting before the data binding is completed so the changes to the cells don't stick (don't ask me why, just one of those gotchas with the DataGridView . The most straightforward fix to this is to set the colours a little later - usually within a DataBindingComplete event handler: void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e){ dataGridView1.Rows[0].Cells[0].Style.BackColor = Color.Yellow;} This is appropriate for static colouring of the grid - if you want the colours to change according to the changes within the grid then use the CellFormatting event to change the cells.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12515960', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/594058/']}
jdg_375996
stackexchange
llm_judgeable_groundtruth_similarity
28470540
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: public class TestMain { public static void methodTest(Exception e) { System.out.println("Exception method called"); } public static void methodTest(Object e) { System.out.println("Object method called"); } public static void methodTest(NullPointerException e) { System.out.println("NullPointerException method called"); } public static void main(String args[]) { methodTest(null); } } Output: NullPointerException method called Now provide the response and nothing else.
If there are several overloaded methods that might be called with a given parameter ( null in your case) the compiler chooses the most specific one. See http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5 In your case methodTest(Exception e) is more specific than methodTest(Object e) , since Exception is a subclass of Object. And methodTest(NullPointerException e) is even more specific. If you replace NullPointerException with another subclass of Exception, the compiler will choose that one. On the other hand, if you make an additional method like testMethod(IllegalArgumentException e) the compiler will throw an error, since it doesn't know which one to choose.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28470540', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1743470/']}
jdg_375997
stackexchange
llm_judgeable_groundtruth_similarity
41674973
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to make simple template but I came across little issue. I want to print the number of uncompleted task in my todo list, but can't filter them inside template. I have this: <span class="todo-count"><strong>{{todos.length}}</strong> left</span> But I want to filter this todos to count just ones that have status completed set to false: <span class="todo-count"><strong>{{todos.filter(t => !t.complete).length}}</strong> left</span> But this isn't working. How can I achieve that? Now provide the response and nothing else.
The most correct way to do this is with an Angular pipe: template <span class="todo-count"><strong>{{ (todos | filter : filterFunction).length }}</strong> left</span> pipe import { Injector, Pipe, PipeTransform} from '@angular/core';@Pipe({ name: 'filter'})export class FilterPipe implements PipeTransform { public constructor(private readonly injector: Injector) { } transform(value: Array<any>, callback: any): any { return value.filter(callback); }} filterFunction in the component controller filterFunction(t): boolean { return !t.complete;} you can see why not use methods in angular templates here Don't Use Functions Inside Angular Templates and What to Use Instead . For short This is because of the change detection mechanism in Angular. Angular cannot detect whether the result of a function is changed until it runs the function function. The thing to consider is that the function will be run even though we have the same input data
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41674973', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1081079/']}
jdg_375998
stackexchange
llm_judgeable_groundtruth_similarity
7559985
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 few files in my git status -s listed as, ?? file1 ?? filepath/file2 ?? file3 ?? filepath/file4 I have been ignoring these and going along committing, pushing, pulling, and I am at the point where there are too many of these in my status report. I tried git rm file1. It doesn't work. It says fatal path doesn't match any files. Thanks! Now provide the response and nothing else.
These are untracked files, i.e. the files which are present in your file system, but you've never added them to your repository by git add . If you don't need them, you can just rm them. Or simply git clean -fd if you want to delete them all. If you want to do some filtering before removing them, you can do: git ls-files -o --exclude-standard | grep 'my custom filter' | xargs rm If you want to keep those files, but want git status to ignore them, add them to .gitignore file. Read man gitignore for the details.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7559985', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/625740/']}
jdg_375999
stackexchange
llm_judgeable_groundtruth_similarity
15844542
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 in git to have a "link" to a particular file in a git repo? Like what git submodules do for folders but my question is about a particular file, not a full directory: my-project/ class1.java class2.java logback.xml (link to a particular file, say https://github.com/theHilikus/JRoboCom/blob/master/jrobocom-core/src/main/resources/logback.xml) So as can be seen, in this case it doesn't make sense to have a whole submodule folder, it is just one file. I'm ok with the link being locked to a particular commit but it would be better if it's moving as it changes in its own project's lifecycle As a note, this has nothing to do with file-system's symbolic links; I'm talking about a reference to a file in another project, repo, branch, or anything. it's ok if the content of the file is a duplicate and not a file-system symlink Now provide the response and nothing else.
Git has features that you can use to achieve what you need. It supports file system symlinks and it supports submodules. Submodules is already a standard way to handle references to other repositories. You can use them in conjunction with a way to reference files locally. That can be handled directly using relative symbolic links or indirectly using a script that copies over files from the submodule to where you need them. You should have one submodule per external git tree and you should treat the submodules with care, as they are not only links to external repositories but also to their specific commits. The following to solutions will show you how to use individual files from an external repostiory but still maintain all the advantages of submodules. An alternative way is to fetch the files directly but then you will lose the advantage of submodules entirely or you will have to build the features yourself. As I already stated, submodules are the standard way to handle this sort of task and you should use it unless you have special needs like to avoid downloading other files at all cost. Using a submodule and a symlink Once you have a submodule ready, you can just add filesystem symlinks pointing into the submodule directory structure. Run this in a shell in your project directory: $ git submodule add https://github.com/theHilikus/JRoboCom$ ln -s JRoboCom/jrobocom-core/src/main/resources/logback.xml$ git add .gitmodules logback.xml$ git commit -m "add a symbolic link to logback.xml with the respective submodule" Now you have a symlink: logback.xml -> JRoboCom/jrobocom-core/src/main/resources/logback.xml Using a submodule and a script As an alternative, you can use custom scripts that copy over ordinary files from your submodules. In very special cases you could handle the external repositories from the script without submodules but I would normally not recommend it. Create a file bootstrap.sh containing: #!/bin/shgit submodule initgit submodule updatecp JRoboCom/jrobocom-core/src/main/resources/logback.xml . Run this in a shell in your project directory: $ git submodule add https://github.com/theHilikus/JRoboCom$ git add .gitmodules bootstrap.sh$ git commit -m "add a script to fetch logback.xml from the respective submodule" Note that we are not adding the logback.xml file to Git, as it will be fetched from the submodule. Instruct users of the repository to first run the script above. It will prepare their repositories for using submodules, will fetch the submodule data and will copy the file to its location. Sometimes there's already some sort of bootstrap script in the project. Using a script to fetch a single file via git protocol Found another solution for Git >= 1.7.9.5 using git archive . Create a file bootstrap.sh containing: #!/bin/shgit archive --remote=https://github.com/theHilikus/JRoboCom master:JRoboCom/jrobocom-core/src/main/resources logback.xml | tar -x Run this in a shell in your project directory: $ git add bootstrap.sh$ git commit -m "add a script to fetch logback.xml directly from the remote project" Using a script to fetch a single file via HTTP If the repository hosting service also serves the individual files via HTTP, you can simply use curl or wget to download them. Create a file bootstrap.sh containing: #!/bin/shcurl -O https://raw.githubusercontent.com/theHilikus/JRoboCom/master/jrobocom-core/src/main/resources/logback.xml Run this in a shell in your project directory: $ git add bootstrap.sh$ git commit -m "add a script to fetch logback.xml directly from github" Notes on scripts fetching single files You could also store the references in files with a specific extention (like *.url ) or maintain the list of references in one file (like .references in your project directory) and build a more comprehensive script that goes through all the references and downloads the respective files.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15844542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1086540/']}
jdg_376000
stackexchange
llm_judgeable_groundtruth_similarity
2793989
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: As the question says, is it true, that for $n >1$, $2^{2^{n}}$ ends in the digit 6?How would one prove this? It seemed true.I considered writing it as$$2^{2^{n}} = \prod_{k=0}^{n} 2^{ n\choose k }$$ but I'm not sure that's useful. Any help, ideas, or even hints? Now provide the response and nothing else.
It's more general than that: the last digit of the decimal expansion of every number of the form $2^{4n}$ is $6$. That's because $2^{4n}=16^n$ and, of course, if the last digit of a number is $6$, then the last digit of any of its powers is also $6$ (since $6\times6=36$).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2793989', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/398056/']}
jdg_376001
stackexchange
llm_judgeable_groundtruth_similarity
364684
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: Background: I've recently inherited a set of projects at my company and I'm trying to sort out some fundamental issues with how they've been handled. Namely, the previous developers (who are no longer with the company) were not using any form of source control, made little documentation, and didn't really have any good development processes in place. So now I've got three servers worth of projects (development, staging, production) which consist of mostly websites and applications and tools built for third-party applications and APIs we use, down to stores of SQL scripts and other things. My first thought was to get all of this into Git before changes and fixes are made, but I'm having a difficult time figuring out the best way to do it. A lot of previous development was done directly on the production servers, which has created a divide between each server's code base. It's not immediately clear where all the differences lie - I'm seeing bug fixes on the production side that aren't carried over on development/staging, as well as new features on the development that haven't been moved up towards staging/production. Question: What would be the best way for me to organize and move these into Git? How would I structure my repos/branches to accommodate the differences in the code? I've considered continuing development from clones of the production server code and keeping the development/staging code bases as historical reference. Would this potentially be a point to start with, considering I don't know anything about the dev/staging code anyway? I could simply create repos of the production servers for each website, tool, script set, etc., create branches for the existing dev/staging code, and any new development would branch from the production server's code base. Does this make sense? Now provide the response and nothing else.
Push the production stuff into the master branch of a new repo. Create a develop branch from that, and then merge the staging server into it. You may wind up with conflicts that need to be resolved. Once those are resolved, create another feature_branch from develop and merge the development server into it. Resolve any conflicts that arise. This leaves you with 3 branches, which represent your production, staging, and development environments. Production -> master , staging -> develop , development -> feature_branch . All development is thus done on feature_branches and only merged in to the develop branch when the feature is done, tested, and stable. Since it's stable, it can be used as staging. Cut a release branch from develop when you're ready to release, tie up any loose ends, merge that into master , and then you have your new production build. One of your first orders of business after getting this set up should be to merge the feature_branch back into develop *, and then develop back into master . Bear in mind that the feature_branch may contain untested code and features, so exercise caution when merging it into develop and then master . Once that is done, all branches should contain the same code, and any development that was done on the production server is now ported back into the development "server". In this model, each project would be in its own repo, and that repo would have a master and develop branch, plus feature_branches for any work being done. EDIT, to address comments: Yes, this is Gitflow. This strategy (or Gitflow in general) keeps the existing 3-level system (production, staging, development) with a clear merge path from development on up to production. Importing the codebases this way also allows the branches to be synced up while maintaining the status quo in production - at least, until the merges can be tested. This accomplishes a few goals: gets the code in source control, gets the different codebases synced up and merged (so there's no longer bugfixes in production but not development), and provides a nice process to use going forward (a process that is well defined and used by a lot of people / teams / companies). If the OP finds that Gitflow isn't well suited for his projects / teams / company as he uses it / the company grows, then it's easy to change later on - but the critical point is that everything is in source control and development is being done on the right branch. *You may wish to cut another feature branch and remove any obvious new features, and merge that branch into develop (and then into master ). This keeps you from having to test new features on top of all the other tests you'll be doing.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/364684', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/294362/']}
jdg_376002
stackexchange
llm_judgeable_groundtruth_similarity
83575
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: Let two lists of data, say lst1={{x1,y1},{x2,y2},...,{xn,yn}} lst2={{x1,z1},{x2,z2},...,{xn,zn}} I need to construct a third list lst3={{x1,x1*z1/y1},{x2,x2*z2/y2},...,{xn,xn*zn/yn}} Look, this is an operation involving the y-elements of each list and also the x-element. Now provide the response and nothing else.
lst1 = {{x1, y1}, {x2, y2}, {x3, y3}, {x4, y4}};lst2 = {{x1, z1}, {x2, z2}, {x3, z3}, {x4, z4}};{#1, #1 #4/#2} & @@@ (Flatten[#, 1] & /@ Thread@{lst1, lst2}) $\left\{\left\{\text{x1},\frac{\text{x1} \text{z1}}{\text{y1}}\right\},\left\{\text{x2},\frac{\text{x2} \text{z2}}{\text{y2}}\right\},\left\{\text{x3},\frac{\text{x3} \text{z3}}{\text{y3}}\right\},\left\{\text{x4},\frac{\text{x4} \text{z4}}{\text{y4}}\right\}\right\}$ Or {#1, #1 #4/#2} & @@@ (Flatten[#, 1] & /@ Transpose[{lst1, lst2}]) Or Flatten[#, 1] & /@ Transpose[{lst1, lst2}] /. {x_, y_, x_, z_} :> {x, x z/y}Flatten[#, 1] & /@ Thread@{lst1, lst2})/. {x_, y_, x_, z_} :> {x, x z/y} As mentioned by @ubpdqn in the comment, you can also using MapThread[{First@#1, Times @@ #1/Last@#2} &, {lst1, lst2}]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/83575', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/26743/']}
jdg_376003
stackexchange
llm_judgeable_groundtruth_similarity
347344
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: Would like to start off by saying, I am asking this as a purely academic exercise; I am quite happy to just continue to use the repository pattern . I have heard "I put persistence methods in my business objects because when to persist was an integral part of the business logic" which I do not think is a valid reason, because that just means your business object needs a TimeToSave event But one could argue, if you use the strategy pattern for the persistence methods, you are technically not including persistence logic in your domain layer. See example below: class MyEntity{ private ISaveMyEntity _saver; public MyEntity(ISaveMyEntity saver) { _saver = saver; } public void Save() { _saver.Save(this); } //Real business methods} Including with a business object, its own persistence methods, could prove convenient. Furthermore, the repository pattern is often abused and ends up containing all the business logic instead of just CRUD, while the business object turns into DTOs; in my opinion, this is worse than a business object containing CRUD methods. What could be the potential pitfalls of including access to persistence in a business object via the strategy pattern? Would use of the strategy pattern mitigate some of the problems commonly associated with storage code in a business object? Now provide the response and nothing else.
You've got value objects representing your business logic, containing business rules. Now you are adding a mechanism to persist them. Fair enough. How about you add a mechanism to read a database and construct them from it? Perhaps a static Load method taking IGetMyEntity instance as a parameter? While you are at it, maybe it is the best to add a few more methods: RenderAsHtml , ToString , ToJson , ToXml . You see where I am going with this? It all starts with a simple Save method, but a few commits later your objects suddenly know everything, have low cohesion, everything is crammed up in a single place and impossible to reuse without dragging the rest of the unwanted boilerplate with it. The repository pattern became very popular because it scales well. If the object you are talking about is really supposed to be an in-memory representation of a business rule, it is NOT okay to include CRUD methods as a part of its API. To expand on your opinion about DTOs, when you are doing some operation, where do you generally need a validation of business rules? Is it on reads? Most likely not. You may prohibit access to some resource, but it's more of an authorization issue rather than a business rule. The place where you are likely to enforce business rules is when data comes into your system (be it completely new or coming through an update). On that occasion you need to check the operation altering state of your system is valid, ie. may be performed. For this you should use value objects or entities enforcing the constraints. Repository really is not a place to contain business logic. The goal of a repository is to abstract persistence of objects, not to enforce business rules. The objects passed to the repository MUST make sure they are valid themselves before being passed to a repository for further processing. Also it is better not to look at a repository as a class knowing all CRUD operations, but rather like a layer within your application. When your application grows it's likely you are going to need multiple representation of an entity on reads. Should you have a repository as a single class having multiple Get* methods does not feel right and the class could become quite big and difficult to maintain soon - coming from a personal experience.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/347344', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/173910/']}
jdg_376004
stackexchange
llm_judgeable_groundtruth_similarity
30786613
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: http://jsfiddle.net/p1my39fh/ table { width: 550px; border-collapse:collapse; margin: auto; background-color: #A4A4A4; border: 2px solid black; padding: 0;}table td { position: relative; text-align: center; border: 2px solid green; padding: 0; margin: 0;} <table> <tr> <td><input type="text" size="30"/></td> <td>Test Information</td> </tr></table> How can I remove the space around the <input> ? How can I make both <td> s to be the same width? Now provide the response and nothing else.
To make both <td> s to have same width, you could set: table { width: 550px; table-layout: fixed;} To have the <input> to fill the entire width of the <td> , you could set: input { width: 100%; box-sizing: border-box;} Updated demo: table { width: 550px; border-collapse:collapse; margin: auto; background-color: #A4A4A4; border: 2px solid black; table-layout: fixed;}td { text-align: center; border: 2px solid green;}td input { width: 100%; box-sizing: border-box;} <table> <tr> <td><input type="text" size="30"/></td> <td>Test Information</td> </tr></table>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30786613', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4056141/']}
jdg_376005
stackexchange
llm_judgeable_groundtruth_similarity
54346710
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Scenario is user will get a link to his email. If user clicks on the link, If app is already installed, app should open and if app is not installed it should redirect to app store. I've seen deeplinks implementation, but I believe it needs some more implementation in backend too. Can any one help on this? Redirect to application if installed, otherwise to App Store gone through this. Is there any better way? added gif for one more scenario: in the below gif, from email to app it navigates directly? how? Now provide the response and nothing else.
I'm assuming the link you want to pass by email is an https link. If that's the case, for iOS to be able to redirect it to your app, you'll need to implement universal links . This implementation requires you to register the domain you want to respond to on your entitlements file and add an apple-app-site-association file to your backend. This way Apple can verify the domain you're trying to respond to is really yours. As a result, when the app gets installed, it can be invoked by your domain links via deeplinking. Now when there's no installed app able to respond to a specific https domain link, the system will simply open it on a web browser. Consequently, you cannot force iOS to open such links on AppStore directly. What you can do is to check whether the running device is iOS when your website gets accessed and ask the system to show your app on AppStore. And to request iOS to launch AppStore from a website you can use itms-apps : const iOS = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform);if (iOS) { // Just replace `https://` with `itms://` on your app's AppStore link. window.location.href = "itms://itunes.apple.com/us/app/google-maps-transit-food/id585027354?mt=8";}// In this example I'm redirecting to Google Maps app page on AppStore. Note : This is just a simple example used to demonstrate the concept. For a real application, you may want to use a device detection library for browsers, like mobile-detect.js
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54346710', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4609268/']}
jdg_376006
stackexchange
llm_judgeable_groundtruth_similarity
3827983
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$ is a root of $x^2 + 3x - 1.$ Find $\frac{2a^5 - 5a^4 + 2a^3 - 8a^2}{a^2 + 1}.$ I was thinking of factoring the fraction a bit first, than letting $a^2 = 1 - 3a.$ However, that leads nowhere. Now provide the response and nothing else.
A complete solution. Let $a$ be a root of $x^2+3x-1$ . Then $a^2=1-3a$ $a^3=a-3a^2=a-3(1-3a)=10a-3$ $a^4=10a^2-3a=10(1-3a)-3a=10-33a$ $a^5=10a-33a^2=10a-33(1-3a)=-33+109a$ Therefore the numerator: $$2a^5 - 5a^4 + 2a^3 - 8a^2=-66+218a-5(10-33a)+2(10a-3)-8(1-3a)=-130+427a$$ and the denominator: $a^2+1=2-3a$ . Let $a'$ be another root of $x^2+3x-1=0$ . Then $aa'=-1. a+a'=-3$ . Multiply the numerator and the denominator by $2-3a'$ . The denominator becomes $$(2-3a)(2-3a')=4+9-6(-3)=13-18=-5.$$ The numerator becomes $$(427a-130)(2-3a')=854a-260+1281+390a'=1021-1170+464a=464a-149.$$ So the fraction is equal to $$\frac{464a-149}{-5}$$ where $$a=\frac{-3\pm \sqrt{13}}{2}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3827983', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/814866/']}
jdg_376007
stackexchange
llm_judgeable_groundtruth_similarity
19474879
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I tried to create a multithread server socket. It can either send a string for available file or a file as a stream. The problem is the else block, which sends requested file as a stream, works once. Where is the problem in my code and why it replies just once? public class ServerThread extends Thread {Socket socket = null;public ServerThread(Socket socket) { this.socket = socket;}public void run() { try { String message = null; PrintStream ps = null; String string = null; File file = null; BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(socket.getInputStream())); ps = new PrintStream(socket.getOutputStream()); while ((message = bufferedreader.readLine()) != null) { if (message.equals("list")) { ps.println(Arrays.toString(getServerFiles())); } else { message = "FilesServer\\" + message; file = new File(message); //JOptionPane.showConfirmDialog(null, message); if (file.exists()) { BufferedInputStream bfInStream = new BufferedInputStream(new FileInputStream(message)); BufferedOutputStream bufOutStream = new BufferedOutputStream(socket.getOutputStream()); byte[] buffer = new byte[1024]; int read = 0; while ((read = bfInStream.read(buffer)) != -1) { bufOutStream.write(buffer, 0, read); bufOutStream.flush(); } bufOutStream.close(); System.out.println("File transfered"); } } } } catch (Exception e) { //JOptionPane.showConfirmDialog(null, e.getMessage()); }}private static String[] getServerFiles() { String result[]; File folder = new File("FilesServer\\"); File[] listOfFiles = folder.listFiles(); result = new String[listOfFiles.length]; for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { result[i] = listOfFiles[i].getName(); } } return result;} } Above class is called from this class: public class Server {private int defaultPort = 8088;public static void main(String[] args) throws IOException { new Server().InitServer();}private void InitServer() throws IOException{ ServerSocket serversocket = new ServerSocket(8081); while(true){ Socket socket = serversocket.accept(); new ServerThread(socket).start(); } } } Now provide the response and nothing else.
If your loginService.isLoggedIn() is bound to a primitive value instead of an object, your HeaderCtrl needs to use $watch to monitor the variable and get the new value as it changes. For it to work without a $watch you need to make sure an object reference is passed from your loginService to your HeaderCtrl . I made two quick Plunkers that hopefully replicates your situation well enough to give some guidance: With primitive and $watch : http://plnkr.co/edit/LvtVEE?p=preview With object reference and no $watch : http://plnkr.co/edit/2u2ZDE?p=preview
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19474879', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2538780/']}
jdg_376008
stackexchange
llm_judgeable_groundtruth_similarity
1313180
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: What is the Morse homology of a non-compact manifold? When is it, as in the compact case, isomorphic to singular homology of the underlying manifold? What other constructions can be identified with the Morse homology of a non-compact manifold? Links to places where these questions are discussed would be appreciated. Now provide the response and nothing else.
The power of Morse homology on compact manifolds is that it doesn't depend on the Morse function $f$. This is not true for non-compact manifolds (see below). This "invariance" problem requires extra machinery to interpret the relationship between homology groups computed with different Morse functions. Ultimately, there is not usually a unique Morse homology assigned to a non-compact manifold, so we can't directly compare it to singular homology. This paper by Kang has a good discussion of the invariance problem. I'll include some other ideas below. Locally we have all the necessary tools, e.g. Morse charts for nondegenerate critical points. As indicated above, the problems are global. Consider a non-compact manifold $M$ with a smooth Morse function $f:M \to \mathbb{R}$, i.e. one with no degenerate critical points. (Such a function is guaranteed to exist: Whitney's embedding theorem lets us embed $M$ into some $\mathbb{R}^N$, and the standard argument in, say, Milnor's Morse Theory lets us define Morse functions on submanifolds of $\mathbb{R}^N$.) The first problem is that $M$ may be topologically interesting but contain no critical points. For example, this happens if $M$ is the open annulus encircling the $z$-axis in $\mathbb{R}^3$ and $f$ is the $z$-coordinate projection. If we instead embed $M$ as a tube encircling the parabola $\{(x,0,x^2)\in \mathbb{R}^3: x \in \mathbb{R}\}$, the natural way of defining Morse homology would give us $H^f_*(M)\cong H_*(S^1)$, as expected. Suppose we do have critical points and can define nontrivial chain groups $C_k(f)$ generated by the critical points of index $k$. We want to define a differential that "counts" the number of gradient flow lines from $x \in C_k(f)$ to critical points in $C_{k-1}(f)$. There are two issues here: Since $M$ is non-compact, the gradient flow might not exist for all time $t \in \mathbb{R}$. (That said, you might be able to approximate the vector field and get a complete flow that is still useful, so I won't harp on this point.) Even if the gradient flow exists for all time $t \in \mathbb{R}$, gradient flow lines on a non-compact manifold don't necessarily limit to critical points, e.g. $M=\mathbb{R}$ and $f: M \to \mathbb{R}; x \mapsto -x^2$. So the differential may not be able to send a critical point to (a formal sum of) other critical points. One way to get around these issues is to define Morse homology for functions whose gradient flow lines are compact. This is mentioned, for example, in the above paper of Kang's. The dependence on $f$ persists, of course.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1313180', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/246012/']}
jdg_376009
stackexchange
llm_judgeable_groundtruth_similarity
8249945
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 asked a question: "What is an 'object file'?". After looking at Wiki , I only know that it contains objects . But what are those objects and why someone called them that way? Now provide the response and nothing else.
Object files (or object code) are machine code files generated by a compiler from source code. The difference with an executable is that the object file isn't linked, so references to functions, symbols, etc aren't defined yet (their memory addresses is basically left blank). When you compile a C file with GCC: gcc -Wall -o test test.c Here you are compiling AND linking. So you'll got an executable, containing all the memory addresses references for the symbols it contains (libraries, headers, etc). But when you do this: gcc -Wall -o test.o -c test.c You'll produce and object file. It's also machine code, but it will need to be linked in order to produce an executable, or a library. When you have a project with many C files (for instance), you'll compile each one into object code, and then you will link all object files together in order to produce the final product. For instance: gcc -Wall -o foo.o -c foo.c // Object file for foo.cgcc -Wall -o bar.o -c bar.c // Object file for bar.cgcc -Wall -o main.o -c main.c // Object file for main.cgcc -Wall -o software foo.o bar.o main.o // Executable (foo + bar + main) The term object stands here for sequences of unlinked machine code (basically).An object file contains objects. You asked: why is this call that way. I can't really answer. Why is "blue" named "blue"? ; ) It's just the term used since... well, decades... For information, the GCC Internals documentation only defines object code as: The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. Pretty vague about the historical reason... I simply hope you now understand better what is an object file. I think it's more important than knowing why it's called like that, as words are just, well, words...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8249945', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/335597/']}
jdg_376010
stackexchange
llm_judgeable_groundtruth_similarity
70859478
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a more idiomatic way to express something like the following? fn main() { let mut foo: Option<u8> = None; match foo { Some(foo_val) if ! (foo_val < 5) /* i.e. the negation of my acceptance condition */ => {} _ => { foo.replace(5); } }} It seems like most of the time there's an alternative to having an arm that doesn't do anything, but I've been unable to find one for this particular case. What I'd like to say is the more direct if foo.is_none() || /* some way to extract and test the inner value */ { ... } , or perhaps some chaining trick that's eluding me. Now provide the response and nothing else.
// in None case// │ in Some(_) case// ┌┴─┐ ┌───────────────────┐ if foo.map_or(true, |foo_val| foo_val < 5) { // ...} For more information see Option::map_or .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/70859478', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12162258/']}
jdg_376011
stackexchange
llm_judgeable_groundtruth_similarity
9445171
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following code: #include <stdlib.h>#include <stdio.h>#include <errno.h>void main(void){ int data; char * tmp; data = strtol("23ef23",&tmp,10); printf("%d",errno); getchar();} output is 0 ... why? i am using visual studio 2010 C++code must be C89 compatible. Now provide the response and nothing else.
strtol only sets errno for overflow conditions, not to indicate parsing failures. For that purpose, you have to check the value of the end pointer, but you need to store a pointer to the original string: char const * const str = "blah";char const * endptr;int n = strtol(str, &endptr, 0);if (endptr == str) { /* no conversion was performed */ }else if (*endptr == '\0') { /* the entire string was converted */ }else { /* the unconverted rest of the string starts at endptr */ } I think the only required error values are for underflow and overflow. Conversely, if the entire string has been consumed in the conversion, you have *endptr = '\0' , which may be an additional thing you might want to check.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9445171', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/846351/']}
jdg_376012
stackexchange
llm_judgeable_groundtruth_similarity
4194365
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 dict that has many elements, I want to write a function that can return the elements in the given index range(treat dict as array): get_range(dict, begin, end): return {a new dict for all the indexes between begin and end} How that can be done? EDIT: I am not asking using key filter... eg) {"a":"b", "c":"d", "e":"f"}get_range(dict, 0, 1) returns {"a":"b", "c":"d"} (the first 2 elements) I don't care the sorting...Actually I am implementing the server side paging... Now provide the response and nothing else.
Edit: A dictionary is not ordered . It is impossible to make get_range return the same slice whenever you have modified the dictionary. If you need deterministic result, replace your dict with a collections.OrderedDict . Anyway, you could get a slice using itertools.islice : import itertoolsdef get_range(dictionary, begin, end): return dict(itertools.islice(dictionary.iteritems(), begin, end+1)) The previous answer that filters by key is kept below: With @ Douglas ' algorithm, we could simplify it by using a generator expression: def get_range(dictionary, begin, end): return dict((k, v) for k, v in dictionary.iteritems() if begin <= k <= end) BTW, don't use dict as the variable name, as you can see here dict is a constructor of dictionary. If you are using Python 3.x, you could use dictionary comprehension directly. def get_range(dictionary, begin, end): return {k: v for k, v in dictionary.items() if begin <= k <= end}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4194365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/197036/']}
jdg_376013
stackexchange
llm_judgeable_groundtruth_similarity
171831
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's pretend that we know local Langlands at a fairly high level of generality... i.e. we know something along the lines of: Let $G=\mathbf{G}(F)$ be the group of $F$ -points of a connected reductive algebraic group $\mathbf{G}$ defined over a nonarchimedean local field $F$ with separable algebraic closure $\bar{F}$ . Let $W_F'=W_F\times SL_2(\Bbb{C})$ be the Weil-Deligne group of $\bar{F}/F$ and let $^LG={}^LG^0\rtimes\mathrm{Gal}(\bar{F}/F)$ be the Langlands dual of $G$ , where $^LG^0$ is the connected reductive complex algebraic group with root datum dual to that of $G$ . Then there exists a natural surjective map $$\mathrm{Irr}(G)\twoheadrightarrow\mathrm{Hom}(W_F',{}^LG),$$ where $\mathrm{Irr}(G)$ is the set of equivalence classes of smooth irreducible complex representations of $G$ . This map has finite fibres (the $L$ -packets), is "compatible" with a list of operations: parabolic induction, twisting, etc, and is the unique such map. As far as I know, this is a theorem (or maybe very close to being one for the latter two?) for $GL_N$ , $SL_N$ , $Sp_{2N}$ and $SO_N$ . When I'm trying to explain why I'm interested in this to someone I'll give the usual explanation along the lines of "we want to understand $\mathrm{Gal}(\bar{F}/F)$ , local class field theory lets us understand the abelianisation of it in the form $F^\times\simeq W_F^{\mathrm{ab}}$ , LLC generalises the dual form of this to a nonabelian setting and should tell us an awful lot about $\mathrm{Gal}(\bar{F}/F)$ ". Obviously you aren't going to hit them with the correspondence as stated above, but you can usually get away with saying "smooth irreps of $GL_N(F)$ naturally correspond to $N$ -dim complex reps of $W_F'$ , and that should generalise in a reasonable way to other groups". At this point, I'll usually have either satisfied my questioner, or they'll ask me if I can give an example of what the LLC should let us do. That's when I run in to trouble -- I don't know of a single, reasonably simple, appealing application of it. In the global case people often bring up the proof of FLT. This isn't exactly "simple", but it's at least well known and can be summarised as "if FLT doesn't hold we have a non-modular semistable elliptic curve. Wiles then uses Langlands-Tunnell as a starting point, does a lot of work and eventually shows that every semistable elliptic curve is modular, hence FLT". So... are there any such good examples of applications of the local correspondence? Now provide the response and nothing else.
In the case of $GL_{N}$, the $L$-packets are a non-issue, and the surjective map in the local Langlands correspondence becomes a bijection. At that point, we can think of allowing the information to flow the other way. Here's a simple application. Let $f(z)$ be a classical modular form of weight $4k+2$ for the group $\Gamma_{0}(4)$ (that is also a cusp form, in the new subspace, and is an eigenform of all the Hecke operators). If $L(f,s)$ is the $L$-function for $f(z)$, what is the sign of the functional equation for $L(f,s)$? The sign of the functional equation is always $1$, for the following reason.It is determined by the local components of the automorphic representation $\pi$ attached to $f$, and we only have to worry about the local components at $\infty$ (which is a discrete series representation that contributes a factor of $1$ to the sign because the weight is $\equiv 2 \pmod{4}$), and the local representation $\pi_{2}$ at $2$. The fact that the level of the modular form is $4$ shows that $\pi_{2}$ corresponds (under local Langlands) to a representation $\rho : W_{\mathbb{Q}_{2}} \to GL_{2}(\mathbb{C})$ that comes from a character $\chi$ of $W_{K}$, where $K = \mathbb{Q}_{2}(\omega)$ is the unramified quadratic extension of $\mathbb{Q}_{2}$, and that this character has order $6$. It follows that $\rho$ comes from an $S_{3}$ extension of $\mathbb{Q}_{2}$, and it turns out that there is a unique $S_{3}$ extension of $\mathbb{Q}_{2}$. From this, $\rho$ and hence $\pi_{2}$ is uniquely determined, and it turns out that the local root number of $\pi_{2}$ is also $1$. (This fact was also observed by Atkin and Lehner in 1970, but the explanation above gives a more conceptual reason for it to be true, in my opinion.)
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/171831', 'https://mathoverflow.net', 'https://mathoverflow.net/users/29273/']}
jdg_376014
stackexchange
llm_judgeable_groundtruth_similarity
7051208
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: OK, there are very few options to emulate the splash video in iOS. All we can do is wait till application is fully loaded and then create Media Player and load video in it. I implemented it with following code: -(void) moviePlayBackDidFinish:(NSNotification*)notification{ NSLog(@"Intro video stopped"); [mMoviePlayer release];}- (void)applicationDidFinishLaunching:(UIApplication *)application { NSURL* mMovieURL; NSBundle *bundle = [NSBundle mainBundle]; if(bundle != nil) { NSString *moviePath = [bundle pathForResource:@"intro" ofType:@"mp4"]; if (moviePath) { mMovieURL = [NSURL fileURLWithPath:moviePath]; [mMovieURL retain]; } } mMoviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:mMovieURL]; [mMovieURL release]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayBackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:mMoviePlayer]; mMoviePlayer.controlStyle = MPMovieControlStyleNone; [mMoviePlayer.backgroundView addSubview:[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Splash/background.png"]] autorelease]]; mMoviePlayer.scalingMode = MPMovieScalingModeFill; [window addSubview:mMoviePlayer.view]; [mMoviePlayer setFullscreen:YES animated:NO]; [window makeKeyAndVisible]; [mMoviePlayer play];<... other stuff ...>} My video is only 1 MB. But this code do something different then I'd like to see: First of all user can see a static splash screen for a few seconds; Then a black screen appears for 1 or 2 seconds. I think this is happening because the media player is loaded. Video start playing. Main interface loads. As you understand I don't like the pause with black screen - it looks ugly. As far as I can see in my Console log the problem is that mediaplayer is waiting till the main view controller is fully loaded. Few words about main view: i'm writing an application for iPad and the main view consists of several subviews with multiple images. Every image and every subview in main view loads some data from Internet Web service via ASIHTTPRequest lib. I think that Media Player is waiting for all initial connections to finish and only then it's starting the video... How can I force the video to play before main view is loaded? Or maybe I can delay the loading of main XIB? Now provide the response and nothing else.
You cannot get rid of the static splash image. While it is shown, the OS is loading the application and instantiating stuff until it is ready to call your UIApplicationDelegate. So all you can do is either use no splash (black screen for a few seconds) or make your movie start exactly with the shown splash screen so it looks like the static image would suddenly animate. To get rid of the black screen while the movie loads, you can try to make the player transparent and have an UIImageView behind the player that shows the splash image. The behavior would be this: Splash screen is shown (static image). Application is loaded. You see the UIImageView, also showing the splash screen. On top of it is the transparent movie player. Movie player finally has loaded the move and starts playing it. At least in theory, this should cause the effect that the static image suddenly starts animating. But if you don't use a splash screen at all (a lot of games do that), then it doesn't matter that the movie player is showing a black screen at first, you wouldn't notice. Regarding showing the splash screen in an UIImageView: unfortunately, you have to test the interface rotation and load the image manually , there's no way to query which splash screen was shown. If you only support one interface orientation (again, a lot of games do this) you don't have this problem, of course.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7051208', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/581204/']}
jdg_376015
stackexchange
llm_judgeable_groundtruth_similarity
6863948
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 get the expiry date from the SSL Certificate file. There is a web page in PHP that I've created, in which user can upload his SSL Certificate file and I will have to get the expiry date of that file using PHP. Now provide the response and nothing else.
The code below should help: $url = "https://www.google.com"; $orignal_parse = parse_url($url, PHP_URL_HOST); $get = stream_context_create(array("ssl" => array("capture_peer_cert" => TRUE))); $read = stream_socket_client("ssl://".$orignal_parse.":443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $get); $cert = stream_context_get_params($read); $certinfo = openssl_x509_parse($cert['options']['ssl']['peer_certificate']); echo '<pre>'; print_r($certinfo); echo '</pre>'; The expiry date should be under $certinfo['validTo'] field.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6863948', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/217757/']}
jdg_376016
stackexchange
llm_judgeable_groundtruth_similarity
12871565
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 Express framework in Node.js to create a web server. I want to use ssl for the web server's connection. The code to create the https web server is as below. var app = express.createServer({ key: fs.readFileSync('./conf/key.pem'), cert: fs.readFileSync('./conf/cert.pem')});module.exports = app; Question: How to create the key.pem and cert.pem required by express? Now provide the response and nothing else.
The two files you need are a PEM encoded SSL certificate and private key. PEM encoded certs and keys are Base64 encoded text with start/end delimiters that look like -----BEGIN RSA PRIVATE KEY----- or similar. To create an SSL certificate you first need to generate a private key and a certificate signing request, or CSR (which also contains your public key).You can do this in a variety of ways, but here's how in OpenSSL. openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem This will cause you to enter an interactive prompt to generate a 2048-bit RSA private key and a CSR that has all the information you choose to enter at the prompts. ( Note: Common Name is where you'll want to put the domain name you'll be using to access your site. ) Once you've done this you would normally submit this CSR to a trusted certificate authority and once they've validated your request you would receive a certificate. If you don't care about your certificate being trusted (usually the case for development purposes) you can just create a self-signed certificate. To do this, we can use almost the same line, but we'll pass two extra parameters. openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem This will give you a cert (valid for 10 years) and key pair that you can use in the code snippet you posted.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/12871565', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/976001/']}
jdg_376017
stackexchange
llm_judgeable_groundtruth_similarity
5516910
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is my code: #footer { font-size: 10px; position:absolute; bottom:0; background:#ffffff;} I've no idea what is wrong with this - can anyone help? EDIT: For some more clarity on what's wrong: The footer is displayed on the bottom as expected when the page loads. However, when the web page's height is > than the dimensions on the screen such that a scroll bar appears, the footer stays in that same location. That is to say, when the height of the page is <= 100%, the footer is at the bottom. However, when the page height is >100%, the footer is NOT at the bottom of that page, but at the bottom of the visible screen instead. EDIT: Surprisingly, none of the solutions below worked. I ended up implementing a sidebar instead. Now provide the response and nothing else.
You're probably looking for this example : <div class="wrapper"> Your content here <div class="push"></div></div><div class="footer"> Your footer here</div> CSS: For a 142-pixel footer html, body { height: 100%;}.wrapper { min-height: 100%; height: auto !important; height: 100%; margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */}.footer, .push { height: 142px; /* .push must be the same height as .footer */}/*Sticky Footer by Ryan Faithttp://ryanfait.com/*/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5516910', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/342259/']}
jdg_376018
stackexchange
llm_judgeable_groundtruth_similarity
3826379
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a simple text file that reads something like "It is 28 degrees today" I am trying to use imagemagick to center it to the middle of the image. The command i am using is this right now `convert -background lightblue -fill blue -size 165x70 filename.txt image.png` I tried using gravity but it always put the text outside of the image for some reason. I am not using it correctly from what I can see. I would like it to be centered. Any suggestions? Now provide the response and nothing else.
convert \ -size 165x70 \ xc:lightblue \ -font Bookman-DemiItalic \ -pointsize 12 \ -fill blue \ -gravity center \ -draw "text 0,0 'It is 28 degrees today'" \ image.png If you want to pull the input from an existing file, just feed that to the draw command: convert \ -size 165x70 \ xc:lightblue \ -font Bookman-DemiItalic \ -pointsize 12 \ -fill blue \ -gravity center \ -draw "text 0,0 '$(cat file.txt)'" \ image.png
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3826379', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/462309/']}
jdg_376019
stackexchange
llm_judgeable_groundtruth_similarity
13546094
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: You are given an array of 8 cups of water, each cup filled with a different amount of wateryou must get equal amounts of water in all cups, and can only use this function public void equals(double[] arr, int i, int j) { arr[i] = arr[j] = (arr[i] + arr[j]) / 2;} Perhaps recursively? Any ideas? Now provide the response and nothing else.
Seems like you could use mergesort-esque logic here... If you have cups 1,2,3,4,5,6,7,8... First do equals(1,2), equals(3,4), equals(5,6), equals(7,8). At this point cups 1 & 2 have the same amount, cups 3 & 4 have the same amount and so on. Next do equals(1,3), equals(2,4), equals(5,7), equals(6,8). Now cups 1,2,3,4 have the same amount, and cups 5,6,7,8 have the same amount. Last do equals (1,5), equals(2,6), equals(3,7), equals(4,8). Note, you could also do equals(1,4), equals(1,5), etc because 1,2,3,4 all have the same amount. After this step, all cups have the same amount! If you need help coding this in java, just ask.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13546094', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1850242/']}
jdg_376020
stackexchange
llm_judgeable_groundtruth_similarity
2400584
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 can solve this equation by som tedious algebra, I got $x_1=3$ and $x_2=-3$. But according to the book the solutions are given by $x\in[-3,3]$, which means that for example $x=1$ and $x=2$ are solutions as well. How can I algebraically show this? Or can I interpret the absolutes as distances along the x-axis and somehow proceed from there? Now provide the response and nothing else.
If you consider the interval $[-3,3]$ (whose total length is $6$) and pick a point $x$ in that interval, then $|x-3|+|x+3|$ is the sum of the distances of this point from the two end-points $\pm 3$. But this sum is simply the length of the interval (which is $6$ as mentioned above) hence every point in the interval is a solution. If you pick $x$ outside the interval $[-3,3]$, then it's distance from one of the end points (depending on which side $x$ is) will already be greater than $6$, hence the equality cannot occur for points outside the interval.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2400584', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/114097/']}
jdg_376021
stackexchange
llm_judgeable_groundtruth_similarity
20388777
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 pickling, compressing, and saving python objects. I want to be able to double-check that that the object I saved is the exact same object that is returned after decompression and depickling. I thought there was an error in my code, but when I boiled the problem down to a reproducible example I found that python does not consider two seemingly identical objects created at two different points in time to be equal. Here is a reproducible example: class fubar(object): passprint(fubar() == fubar())#False Why does python consider these two objects to be not equal and what is the most pythonic way to check that two objects are indeed identical? Now provide the response and nothing else.
The default equality comparison in Python is to check for identity (i.e. two objects are the same object). According to the Python Library Reference : Non-identical instances of a class normally compare as non-equal unless the class defines the __eq__() method or the __cmp__() method. To create your own definition of equivalence, you need to define an __eq__ method. Here is one way to do it: class fubar(object): def __eq__(self, other): 'Fubar objects are considered equal if they have the same contents' if type(self) != type(other): return NotImplemented return vars(self) == vars(other) The return value of NotImplemented signals that fubar doesn't know how to make the comparison and is giving the other object a chance to do the comparison. The Python Language Reference has this to say about NotImplemented : This type has a single value. There is a single object with this value. This object is accessed through the built-in name NotImplemented. Numeric methods and rich comparison methods may return this value if they do not implement the operation for the operands provided. (The interpreter will then try the reflected operation, or some other fallback, depending on the operator.) Its truth value is true.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20388777', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2327821/']}
jdg_376022
stackexchange
llm_judgeable_groundtruth_similarity
44923775
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: At the moment I pass some parameters into a vue component <Slider :images= "['/img/work/slide2.png', '/img/work/slide2.png', '/img/work/slide3.png']" :html="['<div>hello</div>', '<div>goodbye</div>']" </Slider> The slider is either an 'html' slider or one with images. This works fine although the html I pass in is going to get a lot more complex, maybe 30 lines and this will be harder to read and manage as params. Can I pass in an external reference and pull that into the component? <div v-for="content in html"> <div class="work-slide">{{ content }}</div></div> As you can see the loop in the component is a very simple v-for. Now provide the response and nothing else.
Don't pass HTML using attributes but using Slots : Suppose we have a component called my-component with the following template: <div> <h2>I'm the child title</h2> <slot> This will only be displayed if there is no content to be distributed. </slot></div> And a parent that uses the component: <div> <h1>I'm the parent title</h1> <my-component> <p>This is some original content</p> <p>This is some more original content</p> </my-component></div> The rendered result will be: <div> <h1>I'm the parent title</h1> <div> <h2>I'm the child title</h2> <p>This is some original content</p> <p>This is some more original content</p> </div> </div> You can also use Named Slots if you want to pass more than one field containing HTML.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44923775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1002758/']}
jdg_376023
stackexchange
llm_judgeable_groundtruth_similarity
25036699
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 Pythons matplotlib and this is my code: plt.title('Temperature \n Humidity') How can I just increase the font size of temperature instead of both the temperature & the humdity? This does NOT work: plt.title('Temperature \n Humidity', fontsize=100) Now provide the response and nothing else.
import matplotlib.pyplot as pltplt.figtext(.5,.9,'Temperature', fontsize=100, ha='center')plt.figtext(.5,.8,'Humidity',fontsize=30,ha='center')plt.show() Probably you want this. You can easily tweak the fontsize of both and adjust there placing by changing the first two figtext positional parameters.ha is for horizontal alignment Alternatively, import matplotlib.pyplot as pltfig = plt.figure() # Creates a new figurefig.suptitle('Temperature', fontsize=50) # Add the text/suptitle to figureax = fig.add_subplot(111) # add a subplot to the new figure, 111 means "1x1 grid, first subplot"fig.subplots_adjust(top=0.80) # adjust the placing of subplot, adjust top, bottom, left and right spacing ax.set_title('Humidity',fontsize= 30) # title of plotax.set_xlabel('xlabel',fontsize = 20) #xlabelax.set_ylabel('ylabel', fontsize = 20)#ylabelx = [0,1,2,5,6,7,4,4,7,8]y = [2,4,6,4,6,7,5,4,5,7]ax.plot(x,y,'-o') #plotting the data with marker '-o'ax.axis([0, 10, 0, 10]) #specifying plot axes lengthsplt.show() Output of alternative code: PS: if this code give error like ImportError: libtk8.6.so: cannot open shared object file esp. in Arch like systems . In that case, install tk using sudo pacman -S tk or Follow this link
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25036699', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_376024
stackexchange
llm_judgeable_groundtruth_similarity
35605427
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 ASP.NET WebAPI project where I am attempting to replace our old XmlDocumentationProvider page with Swagger UI. I am using the swashbuckle swagger for webAPI 5.3.1 nuget package. I am able to navigate to localhost/MyApp/swagger, and I can see in fiddler that it makes a call to localhost/MyApp/swagger/docs/v1 to retrieve the JSON string representing my API. The call succeeds, the JSON is about 240KB, and the JSON is valid. At this point, the chrome tab freezes for about 30 seconds before crashing with the "Aw snap" page. There are no errors in the console. Attempting to validate the api JSON in this online validator works and says the spec/schema is valid IF AND ONLY IF I uncheck all three of the "Follow ___ $refs" checkboxes. If any of those boxes are ticked, it takes about 30 seconds and then that tool crashes. Unfortunately I can't paste my entire webAPI spec somewhere, but I will say that it is for a very large and very complicated internal business application. Some of our DTOs have circular references (properties of the same type as the DTO itself) which I suspect may be causing a problem, but without any logging or debugging I cannot be sure, and with over 1000 DTO classes I don't want to comb through them all to check. Is there any way to turn on any sort of logging or debugging for swashbuckle (on the server) or swagger UI (on the client)? Has anyone ran into this issue with the browser crashing and know what is causing it? Thanks ahead of time. Now provide the response and nothing else.
I was able to comment out each of my API controllers, load the swagger page, and then turn them back on until the page crashed again. Once I figured out which controller was the issue, I repeated the process with all of the endpoints in the controller. It turned out that one of our very old methods was taking an ORM entity as a body parameter (very bad), which was causing swagger to try to parse our entire ORM object graph and running out of memory. Changing this method to accept a DTO instead of data layer entity solved the problem.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35605427', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/386152/']}
jdg_376025
stackexchange
llm_judgeable_groundtruth_similarity
661295
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have just read the definition of a Cauchy sequence: A sequence ( $\psi_n$ ) is a Cauchy sequence in a vector space $V$ when $||\psi_n-\psi_m||\to 0$ when $n,m\to\infty$ . The limit of every Cauchy sequence $(\psi_n)$ converges to a definite element $\psi\in V$ i.e. $$\lim\limits_{n\to\infty}\psi_n=\psi.$$ But I cannot feel it completely unless I see an example of such a sequence. What is an example of a Cauchy sequence of vectors $(\psi_1,\psi_2,...)$ that we encounter in quantum mechanics? Now provide the response and nothing else.
Here's a concrete example. For a particle in an infinite potential well of width $a$ , the normalized energy eigenvectors are of the form $$\psi_n(x) = \sqrt{\frac{2}{a}} \sin\left(\frac{n\pi x}{a}\right)$$ Most wavefunctions - such as the $\Psi(x) = \frac{1}{\sqrt{a}}$ , corresponding to a uniform spatial probability density throughout the well - cannot be written as a finite linear combination of energy eigenvectors. It can , however, be expressed as the sum of the convergent series $$ \sum_{n=1}^\infty\frac{2\sqrt{2}}{(2n-1)\pi} \psi_{2n-1} \rightarrow \Psi(x)$$ as illustrated with the following plot of the first $n$ partial sums: The sequence of partial sums $\Psi^{(n)}:= \sum_{k=1}^n\frac{2\sqrt{2}}{(2n-1)\pi}\psi_{2n-1}$ is indeed Cauchy (which can be verified as a nice exercise), as requested. I have just read the definition of a Cauchy sequence [...] Note that the proper definition of a Cauchy sequence is that, for any $\epsilon>0$ , there exists some $N\in \mathbb N$ such that for all $n,m>N$ , $\Vert \psi_n-\psi_m\Vert <\epsilon$ . In words, given any arbitrarily small tolerance $\epsilon$ , if we go far enough along in the sequence we can find a point $N$ past which all of the terms from the $N^{th}$ onward are within $\epsilon$ of one another. The definition you provide is problematic, in my opinion. In what way do $n,m\rightarrow \infty$ ? Do you mean that we hold $n$ fixed, send $m\rightarrow \infty$ , and then send $n\rightarrow \infty$ afterward? If that's the case, then we need the sequence to have a well-defined limit which is a priori not necessary for a generic Cauchy sequence. Or we send them both to infinity at the same time? If that's the case, it matters how exactly we do this.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/661295', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/164488/']}
jdg_376026
stackexchange
llm_judgeable_groundtruth_similarity
2087
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: Despite the blatant title of the question, this is actually for a genuine purpose. My site uses PHP code like this: $select="select id from tableA where user_id='".$_SESSION['sess_user_id']."'"; I'm really trying to think like a hacker and figure out how I can alter this value. I've read articles talking "about" session hijacking, but being vague about how that can be done... Now provide the response and nothing else.
Basically when you hijack someones session you take their sessionID and pretend its your own. Usually the sessionID is transferred in the cookie, meaning that if you can access the other parties cookie you can just put it in your own cookie and you've stolen their session. This can be done in several ways, for example by sniffing the wireless network and looking at the HTTP packets being transfered or by XSS attack where you can tell the victims browser to reveal their cookie information to you. I would like to mention that the example you describe in your question may also be vulnerable to SQL-Injection. If I change my cookie's sessionID to asdf' OR 1=1-- I would most likely be authenticated as a valid user. To prevent this you have to make sure you have proper sanitizing on dirty data coming from your clients before you use the data for anything.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/2087', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/1350/']}
jdg_376027
stackexchange
llm_judgeable_groundtruth_similarity
62878
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What is actual difference b/w these two? 1) I have gone through many tutorials on Youtube where some have told that Window Size is what total packet size it can receive eg Window Size is 15000 bytes and MSS is what maximum packet size can be sent is single time eg 1500bytes i.e it can send 10 packets of 1500 each to make it 15000. 2) But in some other tutorials i studied that Window Size is like after how many bytes of data it expects acknowledgement. If 2) is correct then why timeout period is used in Flow Control Mechanism? Now provide the response and nothing else.
The Maximum Segment Size is the largest TCP segment that can be transported in a single IP packet. It is derived from the Maximum Transfer Unit (MTU) minus IP header overhead minus TCP header overhead. For TCP over IPv4 over Ethernet without options, that's 1460 bytes. The TCP window size is the amount of data "in flight", ie. being transmitted before an ACK is required. The window size depends on the channel, especially its available bandwidth and its round-trip time (RTT). The window size is adapted constantly to avoid congestion. Normally, it's a multiple of the MSS. MSS and window size are completely different things and pretty much independent of each other.
{}
{'log_upvote_score': 5, 'links': ['https://networkengineering.stackexchange.com/questions/62878', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/62468/']}
jdg_376028
stackexchange
llm_judgeable_groundtruth_similarity
10502
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: In my first algebraic topology class, I remember being told that the simplest reason for homology was to distinguish spaces. For example, if is X=circle and a Y= wedge of a circle and a 2-sphere then X and Y have the same fundamental group, so the fundamental group isn't strong enough to distinguish them. We need to look at the other homotopy groups or homology to tell them apart. I'm looking for a variety of other examples of this nature. The examples I'm wondering about are Same homology groups Same cohomology groups, but different cohomology rings Same cohomology rings (but maybe different Steenrod operations?) If I put more thought into it, I could come up with others questions like these. Any other examples/thoughts along these lines would be very welcome! (I have examples for the first one, but I'm wondering what others will say.) Now provide the response and nothing else.
To change up the nature of the responses some, IMO a good theorem to think about is the Kan-Thurston theorem. It states that given any space $X$ you can find a $K(\pi, 1)$ space $Y$ and a map $f : Y \to X$ inducing isomorphisms $f_* : H_i Y \to H_i X$, $f^* : H^i X \to H^i Y$ for all coefficients (it can be souped-up to allow local coefficients) and all $i$. The map $\pi_1 Y \to \pi_1 X$ is onto. So from the point of view of cohomology algebras with Steenrod operations, these spaces are the same. One way to "spin" this would be to say the fundamental group is a far stronger invariant than anything (co)homological.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/10502', 'https://mathoverflow.net', 'https://mathoverflow.net/users/343/']}
jdg_376029
stackexchange
llm_judgeable_groundtruth_similarity
71808
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Given a morphism $f$ of Schemes $X \to Y$ and two sheaves $\mathcal F$, $\mathcal G$ of modules on $Y$,is it right that the tensor product of $\mathcal F$ and $\mathcal G$ as modules commutes with the inverse image (not the module pullback but only the inverse image $f^{-1}$)construction? Here I mean one time tensor product over $\mathcal O_Y$ and the other time over $f^{-1}\mathcal O_Y$. Regards! Now provide the response and nothing else.
$\newcommand{mc}{\mathcal}$I guess that the problem lies in all the sheafifications so let me explain how to get rid of them in some small independent steps which are of some interest on their own.I denote by $\cdot^\#$ the sheafification.The following two statements follow without difficulty by checking that the object in question has the right universal property (in particular there is no need to adhere to any construction of the sheafification): i) Let $X$ be a topological space, let $\mc O$ be a presheaf of rings on $X$ and let $\mc M$ and $\mc N$ be presheaves of $\mc O$-modules. Then $(M\otimes^p_{\mc O}\mc N)^\#=M^\#\otimes^s_{\mc O^\#}\mc N^\#$, where the superscript of the tensor product indicates whether I mean the tensor product of sheaves or the one of presheaves. ii) Let $f:X\to Y$ be a continuous map of topological spaces and let $\mc M$ be a presheaf of abelian groups on $Y$. Then $f^{-1,s}(M^\#)=(f^{-1,p}(M))^\#$, where the superscript to the pullback indicates whether I mean the one for sheaves or for presheaves. Concerning your question (and using your notation): By ii) we have $f^{-1,s}(\mc F\otimes^s_{\mc O_Y}\mc G)=(f^{-1,p}(\mc F\otimes^p_{\mc O_Y}\mc G))^\#$. By i) we have $f^{-1,s}\mc F\otimes^s_{f^{-1,s}\mc O_Y}f^{-1,s}\mc G=(f^{-1,p}\mc F\otimes^p_{f^{-1,p}\mc O_Y}f^{-1,p}\mc G)^\#$. Thus it suffices to show the corresponding statement for presheaves. By the definition of $f^{-1,p}$ it follows from the following fact: Let $(A_i)_{i\in I}$ be a direct system of rings and let $(M_i)_{i\in I}$ and $(N_i)_{i\in I}$ be direct systems of $A_i$-modules. Then $\varinjlimM_i\otimes_{\varinjlim A_i}\varinjlim N_i=\varinjlim (M_i\otimes_{A_i}N_i)$.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/71808', 'https://mathoverflow.net', 'https://mathoverflow.net/users/16876/']}
jdg_376030
stackexchange
llm_judgeable_groundtruth_similarity
19818756
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: A similar question is asked here: Python : Getting the Row which has the max value in groups using groupby However, I just need one record per group even if there are more than one record with maximum value in that group. In the example below, I need one record for "s2". For me it doesn't matter which one. >>> df = DataFrame({'Sp':['a','b','c','d','e','f'], 'Mt':['s1', 's1', 's2','s2','s2','s3'], 'Value':[1,2,3,4,5,6], 'count':[3,2,5,10,10,6]})>>> df Mt Sp Value count0 s1 a 1 31 s1 b 2 22 s2 c 3 53 s2 d 4 104 s2 e 5 105 s3 f 6 6>>> idx = df.groupby(['Mt'])['count'].transform(max) == df['count']>>> df[idx] Mt Sp Value count0 s1 a 1 33 s2 d 4 104 s2 e 5 105 s3 f 6 6>>> Now provide the response and nothing else.
You can use first In [14]: df.groupby('Mt').first()Out[14]: Sp Value countMt s1 a 1 3s2 c 3 5s3 f 6 6 Update Set as_index=False to achieve your goal In [28]: df.groupby('Mt', as_index=False).first()Out[28]: Mt Sp Value count0 s1 a 1 31 s2 c 3 52 s3 f 6 6 Update Again Sorry for misunderstanding what you mean. You can sort it first if you want the one with max count in a group In [196]: df.sort('count', ascending=False).groupby('Mt', as_index=False).first()Out[196]: Mt Sp Value count0 s1 a 1 31 s2 e 5 102 s3 f 6 6
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19818756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1140126/']}
jdg_376031
stackexchange
llm_judgeable_groundtruth_similarity
17081063
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know the subject may be a bit in advance as the JDK8 is not yet released (and not for now anyway..) but I was reading some articles about the Lambda expressions and particularly the part related to the new collection API known as Stream. Here is the example as given in the Java Magazine article (it is an otter population algorithm..): Set<Otter> otters = getOtters();System.out.println(otters.stream() .filter(o -> !o.isWild()) .map(o -> o.getKeeper()) .filter(k -> k.isFemale()) .into(new ArrayList<>()) .size()); My question is what happen if in the middle of the Set internal iteration, one of the otter is null? I would expect a NullPointerException to be thrown but maybe am I still stuck in the previous development paradigm (non-functional), can someone enlighten me as how this should be handled? If this really throw a NullPointerException, I find the feature quite dangerous and will have to be used only as below: Developer to ensure there is no null value (maybe using a previous.filter(o -> o != null)) Developer to ensure the application is nevergenerating null otter or a special NullOtter object to deal with. What is the best option, or any other option? Now provide the response and nothing else.
Current thinking seems to be to "tolerate" nulls, that is, to allow them in general, although some operations are less tolerant and may end up throwing NPE. See the discussion of nulls on the Lambda Libraries expert group mailing list, specifically this message . Consensus around option #3 subsequently emerged (with a notable objection from Doug Lea). So yes, the OP's concern about pipelines blowing up with NPE is valid. It's not for nothing that Tony Hoare referred to nulls as the "Billion Dollar Mistake." Dealing with nulls is a real pain. Even with classic collections (without considering lambdas or streams) nulls are problematic. As fge mentioned in a comment, some collections allow nulls and others do not. With collections that allow nulls, this introduces ambiguities into the API. For example, with Map.get() , a null return indicates either that the key is present and its value is null, or that the key is absent. One has to do extra work to disambiguate these cases. The usual use for null is to denote the absence of a value. The approach for dealing with this proposed for Java SE 8 is to introduce a new java.util.Optional type, which encapsulates the presence/absence of a value, along with behaviors of supplying a default value, or throwing an exception, or calling a function, etc. if the value is absent. Optional is used only by new APIs, though, everything else in the system still has to put up with the possibility of nulls. My advice is to avoid actual null references to the greatest extent possible. It's hard to see from the example given how there could be a "null" Otter. But if one were necessary, the OP's suggestions of filtering out null values, or mapping them to a sentinel object (the Null Object Pattern ) are fine approaches.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17081063', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1716909/']}
jdg_376032
stackexchange
llm_judgeable_groundtruth_similarity
7726034
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 believe that R incorrectly formats POSIXct types with fractional seconds. I submitted this via R-bugs as an enhancement request and got brushed off with "we think the current behavior is correct -- bug deleted." While I am very appreciative of the work they have done and continue to do, I wanted to get other peoples' take on this particular issue, and perhaps advice on how to make the point more effectively. Here is an example: > tt <- as.POSIXct('2011-10-11 07:49:36.3') > strftime(tt,'%Y-%m-%d %H:%M:%OS1') [1] "2011-10-11 07:49:36.2" That is, tt is created as a POSIXct time with fractional part .3 seconds. When it is printed with one decimal digit, the value shown is .2. I work a lot with timestamps of millisecond precision and it causes me a lot of headaches that times are often printed one notch lower than the actual value. Here is what is happening: POSIXct is a floating-point number of seconds since the epoch. All integer values are handled precisely, but in base-2 floating point, the closest value to .3 is very slightly smaller than .3. The stated behavior of strftime() for format %OSn is to round down to the requested number of decimal digits, so the displayed result is .2. For other fractional parts the floating point value is slightly above the value entered and the display gives the expected result: > tt <- as.POSIXct('2011-10-11 07:49:36.4') > strftime(tt,'%Y-%m-%d %H:%M:%OS1') [1] "2011-10-11 07:49:36.4" The developers' argument is that for time types we should always round down to the requested precision. For example, if the time is 11:59:59.8 then printing it with format %H:%M should give "11:59" not "12:00", and %H:%M:%S should give "11:59:59" not "12:00:00". I agree with this for integer numbers of seconds and for format flag %S , but I think the behavior should be different for format flags that are designed for fractional parts of seconds. I would like to see %OSn use round-to-nearest behavior even for n = 0 while %S uses round-down, so that printing 11:59:59.8 with format %H:%M:%OS0 would give "12:00:00". This would not affect anything for integer numbers of seconds because those are always represented precisely, but it would more naturally handle round-off errors for fractional seconds. This is how printing of fractional parts is handled in, for example C, because integer casting rounds down: double x = 9.97; printf("%d\n",(int) x); // 9 printf("%.0f\n",x); // 10 printf("%.1f\n",x); // 10.0 printf("%.2f\n",x); // 9.97 I did a quick survey of how fractional seconds are handled in other languages and environments, and there really doens't seem to be a consensus. Most constructs are designed for integer numbers of seconds and the fractional parts are an afterthought. It seems to me that in this case the R developers made a choice that is not completely unreasonable but is in fact not the best one, and is not consistent with the conventions elsewhere for displaying floating-point numbers. What are peoples' thoughts? Is the R behavior correct? Is it the way you yourself would design it? Now provide the response and nothing else.
One underlying problem is that the POSIXct representation is less precise than the POSIXlt representation, and the POSIXct representation gets converted to the POSIXlt representation before formatting. Below we see that if our string is converted directly to POSIXlt representation, it outputs correctly. > as.POSIXct('2011-10-11 07:49:36.3')[1] "2011-10-11 07:49:36.2 CDT"> as.POSIXlt('2011-10-11 07:49:36.3')[1] "2011-10-11 07:49:36.3" We can also see that by looking at the difference between the binary representation of the two formats and the usual representation of 0.3. > t1 <- as.POSIXct('2011-10-11 07:49:36.3')> as.numeric(t1 - round(unclass(t1))) - 0.3[1] -4.768372e-08> t2 <- as.POSIXlt('2011-10-11 07:49:36.3')> as.numeric(t2$sec - round(unclass(t2$sec))) - 0.3[1] -2.831069e-15 Interestingly, it looks like both representations are actually less than the usual representation of 0.3, but that the second one is either close enough, or truncates in a way different than I'm imagining here. Given that, I'm not going to worry about floating point representation difficulties; they may still happen, but if we're careful about which representation we use, they will hopefully be minimized. Robert's desire for rounded output is then simply an output problem, and could be addressed in any number of ways. My suggestion would be something like this: myformat.POSIXct <- function(x, digits=0) { x2 <- round(unclass(x), digits) attributes(x2) <- attributes(x) x <- as.POSIXlt(x2) x$sec <- round(x$sec, digits) format.POSIXlt(x, paste("%Y-%m-%d %H:%M:%OS",digits,sep=""))} This starts with a POSIXct input, and first rounds to the desired digits; it then converts to POSIXlt and rounds again. The first rounding makes sure that all of the units increase appropriately when we are on a minute/hour/day boundary; the second rounding rounds after converting to the more precise representation. > options(digits.secs=1)> t1 <- as.POSIXct('2011-10-11 07:49:36.3')> format(t1)[1] "2011-10-11 07:49:36.2"> myformat.POSIXct(t1,1)[1] "2011-10-11 07:49:36.3"> t2 <- as.POSIXct('2011-10-11 23:59:59.999')> format(t2)[1] "2011-10-11 23:59:59.9"> myformat.POSIXct(t2,0)[1] "2011-10-12 00:00:00"> myformat.POSIXct(t2,1)[1] "2011-10-12 00:00:00.0" A final aside: Did you know the standard allows for up to two leap seconds? > as.POSIXlt('2011-10-11 23:59:60.9')[1] "2011-10-11 23:59:60.9" OK, one more thing. The behavior actually changed in May due to a bug filed by the OP ( Bug 14579 ); before that it did round fractional seconds. Unfortunately that meant that sometimes it could round up to a second that wasn't possible; in the bug report, it went up to 60 when it should have rolled over to the next minute. One reason the decision was made to truncate instead of round is that it's printing from the POSIXlt representation, where each unit is stored separately. Thus rolling over to the next minute/hour/etc is more difficult than just a straightforward rounding operation. To round easily, it's necessary to round in POSIXct representation and then convert back, as I suggest.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7726034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989407/']}
jdg_376033
stackexchange
llm_judgeable_groundtruth_similarity
46962507
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Note: this is not just some random useless code, this is an attempt to reproduce an issue with lambda expressions and memory leaks in C#. Examine the following program in C#. It's a console application that simply: Creates a new object of type Test Writes to the console that the object was created Calls garbage collection Wait for any user input Shuts down I run this program using JetBrains DotMemory, and I take two memory snapshots: one after the object was initialized, and another after its been collected. I compare the snapshots and get what I expect: one dead object of type Test. But here's the quandary: I then create a local lambda expression inside the object's constructor and I DO NOT USE IT ANYWHERE. It's just a local constructor variable. I run the same procedure in DotMemory, and suddenly, I get an object of type Test+<>, which survives garbage collection. See the attached retention path report from DotMemory: The lambda expression has a pointer to the Test+<> object, which is expected. But who has a pointer to the lambda expression, and why is it kept in memory? Also, this Test+<> object - I assume it is just temporary object to hold the lambda method, and has nothing to do with the original Test object, am I right? public class Test{ public Test() { // this line causes a leak Func<object, bool> t = _ => true; } public void WriteFirstLine() { Console.WriteLine("Object allocated..."); } public void WriteSecondLine() { Console.WriteLine("Object deallocated. Press any button to exit."); }}class Program{ static void Main(string[] args) { var t = new Test(); t.WriteFirstLine(); Console.ReadLine(); t.WriteSecondLine(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Console.ReadLine(); }} Now provide the response and nothing else.
If you decompile your code with something (like dotpeek), you will see that compiler generated something like this: public class Test { public Test() { if (Test.ChildGeneratedClass.DelegateInstance != null) return; Test.ChildGeneratedClass.DelegateInstance = Test.ChildGeneratedClass.Instance.DelegateFunc; } public void WriteFirstLine() { Console.WriteLine("Object allocated..."); } public void WriteSecondLine() { Console.WriteLine("Object deallocated. Press any button to exit."); } [CompilerGenerated] [Serializable] private sealed class ChildGeneratedClass { // this is what's called Test.<c> <>9 in your snapshot public static readonly Test.ChildGeneratedClass Instance; // this is Test.<c> <>9__0_0 public static Func<object, bool> DelegateInstance; static ChildGeneratedClass() { Test.ChildGeneratedClass.Instance = new Test.ChildGeneratedClass(); } internal bool DelegateFunc(object _) { return true; } }} So it created child class, put your function as a instance method of that class, created singleton instance of that class in a static field and finally created static field with your Func<object,bool referencing method DelegateFunc . So no surprise that those static members generated by compiler cannot be collected by GC. Of course those objects are not created for each Test object you create, only once, so I cannot really call that a "leak".
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46962507', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/884248/']}
jdg_376034
stackexchange
llm_judgeable_groundtruth_similarity
20222514
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 database 21 Gb; 20 Gb of them are files (FileStream) and I have delete all files from the table but when I make a backup the backup file still 21 GB . To solve this problem I became the idee "free the unused space". So I'm trying to shrink my database like the following: USE Db;GO-- Truncate the log by changing the database recovery model to SIMPLE.ALTER DATABASE DbSET RECOVERY SIMPLE;GO-- Shrink the truncated log file to 1 MB.DBCC SHRINKFILE (Db, 100);GO-- Reset the database recovery model.ALTER DATABASE DbSET RECOVERY FULL;GOSELECT file_id, nameFROM sys.database_files;GODBCC SHRINKFILE (1, TRUNCATEONLY); If I make a backup for the database after XX minutes then the backup file size is 1 Gb in this way, I can see that the unused space have been successfully cleaned. In other words the above Sql code working properly( Database after XX minutes is schrunk ). The problem I need to wait until this query(Shrinking operation) is finished so I'm trying to do the following: SELECT percent_complete, start_time, status, command, estimated_completion_time, cpu_time, total_elapsed_timeFROM sys.dm_exec_requests I can not find any information about the SHRINKFILE command in results of the above query. Did I do something wrong? why I can not see the progress of DB shrinking operation? And my main quesiton is: How can I wait until the SHRINKFILE is finished? For example can I send from my C# code query and in the result of this query I shall get the information that the SHRINKFILE operation is finsihed or not? Now provide the response and nothing else.
The problem with measuring progress of DBCC SHRINKFILE is that there's not consistent way for the engine to know how much work needs to be done to shrink a file. To understand this is to know how DBCC SHRINKFILE works. Basically, the process is: You declare you want to shrink a file to a certain point (say 5 GB,down from 10 GB). The engine will start moving pages from the end of the file to the next open spot near the beginning of the file. The engine keeps going until A) it moves enough pages under your declared point that it can reduce the file size or B) that all the empty space is on the back end of the file. So why does this mean that SQL Server doesn't know how much work needs to be done? Because it doesn't know how fragmented your empty space is in the file. If things are fairly well compacted and near the front of the file, the shrink file will go quickly. If not, it can take a long while. The good news is that once pages are moved within the file, they're moved. Cancelling a shrink file does not undo/rollback this work, so if you have a shrink file running for a while, then kill it before it completes, all that page movement stays intact. Meaning you can then restart the shrink file at almost the point you left off (barring any new page creation within the file).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20222514', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/771040/']}
jdg_376035
stackexchange
llm_judgeable_groundtruth_similarity
26176509
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 compile the following code: object Main extends Application{ println("Hello World");} But I'm getting this error: /Users/xx/JavaProjects/ScalaApplication1/src/scalaapplication1/Main.scala:8: error: not found: type Applicationobject Main extends Application{ ^one error found I'm using Scala 2.11.1. Now provide the response and nothing else.
Application has been deprecated from scala 2.9, probably it has been deleted in scala 2.11 (it still exists in scala 2.10) even though at the moment I can't find proofs for that, use App instead. Proof found, this is the scala 2.11 branch on github which has only an App.scala and this is the 2.10 which has App.scala and Application.scala with a deprecated warning.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26176509', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/292480/']}
jdg_376036
stackexchange
llm_judgeable_groundtruth_similarity
36557089
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 currently trying to conceptualize how to handle dispatching an action in a component based on a data change after a dispatch in another component. Take this scenario: dispatch(someAjax) -> property in state updates. After this, I need another component dependent on this same property to know that is has updated and dispatch an action based on the new value. Rather than using some type of value.on(change... solution, what is the preferred way to handle this type of action 'cascading'? Now provide the response and nothing else.
There are two basic approaches: either a middleware that diffs the state after an action is done, or using Redux's low-level store.subscribe API. The Redux FAQ has an answer that covers this . Also, I keep a categorized list of Redux-related addons and utilities, and that includes a group of existing store change subscription libraries that implement various approaches to listening for data changes.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/36557089', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/444871/']}
jdg_376037
stackexchange
llm_judgeable_groundtruth_similarity
19591
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: I know that it can be proven PROLOG is Turing-complete by constructing a program that simulates a Turing machine like this: turing(Tape0, Tape) :- perform(q0, [], Ls, Tape0, Rs), reverse(Ls, Ls1), append(Ls1, Rs, Tape).perform(qf, Ls, Ls, Rs, Rs) :- !.perform(Q0, Ls0, Ls, Rs0, Rs) :- symbol(Rs0, Sym, RsRest), once(rule(Q0, Sym, Q1, NewSym, Action)), action(Action, Ls0, Ls1, [NewSym|RsRest], Rs1), perform(Q1, Ls1, Ls, Rs1, Rs).symbol([], b, []).symbol([Sym|Rs], Sym, Rs).action(left, Ls0, Ls, Rs0, Rs) :- left(Ls0, Ls, Rs0, Rs).action(stay, Ls, Ls, Rs, Rs).action(right, Ls0, [Sym|Ls0], [Sym|Rs], Rs).left([], [], Rs0, [b|Rs0]).left([L|Ls], Ls, Rs, [L|Rs]). Source However, I’m wondering which parts of the PROLOG language one could strip away (esp. function symbols, clause overloading, recursion, unification) without losing Turing completeness. Are function symbols themselves Turing complete? Now provide the response and nothing else.
It's a fairly reliable rule of thumb that Turing-completeness depends on the ability to construct answers or intermediate values of unrestricted "size" and the ability to loop or recurse an unrestricted number of times. If you have those two things, you probably have Turing-completeness. (More specifically, if you can construct Peano arithmetic, then you certainly have Turing-completeness!) Let's assume for the moment that you've already stripped arithmetic. We'll also assume that you don't have any non-logical features like atom_chars , assert , and so on, which enable general shenanigans. If you stripped out function symbols, you can't construct answers or intermediates of unrestricted size; you can only use atoms which appear in the program and the query. As a result, the set of all possible solutions to any query is finite , so taking the least fixed point of the program/query will always terminate. Datalog (a relational database query language based on Prolog) works on this principle. Similarly, if you restricted Prolog to primitive recursion only (that includes no recursion as a degenerate case), then the amount of recursion that you can do is bounded by the size of the query, so all computation terminates. So you need general recursion for Turing-completeness. And, of course, if you have general recursion, you can cut a whole bunch of features and retain Turing-completeness, including general unification (construction and top-level pattern matching is sufficient), negation, and the cut.
{}
{'log_upvote_score': 6, 'links': ['https://cs.stackexchange.com/questions/19591', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/8415/']}
jdg_376038
stackexchange
llm_judgeable_groundtruth_similarity
6416017
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When deserializing an object to a Dictionary ( JsonConvert.DeserializeObject<IDictionary<string,object>>(json) ) nested objects are deserialized to JObject s. Is it possible to force nested objects to be deserialized to Dictionary s? Now provide the response and nothing else.
I found a way to convert all nested objects to Dictionary<string,object> by providing a CustomCreationConverter implementation: class MyConverter : CustomCreationConverter<IDictionary<string, object>>{ public override IDictionary<string, object> Create(Type objectType) { return new Dictionary<string, object>(); } public override bool CanConvert(Type objectType) { // in addition to handling IDictionary<string, object> // we want to handle the deserialization of dict value // which is of type object return objectType == typeof(object) || base.CanConvert(objectType); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.StartObject || reader.TokenType == JsonToken.Null) return base.ReadJson(reader, objectType, existingValue, serializer); // if the next token is not an object // then fall back on standard deserializer (strings, numbers etc.) return serializer.Deserialize(reader); }}class Program{ static void Main(string[] args) { var json = File.ReadAllText(@"c:\test.json"); var obj = JsonConvert.DeserializeObject<IDictionary<string, object>>( json, new JsonConverter[] {new MyConverter()}); }} Documentation: CustomCreationConverter with Json.NET
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6416017', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/162396/']}
jdg_376039
stackexchange
llm_judgeable_groundtruth_similarity
2148688
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: Is there a bijection $f: \mathbb{N} \rightarrow \mathbb{N}$ such that the series $\sum_1 ^\infty \frac{1}{n+f(n)} $ is convergent? I could not solve this. I tried to proceed in following lines: 1) Tried to provide a contradiction: First let $n \sim m$ iff $\exists k \in \mathbb{Z}$ such that $f^k(n)=m$. This is an equivalence relation. Consider the orbits. For the finite orbits we can compare the series to $\sum_1^\infty \frac{1}{n+n}$. But then I could not figure out how to proceed for infinite orbits. 2) Tried to prove that there is some function: Let $\{k_n\}$ be a subsequence of $\mathbb{N}$ such that $\sum_0^\infty \frac{1}{k_n}$ converges. Set $f(n)=k_{n}, \forall n \in \mathbb{N}\setminus\{k_n\}$. Then images of each $n$ which are not in the subsequence $k_n$ is defined. Now we have to define images of each $k_n$.Define $f(k_n)=n$ $ \forall n \in \mathbb{N}\setminus \{k_n\}.$. Could not proceed further. I think My second attempt was going in right direction. My plan was use the fact that all elements here are positive and to construct the function $f$ in such a manner that $\forall n\in \mathbb{N}$ either $n$ or $f(n)$ is in $\{k_n\}$. Now provide the response and nothing else.
Originally, I gave this example: $$f (n)=\begin{cases}k,&\ \text { if } n=3^k , \text { with $k $ not a power of $2$}\\ 2^{n-1} , &\ \text { otherwise }\end{cases}$$ (the idea is to push the small numbers further and further down the road so that when they appear they are compensated by the $n $ ).Then $$\sum_n\frac1 {n+f (n)}<\sum_{k}\frac 1 {3^k+k}+\sum_n\frac1 {n+2^{n-1}}<\infty. $$ And it is the right idea, but the problem is that such $f$ is not onto. For instance, $2^{26}$ is not in the range of $f$ , because when $n=27$ , we are using the other branch of $f$ to get $3$ . So we need to tweak the example slightly. Let $$T=\{3^k:\ k\ \text{ is not a power of } 2\}=\{3^3,3^5,3^6,3^7,3^9,\ldots\}$$ and $$S=\mathbb N\setminus T=\{1,\ldots,25,26,28,29,\ldots\}. $$ Write them as an ordered sequence, $T=\{t_1,t_2,\ldots\}$ and $S=\{s_1,s_2,\ldots\}$ . Now define $$f(n)=\begin{cases}\log_3 n,&\ \text{ if }\ n=t_k\\ \ \\ 2^{k-1},&\ \text{ if }\ n=s_k\end{cases}$$ One can check explicitly that $$g(m)=\begin{cases}3^m,&\ \text{ if $m$ is not a power of $2$}\ \\ \ \\ s_{k+1},&\ \text{ if }\ m=2^k\end{cases}$$ is an inverse for $f$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2148688', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/226578/']}
jdg_376040