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
24071220
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I'd like to return an HTML page without sending a redirect. The reason being is using a redirect changes the URL in the browser, and I can't redirect someone to the login if they aren't logged in. What's the most straight forward way to do this? Seems like it should be simple without using jsp or other server side view technologies. Now provide the response and nothing else.
You can use forward . Example: say /static/myWebpage.html is your static html page This code will return the content of myWebpage.html without changing the url @Controller@RequestMapping("/path")public class TestingController { @RequestMapping("/page") public String someOtherPage(HttpServletRequest request, HttpServletResponse response) { return "forward:/static/myWebpage.html"; }} Again your url would be "localhost/path/page" but you will be viewing "localhost/static/myWebPage.html"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24071220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/155020/']}
jdg_379741
stackexchange
llm_judgeable_groundtruth_similarity
642329
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 need to test if a family of 7th deg and 13 deg equations are solvable. I'm new to Magma , so my apologies, but what would I type in, http://magma.maths.usyd.edu.au/calc/ to determine the Galois group of $x^5+5x-12=0$ (for example)? Now provide the response and nothing else.
> P< x >:=PolynomialAlgebra(Rationals()); > f:=x^5+5*x-12; > G:=GaloisGroup(f); > print G; Symmetric group G acting on a set of cardinality 5Order = 120 = 2^3 * 3 * 5 Although the permutation group on [1..Degree( $f$ )] is permutationally isomorphic to the Galois group, the bijection with the set of roots of your separable irreducible polynomial $f$ is not determined. For more details see the Magma handbook.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/642329', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/4781/']}
jdg_379742
stackexchange
llm_judgeable_groundtruth_similarity
219094
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: According to the Wikipedia page for key derivation functions , a KDF's purpose is to derive a secret key for cryptography: In cryptography, a key derivation function (KDF) derives one or more secret keys from a secret value such as a master key, a password, or a passphrase using a pseudorandom function.[1][2] KDFs can be used to stretch keys into longer keys or to obtain keys of a required format, such as converting a group element that is the result of a Diffie–Hellman key exchange into a symmetric key for use with AES. Keyed cryptographic hash functions are popular examples of pseudorandom functions used for key derivation.[3] Let's assume we just completed a Curve25519 key exchange, and we want to use the key for a symmetric algorithm, e.g. AES. If the raw shared secret can be used as a key for the symmetric cipher, does using a KDF provide any security benefits? (Assuming that the KDF's output can also be used in the symmetric cipher. If the raw secret cannot be used as a key for the cipher, we apply a KDF to it. In this case, why does the KDF have to be slow? (Or is this property of a KDF just for specific cases, but not this one?) Now provide the response and nothing else.
Not all KDFs are slow! Something like HKDF is extremely fast, and only involves a handful of invocations to the underlying PRF. KDFs are only slow when they're intended to convert a potentially low-entropy input—like a password—to a high-entropy output such as an encryption key or a password verifier. In this scenario, such functions are designed to be slow in order to add computation time as if the attacker were trying to brute force a secret with higher entropy than the one actually used. For something like a shared secret after a Curve25519 key exchange, you would generally prefer a fast KDF. For instance, the Noise protocol framework uses HDKF to generate encryption keys from a shared secret derived from curve multiplication. While you can use a raw shared secret as a key directly, most protocols in practice use some form of a KDF to allow for features like forward secrecy.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/219094', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/-1/']}
jdg_379743
stackexchange
llm_judgeable_groundtruth_similarity
6732124
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Could you please explain the difference between Transfer objects and Domain objects in simple terms ? And if u could give a Java example, that would be great.. Now provide the response and nothing else.
DTOs don't have any logic. They only have fields (state). They are used when transferring data from one layer/subsystem to another Domain objects can have logic (depending on whether you are using domain-driven design or have anemic data model) and they are usually related to the database structure. If using anemic data model (i.e. your domain objects don't have any logic), DTO and domain object can be the same object. Related: http://techblog.bozho.net/?p=427
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6732124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/485743/']}
jdg_379744
stackexchange
llm_judgeable_groundtruth_similarity
27628053
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 write a really simply webapp with PythonAnywhere and Flask that has lets the user upload a text file, generates a csv file, then lets the user download the csv file. It doesn't have to be fancy, it only has to work. I have already written the program for generating the csv from a txt file on the drive. Right now, my function opens the file on the drive with: with open(INPUTFILE, "r") as fname: and writes the csv with: with open(OUTPUTFILE, 'w') as fname: with INPUTFILE and OUTPUTFILE being filename strings. Would it be better for me to handle the files as objects, returned by the flask/html somehow? I don't know how to do this. How should I structure this program? How many HTML Templates do I need? I would prefer to work on the files wihthout saving them anywhere but if I have to save them to the PythonAnywhere directory, I could. How can I do that? Now provide the response and nothing else.
PythonAnywhere dev here. This is a good question about Flask and web development in general rather than specific to our system, so I'll try to give a generic answer without anything specific to us :-) There are a few things that I'd need to know to give a definitive answer to your question, so I'll start by listing the assumptions I'm making -- leave me a comment if I'm wrong with any of them and I'll update the answer appropriately. I'm assuming that the files you're uploading aren't huge and can fit into a reasonable amount of memory -- let's say, smaller than a megabyte. I'm assuming that the program that you've already written to generate the CSV from the text file is in Python, and that it has (or, perhaps more likely, could be easily changed to have) a function that takes a string containing the contents of the text file, and returns the contents that need to be written into the CSV. If both of those are the case, then the best way to structure your Flask app would be to handle everything inside Flask. A code sample is worth a thousand words, so here's a simple one I put together that allows the user to upload a text file, runs it through a function called transform (which is where the function from your conversion program would slot in -- mine just replaces = with , throughout the file), and sends the results back to the browser. There's a live version of this app on PythonAnywhere here . from flask import Flask, make_response, requestapp = Flask(__name__)def transform(text_file_contents): return text_file_contents.replace("=", ",")@app.route('/')def form(): return """ <html> <body> <h1>Transform a file demo</h1> <form action="/transform" method="post" enctype="multipart/form-data"> <input type="file" name="data_file" /> <input type="submit" /> </form> </body> </html> """@app.route('/transform', methods=["POST"])def transform_view(): request_file = request.files['data_file'] if not request_file: return "No file" file_contents = request_file.stream.read().decode("utf-8") result = transform(file_contents) response = make_response(result) response.headers["Content-Disposition"] = "attachment; filename=result.csv" return response Regarding your other questions: Templates: I didn't use a template for this example, because I wanted it all to fit into a single piece of code. If I were doing it properly then I'd put the stuff that's generated by the form view into a template, but that's all. Can you do it by writing to files -- yes you can, and the uploaded file can be saved by using the save( filename ) method on the file object that I'm using the stream property of. But if your files are pretty small (as per my assumption above) then it probably makes more sense to process them in-memory like the code above does. I hope that all helps, and if you have any questions then just leave a comment.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27628053', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3713319/']}
jdg_379745
stackexchange
llm_judgeable_groundtruth_similarity
2773328
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 find the size of an integer array in C. Any method available without traversing the whole array once, to find out the size of the array. Now provide the response and nothing else.
If the array is a global, static, or automatic variable ( int array[10]; ), then sizeof(array)/sizeof(array[0]) works. If it is a dynamically allocated array ( int* array = malloc(sizeof(int)*10); ) or passed as a function argument ( void f(int array[]) ), then you cannot find its size at run-time. You will have to store the size somewhere. Note that sizeof(array)/sizeof(array[0]) compiles just fine even for the second case, but it will silently produce the wrong result.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2773328', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/66593/']}
jdg_379746
stackexchange
llm_judgeable_groundtruth_similarity
6053603
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 I got from JSON [{"photo":null}] and I use this code NSMutableArray *jPhoto = [NSMutableArray arrayWithArray:(NSArray *)[jsonDict valueForKey:@"photo"]]; How can I check it if I want to use if() ?? edit here is JSON Data [{"photo": [{"image":"http:\/\/www.yohyeh.com\/upload\/shisetsu\/13157\/photo\/1304928459.jpg","title":"test picture","content":"this is description for test picture.\r\n\u8aac\u660e\u6587\u306a\u306e\u306b\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb\u30fb"} ,{"image":"http:\/\/www.yohyeh.com\/upload\/shisetsu\/13157\/photo\/1304928115.jpg","title":"nothing","content":"iMirai"} ,{"image":"http:\/\/www.yohyeh.com\/upload\/shisetsu\/13157\/photo\/1303276769.jpg","title":"iMirai","content":"Staff"}]} ] and here is my JSON parser NSError *theError = nil; NSString *URL = [NSString stringWithFormat:@"http://www.yohyeh.com/apps/get_sub_detail.php?id=%@&menu=photo",g_id]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]]; NSURLResponse *theResponse =[[[NSURLResponse alloc]init] autorelease]; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError]; NSMutableString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSDictionary *jsonDict = [string JSONValue]; Thank for help Now provide the response and nothing else.
I believe most JSON parsers represent null as [NSNull null] . Considering jsonDict points to that single element in the array, then the following should work: if ([jsonDict objectForKey:@"photo"] == [NSNull null]) { // it's null} Edit based on comment: so jsonDict , despite its name, is an array. In that case, rename jsonDict to jsonArray to avoid further confusion. Then, considering jsonArray points to an array similar to the example posted in the question: NSArray *photos = [jsonArray valueForKey:@"photo"];for (id photo in photos) { if (photo == [NSNull null]) { // photo is null } else { // photo isn't null }} Further edit based on OP’s modified question: NSArray *jsonArray = [string JSONValue];NSArray *photos = [jsonArray valueForKey:@"photo"];for (id photo in photos) { if (photo == [NSNull null]) { // photo is null } else { // photo isn't null. It's an array NSArray *innerPhotos = photo; … }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6053603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/583018/']}
jdg_379747
stackexchange
llm_judgeable_groundtruth_similarity
4944709
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 in a doubt whether this is a right place for this question..I want to know if windows 7 or xp has any limit on no. of files within particular folder? Now provide the response and nothing else.
There's no practical limit on the combined sizes of all the files in a folder, though there may be limits on the number of files in a folder. More importantly, there are limits on individual file size that depend on what filesystem you're using on your hard disk. (The "filesystem" is nothing more than the specification of exactly how files are store on disk.) Let's break this down by file system: FAT aka FAT16 FAT, for File Allocation Table, is the successor to the original FAT12 filesystem that shipped with MS-DOS many, many years ago. Maximum disk size: 4 gigabytes Maximum file size: 4 gigabytes Maximum number of files on disk: 65,517 Maximum number of files in a single folder: 512 (if I recall correctly, the root folder "/" had a lower limit of 128). FAT32 "There's no practical limit on the combined sizes of all the files in a folder, though there may be limits on the number of files in a folder."FAT32 was introduced to overcome some of the limitations of FAT16. Maximum disk size: 2 terabytes Maximum file size: 4 gigabytes Maximum number of files on disk: 268,435,437 Maximum number of files in a single folder: 65,534 NTFS NTFS, or "New Technology File System" introduced with Windows NT, is a completely redesigned file system. Maximum disk size: 256 terabytes Maximum file size: 256 terabytes Maximum number of files on disk: 4,294,967,295 Maximum number of files in a single folder: 4,294,967,295 Note that when I say "disk" above, I'm really talking about "logical" disks, not necessarily physical. No one makes a 256 terabyte disk drive, but using NTFS you can treat an array of disk drives as a single logical disk. Presumably if you have enough of them, you can build a huge logical drive. Also note that the NTFS's 256 terabyte limitation may well simply be an implementation restriction - I've read that the NTFS format can support disks up to 16 exabytes (16 times 1,152,921,504,606,846,976 bytes). Source : http://ask-leo.com/is_there_a_limit_to_what_a_single_folder_or_directory_can_hold.html
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4944709', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/153541/']}
jdg_379748
stackexchange
llm_judgeable_groundtruth_similarity
61398
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have the fft of some signal, and want a rough estimate of the noise level in order to choose an appropriate threshold for our peak detection algorithm. In general, the fft contains mostly noise with a handful of peaks (which are usually pretty high compared to said noise). For reference, I've attached a screenshot of a pretty typical fft: Now to my proposed algorithm for noise level estimation, which is based on the following assumptions: What i want is the mean and standard deviation of the fft If the fft contained only (gaussian) noise, the median would be very close to the mean Peaks shouldn't affect the median too much The mean and standard deviation are independent of the order of the samples Therefore i can sort the fft and still get the same result So the resulting algorithm looks like this: Sort the fft (ascending) Calculate the mean and standard deviation of the sorted fft, but stop as soon as the mean exceeds the median Use the calculated mean and standard deviation to choose the peak detection threshold Profit? I've tested this algorithm on some typical signals and the results seem to be pretty decent (keeping in mind that i don't need the exact noise level, but just something robust to choose an appropriate threshold). Sorting is a little expensive of course, but i don't expect the noise level to change too much, so i don't need to run it for every fft. That being said, the algorithm itself feels kind of "wrong", because i don't ask the actual question "What would the mean and standard deviation be without the peaks?" but rather "What would the standard deviation be if the mean was X?". So what are your thoughts on this?Are there better algorithms for this kind of problem? (i bet there are) Now provide the response and nothing else.
I'd do some small adjustments to your idea (You really nailed them). Assumptions The Signal Model - Signal + Additive White Gaussian Noise (AWGN) Probably we could generalize it more but this is beyond the scope of this question. The DFT of the signal contains Peaks with relatively small roll off This is important as we're almost saying the Signal is a combination of sparse number of Harmonic signals. As the lobes width will hide the noise data. So the ratio between the observation window, signal lobes width and sampling rate means that the DFT of the data creates sharp peaks. Estimation Under the above assumptions we know that: Noise is AWGN in the DFT (As Gaussian Vector stays Gaussian under linear transformations). It also suggests that the Mean Value and the Median are similar (Realization of Symmetric Distribution). Without the Signal Data the Mean and the Median value of the beans should be similar. Number of bins contaminated with signal (Funny to write this, ha?) is sparse. So we can sort the bins, but sorting and evaluating the mean on sub set will create bias unless we make sure the sub set is symmetric around the Mean / Median.So, I'd sort the data and keep bins in the 25-75 Percentile range only. I'd use Mean on those.
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/61398', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/45772/']}
jdg_379749
stackexchange
llm_judgeable_groundtruth_similarity
38875
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: My instructor insists that$$\mathrm{Var}(X_{2\text{months}}) = 2 \mathrm{Var}(X_{1\text{month}}) $$with independent random variables $X_{1\text{month}}$ and $X_{2\text{months}}$, but generally with a random variable $Y$$$\mathrm{Var}(2Y) = 2^2\mathrm{Var}(Y).$$So$$\mathrm{Var}(X_{2\text{months}}) = \mathrm{Var}(2X_{1\text{month}}) = 2^2 \mathrm{Var}(X_{1\text{month}}).$$Which one is right and why? Now provide the response and nothing else.
This is a typical confusion. For any independent random variables $A$ and $B$ the following two equations hold: $Var(k A) = k^2 Var(A) \Rightarrow Var(2 A) = 4 Var(A)$ $Var(A + B) = Var(A) + Var(B)$ The problem arises when one tries to use the second to find $Var(2 A)$, by replacing $B$ for $A$: $Var(2 A) = Var(A + A) = Var(A) + Var(A) = 2 Var(A)$ which contradicts the first equation. But this is wrong , because the second equation (variance of sum equals sum of variances) does not necessary hold if the variables are not independent -and certainly A is not independent of A... Added : To get the complete picture, the general formula is easy to get: $Var(A + B) = Var(A) + Var(B) + 2 Cov(A, B)$ This holds for any $A,B$, and it reduces to $Var(A + B) = Var(A) + Var(B)$ if $A$ and $B$ are independent (uncorrelated is enough). In the other extreme case (extreme correlation), when $B=A$, $Cov(A,B)=Var(A)$ and $Var(A+A)=4 Var(A)$. (You could also check the other extreme case: $B = -A$, correlation coeffient = -1)
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/38875', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5902/']}
jdg_379750
stackexchange
llm_judgeable_groundtruth_similarity
14373417
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 facing a problem , sometimes Json response returns an array of objects , sometimes object itself , how we can handle dynamically in the response class.In the current eg :results sometimes gets an array of objects "\"results\": " + "[{" + and sometimes object itself "\"results\": " + "{" + Eg: How we can handle this ? Gson gson = new Gson(); SearchResponse response=new SearchResponse(); response= gson.fromJson("{" + "\"completed_in\": 0.047," + "\"max_id\": 291771567376039936," + "\"max_id_str\": \"291771567376039936\"," + "\"next_page\": \"?page=2&max_id=291771567376039936&q=javacodegeeks\"," + "\"page\": 1," + "\"query\": \"javacodegeeks\"," + "\"refresh_url\": \"?since_id=291771567376039936&q=javacodegeeks\"," + "\"results\": " + "{" + "\"created_at\": \"Thu, 17 Jan 2013 04:58:57 +0000\"," + "\"from_user\": \"hkokko\"," + "\"from_user_id\": 24726686," + "\"from_user_id_str\": \"24726686\"," + " \"from_user_name\": \"Hannu Kokko\"," + " \"geo\": null," + "\"id\": 291771567376039936," + "\"id_str\": \"291771567376039936\"," + "\"iso_language_code\": \"en\"," + " \"metadata\": {" + "\"result_type\": \"recent\"}," + "\"profile_image_url\": \"hjh\"," + "\"profile_image_url_https\": \"kkj\"," + "\"source\": \"&lt;a href=&quot;hj;\"," + "\"text\": \"Continuous Deployment: Are You Afraid It Might Work? jh\"," + "\"to_user\": null," + "\"to_user_id\": 0," + "\"to_user_id_str\": \"0\"," + "\"to_user_name\": null" + " }," + "\"results_per_page\": 15," + "\"since_id\": 0," + "\"since_id_str\": \"0\"" + "}", SearchResponse.class); System.out.println(response.toString()); Kindly assist... Can anyone give any suggestions by using different jars to achieve this? Now provide the response and nothing else.
i found a solution for this ,i felt to share this..The code will automatically convert ..if excepted response is arraylist in response class....then if object is coming in response then add to arraylist else if arraylist it will take the same list. we need hook change the response bfore it calls fromJson. public class ArrayAdapter<T> extends TypeAdapter<List<T>> { private Class<T> adapterclass; public ArrayAdapter(Class<T> adapterclass) { this.adapterclass = adapterclass; } public List<T> read(JsonReader reader) throws IOException { List<T> list = new ArrayList<T>(); Gson gson = new Gson(); if (reader.peek() == JsonToken.BEGIN_OBJECT) { T inning = (T) gson.fromJson(reader, adapterclass); list.add(inning); } else if (reader.peek() == JsonToken.BEGIN_ARRAY) { reader.beginArray(); while (reader.hasNext()) { T inning = (T) gson.fromJson(reader, adapterclass); list.add(inning); } reader.endArray(); } else { reader.skipValue(); } return list; } public void write(JsonWriter writer, List<T> value) throws IOException { }}public class ArrayAdapterFactory implements TypeAdapterFactory { @SuppressWarnings({ "unchecked" }) @Override public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { ArrayAdapter typeAdapter = null; try { if (type.getRawType() == List.class) { typeAdapter = new ArrayAdapter( (Class) ((ParameterizedType) type.getType()) .getActualTypeArguments()[0]); } } catch (Exception e) { e.printStackTrace(); } return typeAdapter;} then just call Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ArrayAdapterFactory()).create(); SearchResponse response; esponse= gson.fromJson("your json string", SearchResponse.class)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14373417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/598084/']}
jdg_379751
stackexchange
llm_judgeable_groundtruth_similarity
41411492
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: While reading the python documentation I came across the itertools.groupby() function. It was not very straightforward so I decided to look up some info here on stackoverflow. I found something from How do I use Python's itertools.groupby()? . There seems to be little info about it here and in the documentation so I decided I to post my observations for comments. Thanks Now provide the response and nothing else.
To start with, you may read the documentation here . I will place what I consider to be the most important point first. I hope the reason will become clear after the examples. ALWAYS SORT ITEMS WITH THE SAME KEY TO BE USED FOR GROUPING SO AS TO AVOID UNEXPECTED RESULTS itertools.groupby(iterable, key=None or some func) takes a list of iterables and groups them based on a specified key. The key specifies what action to apply to each individual iterable, the result of which is then used as the heading for each grouping the items; items which end up having same 'key' value will end up in the same group. The return value is an iterable similar to a dictionary in that it is of the form {key : value} . Example 1 # note here that the tuple counts as one item in this list. I did not# specify any key, so each item in the list is a key on its own.c = groupby(['goat', 'dog', 'cow', 1, 1, 2, 3, 11, 10, ('persons', 'man', 'woman')])dic = {}for k, v in c: dic[k] = list(v)dic results in {1: [1, 1], 'goat': ['goat'], 3: [3], 'cow': ['cow'], ('persons', 'man', 'woman'): [('persons', 'man', 'woman')], 10: [10], 11: [11], 2: [2], 'dog': ['dog']} Example 2 # notice here that mulato and camel don't show up. only the last element with a certain key shows up, like replacing earlier result# the last result for c actually wipes out two previous results.list_things = ['goat', 'dog', 'donkey', 'mulato', 'cow', 'cat', ('persons', 'man', 'woman'), \ 'wombat', 'mongoose', 'malloo', 'camel']c = groupby(list_things, key=lambda x: x[0])dic = {}for k, v in c: dic[k] = list(v)dic results in {'c': ['camel'], 'd': ['dog', 'donkey'], 'g': ['goat'], 'm': ['mongoose', 'malloo'], 'persons': [('persons', 'man', 'woman')], 'w': ['wombat']} Now for the sorted version # but observe the sorted version where I have the data sorted first on same key I used for groupinglist_things = ['goat', 'dog', 'donkey', 'mulato', 'cow', 'cat', ('persons', 'man', 'woman'), \ 'wombat', 'mongoose', 'malloo', 'camel']sorted_list = sorted(list_things, key = lambda x: x[0])print(sorted_list)print()c = groupby(sorted_list, key=lambda x: x[0])dic = {}for k, v in c: dic[k] = list(v)dic results in ['cow', 'cat', 'camel', 'dog', 'donkey', 'goat', 'mulato', 'mongoose', 'malloo', ('persons', 'man', 'woman'), 'wombat']{'c': ['cow', 'cat', 'camel'], 'd': ['dog', 'donkey'], 'g': ['goat'], 'm': ['mulato', 'mongoose', 'malloo'], 'persons': [('persons', 'man', 'woman')], 'w': ['wombat']} Example 3 things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "harley"), \ ("vehicle", "speed boat"), ("vehicle", "school bus")]dic = {}f = lambda x: x[0]for key, group in groupby(sorted(things, key=f), f): dic[key] = list(group)dic results in {'animal': [('animal', 'bear'), ('animal', 'duck')], 'plant': [('plant', 'cactus')], 'vehicle': [('vehicle', 'harley'), ('vehicle', 'speed boat'), ('vehicle', 'school bus')]} Now for the sorted version. I changed the tuples to lists here. Same results either way. things = [["animal", "bear"], ["animal", "duck"], ["vehicle", "harley"], ["plant", "cactus"], \ ["vehicle", "speed boat"], ["vehicle", "school bus"]]dic = {}f = lambda x: x[0]for key, group in groupby(sorted(things, key=f), f): dic[key] = list(group)dic results in {'animal': [['animal', 'bear'], ['animal', 'duck']], 'plant': [['plant', 'cactus']], 'vehicle': [['vehicle', 'harley'], ['vehicle', 'speed boat'], ['vehicle', 'school bus']]}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41411492', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2689562/']}
jdg_379752
stackexchange
llm_judgeable_groundtruth_similarity
47319370
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Publish link this is the HTML code <tbody> <tr id="id71" class="even"> <!-- The select row checkbox --> <!-- This is a repeater, will generate one td for each property --> <td> <span></span> </td> <td> <span>orthoacapulco_30cm_cut</span> </td> <td> <span> <a id="id64" href="javascript:;"><span>Publish</span></a> </span> </td> </tr> </tbody> I tried everything. By XPath , CSS selector, by partialLinkName. I can´t use By.ID because never is the same id, and there may be more elements in the table. Now provide the response and nothing else.
Example data: create table my_table(name text, numbers text[], letters text[]);insert into my_table values ('first', '{1, 2}', '{a}' ), ('first', '{2, 3}', '{a, b}'), ('second', '{4}', '{c, d}'), ('second', '{5, 6}', '{c}' ); You should aggregate arrays elements, not arrays. Use unnest() : select name, array_agg(distinct number) as numbers, array_agg(distinct letter) as lettersfrom my_table, unnest(numbers) as number, unnest(letters) as lettergroup by name; name | numbers | letters --------+---------+--------- first | {1,2,3} | {a,b} second | {4,5,6} | {c,d}(2 rows) Alternatively, you can create a custom aggregate. You need a function to merge arrays (concatenation with duplicates removing): create or replace function public.array_merge(arr1 anyarray, arr2 anyarray) returns anyarray language sql immutableas $$ select array_agg(distinct elem order by elem) from ( select unnest(arr1) elem union select unnest(arr2) ) s$$;create aggregate array_merge_agg(anyarray) ( sfunc = array_merge, stype = anyarray);select name, array_merge_agg(numbers) as numbers, array_merge_agg(letters) as lettersfrom my_tablegroup by name;
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47319370', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8948352/']}
jdg_379753
stackexchange
llm_judgeable_groundtruth_similarity
10827404
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using a calculation in my SQL query. How can I use that calculated field in C#? When I try, I get an index out of range exception. My query is: Select OwnerCompanyLog.olog_name,inlt_companyid,inlt_childcompid,inlt_effectinterest,inlt_percent,inlt_sharetype,inlt_shares,inlt_childbase,inlt_effdate, ((inlt_percent * inlt_effectinterest)/100)eff from InterestLogTable INNER JOIN OwnerCompanyLog ON InterestLogTable.inlt_childcompid = OwnerCompanyLog.olog_companyid where inlt_companyid=5 Order By inlt_childcompid I want to use inlt_percent * inlt_effectinterest)/100 in my C# code: entity.ParentCompany = new List<Company>(); while (parentCompanyReader.Read()) { ParentCompany.Effect = parentCompanyReader["eff"].ToString(); entity.ParentCompany.Add(ParentCompany); } parentCompanyReader.Close(); But I got the error above. Now provide the response and nothing else.
In your case we can say rotation of the device is equal to rotation of the device normal (rotation around the normal itself is just ignored like you specified it) CMAttitude which you can get via CMMotionManager.deviceMotion provides the rotation relative to a reference frame . Its properties quaternion, roationmatrix and Euler angles are just different representations. The reference frame can be specified when you start device motion updates using CMMotionManager's startDeviceMotionUpdatesUsingReferenceFrame method. Until iOS 4 you had to use multiplyByInverseOfAttitude Putting this together you just have to multiply the quaternion in the right way with the normal vector when the device lies face up on the table. Now we need this right way of quaternion multiplication that represents a rotation: According to Rotating vectors this is done by: n = q * e * q' where q is the quaternion delivered by CMAttitude [w, (x, y, z)], q' is its conjugate [w, (-x, -y, -z)] and e is the quaternion representation of the face up normal [0, (0, 0, 1)]. Unfortunately Apple's CMQuaternion is struct and thus you need a small helper class. Quaternion e = [[Quaternion alloc] initWithValues:0 y:0 z:1 w:0];CMQuaternion cm = deviceMotion.attitude.quaternion;Quaternion quat = [[Quaternion alloc] initWithValues:cm.x y:cm.y z:cm.z w: cm.w];Quaternion quatConjugate = [[Quaternion alloc] initWithValues:-cm.x y:-cm.y z:-cm.z w: cm.w];[quat multiplyWithRight:e];[quat multiplyWithRight:quatConjugate];// quat.x, .y, .z contain your normal Quaternion.h: @interface Quaternion : NSObject { double w; double x; double y; double z;}@property(readwrite, assign)double w;@property(readwrite, assign)double x;@property(readwrite, assign)double y;@property(readwrite, assign)double z; Quaternion.m: - (Quaternion*) multiplyWithRight:(Quaternion*)q { double newW = w*q.w - x*q.x - y*q.y - z*q.z; double newX = w*q.x + x*q.w + y*q.z - z*q.y; double newY = w*q.y + y*q.w + z*q.x - x*q.z; double newZ = w*q.z + z*q.w + x*q.y - y*q.x; w = newW; x = newX; y = newY; z = newZ; // one multiplication won't denormalise but when multipling again and again // we should assure that the result is normalised return self;}- (id) initWithValues:(double)w2 x:(double)x2 y:(double)y2 z:(double)z2 { if ((self = [super init])) { x = x2; y = y2; z = z2; w = w2; } return self;} I know quaternions are a bit weird at the beginning but once you have got an idea they are really brilliant. It helped me to imagine a quaternion as a rotation around the vector (x, y, z) and w is (cosine of) the angle. If you need to do more with them take a look at cocoamath open source project. The classes Quaternion and its extension QuaternionOperations are a good starting point. For the sake of completeness, yes you can do it with matrix multiplication as well: n = M * e But I would prefer the quaternion way it saves you all the trigonometric hassle and performs better.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10827404', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1419112/']}
jdg_379754
stackexchange
llm_judgeable_groundtruth_similarity
13317
Below is a question asked on the forum ai.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The Wikipedia article for the universal approximation theorem cites a version of the universal approximation theorem for Lebesgue-measurable functions from this conference paper . However, the paper does not include the proofs of the theorem. Does anybody know where the proof can be found? Now provide the response and nothing else.
There are multiple papers on the topic because there have been multiple attempts to prove that neural networks are universal (i.e. they can approximate any continuous function) from slightly different perspectives and using slightly different assumptions (e.g. assuming that certain activation functions are used). Note that these proofs tell you that neural networks can approximate any continuous function, but they do not tell you exactly how you need to train your neural network so that it approximates your desired function. Moreover, most papers on the topic are quite technical and mathematical, so, if you do not have a solid knowledge of approximation theory and related fields, they may be difficult to read and understand. Nonetheless, below there are some links to some possibly useful articles and papers. The article A visual proof that neural nets can compute any function (by Michael Nielsen) should give you some intuition behind the universality of neural networks, so this is probably the first article you should read. Then you should probably read the paper Approximation by Superpositions of a Sigmoidal Function (1989), by G. Cybenko, who proves that multi-layer perceptrons (i.e. feed-forward neural networks with at least one hidden layer) can approximate any continuous function . However, he assumes that the neural network uses sigmoid activations functions, which, nowadays, have been replaced in many scenarios by ReLU activation functions. Other works (e.g. [1] , [2] ) showed that you don't necessarily need sigmoid activation functions, but only certain classes of activation functions do not make neural networks universal. The universality property (i.e. the ability to approximate any continuous function) has also been proved in the case of convolutional neural networks . For example, see Universality of Deep Convolutional Neural Networks (2020), by Ding-Xuan Zhou, which shows that convolutional neural networks can approximate any continuous function to an arbitrary accuracy when the depth of the neural network is large enough. See also Refinement and Universal Approximation via Sparsely Connected ReLU Convolution Nets (by A. Heinecke et al., 2020) See also page 632 of Recurrent Neural Networks Are Universal Approximators (2006), by Schäfer et al., which shows that recurrent neural networks are universal function approximators. See also On the computational power of neural nets (1992, COLT) by Siegelmann and Sontag. This answer could also be useful. For graph neural networks , see Universal Function Approximation on Graphs (by Rickard Brüel Gabrielsson, 2020, NeurIPS)
{}
{'log_upvote_score': 6, 'links': ['https://ai.stackexchange.com/questions/13317', 'https://ai.stackexchange.com', 'https://ai.stackexchange.com/users/27047/']}
jdg_379755
stackexchange
llm_judgeable_groundtruth_similarity
34317668
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 created a simple struct called ShoppingList. struct ShoppingList { var shoppingListId :NSNumber var title :String var groceryItems :[GroceryItem] init() { self.title = "" self.groceryItems = [GroceryItem]() self.shoppingListId = NSNumber(integer: 0) }} Next I created a ShoppingList array like this: var shoppingLists = [ShoppingList]() After that I fetch the shopping lists etc. Now, I iterate through the shoppingLists and change the title but it ever updates the title property. for var shoppingList in shoppingLists { let items = getGroceryItemsByShoppingList(shoppingList) shoppingList.groceryItems = getGroceryItemsByShoppingList(shoppingList) shoppingList.title = "BLAH" // copied by value print("ShoppingList \(shoppingList.title) has \(shoppingList.groceryItems.count) items") // THIS PRINT BLAH}print("shoppingLists[0].groceryItems.count \(shoppingLists[0].groceryItems.count)") // THIS PRINTS THE ORIGINAL CONTENT I believe that when I am running the loop it is copying by value and hence the original array is never changed. How can I change the original array using For loop? Now provide the response and nothing else.
There are two approaches I would use here. The first approach is to reconsider whether ShoppingList is a value type or a reference type. The fact that it has an identifier suggests to me that it's really a reference type. If two shopping lists have the same contents, should the be considered the same list? I suspect not. What would it mean to have two lists that have the same identifier, but different contents? If that's illegal, again, that tends to point to it being a reference type because it has an identity. If it's a reference type, make it a final class : final class ShoppingList {} Final classes preserve the simplicity of structs because they do not suffer the problems of inheritance. But they provide reference semantics. With that change, your original code would work. The other way to approach this is more functional, where everything is a value. In that case, you can achieve this by mapping copies of your shopping lists: shoppingLists = shoppingLists.map { list in var newList = list newList.groceryItems = getGroceryItemsByShoppingList(list) return newList} This pushes us towards a more functional approach, but it makes the identifier awkward. So if you really wanted to go this way, I'd want to get rid of identifiers and maybe even make shopping lists immutable. In that case, any two identical shopping lists are the same list, and you can write in a more functional style. But I suspect that making ShoppingList a reference type is your better approach.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34317668', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/810815/']}
jdg_379756
stackexchange
llm_judgeable_groundtruth_similarity
4825400
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 doesn't exactly seem to be right although I am unsure why.Advice would be great as the documentation for CMPXCHG16B is pretty minimal (I don't own any intel manuals...) template<>inline bool cas(volatile types::uint128_t *src, types::uint128_t cmp, types::uint128_t with){ /* Description: The CMPXCHG16B instruction compares the 128-bit value in the RDX:RAX and RCX:RBX registers with a 128-bit memory location. If the values are equal, the zero flag (ZF) is set, and the RCX:RBX value is copied to the memory location. Otherwise, the ZF flag is cleared, and the memory value is copied to RDX:RAX. */ uint64_t * cmpP = (uint64_t*)&cmp; uint64_t * withP = (uint64_t*)&with; unsigned char result = 0; __asm__ __volatile__ ( "LOCK; CMPXCHG16B %1\n\t" "SETZ %b0\n\t" : "=q"(result) /* output */ : "m"(*src), /* input */ //what to compare against "rax"( ((uint64_t) (cmpP[1])) ), //lower bits "rdx"( ((uint64_t) (cmpP[0])) ),//upper bits //what to replace it with if it was equal "rbx"( ((uint64_t) (withP[1])) ), //lower bits "rcx"( ((uint64_t) (withP[0]) ) )//upper bits : "memory", "cc", "rax", "rdx", "rbx","rcx" /* clobbered items */ ); return result;} When running with an example I am getting 0 when it should be 1. Any ideas? Now provide the response and nothing else.
Noticed a few issues, (1) The main problem is the constraints, "rax" doesn't do what it looks like, rather the first character "r" lets gcc use any register. (2) Not sure how your storing types::uint128_t, but assuming the standard little endian for x86 platforms, then the high and low dwords are also swapped around. (3) Taking the address of something and casting it to something else can break aliasing rules. Depends on how your types::uint128_t is defined as to wether or not this is an issue (fine if it is a struct of two uint64_t's). GCC with -O2 will optimize assuming aliasing rules are not violated. (4) *src should really be marked as an output, rather than specifying memory clobber. but this is really more of a performance rather than correctness issue. similarly rbx and rcx do not need to specified as clobbered. Here is a a version that works, #include <stdint.h>namespace types{ // alternative: union with unsigned __int128 struct uint128_t { uint64_t lo; uint64_t hi; } __attribute__ (( __aligned__( 16 ) ));}template< class T > inline bool cas( volatile T * src, T cmp, T with );template<> inline bool cas( volatile types::uint128_t * src, types::uint128_t cmp, types::uint128_t with ){ // cmp can be by reference so the caller's value is updated on failure. // suggestion: use __sync_bool_compare_and_swap and compile with -mcx16 instead of inline asm bool result; __asm__ __volatile__ ( "lock cmpxchg16b %1\n\t" "setz %0" // on gcc6 and later, use a flag output constraint instead : "=q" ( result ) , "+m" ( *src ) , "+d" ( cmp.hi ) , "+a" ( cmp.lo ) : "c" ( with.hi ) , "b" ( with.lo ) : "cc", "memory" // compile-time memory barrier. Omit if you want memory_order_relaxed compile-time ordering. ); return result;}int main(){ using namespace types; uint128_t test = { 0xdecafbad, 0xfeedbeef }; uint128_t cmp = test; uint128_t with = { 0x55555555, 0xaaaaaaaa }; return ! cas( & test, cmp, with );}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4825400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/90138/']}
jdg_379757
stackexchange
llm_judgeable_groundtruth_similarity
43385587
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 List<Region> Regions { get; set; } in model called News.An Region Model is public class Region { public int Id { get; set; } public string Name { get; set; } public static Region Parse(DataRow row) { return new Region { Id = Database.GetInteger(row["Id"]), Name = Database.GetString(row["Region"]), }; } } in Javascript I am using AJAX post method with formdata. I want to set this region. var regionList = []; if (selected === "region") { if (region.length <= 0) { toastr.warning('Lütfen en az bir bölge seçin !!!'); return; } for (var i = 0; i < region.length; i++) { var item = { Id: region[i] } regionList.push(item); } console.log(regionList); formData.append("Regions", regionList); } Code above in JS i wrote like this to set it public ActionResult AddByRegion(News item) { int refPortal = SessionRepository.GetPortalId(); if(refPortal!=1) return View("List", NewsRepository.ListAll(SessionRepository.GetPortalId())); if (item == null || string.IsNullOrEmpty(item.Title) || string.IsNullOrEmpty(item.Content) ) return Content(Serialization.JsonSerialize(new { Status = 400 })); return Content(Serialization.JsonSerialize(new { Status = 200, Result = NewsRepository.AddByRegion(item) })); } and code above i will get in controller. But it returns always 0 record although at least i choosed two region. $.ajax({ type: 'POST', url: '@Url.Action("AddByRegion", "News")', data: formData, contentType: false, processData: false, success: function(data) { var result = JSON.parse(data); if (result.Result === "SUCCEED") { toastr.success('@Resources.Resource.Success_MediaAdd'); window.location.reload(); return; } else { toastr.error('@Resources.Resource.Error_Unexpected'); return; } }, error: function(error) { toastr.error('@Resources.Resource.Error_Unexpected'); return; }, beforeSend: function() { waitingDialog.show('Wait...'); }, complete: function() { waitingDialog.hide(); } }); My Ajax method is above. Where am I making mistake ? Thanks in advance. Now provide the response and nothing else.
If your using FormData to send the data, you need to .append() each individual name/value to FormData . Since its a collection, you must include the collection indexer (which must be zero based and consecutive), for example formData.append("Regions[0].Id", someValue);formData.append("Regions[0].Name", someValue);formData.append("Regions[1].Id", someValue);formData.append("Regions[1].Name", someValue); Since your doing this in a loop, you can use for (var i = 0; i < region.length; i++) { formData.append("Regions[" + i + "].Id", region[i])}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43385587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_379758
stackexchange
llm_judgeable_groundtruth_similarity
1328357
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Here is my solution:I assume $n^2$ is odd then I put $n^2$= $(2x-1)^2$, now I am taking root square for both sides:$\sqrt{(n^2)}$ = $\sqrt{(2x-1)^2}$ $\Rightarrow$ $n = (2x-1)$ $\Rightarrow$ $n$ is odd since R.H.S has -1 of an even number. Is my solution a good proof? Now provide the response and nothing else.
Not a correct proof because if $n^2$ is odd, then it doesn't necessarily take the form $(2k - 1)^2$. In fact, that's what you are required to prove. Your assumption should be $\exists$ $k \in \mathbb N$, such that $n^2 = 2k - 1$. However, this isn't a very fruitful approach. The classical solution to this is to work by contraposition. Suppose that $n$ is even, then we can write $n = 2k$. Then, $n^2 = 4k^2 = 2(2k^2)$, so it is even. This gives that if $n^2$ is odd, then $n$ is odd.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1328357', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/239279/']}
jdg_379759
stackexchange
llm_judgeable_groundtruth_similarity
33483830
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 Spring+Hibernate+Spring-MVC . I want to define a custom constraint combining two other predefined validation annotations: @NotNull @Size like this: import javax.validation.constraints.NotNull;import javax.validation.constraints.Size;@NotNull@Size(min=4)public @interface JPasswordConstraint {} // this is not correct. It's just a suggestion. and I want to use this annotation in my form models. public class ChangePasswordForm { @NotNull private String currentPass; @JPasswordConstraint private String newPass; @JPasswordConstraint private String newPassConfirm;} UserController.java @RequestMapping(value = "/pass", method = RequestMethod.POST)public String pass2(Model model, @Valid @ModelAttribute("changePasswordForm") ChangePasswordForm form, BindingResult result) { model.addAttribute("changePasswordForm", form); try { userService.changePassword(form); } catch (Exception ex) { result.rejectValue(null, "error.objec", ex.getMessage()); System.out.println(result); } if (!result.hasErrors()) { model.addAttribute("successMessage", "password changed successfully!"); } return "user/pass";} But it does not work. It accepts the less than 4 character passwords. How can I solve this problem? Now provide the response and nothing else.
This is a bit late, but technique of combining validation annotations described in https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/?v=5.4#section-constraint-composition Maybe it was not available, at the time of writing, but solution is following @NotNull@Size(min=4)@Target({ METHOD, FIELD, ANNOTATION_TYPE })@Retention(RUNTIME)@Constraint(validatedBy = { })@Documentedpublic @interface JPasswordConstraint { String message() default "Password is invalid"; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33483830', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1583946/']}
jdg_379760
stackexchange
llm_judgeable_groundtruth_similarity
8606
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: The answers to this question do a good job of exploring, at a heuristic level, what "quantization" should be. From my perspective, quantization involves replacing a (commutative) Poisson algebra by some related noncommutative associative algebra. Poisson algebras arise naturally especially as algebras of functions in geometry and physics. Noncommutative algebras arise naturally as algebras of operators on linear spaces. I've often heard it said that "quantization is not a functor". I'm wondering what a precise statement of this is. For example, I could imagine statements of the following form. There is no functor from the category of Poisson manifolds (and Poisson maps?) to the (opposite of the) category of associative algebras satisfying some nice property. There is no functor from the category of symplectic manifolds (and Poisson maps?) to the (opposite of the) category of associative algebras satisfying some nice property. Recall that for any smooth manifold, its cotangent bundle is naturally symplectic. There is no functor from the category of smooth manifolds to the category of associative algebras that quantizes the cotangent bundle. Recall that the dual to the universal enveloping algebra of a Lie bialgebra is naturally Poisson Hopf. There is no functor from the category of Lie bialgebras to the category of Hopf algebras satisfying some nice property. Actually, 4. is false. Indeed, Etingof and Khazdan constructed a functor from bialgebras to Hopf algebras satisfying a host of properties, and Enriquez classified all the ones with nice properties. Note that Kontsevich does give a quantization of any Poisson manifold, but perhaps his isn't functorial? Now provide the response and nothing else.
Here is one precise statement of how quantization is not a functor: 5) There is no functor from the classical category $\mathcal C$ of Poisson manifolds and Poisson maps to the quantum category $\mathcal Q$ of Hilbert spaces and unitary operators that is consistent with the cotangent bundle/$\frac12$-density relation (explained below). The result is due to Van Hove, in "Sur le probleme des relations entre les transformations unitaires de la mecanique quantique et les transformations canoniques de la mecaniques classique." This is an old paper and I can't find a link for it, but the reference I found it in is Weinstein's "Lectures on Symplectic Manifolds." By "cotangent bundle/$\frac12$-density relation" I mean the following: if $\mathcal M$ is the category of smooth manifolds and diffeomorphisms, we have a cotangent functor $\mathcal M \to \mathcal C$. This assigns to each manifold its cotangent bundle with the canonical symplectic structure, and to each diffeomorphism the induced symplectomorphism of cotangent bundles. We also have a natural functor $\mathcal M \to \mathcal Q$. For any smooth manifold $X$ consider the bundle of complex $\frac12$-densities on $X$. (What is the bundle of complex $s$-densities? Well, the fiber over a point $x \in X$ is the set of functions $\delta_x: \bigwedge^{top} T_xX \to \mathbb{C}$ such that $\delta(cv) = |c|^{s}\delta(v)$.) If $\delta^1$ and $\delta^2$ are smooth compactly-supported $\frac12$-densities, their pointwise product $\delta^1 \bar{\delta^2}$ is a compactly supported 1-density which we can integrate to get a complex number. This turns the space of all such sections into a pre-Hilbert space, the completion of which is what our functor assigns to the manifold $X$. As we would hope for, the canonical nature of the construction lets us assign unitary operators between Hilbert spaces to diffeomorphisms between smooth manifolds, hence is functorial. (Note: If we choose a volume form on $X$, the above procedure produces something isomorphic with the space of $L^2$ functions on $X$ with respect to this form, but to get something functorial we want a canonical construction.) From this pair of functors $\mathcal M \to \mathcal C$ and $\mathcal M \to \mathcal Q$ we get a product functor $\mathcal M \to \mathcal{C} \times \mathcal{Q}$. The image of this functor is a subcategory of $\mathcal C \times \mathcal Q$ which we will call the "cotangent bundle/$\frac12$-density relation." (The word relation is meant in the same sense that an ordinary relation between two sets is a subset of their product). Now we can clarify just what is meant by our original statement: there is no functor $\mathcal C \to \mathcal Q$ whose graph contains the cotangent bundle/$\frac12$-density relation. The reasons why this is a desirable condition come from physics and are beyond me, but roughly speaking I think the point is that there exists a good idea of what a quantization functor is supposed to do to cotangent bundles.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/8606', 'https://mathoverflow.net', 'https://mathoverflow.net/users/78/']}
jdg_379761
stackexchange
llm_judgeable_groundtruth_similarity
82769
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 $\gamma=\omega$ (the first transfinite ordinal). Is it consistent with ZFC that for all ordinals $\alpha, \beta < \gamma$ it holds that $2^{\aleph_\alpha} = 2^{\aleph_\beta}$?If yes, can the bound $\gamma$ be increased here and how much? Update: In what sense the bound $\gamma$ can be made arbitrarily high? If $\beta$ is the initial ordinal of $\beth_1$, then it cannot be that $2^{\aleph_0}=2^{\aleph_\beta}$, right? Now provide the response and nothing else.
Yes. Start with a model of GCH and add $\aleph_{\omega+1}$ Cohen reals. Then $2^{\aleph_n}=\aleph_{\omega+1}$ for all $n<\omega$. You can get the bound $\gamma$ arbitrarily high within the ordinal hierarchy by adding $\kappa$ Cohen reals instead, where $\kappa$ is a regular cardinal greater than $\aleph_\gamma$. (I think that's all correct.)
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/82769', 'https://mathoverflow.net', 'https://mathoverflow.net/users/9550/']}
jdg_379762
stackexchange
llm_judgeable_groundtruth_similarity
300352
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to create more than one private key to SSH into an EC2 instance? What's the general best practice for this? We have multiple users who need to SSH into the servers and distributing one key just does not work well. This does not allow us to remove users from being able to SSH into the server unless we change the key and redistribute. Now provide the response and nothing else.
Absolutely; you just place all the relevant public keys into the image and you should be right to go. I prefer to use a configuration management system to manage SSH keys; that way it's fairly trivial to revoke a user's access even on running systems. There are also far more... let's say "imaginative"... ways of handling this, such as storing all your SSH keys in LDAP, that centralise SSH keys like any other credential.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/300352', 'https://serverfault.com', 'https://serverfault.com/users/19432/']}
jdg_379763
stackexchange
llm_judgeable_groundtruth_similarity
43244958
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am new to redis therefore I don't know more about its complex technicalities. But let me put my scenario here: I am running two websites from same server and I wanted redis to work on both. On searching, I found that I can do this by assigning different index to different db on same server instance like below: //In my first website (development)Idatabase dbOfDev=_conn.GetDatabase(0);//In my second website (production)Idatabase dbOfProd=_conn.GetDatabase(1); This was ideal for me since I could cache both my database in same instance. But then I bumped into What's the Point of Multiple Redis Databases? and How do I change between redis database? links which says "Use of multiple database in same server instance is discouraged and deprecated ". Though these links do try to explain the reason behind it, being a beginner, I am still not able to understand its deep technical aspects. Can anyone explain the reason in simpler terms as why using multiple redis db of same server instance is discouraged. Also, in simpler terms, how can I manage caching of both my websites on same server without the above said approach? Now provide the response and nothing else.
how can I manage caching of both my websites on same server without the above said approach? You can use different key tag for each website. Say, name the two websites as A and B . For all keys of website A , give each key a prefix(key tag): A: . On the other hand, give each key for website B another prefix: B: . In this way, you can have a unique key namespace for each website. SET A:key1 val1SET A:key2 val2LPUSH B:key1 1SADD B:key2 val Also check this answer for more solutions. Can anyone explain the reason in simpler terms as why using multiple redis db of same server instance is discouraged. AFAIK, multiple databases feature is NOT discouraged and deprecated. It's a method to isolated key namespaces for different applications. However, the author of Redis considerRedis multiple database errors my worst decision in Redis design atall , since it makes Redis internals more complex. Redis is single-threaded , so compared to multiple databases, multiple Redis instances can take advantage of multiple cores. If you have multiple databases in one Redis instance, you can still only use one core. Also Redis instance itself has little memory footprint, so you don't need to worry about multiple Redis instance costs you too much. Redis is very fast, and normally the bottleneck is network bandwidth, NOT CPU. So normally you CANNOT get too much gain by using multiple Redis instances. However, if one of your application needs to do some slow commands on Redis, and don't want it to block other applications, you can have a separate Redis instance for the slow application, and have another Redis instance for other fast applications. Also note that Redis Cluster doesn't support multiple databases. Personally, I like this multiple database feature. Normally, if I run a Redis instance, not Redis Cluster, I'll put my data into some database other than the default database, i.e. database 0, to avoid incidentally login Redis and do some horrible things on the default database. Also it's very easy to implement a double buffer with multiple databases, e.g. write data to a new database, when it's done, use the SWAPDB command to swap the old DB and new DB automatically and efficiently.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43244958', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2828434/']}
jdg_379764
stackexchange
llm_judgeable_groundtruth_similarity
9910908
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, when I STORE into HDFS, it creates many part files. Is there any way to store out to a single CSV file? Now provide the response and nothing else.
You can do this in a few ways: To set the number of reducers for all Pig opeations, you can use the default_parallel property - but this means every single step will use a single reducer, decreasing throughput: set default_parallel 1; Prior to calling STORE, if one of the operations execute is (COGROUP, CROSS, DISTINCT, GROUP, JOIN (inner), JOIN (outer), and ORDER BY), then you can use the PARALLEL 1 keyword to denote the use of a single reducer to complete that command: GROUP a BY grp PARALLEL 1; See Pig Cookbook - Parallel Features for more information
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9910908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/229099/']}
jdg_379765
stackexchange
llm_judgeable_groundtruth_similarity
44321586
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 las day of the current year, I need this to change with time so if I use this function in 2018 I get as last day 31 of December 2018 but if I use the function right now it should give me 31 December 2017. I know I can get the current date by just using var current = Date() And I know that I can get for example this same day one year from now that should be approximately var dayComponents = DateComponents() dayComponents.day = 365 let calendar = Calendar(identifier: .gregorian) if let lastDate = calendar.date(byAdding: dayComponents, to: Date()) { return lastDate } else { return Date() } The problem is that I need just from now to the end of the year, how can I achieve this? Now provide the response and nothing else.
I would get the current year component of the current date. Add one to get next year. Then use that to get the 1st day of that year. Then subtract 1 day to get the last day of the current year. // Get the current yearlet year = Calendar.current.component(.year, from: Date())// Get the first day of next yearif let firstOfNextYear = Calendar.current.date(from: DateComponents(year: year + 1, month: 1, day: 1)) { // Get the last day of the current year let lastOfYear = Calendar.current.date(byAdding: .day, value: -1, to: firstOfNextYear)}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44321586', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5245639/']}
jdg_379766
stackexchange
llm_judgeable_groundtruth_similarity
8255929
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 ran into a problem while working with Selenium. For my project, I have to use Chrome. However, I can't connect to that browser after launching it with Selenium. For some reason, Selenium can't find Chrome by itself. This is what happens when I try to launch Chrome without including a path: Traceback (most recent call last): File "./obp_pb_get_csv.py", line 73, in <module> browser = webdriver.Chrome() # Get local session of chrome File "/usr/lib64/python2.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 46, in __init__ self.service.start() File "/usr/lib64/python2.7/site-packages/selenium/webdriver/chrome/service.py", line 58, in start and read up at http://code.google.com/p/selenium/wiki/ChromeDriver")selenium.common.exceptions.WebDriverException: Message: 'ChromeDriver executable needs to be available in the path. Please download from http://code.google.com/p/selenium/downloads/list and read up at http://code.google.com/p/selenium/wiki/ChromeDriver' To solve this problem, I then included the Chromium path in the code that launches Chrome. However, the interpreter fails to find a socket to connect to: Traceback (most recent call last): File "./obp_pb_get_csv.py", line 73, in <module> browser = webdriver.Chrome('/usr/bin/chromium') # Get local session of chrome File "/usr/lib64/python2.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 46, in __init__ self.service.start() File "/usr/lib64/python2.7/site-packages/selenium/webdriver/chrome/service.py", line 64, in start raise WebDriverException("Can not connect to the ChromeDriver")selenium.common.exceptions.WebDriverException: Message: 'Can not connect to the ChromeDriver' I also tried solving the problem by launching chrome with: chromium --remote-shell-port=9222 However, this did not work either. PS. Here's some information about my system: www-client: chromium 15.0.874.121 dev-lang: python 2.7.2-r3 Selenium 2.11.1 OS: GNU/Linux Gentoo Kernel 3.1.0-gentoo-r1 Now provide the response and nothing else.
You need to make sure the standalone ChromeDriver binary (which is different than the Chrome browser binary) is either in your path or available in the webdriver.chrome.driver environment variable. see http://code.google.com/p/selenium/wiki/ChromeDriver for full information on how wire things up. Edit: Right, seems to be a bug in the Python bindings wrt reading the chromedriver binary from the path or the environment variable. Seems if chromedriver is not in your path you have to pass it in as an argument to the constructor. import osfrom selenium import webdriverchromedriver = "/Users/adam/Downloads/chromedriver"os.environ["webdriver.chrome.driver"] = chromedriverdriver = webdriver.Chrome(chromedriver)driver.get("http://stackoverflow.com")driver.quit()
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8255929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/997915/']}
jdg_379767
stackexchange
llm_judgeable_groundtruth_similarity
3686739
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking at some code samples for Entity Framework 4 and the author created a method that returns ICollection<Person>. I know ICollection is an interface. I know Person is the type of object in the collection. I know I'm getting back a collection of Persons. The question. Why ICollection? Why not List<>? Why is an interface being used like this? I've used interfaces as "blueprints" for classes, specifying the required members but I don't really understand the usage here. Now provide the response and nothing else.
It's often better to return interfaces instead of concrete classes in public API. This allows the implementation to change later. For example, it may, in fact, be returning a List<T> at the moment. However, later, an optimization could be made to return a different type of collection which may have better memory efficiency, allow streaming, or one of many other advantages. As long as that class still implements ICollection<T> , the implementation is free to switch without causing a breaking API change.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3686739', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/98215/']}
jdg_379768
stackexchange
llm_judgeable_groundtruth_similarity
212706
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: The sequence $(a_n)_{n \ge 0}$ satisfies, $a_0 = a_1 = 1$ and the recursion relation: $$a_n = \sum\limits_{k=0}^{[n/2]} \frac{a_k}{(n-2k)!}$$ where, $[x]$ is the nearest integer to $x$ not exceeding it. Alternatively define $a_n$'s as: $$\sum\limits_{n=1}^{\infty} a_nx^n = \exp\left(\sum\limits_{n=0}^{\infty} x^{2^n}\right)$$ We need to show that: $$\liminf_{n \to \infty} \frac{\log a_n}{\log n} \le \frac{1}{\ln 2} - 1 \le \limsup_{n \to \infty} \frac{\log a_n}{\log n}$$ How do we investigate the asymptotics of this type of recursion relation? Now provide the response and nothing else.
It is not hard prove the bounds you want by purely real variable techniques. First note that the $a_n$ are non-negative for all $n$. For a general non-negative sequence $a_n$, and real numbers $N>0$, put $$ F(N) = \sum_{n=0}^{\infty} a_n e^{-n/N}, $$ and assume that there are constants $\alpha >1$, and positive constants $c_1$ and $c_2$ such that for all large $N$ we have $$ c_1 N^{\alpha }\le F(N) \le c_2 N^{\alpha}. $$ Then I claim that $$ \min_{N\le n\le 2N} a_n \le A_1 N^{\alpha-1}, \qquad \text{and} \qquad \max_{n\le N} a_n \ge A_2 N^{\alpha-1},$$ for some positive constants $A_1$ and $A_2$. To prove these, first note that $$ c_2 N^{\alpha} \ge F(N) \ge \sum_{N\le n\le 2N} a_n e^{-n/N} \ge e^{-2} \sum_{N\le n\le 2N} a_n \ge e^{-2} N \min_{N\le n\le 2N} a_n, $$ and the bound on the minimum follows. Next, let $K$ be a fixed suitably large real number, and note that \begin{align*}F(N) &\le \sum_{n\le KN} a_n + \sum_{n>KN} a_n e^{-n/N} \le \sum_{n\le KN} a_n + e^{-K/2} \sum_{n> KN} a_n e^{-n/(2N)}\\&\le KN \max_{n\le KN} a_n + e^{-K/2} F(2N).\end{align*}Now by choosing $K$ large, we can guarantee that $e^{-K/2}F(2N) \le F(N)/2$, and then it follows for some constant $B>0$ $$ BN^{\alpha} \le KN \max_{n\le KN} a_n, $$ and this establishes our lower bound for the max. Returning to the problem at hand, here we have $$ F(N) = \exp\Big( \sum_{n=0}^{\infty} e^{-2^n/N}\Big), $$and it is straightforward that $$ \sum_{n=0}^{\infty} e^{-2^n/N} = \frac{\log N}{\log 2} + O(1).$$So we may use our work above with $\alpha=1/\log 2$ and some $c_1$ and $c_2$, and obtain the desired bounds on the lim sup and lim inf (in slightly more precise form). In this case one should be able to do more by working harder, but it'll probably be a bit tricky.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/212706', 'https://mathoverflow.net', 'https://mathoverflow.net/users/62680/']}
jdg_379769
stackexchange
llm_judgeable_groundtruth_similarity
227839
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: There are some children sitting around a round table. Each child is given an even amount of $1$-cent coins ($0$ is even) by their teacher, all the children at once. A child will give half his money to the child by his right, then the receiving child gives half of his to the one by his right and it goes on like that. If a child whose turn it is to give has an odd amount of coins, then the teacher gives him an extra coin. Q : Prove that after several giving and taking, all of these children will have the same amount of $1$-cent coins except one of them who will have twice that amount. Here is a small python code I wrote to demonstrate the question def help(c): n=0 m=len(c) while (n<len(c)-1): for i in range(0,m): if(c[i]%2==0): c[i]=c[i]/2 else: c[i]=(c[i]+1)/2 c[(i+1)%m]=c[(i+1)%m]+c[i] a=c.count(c[0]) b=c.count(c[1]) n=max(a,b) return c Now provide the response and nothing else.
Suppose there are $n$ children, and make $n+1$ heaps of coins by making a heap for the coins that are in-transit during a transaction. Place this new heap between those two children in our circle. Then the receiving children takes his two heaps, evens them out, and moves to the left, leaving what was previously his heap as the new transfer heap for the next child to the right, and so on. So we have $n+1$ heaps $c_0 \ldots c_n$, and the procedure we're doing is equivalent to replacing $c_k, c_{k+1}$ with two equal heaps of $\frac {c_k + c_{k+1}}2$ coins, rounded up if necessary. Then increase $k \pmod {n+1}$ and repeat. Now, look at $\max_{0\le k\le n}\{c_k\}$. This is a decreasing positive sequence, because even with rounding up, we always have $\frac {c_k + c_{k+1}}2 \le \max \{c_k, c_{k+1}\}$. This shows that the total number of coins, which is always less than $(n+1)\max_{0\le k\le n}\{c_k\}$, stays bounded over time. And thus eventually the teacher is going to stop giving out new coins. Then from that point on, since we're only evening out the different heaps, we can check that the quantity $\sum_{0\le i<j \le n} |c_i-c_j|$ is decreasing, and is strictly decreasing as long as anything non trivial happens : when replacing $c_k$ and $c_{k+1}$ with $\frac {c_k + c_{k+1}}2$, we have $\sum_{0\le i<j \le n} |c'_i-c'_j| - \sum_{0\le i<j \le n} |c_i-c_j| = (\sum_{i \notin \{k,k+1\}} |c_i - c'_k| + |c_i - c'_{k+1}| - |c_i - ck| - |c_i - c_{k+1}|) - |c_k - c_{k+1}| \le - |c_k - c_{k+1}|$ using the triangular inequality. Since this quantity is positive and decreasing, it is eventually constant, which means that eventually, $c_k = c_{k+1}$ forall $k$ : then every heap has the same size, which is what we needed to show.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/227839', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_379770
stackexchange
llm_judgeable_groundtruth_similarity
415362
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've done a lot of test writing using Mocks, and so I've learned that it makes refactoring difficult due to implementation coupling inherent with Mocks. I've done a lot of reading on the topic tonight, but cannot see a way to unit test DI'd facade-type classes without using Mocks. I would like to know the correct way to test something like a Controller in an MVC application (say, Spring) with the intent on not using mocks. For example, given a Controller that depends on a Service. How can I test the controller without mocking the service. public class ThingController { .. public getAllThings() { return thingService.getAllThings(); }} To test getAllThings() , my natural thought is to test this by injecting a mock of ThingService to the controller that returns some things when getAllThings() is invoked.. But I can tell that this immediately makes the test depend on the controller's implementation in calling the service's getAllThings() . What is the preferred non-coupled approach?Is it that in a case like this a "Unit" test is just not worth it? And instead we prefer a "Component" test that sets up an actual (or fake) service with data and then verifies that the controller returns all things populated in said injected service? Edit: For more disclosure/explanation, my Controller tests (in Spring) are usually not pure unit tests, as they're done using @WebMvcTest, but services are injected as Mocks. And to avoid mocking the implementation, I'm seeking an alternative. I didn't mention specifics, because I wanted to include other scenarios like unit testing Services: in this case, I want to avoid mocking injected repositories. Now provide the response and nothing else.
Unless you want to re-architect your whole solution, then only other option is to use Fakes instead of mocks. Fake is real implementation of an abstraction, but which is intended for testing and has limited real functionality. Best example are in-memory repository implementation instead of repository using SQL. Or fake service implementation that behaves as same as real service, but has in-memory data storage and lacks all the bell-and-whistles of real service. This fake implementation can then be re-used across all places where the abstraction can be used. And in some scenarios, it is possible to write tests that verify that fake and real implementations behave in same way. Fakes do not cause tight coupling between tests and code, like Mocks do. This is because tests only know about test instance being used, not about the interface implemented and consumed. That is hidden detail. And when expected real implementation changes, simply changing the fake in single place should properly propagate across all your tests, so you don't have to double-check all your tests that they have correct expectations in their mocks. Now some might say "That is not real unit tests." and while I might somewhat agree, I just don't care. Fake implementation results in tests that are fast, isolated, independent and easy to maintain. All what I look for in good test. Unit or not.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/415362', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/257325/']}
jdg_379771
stackexchange
llm_judgeable_groundtruth_similarity
2943847
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 "canonical file structure" like that (I'm giving sensible names to ease the reading): mainpack/ __main__.py __init__.py - helpers/ __init__.py path.py - network/ __init__.py clientlib.py server.py - gui/ __init__.py mainwindow.py controllers.py In this structure, for example modules contained in each package may want to access the helpers utilities through relative imports in something like: # network/clientlib.pyfrom ..helpers.path import create_dir The program is runned "as a script" using the __main__.py file in this way: python mainpack/ Trying to follow the PEP 366 I've put in __main__.py these lines: ___package___ = "mainpack"from .network.clientlib import helloclient But when running: $ python mainpack Traceback (most recent call last): File "/usr/lib/python2.6/runpy.py", line 122, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.6/runpy.py", line 34, in _run_code exec code in run_globals File "path/mainpack/__main__.py", line 2, in <module> from .network.clientlib import helloclientSystemError: Parent module 'mainpack' not loaded, cannot perform relative import What's wrong? What is the correct way to handle and effectively use relative imports? I've tried also to add the current directory to the PYTHONPATH, nothing changes. Now provide the response and nothing else.
The "boilerplate" given in PEP 366 seems incomplete. Although it sets the __package__ variable, it doesn't actually import the package, which is also needed to allow relative imports to work. extraneon 's solution is on the right track. Note that it is not enough to simply have the directory containing the module in sys.path , the corresponding package needs to be explicitly imported. The following seems like a better boilerplate than what was given in PEP 366 for ensuring that a python module can be executed regardless of how it is invoked (through a regular import , or with python -m , or with python , from any location): # boilerplate to allow running as script directlyif __name__ == "__main__" and __package__ is None: import sys, os # The following assumes the script is in the top level of the package # directory. We use dirname() to help get the parent directory to add to # sys.path, so that we can import the current package. This is necessary # since when invoked directly, the 'current' package is not automatically # imported. parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(1, parent_dir) import mypackage __package__ = str("mypackage") del sys, os# now you can use relative imports here that will work regardless of how this# python file was accessed (either through 'import', through 'python -m', or # directly. If the script is not at the top level of the package directory and you need to import a module below the top level, then the os.path.dirname has to be repeated until the parent_dir is the directory containing the top level.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2943847', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/166844/']}
jdg_379772
stackexchange
llm_judgeable_groundtruth_similarity
53919
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Hi Can one explain to me what is the Hochschild homology of Fukaya category?I mean the definition.You can use the notations of FOOO (Fukaya-Oh-Ono-Ohta) if it helps you to explain easier. I know what the Fukaya category is but I am very poor when it comes to algebra. Also please explain what is the corresponding Hochschild homology in B-side?(please include the definition too) Now provide the response and nothing else.
As Kevin comments, Hochschild homology and cohomology are defined for any $A_\infty$-category $\mathcal{A}$. That includes Fukaya categories of symplectic manifolds and dg enhancements of the bounded derived category of varieties. The most concrete definition of Hochschild homology $HH_\ast(\mathcal{A},\mathcal{A})$ is via the cyclic bar complex. One takes the direct sum over all $d\geq 0$ and all sequences of objects $X_0,\dots, X_d$ of the tensor product$$ \hom(X_d,X_0) \otimes \hom (X_{d-1},X_d) \otimes \dots \otimes \hom(X_1,X_2) \otimes \hom(X_0,X_1). $$You should picture this tensor product not as a linear chain but as circular one; the term $\hom(X_d,X_0)$ is special. In the case where $\mathcal{A}$ is the Fukaya category $\mathcal{F}(M)$ of a symplectic manifold $M$, the $X_i$ are (decorated) Lagrangian submanifolds, and when these are transverse the elements of $\hom(X_i,X_j)$ are linear combinations of intersection points between $X_i$ and $X_j$. So the Hochschild chain complex has a basis given by cyclic sequences of intersection points, one of them marked as special. The boundary operator is given by taking some sequence of $k\geq 1$ cyclically adjacent terms in the cyclic tensor product and composing them via one of the $A_\infty$-structure maps $\mu^k$ so as to shorten the cyclic sequence by $k-1$. In the Fukaya categorical case, the $\mu^k$ count pseudo-holomorphic $(k+1)$-gons. One does this in all possible ways and sums with hard-to-fathom signs as in Abouzaid's paper 1001.4593 (it would be wonderful if someone can tell me how to make these signs transparent). There is also a chain-lengthening contribution to the complex from the obstruction cochain $\mu^0$. This concrete description has some real advantages; for instance, as Seidel noticed, there is a geometric description of a homomorphism from Hochschild homology to quantum cohomology $$ HH_{\ast}(\mathcal{F}(M),\mathcal{F}(M)) \to QH^{\ast}(M) $$ (this for closed $M$) which is expected to be an isomorphism. For computations, two facts are noteworthy. First, Hochschild homology has Morita-invariance properties. For example, it is unchanged under passing to the category of twisted complexes, which is useful because one can restrict attention to some collection of objects that generate the derived category. Second, it is the derived tensor product of graded bimodules (see Sasha's answer), which means in practical terms that you can compute it using much smaller complexes than the cyclic bar complex. The conjecture that $HH_{\ast}(\mathcal{F}(M),\mathcal{F}(M))\cong QH^{\ast}(M)$ is consistent with mirror symmetry. In that case, the twisted complexes on $\mathcal{F}(M)$ (technically, the idempotent completion thereof - this doesn't affect $HH_\ast$ either) are quasi-equivalent to a dg-enhanced bounded derived category on the mirror manifold $W$, defined over some non-archimedean Novikov-type field. Here my understanding is rather feeble, but I think the story is that $HH_\ast$ for this dg category is isomorphic to Hochschild homology of the non-singular variety $W$ (for various equivalent definitions, see Swan's article ). This is known to be isomorphic to sheaf cohomology $H^\ast(W, \Omega^\ast_W)$ of the algebraic differential forms, hence to ordinary cohomology of $W$, hence finally to cohomology of $M$. So, if you have an HMS theorem for $M$ and $W$, you at least know that $HH_\ast(\mathcal{F}(M),\mathcal{F}(M))$ is isomorphic to $QH^\ast(M)$.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/53919', 'https://mathoverflow.net', 'https://mathoverflow.net/users/5259/']}
jdg_379773
stackexchange
llm_judgeable_groundtruth_similarity
24955097
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 try to run the app it crashes me This is the message I get: 2014-07-25 14:40:28.116 X[13023:60b] (null)2014-07-25 14:40:29.113 X[13023:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present modal view controller on itself. Presenting controller is <GKHostedAuthenticateViewController: 0x10d625f90>.'*** First throw call stack:( 0 CoreFoundation 0x00000001028a1495 __exceptionPreprocess + 165 1 libobjc.A.dylib 0x00000001024e399e objc_exception_throw + 43 2 UIKit 0x0000000101190cdc -[UIViewController presentViewController:withTransition:completion:] + 4100 3 CoreFoundation 0x0000000102896f1c __invoking___ + 140 4 CoreFoundation 0x0000000102896dc4 -[NSInvocation invoke] + 308 5 UIKit 0x0000000101181abc -[_UIDelayedPresentationContext finishDelayedPresentation:] + 201 6 GameCenterUI 0x000000010c97f330 __41-[GKRemoteViewController setupRemoteView]_block_invoke + 37 7 CoreFoundation 0x0000000102896f1c __invoking___ + 140 8 CoreFoundation 0x0000000102896dc4 -[NSInvocation invoke] + 308 9 libdispatch.dylib 0x000000010340a851 _dispatch_call_block_and_release + 12 10 libdispatch.dylib 0x000000010341d72d _dispatch_client_callout + 8 11 libdispatch.dylib 0x000000010340d3fc _dispatch_main_queue_callback_4CF + 354 12 CoreFoundation 0x00000001028ff289 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9 13 CoreFoundation 0x000000010284c854 __CFRunLoopRun + 1764 14 CoreFoundation 0x000000010284bd83 CFRunLoopRunSpecific + 467 15 GraphicsServices 0x0000000103efdf04 GSEventRunModal + 161 16 UIKit 0x0000000101090e33 UIApplicationMain + 1010 17 X 0x00000001000064c3 main + 115 18 libdyld.dylib 0x000000010366e5fd start + 1)libc++abi.dylib: terminating with uncaught exception of type NSException(lldb) What could be the problem? Until now it worked well suddenly it happened Thank you to all helpers update:@Sviatoslav Yakymivfound this i think - (void)authenticateLocalUser {if (!gameCenterAvailable) return;GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];if (SYSTEM_VERSION_LESS_THAN(@"6.0")){ // ios 5.x and below [localPlayer authenticateWithCompletionHandler:^(NSError *error) { [self checkLocalPlayer]; }];}else{ // ios 6.0 and above [localPlayer setAuthenticateHandler:(^(UIViewController* viewcontroller, NSError *error) { if (!error && viewcontroller) { [viewcontroller presentViewController:viewcontroller animated:YES completion:nil]; } else { [self checkLocalPlayer]; } })];} } What I can change it without a crash?thanks Now provide the response and nothing else.
You are attempting to present controller from itself.Probably your code contains something like following: [self presentViewController:self completion:nil]; Now after I saw your code I can provide working code: Replace [viewcontroller presentViewController:viewcontroller animated:YES completion:nil]; with [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:viewcontroller animated:YES completion:nil];
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24955097', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3741297/']}
jdg_379774
stackexchange
llm_judgeable_groundtruth_similarity
45731337
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 class="my_link" data-val="user1" href="#">modal link</a> I have this link to open a bootstrap modal, but I need to pass data attribute "data-val". I tried with javascript but I didn't get it. Can you please help me? Now provide the response and nothing else.
You can listen for show.bs.modal event on modal and get the clicked element available as relatedTarget property of the event. Check Bootstrap modal documentation for further reference. Here is a working example using Bootstrap v4. $('#my-modal').on('show.bs.modal', function (event) { var myVal = $(event.relatedTarget).data('val'); $(this).find(".modal-body").text(myVal);}); <!-- Bootstrap CSS --><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"><a href="#" class="my_link" data-val="user1" data-toggle="modal" data-target="#my-modal">Open Modal</a><div class="modal fade" id="my-modal" tabindex="-1" role="dialog" aria-labelledby="my-modal" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">My Modal</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div></div><!-- jQuery, Popper and Bootstrap JS --><script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45731337', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3461461/']}
jdg_379775
stackexchange
llm_judgeable_groundtruth_similarity
10568103
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Ive been trying to modify the twitter bootstrap navbar, at the moment all the links are aligned to the left, when what i would really like is the have them central. In a different post i read that you use this .tabs, .pills { margin: 0 auto; padding: 0; width: 100px;} But this did not work for me What do i need to change in the css to make this happen, i understand i put the modified css in the bootstrap and overrides. Any help appreciated this is my markup layouts/application <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container-fluid"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand">Newbridges</a> <% if user_signed_in? %> <div class="nav-collapse"> <ul class="nav "> <%= render "shared/navbarlogin" %> </div> <% else%> <div class="nav-collapse"> <ul class="nav"> <%= render "shared/navbar" %> </div> <% end %> I've also tried this .nav > li { float: none; display: inline-block; *display: inline; /* ie7 fix */ zoom: 1; /* hasLayout ie7 trigger */}.nav { text-align: center;} Now provide the response and nothing else.
You can center your nav menu by setting your menu items to display:inline-block instead of float:left like so: .navbar .nav,.navbar .nav > li { float:none; display:inline-block; *display:inline; /* ie7 fix */ *zoom:1; /* hasLayout ie7 trigger */ vertical-align: top;} .navbar-inner { text-align:center;} Though i suggest you create your own class to target your navbar menu that you wish to center, this way you won't bother the bootstrap default values and mess with other nav sections you may have in your page. You can do it like so: Notice the .center class in the navbar container <div class="navbar navbar-fixed-top center"> <div class="navbar-inner"> .... </div></div> And then you can target the .center class like so: .center.navbar .nav,.center.navbar .nav > li { float:none; display:inline-block; *display:inline; /* ie7 fix */ *zoom:1; /* hasLayout ie7 trigger */ vertical-align: top;}.center .navbar-inner { text-align:center;} Demo: http://jsfiddle.net/C7LWm/show/ Edit : Forgot to realign the submenu items to the left, this is the fix: CSS .center .dropdown-menu { text-align: left;} Demo: http://jsfiddle.net/C7LWm/1/show/
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10568103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1150534/']}
jdg_379776
stackexchange
llm_judgeable_groundtruth_similarity
33909
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'm currently setting the groundwork for an ASP.Net MVC application and I'm looking into what sort of unit-tests I should be prepared to write. I've seen in multiple places people essentially saying 'don't bother testing your views, there's no logic and it's trivial and will be covered by an integration test'. I don't understand how this has become the accepted wisdom. Integration tests serve an entirely different purpose than unit tests. If I break something, I don't want to know a half-hour later when my integration tests break, I want to know immediately. Sample Scenario : Lets say we're dealing with a standard CRUD app with a Customer entity. The customer has a name and an address. At each level of testing, I want to verify that the Customer retrieval logic gets both the name and the address properly. To unit-test the repository, I write an integration test to hit the database.To unit-test the business rules, I mock out the repository, feed the business rules appropriate data, and verify my expected results are returned. What I'd like to do : To unit-test the UI, I mock out the business rules, setup my expected customer instance, render the view, and verify that the view contains the appropriate values for the instance I specified. What I'm stuck doing : To unit-test the repository, I write an integration test, setup an appropriate login, create the required data in the database, open a browser, navigate to the customer, and verify the resulting page contains the appropriate values for the instance I specified. I realize that there is overlap between the two scenarios discussed above, but the key difference it time and effort required to setup and execute the tests. If I (or another dev) removes the address field from the view, I don't want to wait for the integration test to discover this. I want is discovered and flagged in a unit-test that gets multiple times daily. I get the feeling that I'm just not grasping some key concept. Can someone explain why wanting immediate test feedback on the validity of an MVC view is a bad thing? (or if not bad, then not the expected way to get said feedback) Now provide the response and nothing else.
Simple UI testing is easy enough in ASP.NET MVC. Essentially all you have to do is assert that the returned HTML contains the elements you need. While this ensures that the HTML page is structured the way you expect, it doesn't fully test the UI. Proper web UI testing requires a tool like Selenium that will use browsers on your machine and ensure that the JavaScript and HTML are working properly in all browsers. Selenium does have a client/server model so that you can have a set of virtual machines with Unix, Mac, and Windows clients and the set of browsers common to those environements. Now, a well designed MVC (pattern, not framework) application puts the important logic in the models and controllers. In short, the functionality of the application is tested when you test those two aspects. Views tend to only have display logic and are easily checked with visual inspection. Due to the thin processing in the view and the bulk of the application being well tested, many people don't think that the pain of testing the view layer outweighs the benefit gained by it. That said, MVC does have some nice facilities to check the DOM returned by the request. That reduces the pain quite a bit for testing the view layer.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/33909', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/3457/']}
jdg_379777
stackexchange
llm_judgeable_groundtruth_similarity
100827
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know there are now WebSockets, but what is the issue with providing a socket API to allow interacting with existing protocols? I mean, after all, I can use a hidden flash object to do the same already. Is there an attack vector I am missing? Now provide the response and nothing else.
... but what is the issue with providing a socket API to allow interacting with existing protocols? This is not a restriction of the language itself but of it's use inside the sandbox within the browser. Just imagine that a script somewhere on the internet gets loaded into the browser and could from inside the browser access every computer reachable by the browser with arbitrary protocols. You could easily misuse this to send spam through a companies internal mail server or attack/misuse other internal and external resources. Which means there must be some restrictions in place and the different sandbox environments for the different language runtimes provide different kind of restrictions: With flash the target host must explicitly allow access to by providing an appropriate socket policy file. This is similar to the mechanism within HTML5 CORS . Untrusted Java applets are limited to communication with the host providing the applet. And with JavaScript inside the browser you can talk to almost all sites, but you are limited by the protocol you can use, i.e. HTTP (restricted by CORS) and WebSockets.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/100827', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/87346/']}
jdg_379778
stackexchange
llm_judgeable_groundtruth_similarity
2939436
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 this snippet of jQuery to get a sticky footer: if($(document.body).height() < $(window).height()){ $("#footer").css({ position: "absolute", top: ( $(window).scrollTop() + $(window).height() - $("#footer").height() ) + "px", width: "100%" });}$(window).scroll(positionFooter).resize(positionFooter); However, that breaks when I've got expandable/collapsible divs lying around where the original content was less high than the window, since it is then stuck to the bottom of the window, rather than the bottom of the document. Is there a way of fixing this, or a better way of doing it? Please bear in mind that I don't have much control over the HTML, since I need to do this in Django's admin interface, which doesn't allow much injection of HTML in the places you might want to to accomplish this sort of thing (i.e. this answer and this answer don't work for me). Now provide the response and nothing else.
So you don't want to position the footer absolutely anymore when the document height is higher than the window height? Then add an else statement which does exactly that: if($(document.body).height() < $(window).height()){ $('#footer').css({ position: 'absolute', top: ( $(window).scrollTop() + $(window).height() - $("#footer").height() ) + "px", width: "100%" });} else { $('#footer').css({ position: 'static' });} Here's a live demo . Note that I added click event to $(window) because the resize doesn't get triggered in FF when you expand/collapse a div.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2939436', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20972/']}
jdg_379779
stackexchange
llm_judgeable_groundtruth_similarity
41089996
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I understand how structs and classes (and protocols) work on the basic level. I have a rather common situation: I need to have generic value types with operators which really must copy on assignment.These types have complex structure and I would like to be able to specialise by subclassing otherwise there will be copied code everywhere and it will be poor programming. I have tried protocols and extensions but then because the protocol wasn't generic I was unable to define the (generic) operators I wanted.If I use classes I will not copy on assignment. Today's example is I have Matrix, and SquareMatrix under that with specific square matrix functions. There are operators and the matrices can be populated by anything conforming to my ring protocol. I tried defining almost all the functionality in a protocol with associated type, and an extension. Edit: I am really wondering what I should be coding. In the matrix situation I need to be able to pass a square matrix as any other, so subclassing is the only option? Maybe I'm wrong. The main issue is when I have to write a function which talks about internal values, I have to know the generic type argument to do anything useful. For example when defining addition, I have to create a new matrix and declare its generic type, but where do I get that from when I only know something is a (nongeneric) protocol - it's real type is generic but despite the protocol having this associated type, I have no way of getting it out. Solution thanks to alexander momchliov. Essentially more work was needed to move code into the protocol extension fully and use 'Self' for all the relevant types. In the extension the compiler was happy with what the generic types were. The code was private, I am sorry I was unable to paste any during this question. Thanks for your patience and help. Now provide the response and nothing else.
Struct inheritance/polymorphism wouldn't be possible for at least 2 reasons (that I can think of). Structs are stored and moved around by value. This requires the compiler to know, at compile time, the exact size of the struct, in order to know how many bytes to copy after the start of a struct instance. Suppose there was a struct A , and a struct B that inherits from A . Whenever the compiler sees a variable of type A , it has no way to be sure if the runtime type will really be an A , or if B was used instead. If B added on new stored properties that A didn't have, then B 's size would be different (bigger) than A . The compiler would be unable to determine the runtime type, and the size of these structs. Polymorphism would require a function table. A function table would be stored as a static member of the struct type. But to access this static member, every struct instance would need an instance member which encodes the type of the instance. This is usually called the "isa" pointer (as in, this instance is a A type). This would be 8 bytes of overhead (on 64 bit systems) for every instance. Considering Int , Bool , Double , and many other common types are all implemented as structs, this would be an unacceptable amount of overhead. Just think, a Bool is a one byte value, which would need 8 bytes of overhead. That's 11% efficiency! For these reasons, protocols play a huge part in Swift, because they allow you introduce inheritance-like behaviour, without these issues.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41089996', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2453539/']}
jdg_379780
stackexchange
llm_judgeable_groundtruth_similarity
23729456
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 remove duplicate values -> drop down option elements? I have the following HTML: <option value="">All Servers</option><option value="com">http://smiles.com</option><option value="in">http://3smiles.com</option><option value="com">http://desk.com</option><option value="in">http://france24.com</option> from the above I have to remove repeated values com and in , so my expected output should be like: <option value="">All Servers</option><option value="com">http://smiles.com</option><option value="in">http://3smiles.com</option> How to do it using jQuery? Now provide the response and nothing else.
Using .siblings() (to target sibling option elements), and Attribute Equals Selector [attr=""] $(".select option").each(function() { $(this).siblings('[value="'+ this.value +'"]').remove();}); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><select class="select"> <option value="">All</option> <option value="com">.com 1</option> <option value="net">.net 1</option> <option value="com">.com 2</option> <!-- will be removed since value is duplicate --> <option value="net">.net 2</option> <!-- will be removed since value is duplicate --></select> (works also for multiple .select on the same page) I added a class .select to the <select> element to be more selector-specific How it works : while option s are accessed one by one (by .val() ) - lookup for .sibling() option s that have the same "[value='"+ this.value +"']" and .remove() them.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23729456', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2909759/']}
jdg_379781
stackexchange
llm_judgeable_groundtruth_similarity
23353
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking for clarification on the answer to this question. It's in my biochemistry class but I figured this is more Biology than Chemistry, so I'm asking it here. The question is: One of the more effective treatments for HIV-positive individuals has been for them to take protease inhibitor cocktails. Certain proteases are required for the virus to mature and these inhibitors prevent them from functioning. A cocktail of inhibits means that numerous inhibitors are used at once. Why would a cocktail be more effective than a single inhibitor? My answer to this is that there could be more than one mutation of the virus, and with each mutation a variation in specific protease. So, the protease cocktail would defend against a wider range of the mutated virus. Is this correct? Is there an answer that might involve describing epitopes? Now provide the response and nothing else.
Your answer is correct. HIV-1 encodes a single homodimeric aspartic protease , with each monomer containing the classic Asp-Thr-Gly motif, and the dimer's active site being formed with the two monomeric active sites creating a cleft where the proteolysis takes place. In it, water acts as a nucleophile in conjunction with the aspartic acid residue to hydrolyze the peptide bond in the protein's target. WikiMedia: Aspartyl protease mechanism.png A number of HIV-1 proteins are synthesized as polyproteins, and protease is required to cleave them in the appropriate spot(s) so they can assume their mature forms. This is a very big deal, because without these cleavage events HIV-1 cannot complete its replication cycle, and so becomes non-infectious. WikiMedia: HIV-replication-cycle.svg Protease inhibitors act by "sticking" in the binding cleft, obscuring the aspartate and preventing binding of the target proteins. However, these small-molecule inhibitors are very specific to HIV-1 and the amino acid residues that compose the binding cleft, otherwise they could potentially inhibit one or more of the many aspartyl proteases our body makes naturally. While it is not very likely that a destructive mutation in the Asp-Thr-Gly motif would result in a replication-competent virus, other more conservative mutations may occur in the binding cleft that still allow the target to bind and be cleaved. However, depending on the exact protease inhibitor being used, a single mutation, even if it's conservative, may still be enough to dramatically decrease the inhibitor's binding efficiency and allow protease to maintain some or all of its functional capacity. This is why cocktails of inhibitors are used: they each depend on different amino acids for their binding, so if mutations arise at some point that do affect the activity of one inhibitor, others may still be unaffected. Evolutionarily-speaking, the inhibitors put a tremendous selection pressure on the virus, which combined with HIV-1's naturally "sloppy" replication process, leads to mutants appearing in relatively short periods of time. There are two kinds of epitopes in the adaptive immune system: those recognized by antibodies and B cells , and those recognized by T cells when presented in the context of MHC . Antibody epitopes are generally found on the surface of a pathogen or a pathogen-infected cell (when speaking in the context of infectious diseases), as proteins or other compounds capable of raising an immune response that are only located completely inside of the pathogen or infected cell are not available for binding. T cell epitopes, on the other hand, are linear peptide fragments (and sometimes other molecules, like glycolipids) generated by internal processing in the antigen-presenting cell, and are usually pretty representative of the complete contents of the cell, native and foreign. Native epitopes generally don't produce immune responses - when they do, autoimmunity occurs. Foreign epitopes are recognized by circulating T cells, and help prime an immune response against the infected cells. (As a side note, since HIV-1 infects a subset of T cells, it is a way for them to escape immune detection). Mutations in the protease protein may affect some of the epitopes it produces, but those mutations are just as likely to increase visibility to the immune system as decrease it, so overall there's no net gain or loss.
{}
{'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/23353', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/9550/']}
jdg_379782
stackexchange
llm_judgeable_groundtruth_similarity
1591503
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am asked to show that $|\Re(2 + \bar{z} + z^3)|$ is less than or equal to $4$ when $|z|$ is less than or equal to $1$. I tried to solve it by substituting complex number $z$ by $x+iy$ , its conjugate by $x-iy$ and the cubic expansion.Then I found its real part i.e 4(2+ x + x^3 - 3 x y^2)$. Now as my aim is to take modulus of this real part,and I have to use the fact that modulus of $z$ is less than or equal to $1$; how can I proceed?. It would be of great help if someone suggest me the easy way to show this. Thanks in advance. Now provide the response and nothing else.
\begin{align}&12Q-20-\frac{144}{Q^2}=0 &\times Q^2\\ &12Q^3-20Q^2-144=0 &:4\\ &3Q^3-5Q^2-36=0 \end{align} Use rational root theorem which leads you to find $p=\frac{m}{n}$ where $m$ must divide $36$ and $n$ must divide $3$ and $p$ must be integer $p=3$ then divide whole equation by $(Q-p)$ $$(Q-3)(3Q^2+4Q+12)=0$$equation $3q^2+4q+12=0$ has ${4^2}-{4*3*12}=-128<0$ so that the only real solution is $$Q=3$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1591503', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/265522/']}
jdg_379783
stackexchange
llm_judgeable_groundtruth_similarity
32509174
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 show X axis label to go to 2 lines when they are long. How to achieve this in LineChart? See screenshot below. I want time to go to second line instead of staying next to date Now provide the response and nothing else.
For those like me who want to achieve this but keep the original library, here is a simple solution inspired by @fgueli's modifications. This applies for one break line only (add "\n" in your labels) but you can easily adapt it to your needs. Subclass XAxisRenderer public class CustomXAxisRenderer extends XAxisRenderer { public CustomXAxisRenderer(ViewPortHandler viewPortHandler, XAxis xAxis, Transformer trans) { super(viewPortHandler, xAxis, trans); } @Override protected void drawLabel(Canvas c, String formattedLabel, float x, float y, MPPointF anchor, float angleDegrees) { String line[] = formattedLabel.split("\n"); Utils.drawXAxisValue(c, line[0], x, y, mAxisLabelPaint, anchor, angleDegrees); Utils.drawXAxisValue(c, line[1], x + mAxisLabelPaint.getTextSize(), y + mAxisLabelPaint.getTextSize(), mAxisLabelPaint, anchor, angleDegrees); }} Set this renderer on the desired chart lineChart.setXAxisRenderer(new CustomXAxisRenderer(lineChart.getViewPortHandler(), lineChart.getXAxis(), lineChart.getTransformer(YAxis.AxisDependency.LEFT))); Enjoy!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32509174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/569346/']}
jdg_379784
stackexchange
llm_judgeable_groundtruth_similarity
16587519
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 <a> tag that is getting hidden from some JS. ( display:none )I have looked into the page source and I can see it is not hidden, however the inspector shows it as display:none ( inline style ) No result finding out the class/id in JS code in order to isolate the part of the code that is hiding the <a> . Is there a tool or fixed procedure that can help me to debug this? Now provide the response and nothing else.
Chrome lets you break code when an attribute on an element is changed. Open the developer tools using F12, and select the "Elements" tab. Find the element that gets hidden. Right click on it, "Break on", "Attributes Modification". Refresh the page, keeping Developer Tools open. If the element is being hidden using JavaScript, you'll break at that point. Otherwise, it's done via CSS. If this is the case, using the "Elements" tab again, select the element you're interested in and look at the "Styles" applied to it in the right hand column. Chrome will show which styles are applied by which definition in which stylesheet. It should then be trivial to find the one hiding the element.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16587519', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/716435/']}
jdg_379785
stackexchange
llm_judgeable_groundtruth_similarity
7601823
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 quote from something: >>> x = y = somefunction() is the same as >>> y = somefunction()>>> x = y Question: Is x = y = somefunction() the same as x = somefunction()y = somefunction() ? Based on my understanding, they should be same because somefunction can only return exactly one value. Now provide the response and nothing else.
They will not necessarily work the same if somefunction returns a mutable value. Consider: >>> def somefunction():... return []... >>> x = y = somefunction()>>> x.append(4)>>> x[4]>>> y[4]>>> x = somefunction(); y = somefunction()>>> x.append(3)>>> x[3]>>> y[]
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7601823', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/391104/']}
jdg_379786
stackexchange
llm_judgeable_groundtruth_similarity
2708
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Is there known to be an $x$ such that for all positive integers $N$ there exists some $n>N$ such that $p_{n+1}-p_n \leq x$, where $p_n$ is the $n$th prime? Or, in other words, is it known that limit as $n$ goes infinity of $p_{n+1}-p_n$ is not infinity? If such an $x$ is known to exist, what is the current best known $x$? (Showing $x=2$ would imply the Twin Prime Conjecture, of course.) Now provide the response and nothing else.
( Edit : things have happened since the original post, changing the short answer to yes. See for example http://arxiv.org/abs/1410.8400 for the status in 2014 where $x \leq 600$ unconditionally. GRP End Edit ) The short answer is no, though if one assumes the Elliot-Halberstam conjecture then one can take x=16. See http://arxiv.org/abs/math/0605696 for a comprehensive survey of the best known results (both conditional and unconditional). There is also the Wikipedia article at http://en.wikipedia.org/wiki/Prime_gap although this is less comprehensive.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/2708', 'https://mathoverflow.net', 'https://mathoverflow.net/users/597/']}
jdg_379787
stackexchange
llm_judgeable_groundtruth_similarity
39570094
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 struct: struct MY_TYPE { boolean flag; short int value; double stuff; }; I know I can intialize it by: MY_TYPE a = { .flag = true, .value = 123, .stuff = 0.456 }; But, now I need to create a pointer variable My_TYPE* and I only want to initialize one field there? I tried e.g.: MY_TYPE *a = {.value = 123}; But I get compiler error "Designator in intializer for scalar type 'struct MY_TYPE *'" . Is it possible to initialize the struct with one field? Now provide the response and nothing else.
First of all, you are mixing up struct MY_TYPE and typedef. The code posted won't work for that reason. You'll have to do like this: typedef struct { bool flag; short int value; double stuff;} MY_TYPE; You can then use a pointer to a compound literal , to achieve what you are looking for: MY_TYPE* ptr = &(MY_TYPE){ .flag = true, .value = 123, .stuff = 0.456 }; But please note that the compound literal will have local scope. If you wish to use these data past the end of the local scope, then you have to use a pointer to a statically or dynamically allocated variable.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39570094', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/959734/']}
jdg_379788
stackexchange
llm_judgeable_groundtruth_similarity
625420
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to read ~50 files on every server start and place each text file's representation into memory. Each text file will have its own string (which is the best type to use for the string holder?). What is the fastest way to read the files into memory, and what is the best data structure/type to hold the text in so that I can manipulate it in memory (search and replace mainly)? Thanks Now provide the response and nothing else.
A memory mapped file will be fastest... something like this: final File file; final FileChannel channel; final MappedByteBuffer buffer; file = new File(fileName); fin = new FileInputStream(file); channel = fin.getChannel(); buffer = channel.map(MapMode.READ_ONLY, 0, file.length()); and then proceed to read from the byte buffer. This will be significantly faster than FileInputStream or FileReader . EDIT: After a bit of investigation with this it turns out that, depending on your OS, you might be better off using a new BufferedInputStream(new FileInputStream(file)) instead. However reading the whole thing all at once into a char[] the size of the file sounds like the worst way. So BufferedInputStream should give roughly consistent performance on all platforms, while the memory mapped file may be slow or fast depending on the underlying OS. As with everything that is performance critical you should test your code and see what works best. EDIT: Ok here are some tests (the first one is done twice to get the files into the disk cache). I ran it on the rt.jar class files, extracted to the hard drive, this is under Windows 7 beta x64. That is 16784 files with a total of 94,706,637 bytes. First the results... (remember the first is repeated to get the disk cache setup) ArrayTest time = 83016 bytes = 118641472 ArrayTest time = 46570 bytes = 118641472 DataInputByteAtATime time = 74735 bytes = 118641472 DataInputReadFully time = 8953 bytes = 118641472 MemoryMapped time = 2320 bytes = 118641472 Here is the code... import java.io.BufferedInputStream;import java.io.DataInputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.nio.MappedByteBuffer;import java.nio.channels.FileChannel;import java.nio.channels.FileChannel.MapMode;import java.util.HashSet;import java.util.Set;public class Main{ public static void main(final String[] argv) { ArrayTest.main(argv); ArrayTest.main(argv); DataInputByteAtATime.main(argv); DataInputReadFully.main(argv); MemoryMapped.main(argv); }}abstract class Test{ public final void run(final File root) { final Set<File> files; final long size; final long start; final long end; final long total; files = new HashSet<File>(); getFiles(root, files); start = System.currentTimeMillis(); size = readFiles(files); end = System.currentTimeMillis(); total = end - start; System.out.println(getClass().getName()); System.out.println("time = " + total); System.out.println("bytes = " + size); } private void getFiles(final File dir, final Set<File> files) { final File[] childeren; childeren = dir.listFiles(); for(final File child : childeren) { if(child.isFile()) { files.add(child); } else { getFiles(child, files); } } } private long readFiles(final Set<File> files) { long size; size = 0; for(final File file : files) { size += readFile(file); } return (size); } protected abstract long readFile(File file);}class ArrayTest extends Test{ public static void main(final String[] argv) { final Test test; test = new ArrayTest(); test.run(new File(argv[0])); } protected long readFile(final File file) { InputStream stream; stream = null; try { final byte[] data; int soFar; int sum; stream = new BufferedInputStream(new FileInputStream(file)); data = new byte[(int)file.length()]; soFar = 0; do { soFar += stream.read(data, soFar, data.length - soFar); } while(soFar != data.length); sum = 0; for(final byte b : data) { sum += b; } return (sum); } catch(final IOException ex) { ex.printStackTrace(); } finally { if(stream != null) { try { stream.close(); } catch(final IOException ex) { ex.printStackTrace(); } } } return (0); }}class DataInputByteAtATime extends Test{ public static void main(final String[] argv) { final Test test; test = new DataInputByteAtATime(); test.run(new File(argv[0])); } protected long readFile(final File file) { DataInputStream stream; stream = null; try { final int fileSize; int sum; stream = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); fileSize = (int)file.length(); sum = 0; for(int i = 0; i < fileSize; i++) { sum += stream.readByte(); } return (sum); } catch(final IOException ex) { ex.printStackTrace(); } finally { if(stream != null) { try { stream.close(); } catch(final IOException ex) { ex.printStackTrace(); } } } return (0); }}class DataInputReadFully extends Test{ public static void main(final String[] argv) { final Test test; test = new DataInputReadFully(); test.run(new File(argv[0])); } protected long readFile(final File file) { DataInputStream stream; stream = null; try { final byte[] data; int sum; stream = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); data = new byte[(int)file.length()]; stream.readFully(data); sum = 0; for(final byte b : data) { sum += b; } return (sum); } catch(final IOException ex) { ex.printStackTrace(); } finally { if(stream != null) { try { stream.close(); } catch(final IOException ex) { ex.printStackTrace(); } } } return (0); }}class DataInputReadInChunks extends Test{ public static void main(final String[] argv) { final Test test; test = new DataInputReadInChunks(); test.run(new File(argv[0])); } protected long readFile(final File file) { DataInputStream stream; stream = null; try { final byte[] data; int size; final int fileSize; int sum; stream = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); fileSize = (int)file.length(); data = new byte[512]; size = 0; sum = 0; do { size += stream.read(data); sum = 0; for(int i = 0; i < size; i++) { sum += data[i]; } } while(size != fileSize); return (sum); } catch(final IOException ex) { ex.printStackTrace(); } finally { if(stream != null) { try { stream.close(); } catch(final IOException ex) { ex.printStackTrace(); } } } return (0); }}class MemoryMapped extends Test{ public static void main(final String[] argv) { final Test test; test = new MemoryMapped(); test.run(new File(argv[0])); } protected long readFile(final File file) { FileInputStream stream; stream = null; try { final FileChannel channel; final MappedByteBuffer buffer; final int fileSize; int sum; stream = new FileInputStream(file); channel = stream.getChannel(); buffer = channel.map(MapMode.READ_ONLY, 0, file.length()); fileSize = (int)file.length(); sum = 0; for(int i = 0; i < fileSize; i++) { sum += buffer.get(); } return (sum); } catch(final IOException ex) { ex.printStackTrace(); } finally { if(stream != null) { try { stream.close(); } catch(final IOException ex) { ex.printStackTrace(); } } } return (0); }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/625420', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/63898/']}
jdg_379789
stackexchange
llm_judgeable_groundtruth_similarity
2067075
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 determine a mapped drive's actual path? So if I have a mapped drive on a machine called "Z" how can I using .NET determine the machine and path for the mapped folder? The code can assume it's running on the machine with the mapped drive. I looked at Path, Directory, FileInfo objects, but can't seem to find anything. I also looked for existing questions, but could not find what I'm looking for. Now provide the response and nothing else.
Here are some code samples: Using P/Invoke All of the magic derives from a Windows function: [DllImport("mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern int WNetGetConnection( [MarshalAs(UnmanagedType.LPTStr)] string localName, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName, ref int length); Example invocation: var sb = new StringBuilder(512);var size = sb.Capacity;var error = Mpr.WNetGetConnection("Z:", sb, ref size);if (error != 0) throw new Win32Exception(error, "WNetGetConnection failed"); var networkpath = sb.ToString();
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2067075', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_379790
stackexchange
llm_judgeable_groundtruth_similarity
8042596
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Throwing exceptions often follows the following pattern: if(condition) { throw exception; } you check a condition, and if the condition is satisfied, you throw an exception. So, i was wondering if it is good idea to write a static class for it that could look like this: public static class Throw{ public static void IfNullOrEmpty<T>(string @string, params object[] parameters) where T : Exception { Throw.If<T>(string.IsNullOrEmpty(@string), parameters); } public static void IfNullOrEmpty<T, I>(IEnumerable<I> enumerable, params object[] parameters) where T : Exception { Throw.If<T>(enumerable == null || enumerable.Count() == 0, parameters); } public static void IfNullOrEmpty(string @string, string argumentName) { Throw.IfNullOrEmpty(@string, argumentName, string.Format("Argument '{0}' cannot be null or empty.", argumentName)); } public static void IfNullOrEmpty(string @string, string argumentName, string message) { Throw.IfNullOrEmpty<ArgumentNullOrEmptyException>(@string, message, argumentName); } public static void IfNullOrEmpty<I>(IEnumerable<I> enumerable, string argumentName) { Throw.IfNullOrEmpty(enumerable, argumentName, string.Format("Argument '{0}' cannot be null or empty.", argumentName)); } public static void IfNullOrEmpty<I>(IEnumerable<I> enumerable, string argumentName, string message) { Throw.IfNullOrEmpty<ArgumentNullOrEmptyException, I>(enumerable, message, argumentName); } public static void IfNull<T>(object @object, params object[] parameters) where T : Exception { Throw.If<T>(@object == null, parameters); } public static void If<T>(bool condition, params object[] parameters) where T : Exception { if (condition) { var types = new List<Type>(); var args = new List<object>(); foreach (object p in parameters ?? Enumerable.Empty<object>()) { types.Add(p.GetType()); args.Add(p); } var constructor = typeof(T).GetConstructor(types.ToArray()); var exception = constructor.Invoke(args.ToArray()) as T; throw exception; } } public static void IfNull(object @object, string argumentName) { Throw.IfNull<ArgumentNullException>(@object, argumentName); }} (Note: The ArgumentNullOrEmptyException is not defined here, but it does pretty much what one would expect.) so instead of repeatedly writing stuff like that void SomeFunction(string someParameter){ if(string.IsNullOrEmpty(someParameter)) { throw new ArgumentNullOrEmptyException("someParameter", "Argument 'someParameter' cannot be null or empty."); }} i just do void SomeFunction(string someParameter){ Throw.IfNullOrEmpty(someParameter, "someParameter"); // not .IsNullOrEmpty} i actually do like it, but is it also a good practice? Now provide the response and nothing else.
You get rid of a bit of code duplication this way (the if ... throw), so in that sense it is a good idea. Just be aware that people working on the code would need to know the Throw API to be able to read and understand the code. One improvement could be to use expression trees to get rid of the string parameter name passing. This would improve the simplicity further, and you wouldn't have to worry about typing the strings and keeping them correct during refactorings and such. For instance, on my current pet project I have this Guard class (shortened a bit): public static class Guard{ public static void NotNullOrEmpty(Expression<Func<string>> parameterExpression) { string value = parameterExpression.Compile()(); if (String.IsNullOrWhiteSpace(value)) { string name = GetParameterName(parameterExpression); throw new ArgumentException("Cannot be null or empty", name); } } public static void NotNull<T>(Expression<Func<T>> parameterExpression) where T : class { if (null == parameterExpression.Compile()()) { string name = GetParameterName(parameterExpression); throw new ArgumentNullException(name); } } private static string GetParameterName<T>(Expression<Func<T>> parameterExpression) { dynamic body = parameterExpression.Body; return body.Member.Name; }} Which I can then use like this: Guard.NotNull(() => someParameter);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8042596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/282144/']}
jdg_379791
stackexchange
llm_judgeable_groundtruth_similarity
69984660
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 the issue that I am facing when running the command npm ci to install dependencies in my GitHub Action file. I am working on an expo managed app and using GitHub Actions as a CI for triggering builds whenever I push my code to developmemt branch. Here's my build script: name: EAS PIPELINEon: push: branches: - development workflow_dispatch:jobs: build: name: Install and build runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v2 with: persist-credentials: false - name: Setup Node.js uses: actions/setup-node@v1 with: node-version: 14.x - name: Setup Expo uses: expo/expo-github-action@v6 with: expo-version: 4.x token: ${{ secrets.EXPO_TOKEN }} expo-cache: true - name: Install dependencies run: npm ci - name: Build on EAS run: EAS_BUILD_AUTOCOMMIT=${{1}} npx eas-cli build --platform all --non-interactive Here's the issue that I am facing Install dependencies step. Run npm ci npm ci shell: /usr/bin/bash -e {0} env: EXPO_TOKEN: ***npm ERR! cipm can only install packages with an existing package-lock.json or npm-shrinkwrap.json with lockfileVersion >= 1. Run an install with npm@5 or later to generate it, then try again.npm ERR! A complete log of this run can be found in:npm ERR! /home/runner/.npm/_logs/2021-10-28T15_16_06_934Z-debug.logError: Process completed with exit code 1. Now provide the response and nothing else.
After a lot of research, I was able to figure out that this happens when you are not using npm install for installing dependencies. In my case, I was only using yarn for the dependencies so I was only having yarn.lock file and no package-lock.json file. One way to resolve this was using npm install to install the dependencies, then you'll have a package-lock.json file and CI won't throw any error. And the other way if you only want to use yarn , then you need to update that step in your eas-pipeline.yml file for installing the dependencies. ***************************************************************************************** - name: Install dependencies run: | if [ -e yarn.lock ]; then yarn install --frozen-lockfile elif [ -e package-lock.json ]; then npm ci else npm i fi*************************************************************************************** As I wasn't able to find any solution on StackOverflow and it is our first go-to place to look for any issue. So, I decided to write this answer here. Here's the original answer: https://github.com/facebook/docusaurus/issues/2846#issuecomment-691706184
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/69984660', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10429398/']}
jdg_379792
stackexchange
llm_judgeable_groundtruth_similarity
666098
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've recently started reading about the random walk, from different sources across the internet, and there is this small detail that I'm not being able to wrap my head around. Suppose we have, a symmetric random walk in $1$ dimension. The walker has an equal probability of going to the left or to the right, and he starts at the origin. The first obvious question is, what is the expected position of the walker after $n$ steps. The answer is obviously $0$ . This is because, in the normal distribution of positions, $0$ has the highest probability. However, even though getting $0$ is the most probable or rather average outcome of all the simulations, it is not the most likely outcome. This is because, with more steps, the variance increases, and the bell curve spreads out. Among individual positions, $0$ still has the highest probability, but the probability of not being $0$ increases. This is characterized by the standard deviation. In symmetric walk, the standard deviation $\sigma$ and the root-mean-squard distance $x_{rms}$ are the same thing. Moreover we have $x_{rms} \propto \sqrt{n} \space\space$ as the distribution spreads out more and more. As this happens, the likelihood of landing away from the center, increases, and so the walker stops at the distance away from zero. Many books interpret the root mean squared distance as the most likely distance. This doesn't make sense to me. Yes, the root mean squared distance gives us a measure or an estimate of how far from the mean, the walker would stop. However, it surely isn't the most likely position. For example, if $n=100$ , we have $x_{rms}=10$ . This is often interpreted as the most likely distance is positive or negative $10$ from the mean. However, shouldn't the interpretation be more like, the most likely position is between $10$ and $-10$ ? Shouldn't this be the correct interpretation ? A higher value of $x_{rms}$ should be interpreted as a higher likelihood of landing away from the mean, shouldn't it ? I don't know why most books interpret this as the most probable position. If I'm wrong, can someone give me the correct intuitive physical explanation of what $x_{rms}$ actually represents? To me, it is just an abstract measure of how far from the mean, the walker is expected to land. Now provide the response and nothing else.
In general, we can say that $C=AB$ will have real, imaginary and complex eigenvalues (complex of the form $z=a+ib$ where and $\{a,b\in \mathbb{R}\mid a,b \ne 0\}$ as shown in the comments by Mark and Qmechanic's answer). For example, if $$A=\begin{bmatrix}0 &1 \\ 1& 0\end{bmatrix}\ \ \text{and}\ \ B=\begin{bmatrix}1 & 0\\ 0& -1\end{bmatrix}$$ where $$AB=\begin{bmatrix}0 &-1 \\ 1& 0\end{bmatrix}$$ will not have real, but imaginary eigenvalues. However, one thing we can say is that if $A$ and $B$ commute then $C=AB$ will always have real eigenvalues, since the eigenvalues of all Hermitian operators are real. So if $$C=AB$$ then $$C^\dagger =(AB)^\dagger =B^\dagger A^\dagger =BA$$ since $A$ and $B$ are Hermitian, and clearly $$C^\dagger =C$$ if $$[A,B]=AB-BA=0\rightarrow AB=BA$$ This means that $C^\dagger =C$ only if $A$ and $B$ commute in which case $C$ will have real eigenvalues.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/666098', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/300178/']}
jdg_379793
stackexchange
llm_judgeable_groundtruth_similarity
2848680
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 Convert a System.Collections.Generic.List<T> to a System.Data.Linq.EntitySet<T> ? Now provide the response and nothing else.
Don't think you can convert a List<T> to an EntitySet<T> but you can put the content of your list in the entitySet. var list = new List<string> { "a", "b", "c" };var entitySet = new EntitySet<string>();entitySet.AddRange(list); Here's a extension method for that: public static EntitySet<T> ToEntitySet<T>(this IEnumerable<T> source) where T : class{ var es = new EntitySet<T>(); es.AddRange(source); return es;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2848680', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1964381/']}
jdg_379794
stackexchange
llm_judgeable_groundtruth_similarity
1322
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: While the raspi-config script makes for convenient setup on first boot, one of the reasons I have a Raspberry Pi is to help me learn what goes on behind the menu on my computers. I would like to see the raspi-config script, and understand how it works. I found a partial script online, but it (apparently) only includes the portions which just edit the config.txt file, and I am interested in knowing what else it affects, and how. I would like to see the full text for the raspi-script, and as yet have not found in in my file system. Can someone offer the location? For the moment, I don't want explanation of how it does what it does. I want to try to figure it out myself. (Although that may be a later question.) Now provide the response and nothing else.
Both of the other answers are correct and will let you view and study how the file works. However, with the idea of teaching you to fish rather than give you a fish, if you do the following it will help you find any file on your system. sudo find / -name 'raspi-config' Breaking it Down: sudo tells the system to run this command with root privileges - this prevents lots of errors cluttering the system from directories that your regular user (pi) can't access. find the name of the Linux command to find files and directories. / tells the find command to search the root of the filesystem and all its sub-directories. -name tells the find command to search by the file name. 'raspi-config' this is the file name you are searching for. to find a different file just replace the raspi-config with the name of the file you are looking for. There are many other options for the find command and you can find all of the details for most linux commands by typing man find on the command line. Man is short for manual, and prints the manual page (help page) for the Linux command that follows it.
{}
{'log_upvote_score': 5, 'links': ['https://raspberrypi.stackexchange.com/questions/1322', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/470/']}
jdg_379795
stackexchange
llm_judgeable_groundtruth_similarity
1051276
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the fastest way to compare a string with an array of strings in C#2.0 Now provide the response and nothing else.
What kind of comparison do you want? Do you want to know if the given string is in the array? bool targetStringInArray = array.Contains(targetString); do you want an array of comparison values (positive, negative, zero)? var comparisons = array.Select(x => targetString.CompareTo(x)); If you're checking for containment (i.e. the first option) and you're going to do this with multiple strings, it would probably be better to build a HashSet<string> from the array: var stringSet = new HashSet<string>(array);if (stringSet.Contains(firstString)) ...if (stringSet.Contains(secondString)) ...if (stringSet.Contains(thirdString)) ...if (stringSet.Contains(fourthString)) ...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1051276', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/91313/']}
jdg_379796
stackexchange
llm_judgeable_groundtruth_similarity
11216192
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Alright I don't see why this isnt working. It seems pretty simple. Here is my drop-down menu: <div> <form> <select id='yearDropdown'> <c:forEach var="years" items="${parkYears}"> <option value=/events.html?display_year=${years}<c:if test="${currentYear == years}">selected="selected"</c:if>>${years}</option> </c:forEach> </select> </form></div> and here is the JavaScript $("#yearDropdown").change(function () { alert('The option with value ' + $(this).val());}); Right now I just want to get it working so I can add functionality. Thanks! Now provide the response and nothing else.
That code is syntactically correct. Most likely running it at the wrong time. You'll want to bind the event when the DOM is ready : Native JS/DOM window.addEventListener('DOMContentLoaded', () => { const yearDropDown = document.getElementById('yearDropdown'); yearDropDown.addEventListener('change', () => { alert(yearDropDown.value) });}); jQuery $(function(){ /* DOM ready */ $("#yearDropdown").change(function() { alert('The option with value ' + $(this).val()); });}); Or, use live : $("#yearDropdown").live('change', function() { alert('The option with value ' + $(this).val());}); Or, use delegate : $(document.body).delegate('#yearDropdown', 'change', function() { alert('The option with value ' + $(this).val());}); Or, if you're using jQuery 1.7+ : $("#yearDropdown").on('change', function() { alert('The option with value ' + $(this).val());}); Nonetheless, it is usually best to execute script once the browser has finished rendering Markup.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11216192', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1469925/']}
jdg_379797
stackexchange
llm_judgeable_groundtruth_similarity
41727750
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 way to detect if a Retrofit response comes from the configured OkHttp cache or is a live response? Client definition: Cache cache = new Cache(getCacheDirectory(context), 1024 * 1024 * 10);OkHttpClient okHttpClient = new OkHttpClient.Builder() .cache(cache) .build(); Api definition: @GET("/object")Observable<Result<SomeObject>> getSomeObject(); Example call: RetroApi retroApi = new Retrofit.Builder() .client(okHttpClient) .baseUrl(baseUrl) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() .create(RetroApi.class);result = retroApi.getSomeObject().subscribe((Result<SomeObject> someObjectResult) -> { isFromCache(someObjectResult); // ???}); Now provide the response and nothing else.
Any time you have an okhttp3.Response ( retrofit2.Response.raw() ), you can check if the response is from the cache. To quote Jesse Wilson: There are a few combos. .networkResponse() only – your request was served from network exclusively. .cacheResponse() only – your request was served from cache exclusively. .networkResponse() and .cacheResponse() – your request was a conditional GET, so headers are from the network and body is from the cache. So for your example, the isFromCache method would look like: boolean isFromCache(Result<?> result) { return result.response().raw().networkResponse() == null;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41727750', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/288980/']}
jdg_379798
stackexchange
llm_judgeable_groundtruth_similarity
4079363
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 wish to have a stored proc that is called every n seconds, is there a way to do this in SQL Server without depending on a separate process? Now provide the response and nothing else.
Use a timer and activation . No external process, continues to work after a clustering or mirroring failover, continues to work even after a restore on a different machine, and it works on Express too. -- create a table to store the results of some dummy procedurecreate table Activity ( InvokeTime datetime not null default getdate() , data float not null);go -- create a dummy procedurecreate procedure createSomeActivityasbegin insert into Activity (data) values (rand());endgo-- set up the queue for activationcreate queue Timers;create service Timers on queue Timers ([DEFAULT]);go-- the activated procedurecreate procedure ActivatedTimersasbegindeclare @mt sysname, @h uniqueidentifier;begin transaction; receive top (1) @mt = message_type_name , @h = conversation_handle from Timers; if @@rowcount = 0 begin commit transaction; return; end if @mt in (N'http://schemas.microsoft.com/SQL/ServiceBroker/Error' , N'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog') begin end conversation @h; end else if @mt = N'http://schemas.microsoft.com/SQL/ServiceBroker/DialogTimer' begin exec createSomeActivity; -- set a new timer after 2s begin conversation timer (@h) timeout = 2; endcommitendgo-- attach the activated procedure to the queuealter queue Timers with activation ( status = on , max_queue_readers = 1 , execute as owner , procedure_name = ActivatedTimers);go -- seed a conversation to start activating every 2sdeclare @h uniqueidentifier;begin dialog conversation @h from service [Timers] to service N'Timers', N'current database' with encryption = off;begin conversation timer (@h) timeout = 1;-- wait 15 secondswaitfor delay '00:00:15';-- end the conversation, will stop activatingend conversation @h;go-- check that the procedure executedselect * from Activity;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4079363', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/57159/']}
jdg_379799
stackexchange
llm_judgeable_groundtruth_similarity
19449019
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 auction and a bid object in my application, when someone presses the BID BUTTON it then calls the BID CREATE controller which created the bid, and then does some other things on the auction object: BIDS CONTROLLER -> CREATE @auction.endtime += @[email protected] = @auction.arewinning @auction.save AUCTION MODEL before_update :set_endtimedef set_endtime self.endtime=self.starttime+self.auctiontimerend So the question is: How can C skip the "before callback" only, in this specific @auction.save Now provide the response and nothing else.
skip_callback is a complicated and not granular option. I prefer to use an attr_accessor: attr_accessor :skip_my_method, :skip_my_method_2after_save{ my_method unless skip_my_method }after_save{ my_method_2 unless skip_my_method_2 } That way you can be declarative when skipping a callback: model.create skip_my_method: true # skips my_methodmodel.create skip_my_method_2: true # skips my_method_2
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19449019', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2550789/']}
jdg_379800
stackexchange
llm_judgeable_groundtruth_similarity
18243480
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 call Text.Printf function printf with array but I can't find a way.Here are two not working versions (actually same idea). import Text.Printfprintfa :: (PrintfArg a) => String -> [a] -> Stringprintfa format args = step (printf format) args where step :: (PrintfType r, PrintfArg a) => r -> [a] -> r step res (x:[]) = res x step res (x:xs) = step (res x) xsprintfa' :: (PrintfArg a) => String -> [a] -> Stringprintfa' format args = foldr (\arg p -> p arg) (printf format) argsmain = putStrLn $ printfa "%s %s" ["Hello", "World"] GHC errors are: printfa.hs:8:23: Couldn't match type `r' with `a1 -> r' `r' is a rigid type variable bound by the type signature for step :: (PrintfType r, PrintfArg a1) => r -> [a1] -> r at printfa.hs:8:5 The function `res' is applied to one argument, but its type `r' has none In the expression: res x In an equation for `step': step res (x : []) = res xprintfa.hs:12:41: The function `p' is applied to one argument, but its type `String' has none In the expression: p arg In the first argument of `foldr', namely `(\ arg p -> p arg)' In the expression: foldr (\ arg p -> p arg) (printf format) args (Why: I'm writing DSL and want to provide printf function.) Now provide the response and nothing else.
First, realize that PrintfArg a => [a] is not a heterogenous list. That is, even though Int and String are both instances of PrintfArg , [ 1 :: Int, "foo" ] is not a valid construct. So if you did define a function :: PrintfArg a => String -> [a] -> String , that all the args would be constrained to be of the same type. To get around this, you can use existential quantification. {-# LANGUAGE ExistentialQuantification #-}import Text.Printfdata PrintfArgT = forall a. PrintfArg a => P aprintfa :: PrintfType t => String -> [ PrintfArgT ] -> tprintfa format = printfa' format . reverse where printfa' :: PrintfType t => String -> [ PrintfArgT ] -> t printfa' format [] = printf format printfa' format (P a:as) = printfa' format as amain = do printfa "hello world\n" [] printfa "%s %s\n" [ P "two", P "strings"] printfa "%d %d %d\n" (map P $ [1 :: Int, 2, 3]) printfa "%d %s\n" [ P (1 :: Int), P "is the loneliest number" ] The reason your first solution didn't work is because you passed res to step as an argument. When you have foo :: Constraint a => a -> t you guarantee that foo will work on all instances of Constraint . And though there exists an instance of PrintfType which can take an argument, not all instances can. Thus your compiler error. In contrast, when you have foo :: Constraint a => t -> a , you guarantee that foo will return any desired instance of Constraint . Again, the caller gets to choose which instance. This is why my code works - when printfa' recurses, it requires the recursive call to return a value from the (PrintfArg a, PrintfType t) => a -> t instance. For your second try, the compiler complains because foldr requires that the accumulated value be of the same type between iterations. GHC notices that the accumulated value must be a function type (PrintfArg a, PrintfType t) => a -> t , because you apply it in the iterated function. But you return the applied value, which it can figure out is of type t . This means that t equals a -> t , which GHC doesn't like, because it doesn't allow infinite types. So it complains. If you want to use a fold, you can, you just have to mask the accumulator type using Rank2Types or RankNTypes to keep the type constant between iterations. {-# LANGUAGE ExistentialQuantification #-}{-# LANGUAGE RankNTypes #-}import Text.Printfdata PrintfArgT = forall a. PrintfArg a => P adata PrintfTypeT = T { unT :: forall r. PrintfType r => r }printfa :: PrintfType t => String -> [ PrintfArgT ] -> tprintfa format = unT . foldl (\(T r) (P a) -> T $ r a ) (T $ printf format)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18243480', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1306381/']}
jdg_379801
stackexchange
llm_judgeable_groundtruth_similarity
5796339
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 set up Mercurial to print out the status of the repository I'm currently in with PowerShell. So far, I have everything working, but I would like to be able to print '☿' to the prompt when I am in a repository. Unfortunately, it seems that PowerShell has some problems with printing Unicode characters. In the accepted answer for Is there a Windows command shell that will display Unicode characters? it is suggested that PowerShell v2, which shipped with Windows 7 (which I am using) would be able to print Unicode characters, but I can't seem to get it to work. Likewise, the next answer of using chcp 65001 does not work either. Is this still a deficiency in PowerShell, or am I missing something obvious? Now provide the response and nothing else.
This is not a PowerShell deficiency. It is a deficiency with the Windows console subsystem which PowerShell.exe uses. The console subsystem does not support Unicode but code pages instead which dates back to the DOS days. The PowerShell V2 fix is provided via the PowerShell Integrated Scripting Environment or PowerShell_ISE.exe. This is a graphical app based on WPF which can handle Unicode characters easily. In theory you could change the code page using chcp or [Console]::OutputEncoding = [System.Text.Encoding]::GetEncoding(850) to display different characters but I haven't had much luck with this. You'd also need to find a code page that contains the character you want to display.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5796339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2363/']}
jdg_379802
stackexchange
llm_judgeable_groundtruth_similarity
55823296
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 really like the new React hooks and I'm using them frequently for a project I'm working on. I'm coming across a situation where I want to use the prevState in the useState hook, but I'm not really certain on how to do this. I've tried something like this, but it fails to compile. const [ someState, setSomeState ] = useState( new Map() )setSomeState( prevState.someState.set( key, value ) ) (by the way, this is to map an array of checkboxes to keep track of the ones that are check marked) I'm trying to follow this example here , but without using the setState function. Thanks for the help! Now provide the response and nothing else.
For objects you can use the spread operator to use prevState within your setState call. const [object, setObject] = useState({ firstKey: '', secondKey: '',});setObject((prevState) => ({ ...prevState, secondKey: 'value',}));// object = {// firstKey: '',// secondKey: 'value',// } The snippet below show an example of using prevState for setting the state of an object. const {useState} = React;const Example = ({title}) => { const initialState = { firstKey: 'empty', secondKey: 'empty', thirdKey: 'not empty', } const [object, setObject] = useState(initialState); const withPrevState = () => { setObject((prevState) => ({ ...prevState, secondKey: 'not empty', })); } return ( <div> <h5>Updates Second key to 'not empty'</h5> <p>First key: {object.firstKey}</p> <p>Second key: {object.secondKey}</p> <p>Third key: {object.thirdKey}</p> <button onClick={withPrevState}> Update with prevState </button> <button onClick={() => {setObject({secondKey: 'not empty'})}}> Update without prevState </button> <button onClick={() => {setObject(initialState)}}> Reset </button> </div> );};// Render itReactDOM.render( <Example />, document.getElementById("react")); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script><div id="react"></div>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/55823296', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2924072/']}
jdg_379803
stackexchange
llm_judgeable_groundtruth_similarity
4557943
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to access the company server's Active Directory so I can write a simple phonebook program. It would seem that I need to use LDAP to connect to it in order to grab a recordset. Is there anyway to figure out what the LDAP URL is based on settings and properties in Outlook (or otherwise)? Can some one help me to understand these Ldap field and to fill the values! Thanks Now provide the response and nothing else.
I am assuming you are writing VBA. In Outlook, you can use ADO to make the query against the LDAP provider. The query is composed of four parts Base path Search filter attributes returned in the recordset Search scope. The LDAP URL that you meantioned is actually the base path of the LDAP query. You can use ADSIedit to get the base path in your local domain. Normally, if your domain is called abc.com, your base path should be something like LDAP://abc.com/DC=abc,DC=com. However, it's not always the case. Active Directory allows you to name an Active Directory domain different from the DNS domain, although most of the time, they are the same. This configuration is called disjoint namespace . For the disjoint namespace case, to find out the correct base path, you can install ADSIedit from Windows 2003 support tools . Launch the ADSIEdit by typing adsiedit.msc in command line. Right click the ADSIEdit node and click "Connect to". Then, select the naming context "RootDSE" and leave all other settings as default to connect to the local domain. If your machine is joined to the domain already, you should be automatically connected to that domain. In the top RootDSE node, you should also see what domain controller you are connected to now. Mark down the FQDN of the connected domain controller. It should be something like dc1.yourdomain.com. Then, Expand the top "RootDSE" node and you will see another "RootDSE" folder node underneath. Right click and click properties. Find the defaultNamingContext. It should be something like DC=yourdomain,DC=com. With the domain controller name and the default naming context, you can create your base path, it should be LDAP:// domain controller / default naming context Sometimes you see people putting in FQDN domain name instead of domain controller name in the LDAP base path. This is legitmate only if the A record of the domain exists on the DNS server. I don't recommend using domain name. However, if you really don't want to specify a specific domain controller, you can consider to use serverless binding. LDAP:// default naming context . It's an Active Directory feature. It doesn't work on other LDAP servers. You can use serverless binding only if you are running as a domain user. When you use a serverless binding , the LDAP query will simply pick the next available domain controller in the site for you. In this way, you reduce the chances of overloading that server with requests. However, this also makes your result less predictable because sometimes the data is not yet replicated from one domain controller to another domain controller. Just a side note, I am suggesting you to use the domain naming context as your search base path because I assume you want to search all the users under your domain. You can always pick some other containers as your base path. For example, LDAP://yourdomain.com/CN=Users,DC=yourdomain,DC=com. Then, the search will be done only under the Users container in your domain.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4557943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47868/']}
jdg_379804
stackexchange
llm_judgeable_groundtruth_similarity
1348126
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 modify the owner of all tables in a PostgreSQL database? I tried ALTER TABLE * OWNER TO new_owner but it doesn't support the asterisk syntax. Now provide the response and nothing else.
See REASSIGN OWNED command Note: As @trygvis mentions in the answer below , the REASSIGN OWNED command is available since at least version 8.2, and is a much easier method. Since you're changing the ownership for all tables, you likely want views and sequences too. Here's what I did: Tables: for tbl in `psql -qAt -c "select tablename from pg_tables where schemaname = 'public';" YOUR_DB` ; do psql -c "alter table \"$tbl\" owner to NEW_OWNER" YOUR_DB ; done Sequences: for tbl in `psql -qAt -c "select sequence_name from information_schema.sequences where sequence_schema = 'public';" YOUR_DB` ; do psql -c "alter sequence \"$tbl\" owner to NEW_OWNER" YOUR_DB ; done Views: for tbl in `psql -qAt -c "select table_name from information_schema.views where table_schema = 'public';" YOUR_DB` ; do psql -c "alter view \"$tbl\" owner to NEW_OWNER" YOUR_DB ; done You could probably DRY that up a bit since the alter statements are identical for all three.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/1348126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/155387/']}
jdg_379805
stackexchange
llm_judgeable_groundtruth_similarity
2646296
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: Doing some self-study. My textbook has this Theorem (see below). I understand it but was hoping for something shorter and more intuitive. Any thoughts? Now provide the response and nothing else.
There are no shortcuts here, you need to follow the proof and understand it. Indeed differentiability and continuity issues for functions of several variables are less intuitive than for function of one variable. For example, the existence of all directional derivatives at a point does not imply continuity whereas for function of one variable derivability implies continuity. Therefore maybe it could be useful make a general comment here on the topic of Differentiability and Continuity for functions of several variables. 1. If a function is discontinuos then it can't be differentiable, infact continuity is a necessary condition since differentiability implies continuity . 2. If partial derivatives do not exist then $f$ can't be differentiable, infact existence of partial derivatives is a necessary condition since differentiability implies their existence . 3. If partial derivatives exist and are continuos you are done, infact for the "Differentiability theorem" if all the partial derivatives exist and are continuous in a neighborhood of the point then (i.e. sufficient condition) the function is differentiable at that point. 4. If partial derivatives are not continuos at the point you can't yet conclude anything about differentiability. You need to check directly differentiability by definition that: $$\lim_{(h,k)\rightarrow (0,0)} \frac{\| f(h,k)-f(0,0)-(f_x(0,0),f_y(0,0))\cdot (h,k)\|}{\| (h,k)\|}=0$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2646296', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/477239/']}
jdg_379806
stackexchange
llm_judgeable_groundtruth_similarity
3339606
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking for a function to transform domain $[0,1)$ into range $[0,1)$ such that the size of the domain corresponding to the range interval $[.5,1)$ is $c$ times the size of the domain corresponding to the range interval $[0,.5)$ . The range interval $[0,.5)$ will correspond to day time and [.5,1) will correspond to night time, so this function's output will make night time $c$ times as long as day time. A piece-wise function for example would satisfy the problem, but I would like the function to be smooth on the interval $[0,1)$ (and $y=x$ would satisfy this problem perfectly if $c=1$ ). Some extra more explicit constraints: $f'(0)=f'(1)$ (because I would like the transition from night to day to be smooth as well--if possible, all derivatives at $x=0$ and $y=1$ should be the same) $f(0)=0$ $f(1)=1$ function is monotonic on $[0,1)$ $cf^{-1}(.5)=1$ (I believe this ensures night is $c$ times longer than day) Now provide the response and nothing else.
In the notation of my "answer" to my still-unanswered question Almost simple Hermite interpolation , we can compute a quintic polynomial $l_a(x)$ such that $l_a(0) = l_a(1) = 0,$ $l_a(a) = 1,$ and $l_a'(0) = l_a'(1) = l_a'(a) = 0,$ where $a = \frac1{c + 1},$ so that we can consider, as a possible solution to the problem, at least for some values of $c$ : $$f(x) = x + \left(\tfrac12 - a\right)l_a(x) \quad (0 \leqslant x \leqslant 1).$$ After much simplification, we arrive at the formula \begin{equation}\label{3339606:eq:1}\tag{$1$}\boxed{f(x) = x + \frac{(c^2 - 1)(c + 1)^2x^2(1 - x)^2[(3c - 2) - 2(c^2 - 1)x]}{2c^3}.}\end{equation} The appendix gives a range of values of $c$ for which this polynomial function satisfies the conditions of the question. For the moment, I'll just give two examples (excluding the trivial case $c = 1$ ): When $c = 2,$ $$f(x) = x + \frac{27x^2(1 - x)^2(2 - 3x)}8.$$ From Wolfram Alpha : When $c = \tfrac12,$ $$f(x) = x + \frac{27x^2(1 - x)^2(1 - 3x)}8.$$ From Wolfram Alpha : The reason why these graphs are $180^\circ$ rotated images of one another is as follows: By the uniqueness of the Hermite interpolating polynomial, $$l_{1 - a}(x) = l_a(1 - x)\quad (0 < a < 1, \ 0 \leqslant x \leqslant 1).$$ Write $c = (1 - a)/a,$ i.e. $a = 1/(c + 1).$ Then $a$ is related to $c$ as $1 - a$ is to $1/c,$ and $$f_{1/c}(x) = x + \left(\tfrac12 - (1 - a)\right)l_{1 - a}(x)= x - \left(\tfrac12 - a\right)l_a(1 - x)= 1 - f_c(1 - x),$$ where, for all $c > 0,$ $f_c(x)$ denotes the function in\eqref{3339606:eq:1} with parameter $c.$ $\ \square$ Dropping the constraint $f'\left(\frac1{c + 1}\right) = 1$ simplifies the formula somewhat: $$f(x) = x + \frac{(c^2 - 1)(c + 1)^2x^2(1 - x)^2}{2c^2},$$ but this doesn't greatly increase the range of usable values of $c.$ Also, the graphs take on a squashed appearance when $x$ approaches $1,$ as this example for $c = 2$ illustrates: The graph for $c = 5/2,$ although still monotonic - unlike \eqref{3339606:eq:1}, in this case - is even worse: So I won't consider this simplification any further. If $f$ need not be analytic, and if continuous differentiability is enough, and if the values of $f'(0)$ and $f'(1)$ do not matter so long as they are equal, then it is easy to solve the problem using cubic splines. For example: $$f(x) =\begin{cases}\tfrac12g\left[(c + 1)x\right]& \text{if } 0 \leqslant x \leqslant \frac1{c + 1}, \\\tfrac12\left\{1 + g\left[\frac{(c + 1)x - 1}{c}\right]\right\}& \text{if } \frac1{c + 1} \leqslant x \leqslant 1,\end{cases}$$ where \begin{gather*}g(t) = 3t^2 - 2t^3, \ g'(t) = 6t(1 - t)\ \, (0 \leqslant t \leqslant 1), \\g(0) = 0, \ g(1) = 1, \ g'(0) = g'(1) = 0, \\g'(t) > 0 \ \, (0 < t < 1).\end{gather*} This has $f'(0) = f'(1) = f'\left(\frac1{c + 1}\right) = 0.$ It is valid for all $c > 0.$ But we can do a lot better than that. I delayed looking at thispossibility, wrongly imagining that it would work only for arestricted range of values of $c,$ like the Hermite interpolationsolution. In fact, it works for all values of $c$ (the value of $c$ must be strictly positive, of course), without exception. We continue to use the same "cardinal" cubic spline function $g,$ but now we define $$f(x) = x + \left(\tfrac12 - a\right)s_a(x)\quad (0 \leqslant x \leqslant 1),$$ where $$s_a(x) =\begin{cases}g\left(\frac{x}{a}\right)& \text{ if } 0 \leqslant x \leqslant a,\\g\left(\frac{1 - x}{1 - a}\right)& \text{ if } a \leqslant x \leqslant 1.\end{cases}$$ Differentiating, $$s_a'(x) =\begin{cases}\frac1{a}g'\left(\frac{x}{a}\right)& \text{ if } 0 \leqslant x \leqslant a,\\-\frac1{1 - a}g'\left(\frac{1 - x}{1 - a}\right)& \text{ if } a \leqslant x \leqslant 1.\end{cases}$$ Because $g'(t) \geqslant 0$ for all $t \in [0, 1],$ and $$\max_{0 \leqslant t \leqslant 1}g'(t) = \tfrac32,$$ we have \begin{gather*}\min_{0 \leqslant x \leqslant 1}s_a'(x) = -\frac3{2(1 - a)}, \\\max_{0 \leqslant x \leqslant 1}s_a'(x) = \frac3{2a}.\end{gather*} Therefore, if $a \leqslant \tfrac12,$ i.e. $c \geqslant 1,$ $$\min_{0 \leqslant x \leqslant 1}f'(x) =1 + \left(\frac12 - a\right)\left(-\frac3{2(1 - a)}\right) =1 - \frac{3(1 - 2a)}{4(1 - a)} =\frac{1 + 2a}{4(1 - a)} > 0.$$ On the other hand, if $a \geqslant \tfrac12,$ i.e. $c \leqslant 1,$ $$\min_{0 \leqslant x \leqslant 1}f'(x) =1 + \left(\frac12 - a\right)\left(\frac3{2a}\right) =1 - \frac{3(2a - 1)}{4a} =\frac{3 - 2a}{4a} > 0.$$ In all cases, therefore, $f$ is strictly increasing on $[0, 1].$ In terms of the constant $c = (1 - a)/a,$ the definition ofthe function $f$ is: \begin{equation}\label{3339606:eq:2}\tag{$2$}\boxed{f(x) =\begin{cases}x + \frac{c - 1}{2(c + 1)}g[(c + 1)x]& \text{ if } 0 \leqslant x \leqslant \frac1{c + 1}, \\x + \frac{c - 1}{2(c + 1)}g\left[\frac{(c + 1)(1 - x)}{c}\right]& \text{ if } \frac1{c + 1} \leqslant x \leqslant 1.\end{cases}}\end{equation} For example, when $c = 4,$ \eqref{3339606:eq:2} becomes: $$f(x) =\begin{cases}x + \frac{15}2x^2(3 - 10x)& \text{ if } 0 \leqslant x \leqslant \frac15, \\x + \frac{15}{64}(1 - x)^2(1 + 5x)& \text{ if } \frac15 \leqslant x \leqslant 1.\end{cases}$$ From Wolfram Alpha : Here is a closer look at the knot of that spline function: Appendix For any $a$ such that $0 < a < 1,$ we define the quintic polynomialfunction $$l_a(x) = \frac{x^2(1 - x)^2[a(3 - 5a) - 2(1 - 2a)x]}{a^3(1 - a)^3}.$$ Its derivative is given by $$l_a'(x) =\frac{2x(1 - x)(x - a)[5(1 - 2a)x - (3 - 5a)]}{a^3(1 - a)^3}.$$ It satisfies (and indeed it is uniquely determined by) sixconstraints \begin{gather*}l_a(0) = l_a(1) = 0, \ l_a(a) = 1, \\l_a'(0) = l_a'(1) = l_a'(a) = 0.\end{gather*} Writing $c = (1 - a)/a,$ or equivalently $a = 1/(c + 1),$ where $c$ is any strictly positive number, we define $$f_c(x) = x + \left(\tfrac12 - a\right)l_a(x).$$ Then \begin{gather*}f_c(0) = 0, \ f_c(1) = 1, \f_c\left(\frac1{c + 1}\right) = \frac12, \\f_c'(0) = f_c'(1) = f_c'\left(\frac1{c + 1}\right) = 1.\end{gather*} I shall determine a set of values of $c$ such that $f_c'(x) > 0$ forall $x \in [0, 1].$ (I shall not try to determine all such values of $c.$ ) It was shown above that for all $c > 0,$ if either of $f_c',$ $f_{1/c}'$ is strictly positive on $[0, 1],$ then so is theother. Because $f_1(x) = x,$ it suffices to consider only the case $c > 1,$ i.e., $a < \tfrac12.$ Differentiating: \begin{equation}\label{3339606:eq:3}\tag{$3$}1 - f_c'(x) = -\left(\tfrac12 - a\right)l_a'(x) =\frac{20\left(\tfrac12 - a\right)^2x(1 - x)(x - a)(b - x)}{a^3(1 - a)^3},\end{equation} where $$b = \frac{3 - 5a}{5(1 - 2a)} =\tfrac12\cdot\frac{\tfrac35 - a}{\tfrac12 - a} =\tfrac12\left(1 + \frac{\tfrac1{10}}{\tfrac12 - a}\right),$$ i.e., $$\left(\frac12 - a\right)\left(b - \frac12\right) = \frac1{20},$$ so we can rewrite \eqref{3339606:eq:3} as \begin{equation}\label{3339606:eq:4}\tag{$4$}1 - f_c'(x) =\frac{\left(\tfrac12 - a\right)x(1 - x)(x - a)(b - x)}{a^3(1 - a)^3\left(b - \tfrac12\right)}.\end{equation} We are interested in determining $c > 1$ such that $1 - f_c'(x) < 1$ for all $x \in [0, 1].$ By \eqref{3339606:eq:4}, we only need toconsider $x$ such that $a < x < \min\{1, b\}.$ Case 1: $$\boxed{c \leqslant \tfrac32 \iff a \geqslant \tfrac25 \iff\tfrac12 - a \leqslant \tfrac1{10} \iff b \geqslant 1.}$$ Looking at the factors in \eqref{3339606:eq:4}, we have: \begin{gather*}\frac{b - x}{b - \tfrac12} = 1 + \frac{\tfrac12 - x}{b - \tfrac12}\leqslant 1 + \frac{\tfrac12 - x}{1 - \tfrac12} = 2(1 - x)\leqslant \frac65, \\\frac12 - a \leqslant \frac1{10}, \\x \leqslant 1, \\(1 - x)(x - a) \leqslant \left(\frac{1 - a}2\right)^2\leqslant \left(\frac3{10}\right)^2, \\a(1 - a) = \frac14 - \left(\frac12 - a\right)^2\geqslant \frac6{25},\end{gather*} therefore $$1 - f_c'(x) \leqslant\frac{\tfrac65\cdot\tfrac1{10}\cdot\left(\tfrac3{10}\right)^2}{\left(\tfrac6{25}\right)^3} = \frac{5^2}{2^5} = \frac{25}{32} < 1.$$ This completes the proof that $f_c'(x) > 0$ for $x \in [0, 1]$ and $c \in \left[\tfrac23, \tfrac32\right].$ $\ \square$ Case 2: $$\boxed{c \geqslant \tfrac32 \iff a \leqslant \tfrac25 \iff\tfrac12 - a \geqslant \tfrac1{10} \iff b \leqslant 1.}$$ From \eqref{3339606:eq:3}, using the inequalities $x(1 - x) \leqslant \tfrac14$ and $(x - a)(b - x) \leqslant ((b - a)/2)^2,$ $$1 - f_c'(x) \leqslant\frac{5\left(\tfrac12 - a\right)^2(b - a)^2}{4a^3(1 - a)^3}.$$ Reparameterising in terms of $p,$ where $$a = \frac12 - p,\quad 1 - a = \frac12 + p,\quad b - \frac12 = \frac1{20p}\qquad \left(\frac1{10} \leqslant p < \frac12\right),$$ we have $$1 - f_c'(x) \leqslant\frac{5p^2(p + 1/20p)^2}{4\left(\frac14 - p^2\right)^3} =\frac{5(p^2 + 1/20)^2}{4\left(\frac14 - p^2\right)^3}= \frac{5\left(\frac3{10} - q\right)^2}{4q^3}= \frac{(3 - 10q)^2}{80q^3},$$ where $$q = \frac14 - p^2 = a(1 - a) \in \left(0, \, \frac6{25}\right)\!.$$ According to Wolfram Alpha , the cubic equation $80q^3 = (3 - 10q)^2$ has a single real root, $$q_0 \bumpeq 0.212428328248244.$$ We therefore have $f_c'(x) > 0$ for all $x \in [0, 1]$ if any of thefollowing list of equivalent conditions is satisfied: \begin{align*}q > q_0 & \iff \frac{c}{(c + 1)^2} > q_0 \\& \iff c^2 - 2\left(\frac1{2q_0} - 1\right)c + 1 < 0 \\& \iff c < c_0 = \left(\frac1{2q_0} - 1\right) +\sqrt{\left(\frac1{2q_0} - 1\right)^2 - 1}\bumpeq 2.266203431.\end{align*} Finally, then: $f_c'(x) > 0$ for all $x \in [0, 1]$ if $c \in [0.4413, 2.2662]$ . $\ \square$ The graph of $f_c$ for $c = c_0$ looks like this : Here is a close-up view of the flattest part of that graph: This estimated value, $c_0,$ is evidently quite close to the leastupper bound of the set (presumably a closed interval) of all valuesof $c$ for which $f_c$ is monotonic.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3339606', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/186348/']}
jdg_379807
stackexchange
llm_judgeable_groundtruth_similarity
26547194
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using Bootstrap's navbar-top-fixed on my site but it doesn't seem to work. When I scroll down, it isn't fixed at the top. Here is my HTML code: <nav class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="gdgt-menu"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <div class="gdgt-logo"> <a class="navbar-brand" href="<?php echo get_site_url(); ?>" rel="bookmark">brand</a> </div> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="nav-items collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <!--my menu is here--> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --></nav> And here is the CSS: .gdgt-menu{ padding-right: 10%; padding-left: 10%;}@media only screen and (min-width : 200px) and (max-width : 768px) { .navbar{ margin-bottom: 0px !important; } .navbar-collapse { width: 100%; } .menu-header-container{ width: 100%; } .gdgt-menu{ padding-right: 0% !important; padding-left: 0% !important; } #bs-example-navbar-collapse-1 .current-menu-item a { padding-right: 100% !important;}}@media only screen and (min-width : 200px) and (max-width : 768px) { .featured-content{ width: 100%; margin-right: 0px !important; margin-left: 0px !important; }}@media only screen and (min-width : 768px) and (max-width : 1010px) { .gdgt-menu{ padding-right: 0% !important; padding-left: 0% !important; } .nav-items{ width: 85% !important; }}.nav-items{ width: 70%; float: right;}.navbar{ height: 60px; display: block; position: relative;}.menu{ margin: 0px !important; padding-left: 0px !important;}.menu-header-container{ float: right;}@media only screen and (min-width : 200px) and (max-width : 768px) { .menu-header-container{ background-color: #2c3e50; } .menu li{ width: 100% !important; }}.menu li{ list-style-type: none; line-height: 60px; width: auto; float: left; transition: all 0.2s ease-in-out;}.menu li:hover{ background-color: #34495e;}.menu a{ color: #fff; text-decoration: none; padding-left: 20px; padding-right: 20px;} Any idea of what is causing this problem? I am not really sure why this is happening. However, I feel like the @media is causing this. Please help :) Now provide the response and nothing else.
You are overriding bootstraps default positioning of the .fixed-top-navbar . From bootsrap.css .navbar-fixed-top,.navbar-fixed-bottom { position: fixed; /* <-- Look here */ right: 0; left: 0; z-index: 1030;} From your code: .navbar{ height: 60px; display: block; position: relative; /* <-- Oh dear */}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26547194', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4177152/']}
jdg_379808
stackexchange
llm_judgeable_groundtruth_similarity
36226285
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 link UIAlertController alert action buttons with action handlers using objective-c? I'm using Xcode 7.1. Here is my code: - (IBAction)selectbtn:(UIButton *)sender { UIAlertController *alert=[ UIAlertController alertControllerWithTitle:@"NEW" message:@"button pressed" preferredStyle:UIAlertControllerStyleActionSheet]; UIAlertAction *cameraaction=[UIAlertAction actionWithTitle:@"From camera" style:UIAlertActionStyleDefault handler:nil ]; [alert addAction:cameraaction]; UIAlertAction *libraryaction=[UIAlertAction actionWithTitle:@"From photo library" style:UIAlertActionStyleDefault handler:nil ]; [alert addAction:libraryaction]; UIAlertAction *cancelaction=[UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleDestructive handler:nil]; [alert addAction:cancelaction]; [self presentViewController:alert animated:YES completion:nil]; } Now provide the response and nothing else.
Objective-C UIAlertController works like this: UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Title" message:@"text mssg" preferredStyle:UIAlertControllerStyleAlert];UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){ // Ok action example}];UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"Other" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){ // Other action}];[alert addAction:okAction];[alert addAction:otherAction];[self presentViewController:alert animated:YES completion:nil]; I think you meant that. Swift 3.0/4.0 let myalert = UIAlertController(title: "Titulo mensaje", message: "Mi mensaje.", preferredStyle: UIAlertControllerStyle.alert)myalert.addAction(UIAlertAction(title: "Aceptar", style: .default) { (action:UIAlertAction!) in print("Selected") })myalert.addAction(UIAlertAction(title: "Cancelar", style: .cancel) { (action:UIAlertAction!) in print("Cancel") }) self.present(myalert, animated: true) Swift 5 let myalert = UIAlertController(title: "Titulo mensaje", message: "Mi mensaje.", preferredStyle: UIAlertController.Style.alert) myalert.addAction(UIAlertAction(title: "Aceptar", style: .default) { (action:UIAlertAction!) in print("Selected") }) myalert.addAction(UIAlertAction(title: "Cancelar", style: .cancel) { (action:UIAlertAction!) in print("Cancel") }) self.present(myalert, animated: true)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36226285', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6115231/']}
jdg_379809
stackexchange
llm_judgeable_groundtruth_similarity
35925504
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 get URI::InvalidURIError testing Rails Home controller: require 'test_helper'class HomeControllerTest < ActionDispatch::IntegrationTest test "should get index" do get :index assert_response :success endend get the following error: EError:HomeControllerTest#test_should_get_index:URI::InvalidURIError: bad URI(is not URI?): http://www.example.com:80index test/controllers/home_controller_test.rb:7:in `block in <class:HomeControllerTest>' The stack is the following: Rails 5.0.0.beta3minitest (5.8.4) Now provide the response and nothing else.
Controller tests inherit from ActionController::TestCase , while your testinherits from ActionDispatch::IntegrationTest . So you're using an integration test and not a controller test. The error is: http://www.example.com:80index That doesn't look right, does it? ;-) The solution is to use a full path: get '/index' Remember, integration tests aren't really tied to any specific controller (or anything else, for that matter). They test the integration of several components in your application. So if you're testing the index action of a UserController you'd probably need to use /users/index . If you intended to make a controller test and not an integration test, you want to set the correct superclass. Using get :index (for the index method) should work fine then.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35925504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/467255/']}
jdg_379810
stackexchange
llm_judgeable_groundtruth_similarity
406609
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: This is a continuation of Number of drifted Brownian motions that never hit zero under allocation For each $n\ge 1$ , consider $X^i_t=1+\beta t + W^i_t$ for $i=1,\ldots n$ and $t\ge 0$ , where $\beta>0$ and $(W^i_t)_{t\ge 0}$ are independent Brownian motions. $\phi\equiv \big((\phi^1_t)_{t\ge 0},\ldots, (\phi^n_t)_{t\ge 0}\big)$ is called an allocation strategy if every $(\phi^i_t)_{t\ge 0}$ is progressively measurable w.r.t. the Brownian filtration $\big(\mathcal F_t:=\sigma(W^1_s,\ldots, W^n_s, s\le t)\big)_{t\ge 0}$ , $$\phi^i_t\ge 0 \quad\mbox{ and }\quad \sum_{i=1}^n\phi^i_t\le 1,\quad \forall t\ge 0.$$ Denote $$X^{\phi,i}_t:=X^i_t+\int_0^t \phi^i_sds \quad \mbox{and} \quad \tau^{\phi}_i:=\inf\{t\ge 0: X^{\phi,i}_t\le 0\}.$$ Let $S^{\phi}_n:=\sum_{1\le i\le n}{\bf 1}_{\{\tau^{\phi}_i=\infty\}}$ be the number of $X^{\phi,i}$ that never hits zero. Clearly, $$\frac{\mathbb E[S^{\bf 0}]}{n}~=~\mathbb P[X^1_t>0, \forall t\ge 0]~=~1-e^{-\beta},$$ where $\bf 0$ stands for the strategy with $\phi^i\equiv 0$ for $i=1,\ldots, n$ . Can we can show $$\lim_{n\to\infty}\frac{\mathbb E[S^{\phi}]}{n}~~=~~1-e^{-\beta}$$ for all the strategies $\phi$ ? Any answers, comments or references are highly appreciated! Now provide the response and nothing else.
The simplest blowup morphism $\mathrm{Bl}_0(\mathbb{A}^2) \to \mathbb{A}^2$ (with center at a point) is not flat. EDIT. Here is an example with affine morphism. Let $$X = \{ x_1y_1 + x_2y_2 + x_3y_3 = 0 \} \subset \mathbb{A}^4_{x_1,x_2,x_3,x_4} \times \mathbb{A}^4_{y_1,y_2,y_3}$$ and let $f \colon X \to \mathbb{A}^3$ be the projection to the second factor. This example, however, is singular at the point $(0,0)$ . EDIT 2. Consider the variety $$\bar{X} = \{x_1y_1 + x_2y_2 + x_3y_3 = 0\} \subset\mathbb{P}^2_{x_1:x_2:x_3} \times \mathbb{A}^3_{y_1,y_2,y_3}.$$ It is smooth, because the projection to $\mathbb{P}^2$ is a fibration with fiber $\mathbb{A}^2$ . On the other hand, the projection $\bar{f} \colon \bar{X} \to \mathbb{A}^3$ is not flat, because the dimension of the fiber jumps at $0$ . Now let $$X = \bar{X} \cap ((\mathbb{P}^2 \setminus C) \times \mathbb{A}^3),$$ where $C$ is a smooth conic. Then $X$ is smooth, because it is open in $\bar{X}$ ; $X$ is affine over $\mathbb{A}^3$ because $\mathbb{P}^2 \setminus C$ is affine, the map $f \colon X \to \mathbb{A}^3$ is surjective, because the smooth conic $C$ cannot contain a fiber of $\bar{f}$ (a line or the plane), the map $f$ is not flat, because the dimension of the fiber still jumps at $0$ .
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/406609', 'https://mathoverflow.net', 'https://mathoverflow.net/users/261243/']}
jdg_379811
stackexchange
llm_judgeable_groundtruth_similarity
174371
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: Given the following data file... foo 10bar 20oof 50rab 20 ... how would I print column two as a percent of the total of column two? In other words, I want... foo 10 10%bar 20 20%oof 50 50%rab 20 20% ... with less obvious numbers of course. I can create a running total easily enough, but I'm not sure how I can calculate the total before printing the lines . I am doing this in an awk file totals.awk ... #!/usr/bin/awk -fBEGIN{ runningtotal=0}{ runningtotal=runningtotal+$2 print $1 "\t" $2 "\t" runningtotal "\t" $2/runningtotal} So, running ./totals.awk data yields... foo 10 10 1bar 20 30 0.666667oof 50 80 0.625rab 20 100 0.2 Is there a way to loop twice, once to calculate the total, and once to print the lines? Is this possible in AWK, or must I use other utilities? Now provide the response and nothing else.
To create the table with a single call to awk : $ awk 'FNR==NR{s+=$2;next;} {printf "%s\t%s\t%s%%\n",$1,$2,100*$2/s}' data datafoo 10 10%bar 20 20%oof 50 50%rab 20 20% How it works The file data is provided as an argument to awk twice. Consequently, it will be read twice, the first time to get the total, which is stored in the variable s , and the second to print the output. Looking at the commands in more detail: FNR==NR{s+=$2;next;} NR is the total number of records (lines) that awk has read and FNR is the number of records read so far from the current file. Consequently, when FNR==NR , we are reading the first file. When this happens, the variable s is incremented by the value in the second column. Then, next tells awk to skip the rest of the commands and start over with the next record. Note that it is not necessary to initialize s to zero. In awk , all numeric variables are, by default, initialized to zero. printf "%s\t%s\t%s%%\n",$1,$2,100*$2/s If we reach this command, then we are processing the second file. This means that s now holds the total of column 2. So, we print column 1, column 2, and the percentage, 100*$2/s . Output format options With printf , detailed control of the output format is possible. The command above uses the %s format specifier which works for strings, integers, and floats. Three other option that might be useful here are: %d formats numbers as integers. If the number is actually floating point, it will be truncated to an integer %f formats numbers as floating point. It is also possible to specify widths and decimals places as, for example, %5.2f . %e provides exponential notation. This would be useful if some numbers were exceptionally large or small. Make a shell function If you are going to use this more than once, it is an inconvenience to type a long command. Instead create either a function or a script to hole the command. To create a function called totals , run the command: $ totals() { awk 'FNR==NR{s+=$2;next;} {printf "%s\t%s\t%s%%\n",$1,$2,100*$2/s}' "$1" "$1"; } With this function defined, the percentages for a data file called data can be found by running: $ totals data To make the definition of totals permanent, place it in your ~/.bashrc file. Make a shell script If you prefer a script, create a file called totals.sh with the contents: #!/bin/shawk 'FNR==NR{s+=$2;next;} {printf "%s\t%s\t%s%%\n",$1,$2,100*$2/s}' "$1" "$1" To get the percentages for a data file called data , run: sh totals.sh data
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/174371', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/55374/']}
jdg_379812
stackexchange
llm_judgeable_groundtruth_similarity
44387285
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Now in iOS 11, the sizeThatFits method is not called from UINavigationBar subclasses. Changing the frame of UINavigationBar causes glitches and wrong insets.So, any ideas how to customize navbar height now? Now provide the response and nothing else.
Updated 07 Jan 2018 This code is support XCode 9.2, iOS 11.2 I had the same problem. Below is my solution. I assume that height size is 66. Please choose my answer if it helps you. Create CINavgationBar.swift import UIKit@IBDesignableclass CINavigationBar: UINavigationBar { //set NavigationBar's height @IBInspectable var customHeight : CGFloat = 66 override func sizeThatFits(_ size: CGSize) -> CGSize { return CGSize(width: UIScreen.main.bounds.width, height: customHeight) } override func layoutSubviews() { super.layoutSubviews() print("It called") self.tintColor = .black self.backgroundColor = .red for subview in self.subviews { var stringFromClass = NSStringFromClass(subview.classForCoder) if stringFromClass.contains("UIBarBackground") { subview.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: customHeight) subview.backgroundColor = .green subview.sizeToFit() } stringFromClass = NSStringFromClass(subview.classForCoder) //Can't set height of the UINavigationBarContentView if stringFromClass.contains("UINavigationBarContentView") { //Set Center Y let centerY = (customHeight - subview.frame.height) / 2.0 subview.frame = CGRect(x: 0, y: centerY, width: self.frame.width, height: subview.frame.height) subview.backgroundColor = .yellow subview.sizeToFit() } } }} Set Storyboard Set Custom NavigationBar class Add TestView + Set SafeArea ViewController.swift import UIKitclass ViewController: UIViewController { var navbar : UINavigationBar! @IBOutlet weak var testView: UIView! override func viewDidLoad() { super.viewDidLoad() //update NavigationBar's frame self.navigationController?.navigationBar.sizeToFit() print("NavigationBar Frame : \(String(describing: self.navigationController!.navigationBar.frame))") } //Hide Statusbar override var prefersStatusBarHidden: Bool { return true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(false) //Important! if #available(iOS 11.0, *) { //Default NavigationBar Height is 44. Custom NavigationBar Height is 66. So We should set additionalSafeAreaInsets to 66-44 = 22 self.additionalSafeAreaInsets.top = 22 } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }} SecondViewController.swift import UIKitclass SecondViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // Create BackButton var backButton: UIBarButtonItem! let backImage = imageFromText("Back", font: UIFont.systemFont(ofSize: 16), maxWidth: 1000, color:UIColor.white) backButton = UIBarButtonItem(image: backImage, style: UIBarButtonItemStyle.plain, target: self, action: #selector(SecondViewController.back(_:))) self.navigationItem.leftBarButtonItem = backButton self.navigationItem.leftBarButtonItem?.setBackgroundVerticalPositionAdjustment(-10, for: UIBarMetrics.default) } override var prefersStatusBarHidden: Bool { return true } @objc func back(_ sender: UITabBarItem){ self.navigationController?.popViewController(animated: true) } //Helper Function : Get String CGSize func sizeOfAttributeString(_ str: NSAttributedString, maxWidth: CGFloat) -> CGSize { let size = str.boundingRect(with: CGSize(width: maxWidth, height: 1000), options:(NSStringDrawingOptions.usesLineFragmentOrigin), context:nil).size return size } //Helper Function : Convert String to UIImage func imageFromText(_ text:NSString, font:UIFont, maxWidth:CGFloat, color:UIColor) -> UIImage { let paragraph = NSMutableParagraphStyle() paragraph.lineBreakMode = NSLineBreakMode.byWordWrapping paragraph.alignment = .center // potentially this can be an input param too, but i guess in most use cases we want center align let attributedString = NSAttributedString(string: text as String, attributes: [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.paragraphStyle:paragraph]) let size = sizeOfAttributeString(attributedString, maxWidth: maxWidth) UIGraphicsBeginImageContextWithOptions(size, false , 0.0) attributedString.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }} Yellow is barbackgroundView. Black opacity is BarContentView. And I removed BarContentView's backgroundColor. That's It.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44387285', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5328102/']}
jdg_379813
stackexchange
llm_judgeable_groundtruth_similarity
15161348
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 compute the number of lines of a UILabel with a fixed width and a given text ? Now provide the response and nothing else.
This code assumes label has the desired text and its frame is already set to the desired width. - (int)lineCountForLabel:(UILabel *)label { CGSize constrain = CGSizeMake(label.bounds.size.width, FLT_MAX); CGSize size = [label.text sizeWithFont:label.font constrainedToSize:constrain lineBreakMode:UILineBreakModeWordWrap]; return ceil(size.height / label.font.lineHeight);} Update : If all you want is to determine the required height for the label based on its text and current width, then change this to: - (CGSize)sizeForLabel:(UILabel *)label { CGSize constrain = CGSizeMake(label.bounds.size.width, FLT_MAX); CGSize size = [label.text sizeWithFont:label.font constrainedToSize:constrain lineBreakMode:UILineBreakModeWordWrap]; return size;} The returned size is the proper width and height to contain the label.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15161348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/507323/']}
jdg_379814
stackexchange
llm_judgeable_groundtruth_similarity
24511153
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My query: DELETE a FROM TR_ContactResultRecord aINNER JOIN TR_Case b on (a.FireStationCode=b.FireStationCode and a.CaseNo=b.CaseCode )WHERE b.Update_DateTime <=20140628134416 It show error: [Err] 1 - near "a": syntax error How delete table inner join with other table in Sqlite? Now provide the response and nothing else.
Try to rewrite you query using subquery: In case your PK for TR_ContactResultRecord is CaseNo DELETE FROM TR_ContactResultRecordWHERE CaseNo IN ( SELECT CaseNo FROM TR_ContactResultRecord a INNER JOIN TR_Case b ON (a.FireStationCode=b.FireStationCode and a.CaseNo=b.CaseCode ) WHERE b.Update_DateTime <=20140628134416);
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24511153', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1497597/']}
jdg_379815
stackexchange
llm_judgeable_groundtruth_similarity
7293408
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 my JAVA_HOME is set to a JDK that is 1.4.2. To run Maven 3, I would need 1.5 and above. Is there any way to instruct my Maven installation to use another JDK that is installed other than changing the JAVA_HOME environment variable? Now provide the response and nothing else.
That's pretty much the way to do it. I assume you mean you don't want to change your global JAVA_HOME. That's fine. You just need to set a different JAVA_HOME for Maven. You can easily do that by creating a file at /etc/mavenrc or ~/.mavenrc (Linux) or %HOME%\mavenrc_pre.bat (Windows) with the appropriate JAVA_HOME defined in it. Maven executes those on startup if they exist unless you've defined a variable named MAVEN_SKIP_RC . You could also modify the Maven startup scripts directly, but there's no good reason for that since it gives you these nice hooks.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7293408', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/321862/']}
jdg_379816
stackexchange
llm_judgeable_groundtruth_similarity
21184
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to recommend to my fellow developers that we all use bcrypt to hash stored passwords. We all use java and I hesitate to recommend jBCrypt only because its latest version number (0.3) indicates that it is a beta release. I see that recent versions of Spring Security have included an implementation that is mostly the exact code from jBCrypt. By "mostly" I mean that Spring Security has changed it to meet their coding conventions and little else that I can detect. To me, Spring Security is a pretty good stamp of approval. My question is: would you all feel comfortable recommending Spring's implementation? If I test it and compare the results to actual bcrypt results, would this be good enough? How would I know if my tests were thorough? Now provide the response and nothing else.
You could audit the jBCrypt code yourself. It is small: one 750-line source code file, half of which being an array of constants. Moreover, since this is Java, you do not have to fear the dreaded "undefined behaviour" of C: if it works well on your machine, it will work well everywhere (for that kind of code, which does not involve threads, system access of floating point computations, the "write once, run everywhere" mantra of Java tends to be true). You can also have a look at the accompanying TestBCrypt.java file: this looks like a reasonably thorough application of known test vectors (including some non-ASCII passwords). The code looks fine to me. For most opensource projects, version numbers are meaningless, since they translate more the author's feeling of inner fulfillment than any actual technical quality of the software. Note: of course, since the point of slow hashing is a budget race between the defender and the attacker, by using Java you are giving a 3x advantage to the attacker: he will use optimized C or assembly (or some FPGA). Yet, properly applied bcrypt, even with Java, should be enough to ensure that password storage is no longer the worst of your problems.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/21184', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/13768/']}
jdg_379817
stackexchange
llm_judgeable_groundtruth_similarity
36541769
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 tried image slider and solved error of .this file using getActivity().But as soon as i open the app it will stop how to solve that. java code that extends fragment .java code public class CargoHome extends Fragment {View myView;Animation fade_in, fade_out;ViewFlipper viewFlipper;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { myView = inflater.inflate(R.layout.cargo_home, container, false); viewFlipper = (ViewFlipper)getActivity().findViewById(R.id.backvf); fade_in = AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in); fade_out = AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out); viewFlipper.setInAnimation(fade_in); viewFlipper.setOutAnimation(fade_out); viewFlipper.setAutoStart(true); viewFlipper.setFlipInterval(5000); viewFlipper.startFlipping(); return myView;} } xml code .xml code <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"><LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent"> <ViewFlipper android:id="@+id/backvf" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/img1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:scaleType="fitCenter" android:src="@drawable/bolt" /> <ImageView android:id="@+id/img2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:scaleType="fitCenter" android:src="@drawable/nano" /> <ImageView android:id="@+id/img3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:scaleType="fitCenter" android:src="@drawable/zest" /> </ViewFlipper> </LinearLayout></RelativeLayout> fade_in and fade_out xml file fade_in and fade_out.xml <?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"> <alpha android:duration="2000" android:fromAlpha="0.0" android:toAlpha="1.0" android:interpolator="@android:anim/accelerate_interpolator" /></set> Now provide the response and nothing else.
Swift 3.0+: let element = arr.remove(at: 3)arr.insert(element, at: 2) and in function form: func rearrange<T>(array: Array<T>, fromIndex: Int, toIndex: Int) -> Array<T>{ var arr = array let element = arr.remove(at: fromIndex) arr.insert(element, at: toIndex) return arr} Swift 2.0: This puts 3 into position 4. let element = arr.removeAtIndex(3)arr.insert(element, atIndex: 2) You can even make a general function: func rearrange<T>(array: Array<T>, fromIndex: Int, toIndex: Int) -> Array<T>{ var arr = array let element = arr.removeAtIndex(fromIndex) arr.insert(element, atIndex: toIndex) return arr} The var arr is needed here, because you can't mutate the input parameter without specifying it to be in-out . In our case however we get a pure functions with no side effects, which is a lot easier to reason with, in my opinion.You could then call it like this: let arr = [1,2,3,4]rearrange(arr, fromIndex: 2, toIndex: 0) //[3,1,2,4]
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/36541769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6186568/']}
jdg_379818
stackexchange
llm_judgeable_groundtruth_similarity
24301986
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 get 2 classes in package P . Interface class A and its implementation class B . In the file with class B I get the following error: The type java.lang.CharSequence cannot be resolved. It is indirectly referenced from required .class files . I'm using Eclipse Helios and $ java -versionjava version "1.8.0_05"Java(TM) SE Runtime Environment (build 1.8.0_05-b13)Java HotSpot(TM) Server VM (build 25.5-b02, mixed mode) Standard solution of removing and adding JRE doesn't work. How can I fix it? EDIT: Code: Class A : package com.jax;import javax.jws.WebMethod;import javax.jws.WebService;import javax.jws.soap.SOAPBinding;import javax.jws.soap.SOAPBinding.Style;@WebService@SOAPBinding(style = Style.RPC)public interface WebServiceInter {@WebMethodString sayHello();} Class B : package com.jax; // **Error is here**import javax.jws.WebService;@WebService(endpointInterface = "com.jax.WebServiceInter")public class WebServiceImpl implements WebServiceInter{ @Override public String sayHello(){ return "Hello!"; }} Project structure: ProjectName -> Java Resources -> com.jax -> Class A , Class B Now provide the response and nothing else.
Java 8 supports default methods in interfaces. And in JDK 8 a lot of old interfaces now have new default methods. For example, now in CharSequence we have chars and codePoints methods . If source level of your project is lower than 1.8, then compiler doesn't allow you to use default methods in interfaces. So it cannot compile classes that directly on indirectly depend on this interfaces. If I get your problem right, then you have two solutions. First solution is to rollback to JDK 7, then you will use old CharSequence interface without default methods. Second solution is to set source level of your project to 1.8, then your compiler will not complain about default methods in interfaces.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24301986', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3712116/']}
jdg_379819
stackexchange
llm_judgeable_groundtruth_similarity
359194
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 would like to understand why is redis called an in memory database when it provides persistence similar to databases like MySQL or Postgres: http://oldblog.antirez.com/post/redis-persistence-demystified.html https://redis.io/topics/persistence Now provide the response and nothing else.
Redis is an in-memory database because it keeps the whole data set in memory, and answers all queries from memory. Because RAM is faster than disks, this means Redis always has very fast reads. The drawback is that the maximum size of the data set is limited by the available RAM. Redis has various options to save the data to permanent storage. This permanent representation can then be used to rebuild the in-memory state of a Redis instance. However, this representation is not indexed and cannot be used to answer queries directly from disk. This is in stark contrast to databases like Postgres. They always keep the whole data set including indices on disk in a format that allows random access. Queries can be answered directly from the on-disk data. The database may load caches or indices into memory as an optimization, but that is not fundamentally necessary: the database can handle more data than fits into RAM. A larger difference between Redis and SQL databases is how they deal with writes, i.e. what durability guarantees they provide. There are a lot of tunable parameters here, so it's not correct to say “an SQL database is always more durable than a Redis database”. However, Redis usually commits data to permanent storage on a periodic basis, whereas Postgres will usually commit before each transaction is marked as complete. This means Postgres is slower because it commits more frequently, but Redis usually has a time window where data loss may occur even when the client was told that their update was handled successfully. This data loss may or may not be an acceptable tradeoff in a given use case. What kind of data set always fits into RAM, is a good match for a key–value datamodel, and doesn't need durability? A cache for some other data source. Redis is very good at being fast. SQL databases like Postgres are better at dealing with large data sets and providing ACID guarantees .
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/359194', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/23899/']}
jdg_379820
stackexchange
llm_judgeable_groundtruth_similarity
9198309
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to create a one step checkout, but in the checkout page I have problem with order review part . When I select a payment method for example "cash on deliver" has 5$ extra, or "checkorder" has %4 discount or "credit card payment" adds extra to the order total. I need a way to calculate the discounts before saving the payment method. Any suggestion? Now provide the response and nothing else.
Because we are talking about Magento, there are several ways you could do this. The best way to implement that functionality would be to create your own total models for the discounts or additional charges. How to create custom Magento total models To create your own total model you first need to create a module, and add the total models to the configuration. <global> <sales> <quote> <totals> <your_total> <class>your_module/quote_address_total_yourTotal</class> <after>shipping</after><!-- calculate after these total models --> <before>grand_total,tax</before><!-- calculate before these total models --> </your_total> </totals> </quote> <order_invoice> <totals> <your_total> <class>your_module/order_invoice_total_yourTotal</class> <after>shipping</after> <before>grand_total,tax</before> </your_total> </totals> </order_invoice> <order_creditmemo> <totals> <your_total> <class>your_module/order_creditmemo_total_yourTotal</class> <after>shipping</after> <before>grand_total,tax</before> </your_total> </totals> </order_creditmemo> </sales> <pdf> <totals> <your_total translate="title"> <title>Your Total</title> <source_field>your_total</source_field> <font_size>7</font_size> <display_zero>0</display_zero> <sort_order>450</sort_order> </your_total> </totals> </pdf></global> Then implement the three classes specified in the XML. The quote address total needs to extend sales/quote_address_total_abstract and implement the two methods collect() and fetch() . class Your_Module_Model_Quote_Address_Total_YourTotal extends Mage_Sales_Model_Quote_Address_Total_Abstract{ // Calculate your total value public function collect(Mage_Sales_Model_Quote_Address $address) { parent::collect($address); // Calculate the totals based on the information in the $address // and the $address->getQuote() // To get the items in the cart use $address->getAllItems() // To get the payment method use getPayment()->getMethodInstance() // etc // When your totals are known.. $this->_addAmount($total); // store view currency amount $this->_addBaseAmount($baseTotal); // base currency amount // Also store in address for later reference in fetch() $address->setMyTotal($total); $address->setBaseMyTotal($baseTotal); return $this; } // If the total should be displayed in the cart and the checkout // add them to the address model here, otherwise just return // (it will still be calculated and added to the grand total) public function fetch(Mage_Sales_Model_Quote_Address $address) { if ($address->getMyTotal() > 0) { $address->addTotal(array( 'code' => $this->getCode(), 'title' => Mage::helper('your_module')->__('Your Total'), 'value' => $address->getMyTotal() )); } return $this; }} The next class specified in the config XML is the invoice total model your_module/order_invoice_total_yourTotal . class Your_Module_Model_Order_Invoice_Total_YourTotal extends Mage_Sales_Model_Order_Invoice_Total_Abstract{ // Collect the totals for the invoice public function collect(Mage_Sales_Model_Order_Invoice $invoice) { $order = $invoice->getOrder(); $myTotal = $order->getMyTotal(); $baseMyTotal = $order->getBaseMyTotal(); $invoice->setGrandTotal($invoice->getGrandTotal() + $myTotal); $invoice->setBaseGrandTotal($invoice->getBaseGrandTotal() + $basemyTotal); return $this; }} The final class you need to implement in the creditmemo total model, which is just like the invoice total model, only it extends the abstract class Mage_Sales_Model_Order_Creditmemo_Total_Abstract . You will also need to add the attributes using a setup script: /** * @var Mage_Sales_Model_Resource_Setup $installer */$installer = Mage::getResourceModel('sales/setup', 'default_setup');$installer->startSetup();$installer->addAttribute('order', 'base_your_total', array( 'label' => 'Base Your Total', 'type' => 'decimal',));$installer->addAttribute('order', 'your_total', array( 'label' => 'Your Total', 'type' => 'decimal',));$installer->addAttribute('invoice', 'base_your_total', array( 'label' => 'Base Your Total', 'type' => 'decimal',));$installer->addAttribute('invoice', 'your_total', array( 'label' => 'Your Total', 'type' => 'decimal',));$installer->addAttribute('creditmemo', 'base_your_total', array( 'label' => 'Base Your Total', 'type' => 'decimal',));$installer->addAttribute('creditmemo', 'your_total', array( 'label' => 'Your Total', 'type' => 'decimal',));$installer->endSetup(); In order to display the new total in the admin area, you need to add a totals block for it using layout XML. Register a layout update file for the adminhtml area in your module. Here is a sample content: <layout version="0.1.0"> <adminhtml_sales_order_view> <reference name="order_totals"> <block type="your_module/sales_total_yourTotal" name="total_your_total" as="your_total"/> </reference> </adminhtml_sales_order_view> <adminhtml_sales_order_invoice_new> <reference name="invoice_totals"> <block type="your_module/sales_total_yourTotal" name="total_your_total" as="your_total"/> </reference> </adminhtml_sales_order_invoice_new> <adminhtml_sales_order_invoice_updateqty> <reference name="invoice_totals"> <block type="your_module/sales_total_yourTotal" name="total_your_total" as="your_total"/> </reference> </adminhtml_sales_order_invoice_updateqty> <adminhtml_sales_order_invoice_view> <reference name="invoice_totals"> <block type="your_module/sales_total_yourTotal" name="total_your_total" as="your_total"/> </reference> </adminhtml_sales_order_invoice_view> <adminhtml_sales_order_creditmemo_new> <reference name="creditmemo_totals"> <block type="your_module/sales_total_yourTotal" name="total_your_total" as="your_total"/> </reference> </adminhtml_sales_order_creditmemo_new> <adminhtml_sales_order_creditmemo_view> <reference name="creditmemo_totals"> <block type="your_module/sales_total_yourTotal" name="total_your_total" as="your_total"/> </reference> </adminhtml_sales_order_creditmemo_view></layout> If you don't want to display your total somewhere, just leave it out. It will still be calculated.Okay, almost there. Finally, the admin area total block class implementation: // Many ways to implement this, here is one optionclass Your_Module_Block_Sales_Total_YourTotal extends Mage_Core_Block_Abstract{ public function initTotals() { $parent = $this->getParentBlock(); $value = $parent->getSource()->getMyTotal(); if ($value > 0) { $total = new Varien_Object(array( 'code' => 'my_total', 'value' => $parent->getSource()->getMyTotal(), 'base_value' => $parent->getSource()->getBaseMyTotal(), 'label' => $this->__('My Total'), 'field' => 'my_total' )); $parent->addTotal($total, 'my_total'); } return $this; }} Now the only thing missing is the fieldset to copy the total amount from the quote address to the order, and from the order to the invoice and creditmemo. Add the following XML to the config.xml: <fieldsets> <sales_convert_quote_address> <shipping_surcharge><to_order>*</to_order></shipping_surcharge> <base_shipping_surcharge><to_order>*</to_order></base_shipping_surcharge> </sales_convert_quote_address> <sales_convert_order> <shipping_surcharge><to_invoice>*</to_invoice><to_cm>*</to_cm></shipping_surcharge> </sales_convert_order></fieldsets> And thats it. The total will be displayed everywhere (including the generated PDF's). As I said, there are many other ways to simply update the values of the total models already present in the core, but this is the full blown way to implement it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9198309', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/516218/']}
jdg_379821
stackexchange
llm_judgeable_groundtruth_similarity
412952
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: An ancient version of ipconfig (inside initramfs) requires its user input to supply only up to 7 colon separated elements, like: ip=client-ip:server-ip:gw-ip:netmask:hostname:device:autoconf result in an ipconfig error when users do supply more than 7 elements. Therefore the extra (2 DNS resolvers) should be chopped off. That can be done inside a subshell with cut , like: validated_input=$(echo ${user_input} | cut -f1,2,3,4,5,6,7 -d:) How can such cut be written using (b)ash parameter expansion/substitution? Without: launching subshell(s)/subprocess(es) (piping) IFS-wrangling/mangling Because of (1) speed, see Using bash variable substitution instead of cut/awk , and (2) learning. In other words: How to do a lookup for n-th (7-th) character occurrence and remove/trim everything from there until the end of the string? Now provide the response and nothing else.
This uses only parameter expansion: ${var%:"${var#*:*:*:*:*:*:*:}"} Example : $ var=client-ip:server-ip:gw-ip:netmask:hostname:device:autoconf:morefields:another:youwantanother:haveanother:$ echo "${var%:"${var#*:*:*:*:*:*:*:}"}"client-ip:server-ip:gw-ip:netmask:hostname:device:autoconf Thanks ilkkachu for coming up with a fix to the trailing : ! ${parameter#word}${parameter##word} The word is expanded to produce a pattern just as in filename expansion (see Filename Expansion). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ‘#’ case) or the longest matching pattern (the ‘##’ case) deleted. If parameter is ‘@’ or ‘ ’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘ ’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list. This will attempt to match the beginning of your parameter, and if it does it will strip it. Example : $ var=a:b:c:d:e:f:g:h:i$ echo "${var#a}":b:c:d:e:f:g:h:i$ echo "${var#a:b:}"c:d:e:f:g:h:i$ echo "${var#*:*:}"c:d:e:f:g:h:i$ echo "${var##*:}" # Two hashes make it greedyi ${parameter%word}${parameter%%word} The word is expanded to produce a pattern just as in filename expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the ‘%’ case) or the longest matching pattern (the ‘%%’ case) deleted. If parameter is ‘@’ or ‘ ’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘ ’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list. This will attempt to match the end of your parameter, and if it does it will strip it. Example : $ var=a:b:c:d:e:f:g:h:i$ echo "${var%i}"a:b:c:d:e:f:g:h:$ echo "${var%:h:i}"a:b:c:d:e:f:g$ echo "${var%:*:*}"a:b:c:d:e:f:g$ echo "${var%%:*}" # Two %s make it greedya So in the answer: ${var%:"${var#*:*:*:*:*:*:*:}"} (note the quotes around ${var#...} so that it is treated as a literal string (not a pattern) to be stripped off the end of $var ). When applied to: var=client-ip:server-ip:gw-ip:netmask:hostname:device:autoconf:morefields:another:youwantanother:haveanother: ${var#*:*:*:*:*:*:*:} = morefields:another:youwantanother:haveanother: That is expanded inside ${var%: ... } like so: ${var%:morefields:another:youwantanother:haveanother:} So you are saying give me: client-ip:server-ip:gw-ip:netmask:hostname:device:autoconf:morefields:another:youwantanother:haveanother: But trim :morefields:another:youwantanother:haveanother: off the end. The Bash Reference Manual ( 3.5.3 )
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/412952', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/17560/']}
jdg_379822
stackexchange
llm_judgeable_groundtruth_similarity
32716685
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 do a programmatical RayTracer in Java for demo purpose while giving a presentation about Ray Tracing in general (also mentioning 3D, this 2D model should only be for easier understanding, and to train my general Java knowledge). My problem is, that i dont know where to start this whole thing. The first thing i would try is to use vectors to trace every pixel on the screen from a given coordinate (eg. the position of my mouse cursor). Then I would calculate if the vector intersects with a polygon and then i would stop the vector there and draw it only to this specific point. Maybe i could even draw some shadows by calculating the normal and reflect the vector in the other direction with a lower intensity. So would it be a good idea to draw a vector from A = {everypixelonthescreen} to a specific Point P and calculate the intersections? The finished version should look somewhat like this: Now provide the response and nothing else.
I am afraid that the kind of ray trace app you are proposing is a bit more misleading than to use a real 3D ray-tracer. 2D ray tracers are used a bit differently and this may confuse your audience a lot I would try to chose a more native 2D ray-trace usage like: Optic simulation This is used to simulate lens and mirrors optics. This image is from one of my ancient 2D ray-trace simulations: Store your world You’ve got a lens in the form of polylines + diffraction index and mirrors also as polylines. You have the world diffraction index cast R,G,B rays from source of light Cast important ones only or all of them. Use Snell's law to simulate optics As you can see the chromatic error is visible (each color has its own wavelength so the diffraction index is different). You can also use MultiBand rendering . I used this to tune custom optic systems. If you add drag & drop capability you’ve got Optic Lab . Wolfenstein demo This pseudo 3D game used a 2D ray casting engine. See Wiki: Wolfenstein_3D_engine . This image was taken from this link: first draw the floor and ceiling/sky as 2 half screens (screen divided by horizon) then you’ve got a 2D map of your maze/world (right) So cast rays from your current position in all visible directions (similar to your image but usually a 60 degree view is used). Rays must be done with subpixel (cell) precision. Where your ray hit the wall (on map) obtain the subpixel (cell) position. It indicates which part of wall texture is hit draw the appropriate column (vertical line) on the screen for each ray hit The size and scale of it is determinated by the distance from the ray origin. The fish eye correction is applied — if my memory serves it was done by using only perpendicular distance (multiply distance by cos(ray_angle - player_angle) ). Here’s an example of what I busted out for fun just now: It was done in C++ with pure GDI (using the bitmap scan line only), no other 3th party libs at all. It uses a single texture, diffuse + ambient lighting, 2D raycasting. Has 2 bitmaps (screen, texture-atlas) and a single 2D map. The code is less then 9 KByte including rems. It is controlled by keyboard only (mouse is used to edit the maze in the map subwindow). Here animated GIF example: If you're interested see this related QA: Wolfenstein with variable height of cells
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32716685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3398060/']}
jdg_379823
stackexchange
llm_judgeable_groundtruth_similarity
60235314
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I recently started update to okhttp3 to 4.x In doing so I am getting following build time error: Using 'url(): HttpUrl' is an error. moved to val The issue is happening when I am trying to get url from request object obtained via call: e.g call.enque(callback : Callback){ override fun onFailure(call : Call, t:Throwable) { val url = call.request().url().toString } } I looked up further and the Url object within Request is val aka final now. Also, no directions on their upgrade guide https://square.github.io/okhttp/upgrading_to_okhttp_4/ I would appreciate for any suggestions on another way to obtain Url. Now provide the response and nothing else.
Using 'url(): HttpUrl' is an error. moved to val This means you should change the function call url() to a property access url . okhttp 4 comes with replaceWith param in the deprecation annotation that makes e.g. Android Studio to offer that fix automatically with right-click/alt-enter on the error: @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "url"), level = DeprecationLevel.ERROR) From comments: Upon further investigation I found out that the request() or Request object is from Retrofit 2. And Retrofit 2 returns call object from okhttp3 That's an issue with Android Studio. You can work around it with explicit cast to okhttp 4 types, e.g. (call.request() as Request).url .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60235314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/957658/']}
jdg_379824
stackexchange
llm_judgeable_groundtruth_similarity
27029846
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to use VIM to replace all the characters up to the first comma in a large text file (10mb+) I have something that looks like: foo,bar,sunapple,pear,goosemonkey,pig,baby and I want it to look like: bar,sunpear,goosepig,baby Now provide the response and nothing else.
The following should do it :%s/^[^,]*,// Explanation: : Command mode % Apply to every line s Substitute / match ^ From the start of the line [^,] Any character other than comma * (See previous) Repeated or empty , A comma / replace nothing / finished Alternatively you can use sed: sed 's/^[^,]*,//' -i FILENAME or sed 's/^[^,]*,//' FILENAME > NEWFILENAME Edit: minor formatting and explain ":"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27029846', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3646369/']}
jdg_379825
stackexchange
llm_judgeable_groundtruth_similarity
31262539
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 these strings: baseUrl = "http://www.example.com"baseUrl = "https://secure.example-server.com:443" Can someone tell me how I can extract the server information from baseUrl so I can get either "example" and "example-server" Now provide the response and nothing else.
You can use regex : baseUrl.match(/\.(.*?)\.co/i)[1]; Regex Explanation / : Delimiters of regex \. : Matches . literal(need to be escaped) () : Capturing group .*? : Match any string co : Matches string co i : Match in-case-sensitive [1] : Get the capturing group Regex Visualization
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31262539', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/975566/']}
jdg_379826
stackexchange
llm_judgeable_groundtruth_similarity
4661211
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to create a generic object from a reflected type in C# (.Net 2.0)? void foobar(Type t){ IList<t> newList = new List<t>(); //this doesn't work //...} The Type, t, is not known until runtime. Now provide the response and nothing else.
Try this: void foobar(Type t){ var listType = typeof(List<>); var constructedListType = listType.MakeGenericType(t); var instance = Activator.CreateInstance(constructedListType);} Now what to do with instance ? Since you don't know the type of your list's contents, probably the best thing you could do would be to cast instance as an IList so that you could have something other than just an object : // Now you have a list - it isn't strongly typed but at least you// can work with it and use it to some degree.var instance = (IList)Activator.CreateInstance(constructedListType);
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4661211', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/140731/']}
jdg_379827
stackexchange
llm_judgeable_groundtruth_similarity
318851
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 very often get myself in a situation where I need a different behavior of a component which depends on the concrete type of a different Interface. To illustrate my question, I have written a small code piece which will show what I mean. In this Example I'm trying to instantiate an food object from an animal object. interface Animal { void growl(); String getAnimalType(); //"DOG" or "FISH"}abstract class Food {}Meat extends Food {}Bread extends Food {}class FoodFactory { Food createFoodForAnimal(Animal animal) { switch (animal.getAnimalType()) { case "DOG": Food food = new Meat(); break; case "FISH": Food food = new Bread(); break; default: return; } }}Animal dog = new Dog();Animal fish = new Fish();FoodFactory factory = new FoodFactory();Food food = factory.createFoodForAnimal(dog)Food food = factory.createFoodForAnimal(fish) To me this feels somewhat dirty, because is looks like a cast in disguise. Now provide the response and nothing else.
Tell, don't ask might help you out here. switch (animal.getAnimalType()) { case "DOG": Food food = new Meat(); break; case "FISH": Food food = new Bread(); break; default: return; } Notice what this code fragment is - a switch on behavior. That's a "code smell" in an object oriented solution. Usually, it indicates that there is an underlying object that you haven't discovered. Here, it might be more accurate to say that you haven't delegated the responsibility to the objects you have already discovered. interface Animal { void growl(); void orderDinner(DinnerOrder order);}class Dog implements Animal { //... void orderDinner(DinnerOrder order) { order.add(new Meat()); }}class Fish implements Animal { //... void orderDinner(DinnerOrder order) { order.add(new Bread()); }} Actually, it probably doesn't quite make sense to specify the instance of the food that the animal wants - it probably doesn't care about a specific Bread entity, so much as Bread as a type . So maybe that gets deferred to the DinnerOrder object. So you might implement DinnerOrder with methods that allow an animal to specify the kind of food that it wants, and free the Animal from knowing the details (encapsulation). class Fish implements Animal { //... void orderDinner(DinnerOrder order) { order.addBread(); }} Hard wiring in a specific command isn't readily generalized. So it might be that you want to use arguments to specify the food after all. But as noted above, we probably don't care which Bread entity is dinner tonight; in particular, we might want to give the Animals a special treat at Christmas; so the animals specify what they want, and then the provider does its best. class Fish implements Animal { //... void orderDinner(DinnerOrder order) { order.add(BREAD); }} Of course, if you think preferredFood is a trait that a number of Animals have, then you might look to treat the food, not as a static constant, but as a property of an instance. class Fish implements Animal { //... void orderDinner(DinnerOrder order) { order.add(this.preferredFood); }} This is a very common OO pattern; a method that passes a copy of its state to an argument for further processing. For instance, this is how DomainServices typically work in a domain model -- the service is passed to an aggregate, which supplies its own state back to the service for work. Specifications are sometimes used to make this even more general. Instead of passing a property for the DinnerOrder to interpret, you can pass a predicate that identifies what foods have that property, and then let the receiver investigate the alternatives available. Specification<Food> FISH_FOOD = new Specification { boolean isSatifiedBy(Food food) { return food.isA(BREAD); }}class Fish implements Animal { //... void orderDinner(DinnerOrder order) { order.order(FISH_FOOD); }} Used in this way, the Specification is an example of the Strategy pattern; which might be a better fit if you wanted to give the Animals a way to rank/choose which of the available options they would prefer....
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/318851', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/228943/']}
jdg_379828
stackexchange
llm_judgeable_groundtruth_similarity
30479
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 see these around the web and would like to make them in Mathematica . Combining them in an array is actually quite mesmerizing! Now provide the response and nothing else.
Forward Mapping One way to do it is to create the texture for one tile and then transform repeated copies of it in a way that resembles the original illusion. First we create the tile: tile = Module[{KeyHole}, KeyHole[base_] := Sequence[ Disk[{0, 1/3} + base, 1/10], Rectangle[{-1/30, 1/15} + base, {1/30, 1/3} + base] ]; Image@Rasterize@Graphics[ {Orange, Rectangle[{0, 0}, {1, 1}], Blue, Rectangle[{0, 0}, {1/2, 1/2}], Rectangle[{1/2, 1/2}, {1, 1}], Black, KeyHole[{0, 0}], KeyHole[{1/2, 1/2}], KeyHole[{1, 0}], White, KeyHole[{0, 1/2}], KeyHole[{1/2, 0}], KeyHole[{1, 1/2}] }, PlotRange -> {{0, 1}, {0, 1}} ] ] Then we make repeated copies of it: floortex = ImagePad[ ImageRotate[#, Right], 5 First@ImageDimensions[#], "Periodic" ] &[tile] For the transformation we can use an exponential mapping, which will turn the $y$-coordinate into an angle and the $x$-coordinate into an exponent for radial distance. Since the mapping is most elegantly described with complex numbers but we need to work with cartesian coordinates we can use ComplexExpand to do the work for us (which is not very hard in this case, but could be useful for trying out other mappings): ComplexExpand[Through[{Re, Im}[ Exp[x + I y] ]]](* {E^x Cos[y], E^x Sin[y]} *) Since this is so useful we wrap it in a procedure for easy reuse: CartesianMappingFromComplexFunction[f_] := Function[{x, y}, Evaluate@ComplexExpand@Through[{Re, Im}[f[x + I y]]] ] Now we just need a way to transform our checkerboard image according to our mapping, which is exactly what ImageForwardTransformation does: ImageForwardTransformation[ floortex, {Exp[#[[1]]] Cos[#[[2]]], Exp[#[[1]]] Sin[#[[2]]]} &, PlotRange -> {{-1, 1}, {-1, 1}}, DataRange -> {{-2 \[Pi], 0}, {0, 2 \[Pi]}}, Background -> White] Inverse Mapping Michael E2 pointed out another possible way, namely using the inverse mapping, so let's try that! Up to now we basically let Mathematica do a forward transform of our checkerboard into the disk shape and let it fill the holes via interpolation and throw away the points that got mapped outside of our PlotRange which is kind of wasteful. Instead we can go the reverse route and start with the destination pixel locations and ask where they came from before undergoing that exponential mapping. Since we made the effort to generalize the procedure of getting a cartesian mapping from any complex function we now can just plug in the inverse complex function, which is the (or rather a branch of) the complex Log , and get CartesianMappingFromComplexFunction[Log](* Function[{x, y}, {Log[x^2 + y^2]/2, Arg[x + I*y]}] *) Great! Now we can use ImageTransformation with our inverse mapping ImageTransformation[ floortex, {Log[#[[1]]^2 + #[[2]]^2]/2, Arg[#[[1]] + I*#[[2]]]} &, PlotRange -> {{-1, 1}, {-1, 1}}, DataRange -> {{-2 \[Pi], 0}, {-\[Pi], \[Pi]}}, Padding -> White] where we had to adjust the DataRange in order to coincide with the target set of Arg . Because we evenly sample the target image instead of the original checkerboard, we get much better image quality with less computation (14s vs. 19s on my machine). To see the difference here are images from both approaches, but generated from a tile with RasterSize -> 128 and ImageResolution -> 128 given as options to Rasterize : ImageForwardTransformation ImageTransformation With ImageTransformation , we basically get antialiasing for free, which can be further customized via the Resampling option.
{}
{'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/30479', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/686/']}
jdg_379829
stackexchange
llm_judgeable_groundtruth_similarity
62115518
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 add a persistent layout to certain pages of my Next.js application. I found this article explaining a couple ways on how someone could do this. It seems pretty straightforward, however I have encountered the following two problems when using the recommended way of doing it: I am using TypeScript and am not sure how to type it. For example, I have the following, which is working, but I obviously don't like using as any : const getLayout = (Component as any).getLayout || ((page: NextPage) => <SiteLayout children={page} />); I am using Apollo and so I am using a withApollo HOC (from here ) for certain pages. Using this causes Component.getLayout to always be undefined . I don't have a good enough understanding of what is going on to know why this is happening (I can guess), so it's difficult to solve this by myself. Since asking this question they have added a good example to their documentation Now provide the response and nothing else.
I have the similar problem and this is how I solved it for my project. Create a types/page.d.ts type definition: import { NextPage } from 'next'import { ComponentType, ReactElement, ReactNode } from 'react'export type Page<P = {}> = NextPage<P> & { // You can disable whichever you don't need getLayout?: (page: ReactElement) => ReactNode layout?: ComponentType} In your _app.tsx file, import type { AppProps } from 'next/app'import { Fragment } from 'react'import type { Page } from '../types/page'// this should give a better typingtype Props = AppProps & { Component: Page}const MyApp = ({ Component, pageProps }: Props) => { // adjust accordingly if you disabled a layout rendering option const getLayout = Component.getLayout ?? (page => page) const Layout = Component.layout ?? Fragment return ( <Layout> {getLayout(<Component {...pageProps} />)} </Layout> ) // or swap the layout rendering priority // return getLayout(<Layout><Component {...pageProps} /></Layout>)}export default MyApp The above is just a sample implementation best suited for my use-case, you can switch the type in types/page.d.ts to fit your needs.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/62115518', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4255859/']}
jdg_379830
stackexchange
llm_judgeable_groundtruth_similarity
16041232
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 building a web app in Django. I have a model that uploads a file, but I can not delete the file. Here is my code: class Song(models.Model): name = models.CharField(blank=True, max_length=100) author = models.ForeignKey(User, to_field='id', related_name="id_user2") song = models.FileField(upload_to='/songs/') image = models.ImageField(upload_to='/pictures/', blank=True) date_upload = models.DateField(auto_now_add=True) def delete(self, *args, **kwargs): # You have to prepare what you need before delete the model storage, path = self.song.storage, self.song.path # Delete the model before the file super(Song, self).delete(*args, **kwargs) # Delete the file after the model storage.delete(path) Then, in python manage.py shell I do this: song = Song.objects.get(pk=1)song.delete() It deletes the record from the database but not the file on server.What else can I try? Thanks! Now provide the response and nothing else.
Before Django 1.3, the file was deleted from the filesystem automatically when you deleted the corresponding model instance. You are probably using a newer Django version, so you'll have to implement deleting the file from the filesystem yourself. Simple signal-based sample My method of choice at the time of writing is a mix of post_delete and pre_save signals, which makes it so that obsolete files are deleted whenever corresponding models are deleted or have their files changed. Based on a hypothetical MediaFile model: import osimport uuidfrom django.db import modelsfrom django.dispatch import receiverfrom django.utils.translation import ugettext_lazy as _class MediaFile(models.Model): file = models.FileField(_("file"), upload_to=lambda instance, filename: str(uuid.uuid4()))# These two auto-delete files from filesystem when they are unneeded:@receiver(models.signals.post_delete, sender=MediaFile)def auto_delete_file_on_delete(sender, instance, **kwargs): """ Deletes file from filesystem when corresponding `MediaFile` object is deleted. """ if instance.file: if os.path.isfile(instance.file.path): os.remove(instance.file.path)@receiver(models.signals.pre_save, sender=MediaFile)def auto_delete_file_on_change(sender, instance, **kwargs): """ Deletes old file from filesystem when corresponding `MediaFile` object is updated with new file. """ if not instance.pk: return False try: old_file = MediaFile.objects.get(pk=instance.pk).file except MediaFile.DoesNotExist: return False new_file = instance.file if not old_file == new_file: if os.path.isfile(old_file.path): os.remove(old_file.path) I think one of the apps I’ve built a while back used this code in production, but nevertheless use at your own risk. For example, there’s a possible data loss scenario: your data might end up referencing a nonexistent file if your save() method call happens to be within a transaction that gets rolled back. You could consider wrapping file-removing logic into transaction.on_commit() , along the lines of transaction.on_commit(lambda: os.remove(old_file.path)) , as suggested in Mikhail’s comment . django-cleanup library does something along those lines . Edge case: if your app uploads a new file and points model instance to the new file without calling save() (e.g. by bulk updating a QuerySet ), the old file will keep lying around because signals won’t be run. This doesn’t happen if you use conventional file handling methods. Coding style: this example uses file as field name, which is not a good style because it clashes with the built-in file object identifier. Addendum: periodic cleanup Realistically, you may want to also run a periodic task to handle orphan file cleanup in case a runtime failure prevents some file from being removed. With that in mind, you could probably get rid of signal handlers altogether, and make such a task the mechanism for dealing with insensitive data and not-so-large files. Either way though, if you are handling sensitive data, it’s always better to double- or triple- check that you never fail to timely delete data in production to avoid any associated liabilities. See also FieldFile.delete() in Django 1.11 model field reference (note that it describes the FieldFile class, but you’d call .delete() directly on the field: FileField instance proxies to the corresponding FieldFile instance, and you access its methods as if they were field’s) Note that when a model is deleted, related files are not deleted. If you need to cleanup orphaned files, you’ll need to handle it yourself (for instance, with a custom management command that can be run manually or scheduled to run periodically via e.g. cron). Why Django doesn’t delete files automatically: entry in release notes for Django 1.3 In earlier Django versions, when a model instance containing a FileField was deleted, FileField took it upon itself to also delete the file from the backend storage. This opened the door to several data-loss scenarios, including rolled-back transactions and fields on different models referencing the same file. In Django 1.3, when a model is deleted the FileField ’s delete() method won’t be called. If you need cleanup of orphaned files, you’ll need to handle it yourself (for instance, with a custom management command that can be run manually or scheduled to run periodically via e.g. cron). Example of using a pre_delete signal only
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/16041232', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1967886/']}
jdg_379831
stackexchange
llm_judgeable_groundtruth_similarity
21540951
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 setup a [add media] button, with: proper wordpress [media] UI has size and alignments UI in popup right hand side can custom popup title and button size and alignments arguments can send back to be use Now provide the response and nothing else.
Just try to cover most solutions: use tb_show("", "media-upload.php?type=image&amp;TB_iframe=true"); and window.send_to_editor problem: has no standard wp.media UI in js code: jQuery("#my_button").click(function() { tb_show("", "media-upload.php?type=image&amp;TB_iframe=true"); return false;});window.send_to_editor = function(html) { console.log(html); tb_remove();} use wp.media({frame: 'post'}) problem: cannot custom UI elements, such as: title, button in js code: function clearField(){ #remove file nodes #...}var frame = wp.media({frame: 'post'});frame.on('close',function() { var selection = frame.state().get('selection'); if(!selection.length){ clearField(); }});frame.on( 'select',function() { var state = frame.state(); var selection = state.get('selection'); if ( ! selection ) return; clearField(); selection.each(function(attachment) { console.log(attachment.attributes); });});frame.open(); use wp.media.editor with wp.media.editor.open( editor_id ) problem: cannot custom UI elements, such as: title, button in js code: https://wordpress.stackexchange.com/questions/75808/using-wordpress-3-5-media-uploader-in-meta-box#75823 use wp.media with rewrite wp.media.controller.Library and retrieve attachment in select problem: complicated ..., but once you understand it, it all make sense, and it is my finial solution in js code: /** * Please attach all the code below to a button click event **///create a new Library, base on defaults//you can put your attributes invar insertImage = wp.media.controller.Library.extend({ defaults : _.defaults({ id: 'insert-image', title: 'Insert Image Url', allowLocalEdits: true, displaySettings: true, displayUserSettings: true, multiple : true, type : 'image'//audio, video, application/pdf, ... etc }, wp.media.controller.Library.prototype.defaults )});//Setup media framevar frame = wp.media({ button : { text : 'Select' }, state : 'insert-image', states : [ new insertImage() ]});//on close, if there is no select files, remove all the files already selected in your main frameframe.on('close',function() { var selection = frame.state('insert-image').get('selection'); if(!selection.length){ #remove file nodes #such as: jq("#my_file_group_field").children('div.image_group_row').remove(); #... }});frame.on( 'select',function() { var state = frame.state('insert-image'); var selection = state.get('selection'); var imageArray = []; if ( ! selection ) return; #remove file nodes #such as: jq("#my_file_group_field").children('div.image_group_row').remove(); #... //to get right side attachment UI info, such as: size and alignments //org code from /wp-includes/js/media-editor.js, arround `line 603 -- send: { ... attachment: function( props, attachment ) { ... ` selection.each(function(attachment) { var display = state.display( attachment ).toJSON(); var obj_attachment = attachment.toJSON() var caption = obj_attachment.caption, options, html; // If captions are disabled, clear the caption. if ( ! wp.media.view.settings.captions ) delete obj_attachment.caption; display = wp.media.string.props( display, obj_attachment ); options = { id: obj_attachment.id, post_content: obj_attachment.description, post_excerpt: caption }; if ( display.linkUrl ) options.url = display.linkUrl; if ( 'image' === obj_attachment.type ) { html = wp.media.string.image( display ); _.each({ align: 'align', size: 'image-size', alt: 'image_alt' }, function( option, prop ) { if ( display[ prop ] ) options[ option ] = display[ prop ]; }); } else if ( 'video' === obj_attachment.type ) { html = wp.media.string.video( display, obj_attachment ); } else if ( 'audio' === obj_attachment.type ) { html = wp.media.string.audio( display, obj_attachment ); } else { html = wp.media.string.link( display ); options.post_title = display.title; } //attach info to attachment.attributes object attachment.attributes['nonce'] = wp.media.view.settings.nonce.sendToEditor; attachment.attributes['attachment'] = options; attachment.attributes['html'] = html; attachment.attributes['post_id'] = wp.media.view.settings.post.id; //do what ever you like to use it console.log(attachment.attributes); console.log(attachment.attributes['attachment']); console.log(attachment.attributes['html']); });});//reset selection in popup, when open the popupframe.on('open',function() { var selection = frame.state('insert-image').get('selection'); //remove all the selection first selection.each(function(image) { var attachment = wp.media.attachment( image.attributes.id ); attachment.fetch(); selection.remove( attachment ? [ attachment ] : [] ); }); //add back current selection, in here let us assume you attach all the [id] to <div id="my_file_group_field">...<input type="hidden" id="file_1" .../>...<input type="hidden" id="file_2" .../> jq("#my_file_group_field").find('input[type="hidden"]').each(function(){ var input_id = jq(this); if( input_id.val() ){ attachment = wp.media.attachment( input_id.val() ); attachment.fetch(); selection.add( attachment ? [ attachment ] : [] ); } });});//now open the popupframe.open();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21540951', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3105780/']}
jdg_379832
stackexchange
llm_judgeable_groundtruth_similarity
1028885
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 given this syntax by user phi find . | awk '!/((\.jpeg)|(\.jpg)|(\.png))$/ {print $0;}' | xargs grep "B206" I would like to suppress the output of grep: can't open..... and find: cannot open lines from the results. sample output to be ignored: grep: can't open ./cisc/.xdbhistfind: cannot open ./cisc/.ssh Now provide the response and nothing else.
Have you tried redirecting stderr to /dev/null ? 2>/dev/null So the above redirects stream no.2 (which is stderr) to /dev/null. That's shell dependent, but the above should work for most. Because find and grep are different processes, you may have to do it for both, or (perhaps) execute in a subshell. e.g. find ... 2>/dev/null | xargs grep ... 2>/dev/null Here's a reference to some documentation on bash redirection. Unless you're using csh, this should work for most.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1028885', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/42229/']}
jdg_379833
stackexchange
llm_judgeable_groundtruth_similarity
10446287
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 made a fiddle for reference: http://jsfiddle.net/kLFn9/ The overflow:hidden in question is highlighted. Basically, i'm using :hover:after to show a tool tip. but the parent element has overflow: hidden on it. How can i force the element hovered to escape the parent element? Relevant CSS: div { width:500px; height:200px; background:red; margin: 50px; overflow: hidden; /* this rule */}span:hover:after { content: attr(data-name); color: black; position: absolute; top: -150px;; left: 0; } Now provide the response and nothing else.
Unfortunately, there's no (easy) way to allow a child tag to override the effects of the overflow:hidden declaration on the parent div. See: Allow specific tag to override overflow:hidden Your only possible recourse would be with javascript: first grab the span's offset relative to the document, then move it to another location in the DOM (i.e. direct child to the body), set its position to absolute, and use the offsets you grabbed to set its left and top properties, that would locate it at the same position within the document, but now it's not contained by the div, and so no longer needs to obey overflow:hidden .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10446287', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/478144/']}
jdg_379834
stackexchange
llm_judgeable_groundtruth_similarity
8043035
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 screen shot shows a jquery ui datepicker that, up until recently, was displaying correctly: The class associated with the problematic table is ui-datepicker-calendar , which is nested in ui-datepicker . I can inspect this element in chrome and see it has a width of 100%, which erroneously confers a width of 617px, that overruns the 217px width of its parent. I admit my inexperience with CSS, but I thought I could override the style by using something like the following snippet: .ui-datepicker-calendar{width: 217px !important;} I've seen this work in other questions on Stack Overflow, but I've been unable to fix this particular bug with like solutions to the above. Any ideas are enthusiastically welcomed. Edit: Code: HTML: <div id="container"> <br /> <!--This div will be dynamically loaded based on the selected tab--> <div id="dataDisplay"> <!-- Section table is loaded here --> </div> <!--This div will be dynamically loaded based on the selected tab--> <div id="mainBody"> <!--Date picker is loaded here --> </div></div> In the CSS: #sectionTable th, td{ border-collapse:collapse; background-color:#EEE; border:2px solid #39F; min-width:80px; width:97%;} The culprit is in the above CSS entry for sectionTable. Defining the width on this table in another div caused the symptoms in the above screen shot as Mystere Man points out. For anyone else that stumbles across this question, check out the following resources for CSS syntax and selectors to get a better hold of your CSS file. http://www.w3.org/TR/CSS2/selector.html http://hacks.mozilla.org/2009/07/slick-tables-with-css-3-selectors/ http://css.maxdesign.com.au/selectutorial/ Now provide the response and nothing else.
Actually you're already defining a struct... Behind the scenes an enum is just a struct (but which derives from System.Enum) and the values of the enum are defined as constants (you can verify this with ILDASM). Your enum definition translates into the following pseudo C# code: public struct Color : System.Enum{ public const int Red = 1; public const int Blue = 1; public const int Green = 1;} The above code won't compile in C# because the compiler doesn't allow defining a struct with an explicit base class, but that's what it emits for an enum definition. Since there is no problem with a type that contains an multiple constants that have the same value, there is no problem with the enum definition. But since the enum does not have unique values you might have an issue when converting into this enum. For example the following two line of codes will return the enum value Red, because the first value is arbitrarily selected. Color color1 = (Color)1;Color color2 = (Color)Enum.Parse(typeof(Color), "1"); Strictly speaking the enum value is not Red, it is 1, but when you print out the value you'll see Red. Also, the following boolean is true which looks a bit weird... // true (Red is Green??)bool b = Color.Red == Color.Green; At the bottom line this is perfectly legal, but it's up to you to use it when it makes sense... Here is a direct link to the section of my .NET tutorial that discusses enumerations under the hood: http://motti.me/c1E
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8043035', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/453020/']}
jdg_379835
stackexchange
llm_judgeable_groundtruth_similarity
71994
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: Given 6 points that are connected with each other with a resistor of resistance $R$, find the resistance between any two points . (Answer: $R/3$) (All the conducting wires have the same resistance $R$.) I know that such a wording immediately implies that these 6 points are absolutely identical, which makes it possible to apply symmetry arguments that will help in reducing the network to a simpler one. That is, after choosing any two points in the network, the remaining four points will still be identical, so we can swap any of them and the network will remain the same. Thus, we can remove the resistors which are connected between these other four points, since the points are identical. However, we can also swap the two chosen points, and the system will still remain the same. So why can't we also remove the resistor between the two chosen points? I'm told of the following analogy: The system of these 6 points is like a system of 6 absolutely similar balls painted, say, in white. By choosing two points, we paint them in black, thus the system loses some symmetry level, but its certain elements are still symmetrical under certain rearrangements. Specifically, any two of the white balls can be swapped without changing the system in any way, so all the white balls are identical and we can ignore any resistors between them.But swapping the two black balls still won't change the system, so why can't we follow the same logic and ignore the resistor between them as well? I'll generalize the question a little bit: why don't we care about other symmetries in the system? (I'm looking forward a simple explanation, without involving advanced math, as I'm just a self-taught beginner and I'm only familiar with calculus. So I try to avoid matrices and anything advanced which students learn in advanced courses of electronics. I just want to get the idea and the concept itself.) Now provide the response and nothing else.
We can't remove the resistor between the two points we've chosen because they're not at the same voltage. OK, let's unpack that a little. Imagine that you actually have a resistor network ( any resistor network) built and want to measure its resistance with an ohmmeter . To do that, you need to choose two of the points in the network and connect the leads of the ohmmeter to them. The ohmmeter will then pass a small DC current through the network, measure the voltage difference $\Delta V$ between its leads and the current $I$ flowing through the network between them, and calculate the resistance $R$ of the network using Ohm's law : $$R = \frac{\Delta V}I$$ Now, since we're feeding a fixed DC current into the network, and since we only have passive resistive components in it, the network will very rapidly (essentially instantaneously) settle into a steady state where each node is at a constant voltage and each resistor has a constant current flowing through it. Specifically, the node to which we've connected the negative lead of the ohmmeter is pulled down to some fixed voltage $V^-$, while the node to which we've connected the positive lead is pulled up to some voltage $V^+ > V^-$. Every other node $i$ of the network will be at some intermediate voltage $V_i$ between $V^-$ and $V^+$. Using your colored balls analogy, it's as if we've chosen two balls, colored one of them white and one black , and colored the rest of the balls with different shades of gray according to their equilibrium voltage, as determined by Ohm's law and Kirchhoff's first law . Indeed, we can mechanically solve for the equilibrium current $I$ through the system simply by writing down the expressions for the current flow through each resistor $ij$ given by Ohm's law: $$I_{ij} = \frac{V_i - V_j}{R_{ij}}$$ and the conservation of current at each node $i$ given by Kirchhoff's first law: $$\sum_j I_{ij} = I^0_i = 0 \text{ for all }i \notin \{a,b\},$$ together with the known voltages $V_a = V^+$ and $V_b = V^-$ and excess currents $I^0_a = -I^0_b = I$ for the endpoint nodes $a$ and $b$, and solving the resulting system of linear equations for $I$. However, if we want to simplify the system before solving it, we can apply two useful observations: First, if two nodes have the same voltage, no current can flow between them: $V_i = V_j$ $\implies$ $I_{ij} = 0$. (Check this using Ohm's law above!) Thus, we can completely ignore any resistors between such nodes. In fact, we can even effectively collapse such nodes together into a single node (as if they were connected by a wire with zero resistance), as long as we remember to account for the fact that we may end up with several resistors in parallel between two nodes. Second, if we have two nodes $i$ and $j$ such that $R_{ik} = R_{jk}$ for all nodes $k$ (where we take $R_{ik} = \infty$ if $i$ and $k$ are not connected) and $I^0_i = I^0_j$, then we can swap the labels of those two nodes without changing any of the parameters of the system. Thus, by symmetry, the solution must have $V_i = V_j$, since otherwise swapping the labels would change the solution without changing the parameters (which is a contradiction if the system is well defined and thus uniquely solvable). In your example network, every node is connected to every other node by identical resistors, and so $R_{ik} = R_{jk}$ for all nodes $i$, $j$, $k$. For all but the two chosen endpoint nodes, we also have $I^0_i = I^0_j = 0$, and so all the other nodes except the endpoints can be exchanged without changing the system. Thus, we may ignore any resistors between them and even collapse them all into a single node. However, the reason we cannot exchange the two chosen endpoints is that we broke the symmetry when we connected the measurement leads to them: those points have current flowing into them from outside the network, which will pull them to different voltages. In particular, the voltage difference will cause a non-zero current to flow across any resistor connecting those two nodes, and so such resistors cannot be ignored when calculating the total current flow across the system. (If there was no externally supplied current, all the nodes in the network would indeed be symmetrical, and we could correctly deduce that no current would flow between any of them. But that scenario is completely useless for calculating the resistance, since we'd just end up with the indeterminate form $R = \Delta V/I = 0/0$.)
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/71994', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/24689/']}
jdg_379836
stackexchange
llm_judgeable_groundtruth_similarity
1117622
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 reading Code Complete where McConnell strongly encourages making all variables private. Coincedentally I just so happened to be working on a project where I needed to change a private variable. The class had a private variable (a String ) telling it where to load an image from to use in the system chrome. I needed to change this image, I do not know about other languages but as far as I know in Flex/AIR, there is no way to override a private variable. If it had been declared protected, I could have simply extended the class, and overridden that variable. But since it was private, I had to copy all the code from the class and create a duplicate class with the only difference being that string. I think the argument is to use private as it makes for looser coupling between super and subclasses, however I had to completely violate DRY to be able to achieve a simple string change, which seems to me as worse. This makes me think that protected is better than private. However, I want to do things the right best-practices way. So if private is better, I want to understand why. If the general consensus is that private is better, can someone explain why? Now provide the response and nothing else.
In this case, the location of that image used to be a private, implementation-specific feature of the base class. Your new requirements meant that it needed to be able to vary from one derived class to another. You should keep the member field private, but define a protected virtual property to expose it to derived classes: private const string _defaultImagePath = @"C:\whatever.bmp";protected virtual string ImagePath { get {return _defaultImagePath;}} In the derived class that wants to change it: private const string _myImagePath = @"C:\other.bmp";protected override string ImagePath { get {return _myImagePath;}} You will also want to change the base class so that it uses the property when it needs the image path, instead of using the field. This is the "Encapsulate Field" refactoring.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1117622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/46011/']}
jdg_379837
stackexchange
llm_judgeable_groundtruth_similarity
11173850
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've created a new .xml file in my layout folder called log.xml . It only contains one TextView . Is it possible to set the text on the textview located in the log.xml from my main activity? Or can it only be set when in an activity which uses the log.xml as view? Hope you get what i mean here, otherwise ill elaborate. Thanks Now provide the response and nothing else.
If you don't set the xml you are talking about on "setContentView()" you can always get it with layout inflater. You'll have to add the tv to the current layout using addView() though. LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);View vi = inflater.inflate(R.layout.log, null); //log.xml is your file.TextView tv = (TextView)vi.findViewById(R.id.tv); //get a reference to the textview on the log.xml file.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11173850', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/598511/']}
jdg_379838
stackexchange
llm_judgeable_groundtruth_similarity
40231813
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 on project that needs to use an httpOnly cookie. The project requires a direct call to the API. Let's say it's xxx.com/vx/auth/login that authenticates user login attempt. That endpoint will give response and also set-cookie to the client. Something like this: Set-Cookie:token=eyJ0b2tlbiI6ImV5SmhiR2NpT2lKSVV6STFOaUlzSW5SNWNDSTZJa3BYVkNKOS5leUoxYVdRaU9pSXhNREEwT0RJd05DSXNJbDlwWkNaNkluWXhYM1Z6WlhKekx6RXdNRFE0TWpBMElpd2libUZ0WlNJNklrRm5kVzVuSUZOMWNubGhJRUpoYm1kellTSXNJbVZ0WVdsc0lqb2ljR0ZwYm1GdVpHVnpkR2x1WldSQWVXRm9iMjh1WTI5ddlpd2liR1YyWld3aU9qQXNJbWxoZENJNk1UUTNOek0zTVRnMk55d2laWGh3SWpveE5EYzNOVFEwTmpZc2ZRLmtUN0IzNW9YYjQ2RmU3WWFLYkd4MXhoYkdGUWJ1TFg1U053N3FWSjNfa2siffQ==; expires=Thu, 27 Oct 2016 05:04:27 GMT; path=/; HttpOnly But when I look at the devtools , the cookie is not set. Even after I refresh several times. What do I miss here? Do I need to create a proxy to handle this? * I used to use proxy and it works well Now provide the response and nothing else.
I finally managed to solve this problem by coordinating with the backend engineer guy: Remove wildcard from Access-Control-Allow-Origin and use specific domain origin instead. If not, Set Access-Control-Allow-Credentials: true And in the request, I set withCredentials to true . NOTE: If you set withCredentials to true , you have to set Access-Control-Allow-Credentials to true also. Plus, this won't work if you still use wildcard in your Access-Control-Allow-Origin . Further reading about "Request With Credentials"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40231813', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3200803/']}
jdg_379839
stackexchange
llm_judgeable_groundtruth_similarity
2036956
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 get_browser() function in an attempt to warn people that their browser doesn't support Javascript. Actually I'm using it to tell them they can use certain parts of a web application I'm building. I've decided to properly use Javascript because I'm tired of listening to developers that are scared of using it and I've seen some great potential in the language. I digress, here is the error. browscap ini directive not set Now I'd imagine this means I need somthing set it the php.ini. Can someone give me some direction on this one? Now provide the response and nothing else.
I don't think this is the "best" solution to detect is a browser supports what you need for your website : first of all, browsers can lie -- they can send whatever thay want as User-Agent And even if a given version of a support should support what you need, Javascript can still be disabled. second, there are more "proper" way to detect what a browser can do or not, when it comes to Javascript. For the second point, you should test if the browser actually supports what you need -- and not rely on a list such as the browscap one. Still, to answer your question about browscap : there is a note at the bottom of the manual page for get_browser that says (quoting) : Note: In order for this to work, your browscap configuration setting in php.ini must point to the correct location of the browscap.ini file on your system. browscap.ini is not bundled with PHP, but you may find an up-to-date » php_browscap.ini file here. While browscap.ini contains information on many browsers, it relies on user updates to keep the database current. The format of the file is fairly self-explanatory. So, you have to : download the browscap file, and set the browscap directive in your php.ini file, so it points to the file you downloaded.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2036956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/243568/']}
jdg_379840