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 | 40242977 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have some cases where I have to call method names from class names. string scenario1 = "MockScenario1";string scenario2 = "MockScenario2";MockScenario1.GetInfo();MockScenario2.GetInfo(); How can I dynamically use the strings to call method name here like scenario1.GetInfo()scenario2.GetInfo() I tried to find out all options by string and control space to find related options. Any suggestions? I am tried the below and trying to Get class name generated dynamically The below code generated method name dynamically string methodName = "hello";//Get the method information using the method info class MethodInfo mi = this.GetType().GetMethod(methodName);//Invoke the method// (null- no parameter for the method call// or you can pass the array of parameters...)mi.Invoke(this, null); More clear scenario:I am trying to send class name as parameterMockScenario1 and MockScenario2 are class names. string scenarioCats = "MockScenario1";string scenarioDogs = "MockScenario2";GetResult(scenarioCats);GetResult(scenarioDogs);public static void GetCatsResult(string scenarioCats){scenarioCats obj = new scenarioCats(); obj.GetInfo(); }public static void GetDogsResult(string scenarioDogs){scenarioDogs obj = new scenarioDogs(); obj.GetInfo(); }
Now provide the response and nothing else.
| How to create an instance of a type from its string representation: string scenario1 = "TheNamespace.MockScenario1";Type theType = this.GetType().Assembly.GetType(scenario1);var theInstance = (MockScenario1)Activator.CreateInstance(theType);theInstance.GetInfo(); It will be better if your classes implement a common interface, for example IGetInfoAware , and then you could write a more generic loader: var theInstance = (IGetInfoAware)Activator.CreateInstance(theType); Note: you need to provide the full class name for scenario1 and scenario2 See Activator.CreateInstance EDIT: As @Georg pointed out, if the type is not declared in the assembly of the context objects, then it is necessary first to get the assembly where the type is hosted: var theAssembly = ( from Assembly assembly in AppDomain.CurrentDomain.GetAssemblies() where (assembly.FullName == "TheNamespace.AssemblyName") select assembly).FirstOrDefault();if ( theAssembly!= null ){ Type theType = theAssembly.GetType(scenario1); var theInstance = (IGetInfoAware)Activator.CreateInstance(theType); theInstance.GetInfo();} If for some reason the assembly name is unknown to you, then the type could be resolved like the following: public Type GetTypeFromString(String typeName){ foreach (Assembly theAssembly in AppDomain.CurrentDomain.GetAssemblies()) { Type theType = theAssembly.GetType(typeName); if (theType != null) { return theType; } } return null;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40242977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1041205/']} | jdg_82941 |
stackexchange | llm_judgeable_groundtruth_similarity | 3293493 |
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 Jersey and JAXB to build a simple RESTful webserviceI have a HashMap of 'String' to 'Integer': 2010-04 -> 24 2010-05 -> 45 I need to generate an XML response which looks like this: <map> <2010-04>24</2010-04> <2010-05>45</2010-05> </map> What is the best way to generate dynamic tag names with JAXB?
Now provide the response and nothing else.
| You can use an @XmlAnyElement -annotated property and return the elements as JAXBElement s: private Map<String, Integer> months = ...;@XmlAnyElementpublic List<JAXBElement<Integer>> getMonths() { List<JAXBElement<Integer>> elements = new ArrayList<JAXBElement<Integer>>(); for (Map.Entry<String, Integer> month: months.entrySet()) elements.add(new JAXBElement(new QName(month.getKey()), Integer.class, month.getValue())); return elements;} This approach is ugly, but not uglier than the XML it produces. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3293493', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/175086/']} | jdg_82942 |
stackexchange | llm_judgeable_groundtruth_similarity | 7814027 |
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 writing a system tray app that needs to check if an internal web based app is open. I can check IE using the following: SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows(); string filename; bool sdOpen = false; foreach (SHDocVw.InternetExplorer ie in shellWindows) { filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower(); if (filename.Equals("iexplore")) { string[] urlParts = (ie.LocationURL.ToString()).Split('/'); string website = urlParts[2]; if (website == "myApp:8080") { sdOpen = true; }; } } if (sdOpen) { Console.WriteLine("App is open"); } else { Console.WriteLine("App is not open"); }; Console.ReadKey(true); However, some of the users using the system prefer Chrome or Firefox. How can I do the same as above (i.e. get the urls of any open tabs in the browser) for Chrome and Firefox? (I'm not going to bother with other browsers as these are the only ones in use in our organisation.)
Now provide the response and nothing else.
| It's specific for every browser. That's for the major ones: Internet Explorer - You can use SHDocVw (like you did) Firefox - You can get the URL using DDE (source below) Chrome - You can get the URL while enumerating all the child windows untill you get to the control with class "Chrome_OmniboxView" and then get the text using GetWindowText Opera - You can use the same thing as Firefox, but with "opera" Safari - There is no known method since it uses custom drawn controls EDIT: Since 2014, Chrome has changed and you need to get the URL with Acessibility. Code to get the URL from Firefox/Opera using DDE (which used NDDE - the only good DDE wrapper for .NET): //// usage: GetBrowserURL("opera") or GetBrowserURL("firefox")//private string GetBrowserURL(string browser) { try { DdeClient dde = new DdeClient(browser, "WWW_GetWindowInfo"); dde.Connect(); string url = dde.Request("URL", int.MaxValue); string[] text = url.Split(new string[] { "\",\"" }, StringSplitOptions.RemoveEmptyEntries); dde.Disconnect(); return text[0].Substring(1); } catch { return null; }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7814027', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/375655/']} | jdg_82943 |
stackexchange | llm_judgeable_groundtruth_similarity | 2400097 |
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 read StartingMonthColumn and CategoryHeadingColumnfrom the below app.config file using the code ConfigurationSettings.AppSettings["StartingMonthColumn"] but it is returning null, also ConfigurationSettings.AppSettings.Count returns zero Please help me to read this in my windows application <configuration> <configSections> <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" > <section name="CTARepository.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" /> </sectionGroup> </configSections> <userSettings> <CTARepository.Properties.Settings> <setting name="Setting" serializeAs="String"> <value /> </setting> </CTARepository.Properties.Settings> </userSettings> <appSettings> <add key="StartingMonthColumn" value="7"/> <add key="CategoryHeadingColumn" value="1"/> </appSettings></configuration>
Now provide the response and nothing else.
| Configuration Settings .AppSettings is obsolete , you should use Configuration Manager .AppSettings instead (you will need to add a reference to System.Configuration ) int value = Int32.Parse(ConfigurationManager.AppSettings["StartingMonthColumn"]); If you still have problems reading in your app settings then check that your app.config file is named correctly. Specifically, it should be named according to the executing assembly i.e. MyApp.exe.config , and should reside in the same directory as MyApp.exe . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2400097', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/260681/']} | jdg_82944 |
stackexchange | llm_judgeable_groundtruth_similarity | 6416385 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Recently, many questions pop up on how to provide your own swap function. With C++11, std::swap will use std::move and move semantics to swap the given values as fast as possible. This, of course, only works if you provide a move constructor and a move assignment operator (or one that uses pass-by-value). Now, with that given, is it actually necessary to write your own swap functions in C++11? I could only think of non-movable types, but then again, the custom swap s usually work through some kind of "pointer exchange" (aka moving). Maybe with certain reference variables? Hm...
Now provide the response and nothing else.
| It is a matter of judgment. I will typically let std::swap do the job for prototyping code, but for release code write a custom swap. I can usually write a custom swap that is about twice as fast as 1 move construction + 2 move assignments + 1 resourceless destruction. However one may want to wait until std::swap actually proves to be a performance problem before going to the bother. Update for Alf P. Steinbach: 20.2.2 [utility.swap] specifies that std::swap(T&, T&) has a noexcept equivalent to: template <class T>voidswap(T& a, T& b) noexcept ( is_nothrow_move_constructible<T>::value && is_nothrow_move_assignable<T>::value ); I.e. if move operations on T are noexcept , then std::swap on T is noexcept . Note that this spec doesn't require move members. It only requires that construction and assignment from rvalues exists, and if it is noexcept , then swap will be noexcept . E.g.: class A{public: A(const A&) noexcept; A& operator=(const A&) noexcept;}; std::swap<A> is noexcept, even without move members. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6416385', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/500104/']} | jdg_82945 |
stackexchange | llm_judgeable_groundtruth_similarity | 34727936 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to access typed object with bracket notation like this: interface IFoo { bar: string[];}var obj: IFoo = { bar: ["a", "b"] }var name = "bar";obj[name]. // type info lost after dot According to the spec 4.10 as far as I understood it, it is an expected behavior: A bracket notation property access of the form ObjExpr [ IndexExpr ] .... Otherwise, if IndexExpr is of type Any, the String or Number primitive type, or an enum type, the property access is of type Any. Can anyone confirm if that is true and if it is possible to circumvent this behavior. Edit: My use case is with object minification as in var props = {long_name: "n"}; var shortName = props.long_name;function(minObj) { var value = minObj[shortName] var newMinObj = {}; newMinObj[shortName] = value.toUpperCase(); db.save(newMinObj)}
Now provide the response and nothing else.
| Instead of using a variable in obj[x] , you can write : obj["bar"].sort The only reason to use a variable here is to choose an arbitrary property from your IFoo interface. You seem to only have one. If you had many string arrays on your IFoo , you could make it indexable and write: interface IFoo { bar: string[]; bar2: string[]; [key: string]: string[]; // IFoo is indexable; not a new property} Which would allow you to write: var name = "bar";obj[name].sort; But it would also allow you to write: obj["some new property"] = ["a", "b"];obj["some new property"].sort; | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34727936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1504867/']} | jdg_82946 |
stackexchange | llm_judgeable_groundtruth_similarity | 32101 |
Below is a question asked on the forum linguistics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In many languages we usually say "between min and max" (e.g., grades "between 1 and 10"). Are there any languages where the reverse construction ("between max and min", e.g. grades "between 10 and 1") is used?
Now provide the response and nothing else.
| In German, I am aware of two instances where the "reverse" order is used: 1) The weather forecast of the newscast "Tagesschau" (and quite possibly many other weather forecasts, but not all) always states the range of lowest expected temperatures with the higest number first. From today's 8pm broadcast : In der Nacht 19 bis 12 Grad; am Tag 18 Grad im südwestlichen Bergland, 27 in der Niederlausitz. Translation: At night, 19 to 12 degrees [celsius]; during the day, 18 degrees in the southwestern uplands, 27 degrees in Lower Lusatia. I is used very consistently. Here are the archived broadcasts of the last few days.: https://youtu.be/kADSW8lqb60?t=882 https://youtu.be/4kRKGXeYigg?t=972 https://youtu.be/t8JOLMGEMSw?t=903 https://youtu.be/yBssC2K_LmY?t=886 https://youtu.be/6oZLJJC2hts?t=952 If you understand a little bit of German, you can listen out for the numbers and for the word "Grad" (degrees). Usage of this ordering goes back a long way. See for example this 1983 recording : Tiefsttemperaturen 5 bis 1, Tageshöchsttemperaturen 7[!] bis 12 Grad yes, he says 7, even though the thermometer graphic displays 9 However, these even older recordings use "standard ordering": December 30, 1973 Im Norden Tiefsttemperaturen 1 bis 5 Grad, Tageshöchsttemperaturen 4 bis 7 [cut off] July 30, 1979 Tiefsttemperaturen in der Nacht 11 bis 15 Grad, Tageshöchsttemperaturen 20 bis 25 Grad, nur im Norden etwas weniger. 2) Some cities (particularly those with inconsistent numbering schemes ) add house number range information to all or some of their street name signs. The house number that is closest to the location of the sign is stated first, followed by the last house number before the next (major) intersection, which often results in the larger number coming first. This Berlin-style sign shows for example "56 – 48". | {} | {'log_upvote_score': 5, 'links': ['https://linguistics.stackexchange.com/questions/32101', 'https://linguistics.stackexchange.com', 'https://linguistics.stackexchange.com/users/25187/']} | jdg_82947 |
stackexchange | llm_judgeable_groundtruth_similarity | 29841701 |
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 creating a website using Laravel 5. I'm using queues with beanstalkd with 2 tubes. I have 10 workers monitored by daemontools. 5 workers process tube A and B. The other 5 workers only process tube B. Things work great most of the time, but occasionally tube B seems to lock up. The logs show that the workers are throwing an exception. [2015-04-24 07:09:36] local.ERROR: exception 'Pheanstalk\Exception\ServerException' with message 'Cannot delete job 273812: NOT_FOUND' in /x/website/vendor/pda/pheanstalk/src/Command/DeleteCommand.php:44Stack trace:#0 /x/website/vendor/pda/pheanstalk/src/Connection.php(121): Pheanstalk\Command\DeleteCommand->parseResponse('NOT_FOUND', NULL)#1 /x/website/vendor/pda/pheanstalk/src/Pheanstalk.php(384): Pheanstalk\Connection->dispatchCommand(Object(Pheanstalk\Command\DeleteCommand))#2 /x/website/vendor/pda/pheanstalk/src/Pheanstalk.php(67): Pheanstalk\Pheanstalk->_dispatch(Object(Pheanstalk\Command\DeleteCommand))#3 /x/website/vendor/laravel/framework/src/Illuminate/Queue/Jobs/BeanstalkdJob.php(73): Pheanstalk\Pheanstalk->delete(Object(Pheanstalk\Job))#4 /x/website/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(46): Illuminate\Queue\Jobs\BeanstalkdJob->delete()#5 /x/website/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(126): Illuminate\Queue\CallQueuedHandler->call(Object(Illuminate\Queue\Jobs\BeanstalkdJob), Array)#6 /x/website/vendor/laravel/framework/src/Illuminate/Queue/Jobs/BeanstalkdJob.php(51): Illuminate\Queue\Jobs\Job->resolveAndFire(Array)#7 /x/website/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(207): Illuminate\Queue\Jobs\BeanstalkdJob->fire()#8 /x/website/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(159): Illuminate\Queue\Worker->process('beanstalkd', Object(Illuminate\Queue\Jobs\BeanstalkdJob), '20', '120')#9 /x/website/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(113): Illuminate\Queue\Worker->pop(NULL, NULL, '120', 3, '20')#10 /x/website/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(85): Illuminate\Queue\Worker->runNextJobForDaemon(NULL, NULL, '120', 3, '20')#11 /x/website/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(101): Illuminate\Queue\Worker->daemon(NULL, NULL, '120', 128, 3, '20')#12 /x/website/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(67): Illuminate\Queue\Console\WorkCommand->runWorker(NULL, NULL, '120', 128, true)#13 [internal function]: Illuminate\Queue\Console\WorkCommand->fire()#14 /x/website/vendor/laravel/framework/src/Illuminate/Container/Container.php(523): call_user_func_array(Array, Array)#15 /x/website/vendor/laravel/framework/src/Illuminate/Console/Command.php(115): Illuminate\Container\Container->call(Array)#16 /x/website/vendor/symfony/console/Symfony/Component/Console/Command/Command.php(257): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))#17 /x/website/vendor/laravel/framework/src/Illuminate/Console/Command.php(101): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))#18 /x/website/vendor/symfony/console/Symfony/Component/Console/Application.php(874): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))#19 /x/website/vendor/symfony/console/Symfony/Component/Console/Application.php(195): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Queue\Console\WorkCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))#20 /x/website/vendor/symfony/console/Symfony/Component/Console/Application.php(126): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))#21 /x/website/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(94): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))#22 /x/website/artisan(36): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))#23 {main} I'm wondering if the problem might be caused by several workers going for the same job. Is that possible or is there some sort of mutex to control this? What else might cause this?
Now provide the response and nothing else.
| The queued command was taking too long and the problem was caused by the TTR value on the tube in beanstalkd, but it's not necessary to change that value. In a nutshell, beanstalkd will keep the job reserved only for a maximum period of time (up to the TTR) and then it will assume that something has gone wrong and return the job back to the ready state. Instead, it's possible to periodically touch the job to reset the reservation timer. In Laravel, I've added this to my App\Commands\Command class and I periodically call it inside of loops on long running jobs. public function touch(){ if (method_exists($this->job, 'getPheanstalk')) { $this->job->getPheanstalk()->touch($this->job->getPheanstalkJob()); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29841701', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/756439/']} | jdg_82948 |
stackexchange | llm_judgeable_groundtruth_similarity | 3146702 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the difference between class and instance methods in Objective-C and when should I use each of them?
Now provide the response and nothing else.
| Using the tired old Car analogy... Think of a Class like it is a factory that makes Instances of the class. For example, you might have a Car class and you might declare a method like: + carWithColor: (NSColor *) aColor; And that method would then create a new Car instance, set the color, and return it: + carWithColor: (NSColor *) aColor { Car *aCar = [[[self alloc] init] autorelease]; [aCar paintWithColor: aColor]; return aCar; } Now, that Car class would then declare an instance method that allows the car to be painted. Why an instance method? Because every car can have a different color (and the color of the car would likely be stored in an instance variable). - (void) paintWithColor: (NSColor *) aColor{ ... do your paint stuff here ...} This is explained in the Objects, Classes, and Messaging section of the Objective-C documentation. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3146702', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/251304/']} | jdg_82949 |
stackexchange | llm_judgeable_groundtruth_similarity | 21909417 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
First of all, this may look like a duplicate of: postgres hstore exists and doesn't exist at same time but it is not. While I am getting the same error message in the circumstance. When checking to see if hstore is installed on the DB, we can see that it is: ./psql -d photographerio_development -c '\dx' List of installed extensions Name | Version | Schema | Description ---------+---------+------------+-------------------------------------------------- hstore | 1.2 | hstore | data type for storing sets of (key, value) pairs plpgsql | 1.0 | pg_catalog | PL/pgSQL procedural language and it is too on the template_1 DB. So, when I try to run the migration to add the hstore, I get the PG::Error: ERROR: extension "hstore" already exists and when I comment out this migration, on the next one, which requires the hstore, it says PG::UndefinedObject: ERROR: type "hstore" does not exist which is a bit of a paradox. It is a Rails 4.0.1 app with postgresql 9 and I have hstore working on a few other projects running on this machine.
Now provide the response and nothing else.
| You have installed the hstore extension in a schema named hstore which is presumably not on your default search_path . You must do one of these: Add hstore to search_path during connection setup; Add hstore to search_path with an ALTER USER ... SET or ALTER DATABASE ... SET ; Move the hstore extension from the hstore schema into public ; or schema-qualify all references to hstore , e.g. hstore.hstore(...) . This must be done for operators too; -> becomes OPERATOR(hstore.->) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21909417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/358524/']} | jdg_82950 |
stackexchange | llm_judgeable_groundtruth_similarity | 19452971 |
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 standard array-size macro that is often taught is #define ARRAYSIZE(arr) (sizeof(arr) / sizeof(arr[0])) or some equivalent formation. However, this kind of thing silently succeeds when a pointer is passed in, and gives results that can seem plausible at runtime until things mysteriously fall apart. It's all-too-easy to make this mistake: a function that has a local array variable is refactored, moving a bit of array manipulation into a new function called with the array as a parameter. So, the question is: is there a "sanitary" macro to detect misuse of the ARRAYSIZE macro in C, preferably at compile-time? In C++ we'd just use a template specialized for array arguments only; in C, it seems we'll need some way to distinguish arrays and pointers. (If I wanted to reject arrays, for instance, I'd just do e.g. (arr=arr, ...) because array assignment is illegal).
Now provide the response and nothing else.
| Linux kernel uses a nice implementation of ARRAY_SIZE to deal with this issue: #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr)) with #define __must_be_array(a) BUILD_BUG_ON_ZERO(__same_type((a), &(a)[0])) and #define __same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b)) Of course this is portable only in GNU C as it makes use of two instrinsics: typeof operator and __builtin_types_compatible_p function. Also it uses their "famous" BUILD_BUG_ON_ZERO macro which is only valid in GNU C. Assuming a compile time evaluation requirement (which is what we want), I don't know any portable implementation of this macro. A "semi-portable" implementation (and which would not cover all cases) is: #define ARRAY_SIZE(arr) \ (sizeof(arr) / sizeof((arr)[0]) + STATIC_EXP(IS_ARRAY(arr))) with #define IS_ARRAY(arr) ((void*)&(arr) == &(arr)[0])#define STATIC_EXP(e) \ (0 * sizeof (struct { int ARRAY_SIZE_FAILED:(2 * (e) - 1);})) With gcc this gives no warning if argument is an array in -std=c99 -Wall but -pedantic would gives a warning. The reason is IS_ARRAY expression is not an integer constant expression (cast to pointer types and subscript operator are not allowed in integer constant expressions) and the bit-field width in STATIC_EXP requires an integer constant expression. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19452971', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1204143/']} | jdg_82951 |
stackexchange | llm_judgeable_groundtruth_similarity | 52162091 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have 2 strings string a = "foo bar";string b = "bar foo"; and I want to detect the changes from a to b . What characters do I have to change, to get from a to b ? I think there must be a iteration over each character and detect if it was added, removed or remained equal. So this is my exprected result 'f' Remove'o' Remove'o' Remove' ' Remove'b' Equal'a' Equal'r' Equal' ' Add'f' Add'o' Add'o' Add class and enum for the result: public enum Operation { Add,Equal,Remove };public class Difference{ public Operation op { get; set; } public char c { get; set; }} Here is my solution but the "Remove" case is not clear to me how the code has to look like public static List<Difference> CalculateDifferences(string left, string right){ int count = 0; List<Difference> result = new List<Difference>(); foreach (char ch in left) { int index = right.IndexOf(ch, count); if (index == count) { count++; result.Add(new Difference() { c = ch, op = Operation.Equal }); } else if (index > count) { string add = right.Substring(count, index - count); result.AddRange(add.Select(x => new Difference() { c = x, op = Operation.Add })); count += add.Length; } else { //Remove? } } return result;} How does the code have to look like for removed characters? Update - added a few more examples example 1: string a = "foobar";string b = "fooar"; expected result: 'f' Equal'o' Equal'o' Equal'b' Remove'a' Equal'r' Equal example 2: string a = "asdfghjk";string b = "wsedrftr"; expected result: 'a' Remove'w' Add's' Equal'e' Add'd' Equal'r' Add'f' Equal'g' Remove'h' Remove'j' Remove'k' Remove't' Add'r' Add Update: Here is a comparison between Dmitry's and ingen's answer: https://dotnetfiddle.net/MJQDAO
Now provide the response and nothing else.
| You are looking for (minimum) edit distance / (minimum) edit sequence . You can find the theory of the process here: https://web.stanford.edu/class/cs124/lec/med.pdf Let's implement (simplest) Levenstein Distance / Sequence algorithm (for details see https://en.wikipedia.org/wiki/Levenshtein_distance ). Let's start from helper classes (I've changed a bit your implementation of them): public enum EditOperationKind : byte { None, // Nothing to do Add, // Add new character Edit, // Edit character into character (including char into itself) Remove, // Delete existing character }; public struct EditOperation { public EditOperation(char valueFrom, char valueTo, EditOperationKind operation) { ValueFrom = valueFrom; ValueTo = valueTo; Operation = valueFrom == valueTo ? EditOperationKind.None : operation; } public char ValueFrom { get; } public char ValueTo {get ;} public EditOperationKind Operation { get; } public override string ToString() { switch (Operation) { case EditOperationKind.None: return $"'{ValueTo}' Equal"; case EditOperationKind.Add: return $"'{ValueTo}' Add"; case EditOperationKind.Remove: return $"'{ValueFrom}' Remove"; case EditOperationKind.Edit: return $"'{ValueFrom}' to '{ValueTo}' Edit"; default: return "???"; } } } As far as I can see from the examples provided we don't have any edit operation, but add + remove ; that's why I've put editCost = 2 when insertCost = 1 , int removeCost = 1 (in case of tie : insert + remove vs. edit we put insert + remove ).Now we are ready to implement Levenstein algorithm: public static EditOperation[] EditSequence( string source, string target, int insertCost = 1, int removeCost = 1, int editCost = 2) { if (null == source) throw new ArgumentNullException("source"); else if (null == target) throw new ArgumentNullException("target"); // Forward: building score matrix // Best operation (among insert, update, delete) to perform EditOperationKind[][] M = Enumerable .Range(0, source.Length + 1) .Select(line => new EditOperationKind[target.Length + 1]) .ToArray(); // Minimum cost so far int[][] D = Enumerable .Range(0, source.Length + 1) .Select(line => new int[target.Length + 1]) .ToArray(); // Edge: all removes for (int i = 1; i <= source.Length; ++i) { M[i][0] = EditOperationKind.Remove; D[i][0] = removeCost * i; } // Edge: all inserts for (int i = 1; i <= target.Length; ++i) { M[0][i] = EditOperationKind.Add; D[0][i] = insertCost * i; } // Having fit N - 1, K - 1 characters let's fit N, K for (int i = 1; i <= source.Length; ++i) for (int j = 1; j <= target.Length; ++j) { // here we choose the operation with the least cost int insert = D[i][j - 1] + insertCost; int delete = D[i - 1][j] + removeCost; int edit = D[i - 1][j - 1] + (source[i - 1] == target[j - 1] ? 0 : editCost); int min = Math.Min(Math.Min(insert, delete), edit); if (min == insert) M[i][j] = EditOperationKind.Add; else if (min == delete) M[i][j] = EditOperationKind.Remove; else if (min == edit) M[i][j] = EditOperationKind.Edit; D[i][j] = min; } // Backward: knowing scores (D) and actions (M) let's building edit sequence List<EditOperation> result = new List<EditOperation>(source.Length + target.Length); for (int x = target.Length, y = source.Length; (x > 0) || (y > 0);) { EditOperationKind op = M[y][x]; if (op == EditOperationKind.Add) { x -= 1; result.Add(new EditOperation('\0', target[x], op)); } else if (op == EditOperationKind.Remove) { y -= 1; result.Add(new EditOperation(source[y], '\0', op)); } else if (op == EditOperationKind.Edit) { x -= 1; y -= 1; result.Add(new EditOperation(source[y], target[x], op)); } else // Start of the matching (EditOperationKind.None) break; } result.Reverse(); return result.ToArray();} Demo: var sequence = EditSequence("asdfghjk", "wsedrftr"); Console.Write(string.Join(Environment.NewLine, sequence)); Outcome: 'a' Remove'w' Add's' Equal'e' Add'd' Equal'r' Add'f' Equal'g' Remove'h' Remove'j' Remove'k' Remove't' Add'r' Add | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52162091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6315290/']} | jdg_82952 |
stackexchange | llm_judgeable_groundtruth_similarity | 334199 |
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 there a straightforward way to find the VNC screen (i.e. port number minus 5900) onto which a KVM guest is bound? My guests are all configured to run with VNC enabled, but the order in which they occupy the ports is random. Alternately, is there a way to assign them in the configuration (of guest or host), so that each respective guest will occupy a predefined port?!
Now provide the response and nothing else.
| Since you're using libvirt , you can just ask it! root@onhost1:~# virsh list Id Name State---------------------------------- 1 one-34 running 2 one-36 running 3 one-38 runningroot@onhost1:~# virsh vncdisplay one-34:34root@onhost1:~# virsh vncdisplay 1:34 (my particular correlation of name to VNC display port is due to the use of Open Nebula) EDIT: Nowadays, you can use domdisplay to get the URI of the display whether it's VNC or Spice: ○ → virsh domdisplay win-michaelvnc://127.0.0.1:0○ → for dom in $(virsh list --name); do echo -n "$dom: "; virsh domdisplay $dom; donewin-michael-m: vnc://127.0.0.1:0 Here's a one-liner to execute this for all running guests at once: for i in $(virsh -q list|awk '{print $2}'|sort); do echo -e "\033[01;31m$i\033[00m -> $(virsh vncdisplay $i)"done Also made it into a function that sorts output by port number: function vnc-list{ for i in $(virsh -q list|awk '{print $2}'|sort); do PORTNUM=$(virsh vncdisplay $i|cut -f 2 -d ':') printf "% 2d: \033[01;32m%.20s\033[00m\n" "$PORTNUM" "$i"; done | sort -n} | {} | {'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/334199', 'https://serverfault.com', 'https://serverfault.com/users/71790/']} | jdg_82953 |
stackexchange | llm_judgeable_groundtruth_similarity | 2120779 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
With PHP, how can I isolate the contents of the src attribute from $foo? The end result I'm looking for would give me just " http://example.com/img/image.jpg " $foo = '<img class="foo bar test" title="test image" src="http://example.com/img/image.jpg" alt="test image" width="100" height="100" />';
Now provide the response and nothing else.
| If you don't wish to use regex (or any non-standard PHP components), a reasonable solution using the built-in DOMDocument class would be as follows: <?php $doc = new DOMDocument(); $doc->loadHTML('<img src="http://example.com/img/image.jpg" ... />'); $imageTags = $doc->getElementsByTagName('img'); foreach($imageTags as $tag) { echo $tag->getAttribute('src'); }?> | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2120779', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/156180/']} | jdg_82954 |
stackexchange | llm_judgeable_groundtruth_similarity | 3925947 |
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 wonder how Java is more portable than C, C++ and .NET and any other language. I have read many times about java being portable due to the interpreter and JVM, but the JVM just hides the architectural differences in the hardware, right? We'd still need different JVMs for different machine architectures. What am I missing here? So if someone writes an abstraction layer for C for the most common architectures, let's say the CVM, then any C program will run on those architectures once CVM is installed, isn't it? What exactly is this portability? Can .NET be called portable?
Now provide the response and nothing else.
| Portability isn't a black and white, yes or no kind of thing. Portability is how easily one can I take a program and run it on all of the platforms one cares about. There are a few things that affect this. One is the language itself. The Java language spec generally leaves much less up to "the implementation". For example, "i = i++" is undefined in C and C++, but has a defined meaning in Java. More practically speaking, types like "int" have a specific size in Java (eg: int is always 32-bits), while in C and C++ the size varies depending on platform and compiler. These differences alone don't prevent you from writing portable code in C and C++, but you need to be a lot more diligent. Another is the libraries. Java has a bunch of standard libraries that C and C++ don't have. For example, threading, networking and GUI libraries. Libraries of these sorts exist for C and C++, but they aren't part of the standard and the corresponding libraries available can vary widely from platform to platform. Finally, there's the whole question of whether you can just take an executable and drop it on the other platform and have it work there. This generally works with Java, assuming there's a JVM for the target platform. (and there are JVMs for many/most platforms people care about) This is generally not true with C and C++. You're typically going to at least need a recompile, and that's assuming you've already taken care of the previous two points. Yes, if a "CVM " existed for multiple platforms, that would make C and C++ more portable -- sort of. You'd still need to write your C code either in a portable way (eg: assuming nothing about the size of an int other than what the standard says) or you'd write to the CVM (assuming it has made a uniform decision for all of these sorts of things across all target platforms). You'd also need to forgo the use of non-standard libraries (no networking, threading or GUI) or write to the CVM-specific libraries for those purposes. So then we're not really talking about making C and C++ more portable, but a special CVM-C/C++ that's portable. Once again, portability isn't a black and white thing. Even with Java there can still be incompatibilities. The GUI libraries (especially AWT) were kind of notorious for having inconsistent behavior, and anything involving threads can behave differently if you get sloppy. In general, however, it's a lot easier to take a non-trivial Java program written on one platform and run it on another than it is to do the same with a program written in C or C++. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3925947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/373151/']} | jdg_82955 |
stackexchange | llm_judgeable_groundtruth_similarity | 2479784 |
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 DLL which contains a class with static members . I use __declspec(dllexport) in order to make use of this class's methods . But when I link it to another project and try to compile it, I get "unresolved external symbol" errors for the static data. e.g.In DLL, Test.h class __declspec(dllexport) Test{protected: static int d;public: static void m(){int x = a;}} In DLL, Test.cpp #include "Test.h"int Test::d; In the application which uses Test, I call m(). I also tried using __declspec(dllexport) for each method separately but I still get the same link errors for the static members. If I check the DLL (the .lib) using dumpbin, I could see that the symbols have been exported. For instance, the app gives the following error at link time: 1>Main.obj : error LNK2001: unresolved external symbol "protected: static int CalcEngine::i_MatrixRow" (?i_MatrixRow@CalcEngine@@1HA) But the dumpbin of the .lib contains: Version : 0 Machine : 14C (x86) TimeDateStamp: 4BA3611A Fri Mar 19 17:03:46 2010 SizeOfData : 0000002C DLL name : CalcEngine.dll Symbol name : ?i_MatrixRow@CalcEngine@@1HA (protected: static int CalcEngine::i_MatrixRow) Type : data Name type : name Hint : 31 Name : ?i_MatrixRow@CalcEngine@@1HA I can't figure out how to solve this. What am I doing wrong? How can I get over these errors? P.S. The code was originally developed for Linux and the .so/binary combination works without a problem EDIT: In the given case, the static variables are not directly referred by the application but the method is inlined since it's in the header. I was able to resolve the link errors by moving the methods to the .cpp file.
Now provide the response and nothing else.
| In this thread at cprogramming.com it is suggested that a static variable is local to the dll and not exported. Summary of discussion below The static member is not accessed directly by code in the calling application, only through member functions of the class in the dll. However there are several inline functions accessing the static member. Those functions will be inline expanded into the calling applications code makeing the calling application access the static member directly. That will violate the finding referenced above that static variables are local to the dll and cannot be referenced from the calling application. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2479784', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/86059/']} | jdg_82956 |
stackexchange | llm_judgeable_groundtruth_similarity | 134093 |
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:
Yesterday I was setting up my new windows laptop and while browsing on Firefox I got a webpage saying "urgent Firefox update is available" and I accidentally executed it. I immediately realised that it was a malware and immediately uninstalled Firefox. I had my Facebook and Gmail logged in on Firefox and have since changed their passwords. Is there anything else that I should be concerned about? It is a brand new laptop so I don't have any personal data on it. So that is not a worry. On a side note, when I installed Firefox back, I was already logged into FB and Gmail. I am not sure if it is because of the malware.
Now provide the response and nothing else.
| If it is a brand new laptop I would just reinstall the OS. The malware that you executed will not be fixed by removing Firefox. If your computer had more time invested in it, it may of been worth while trying various malware/virus detection/removal products. But as it is brand new just reinstall the operating system. As for what effect it could have, did it prompt to "make changes to your computer"? If yes and you clicked yes, then the malware could do almost anything, from installing new software, to modifying the operating system, to installing device drivers. The most common thing for malware to do is to install something that autostarts and contacts another computer and requests instructions. These instructions are normally either to be part of a botnet, being part of a DDoS attack, sending spam emails, clicking on ads on webpages. Or installing crypto-locker which would encrypt all your files on your computer and demand money to decrypt. There are lots of other things this could do, these are just some examples. | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/134093', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/107935/']} | jdg_82957 |
stackexchange | llm_judgeable_groundtruth_similarity | 2114965 |
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 long Scroll Viewer and I want to mark important spots with small images on the scroll bar. If the the image is clicked the scroll bar will jump to the corresponding content. I've seen this functionality in a few applications such as Eclipse and Chrome and was wondering how to reproduce it with WPF.
Now provide the response and nothing else.
| Short answer is "change the template of the ScrollBar". Long answer is... That I would add an ItemsControl in the template of the ScrollBar control. I would put this ItemsControl on top of the template with its IsHitTestVisible set to false so that it does not capture mouse events. Then I would use a Canvas as the ItemsPanelTemplate in order to be able to place the spots properly. I would use databinding with the ItemsSource property of the ItemsControl and a DataTemplate in order to render each element with an image. Here is a sample that I did using Blend. Of course it's not complete (it does not handle mouse event for example), but I hope it will be a starting point for you. (source: japf.fr ) <ControlTemplate TargetType="{x:Type ScrollBar}"> <Grid SnapsToDevicePixels="true" Background="{TemplateBinding Background}"> <Grid.ColumnDefinitions> <ColumnDefinition MaxWidth="{DynamicResource {x:Static SystemParameters.HorizontalScrollBarButtonWidthKey}}"/> <ColumnDefinition Width="0.00001*"/> <ColumnDefinition MaxWidth="{DynamicResource {x:Static SystemParameters.HorizontalScrollBarButtonWidthKey}}"/> </Grid.ColumnDefinitions> <RepeatButton Style="{StaticResource ScrollBarButton}" Command="{x:Static ScrollBar.LineLeftCommand}" Microsoft_Windows_Themes:ScrollChrome.ScrollGlyph="LeftArrow"/> <Track x:Name="PART_Track" Grid.Column="1" d:IsHidden="True"> <Track.Thumb> <Thumb Style="{StaticResource ScrollBarThumb}" Microsoft_Windows_Themes:ScrollChrome.ScrollGlyph="HorizontalGripper"/> </Track.Thumb> <Track.IncreaseRepeatButton> <RepeatButton Style="{StaticResource HorizontalScrollBarPageButton}" Command="{x:Static ScrollBar.PageRightCommand}"/> </Track.IncreaseRepeatButton> <Track.DecreaseRepeatButton> <RepeatButton Style="{StaticResource HorizontalScrollBarPageButton}" Command="{x:Static ScrollBar.PageLeftCommand}"/> </Track.DecreaseRepeatButton> </Track> <ItemsControl Grid.Column="1" HorizontalAlignment="Stretch"> <sys:Double>10</sys:Double> <sys:Double>50</sys:Double> <sys:Double>100</sys:Double> <sys:Double>140</sys:Double> <ItemsControl.ItemTemplate> <DataTemplate> <Rectangle Fill="Orange" Width="3" Height="16"/> </DataTemplate> </ItemsControl.ItemTemplate> <ItemsControl.ItemContainerStyle> <Style TargetType="ContentPresenter"> <Setter Property="Canvas.Left" Value="{Binding }" /> </Style> </ItemsControl.ItemContainerStyle> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Canvas/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> </ItemsControl> <RepeatButton Style="{StaticResource ScrollBarButton}" Grid.Column="2" Command="{x:Static ScrollBar.LineRightCommand}" Microsoft_Windows_Themes:ScrollChrome.ScrollGlyph="RightArrow" d:IsHidden="True"/> </Grid></ControlTemplate> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2114965', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3677/']} | jdg_82958 |
stackexchange | llm_judgeable_groundtruth_similarity | 39056 |
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Background: I'm training to be a geography teacher. Currently I have practice lessons and I'll be discussing solar time and standard time with the class. Now I stumbled over an issue to which I could not find an answer: We teach the students: Sidereal day: In 23 h 56 min the earth rotates 360° Solar day: In 24 h the earth rotates 361° We also teach that in order to construct time zones (as a replacement of solar time), one divided 360° by 24 (to have a zone for each hour of the day), which results in 24 zones with 15° each. Now my question is: Why does one mix the measures for sidereal day and solar day? Or put differently: Why doesn't one calculate 361°/24 or 360° / 23.933?
Now provide the response and nothing else.
| The Earth takes 23 hours 56 minutes to rotate once. But that is not relevant to most people. Sure, the stars will be in the same position again after 23 hours 56 minutes, but the sun will not be in the same position. It is far more important, for most people, to measure the time from noon to noon. And the average time from noon to noon is 24 hours. This is because the motion of the sun is a combination of both the spinning of the Earth and the orbit of the Earth around the sun. The orbital motion of the Earth adds four minutes. You should also teach the students In twenty-four hours the sun advances 360 degrees. (solar day) Time zones are based on clock time, which is based on the motion of the sun and not the motion of the stars. | {} | {'log_upvote_score': 7, 'links': ['https://astronomy.stackexchange.com/questions/39056', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/35299/']} | jdg_82959 |
stackexchange | llm_judgeable_groundtruth_similarity | 3005314 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How to evaluate the following limit? $$\lim_{n \to \infty} \sum_{k=1}^n \frac{n+k}{n^3+k}$$ I think that every term of the sum is greater than the first one and smaller than the last one and then from the squeeze theorem the limit is $0$ . However, I can't prove that inequality.
Now provide the response and nothing else.
| This should work: $$\sum_{k=1}^n\frac{n+k}{n^3+k}\leq\sum_{k=1}^n\frac{n+k}{n^3}\leq\sum_{k=1}^n\frac{n+n}{n^3}=\frac{2n^2}{n^3}=\frac{2}{n}\to0$$ Also, every term is $\geq 0$ so $0$ is also a lower bound. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3005314', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/600843/']} | jdg_82960 |
stackexchange | llm_judgeable_groundtruth_similarity | 9332360 |
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 update a query so that it checks that a duplicate entry does not exist before insertion. In MySQL I can just use INSERT IGNORE so that if a duplicate record is found it just skips the insert, but I can't seem to find an equivalent option for Oracle. Any suggestions?
Now provide the response and nothing else.
| Check out the MERGE statement. This should do what you want - it's the WHEN NOT MATCHED clause that will do this. Do to Oracle's lack of support for a true VALUES() clause the syntax for a single record with fixed values is pretty clumsy though: MERGE INTO your_table ytUSING ( SELECT 42 as the_pk_value, 'some_value' as some_column FROM dual) t on (yt.pk = t.the_pke_value) WHEN NOT MATCHED THEN INSERT (pk, the_column) VALUES (t.the_pk_value, t.some_column); A different approach (if you are e.g. doing bulk loading from a different table) is to use the "Error logging" facility of Oracle. The statement would look like this: INSERT INTO your_table (col1, col2, col3) SELECT c1, c2, c3 FROM staging_table LOG ERRORS INTO errlog ('some comment') REJECT LIMIT UNLIMITED; Afterwards all rows that would have thrown an error are available in the table errlog . You need to create that errlog table (or whatever name you choose) manually before running the insert using DBMS_ERRLOG.CREATE_ERROR_LOG . See the manual for details | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9332360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/892593/']} | jdg_82961 |
stackexchange | llm_judgeable_groundtruth_similarity | 232242 |
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'm reading some notes on quantum mechanics that state the following. $$\langle x\rvert \left( \hat{x} + \frac{i\hat{p}}{m\omega}\right) \lvert E \rangle = 0 \Rightarrow \left( x+ \frac{\hbar}{m\omega}\frac{d}{dx}\right)\langle x \lvert E\rangle=0$$ Why is this true? By linearity, we know that $$\langle x\rvert \left( \hat{x} + \frac{i\hat{p}}{m\omega}\right)\lvert E \rangle = \langle x\rvert \hat{x}\lvert E \rangle + \langle x\rvert \frac{i\hat{p}}{m\omega}\lvert E \rangle$$ $$= \langle x\rvert x\lvert E \rangle + \langle x\rvert \frac{\hbar}{m\omega}\frac{d}{dx}\lvert E \rangle$$ $$= x\langle x\lvert E \rangle + \frac{\hbar}{m\omega} \langle x\rvert \frac{d}{dx}\lvert E \rangle$$ So we require $$\langle x\rvert \frac{d}{dx}\lvert E \rangle=\frac{d}{dx}\langle x\rvert E \rangle$$ These seem like two very different expressions. On the left hand side, the operator is acting on an energy eigenstate in a Hilbert space whereas the operator is acting on a probability amplitude on the right hand side.
Now provide the response and nothing else.
| The relevant identity is $$\langle x| \hat{p}|\psi\rangle =−i \hbar \frac{d}{dx}\langle x|\psi\rangle\tag{1}$$ which is nothing but the definition of the operator $\hat{p}$. Instead $\frac{d}{dx}|\psi\rangle$ does not make sense as it stands. Because $\frac{d}{dx}$ acts on functions of $x$ whereas $|\psi\rangle$ is a vector in a Hilbert space. Conversely $\langle x|\psi \rangle = \psi (x)$ defines a function of $x$ when $x$ varies in $\mathbb R$so that $\frac{d}{dx}\langle x|\psi\rangle$ makes sense. The operator $\hat{p}$ must be viewed as an operator working on abstract vectors of the abstract Hilbert space $\cal H$ and it has different equivalent definitions depending on the representation you fix for $\cal H$ in terms of a Hilbert space of functions . As a matter of fact, if dealing with the so-called position representation , i.e., representing the vectors $|\psi\rangle$ in terms of wavefunctions $\psi= \psi(x)$, the corresponding Hilbert space isomorphism is$$U: \cal H \ni |\psi\rangle \mapsto \psi\quad \mbox{with $\psi(x) = \langle x|\psi \rangle$ for $x \in \mathbb R$}\:.$$That is a Hilbert-space isomorphism from $\cal H$ to $L^2(\mathbb R, dx)$. Definition (1) can be rephrased as $$\hat{p} = U \left(-i \hbar \frac{d}{dx}\right)\: U^{-1}$$ and it holds, obviously, when dealing with a suitably smooth domain of functions in $L^2(\mathbb R, dx)$. An alternate equivalent definition is obtained by dealing with the so-called momentum representation , where the wavefunctions are function of the momentum values: $\hat{\psi}= \hat{\psi}(p)$. Here, $$\hat{p} = V p \: V^{-1}\tag{2}$$ where $p$ in the right-hand side is the multiplicative operator and $$V: \cal H \ni |\psi\rangle \mapsto \hat\psi\quad \mbox{with $\hat{\psi}(p) = \langle p|\psi \rangle$ for $p \in \mathbb R$.}$$Above, $$\langle p|\psi \rangle = \frac{1}{\sqrt{2\pi \hbar}}\int_{\mathbb R} e^{-i\frac{px}{\hbar}}\psi(x) dx$$ and $V : {\cal H} \to L^2(\mathbb R, dp)$ is another Hilbert-space isomorphism. Clearly, here $VU^{-1} : L^2(\mathbb R, dx) \to L^2(\mathbb R, dp)$ is the Fourier transform . Within this framework, another way to write (2) is$$\langle p| \hat{p}|\psi\rangle =p\langle p|\psi\rangle\tag{3}\:.$$ | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/232242', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/52501/']} | jdg_82962 |
stackexchange | llm_judgeable_groundtruth_similarity | 148756 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Define $N_n$ as $n$ th natural number: $N_0=0, N_1=1, N_2=2, ...$. What happens after exponentiation? We have the following equation: $2^{N_n}=N_{2^{n}}$. (Which says: For all finite cardinal $n$ we have: $2^{n~\text{th finite cardinal}}=2^{n}~\text{th finite cardinal}$). What this means? The gap between $N_n$ and $2^{N_n}$ is rapidly increasing in exponential speed . Now look at the $\text{GCH}$. It says that the gap between an infinite cardinal $\kappa$ and $2^{\kappa}$ is just a constant number $1$ in cardinals. Even in models for total failure of $\text{GCH}$ we usually have a finite gap between $\kappa$ and $2^{\kappa}$. Now if we look at the infinite cardinals as generalization of natural numbers it seems we should restate continuum hypothesis with more acceleration for the function $\kappa \mapsto 2^{\kappa}$ in order to uniform the behavior of exponentiation function in finite and infinite cardinals. Note to the following statement: For all cardinal $\kappa$ we have $2^{\kappa~\text{th infinite cardinal}}=2^{\kappa}~\text{th infinite cardinal}$. This is a direct generalization of the equation $\forall n\in \omega~~~~~2^{N_n}=N_{2^n}$ to the following form: Natural Continuum Hypothesis (NCH): $~~~\forall \kappa\in Card~~~~~2^{\aleph_{\kappa}}=\aleph_{2^{\kappa}}$ Unfortunately $\text{NCH}$ is contradictory by Konig's lemma because assuming $\text{NCH}$ we have: $\aleph_{\aleph_0}<cf(2^{\aleph_{\aleph_0}})=cf(\aleph_{\aleph_1})\leq \aleph_1$ a contradiction. (Thanks to Ramiro and Emil for their advices.) But the acceleration problem remains open. The main question here is this: Can we have a rapidly increasing gap between carinals by exponentiation? In the other words: Question 1: Assuming consistency of $\text{ZFC}$ (plus some large cardinal axiom or axiom of constructibility), is the following statement consistent with $\text{ZFC}$? $\forall \kappa\in Card~~~\exists \lambda \in Card~;~~~~~\lambda\geq 2^{\kappa}~\wedge~2^{\aleph_{\kappa}}=\aleph_{\lambda}$ Definition 1: Let $\kappa$ be a (finite or infinite) cardinal. Define $\kappa$-based beth function as follows: $\beth_{(\kappa)}:Ord\longrightarrow Card$ $\beth_{(\kappa)}(0):=\kappa$ $\forall \alpha\in Ord~~~\beth_{(\kappa)}(\alpha +1):=2^{\beth_{(\kappa)}(\alpha)}$ $\forall \alpha\in LimitOrd~~~\beth_{(\kappa)}(\alpha):=\bigcup_{\beta \in \alpha}\beth_{(\kappa)}(\beta)$ Definition 2: Let $F:Card\longrightarrow Card$ be an increasing function and $\delta$ an ordinal. We say that $F$ has acceleration rank $\delta$ if $\delta=min\{\alpha\in Ord~|~\forall \kappa\in Card~~~\beth_{(\kappa)}(\alpha)\leq F(\kappa) < \beth_{(\kappa)}(\alpha+1)\}$. For example the functions $\kappa\mapsto \kappa^{+}$, $\kappa\mapsto 2^{\kappa}$, $\kappa\mapsto 2^{2^{\kappa}}$ have acceleration ranks $0, 1, 2$ respectively. Question 2: Is there any limitation for acceleration of the continuum function? Precisely is the following statement true? "For any ordinal $\delta$ there is an increasing function $F:Card\longrightarrow Card$ with acceleration rank $\delta$ such that assuming consistency of $\text{ZFC}$ (and some large cardinal axiom) one can prove the consistency of $\text{ZFC}$ with the statement $\forall \kappa\in Card~~~2^{\aleph_{\kappa}}=\aleph_{F(\kappa)}$." According to Emil's interesting comment I added his question here: Question 3: Assuming consistency of $\text{ZFC}$ (and some large cardinal axiom or axiom of constructibility), is the following consistent with $\text{ZFC}$? $\forall \kappa\in Card~~~~\exists \lambda\in Card~~~~~2^{\aleph_{\kappa}}=\aleph_{\lambda}$ Note that it is not trivial that one can have a "cardinal index" for $\aleph$ as value of $2^{\aleph_{\kappa}}$ everywhere. Perhaps we will need some non-cardinal ordinals as indexes to avoid inconsistency.
Now provide the response and nothing else.
| Let me provide a large cardinal lower bound for the statement in question 1. Since $\kappa\lt\kappa+1\lt 2^\kappa$ for $\kappa>1$, the statement implies that there isa universal failure of the GCH above $\aleph_1$ at cardinals of the form $\aleph_\kappa$ for $\kappa$ a cardinal. In particular, this implies thatthe negation of the singular cardinals hypothesisSCH . Since $\neg\text{SCH}$ is known to have large cardinal strength, we have large cardinallower bounds for the consistency strength of your statement. Meanwhile, since the statement also implies violations of the SCH arbitrarilyhigh in the cardinals, it follows by a result of Solovay that it is inconsistent with the existence of strongly compact cardinals. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/148756', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']} | jdg_82963 |
stackexchange | llm_judgeable_groundtruth_similarity | 5364928 |
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 require all files in a folder in node.js? need something like: files.forEach(function (v,k){ // require routes require('./routes/'+v);}};
Now provide the response and nothing else.
| When require is given the path of a folder, it'll look for an index.js file in that folder; if there is one, it uses that, and if there isn't, it fails. It would probably make most sense (if you have control over the folder) to create an index.js file and then assign all the "modules" and then simply require that. yourfile.js var routes = require("./routes"); index.js exports.something = require("./routes/something.js");exports.others = require("./routes/others.js"); If you don't know the filenames you should write some kind of loader. Working example of a loader: var normalizedPath = require("path").join(__dirname, "routes");require("fs").readdirSync(normalizedPath).forEach(function(file) { require("./routes/" + file);});// Continue application logic here | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/5364928', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/663447/']} | jdg_82964 |
stackexchange | llm_judgeable_groundtruth_similarity | 4921034 |
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 Douglas Crockford's design pattern to implement private, privileged and public methods. It basically looks something like this (using RequireJS ): define(function () { return function () { var that = {}, _init = function () { // "constructor" }, _privateFn = function () { return 42; }; that.publicFn = function () { return 2 * _privateFn(); }; _init(arguments); return that; };}); However, I'm having trouble getting the jsdoc toolkit to parse it correctly. I've played around with the @name and @memberOf annotations (like here ), but no matter what I do, I just can't get the functions to show up. Does anyone know a solution?
Now provide the response and nothing else.
| Okay, I finally figured it out. Here's how you do it: /*** @name MyModule* @namespace*/define(['MyModule'], (function () { "use strict"; var Clazz = function (config) { var that = {}, /** * @private * @type number * @name MyModule#_privateField * @field */ _privateField = 42, /** * Returns a private field * * @private * @memberOf MyModule# */ _privateFn = function () { return _privateField; }; /** * Uppercases a string value. * * @public * @name MyModule#publicFn * @function * @param {string} value The value to uppercase. */ that.publicFn = function (value) { return value.toUpperCase(); }; return that; } return Clazz;})); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4921034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106236/']} | jdg_82965 |
stackexchange | llm_judgeable_groundtruth_similarity | 6967463 |
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 less verbose alternative to this: for x in xrange(array.shape[0]): for y in xrange(array.shape[1]): do_stuff(x, y) I came up with this: for x, y in itertools.product(map(xrange, array.shape)): do_stuff(x, y) Which saves one indentation, but is still pretty ugly. I'm hoping for something that looks like this pseudocode: for x, y in array.indices: do_stuff(x, y) Does anything like that exist?
Now provide the response and nothing else.
| I think you're looking for the ndenumerate . >>> a =numpy.array([[1,2],[3,4],[5,6]])>>> for (x,y), value in numpy.ndenumerate(a):... print x,y... 0 00 11 01 12 02 1 Regarding the performance. It is a bit slower than a list comprehension. X = np.zeros((100, 100, 100))%timeit list([((i,j,k), X[i,j,k]) for i in range(X.shape[0]) for j in range(X.shape[1]) for k in range(X.shape[2])])1 loop, best of 3: 376 ms per loop%timeit list(np.ndenumerate(X))1 loop, best of 3: 570 ms per loop If you are worried about the performance you could optimise a bit further by looking at the implementation of ndenumerate , which does 2 things, converting to an array and looping. If you know you have an array, you can call the .coords attribute of the flat iterator. a = X.flat%timeit list([(a.coords, x) for x in a.flat])1 loop, best of 3: 305 ms per loop | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/6967463', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/76701/']} | jdg_82966 |
stackexchange | llm_judgeable_groundtruth_similarity | 624260 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to clear out and reuse an ostringstream (and the underlying buffer) so that my app doesn't have to do as many allocations. How do I reset the object to its initial state?
Now provide the response and nothing else.
| I've used a sequence of clear and str in the past: // clear, because eof or other bits may be still set. s.clear();s.str(""); Which has done the thing for both input and output stringstreams. Alternatively, you can manually clear, then seek the appropriate sequence to the begin: s.clear();s.seekp(0); // for outputs: seek put ptr to starts.seekg(0); // for inputs: seek get ptr to start That will prevent some reallocations done by str by overwriting whatever is in the output buffer currently instead. Results are like this: std::ostringstream s;s << "hello";s.seekp(0);s << "b";assert(s.str() == "bello"); If you want to use the string for c-functions, you can use std::ends , putting a terminating null like this: std::ostringstream s;s << "hello";s.seekp(0);s << "b" << std::ends;assert(s.str().size() == 5 && std::strlen(s.str().data()) == 1); std::ends is a relict of the deprecated std::strstream , which was able to write directly to a char array you allocated on the stack. You had to insert a terminating null manually. However, std::ends is not deprecated, i think because it's still useful as in the above cases. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/624260', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23524/']} | jdg_82967 |
stackexchange | llm_judgeable_groundtruth_similarity | 53736948 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
ModelCheckPoint gives options to save both for val_Acc and val_loss separately. I want to modify this in a way so that if val_acc is improving -> save model. if val_acc is equal to previous best val_acc then check for val_loss , if val_loss is less than previous best val_loss then save the model. if val_acc(epoch i)> best_val_acc: save model else if val_acc(epoch i) == best_val_acc: if val_loss(epoch i) < best_val_loss: save model else do not save model
Now provide the response and nothing else.
| You can just add two callbacks: callbacks = [ModelCheckpoint(filepathAcc, monitor='val_acc', ...), ModelCheckpoint(filepathLoss, monitor='val_loss', ...)]model.fit(......., callbacks=callbacks) Using custom callbacks You can do anything you want in a LambdaCallback(on_epoch_end=saveModel) . best_val_acc = 0best_val_loss = sys.float_info.max def saveModel(epoch,logs): val_acc = logs['val_acc'] val_loss = logs['val_loss'] if val_acc > best_val_acc: best_val_acc = val_acc model.save(...) elif val_acc == best_val_acc: if val_loss < best_val_loss: best_val_loss=val_loss model.save(...) callbacks = [LambdaCallback(on_epoch_end=saveModel)] But this is nothing different from a single ModelCheckpoint with val_acc . You won't really be getting identical accuracies unless you're using very few samples, or you have a custom accuracy that doesn't vary much. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53736948', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10779185/']} | jdg_82968 |
stackexchange | llm_judgeable_groundtruth_similarity | 6527462 |
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 display a objects in my model in the form of a table, but am having a hard time trying to create the rows and columns dynamically. I have a model called Pictures and currently I'm displaying all of them in a looooong list. <% for picture in @pictures %> <p><%= image_tag(picture.url) %></p><% end %> How can I turn this into a table in the view with rails? <table><tr><% for picture in @pictures %> <td> <%= image_tag(picture.url) %> </td>** Here's where I'm confused..How can I write after 6 cells create a new row?? *****<% end %></table> So the question is really related to how to breakup this type of data within the view.
Now provide the response and nothing else.
| Have a look at the enumerable method ".each_slice". http://www.ruby-doc.org/core/classes/Enumerable.html#M001514 With it you can do something along the lines of: <table> <% @pictures.each_slice(6) do |slice| %> <tr> <% slice.each do |picture| %> <td> <%= image_tag(picture.url) %> </td> <% end %> </tr> <% end %></table> You may have to do some fiddling to populate the last row nicely, but that should get you on your way. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6527462', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/251234/']} | jdg_82969 |
stackexchange | llm_judgeable_groundtruth_similarity | 19318298 |
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 defined a function in an IPython notebook and would like to be able to block comment a section of it. Intuitively, I'd expect to be able to highlight a section of code, right click and have an option to comment out the selection but this has not been implemented. Is there a way to do this?
Now provide the response and nothing else.
| Default solution In IPython 2.x and 3.x (cmd|ctrl)-/ works but requires an english (american) keyboard layout, see https://github.com/ipython/ipython/pull/3673 . Other keyboard layouts In case you have a non-english keyboard layout, you can define a custom keybinding for the codemirror editor via your custom.js. To this end add e.g. the following lines define([ 'base/js/namespace', 'base/js/events' ], function(IPython, events) { events.on("app_initialized.NotebookApp", function () { IPython.Cell.options_default.cm_config.extraKeys = {"Ctrl-," : "toggleComment"}; } ); }); to use Ctrl + , to toggle (block) comments. I use this with a german keyboard layout and IPython 3.0.The previous solution (see edits) worked fine with chrome, but not with firefox. Old solution (IPython 1.x) If you are using IPython 1.x you can try the comment-uncomment.js from https://github.com/ipython-contrib/IPython-notebook-extensions - I haven't tried this yet, but I guess its a good start. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19318298', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1856916/']} | jdg_82970 |
stackexchange | llm_judgeable_groundtruth_similarity | 1832 |
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
We have a LAN with 20 machines on it. They are connected to a switch which also connects to our primary Westell DSL modem for internet access. The modem does the NATing and is the DHCP server, (so that our internal addresses are 192.168.1.*). We have a backup modem and phone line which is just like the primary except, of course, its IP address to the outside world is different. The plan is that if the primary line fails, we just move the cable that connects the modem and switch from the primary to the backup modem. It's crude and not exactly real-time but sufficient for our needs. The question is, when the switch-over is made, what happens to the DHCP assigned addresses? The machines already have addresses, but the backup modem doesn't know about them. So what happens? Will confusion reign on the LAN?
Now provide the response and nothing else.
| Will confusion reign on the LAN? Generally, no. The machines that have addresses will still have them, until their lease expires. I'm not sure how smart the Westel DHCPd is, but most will verify an address is not in use before assigning it. You can avoid any possible collisions by setting each router to use a different range of addresses: router 1 -- 192.168.1.100-149, router 2 -- 192.168.1.150-199. When new machines come online or old leases expire, they'll get an address from the currently active router. (Just remember to not set any host to 100-199.) | {} | {'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/1832', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/1652/']} | jdg_82971 |
stackexchange | llm_judgeable_groundtruth_similarity | 38642 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How do you show, that for every bound $\epsilon$, there is a non-zero probability that the motion is bounded on a finite interval.i.e. $$\mathbb{P} (\sup_{t\in[0,1]} |B(t)| < \epsilon) > 0$$ I tried using the reflection principle, I can show that if B* is the motion reflected on the hitting time with the bound, $\tau$, then I think that$$P(\sup_{t\in[0,1]} |B(t)| > \epsilon) = P(|B(1)| > \epsilon) + P(|B*(1)| > \epsilon) - P(\tau < 1, |B(1)-B(\tau)| > 2\epsilon)$$However, I have no idea how to bound the third term (in a useful way, which would show that this probability is non-one)
Now provide the response and nothing else.
| Here's three different methods of showing that $\mathbb{P}(\sup_{t\in[0,1]}\vert B_t\vert < \epsilon)$ is nonzero. A simple argument based on intuition. You can break the unit interval into a lot of small time steps and, by continuity, the Brownian motion will not move much across each of these steps. By independence of the increments, there is a positive (but small) probability that they largely cancel out, so $B$ stays within $\epsilon$ of the origin. To make this precise, choose a positive integer $n$ such that $q\equiv\mathbb{P}(\sup_{t\le1/n}\vert B_t\vert < \epsilon/2)$ is nonzero ($q$ can be made as close to 1 as you like, by taking $n$ large). By symmetry, the event $\{\sup_{t\le1/n}\vert B_t\vert < \epsilon/2,\ B_{1/n}>0\}$ has probability $q/2$. Note that, if $\sup_{t\in[k/n,(k+1)/n]}\vert B_t-B_{k/n}\vert < \epsilon/2$ and $B_{(k+1)/n}-B_{k/n}$ has the opposite sign to $B_{k/n}$ for each $k=0,1,\ldots,n-1$ then $\vert B_t\vert$ will be bounded by $\epsilon/2$ at the times $k/n$ and, therefore, $\sup_{t\le1}\vert B_t\vert$ will be less than $\epsilon$. So, $\mathbb{P}(\sup_{t\le1}\vert B_t\vert < \epsilon)\ge(q/2)^n$. Use a cunning trick. If $X,Y$ are independent Brownian motions over the interval $[0,1]$, then $B=(X-Y)/\sqrt{2}$ is also a Brownian motion. The sample paths of $X,Y,B$ can be considered as lying in the (complete, separable) metric space $C([0,1])$ of continuous functions $[0,1]\to\mathbb{R}$ under the supremum norm . By separability, $C([0,1])$ can be covered by countably many open balls of radius $\epsilon/\sqrt{2}$. So, by countable additivity of the probability measure, there exists at least one such ball containing $X$ with probability $q > 0$. By independence, $X,Y$ are both contained in this ball with probability $q^2 > 0$, in which case $\Vert B\Vert_\infty=\Vert X- Y\Vert_\infty/\sqrt{2}<\epsilon$. Exact calculation. You can calculate an exact expression for the probability, as an infinite sum, and verify that it is dominated by a single positive term as $\epsilon$ goes to zero. This is not as simple as the intuitive argument I gave above, but has the advantage that it also gives an accurate asymptotic expression for the probability, which goes to zero like $e^{-\pi^2/(8\epsilon^2)}$ as $\epsilon\to0$ (this is positive, but tends to zero very quickly). The probability can be calculated using the reflection principal (also see my comments and Douglas Zare's answer to this question ). Writing $p(x)=(2\pi)^{-1/2}e^{-x^2/2}$ for the probability density function of $B_1$ and $f(x)=\sum_{n=-\infty}^\infty(-1)^n1_{\{(2n-1)\epsilon < x < (2n+1)\epsilon\}}$ (which is a kind of square wave function),$$\mathbb{P}\left(\sup_{t\le1}\vert B_t\vert < \epsilon\right)=\mathbb{E}[f(B_1)]=\int_{-\infty}^\infty f(x)p(x)\,dx.\qquad{\rm(1)}$$This expression comes from the reflection principle, which says that reflecting $B$ after it first hits $\pm\epsilon$ gives another Brownian motion. That is, $\hat B_t\equiv B_t+1_{\{t\ge T\}}2(B_T-B_t)$ is a Brownian motion, where $T$ is the first time at which $\vert B_T\vert=\epsilon$. As $f$ is antisymmetric about both $\epsilon$ and $-\epsilon$, the sum $f(B_1)+f(\hat B_1)$ vanishes whenever $T\le1$. So, $1_{\{T > 1\}}=(f(B_1)+f(\hat B_1))/2$, and taking the expectation gives (1). You can perform the integral in (1) directly to express the probability as an infinite sum over the cumulative normal distribution function, but this is not so good in the limit where $\epsilon$ is small, as you don't have a single dominant term. Alternatively, the integral in (1) can be written as $\int_{-\epsilon}^\epsilon\theta(x)\,dx$ where $\theta(x)=\sum_{n=-\infty}^\infty(-1)^np(x+2n\epsilon)$. As $\theta$ has period $4\epsilon$ you can write it as a Fourier series, and working out the coefficients gives$$\theta(x)=\epsilon^{-1}\sum_{\substack{n > 0,\\n{\rm\ odd}}}\cos\left(\frac{n\pi x}{2\epsilon}\right)\exp\left(-\frac{n^2\pi^2}{8\epsilon^2}\right).$$This is a very fast converging sum, especially for small $\epsilon$ (the terms vanish much faster then exponentially in $n$). Actually, $\theta$ is a theta function and the fourier transform is the same thing as the Jacobi identity . Integrating it term by term gives$$\mathbb{P}\left(\sup_{t\le1}\vert B_t\vert < \epsilon\right)=\sum_{\substack{n > 0,\\ n{\rm\ odd}}}\frac{4}{n\pi}(-1)^{(n-1)/2}\exp\left(-\frac{n^2\pi^2}{8\epsilon^2}\right)$$As the first term goes to zero much more slowly than the sum of the remaining terms (as $\epsilon\to0$) this gives the asymptotic expression$$\mathbb{P}\left(\sup_{t\le1}\vert B_t\vert < \epsilon\right)\sim\frac{4}{\pi}\exp\left(-\frac{\pi^2}{8\epsilon^2}\right).$$ | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/38642', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8911/']} | jdg_82972 |
stackexchange | llm_judgeable_groundtruth_similarity | 37309440 |
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 right/best way to get data from an RSS feed using ASP.Net Core 1.0 (RC2) in C#. I want to work with the data in the RSS feed from my Wordpress blog which is https://blogs.msdn.microsoft.com/martinkearn/feed/ I know that in ASP.net 4.x, you'd use RssReader or SyndicationFeed but I cannot find an equivalent for ASP.net core. This is as far as I have got which returns the raw feed but I do not know how to extract the data from it. I want to enumerate the items and get the title and description from each one var feedUrl = "https://blogs.msdn.microsoft.com/martinkearn/feed/"; using (var client = new HttpClient()) { client.BaseAddress = new Uri(feedUrl); var responseMessage = await client.GetAsync(feedUrl); var responseString = await responseMessage.Content.ReadAsStringAsync(); }
Now provide the response and nothing else.
| According to this issue , System.ServiceModel.Syndication has not yet been ported to ASP.NET Core. Currently, this leaves you with 2 options: Target the full .NET framework to provide access to SyndicationFeed Build your own XML parser using .NET Core to reproduce the functionality you require Target the full .NET framework This is undoubtedly the easiest approach depending on your requirements. If you will be deploying to windows only then you can run ASP.NET Core on top of the .NET 4.X framework. To do this, update your project.json from something like this frameworks": { "netcoreapp1.0": { "imports": [ "dotnet5.6", "dnxcore50", "portable-net45+win8" ] }} to this: frameworks": { "net452": { "frameworkAssemblies": { "System.ServiceModel": "" } }} Build your own XML Parser This will give you the most flexibility, in that you will still be able to run cross platform using the .NET Core framework. It requires a little more work to deserialise the string you have already obtained, but there are lots of examples on how to do just this, e.g. http://www.anotherchris.net/csharp/simplified-csharp-atom-and-rss-feed-parser/ | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37309440', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1601158/']} | jdg_82973 |
stackexchange | llm_judgeable_groundtruth_similarity | 51434005 |
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 viewset and I override list() method, but filtering by field stop working. How can I call filtering options from my code: This is my viewset: class SupplementViewSet(viewsets.ModelViewSet): permission_classes = (permissions.IsAuthenticated,) queryset = models.Product.objects.filter() serializer_class = serializers.SuplementSerializer filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,) search_fields = ('hotel', 'name') filter_fields = ('id', 'hotel', 'name') def perform_create(self, instance): instance.save(product_type=models.Product.SUPPLEMENT) def list(self, request, pk=None): if pk == None: supplements = models.Product.objects.filter(product_type=models.Product.SUPPLEMENT) else: supplements = models.Product.objects.get(product_type=models.Product.SUPPLEMENT, id=pk) page = self.paginate_queryset(supplements) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(page, many=True) result_set = serializer.data return Response(result_set) def get_result_set(self, supplements): result_set = serializers.ProductSerializer(supplements, many=True).data return result_set Thanks for the help.
Now provide the response and nothing else.
| def list(self, request, pk=None): if pk == None: supplements = models.Product.objects.filter(product_type=models.Product.SUPPLEMENT) else: supplements = models.Product.objects.filter(product_type=models.Product.SUPPLEMENT, id=pk) supplements= self.filter_queryset(supplements) page = self.paginate_queryset(supplements) self.filter_queryset(queryset) is what you need, but it must accept queryset. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51434005', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6843153/']} | jdg_82974 |
stackexchange | llm_judgeable_groundtruth_similarity | 42094480 |
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 compare two dictionaries keys and if there is a match I want to create a new dict with the key and the values from both dictionaries, if no match I want to put value 0. I tried the below code but I got KeyError: 't2.large' when I tried to print this key which is not in the first dict a . c = dict()a = {'m3.xlarge': 4, 't2.medium': 1, 't2.large': 1, 'm3.large': 1}b = {'m3.xlarge': 5, 't2.medium': 1, 'm3.large': 2, 'm4.large': 1}c = dict()for key, value in a.items(): if key in b.keys(): a_key = key a_value = value b_value = b[key] c.setdefault(a_key,[]).append(a_value) c.setdefault(a_key,[]).append(b_value) elif key not in b.keys(): value = b.get(key) print("key not in b.keys() => ", value) # key not in b.keys() => None b_value = b[key] print("key a not in b.keys => ", b_value) # KeyError: 't2.large'print(c) The result should be like this: # c = {'m3.xlarge': [4, 5], 't2.medium': [1, 1], 't2.large': [1, 0], 'm3.large': [1, 2], 'm4.large': [0, 1]} My second question, how I can do the same thing but without appending the key:value to the new dict if there is a match between the key:value from both dict. 't2.medium': [1, 1] will be removed because the keys:values are the same 1-1c = {'m3.xlarge': [4, 5], 't2.large': [1, 0], 'm3.large': [1, 2], 'm4.large': [0, 1]} Thanks!
Now provide the response and nothing else.
| In order to answer the question, we should first clear up some concepts. What is an array and how can it be used? And what is the code in the question, if not an array? What is an array? The formal definition of an array is found in the C standard, ISO 9899:2011 6.2.5/20 Types . An array type describes a contiguously allocated non-empty set of objects with a particular member object type, called the element type. In plain English, an array is a collection of items of the same type allocated contiguously, in adjacent memory cells. For example an array of 3 integers int arr[3] = {1,2,3}; would be allocated in memory like this: +-------+-------+-------+| | | || 1 | 2 | 3 || | | |+-------+-------+-------+ So what about the formal definition of a multi-dimensional array? Actually, it is the very same definition as cited above. It applies recursively. If we would allocate a 2D array, int arr[2][3] = { {1,2,3}, {1,2,3} }; it would get allocated in memory like this: +-------+-------+-------+-------+-------+-------+| | | | | | || 1 | 2 | 3 | 1 | 2 | 3 || | | | | | |+-------+-------+-------+-------+-------+-------+ What we have in this example is actually an array of arrays. An array which has 2 items, each of them an array of 3 integers. An array is a type like any other Arrays in C often follow the same type system as regular variables. As shown above, you can have an array of arrays, like you can have an array of any other type. You can also apply the same kind of pointer arithmetic on n -dimensional arrays as on plain one-dimensional arrays. With a regular one-dimensional arrays, applying pointer arithmetic should be trivial: int arr[3] = {1,2,3};int* ptr = arr; // integer pointer to the first element.for(size_t i=0; i<3; i++){ printf("%d ", *ptr); // print contents. ptr++; // set pointer to point at the next element.} This was made possible through "array decay". When arr was used inside an expression, it "decayed" into a pointer to the first element. Similarly, we can use the very same kind of pointer arithmetic to iterate through an array of arrays, by using an array pointer : int arr[2][3] = { {1,2,3}, {1,2,3} };int (*ptr)[3] = arr; // int array pointer to the first element, which is an int[3] array.for(size_t i=0; i<2; i++){ printf("%d %d %d\n", (*ptr)[0], (*ptr)[1], (*ptr)[2]); // print contents ptr++; // set pointer to point at the next element} Again there was array decay. The variable arr which was of type int [2][3] decayed into a pointer to the first element. The first element was an int [3] and a pointer to such an element is declared as int(*)[3] - an array pointer. Understanding array pointers and array decay is necessary in order to work with multi-dimensional arrays. There are more cases where arrays behave just like regular variables. The sizeof operator works just the same for (non-VLA) arrays as for regular variables. Examples for a 32 bit system: int x; printf("%zu", sizeof(x)); prints 4 . int arr[3] = {1,2,3}; printf("%zu", sizeof(arr)); prints 12 (3*4=12) int arr[2][3] = { {1,2,3}, {1,2,3} }; printf("%zu", sizeof(arr)); prints 24 (2*3*4=24) Like any other type, arrays can be used with library functions and generic APIs. Since arrays fulfil the requirement of being allocated contiguously, we can for example safely copy them with memcpy : int arr_a[3] = {1,2,3};int arr_b[3];memcpy(arr_b, arr_a, sizeof(arr_a)); Contiguous allocation is also the reason why other similar standard library functions like memset , strcpy , bsearch and qsort work. They are designed to work on arrays allocated contiguously. So if you have a multi-dimensional array, you can efficiently search it and sort it with bsearch and qsort , saving you the fuss of implementing binary search and quick sort yourself and thereby re-inventing the wheel for every project. All of the above consistencies between arrays and other types is a very good thing that we want to take advantage of, particularly when doing generic programming. What is the pointer-to-pointer thing, if not an array? Now to get back to the code in the question, which used a different syntax with a pointer-to-pointer. There is nothing mysterious about it. It is a pointer to pointer to type, no more no less. It is not an array. It is not a 2D array. Strictly speaking, it cannot be used to point at an array, nor can it be used to point at a 2D array. A pointer-to-pointer can however be used to point at the first element of an array of pointers, instead of pointing at the array as whole. And that is how it is used in the question - as a way to "emulate" an array pointer. In the question, it is used to point at an array of 2 pointers. And then each of the 2 pointers is used to point at an array of 3 integers. This is known as a look-up table, which is a kind of abstract data type (ADT), which is something different from the lower level concept of plain arrays. The main difference is how the look-up table is allocated: +------------+| || 0x12340000 || |+------------+ | | v+------------+ +-------+-------+-------+| | | | | || 0x22223333 |---->| 1 | 2 | 3 || | | | | |+------------+ +-------+-------+-------+| | | 0xAAAABBBB |--+| | | +------------+ | | | +-------+-------+-------+ | | | | | +->| 1 | 2 | 3 | | | | | +-------+-------+-------+ The 32 bit addresses in this example are made-up. The 0x12340000 box represents the pointer-to-pointer. It contains an address 0x12340000 to the first item in an array of pointers. Each pointer in that array in turn, contains an address pointing at the first item in an array of integers. And here is where the problems start. Problems with the look-up table version The look-up table is scattered all over the heap memory. It is not contiguously allocated memory in adjacent cells, because each call to malloc() gives a new memory area, not necessarily located adjacently to the others. This in turn gives us lots of problems: We can't use pointer arithmetic as expected. While we can use a form of pointer arithmetic to index and access the items in the look-up table, we can't do so using array pointers. We can't use the sizeof operator. Used on the pointer-to-pointer, it would give us the size of a pointer-to-pointer. Used to the first item pointed at, it would give us the size of a pointer. Neither of them is the size of an array. We can't use standard library functions that excepts an array type ( memcpy , memset , strcpy , bsearch , qsort and so on). All such functions assume to get arrays as input, with data allocated contiguously. Calling them with our look-up table as parameter would result in undefined behavior bugs, such as program crashes. Repeated calls of malloc to allocate several segments leads to heap fragmentation , which in turn results in poor use of RAM memory. Since the memory is scattered, the CPU cannot utilize cache memory when iterating through the look-up table. Efficient use of the data cache requires a contiguous chunk of memory which is iterated through from top to bottom. This means that the look-up table, by design, has significantly slower access time than a real multi-dimensional array. For each call to malloc() , the library code managing the heap has to calculate where there is free space. Similarly for each call to free() , there is overhead code which has to be executed. Therefore, as few calls to these functions as possible is often preferable, for the sake of performance. Are look-up tables all bad? As we can see, there are a lot of problems with pointer-based look-up tables. But they aren't all bad, it is a tool like any other. It just has to be used for the right purpose. If you are looking for a multi-dimensional array, which should be used as an array, look-up tables are clearly the wrong tool. But they can be used for other purposes. A look-up table is the right choice when you need all dimensions to have completely variable sizes, individually. Such a container can be handy when for example creating a list of C strings. It is then often justified to take the above mentioned execution speed performance loss in order to save memory. Also, the look-up table has the advantage that you can re-alloce parts of the table in run-time without the need to re-allocate a whole multi-dimensional array. If this is something that needs to be done frequently, the look-up table might even outperform the multi-dimensional array in terms of execution speed. For example, similar look-up tables can be used when implementing a chained hash table. How to properly allocate a multi-dimensional array dynamically then? The easiest form in modern C is to simply use a variable-length array (VLA). int array[x][y]; where x and y are variables given values in run-time, prior array declaration. However, VLAs have local scope and do not persist throughout the duration of the program - they have automatic storage duration. So while VLAs may be convenient and fast to use for temporary arrays, it is not an universal replacement to the look-up table in the question. To truly allocate a multi-dimensional array dynamically, so that it gets allocated storage duration , we have to use malloc() / calloc() / realloc() . I'll give one example below. In modern C, you would use array pointers to a VLA. You can use such pointers even when no actual VLA is present in the program. The benefit of using them over a plain type* or a void* is increased type-safety. Using a pointer to a VLA also allows you to pass the array dimensions as parameters to the function using the array, making it both variable and type safe at once. Unfortunately, in order to use the benefits of having a pointer to VLA, we can't return that pointer as a function result. So if we need to return a pointer to the array to the caller, it must be passed as a parameter (for the reasons described in Dynamic memory access only works inside function ). This is fine practice in C, but makes the code a bit hard to read. It would look something like this: void arr_alloc (size_t x, size_t y, int(**aptr)[x][y]){ *aptr = malloc( sizeof(int[x][y]) ); // allocate a true 2D array assert(*aptr != NULL);} While this syntax with a pointer to an array pointer might look a bit strange and intimidating, it doesn't get more complex than this even if we add more dimensions: void arr_alloc (size_t x, size_t y, size_t z, int(**aptr)[x][y][z]){ *aptr = malloc( sizeof(int[x][y][z]) ); // allocate a true 3D array assert(*aptr != NULL);} Now compare that code with the code for adding one more dimension to the look-up table version: /* Bad. Don't write code like this! */int*** arr_alloc (size_t x, size_t y, size_t z){ int*** ppp = malloc(sizeof(*ppp) * x); assert(ppp != NULL); for(size_t i=0; i<x; i++) { ppp[i] = malloc(sizeof(**ppp) * y); assert(ppp[i] != NULL); for(size_t j=0; j<y; j++) { ppp[i][j] = malloc(sizeof(***ppp) * z); assert(ppp[i][j] != NULL); } } return ppp;} Now that is one unreadble mess of "three-star programming". And lets not even consider 4 dimensions... The full code of a version using true 2D arrays #include <stdlib.h>#include <stdio.h>#include <assert.h>void arr_alloc (size_t x, size_t y, int(**aptr)[x][y]){ *aptr = malloc( sizeof(int[x][y]) ); // allocate a true 2D array assert(*aptr != NULL);}void arr_fill (size_t x, size_t y, int array[x][y]){ for(size_t i=0; i<x; i++) { for(size_t j=0; j<y; j++) { array[i][j] = (int)j + 1; } }}void arr_print (size_t x, size_t y, int array[x][y]){ for(size_t i=0; i<x; i++) { for(size_t j=0; j<y; j++) { printf("%d ", array[i][j]); } printf("\n"); }}int main (void){ size_t x = 2; size_t y = 3; int (*aptr)[x][y]; arr_alloc(x, y, &aptr); arr_fill(x, y, *aptr); arr_print(x, y, *aptr); free(aptr); // free the whole 2D array return 0;} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/42094480', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4308473/']} | jdg_82975 |
stackexchange | llm_judgeable_groundtruth_similarity | 325488 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Going to one of my websites produces this; top; Seconds later all goes back to normal again..... do I maybe have some sort of aggressive http logger or something installed? rcconf;
Now provide the response and nothing else.
| Ideally either I'd like nginx to not serve https at all unless the hostname matches, or for it to redirect to http at the same host. Neither is possible. The connection from a client that goes to https://foo.example.com/ cannot be accepted by anything but an SSL certificate with "foo.example.com" as one of its names. There is no opportunity to redirect until the SSL connection is accepted. If you configure each site for SSL, a user who clicks through the certificate error will get the site they requested. If you configure a "catch all" site for SSL that provides only an error page and configure name-based virtual hosting for the one site that is supposed to support SSL, you can serve an error page to clients. SSL and HTTP virtual hosting just don't play nicely together. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/325488', 'https://serverfault.com', 'https://serverfault.com/users/85534/']} | jdg_82976 |
stackexchange | llm_judgeable_groundtruth_similarity | 2971160 |
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:
$\lim_{x \to \infty} x-x^2\ln(1+1/x)$ I tried to write it as a fraction and use L'Hospital Rule but it will still be a indetermination. The answer seems to be $1/2$ . Can somebody help me, please?
Now provide the response and nothing else.
| HINT To use l'Hopital let consider $$x-x^2\ln\left(1+\frac1x\right)=\frac{\frac1x-\ln\left(1+\frac1x\right)}{\frac1{x^2}}$$ then take $y=\frac1x \to 0^+$ to obtain $$\lim_{x\to \infty} x-x^2\ln\left(1+\frac1x\right)=\lim_{y\to 0^+} \frac{y-\ln\left(1+y\right)}{y^2}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2971160', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/588960/']} | jdg_82977 |
stackexchange | llm_judgeable_groundtruth_similarity | 33657212 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to be able to click anywhere inside the body except that one specific element. I can't find out what's wrong with the code I have done. When I click on the one specific element .except inside body , I don't want it to hide but when I click on body it should hide. HTML <html> <head> <title>Click anywhere except that specific element</title> </head> <body id="wrapper"> <center> <div id="except"></div> </center> </body></html> JS var body = document.getElementById('wrapper');var except = document.getElementById('except');if(body.addEventListener) body.addEventListener("click", function(){bodyClick("yes")}, false);else body.attachEvent("onclick", bodyClick);function bodyClick(clicked){ except.addEventListener("click", exceptClick,false); function exceptClick(){ bodyClick("no"); if(clicked === "yes") except.style.display = "none"; } if(clicked === "yes") except.style.display = "none"; else except.style.display = "show";} Any help is appreciated. Forgive me for the incorrect formatting (it's my first post here). Thank You!
Now provide the response and nothing else.
| You need to stopPropagation to the outer element. Here's a simple illustration: http://jsfiddle.net/5mhqrhwk/3/ var body = document.getElementById('wrapper');var except = document.getElementById('except');body.addEventListener("click", function () { alert("wrapper");}, false);except.addEventListener("click", function (ev) { alert("except"); ev.stopPropagation(); //this is important! If removed, you'll get both alerts}, false); HTML: <div id="wrapper"> <center> <div id="except"></div> </center></div> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33657212', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4460907/']} | jdg_82978 |
stackexchange | llm_judgeable_groundtruth_similarity | 16324654 |
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 developing a "Sokoban" game at a very basic level. I'm trying to make this for loop but cannot seem to complete it. My aim is to carry out an example of the movement code below, I feel my syntax is wrong in regards to adding another condition where it says "(diamondlist.Count) & (Playerlist.Count). The error I am getting is "Operator '&' cannot be applied to operands of type 'bool' and 'int'. I have tried to add double "&&" and this does not solve it eitheir, any help is appreciated - thanks :D protected override void Update(GameTime gameTime) { for (int i = 0; i < (diamondlist.Count) & (Playerlist.Count); i++) { if ((Playerlist[i].Position == diamondlist[i].Position) && kb_old.IsKeyDown(Keys.W)) { if (currentMap.isWalkable(new Point(diamondlist[i].m_position.X, diamondlist[i].m_position.Y - 1))) diamondlist[i].m_position.Y--; }
Now provide the response and nothing else.
| There are a few problems. The expression i < (diamondlist.Count) & (Playerlist.Count) is evaluated as: (i < diamondlist.Count) & Playerlist.Count The first part of the expression ( i < diamondlist.Count ) is a bool , but the second part ( Playerlist.Count ) is an int . It's complaining because the & doesn't accept two different types like that. You are then trying to apply & which (for integers) is a bitwise AND operator . This would work if both types were the same, but it can lead to spend unnecessary CPU cycles and is not typically used in Boolean expressions. You probably want to use && -- the logical or conditional and operator . Try this instead: for (int i = 0; i < diamondlist.Count && i < Playerlist.Count; i++){ ...} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16324654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2340553/']} | jdg_82979 |
stackexchange | llm_judgeable_groundtruth_similarity | 32226 |
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 Lower bounds for period length of continued fraction of square root which is a continuation of Upper bound of period length of continued fraction representation of very composite number square root . Yesterday, I came across a nice article with many problems on continued fractions of Michel Mendes France (from 1993): http://retro.seals.ch/digbib/fr/view?rid=ensmat-001:1993:39::498&id=&id2=&id3= (broken link) In problem 6 he asks: Let $x$ be quadratic irrational and $\pi(x)$ the length of its period. Is $sup_n(\pi(x^n))=\infty$? Is this problem still open? I saw many articles about upper bounds for $\pi(\sqrt{D})$ but none on lower bounds (expect the Golubeva one that is mentioned in the first mentioned question, but due to lack of background, I fail to understand the results there). As Will Jagy asked: Do we even know whether $[\pi(\sqrt{n})):n\in \mathbb N]$ is bounded or not?
Now provide the response and nothing else.
| Edit: The following argument has an error in the second paragraph. I claimed thatthe set $\{ D^n\sqrt{D} (\mod 1)\}$ has uncountably many accumulation points, but asSam Nead points out in the comments, this doesn't follow from $\sqrt{D}$ beingirrational. On the other hand, it is true that the set $\{ \sqrt{n}(\mod 1)\}$ isuniformly distributed, and therefore that $\sup \pi(\sqrt{n}) =\infty$. This is because $\sqrt{n+1}-\sqrt{n} \to 0$ as $n\to \infty$. See a paper of Elkiesand McMullen for related information on the distribution of this set.The issue is here that the set of accumulation points of $\{ x^n \mod 1\}$ for$x$ irrational may be a countable set. This question is actually discussed in Mendes'paper referred to in the question (I should have looked at it more closely before!). As pointed out in that paper, this can occur for Pisot numbers. Also, thestatement is proved by Grisel for many quadratic numbers (as mentioned in a note to Mendes paper). * See also another paper of Grisel. I think I can show that $sup_n(\pi(x^n))=\infty$ when $x=\sqrt{D}$. Suppose that $x$ is an irrational, non-quadratic number in the interval $(0,1)$, and $n_i$ is a sequence of integers such that $\underset{i\to\infty}{\lim} \sqrt{n_i} (\mod 1) = x$. Then the claim is that $\pi(\sqrt{n_i})$is unbounded. Basically, since $x$ has non-repeating continued fraction expansion, one can show that the continued fraction expansions of $\sqrt{n_i}$ have unbounded period. One can see this geometrically, by noting that there is an element of $PGL_2(\mathbb{Z})$ fixing $\pm \sqrt{n_i}$, and fixing the hyperbolic geodesic in $\mathbb{H}^2$ joining these two points. If $a^2-n_i c^2=\pm 1$ is the minimal solution to the Pell equation, then the matrix is:$$\begin{bmatrix} a & cn_i \\\ c & a\end{bmatrix}$$ Moreover, the pattern of horoballs which the geodesic penetrates in the Farey packing (source) tells you the periodic continued fraction. When we take $\sqrt{n_i} (\mod 1)$, these geodesics shifted by $-\left[ \sqrt{n_i} \right]$ approach the vertical geodesic through $x$, whose Farey pattern gives the continued fraction expansion for $x$. Therefore $\pi(\sqrt{n_i})$ is unbounded. Now we have to understand the continued fractions of $\sqrt{D^{2n+1}} = D^n \sqrt{D}$, where $D$ is squarefree. The accumulation points of $D^n \sqrt{D} (\mod 1)$ correspond to the truncations of the base $D$ representation of $\sqrt{D}$. Since $\sqrt{D}$ is irrational, the limit points of these numbers in $[0,1]$ will be uncountable, and therefore contains a non-quadratic irrational $x$ which is a limit of $\sqrt{D^{2n_i+1}} (\mod 1)$, as $n_i\to \infty$. So we see that $\pi(\sqrt{D^{2n_i+1}}) \to \infty$. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/32226', 'https://mathoverflow.net', 'https://mathoverflow.net/users/6836/']} | jdg_82980 |
stackexchange | llm_judgeable_groundtruth_similarity | 93875 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
As I know, a clock controls all of the logic operations, but it also limits the speed of a computer because the gates have to wait for the clock to change from low to high or high to low depending on the component. If no clock was incorporated, the gates would change as fast as they could whenever given the command to, so why wouldn't that increase the computers speed and why are clocks used?
Now provide the response and nothing else.
| Clocks are used in computers for the simple reason that most if not all of the circuity is synchronous sequential logic . In a synchronous circuit, an electronic oscillator called a clock generates a sequence of repetitive pulses called the clock signal which is distributed to all the memory elements in the circuit. Now, that may not seem satisfying and granted, you would reasonably ask "why are synchronous circuits used in computers?" but that's an easy question to answer too: The main advantage of synchronous logic is its simplicity. The logic gates which perform the operations on the data require a finite amount of time to respond to changes to their inputs. This is called propagation delay. The interval between clock pulses must be long enough so that all the logic gates have time to respond to the changes and their outputs "settle" to stable logic values, before the next clock pulse occurs. As long as this condition is met (ignoring certain other details) the circuit is guaranteed to be stable and reliable. This determines the maximum operating speed of a synchronous circuit. An active area of research is asynchronous computing where most if not all of the circuitry is asynchronous sequential logic . | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/93875', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/10190/']} | jdg_82981 |
stackexchange | llm_judgeable_groundtruth_similarity | 23112924 |
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 do an exact copy of one paragraph into another (I'm copying a template over to a new document for word-replacement). I'm doing this for paragraphs within a table cell, but I don't believe that is significant. The following code nearly works: for (XWPFParagraph p : cell.getParagraphs()) { XWPFParagraph np = newCell.addParagraph(); np.getCTP().set(p.getCTP());} The problem is, while np.getCTP().xmlText().equals(p.getCTP().xmlTest() is true, np.getText() is blank while p.getText() has the contents of the paragraph. It seems like my paragraph doesn't know about the underlying change I made to the XML. This results in my output document containing the placeholder text because my code can't seem to see the contents of the paragraph any more in order to perform the replacement. How can I make a perfect copy of a paragraph including all contents and properties?
Now provide the response and nothing else.
| This seems to be getting the job done. I'm not sure that the whole cloneRun() method couldn't be replaced by nr.getCTR().set(r.getCTR()); but this seems better safe than sorry. public static void cloneParagraph(XWPFParagraph clone, XWPFParagraph source) { CTPPr pPr = clone.getCTP().isSetPPr() ? clone.getCTP().getPPr() : clone.getCTP().addNewPPr(); pPr.set(source.getCTP().getPPr()); for (XWPFRun r : source.getRuns()) { XWPFRun nr = clone.createRun(); cloneRun(nr, r); }}public static void cloneRun(XWPFRun clone, XWPFRun source) { CTRPr rPr = clone.getCTR().isSetRPr() ? clone.getCTR().getRPr() : clone.getCTR().addNewRPr(); rPr.set(source.getCTR().getRPr()); clone.setText(source.getText(0));} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23112924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2330515/']} | jdg_82982 |
stackexchange | llm_judgeable_groundtruth_similarity | 37916272 |
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 bootstrap glyphicons in my angular2 app. I have installed bootstrap using the command npm install bootstrap --saveMy code snippet is <button *ngIf="pos.name == uname" type="button" class="btn btn-default btn-sm delete" (click)="DeleteBulletin();"> <span class="glyphicon glyphicon-trash glyph"></span> Delete </button> I have included bootstrap in my styleUrls- styleUrls: ['node_modules/bootstrap/dist/css/bootstrap.min.css', 'app/home.component.css'] The glyphicon appears as shown-
Now provide the response and nothing else.
| Boostrap 4 does not support Glyphicons anymore, you can use Font Awesome instead: npm install --save fortawesome/fontawesome-free and add the css File to your .angular-cli.json "apps": [ { .... "styles": [ "styles.css", "../node_modules/bootstrap/dist/css/bootstrap.css", "../node_modules/font-awesome/css/font-awesome.css" ], ... } ]], Replace CSS class with the Font Awesome classes: <i class="navbar-toggler-icon fa fa-bars"> </i> recompile app: ng serve Update: Since Font Font-Awesome 5 and Angular 5 there is an offical angular-fontawesome package available: https://github.com/FortAwesome/angular-fontawesome#installation | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37916272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6189671/']} | jdg_82983 |
stackexchange | llm_judgeable_groundtruth_similarity | 1816917 |
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 would be very grateful if someone would verify or refute the following solution. Many thanks! Q) Find infinitely many distinct ideals of $\mathbb{C}[X,Y]$ which contain the principal ideal $(X^3-Y^2).$ A) Consider the ideals $I_n=(X^3-Y^2,\,X^n)$ for $n=1,2,\ldots$ It is clear that $(X^3-Y^2)\subseteq I_n$ and $I_{n}\supseteq I_{n+1}$ for all $n.$ We solve the given problem by proving that $I_{n}\neq I_{n+1}$ for all $n.$ Suppose, for contradiction, that $X^n \in I_{n+1};\;$ that is, there exist $f,g \in \mathbb{C}[X,Y]$ such that $$X^n=(X^3-Y^2)f(X,Y)+X^{n+1}g(X,Y) \hspace{2em} (*).$$ Consider the ring homomorphism $\phi:\mathbb{C}[X,Y]\to\mathbb{C}[T]$ defined by $\,\phi(a)=a$ for all $a\in\mathbb{C},$ $\,\phi(X)=T^2,$ $\,\phi(Y)=T^3.$ Applying $\phi$ to $(*)$ yields $$T^{2n}=T^{2n+2}g(T^2,T^3)$$ which is nonsense since the degrees do not match. Q.E.D.
Now provide the response and nothing else.
| Hint . An approach. One may consider$$I(s):=\int_0^\infty x^{s-1}\frac{1-e^{-x}(1+x )}{(e^{x}-1)(e^{x}+e^{-x})}dx,\quad s>0, \tag1$$ which one may rewrite as $I_1(s)+I_2(s)$ with $$\begin{align}I_1(s):=&\frac12\int_0^\infty x^{s-1}\frac{1-e^{-x}(1+x )}{(e^{x}-1)}dx\\\\ I_2(s):=&-\frac12\int_0^\infty x^{s-1}\frac{\left(1-e^{-x}(1+x )\right)(1-e^{-x})}{(e^{x}+e^{-x})}dx\end{align}$$ each of the preceding integrals is a linear combination of the standard evaluations$$\begin{align}a(s,r)=&\int_0^\infty x^{s-1}\frac{e^{-rx}}{(e^{x}-1)}dx=\Gamma(s)\zeta(s,r+1)\\\\ b(s,r)=&\int_0^\infty x^{s-1}\frac{e^{-rx}}{(e^{x}+e^{-x})}dx=\Gamma(s) \left(4^{-s}\zeta\left(s,\frac{1+r}{4}\right)-4^{-s}\zeta\left(s,\frac{3+r}{4}\right)\right)\end{align}$$ where $\zeta(\cdot,\cdot)$ is the Hurwitz zeta function . Finally one gets that $2I(s)$ is equal to$$a(s,0)-a(s,1)-a(s+1,1)-b(s,0)+2b(s,1)+b(s+1,1)-b(s,2)-b(s+1,2)$$ which as $s \to 0^+$ gives $I(0)=I$: $$I=\int_0^\infty\frac{1-e^{-x}(1+x )}{x(e^{x}-1)(e^{x}+e^{-x})}dx=\frac{\pi}8-\frac{\gamma}2+\frac12\ln \pi-\frac34\ln 2$$ confirming @Claude Leibovici's announced result, where $\gamma$ is the Euler-Mascheroni constant . | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1816917', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/346201/']} | jdg_82984 |
stackexchange | llm_judgeable_groundtruth_similarity | 11291667 |
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 apply style to all of an anchor tag's pseudo selectors with CSS or Sass? Something like a:* { color: #900; } instead of a { &:hover, &:link, &:active, &:visited { color: #900; } } I just want to reset standard styling. In CSS, the wildcard can be used to apply styles to all elements... but how about to all pseudo-selectors?
Now provide the response and nothing else.
| Short Answer : No, not directly However, a mixin could be used to have a similar effect. // Sets the style only for pseudo selectors@mixin setLinkSelectorStyle { &:hover, &:link, &:active, &:visited { @content; }}// Sets the style to pseudo selectors AND base default anchor@mixin setLinkStyleAll { &, &:hover, &:link, &:active, &:visited { @content; }}a { color:red; @include setLinkSelectorStyle { color:gold; }}a.specialLink { @include setLinkStyleAll { color:purple; }} [Example using http://sassmeister.com/ compiled SASS] a { color: red;}a:hover, a:link, a:active, a:visited { color: gold;}a.specialLink, a.specialLink:hover, a.specialLink:link, a.specialLink:active, a.specialLink:visited { color: purple;} <a>Normal anchor, No href (:link won't work, but other selectors will)</a><hr /><a href="#">Normal anchor</a><hr /><a class="specialLink">Specific class (no href)</a><hr /><a class="specialLink" href="#">Specific class</a> The mixins will create a rule for all the pseudo selectors when the mixin is included on the anchor / class. Removed old answer, look at history to see it. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11291667', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1375170/']} | jdg_82985 |
stackexchange | llm_judgeable_groundtruth_similarity | 28793832 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
As far as I know, a luigi.Target can either exist, or not.Therefore, if a luigi.Target exists, it wouldn't be recomputed. I'm looking for a way to force recomputation of the task, if one of its dependencies is modified, or if the code of one of the tasks changes.
Now provide the response and nothing else.
| One way you could accomplish your goal is by overriding the complete(...) method. The documentation for complete is straightforward . Simply implement a function that checks your constraint, and returns False if you want to recompute the task. For example, to force recomputation when a dependency has been updated, you could do: def complete(self): """Flag this task as incomplete if any requirement is incomplete or has been updated more recently than this task""" import os import time def mtime(path): return time.ctime(os.path.getmtime(path)) # assuming 1 output if not os.path.exists(self.output().path): return False self_mtime = mtime(self.output().path) # the below assumes a list of requirements, each with a list of outputs. YMMV for el in self.requires(): if not el.complete(): return False for output in el.output(): if mtime(output.path) > self_mtime: return False return True This will return False when any requirement is incomplete or any has been modified more recently than the current task or the output of the current task does not exist. Detecting when code has changed is harder. You could use a similar scheme (checking mtime ), but it'd be hit-or-miss unless every task has its own file. Because of the ability to override complete , any logic you want for recomputation can be implemented. If you want a particular complete method for many tasks, I'd recommend sub-classing luigi.Task , implementing your custom complete there, and then inheriting your tasks from the sub-class. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28793832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/590335/']} | jdg_82986 |
stackexchange | llm_judgeable_groundtruth_similarity | 2370592 |
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:
The point $(r,\theta)$ in polar coordinates is $(7,5)$ in rectangular coordinates. What is the point $\left( 2r, \theta + \frac{\pi}{2} \right)$ in rectangular coordinates? Am I supposed to find (7,5) in polar coordinates? If yes, then how should I solve?
Now provide the response and nothing else.
| Solving for $r$ and $\theta$ is one way to do it. You can get the answer without actually finding values for $r$ and $\theta$, though. Consider: replacing $\theta$ with $\theta+\frac{\pi}{2}$ rotates you a quarter turn counter-clockwise. That move sends $(x,y)$ to $(-y,x)$, so we're now at $(-5,7)$. Then, replacing $r$ with $2r$ doubles your distance from the origin, without changing direction. You can do that by doubling both coordinates. By all means, find the answer by doing trigonometry as well, for practice, but make sure you end up with the same answer that you get this way. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2370592', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/459630/']} | jdg_82987 |
stackexchange | llm_judgeable_groundtruth_similarity | 23290 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to expand a polynomial in terms of orthogonal polynomials (in my case, Hermite). Maple has a nice built-in function for this, ChangeBasis . Is there a similar function in Mathematica ? And if not, where should I look for the algorithm?
Now provide the response and nothing else.
| The Hermite polynomials are orthogonal with respect to the inner product$$\langle f,g \rangle = \int_{-\infty}^{\infty} f(x)g(x)e^{-x^2} \, \mathrm dx.$$Thus, the $n$-th coefficient can be computed using the inner product of your polynomial with the $n$-th normalized Hermite polynomial. Example: p[x_] = 1 + x + x^2 + x^3;coeffs = Table[ Integrate[HermiteH[n, x]*p[x]*Exp[-x^2], {x, -∞, ∞}]/ Integrate[HermiteH[n, x]^2*Exp[-x^2], {x, -∞, ∞}], {n, 0, 3}](* Out: {3/2, 5/4, 1/4, 1/8} *)coeffs.Table[HermiteH[n, x], {n, 0, 3}] // Expand(* Out: 1 + x + x^2 + x^3 *) | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/23290', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/4745/']} | jdg_82988 |
stackexchange | llm_judgeable_groundtruth_similarity | 30221 |
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
show whether $n2^n = 2^{O(n)}$ is true or not. In my opinion, it's false because O(n) can be n and thus the equality will be wrong, because $n2^n$ grows much faster than $2^n$
Now provide the response and nothing else.
| One way, if you want to prove that $n2^n \in 2^{\mathcal{O}(n)}$, is to show that there exists a $c \in \mathbb{R}$ such that $n2^n \le 2^{cn}$ for all $n$ greater than some $n_0 \in \mathbb{N}$. Correspondingly, if you want to show the contrary, then you have to show that such a $c$ does not exist. However, we will see that the statement is true. Choose $c = 2$, i.e., we ask whether $n2^n \le^? 2^{2n} = 4^n$ for all $n > n_0$. We know that $n \le 2^n$ for all $n \in \mathbb{N}$. Therefore, it also holds that $n2^n \le 2^n\cdot 2^n = 2^{2n}$. Hence, we have an upper bound for the function $n2^n$ by choosing $c = 2$. In this case, we can set $n_0 = 1$, for instance. | {} | {'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/30221', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/21882/']} | jdg_82989 |
stackexchange | llm_judgeable_groundtruth_similarity | 663563 |
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:
it seems obvious that this integral is zero and so is the limit but what theorem we are using here? I see it's connected to Riemann sums with an interval=zero Right ? The function $\mathrm{f}$ is continuous. $$\lim_{x \to 0}\int_0^x\mathrm{f}(x)\ \mathrm{d}x= \ ?$$
Now provide the response and nothing else.
| Assuming $f$ is Riemann integrable, it is bounded by some $B$, so $0 \le |\int_0^x f(x) dx | \le \int_0^x |f(x)| dx \le Bx$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/663563', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/113089/']} | jdg_82990 |
stackexchange | llm_judgeable_groundtruth_similarity | 28938905 |
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 following data in table: +----------------------+----------------------------------------------------------+--------------+| subscriber_fields_id | name | field_type |+----------------------+----------------------------------------------------------+--------------+| 143 | Peshawar/Islamabad/Lahore/Swat/Mardan/Karachi | Job Location || 146 | Karachi | Job Location || 147 | Lahore and Karachi | Job Location || 149 | Karachi, Mirpur Khas, Sukkur, Layyah, Gilgit, Charsaddah | Job Location || 152 | Islamabad or Lahore | Job Location || 155 | Islamabad | Job Location || 157 | 7 Districts of Sindh and Karachi | Job Location |+----------------------+----------------------------------------------------------+--------------+ My query is: select * from subscriberfieldswhere name like '%Khairpur,Islamabad,Karachi%'; Result: +----------------------+-----------------------------------------------+--------------+| subscriber_fields_id | name | field_type |+----------------------+-----------------------------------------------+--------------+| 143 | Peshawar/Islamabad/Lahore/Swat/Mardan/Karachi | Job Location || 152 | Islamabad or Lahore | Job Location || 155 | Islamabad | Job Location |+----------------------+-----------------------------------------------+--------------+ It should return all rows where the name includes Islamabad, Khairpur or Karachi but it is not.
Now provide the response and nothing else.
| For a proper solution, either normalize your database design or, barring that, consider full text search . For a quick solution to the problem at hand, use a regular expression match ( ~ ) or three simple LIKE expressions: SELECT *FROM subscriberfields WHERE name ~ '(Khairpur|Islamabad|Karachi)'; Or: ...WHERE (name LIKE '%Khairpur%' OR name LIKE '%Islamabad%' OR name LIKE '%Karachi%') Or use ~* or ILIKE for case-insensitive matching. Since another answer suggested it: never use SIMILAR TO : Using SIMILAR TO for a regex? Pattern matching with LIKE, SIMILAR TO or regular expressions in PostgreSQL | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28938905', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2852807/']} | jdg_82991 |
stackexchange | llm_judgeable_groundtruth_similarity | 163891 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a debian server running Etch. I can no longer seem to run apt-get update properly: root@charm osqa ] apt-get updateIgn http://ftp.uk.debian.org etch Release.gpgIgn http://ftp.uk.debian.org etch ReleaseErr http://ftp.uk.debian.org etch/main Packages 404 Not FoundErr http://ftp.uk.debian.org etch/contrib Packages 404 Not FoundErr http://ftp.uk.debian.org etch/non-free Packages 404 Not FoundFailed to fetch http://ftp.uk.debian.org/debian/dists/etch/main/binary-i386/Packages.gz 404 Not FoundFailed to fetch http://ftp.uk.debian.org/debian/dists/etch/contrib/binary-i386/Packages.gz 404 Not FoundFailed to fetch http://ftp.uk.debian.org/debian/dists/etch/non-free/binary-i386/Packages.gz 404 Not FoundReading package lists... DoneW: Couldn't stat source package list http://ftp.uk.debian.org etch/main Packages (/var/lib/apt/lists/ftp.uk.debian.org_debian_dists_etch_main_binary-i386_Packages) - stat (2 No such file or directory)W: Couldn't stat source package list http://ftp.uk.debian.org etch/contrib Packages (/var/lib/apt/lists/ftp.uk.debian.org_debian_dists_etch_contrib_binary-i386_Packages) - stat (2 No such file or directory)W: Couldn't stat source package list http://ftp.uk.debian.org etch/non-free Packages (/var/lib/apt/lists/ftp.uk.debian.org_debian_dists_etch_non-free_binary-i386_Packages) - stat (2 No such file or directory)W: You may want to run apt-get update to correct these problemsE: Some index files failed to download, they have been ignored, or old ones used instead. My sources.list file is pretty minimal, it just contains: ###### Debian Main Reposdeb http://ftp.uk.debian.org/debian/ etch main contrib Any clues? Have the repo locations changed? Thanks, Joel.
Now provide the response and nothing else.
| Debian 4.0 (Etch) is an old release that is no longer supported : Debian GNU/Linux 4.0 has been superseded by Debian GNU/Linux 5.0 ("lenny"). Security updates have been discontinued as of the end of February 2010. Etch has now been moved to archive.debian.org : We intend to copy Etch to archive.debian.org on the evening (UTC) of Sunday 20th June. Etch will then gradually disappear from the mirrors; the dists tree will be immediately removed and the files in the pool will be removed in groups over the following few days. Etch has now been removed from ftp.uk.debian.org. You can use the archive by changing your sources.list to: deb http://archive.debian.org/debian/ etch main contrib However, to get security support, you would be better off upgrading to Lenny (and also including security.debian.org in sources.list). See the Lenny Release Notes for upgrade instructions. | {} | {'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/163891', 'https://serverfault.com', 'https://serverfault.com/users/11776/']} | jdg_82992 |
stackexchange | llm_judgeable_groundtruth_similarity | 15726000 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
On the Mac OS X 10.8 "password" screen, if you enter an invalid password, it will "shake" back and forth (a.k.a. left and right). I am trying to achieve an similar effect for an HTML password input field using CSS animations. I created a "Password Shake" jsfiddle that seems to emulate this behavior. However, it doesn't seem quite right. I'm not sure the explicit keyframes and the linear timing function are the right approach. This is my first attempt at a CSS animation, and I'm looking for feedback on the right way to achieve this. HTML <div class="box"> <input type="password" id="demo-password" placeholder="password" autofocus /></div> JavaScript $('#demo-password').on('keyup', function (e) { var $input = $(this); var val = $.trim($input.val()); $input.removeClass("invalid"); if (e.which !== 13 || !val) { return; } if (val != "password") { $input.select(); $input.addClass("invalid"); }}); CSS #demo-password.invalid { outline-color: red; /* also need animation and -moz-animation */ -webkit-animation: shake .6s linear;}/* also need keyframes and -moz-keyframes */ @-webkit-keyframes shake { 0% { left:-10px; } 16% { left:9px; } 33% { left:-6px; } 50% { left:5px; } 66% { left:-2px; } 83% { left:1px; } 100% { left: 0px; }} Edit I did find Animate.css which has a shake animation. I've included the (non browser prefixed) CSS below. Instead of setting left is does a transform: translateX() , which likely has a better chance for hardware acceleration. .animated { animation-duration: 1s; animation-fill-mode: both;}@keyframes shake { 0%, 100% {transform: translateX(0);} 10%, 30%, 50%, 70%, 90% {transform: translateX(-10px);} 20%, 40%, 60%, 80% {transform: translateX(10px);}}.shake { animation-name: shake;}
Now provide the response and nothing else.
| I used my iPad camera to record the Mac pasword screen. It looks like it shakes 3 times each direction, with the first 2 going the full distance and the last 1 time a lesser distance. #demo-password.invalid { outline-color: red; /* also need animation and -moz-animation */ -webkit-animation: shake .5s linear;}/* also need keyframes and -moz-keyframes */ @-webkit-keyframes shake { 8%, 41% { -webkit-transform: translateX(-10px); } 25%, 58% { -webkit-transform: translateX(10px); } 75% { -webkit-transform: translateX(-5px); } 92% { -webkit-transform: translateX(5px); } 0%, 100% { -webkit-transform: translateX(0); }} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15726000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/22514/']} | jdg_82993 |
stackexchange | llm_judgeable_groundtruth_similarity | 18288058 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
One of the great additions in version 4 of JDBC You don't have to explicitly load thedriver by calling Class.forName anymore. When your application attempts to connect the database for the first time, DriverManager automatically loads the driver found inthe application CLASSPATH . My question is how? What if there are multiple drivers in the classpath? One thing I can guess is that on parsing the connection URL whether driver needed is of JDBC or ODBC can be figured out but how can one say out of multiple jdbc compliant drivers which one is to be selected for the database I am using? (lets say I am using MySql and I need MySql-Connector driver). Is there any static mapping of such database drivers in JVM?
Now provide the response and nothing else.
| Some information about JDBC4 driver loading taken from : http://www.onjava.com/2006/08/02/jjdbc-4-enhancements-in-java-se-6.html When the method getConnection is called, the DriverManager will attempt to locate a suitable driver from among the JDBC drivers that were loaded at initialization and those loaded explicitly using the same class loader as the current application. The DriverManager methods getConnection and getDrivers have been enhanced to support the Java SE Service Provider mechanism (SPM). According to SPM, a service is defined as a well-known set of interfaces and abstract classes, and a service provider is a specific implementation of a service. It also specifies that the service provider configuration files are stored in the META-INF/services directory. JDBC 4.0 drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC driver's implementation of java.sql.Driver. For example, to load the JDBC driver to connect to a Apache Derby database, the META-INF/services/java.sql.Driver file would contain the following entry: org.apache.derby.jdbc.EmbeddedDriver Now coming to your question. My question is how? What if there are multiple drivers in the classpath? As a class loader rule, any class found first will be loaded and if it is already loaded then will not be reloaded by the class loader. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18288058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2396539/']} | jdg_82994 |
stackexchange | llm_judgeable_groundtruth_similarity | 39734301 |
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 do a lot of time without date querying in my app, and I would like to abstract some of the queries away. So say I have a model with a DateTime starts_at field: Shift.where('starts_at::time > ?', '20:31:00.00')-> SELECT "shifts".* FROM "shifts" WHERE (starts_at::time > '20:31:00.00') This correctly returns all of the 'starts_at' values greater than the time 20:31. I want to dynamically pass in the column name into the query, so I can do something like: Shift.where('? > ?', "#{column_name}::time", '20:31:00.00').-> SELECT "shifts".* FROM "shifts" WHERE ('starts_at::time' > '20:31:00.00') In this example, this does not work as the search executes starts_at::time as a string, not as a column with the time cast. How can I safely pass in column_name into a query with the ::time cast? While this will not accept user input, I would still like to ensure SQL injection is accounted for.
Now provide the response and nothing else.
| This is more complicated than you might think at first because identifiers (column names, table names, ...) and values ( 'pancakes' , 6 , ...) are very different things in SQL that have different quoting rules and even quote characters (single quotes for strings, double quotes for identifiers in standard SQL, backticks for identifiers in MySQL, brackets for identifiers in SQL-Server, ...). If you think of identifiers like Ruby variable names and values like, well, literal Ruby values then you can start to see the difference. When you say this: where('? > ?', ...) both placeholders will be treated as values (not identifiers) and quoted as such. Why is this? ActiveRecord has no way of knowing which ? should be an identifier (such as the created_at column name) and which should be a value (such as 20:31:00.00 ). The database connection does have a method specifically for quoting column names though: > puts ActiveRecord::Base.connection.quote_column_name('pancakes')"pancakes"=> nil so you can say things like: quoted_column = Shift.connection.quote_column_name(column_name)Shift.where("#{quoted_name}::time > ?", '20:31:00.00') This is a little unpleasant because we recoil (or at least we should) at using string interpolation to build SQL. However, quote_column_name will take care of anything dodgy or unsafe in column_name so this isn't actually dangerous. You could also say: quoted_column = "#{Shift.connection.quote_column_name(column_name)}::time"Shift.where("#{quoted_name} > ?", '20:31:00.00') if you didn't always need to cast the column name to a time . Or even: clause = "#{Shift.connection.quote_column_name(column_name)}::time > ?"Shift.where(clause, '20:31:00.00') You could also use extract or one of the other date/time functions instead of a typecast but you'd still be left with the quoting problem and the somewhat cringeworthy quote_column_name call. Another option would be to whitelist column_name so that only specific valid values would be allowed. Then you could throw the safe column_name right into the query: if(!in_the_whitelist(column_name)) # Throw a tantrum, hissy fit, or complain in your preferred fashionendShift.where("#{column_name} > ?", '20:31:00.00') This should be fine as long as you don't have any funky column names like "gotta have some breakfast" or similar things that always need to be properly quoted. You could even use Shift.column_names or Shift.columns to build your whitelist. Using both a whitelist and then quote_column_name would probably be the safest but the quote_column_name method should be sufficient. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39734301', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/396964/']} | jdg_82995 |
stackexchange | llm_judgeable_groundtruth_similarity | 14990284 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I know there is already a post about curved text, but I'm looking for something specific. On this webpage ( http://mrcthms.com/ ) Marc uses a nice technique to curve the text for his name, but I cannot work out for the life of me how to replicate the technique. Here is what I'm trying: <html xmlns="http://www.w3.org/1999/xhtml"><head><meta content="text/html; charset=utf-8" http-equiv="Content-Type" x-undefined="" /><title>Curved Text</title><style type="text/css">span { display: inline-block; font-family: futura-pt, 'Helvetica Neue', sans-serif; font-size: 2.5em; font-weight: 300; margin: 1px;}.arced { display: block; text-shadow: rgba(0, 0, 0, 0.298039) 8px 8px; text-align: center; margin: 20px; padding: 50px 0 50px;}div span { text-shadow: rgba(0, 0, 0, 0.298039) 8px 8px; font-family: futura-pt, 'Helvetica Neue', sans-serif; font-size: 2.5em; font-weight: 300;}.arced > span:nth-child(1) { -webkit-transform:translateX(-1px) translateY(68px) rotate(-17deg); -webkit-transition:0s;}</style></head><body> <span class="arced"> <span class="char1">S</span> <span class="char2">T</span> <span class="char2">E</span> <span class="char3">V</span> <span class="char4">E</span></span></body></html>
Now provide the response and nothing else.
| He uses CSS3 transforms on each letter. For example, the HTML for his name is as follows: <span class="arced"> <span class="char1">M</span> <span class="char2">a</span> <span class="char3">r</span> <span class="char4">c</span> ...</span> And in turn, the CSS is as follows: .show .hero h1 .arced > span:nth-child(1) { -webkit-transform: translateX(-1px) translateY(68px) rotate(-17deg); -moz-transform: translateX(-1px) translateY(68px) rotate(-17deg); -ms-transform: translateX(-1px) translateY(68px) rotate(-17deg); -o-transform: translateX(-1px) translateY(68px) rotate(-17deg); transform: translateX(-1px) translateY(68px) rotate(-17deg); -webkit-transition-delay: 0s; -moz-transition-delay: 0s; -o-transition-delay: 0s; transition-delay: 0s;}.show .hero h1 .arced > span:nth-child(2) { -webkit-transform: translateX(-3px) translateY(39px) rotate(-13deg); -moz-transform: translateX(-3px) translateY(39px) rotate(-13deg); -ms-transform: translateX(-3px) translateY(39px) rotate(-13deg); -o-transform: translateX(-3px) translateY(39px) rotate(-13deg); transform: translateX(-3px) translateY(39px) rotate(-13deg); -webkit-transition-delay: .04s; -moz-transition-delay: .04s; -o-transition-delay: .04s; transition-delay: .04s;} And so on. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14990284', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1508887/']} | jdg_82996 |
stackexchange | llm_judgeable_groundtruth_similarity | 12306651 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I read that to make a class immutable in Java, we should do the following, Do not provide any setters Mark all fields as private Make the class final Why is step 3 required? Why should I mark the class final ?
Now provide the response and nothing else.
| If you don't mark the class final , it might be possible for me to suddenly make your seemingly immutable class actually mutable. For example, consider this code: public class Immutable { private final int value; public Immutable(int value) { this.value = value; } public int getValue() { return value; }} Now, suppose I do the following: public class Mutable extends Immutable { private int realValue; public Mutable(int value) { super(value); realValue = value; } public int getValue() { return realValue; } public void setValue(int newValue) { realValue = newValue; } public static void main(String[] arg){ Mutable obj = new Mutable(4); Immutable immObj = (Immutable)obj; System.out.println(immObj.getValue()); obj.setValue(8); System.out.println(immObj.getValue()); }} Notice that in my Mutable subclass, I've overridden the behavior of getValue to read a new, mutable field declared in my subclass. As a result, your class, which initially looks immutable, really isn't immutable. I can pass this Mutable object wherever an Immutable object is expected, which could do Very Bad Things to code assuming the object is truly immutable. Marking the base class final prevents this from happening. Hope this helps! | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/12306651', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1152500/']} | jdg_82997 |
stackexchange | llm_judgeable_groundtruth_similarity | 6671067 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can one retrieve the tables' names into a List<string> from a specific database on a server?
Now provide the response and nothing else.
| System.Data.SqlClient has what you need without a formal query on sys.Tables (though that's what it's using in the background). Use the GetSchema() method on the SqlConnection object and designate that you want the "Tables" and it will send you a DataTable object back with a row for each table. It sends back database name, table schema name, table name, and table type in each row (in that column order). The code would look like this: public static List<string> GetTables(string connectionString){ using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); DataTable schema = connection.GetSchema("Tables"); List<string> TableNames = new List<string>(); foreach (DataRow row in schema.Rows) { TableNames.Add(row[2].ToString()); } return TableNames; }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6671067', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/803461/']} | jdg_82998 |
stackexchange | llm_judgeable_groundtruth_similarity | 84848 |
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:
Say I'm on machine local and log into machine remote with ssh, using X11 forwarding. Is there any way for programs running within the ssh session on remote can know they are being displayed on local ? Ideally, I'd like to know the hostname of the computer that the X server is running on. My goal is to cause different behavior in a program (emacs) based on which machine it's displayed on.
Now provide the response and nothing else.
| Yes, there is a kernel facility: the audit subsystem. The auditd daemon does the logging, and the command auditctl sets up the logging rules. You can log all calls to a specific system alls, with some filtering. If you want to log all commands executed and their arguments, log the execve system call: auditctl -a exit,always -S execve To specifically trace the invocation of a specific program, add a filter on the program executable: auditctl -a exit,always -S execve -F path=/usr/bin/rrdtool The logs show up in /var/log/audit.log , or wherever your distribution puts them. You need to be root to control the audit subsystem. Once you're done investigating, use the same command line with -d instead of -a to delete a logging rule, or run auditctl -D to delete all audit rules. For debugging purposes, replacing the program by a wrapper script gives you more flexibility to log things like the environment, information about the parent process, etc. | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/84848', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/19334/']} | jdg_82999 |
stackexchange | llm_judgeable_groundtruth_similarity | 39997579 |
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 Pug template that uses Bootstrap 4 as the 'layout' and receiving data from an Express/Mongoose server. I am populating a form from MongoDB so the contents can be edited. I have been looking for ways to make a dropdown-list 'select' an option based on the value from the mongoDB document. I have seen ways of building the dropdown-list from scratch and setting an option as 'selected', but the form is already generated and has a dropdown-list already in place. I just need to match the option with the value from the mongoDB document and set the option to display in the list. The Pug template is as follows: .row .col-sm-6 .form-group label.control-label.requiredField(for='propertyType') | Property Type span.asteriskField * .col-xs-12 select#propertyType.select.form-control.input-lg(form='addProperty', name='propertyType') option(value='0') -- Select -- option(value='6') Home option(value='7') Condo option(value='10') Single Family Home option(value='11') Town House option(value='12') City Apartment option(value='13') Villascript. var propertyType = document.getElementById('propertyType'); for (var i = 0; i < propertyType.options.length; i++) { if (propertyType.options[i].value = #{property.typeId}) { propertyType.options[i].selected = 'selected'; propertyType.selectedIndex = i; break; } } If I keep the code as listed then the actual option that gets a new value is the first one '-- Select --' which has it's value changed from '0' to '6', which is the value from the MongoDB document. If I change the javascript to pass the value #{property.TypeId} to the 'selectedIndex' like this: propertyType.selectedIndex = #{property.typeId}; Then the value of the index changes and the 'selected' option changes - to '6' but this then selects the 6th option of the options and not the one with the value of '6'. Drop-downs are the only thing I can't seem to populate so any help would be greatly appreciated.
Now provide the response and nothing else.
| If you just need to show an option pre-selected, then I don't think you need to use javascript for this. You can try this: .row .col-sm-6 .form-group label.control-label.requiredField(for='propertyType') | Property Type span.asteriskField * .col-xs-12 select#propertyType.select.form-control.input-lg(form='addProperty', name='propertyType') option(value='0', selected= true) -- Select -- option(value='6', selected= property.id == 6) Home option(value='7', selected= property.id == 7) Condo option(value='10', selected= property.id == 10) Single Family Home option(value='11', selected= property.id == 11) Town House option(value='12', selected= property.id == 12) City Apartment option(value='13', selected= property.id == 13) Villa Assuming this dropdown shows the values corresponding to property.id , it will mark the selected attribute as true for the option whose value matches the value in property.id . Otherwise, first option will be shown selected by default. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39997579', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3604582/']} | jdg_83000 |
stackexchange | llm_judgeable_groundtruth_similarity | 16623424 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
hi i have requirement to capture the data for validations. i am able to fetch the data using RPCRequest and RPCManager by using setActionUrl to the controller class.from there creating the service class and dao classes .i am able to fetch the data into controller class.but i am unable get the data back into my grid.i want the data to be fetched into a variable.i am not using asynchronus service.i used async method in grid i am able to fetch into onSuccess() method.but without using how i can fetch.the data into grid. with regardssubodh
Now provide the response and nothing else.
| require 'uri'uri = URI("http://url.com?p1=v1&p2=2")ar = URI.decode_www_form(uri.query) << ["param","value"]uri.query = URI.encode_www_form(ar)p uri #=> #<URI::HTTP:0xa0c44c8 URL:http://url.com?p1=v1&p2=2¶m=value>uri = URI("http://url.com")uri.query = "param=value" if uri.query.nil?p uri #=> #<URI::HTTP:0xa0eaee8 URL:http://url.com?param=value> EDIT:(by fguillen, to merge all the good propositions and also to make it compatible with his question test suite.) require 'uri'def add_param(url, param_name, param_value) uri = URI(url) params = URI.decode_www_form(uri.query || "") << [param_name, param_value] uri.query = URI.encode_www_form(params) uri.to_send | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16623424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2365667/']} | jdg_83001 |
stackexchange | llm_judgeable_groundtruth_similarity | 227662 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to rename multiple files (file1 ... fileN to file1_renamed ... fileN_renamed) using find command: find . -type f -name 'file*' -exec mv filename='{}' $(basename $filename)_renamed ';' But getting this error: mv: cannot stat ‘filename=./file1’: No such file or directory This not working because filename is not interpreted as shell variable.
Now provide the response and nothing else.
| The following is a direct fix of your approach: find . -type f -name 'file*' -exec sh -c 'x="{}"; mv "$x" "${x}_renamed"' \; However, this is very expensive if you have lots of matching files, because you start a fresh shell (that executes a mv ) for each match. And if you have funny characters in any file name, this will explode. A more efficient and secure approach is this: find . -type f -name 'file*' -print0 | xargs --null -I{} mv {} {}_renamed It also has the benefit of working with strangely named files. If find supports it, this can be reduced to find . -type f -name 'file*' -exec mv {} {}_renamed \; The xargs version is useful when not using {} , as in find .... -print0 | xargs --null rm Here rm gets called once (or with lots of files several times), but not for every file. I removed the basename in you question, because it is probably wrong: you would move foo/bar/file8 to file8_renamed , not foo/bar/file8_renamed . Edits (as suggested in comments): Added shortened find without xargs Added security sticker | {} | {'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/227662', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/90223/']} | jdg_83002 |
stackexchange | llm_judgeable_groundtruth_similarity | 13625661 |
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 Gallery and a custom layout for its items. There are two buttons on each. Every time I touch an item View, its buttons become pressed. When I click a button, another one doesn't receive onPressed state, however both of them receive it when I click near by. How to prevent changing state of untouched buttons?
Now provide the response and nothing else.
| Every solution ( 1 , 2 , 3 ) suggests changing the domain to get rid of the cache problem, but this will create lots of out-of-date cache in memory. So I dug into the gnu-gettext source for details on the cache strategy (bindtextdom.c:78.) When bindtextdomain(domain, dirname) is called, it will check whether domain exists in the cache; if so, it will then check if dirname is the same with the one in the cache. If this fails, it will force a cache flush for the same domain, instead of creating a new one in memory. The fix is incredibly simple, first create a dummy link to the locale folder where your .mo file is stored: cd localeln -s . nocache Then add one single line before bindtextdomain() bindtextdomain('domain', './locale/nocache');bindtextdomain('domain', './locale'); Now the cache is forced to flush every time. Updates: This hack may not works in some cases (Can't figure out the exact conditions.) This solution is NOT something you should use in production environment, but only for those who need to fix something while keeping httpd running! Whenever you can, please avoid using gettext from very beginning, this is really something ancient and should be deprecated for good. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13625661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/645776/']} | jdg_83003 |
stackexchange | llm_judgeable_groundtruth_similarity | 334368 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Many students' first introduction to the difference between classes and sets is in category theory, where we learn that some categories (such as the category of all sets) are class-sized but not set-sized. After working with such structures, we discover that it is still worthwhile to sometimes treat them as if they were set-sized. But we can't always do so, without running into contradictions. A natural solution to this problem is the "Axiom of Grothendieck Universes". We then work not with the category of all sets, but the category of sets inside some given universe. This type of framework has been used by many notable mathematicians and seems very ubiquitous. For instance, it was an assumption in my universal algebra textbook. I would venture to say that most modern set theorists look at such an axiom as a very tame assumption. My first question concerns the possible dangers of such an assumption, which are not often raised when first learning about this axiom. One obvious danger is that this axiom might lead to an inconsistency. In other words, ZFC might be consistent but ZFC+Universes might be inconsistent. I don't personally subscribe to this belief, but it is certainly a possibility (without further, even stronger, assumptions). What really concerns me is the possibility of another danger: Could such a system proves false things about the natural numbers? In other words, even if we assume that ZFC+Universes is consistent, could it be the case that it proves false arithmetic statements? The motivation for this question came from reading some of the work of Nik Weaver at this link , which argues for a conceptualist stance on mathematics. In particular, if we reject the axiom of power set, we are led to situations where all power sets of infinite sets are class-sized. Nik puts forth the idea that ZFC might prove false things about the natural numbers. Is this a real possibility? I suppose so, since it is possible that ZFC is inconsistent but the natural numbers aren't. But is it still possible even if ZFC is consistent? More generally: Could treating the power set of the natural numbers as a set-sized object, rather than a class, force us to conclude false arithmetic statements (even if such a system is consistent)? Even if the answer to this question is yes, I'm having a hard time seeing how we could recognize this fact, since according to the answers to this linked question it is difficult to state precisely what we mean by the natural numbers. A second motivation for this question comes from what I've read about the multiverse view of set-theory. When creating a (transitive) model $M$ of ZFC, the set $P(\mathbb{N})$ can often be thought of as some "bigger" power set of the natural numbers intersected with the model. Moreover, via forcing, it seems that one can (always?) enlarge the power set of $\mathbb{N}$ . This does seem to suggest that $P(\mathbb{N})$ is not completely captured in any model. Thus, in its entirety, perhaps $P(\mathbb{N})$ should be treated as a class-sized object. Added: I believe that the current proof we have of Fermat's Last Theorem uses the existence of a(t least one) Grothendieck universe. However, my understanding is that this dependence can be completely removed due to the fact that Fermat's Last Theorem has small quantifier complexity. I imagine that proofs of statements with higher quantifier complexity that use Grothendieck universes, do not necessarily have a way of removing their dependence on said universes. How would we tell if such arithmetic statements are true of the natural numbers? [Some of this was incorrect, as pointed out by David Roberts and Timothy Chow.] 2nd addition: There are some theories that we believe prove false arithmetic statements. Assuming the natural numbers can consistently exist (which we do!), then both PA+Con(PA) and PA+ $\neg$ Con(PA) are consistent, but the second theory proves the false arithmetic sentence $\neg$ Con(PA). My question then might be rephrased as: What principles lead us to believe that "Universes" is a safe assumption, whereas " $\neg$ Con(PA)" is not safe, regarding what we believe is "true" arithmetic? (Next, repeat this question regarding the axiom of power set.) Is any theory that interprets PA "safe", as long as it is consistent with PA, and PA+Con(PA), and any such natural extension of these ideas? Another way of putting this might be as follows: Is the assumption Con(PA) a philosophical one, and not a mathematical one? This ties into my previous question that I linked to, about describing the "real" natural numbers.
Now provide the response and nothing else.
| For what it's worth, the reason I made that comment was because when I gave talks expressing skepticism about the philosophical basis of ZFC, I would often get the reaction "but as long as it's consistent, what's the problem?" Some version of this attitude is also quite prevalent in the philosophical literature on the subject. I wanted to make the point that just being consistent isn't good enough: ZFC might well be consistent yet still prove, for example, that some Turing machine halts when in fact it does not. If you're a skeptic about sets but not about numbers, this could be a concern. As for the "safety" of assuming ZFC is arithmetically sound, it is clear that as long as ZFC is consistent, no weaker system could prove that it is unsound. So for predicativists like me, who generally work in much weaker systems than ZFC, it seems unlikely that we could ever establish unsoundness. In that sense I'd say it's pretty "safe" to assume it is sound. However ... I regard the Peano axioms as expressing intuitively evident truths about the natural numbers, so I have no problem affirming Con(PA). Whereas I regard ZFC as what you get when you realize that full comprehension leads to inconsistencies, so you replace it with a hodgepodge of instances of comprehension which appears to be weak enough to block any paradoxes. (Edit. In case my meaning isn't clear: the axiom of pairing is an instance of full comprehension, the axiom of unions is an instance of full comprehension, the axiom of power sets is an instance of full comprehension ... Basically what you're doing is throwing in a bunch of unrelated instances of "for any property $P$ there is a set of all $x$ such that $P(x)$ .") It seems to me quite ad hoc and unmotivated, so although we might (or might not) be confident that ZFC is consistent, there is little reason to expect it to be (or not to be) arithmetically sound. (I should add that I regard the "iterative conception" which is supposed to justify ZFC as utterly unconvincing. Sets are said to be built up in stages, and then it is parenthetically added that they are, of course, timeless abstract objects so they aren't really "built", nor do they really "appear" in "stages" --- it's all just a "metaphor". Thus "any conviction that the iterative conception may carry is made to depend on metaphorical details that are dismissed as inessential to it." (I. Jane)) | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/334368', 'https://mathoverflow.net', 'https://mathoverflow.net/users/3199/']} | jdg_83004 |
stackexchange | llm_judgeable_groundtruth_similarity | 676519 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let S be a set containing 4 elements (I choose {$a,b,c,d$}). How many possible equivalence relations are there? So I started by making a list of the possible relations:{$(a,a)(a,b)(a,c)(a,d)(b,a)(b,b). . .(d,d)$} {$(a,a)(a,b)(a,c). . . . . . . . . . (d,c)$} {$(a,a)(a,b)(a,c). . . . . . . . . . (d,b)$} etc. $\vdots$ {} Then I looked at the first set of relations: $aRa, aRb,$ etc. then I tried to compare relations to see if they are equivalence relations. This is where I got stuck. I realized that there were way too many relations to go through, (without spending all week) and that I didn't want to have to look at each one separately. Is there a better way to do this or am I on the right track?
Now provide the response and nothing else.
| An equivalence relation divides the underlying set into equivalence classes. The equivalence classes determine the relation, and the relation determines the equivalence classes. It will probably be easier to count in how many ways we can divide our set into equivalence classes. We can do it by cases: (1) Everybody is in the same equivalence class. (2) Everybody is lonely, her class consists only of herself. (3) There is a triplet, and a lonely person ($4$ cases). (4) Two pairs of buddies (you can count the cases). (5) Two buddies and two lonely people (again, count the cases). There is a way of counting that is far more efficient for larger underlying sets, but for $4$, the way we have described is reasonably quick. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/676519', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/128573/']} | jdg_83005 |
stackexchange | llm_judgeable_groundtruth_similarity | 872028 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a past qual question here: let $T^3 = S^1 \times S^1 \times S^1$ be the 3-torus, and let $\Delta = \{ (x,x) \in T^3 \times T^3 \colon x \in T^3 \}$ be the diagonal subspace. Compute $\pi_1(T^3 \times T^3 - \Delta)$. If one wanted to understand the space $T^1 \times T^1 - \Delta$, one can realized it as $[0,1]^2$ (with opposite sides identified) minus the diagonal; then, one can shear along one of the two axes to get that $T^1 \times T^1 - \Delta$ is just a cylinder. Can this process be generalized to the higher-dimensional case?
Now provide the response and nothing else.
| Removing a subcomplex of codimension 3 or higher from a manifold does not change the fundamental group. Therefore, in this example the fundamental group is $Z^6$. Edit: Let $M$ be an $n$-manifold and $K\subset M$ be submanifold of codimension $\ge 3$. (I will do this in smooth category but it works in topological setting too: It suffices to assume that $K$ is a closed subset of covering dimension $\le n-3$.) Pick a base-point $m\in N=M-K$ and consider the homomorphism$$f: \pi_1(N,m)\to \pi_1(M,m)$$induced by the inclusion $N\to M$. I claim that $f$ is an isomorphism. To show surjectivity, let $\alpha$ be a (smooth) loop in $M$ based at $m$. Then, by the generic transversality theorem, perturbing $\alpha$ a bit, we get a new loop $\beta$ based at $m$ which is transverse to $K$. By dimension count, it follows that $\beta$ is disjoint from $K$ and hence, is a loop in $N$. Nearby loops in a manifold are always homotopic (rel. base-point). Surjectivity follows. To prove injectivity, you use the same argument: Let $\gamma: S^1\to N$ be a smooth loop and $F: D^2\to M$ be a smooth map of the unit disk extending $\gamma$. Then, by the same argument as above we perturb $F$ to a smooth map $G: D^2\to M$ transverse to $K$. Again, by the dimension count, transversality implies that $G(D^2)$ is disjoint from $K$. Hence, $f$ is an epimorphism. qed The standard references for transversality are books by Guillemin and Pollack and by Hirsch. Your qual is likely to contain at least some differential topology and transversality material. Same argument works if you work with a triangulated manifold $M$ where $K$ is a subcomplex of codimension $\ge 3$. (You use the fact that a 2-dimensional affine subspace of $R^n$ is generically disjoint from a subspace of codimension $\ge 3$.) | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/872028', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/67412/']} | jdg_83006 |
stackexchange | llm_judgeable_groundtruth_similarity | 100245 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
There are several claims in the literature that there are no injective groups (with more than one element), but I have not found a proof. For example, Mac Lane claims in his Duality from groups paper in the 1950 Bull. A.M.S. that Baer showed him an elegant proof, but gives no hint of what it might be. Does anyone know of an actual published proof?
Now provide the response and nothing else.
| Let $G$ be a non-trivial injective group and $g \in G$ non-trivial. From category theory, $G \times G$ is injective as well. But, now $G \times G$ embeds into a group $H$, where $(g,e)$ and $(e,g)$ are conjugate using an HNN-extension, or just embedding into the group $H:=(G \times G) \rtimes \mathbb Z/2\mathbb Z$. Since $(g,e)$ and $(e,g)$ are not conjugate in $G \times G$, $H$ cannot split back to $G \times G$. This is a contradiction. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/100245', 'https://mathoverflow.net', 'https://mathoverflow.net/users/24338/']} | jdg_83007 |
stackexchange | llm_judgeable_groundtruth_similarity | 378787 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
A Banach space $X$ is called a Grothendieck space if $\text{weak}^{*}$ -null sequences in $X^{*}$ are weakly null. Some of the classical Grothendieck spaces are the $C(\Omega)$ spaces if $\Omega$ is extremally disconnected. However, $C[0,1]$ is not a Grothendieck space. This fact can easily be deduced from some well-known characterizations of Grothendieck spaces, such as, $C(\Omega)$ is a Grothendieck space if and only if it does not contain any complemented copy of $c_{0}$ . But my concern is whether there is a direct proof of this fact, that is, a construction of a $\text{weak}^{*}$ -null sequence $(\mu_{n})_{n}$ in $C[0,1]^{*}$ which is not weakly null.
Now provide the response and nothing else.
| Consider $\delta_{1/n}-\delta_0$ ; this defines a weak $^*$ null sequences which is not weakly null; e.g., $\langle \delta_{1/n}-\delta_0, \chi_{\{0\}} \rangle \not\to 0$ . So if $\Omega$ contains a nontrivial convergent sequence, $C(\Omega)$ cannot be a Grothendieck space. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/378787', 'https://mathoverflow.net', 'https://mathoverflow.net/users/41619/']} | jdg_83008 |
stackexchange | llm_judgeable_groundtruth_similarity | 6458708 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm working with a database that includes hex codes for UTF32 characters. I would like to take these characters and store them in an NSString. I need to have routines to convert in both ways. To convert the first character of an NSString to a unicode value, this routine seems to work: const unsigned char *cs = (const unsigned char *) [s cStringUsingEncoding:NSUTF32StringEncoding];uint32_t code = 0;for ( int i = 3 ; i >= 0 ; i-- ) { code <<= 8; code += cs[i];}return code; However, I am unable to do the reverse (i.e. take a single code and convert it into an NSString). I thought I could just do the reverse of what I do above by simply creating a c-string with the UTF32 character in it with the bytes in the correct order, and then create an NSString from that using the correct encoding. However, converting to / from cstrings does not seem to be reversible for me. For example, I've tried this code, and the "tmp" string is not equal to the original string "s". char *cs = [s cStringUsingEncoding:NSUTF32StringEncoding];NSString *tmp = [NSString stringWithCString:cs encoding:NSUTF32StringEncoding]; Does anyone know what I am doing wrong? Should I be using "wchar_t" for the cstring instead of char *? Any help is greatly appreciated! Thanks,Ron
Now provide the response and nothing else.
| You have a couple of reasonable options. 1. Conversion The first is to convert your UTF32 to UTF16 and use those with NSString, as UTF16 is the "native" encoding of NSString. It's not actually all that hard. If the UTF32 character is in the BMP (e.g. it's high two bytes are 0's), you can just cast it to unichar directly. If it's in any other plane, you can convert it to a surrogate pair of UTF16 characters. You can find the rules on the wikipedia page . But a quick (untested) conversion would look like UTF32Char inputChar = // my UTF-32 characterinputChar -= 0x10000;unichar highSurrogate = inputChar >> 10; // leave the top 10 bitshighSurrogate += 0xD800;unichar lowSurrogate = inputChar & 0x3FF; // leave the low 10 bitslowSurrogate += 0xDC00; Now you can create an NSString using both characters at the same time: NSString *str = [NSString stringWithCharacters:(unichar[]){highSurrogate, lowSurrogate} length:2]; To go backwards, you can use [NSString getCharacters:range:] to get the unichar's back and then reverse the surrogate pair algorithm to get your UTF32 character back (any characters which aren't in the range 0xD800-0xDFFF should just be cast to UTF32 directly). 2. Byte buffers Your other option is to let NSString do the conversion directly without using cStrings. To convert a UTF32 value into an NSString you can use something like the following: UTF32Char inputChar = // input UTF32 valueinputChar = NSSwapHostIntToLittle(inputChar); // swap to little-endian if necessaryNSString *str = [[[NSString alloc] initWithBytes:&inputChar length:4 encoding:NSUTF32LittleEndianStringEncoding] autorelease]; To get it back out again, you can use UTF32Char outputChar;if ([str getBytes:&outputChar maxLength:4 usedLength:NULL encoding:NSUTF32LittleEndianStringEncoding options:0 range:NSMakeRange(0, 1) remainingRange:NULL]) { outputChar = NSSwapLittleIntToHost(outputChar); // swap back to host endian // outputChar now has the first UTF32 character} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6458708', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/683389/']} | jdg_83009 |
stackexchange | llm_judgeable_groundtruth_similarity | 408201 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
let $a_{1}=1,a_{2}=2,a_{3}=5$,and $$a_{n}=3a_{n-1}a_{n-2}-a_{n-3}$$ show that$a_{n}=a^2+b^2,a,b\in N$ while $a_{1}=0^2+1^2,a_{2}=2=1^2+1^2,a_{3}=5=2^2+1^2,a_{4}=29=5^2+2^2,a_{5}=433=17^2+12^2$ and so on
Now provide the response and nothing else.
| There are many such properties involving the Markov numbers , see also OEIS , which together make up a tree rather than a single sequence. The numbers are any of the variables (required to be positive integers) in $$ x^2 + y^2 + z^2 = 3 x y z. $$ Your sequence $1,2,5,29,433,37666,48928105,\ldots$ is the fastest growing branch in the tree, in that you are replacing (jumping out) the smallest number in the current triple. The slowest growing branch is the Fibonacci numbers with odd index $1,2,5,13,34,89,233,610,1597,\ldots,$ in that the middle-sized number in the triple is replaced. See jpeg far below. Oh, if you replace the largest number in the triple, you jump back closer to the root. Travel within the tree is one of the more serious uses of Vieta Jumping . The other serious use, with recent articles in the AMS Bulletin by Kontorovich and by E. Fuchs , is Apollonian Gaskets . I would like to put, at a minimum, Wikipedia links at Vieta Jumping and Apollonian Gaskets pointing to each other, but I have had little luck with Wikipedia and the relationship has not been noticed in print. Your property (sum of two squares) is true for all Markov numbers. The most striking property, for me, is that if $m$ is a Markov number, then $$9m^2 - 4 $$ is the sum of two squares. The shortest proof that $m$ itself is the sum of two squares is probably this: in $$ x^2 + y^2 + z^2 = 3 x y z $$ the initial solution is $(1,1,1).$ So the greatest common divisor is $1.$ There is a proof by induction that $\gcd (x,y,z)=1$ whenever $(x,y,z)$ is such a Markov triple; we are going to move to a new triple with $z' = 3 x y - z.$ If there is any prime $p$ that divides all three $3xy-z,x,y$ Then it also divides $(3xy) -(3xy-z)=z,$ causing $\gcd (x,y,z) \neq 1,$ violating the induction assumption. Now, $$ 3xyz - z^2 = x^2 + y^2, $$ $$ z(3xy - z) = x^2 + y^2. $$IF there were any prime $q \equiv 3 \pmod 4,$ such that $q |z,$ it would also be true that $q|(x^2 + y^2).$ However, it is a standard fact that if such $q|(x^2 + y^2),$ then $q|x$ and $q|y.$ So, if this happened, $q$ would divide all three, violating $\gcd (x,y,z)=1.$ Note that the same trick works to show that $z$ cannot be divisible by 4, otherwise all three numbers would be even. As a result, any Markov number $m$ is not divisible by 4 or by any prime $q \equiv 3 \pmod 4,$ so we can write it primitively as the sum of two squares, $m = u^2 + v^2$ with $\gcd(u,v)=1.$ Proof of standard fact: (it seems DonAntonio has this; oh, well...) If $q \equiv 3 \pmod 4$ and$$ x^2 + y^2 \equiv 0 \pmod q, $$ ASSUME $y \neq 0 \pmod q.$Then $$ x^2 \equiv - y^2 \pmod q, $$ but $y$ has a multiplicative inverse in this field, and$$ x^2 / y^2 \equiv - 1 \pmod q, $$$$ (x / y)^2 \equiv - 1 \pmod q, $$which violates the fact that $-1$ is not a quadratic residue for primes $q \equiv 3 \pmod 4.$ ================= This is page 19 from Cusick and Flahive ============= | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/408201', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/58742/']} | jdg_83010 |
stackexchange | llm_judgeable_groundtruth_similarity | 40097127 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
this is a quiz where I am trying to populate each question with a word from a JSON file. Here is the JSFiddle activity.json are the questionswords.json are the words Can someone help me? It's bringing undefined. The Id of the div I want to populate the word is #words I've got lost and can't find a way to show them. $(document).ready(function() { var questionNumber = 0; var wordNumber = 0; var questionBank = new Array(); var wordsBank = new Array(); var stage = "#game1"; var stage2 = new Object; var questionLock = false; var numberOfQuestions; var score = 0; $.getJSON('activity.json', function(data) { for (i = 0; i < data.quizlist.length; i++) { questionBank[i] = new Array; questionBank[i][0] = data.quizlist[i].question; questionBank[i][1] = data.quizlist[i].option1; questionBank[i][2] = data.quizlist[i].option2; questionBank[i][3] = data.quizlist[i].option3; } $.getJSON('words.json', function(data) { for (i = 0; i < data.quizlist.length; i++) { wordsBank[i] = new Array; wordsBank[i] = data.quizlist[0].words1; wordsBank[i] = data.quizlist[1].words2; } numberOfWords = wordsBank.length; }) numberOfQuestions = questionBank.length; displayQuestion(); }) //gtjson function displayQuestion() { var q1; var q2; var q3; var q4; var q5; var rnd = Math.random() * 3; rnd = Math.ceil(rnd); if (rnd == 1) { q1 = questionBank[questionNumber][1]; q2 = questionBank[questionNumber][2]; q3 = questionBank[questionNumber][3]; } if (rnd == 2) { q2 = questionBank[questionNumber][1]; q3 = questionBank[questionNumber][2]; q1 = questionBank[questionNumber][3]; } if (rnd == 3) { q3 = questionBank[questionNumber][1]; q1 = questionBank[questionNumber][2]; q2 = questionBank[questionNumber][3]; } $(stage).append('<div class="questionText">' + questionBank[questionNumber][0] + '</div><div id="1" class="option">' + q1 + '</div><div id="2" class="option">' + q2 + '</div><div id="3" class="option">' + q3 + '</div>'); $('.option').click(function() { if (questionLock == false) { questionLock = true; $('#words').append('<div class="word-pt bluedark_txt">' + q5 + '</div><div id="1" class="words word-en bluish_txt">' + q4 + '</div>'); //correct answer if (this.id == rnd) { $(stage).append('<div class="feedback1">CORRECT</div>'); score++; } //wrong answer if (this.id != rnd) { $(stage).append('<div class="feedback2">WRONG</div>'); } setTimeout(function() { changeQuestion() }, 1000); } }) } //display question function changeQuestion() { questionNumber++; if (stage == "#game1") { stage2 = "#game1"; stage = "#game2"; } else { stage2 = "#game2"; stage = "#game1"; } if (questionNumber < numberOfQuestions) { displayQuestion(); } else { displayFinalSlide(); } $(stage2).animate({ "right": "+=800px" }, "slow", function() { $(stage2).css('right', '-800px'); $(stage2).empty(); }); $(stage).animate({ "right": "+=800px" }, "slow", function() { questionLock = false; }); } //change question
Now provide the response and nothing else.
| Git is behaving correctly. This is the expected (though not really "desired", in your case) result. There's a bit at the bottom about how to work with Git to make it actually useful for you. Besides Mykhailo Kovalskyi's answer , there's a more likely scenario. You did this: git checkout -b "misc"git pull origin master The first line is straightforward enough. It's the second that's extra-complicated, because git pull is git fetch followed by git merge , and both of those are a little bit complicated themselves. Drawing the graph (see Pretty git branch graphs ) Whenever you are working with branches in Git—and you're always working with branches, so this is really just "whenever you're working with Git"—it's important to keep the commit graph in mind. The graph, or DAG (Directed Acyclic Graph), is always there, usually lurking just out of sight. To see it with git log , use --graph , often with --oneline . To see it with visualizers, use something like gitk or one of the many annoying GUIs, which give you views like those shown here (this is just a randomly-chosen question on stackoverflow about what was seen in gitk vs git-gui ). The graph determines how merges will work, so it's very important at that time. At other times, it mostly just lurks, out of the way but ever-present. Almost everything in Git is oriented around adding commits, which adds entries to this graph. 1 So, let's draw a bit of a graph, and then observe git fetch and git merge in action. Here's a graph of a repository with nothing but a master branch, with four commits on it: o--o--o--o <-- master The master branch "points to" the tip-most commit. In this graph, with newer commits at the right, that's the right-most commit. Each commit also points backwards, to its parent commit. That is, the lines in o--o--o really should be arrows: o <- o <- o . But these arrows all point backwards, which is annoying and mostly useless to humans, so it's nicer to just draw them as lines. The thing is that these backwards arrows are how Git finds earlier commits, because branch names only point to the tip-most commit! Git also has the name HEAD , which is a symbol for the "current commit". The way HEAD normally works is that it actually contains the branch name, and the branch name then points to the tip commit. We can draw this with a separate arrow: HEAD | vo--o--o--o <-- master but that takes too much room, so I usually use this: o--o--o--o <-- master (HEAD) Git will discover that HEAD is "attached to" (contains the name) master , then follow the backwards arrow from master to the tip commit. Hint: use git log --decorate to show branch names and HEAD . It's particularly good with --oneline --graph : think of this as a friendly dog: Decorate, Oneline, Graph . In Git 2.1 and later, --decorate happens automatically, so you don't have to turn it on yourself most of the time. See also this answer to Pretty git branch graphs . Note that git log --decorate prints the decoration as HEAD -> master when HEAD points to master . When HEAD points directly to a commit, Git calls this a detached HEAD , and you might see HEAD, master instead. This formatting trick was new in Git 2.4: before that, it just showed HEAD, master for both detached HEAD mode, and non-detached-HEAD mode, for this case. In any case, I call "non-detached" an attached HEAD , and I think master (HEAD) shows this attachment pretty well.) Now, the git checkout -b misc step creates a new branch name. By default, this new branch name points to the current (HEAD) commit, so now we have: o--o--o--o <-- master, misc (HEAD) 1 In fact, you can never change a commit. Things that seem to change a commit, really work by adding a new commit, that resembles the old one, and then they cover up the old one and show you the new one instead. This makes it look like the commit has changed, but it hasn't. You also can't remove commits, or at least, not directly: all you can do is make them unreachable , from branch and tag names and the like. Once a commit is unreachable, Git's maintenance "garbage collector" eventually removes them. Making git gc remove them now can be difficult. Git tries really hard to let you get your commits back, even if you want them gone. But, all of this applies only to commits , hence the rule of thumb: "commit early and often". Anything you have actually committed, Git will try to let you retrieve again later, usually for up to 30 or 90 days. git fetch What git fetch does can be summarized as: call up another Git; ask it which commits it has; and collect those commits, plus whatever else is required to make those commits sensible, and add them to your repository. In this way, Git is like The Borg . But instead of: "We are the Borg. We will add your biological and technological distinctiveness to our own," Git says "I am the Git. Your technologically-distinctive commits will be added to my own!" So, let's see what happens when you git fetch origin . You have this: o--o--o--o <-- master, misc (HEAD) They have this, which has several extra commits on their master (and we don't care about their HEAD now): o--o--o--o--o--o <-- master Your Git renames their master, calling it origin/master on your own end, so that you can keep them straight. Their two new commits are added to your repository, all Borg-like. Those new commits point back to the existing four commits, with the usual backwards arrows, but now it takes more room to draw the graph: o--o--o--o <-- master, misc (HEAD) \ o--o <-- origin/master Note that none of your branches are changed. Only the origin ones change. Your Git adds their technological uniqueness, 2 and re-points your origin/master to keep track of "where master was on origin the last time I checked." 2 This is where those big ugly SHA-1 IDs come in. The hashes are how Git can tell which commits are unique to which repository. The key is that the same commit always makes the same hash ID , so if their Git has commit 12ab9fc7... , and your Git has commit 12ab9fc7... , your Git already has their commit, and vice versa. The mathematics behind all this is rather deep and beautiful. git merge The second half of git pull is to run git merge . It runs the equivalent 3 of git merge origin/master . The git merge command starts by finding the merge base , and this is where the graph suddenly really matters. The merge base between two commits is, loosely speaking, "the point in the graph where the lines all come back together." Usually the two commits are two branch-tips, pointed-to by two branch names . A typical, and nicely obvious, case occurs with this: o--o <-- branch1 (HEAD) /o--o--o--* \ o--o--o <-- branch2 What git merge does is to locate the nearest common-ancestor commit, which I've drawn as * instead of just o here. That's the merge base . It's simply the point from which the two branches "fork off". The goal of git merge is to find out what "you" have changed—what you've done in branch1 since commit * —and what "they" have changed, i.e., what has changed in branch2 since commit * . To get those changes, Git runs two git diff commands. The same applies even if we draw the commits like this: o--o--o--*--o--o <-- branch1 (HEAD) \ o--o--o <-- branch2 This is the same graph , so it's the same merge . Git compares commit * against the tip of branch1 ("what's changed in our two commits?"), and commit * against the tip of branch2 ("what's changed in their three commits?"). Then Git does its best to combine those changes, and makes a new merge commit from the result. The exact details of all this combining-and-committing don't matter yet, because we don't have a graph like that. What we have is this: o--o--o--* <-- master, misc (HEAD) \ o--o <-- origin/master Note that I've kept the * notion here. That's because git merge still finds the merge base. The problem here is that the merge base is the branch tip: the name misc points directly to commit * . If Git were to do git diff <commit-*> <commit-*> , the diff would obviously be empty. Commit * is the same as commit * . So how can we merge these? Git's answer is: we don't merge at all. We do what Git calls a fast forward . Note that although the internal commit arrows all point backwards, if we just imagine them pointing forwards instead, it's now easy to take the misc branch-label and slide it forward , going down along the dog-leg and then to the right. The result looks like this: o--o--o--o <-- master \ o--o <-- origin/master, misc (HEAD) So now our config file is the one in the HEAD commit, which is the tip-most commit of misc , which is the same commit as origin/master . In other words, we lost our changes to the config file, as they were overridden by their changes to the config file. 3 The details of why it doesn't actually use git merge origin/master are mostly irrelevant here, but have a lot to do with history. In the old days of Git, before version 1.8.4, some git fetch origin s never actually bothered to update origin/master . This was a bad design decision, and in all modern Git versions, git fetch does update it. Would doing a "real merge" instead of a fast-forward help? If we go back to our original setup (and drop the name master since it's in the way): o--o--o--* <-- misc (HEAD) \ o--o <-- origin/master we could, instead of letting git pull run git merge , run our own git merge --no-ff origin/master , to merge origin/master but not allow Git to do a fast-forward. Would this help? Alas, no. Remember that the goal of a merge is to combine all the changes since the merge-base. So Git will run two diffs: git diff <commit-*> <commit-*> # this diff is emptygit diff <commit-*> origin/master # this is "what they changed" Git will then combine our changes (none) with their changes, and make a new merge commit: o--o--o--o------o <-- misc (HEAD) \ / o--o <-- origin/master We have a different graph (it's sort of a soup ladle or Big Dipper ), but we took their changes, including the password change, while keeping nothing of ours (we had no changes since the merge base). Making merge be useful What we need is to make sure "our" changes—they have to be our changes, in Git's eyes—"look different" from "their" changes. That means we need Git to choose a different merge base. The merge base is, as I said above, the point at which our commits and their commits begin to diverge. That means we need to make our own branch, and make sure we don't "fast forward" too much, or perhaps even at all. So, we probably do want to avoid git pull . 4 We also may want to pick an earlier point at which we make our own branch. We want our graph's branch to maintain its own distinctiveness, as it were, from theirs. I've given a few of these commits letter-names so that I can talk about them: A-----B <-- misc (HEAD) / /o--o--o--o <-- master \ o--C <-- origin/master In commit A , we change the config file to have a different password. Then we git merge (not fast-forward) the tip of master to pick up new stuff, without letting the password change. This step may be very manual, or totally automatic, but once it's committed, we're done: commits are permanent; they can't be changed. 5 Now we can allow master to "fast forward" as usual: A-----B <-- misc (HEAD) / /o--o--o--*--o--C <-- master, origin/master Now, when we git merge origin/master or git merge master , 6 the merge base will be the commit I've marked * . If we didn't change the password from * to B , and they changed it from * to C , we'll pick up their change—but they should no longer need to change it, because we never send them commits A and B ; we keep those to ourselves. So there should be no change to the password from * to C , and we'll keep our changed password when we make our new merge: A-----B-----D <-- misc (HEAD) / / /o--o--o--o--o--C <-- master, origin/master Later, we'll pick up even more commits, merge (fast forward) them into master , and be ready to merge again: A-----B-----D <-- misc (HEAD) / / /o--o--o--o--o--C--o--o <-- master, origin/master This time, the merge base will be commit C —it's the closest one that is on both misc and their branch—and Git will diff C vs origin/master . Presumably, they still won't have changed the password, because we still didn't give them commit D . 4 I avoid git pull as much as possible, but depending on how you go about this, you may be able to use it anyway, especially for master . 5 We make any ordinary new commit by moving the branch label to the new commit: remember that branch names just point to the tip-most commit. We just make a new tip commit, with its parent being the previous tip-most commit, and re-point the label, moving forward one step. But look what happens when we make a new commit that points further back , not just to the old tip commit, for its parent. Now we "rewrite history" by hiding some previous commits. (Try drawing this graph.) This is how both git commit --amend and git rebase work. 6 Note that these do the same thing , as the tip of master and the tip of origin/master are the same commit . The one difference is that the default commit message will change: one will say "merge master" and the other will say "merge origin/master". (There's some fiddly stuff in Git's commit message formatting that treats master differently from everything else, too, but we can ignore that. It's just a historical artifact.) One final note: configs and passwords in commits = bad Because commits are so permanent, it's generally a very bad idea to put passwords into them. Anyone with access to your repository can look through historical commits and find the passwords. Configuration files, too, generally shouldn't be committed at all, though here there's no real security issue. Instead, it's a matter of the very problem you have run into: everyone needs a different configuration. Committing yours to a shared repository makes no sense. If it's a private repository, that makes somewhat more sense, and if it's a private branch it's OK (if still sub-optimal in most cases). It's pretty common to want some sort of sample configuration, or a default initial configuration. These should indeed be in commits. The trick is to make sure that the sample, or default initial, configuration is separate from the "live" configuration. For instance, with some systems, you'd include: config.default and have a little bit of code, such as: [ -f .config ] || cp config.default .config to set up the default configuration as the .config file on the first run. Then with .config in .gitignore , it won't ever get put into the repository, so it will never be in any commits and you won't have this issue in the first place. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40097127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4572652/']} | jdg_83011 |
stackexchange | llm_judgeable_groundtruth_similarity | 26897 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I have enough fears that this question might get struck down. Still let me try. I shall restrict myself to $\frac{\lambda \phi^4}{4!}$ perturbed real scalar quantum field theory and call as "symmetry factor" of a Feynman diagram to be the eventual number by which the power of $\lambda$ is divided in the final integral representation of the diagram. In that way the symmetry factor of the figure of eight vacuum bubble is 8 and of the "tadpole diagram" it is 2. One way to get this factor right is to count the number of ways the free arms in the "pre-diagram" can be contracted. But this is more like a cook-book rule than an understanding of how the factor comes. I believe the most conceptually correct way is to count for every diagram the number of terms in the representation as a functional derivative of the path-integral which give that diagram. In that picture one has to argue that there were precisely $4!$ terms produced by the functional derivative which produced that figure of eight vacuum bubble. Which I can argue. But for the tadpole diagram and the product of the vacuum bubble with the free-propagator, I can't find an argument. Like one has to be able to show that in the functional derivative picture there are $4!\times 3! \times (2!)^2$ terms corresponding to the tadpole diagram. Any help regarding how this counting is done or any general framework which helps compute these symmetry factors correctly?
Now provide the response and nothing else.
| Exactly how you count symmetries depends on your normalizations, and in particular on whether you use divided (i.e. "exponential") power series or ordinary power series. I believe strongly that divided powers are the way to go. To establish notation, I will first review the preliminaries, that I'm sure you already know. So let me consider Dyson series for integrals of the form:$$\int_{x\in X} \exp\left( \sum_{n\geq 2} \frac{c_n x^n}{n!} \right) {\rm d}x$$In actual physics examples, $X$ is an infinite-dimensional space and the measure ${\rm d}x$ does not exist, but no matter. Each coefficient $c_n$ is a symmetric tensor $X^{\otimes n} \to \mathbb R$ or $\mathbb C$, and we suppose that $c_2$ is invertible as a map $X \to X^*$ — in infinite-dimensional settings, this is a very problematic supposition, and leads to questions of renormalization, which I will not address here. (Incidentally, in all actual physical quantum field theories, $c_2$ is not a priori invertible, because of gauge symmetry; so I am assuming that you have fixed that however suits your fancy.) Finally, Dyson series / Feynman diagrams are by definition perturbative , meaning that you need some perturbation parameter. There are various choices for how to do this; ultimately what's important is that ratios $\lvert c_n\rvert / \lvert c_2 \rvert^{n/2}$ are infinitesimal for $n \geq 3$. In your example, $c_2$ is normalized to unity, and $c_4 = \lambda \ll 1$. Another option is to set all coefficients $\lvert c_n\rvert \sim \hbar^{-1}$, where $\hbar \ll 1$. In any case, the Dyson series is correctly calculated by expanding$$ \int_{x\in X} \exp\left( \sum_{n\geq 2} \frac{c_n x^n}{n!} \right) {\rm d}x = \int_{x\in X} \exp \left( \frac{c_2x^2}2\right) \sum_{m=0}^\infty \left( \sum_{n\geq 3} \frac{c_n x^n}{n!} \right)^m {\rm d}x, $$using "Wick's theorem" for $b_\ell$ a totally symmetric tensor $X^{\otimes \ell} \to \mathbb R$:$$ \int_{x\in X} \exp \left( \frac{c_2x^2}2\right) \frac{b_\ell x^\ell}{\ell!} = \begin{cases} 0, & \ell \text{ odd} \\ \text{normalization} \times \frac{b_\ell (c_2/2)^{\ell/2}}{(\ell/2)!}, & \ell \text{ even} \end{cases},$$(where $\text{normalization}$ involves $\det c_2$, factors of $\sqrt{2\pi}$, and doesn't make really sense in infinite dimensions), and recognizing what all of these exponential generating functions are counting. When all the dust has settled, what these are counting is (all: disconnected, empty, etc., are allowed) graphs with trivalent-and-higher vertices, mod symmetries. If you throw a $\log$ out in front of the whole integral, then the resulting exponential generating function counts connected graphs, still mod symmetries. In any case, to actually answer your question for the Dyson series above: the value of each graph is computed by placing a $c_n$ at each vertex of valence $n$ and a $(c_2)^{-1}$ on each edge, and contracting these tensors according to the graph. The symmetry factor is precisely the number of automorphisms of the graph, defined as follows: Definition: A Feynman graph is a collection $H$ of half edges along with two partitions: one ( edges ) into sets of size precisely $2$, and the other ( vertices ) into sets of size at least $3$. (Since each graph will be weighted by the coefficients $c_n$, if you want graphs for a theory with most $c_n = 0$, you can restrict to only graphs with the prescribed valences. If $X$ splits as a direct sum $X = X_1 \oplus X_2$, you can reasonably define graphs with half-edges colored by $X_1,X_2$. If you want to compute an integral with an "observable", you should consider graphs with prescribed "external half-edges".) This is the correct definition, because it gives the correct notion of iso/automorphism. In particular, an isomorphism of Feynman graphs is a bijection of half edges that induces bijections on the partitions. An automorphism is an isomorphism from a Feynman graph to itself. Then the symmetry factor is precisely the number of automorphism in this sense. (A different notion of "graph" more commonly used in mathematics is that of an "adjacency matrix", which is a $\mathbb Z_{\geq 0}$-valued matrix indexed by the vertices of the graph. The natural notion of isomorphism of such things is a bijection of vertices that induces an equality of adjacency matrices, but this is not the right one for counting symmetries of Feynman diagrams, as, for example, it gives "$1$" for each of the figure-eight and tadpole diagrams.) For small graphs, the automorphism group splits as a direct product. For example, for the figure eight, the automorphism group is $(\mathbb Z/2) \ltimes (\mathbb Z/2)^2$, where the $(\mathbb Z/2)^2$ acts as flips of the two lobes of the figure eight, and the left-hand $\mathbb Z/2$ switches the two lobes. In a "$\phi^3$" theory, the theta graph has automorphism group $(\mathbb Z/2) \ltimes S_3$, where $S_3$, the symmetric group on three objects, acts to permute the edges, and the $\mathbb Z/2$ switches the two vertices. So the figure eight has $2\times 2^2 = 8$ symmetries, and the theta has $2\times 3! = 12$ symmetries. For small graphs, you can really just read off these semidirect-product decompositions: self-loops contribute factors of $\mathbb Z/2$, each collection of $k$ parallel edges contributes a factor of $S_k$, if you permute vertices, that's another factor, etc. For large graphs, the computations become much harder, and I think I can find a graph whose symmetry group is any finite group you want (but don't quote me on that thought). A slow way to do the computation is to consider all possible permutations of half edges, and see if they induce automorphism. This is slow because there are $(\text{lots})!$ many such permutations. The whole point of working with Dyson series is to avoid this. Fortunately, no one ever computes large graphs, because even just contracting all the tensors is so hard for those. Finally, I cannot help but mention one more fact you probably know. These Dyson series almost never have positive radius of convergence in the perturbation parameters. In particular, even after dividing by symmetry factors, there are still a lot of graphs, and so the coefficients grow as $n!$. A good exercise is to compute the Dyson series for the conditionally-convergent Riemann integral $\int_{\mathbb R} \exp \frac i \hbar \bigl( \frac{x^2}2 + \lambda \frac{x^3}6 \bigr){\rm d}x$. (The $i$ is there to make the integral conditionally converge; I tend to work with $\hbar$ as my perturbation parameter.) Then the Dyson series grows as $\sum \frac{(6n!)}{(2n)!\,(3n)!} \alpha^n$, where $\alpha$ is linear in $\lambda\hbar$ (something like $\alpha = \lambda\hbar / 6$). The point is that by Stirling's formula $\frac{(6n!)}{(2n)!\,(3n)!} \approx \beta^n n!$ for some positive $\beta$. In any case, this is not at all surprising. Integrals of the form $\int \exp \sum c_nx^n/n!$ are essentially never analytic at $0,\infty$ in the coefficients — for example, Gauss's formula $\int_{\mathbb R}\exp(-a^{-1}x^2/2){\rm d}x = \sqrt{2\pi a}$ has a ramified point at $a = 0,\infty$, and so the Riemann integral extends from its domain of convergence (${\rm Re}(a) > 0$) to a double-valued complex function in $a$. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/26897', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2678/']} | jdg_83012 |
stackexchange | llm_judgeable_groundtruth_similarity | 19186585 |
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 are the key differences between CSS transformations and transitions? Both of those are used to change the current shape/state of an object. (you can do pretty animations with JS etc..) But it's still not clear to me which one to use where and for what.
Now provide the response and nothing else.
| transition and transform are separate CSS properties, but you can supply transform to transition to "animate" a transformation. transition The CSS transition property listens for changes to specified properties (background-color, width, height, etc.) over time. transition Property Syntax: selector { transtion: [property-name] [duration] [timing-function] [delay]} For example, the below styles will change the color of a div's background to orange over a period of 1 second upon hover. div { width: 100px; height: 100px; background-color: yellow; transition: background-color 1s; /* timing function and delay not specified */}div:hover { background-color: orange;} <div></div> transform The CSS transform property rotates/scales/skews an element over the X,Y, or Z axes. Its behavior does not relate to transition . Simply put, on page load, the element will just appear rotated/skewed/scaled. Now if you wanted the rotating/skewing/scaling to happen, say when a user hovered over the element, you would need to "transition" the "transformation". Here's how: since the transition property's functionality is to listen to changes in other css properties, you can actually supply transform as an argument to transition and "animate" the transformation based on desired trigger (for example, a hover action). transform Property Syntax select { transform: [rotate] [skew] [scale] [translate] [perspective]} For example, the below styles will rotate a div over a period of 1 second upon hover. div { width: 100px; height: 100px; background-color: yellow; transition: transform 1s; /* timing function and delay not specified */}div:hover { transform: rotate(30deg);} <div></div> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19186585', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2387506/']} | jdg_83013 |
stackexchange | llm_judgeable_groundtruth_similarity | 21700872 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm working with data from the Tate collection published here: https://github.com/tategallery/collection I'm trying to group the artists by movement. Every JSON object of an artist has a property "movements", which is an array of zero or more elements. For example, Vito Acconci is associated with Conceptual Art and Performance Art: "movements": [ { "era": { "id": 415, "name": "20th century post-1945", "workCount": 3604 }, "id": 421, "name": "Conceptual Art", "workCount": 478 }, { "era": { "id": 415, "name": "20th century post-1945", "workCount": 3604 }, "id": 436, "name": "Performance Art", "workCount": 81 }] I now want to group the artists by their movement, ideally using d3.nest(). My problem is, how do I process artists that are associated with several movements? I'd want them to appear once in every associated movement. Here is a JSFiddle with an excerpt of the data: http://jsfiddle.net/jwFZV/
Now provide the response and nothing else.
| It's as simple as Task.Run(() => ExpensiveTask()); To make it an awaitable method: public Task ExpensiveTaskAsync(){ return Task.Run(() => ExpensiveTask());} The important thing here is to return a task. The method doesn't even have to be marked async. (Just read a little bit further for it to come into the picture) Now this can be called as async public void DoStuff(){ PrepareExpensiveTask(); await ExpensiveTaskAsync(); UseResultsOfExpensiveTask();} Note that here the method signature says async , since the method may return control to the caller until ExpensiveTaskAsync() returns. Also, expensive in this case means time-consuming, like a web request or similar. To send off heavy computation to another thread, it is usually better to use the "old" approaches, i.e. System.ComponentModel.BackgroundWorker for GUI applications or System.Threading.Thread . | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/21700872', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2008439/']} | jdg_83014 |
stackexchange | llm_judgeable_groundtruth_similarity | 135777 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Seeking a method to: Take whitespace separated tokens in a String; return a suggested Word ie: Google Search can take "fonetic wrd nterpreterr" , and atop of the result page it shows "Did you mean: phonetic word interpreter" A solution in any of the C* languages or Java would be preferred. Are there any existing Open Libraries which perform such functionality? Or is there a way to Utilise a Google API to request a suggested word?
Now provide the response and nothing else.
| In his article How to Write a Spelling Corrector , Peter Norvig discusses how a Google-like spellchecker could be implemented. The article contains a 20-line implementation in Python, as well as links to several reimplementations in C, C++, C# and Java. Here is an excerpt: The full details of an industrial-strength spell corrector like Google's would be more confusing than enlightening, but I figured that on the plane flight home, in less than a page of code, I could write a toy spelling corrector that achieves 80 or 90% accuracy at a processing speed of at least 10 words per second. Using Norvig's code and this text as training set, i get the following results: >>> import spellch>>> [spellch.correct(w) for w in 'fonetic wrd nterpreterr'.split()]['phonetic', 'word', 'interpreters'] | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/135777', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4857/']} | jdg_83015 |
stackexchange | llm_judgeable_groundtruth_similarity | 30786226 |
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 single page on my site that has a shopping cart function that allows credit card purchases. I want this page to be served with https. When users leave that page, I want them to be redirected back to http pages. When I set up the rewrite rules I can deliver the HTTPS page no problem, but when I add rules to send the user back to HTTP, the entire HTTPS page breaks because all the assets get redirected to http or something. Here is my rewrite rules: RewriteCond %{HTTPS} onRewriteCond %{REQUEST_URI} !/bookings.html RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]RewriteCond %{HTTPS} offRewriteCond %{REQUEST_URI} ^/bookings.htmlRewriteRule ^(.*)$ https://%{SERVER_NAME}/bookings.html [R=301,L] I am using absolute urls in my html. I would just serve the whole site HTTPS, but the client has tripadivsor widgets that are very important to his business and they break over HTTPS.
Now provide the response and nothing else.
| Yes, the pointer to the struct is automatically dereferenced. From the spec on selectors : The following rules apply to selectors: For a value x of type T or *T where T is not a pointer or interface type, x.f denotes the field or method at the shallowest depth in T where there is such an f . If there is not exactly one f with shallowest depth, the selector expression is illegal. ... As an exception, if the type of x is a named pointer type and (*x).f is a valid selector expression denoting a field (but not a method), x.f is shorthand for (*x).f . Therefore, the following two statements are the same (with the first being preferred): filename := p.Title + ".txt"filename := (*p).Title + ".txt" | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30786226', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2570466/']} | jdg_83016 |
stackexchange | llm_judgeable_groundtruth_similarity | 47905 |
Below is a question asked on the forum engineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I recently received an order of extruded aluminum strip 3/32" thick that supposed to be 6061 hardened to specification ASTM B221. However, when we tried to bend it, it broke and the interior looked like cast zinc coated with aluminum. Is 6061 supposed to look that way and be unable to bend 90-degrees? How can I verify that I have solid aluminum and not some fake alloy with zinc in it?
Now provide the response and nothing else.
| I figured out a simple test. Since the density of 6061 is 2.5 g/cm3 and the density of zinc is over 7 g/cm3, all I had to do was measure the density of the material. This showed that indeed it was aluminum. So, its brittleness is probably just because it was hardened. | {} | {'log_upvote_score': 6, 'links': ['https://engineering.stackexchange.com/questions/47905', 'https://engineering.stackexchange.com', 'https://engineering.stackexchange.com/users/1672/']} | jdg_83017 |
stackexchange | llm_judgeable_groundtruth_similarity | 10660438 |
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 compare an array of integers to the tags of imageviews I have uniquely made. using this line: if(grid[i][j] == buttons[k].getTag()){ I know im on the right tracks, but I can't figure out if i need to cast it or use a method. I know its a simple question, but any help would be greatly appreciated, thanks.
Now provide the response and nothing else.
| Tag is an Object, so put an Integer : /* * UseValueOf * ---------- * Priority: 4 / 10 * Severity: Warning * Category: Performance * * You should not call the constructor for wrapper classes directly, such as`new * Integer(42)`. Instead, call the valueOf factory method, such as * Integer.valueOf(42). This will typically use less memory because common * integers such as 0 and 1 will share a single instance. *///MyView.setTag(new Integer(42));MyView.setTag(Integer.valueOf(42)); Then retrieve the value like this: int tagValue = (Integer)MyView.getTag(); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10660438', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1399604/']} | jdg_83018 |
stackexchange | llm_judgeable_groundtruth_similarity | 46863910 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider this base64 encode image <img src='data:image/Png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABICAYAAABhlHJbAAAABHNCSVQICAgIfAhkiAAAAAFzUkdCAK7OHOkAAAAEZ0FNQQAAsY8L/GEFAAAACXBIWXMAABVlAAAVZQGF3cVdAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAABnNJREFUeF7tnFls3EQYx11ucQshClWbtb1LC4RLIARIHAXxgsQDCOWhJGs7mypIoII4BAIhsYAEWY+TlEo8FAQSQjxAuR54AnFUFHH0CQlEEWcaQhpKmx5poVWb8H3eb92Jd7Nre8a7a2d/0l9txvN99vw1HnvtGSsdqskYzu2ayb4A7dNN9oNm2E8qPW8fT5s71EOznDwYdxQ0x0s12LtXD248kaoFpFg8TisMX6Gb9t264dwHSR5PtEz7Mc10BrE92b6RnKLMLaGWulDPO+w3ryLoje8FMlG37As1094IQX/7k6RJqsl+wdNz2WDxVDXProWyGX8dv+qamFu34WQwbz1UPOIPTLec3+HfndXltQU9+P0qE1Vr9GzY+K2/MugACAfUd8q9Mslir4M+BMO+oXb52xpYaOLq1cUTyLziKVCIJvGVtmYMdlf4gTMZ4NkGpjq+NoeTwZ51k8EA+zS/AcaG5z13U0o2zy6FtoqO8ZNKpm/0AvgP350Z7SO1kHlTXJujalqB3vZApQCvSti1aT+pJGcOdUNbZZiHegtP308qBXCJfoL2k0q6+p1LYNzbwRkgoumca /> I would like to post this src to Mvc controller but getting null when post with ajax here is the post method. var file = document.getElementById("base64image").src; var formdata = new FormData(); formdata.append("base64image", file); $.ajax({ url: "http://localhost:26792/home/SaveImage", type: "POST", data: file }); Mvc Controller [HttpPost] public void SaveImage(Image file) { } I think the datatype I am using is not valid for this please suggest me what can I do here. Full Html Code <!doctype html><html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>WebcamJS Test Page</title><style type="text/css"> body { font-family: Helvetica, sans-serif; } h2, h3 { margin-top:0; } form { margin-top: 15px; } form > input { margin-right: 15px; } #results { float:right; margin:20px; padding:20px; border:1px solid; background:#ccc; }</style></head><body><div id="results">Your captured image will appear here...</div><h1>WebcamJS Test Page</h1><h3>Demonstrates simple 320x240 capture & display</h3><div id="my_camera"></div><!-- First, include the Webcam.js JavaScript Library --><script type="text/javascript" src="../webcam.min.js"></script><!-- Configure a few settings and attach camera --><script language="JavaScript"> Webcam.set({ width: 320, height: 240, image_format: 'jpeg', jpeg_quality: 90 }); Webcam.attach( '#my_camera' );</script><!-- A button for taking snaps --><form> <input type=button id="takeshot" value="Take Snapshot" onClick="take_snapshot()"></form><!-- Code to handle taking the snapshot and displaying it locally --><script language="JavaScript"> window.onload = function () { setInterval(function () { take_snapshot() }, 5000); } function take_snapshot() { // take snapshot and get image data Webcam.snap( function(data_uri) { // display results in page document.getElementById('results').innerHTML = '<h2>Here is your image:</h2>' + '<img id="base64image" src="' + data_uri + '"/>'; }); var file = document.getElementById("base64image").src; var formdata = new FormData(); formdata.append("base64image", file); $.ajax({ url: "http://localhost:26792/home/SaveImage", type: "POST", data: file }); //var ajax = new XMLHttpRequest(); //ajax.addEventListener("load", function (event) { uploadcomplete(event); }, false); //ajax.open("POST", "http://localhost:26792/home/SaveImage"); //ajax.send(formdata); } </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </body> </html>
Now provide the response and nothing else.
| I am not 100 % sure what your end goals are here. But the below answer explains how you can send a base64 image source string to server and save it. I tested it with a base64 string generated from a small image (22 KB size) and it worked. In your ajax call, you should be sending the FormData object you created, not the value of file variable. Also make sure you use processData and contentType properties when making the ajax call while sending a FormData object. var file = document.getElementById("base64image").src;var formdata = new FormData();formdata.append("base64image", file);$.ajax({ url: "@Url.Action("SaveImage")", type: "POST", data: formdata, processData: false, contentType: false}); Now since this is the base 64 string of the image, use string as the parameter type of your action method. The parameter name should match with your formdata item key( base64Image ). You can generate a byte array from the base64 string in your action method. Also the image source starts with data:image/png;base64, which needs to be removed from the string before you try to convert it. The below method accepts the string you are sending from the client, and removes the first 21 characters and use the result of that (which is now a valid base 64 string) and then creates an image from that and saves to Content/Images/ directory in the app root with a random file name. [HttpPost]public void SaveImage(string base64image){ if (string.IsNullOrEmpty(base64image)) return; var t = base64image.Substring(22); // remove data:image/png;base64, byte[] bytes = Convert.FromBase64String(t); Image image; using (MemoryStream ms = new MemoryStream(bytes)) { image = Image.FromStream(ms); } var randomFileName = Guid.NewGuid().ToString().Substring(0, 4) + ".png"; var fullPath = Path.Combine(Server.MapPath("~/Content/Images/"), randomFileName); image.Save(fullPath, System.Drawing.Imaging.ImageFormat.Png);} I am not 100 % sure that the default model binder can bind the base64 string to an image. If not, you can perhaps create one which does that and add that to the model binders in your system and then use the Image as the parameter type. The code inside model binder will be very similar ( read the string and generate image from that) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46863910', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4569045/']} | jdg_83019 |
stackexchange | llm_judgeable_groundtruth_similarity | 6968366 |
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 fail to see what makes YAML any less of a markup language than XML. The purpose of a markup language is to define the structure of a document, and YAML does exactly that (YAML stands for YAML ain't markup language ). What YAML should instead stand for is, Yet another markup language .
Now provide the response and nothing else.
| So, a markup language presumes a base text, typically human readable, and then special indicators or "markup" which direct processing. The idea comes from an editor, who would take a printed-version of someone's manuscript, and "mark it up" to show where new lines should go, edits, etc. In this manner, SGML is a meta-language for declaring markup languages, and HTML is a markup language. In 1996-7, when XML came on the scene, it was sold as a simplified SGML meta-language for creating markup languages. In XML (and SGML), you have elements to "mark" a portion of text, and then attributes that modify the marking. Over time, XML was used for much more than document markup though, people used it for data serialization -- even though it was never designed to do such a thing. Of course, it was the big problem to be solved. YAML and JSON appeared on the scene and focused on data serialization, not document markup. In these languages, there simply isn't a core document text. Hence, YAML Ain't Markup Language is quite an accurate differentiator from XML. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6968366', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/337306/']} | jdg_83020 |
stackexchange | llm_judgeable_groundtruth_similarity | 1470686 |
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 a software engineering student, so I don't have probability theory in my career, but I hear people near my circle talk about stochastic processes very often. Could someone explain in simple words what these are? E: I'll make myself a bit more precise. I've heard people describe a series of events via a stochastic process, I've read the wiki, and I don't understand how the 'collection of random variables' part comes to play: what does it mean to represent something via a non-deterministic process? Could somebody provide a concrete example of a representation of something via a stochastic process (and how it defers from a deterministic process)?
Now provide the response and nothing else.
| Very roughly speaking, you can think of a stochastic process as a process that evolves in a random way. The randomness can be involved in when the process evolves, and also how it evolves. A very simple example of a stochastic process is the decay of a radioactive sample (with only one parent and one daughter product). Initially, it has some large number $N$ of atoms of the parent element. Over time, the number of such atoms decreases, always by $1$, but at random moments in time. The state of the system can be represented by $k$, the number of atoms of the parent element present at a given moment in time. Initially, $k = N$, but eventually, it will fall to zero. In this process, when the state changes is random, but not how it changes. In other processes, such as a discrete-time random walk, when the state changes is deterministic, but how it changes is random. And there are other processes in which both when the state changes and how it changes are random. Interestingly, in many cases, stochastic processes are used to model situations that may not have inherent randomness. For instance, Brownian motion is the result of forces that could, in principle, be determined precisely (if we ignored quantum mechanics). However, the number of objects in a normal system is so large that such an analysis would be intractable. Instead, we model the motion of objects using a stochastic process, and thereby obtain some insight into the behavior of such systems (for instance, the statistical behavior of a given particle over time) that we could not begin to with a deterministic approach. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1470686', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/193752/']} | jdg_83021 |
stackexchange | llm_judgeable_groundtruth_similarity | 57748994 |
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 disassembled a C program with Radare2. Inside this program there are many calls to scanf like the following: 0x000011fe 488d4594 lea rax, [var_6ch]0x00001202 4889c6 mov rsi, rax0x00001205 488d3df35603. lea rdi, [0x000368ff] ; "%d" ; const char *format0x0000120c b800000000 mov eax, 00x00001211 e86afeffff call sym.imp.__isoc99_scanf ; int scanf(const char *format)0x00001216 8b4594 mov eax, dword [var_6ch]0x00001219 83f801 cmp eax, 1 ; rsi ; "ELF\x02\x01\x01"0x0000121c 740a je 0x1228 Here scanf has the address of the string "%d" passed to it from the line lea rdi, [0x000368ff] . I'm assuming 0x000368ff is the location of "%d" in the exectable file because if I restart Radare2 in debugging mode ( r2 -d ./exec ) then lea rdi, [0x000368ff] is replaced by lea rdi, [someMemoryAddress] . If lea rdi, [0x000368ff] is whats hard coded in the file then how does the instruction change to the actual memory address when run?
Now provide the response and nothing else.
| Radare is tricking you, what you see is not the real instruction, it has been simplified for you. The real instruction is: 0x00001205 488d3df3560300 lea rdi, qword [rip + 0x356f3]0x0000120c b800000000 mov eax, 0 This is a typical position independent lea . The string to use is stored in your binary at the offset 0x000368ff , but since the executable is position independent, the real address needs to be calculated at runtime. Since the next instruction is at offset 0x0000120c , you know that, no matter where the binary is loaded in memory, the address you want will be rip + (0x000368ff - 0x0000120c) = rip + 0x356f3 , which is what you see above. When doing static analysis, since Radare does not know the base address of the binary in memory, it simply calculates 0x0000120c + 0x356f3 = 0x000368ff . This makes reverse engineering easier, but can be confusing since the real instruction is different. As an example, the following program: int main(void) { puts("Hello world!");} When compiled produces: 6b4: 48 8d 3d 99 00 00 00 lea rdi,[rip+0x99] 6bb: e8 a0 fe ff ff call 560 <puts@plt> So rip + 0x99 = 0x6bb + 0x99 = 0x754 , and if we take a look at offset 0x754 in the binary with hd : $ hd -s 0x754 -n 16 a.out00000754 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 00 00 00 00 |Hello world!....|00000764 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57748994', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4283307/']} | jdg_83022 |
stackexchange | llm_judgeable_groundtruth_similarity | 818891 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can anyone briefly explain what is the use of GenericIdentity and where to use it.
Now provide the response and nothing else.
| GenericIdentity and GenericPrincipal are the simplest way of describing a user as a "principal". This can be used for implementation-unaware security checking in an application - i.e. if the user logs in as "Fred" with the "User" and "Admin" permissions: string[] roles = { "User", "Admin" }; Thread.CurrentPrincipal = new GenericPrincipal( new GenericIdentity("Fred"), roles); You might do this at the point of client login to a winform, or there are specific points to do this in WCF, ASP.NET, etc. Then later code, without having to know how those permissions are handled, can check that permission - either via IsInRole , or declaratively: [PrincipalPermission(SecurityAction.Demand, Role = "Admin")]void SomeAdminFunction() { } Some useful utility code here is null-safe wrappers around principal/identity: public static string GetUsername() { IPrincipal principal = Thread.CurrentPrincipal; IIdentity identity = principal == null ? null : principal.Identity; return identity == null ? null : identity.Name;}public static bool IsInRole(string role) { IPrincipal principal = Thread.CurrentPrincipal; return principal == null ? false : principal.IsInRole(role);} Then you might have some audit code in your DAL: row.UpdatedBy = MyUtilityClass.GetUsername(); GenericPrincipal is useful for the simple cases of a plain username and set of known roles.More sophisticated principal implementations might, for example, do "on demand" access checking - i.e. until you ask for the "Foo" role it doesn't know - it then finds out (by talking to a web-service, database, active-directory, etc) and caches the result for future access. This is useful when the list of potential roles is large, and the number of roles typically queried in reality is small. You can also use a principal to store extra identity information that is only needed in certain contexts - for example, a security token. Callers might test the principal with as to see if it supports the extra data. Using "principal" is useful because your logic processing code can talk about identity, without having to know whether this is winforms, ASP.NET, WCF, a windows service, etc - it is abstract. Additionally, some 3rd party code will also talk to the principal. As another example - I wrote some example code here that shows how to use the principal to control access to winform controls via the designer (via an IExtenderProvider - which puts extra entries into the property grid in VS). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/818891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/95373/']} | jdg_83023 |
stackexchange | llm_judgeable_groundtruth_similarity | 33852267 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have this code # Modelsclass NestedSample(models.Model): something = models.CharField(max_length=255)class Sample(models.Model): thing = models.BooleanField() nested = models.ForeignKey(NestedSample)# Serializersclass NestedSampleSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = api_models.NestedSampleclass SampleSerializer(serializers.HyperlinkedModelSerializer): nested = NestedSampleSerializer() # HERE filter delete=false nested2 = NestedSample2Serializer() # HERE filter deletefalse class Meta: model = api_models.Sample In my view I am overrding the queryset for delete=False but it is not applying to nested serializers.
Now provide the response and nothing else.
| delete=False in queryset will only filter Sample . To filter queryset in nested serializer you can use serializers.ListSerializer like: class FilterDeleteListSerializer(serializers.ListSerializer): def to_representation(self, data): data = data.filter(delete=False) return super(FilterDeleteListSerializer, self).to_representation(data)class NestedSampleSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = api_models.NestedSample list_serializer_class = FilterDeleteListSerializer class NestedSample2Serializer(serializers.HyperlinkedModelSerializer): class Meta: model = api_models.NestedSample2 list_serializer_class = FilterDeleteListSerializer class SampleSerializer(serializers.HyperlinkedModelSerializer): nested = NestedSampleSerializer() # HERE filter delete=false nested2 = NestedSample2Serializer() # HERE filter deletefalse class Meta: model = api_models.Sample Learn more here | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33852267', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5438896/']} | jdg_83024 |
stackexchange | llm_judgeable_groundtruth_similarity | 13994150 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Wikipedia classifies "call super" as an anti-pattern, and I don't really understand why. The pattern is used pretty frequently in objective-C/cocoa; for example init/dealloc, drawrect, awakefromnib all require you to call super. Am I misunderstanding the concept here? Link to the article: http://en.wikipedia.org/wiki/Call_super
Now provide the response and nothing else.
| As it says in the article, it is the necessity to call the super method that is the antipattern, i.e. the super class "expects" you to override the method to make the functionality complete - but it does so without making this expectation explicit. And it also expects you to call the super implementation. Both are required for the program to work. This is an antipattern, because the intent of the programmer cannot be deduced from the code. If your co-workers decided to work on it, they wouldn't know what you expected the class to do, and are therefore likely to encounter problems and/or irritations. So if you expect some parts of a method to be overridden, but other things need to stay in place, it is recommended to use the template method pattern , where you keep all the things that must not be replaced in one (private) method, which then calls another one - completely separate -, which must be implemented in order for the program to work (in some languages, it won't even compile otherwise).That way, you make sure the important things remain where they have to be, and whoever extends the class will know exactly what to do, while remaining blissfully ignorant of the other implementation details. Objective-C does not have abstract or virtual methods, but you can achieve the same effect by explicitly raising an exception if the super method is called. That way, if your co-workers forget to override the method, the program will crash - and it will crash with an error message that they will understand, and that will enable them to understand and fix the problem faster and more easily than some erratic behavior with no explanation, due to the functionality not being complete. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13994150', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1114924/']} | jdg_83025 |
stackexchange | llm_judgeable_groundtruth_similarity | 17487514 |
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 source some shell scripts in c using exec() . What is source ? is that a binary executable or a shell script ? where can i find that in linux file system ? I ran charan@PC-113:~$ which source charan@PC-113:~$
Now provide the response and nothing else.
| It is a builtin shell command, like cd , exit , pwd ...: $ enable -p | grep sourceenable source Note that enable -p shows all the builtins. More info in enable Man page . Update Just saw a pretty interesting thread in SuperUser: What does source do? $ type sourcesource is a shell builtin Update 2 - comment by Tony D @SIGSEGV: sometimes a command can be implemented as an external (non-shell) executable, but some shells will still want to provide their own implementation... possibly with different behaviour, possibly just to make it faster. test and pwd are examples of this. For example, the shell can get its current working directory using getcwd(), but if it runs a separate executable without changing the current directory for that executable, and the executable runs getcwd() - it still works. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17487514', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1619597/']} | jdg_83026 |
stackexchange | llm_judgeable_groundtruth_similarity | 3081044 |
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 multiprocessing version of text categorization code i found here (amongst other cool things). I've appended the full code below. I've tried a couple of things - tried a lambda function first, but it complained of not being serializable (!?), so attempted a stripped down version of the original code: negids = movie_reviews.fileids('neg') posids = movie_reviews.fileids('pos') p = Pool(2) negfeats =[] posfeats =[] for f in negids: words = movie_reviews.words(fileids=[f]) negfeats = p.map(featx, words) #not same form as below - using for debugging print len(negfeats) Unfortunately even this doesnt work - i get the following trace: File "/usr/lib/python2.6/multiprocessing/pool.py", line 148, in map return self.map_async(func, iterable, chunksize).get()File "/usr/lib/python2.6/multiprocessing/pool.py", line 422, in get raise self._valueZeroDivisionError: float division Any idea what i might be doing wrong? should i be using pool.apply_async instead (in of itself that doesnt seem to solve the problem either - but perhaps i am barking up the wrong tree) ? import collectionsimport nltk.classify.util, nltk.metricsfrom nltk.classify import NaiveBayesClassifierfrom nltk.corpus import movie_reviewsdef evaluate_classifier(featx): negids = movie_reviews.fileids('neg') posids = movie_reviews.fileids('pos') negfeats = [(featx(movie_reviews.words(fileids=[f])), 'neg') for f in negids] posfeats = [(featx(movie_reviews.words(fileids=[f])), 'pos') for f in posids] negcutoff = len(negfeats)*3/4 poscutoff = len(posfeats)*3/4 trainfeats = negfeats[:negcutoff] + posfeats[:poscutoff] testfeats = negfeats[negcutoff:] + posfeats[poscutoff:] classifier = NaiveBayesClassifier.train(trainfeats) refsets = collections.defaultdict(set) testsets = collections.defaultdict(set) for i, (feats, label) in enumerate(testfeats): refsets[label].add(i) observed = classifier.classify(feats) testsets[observed].add(i) print 'accuracy:', nltk.classify.util.accuracy(classifier, testfeats) print 'pos precision:', nltk.metrics.precision(refsets['pos'], testsets['pos']) print 'pos recall:', nltk.metrics.recall(refsets['pos'], testsets['pos']) print 'neg precision:', nltk.metrics.precision(refsets['neg'], testsets['neg']) print 'neg recall:', nltk.metrics.recall(refsets['neg'], testsets['neg']) classifier.show_most_informative_features()
Now provide the response and nothing else.
| No. EDIT : A CURLINFO_CERTINFO option has been added to PHP 5.3.2. See http://bugs.php.net/49253 Apparently, that information is being given to you by your proxy in the response headers. If you want to rely on that, you can use curl's CURLOPT_HEADER option to true to include the headers in the output. However, to retrieve the certificate without relying on some proxy, you must do <?php$g = stream_context_create (array("ssl" => array("capture_peer_cert" => true)));$r = fopen("https://www.google.com/", "rb", false, $g);$cont = stream_context_get_params($r);var_dump($cont["options"]["ssl"]["peer_certificate"]); You can manipulate the value of $cont["options"]["ssl"]["peer_certificate"] with the OpenSSL extension. EDIT : This option is better since it doesn't actually make the HTTP request and does not require allow_url_fopen : <?php$g = stream_context_create (array("ssl" => array("capture_peer_cert" => true)));$r = stream_socket_client("ssl://www.google.com:443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $g);$cont = stream_context_get_params($r);var_dump($cont["options"]["ssl"]["peer_certificate"]); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3081044', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/264875/']} | jdg_83027 |
stackexchange | llm_judgeable_groundtruth_similarity | 5886738 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
rails g model Article name:stringrails g model Category name:stringrails g model Tag name:string taggable_id:integer taggable_type:string category_id:integer I have created my models as shown in the preceding code. Articles will be one of many models which can have tags. The category model will contain all categories which may be assigned. The tag model will be a polymorphic join-table which represents tagged relationships. class Article < ActiveRecord::Base has_many :tags, :as => :taggable has_many :categories, :through => :taggableendclass Category < ActiveRecord::Base has_many :tags, :as => :taggable has_many :articles, :through => :taggableendclass Tag < ActiveRecord::Base belongs_to :taggable, :polymorphic => true belongs_to :categoryend I can't seem to get this to work, I can do it non polymorphic, but I must have something wrong with the polymorphic part. Any ideas? Edit: Still not getting this right: class Article < ActiveRecord::Base has_many :taggables, :as => :tag has_many :categories, :through => :taggables, :source => :tag, :source_type => "Article"endclass Category < ActiveRecord::Base has_many :taggables, :as => :tag has_many :articles, :through => :taggables, :source => :tag, :source_type => "Article"endclass Tag < ActiveRecord::Base belongs_to :taggable, :polymorphic => true belongs_to :categoryend
Now provide the response and nothing else.
| To create a polymorphic has_many :through, you must first create your models. We will use'Article,' 'Category,' and 'Tag' where 'Tag' is the join-model and Article is one of many objects which can be "tagged" with a category. First you create your 'Article' and 'Category' models. These are basic models which do not need any special attention, just yet: rails g model Article name:stringrails g model Category name:string Now, we will create our polymorphic join-table: rails g model Tag taggable_id:integer taggable_type:string category_id:integer The join-table joins together two tables, or in our case one table to many others via polymorphic behavior. It does this by storing the ID from two separate tables. This creates a link. Our 'Category' table will always be a 'Category' so we include 'category_id.' The tables it links to vary, so we add an item 'taggable_id' which holds the id of any taggable item. Then, we use 'taggable_type' to complete the link allowing the link to know what it is linked to, such as an article. Now, we need to set up our models: class Article < ActiveRecord::Base has_many :tags, :as => :taggable, :dependent => :destroy has_many :categories, :through => :tagsendclass Category < ActiveRecord::Base has_many :tags, :dependent => :destroy has_many :articles, :through => :tags, :source => :taggable, :source_type => 'Article'endclass Tag < ActiveRecord::Base belongs_to :taggable, :polymorphic => true belongs_to :categoryend After this, setup your database using: rake db:migrate That's it! Now, you can setup your database with real data: Category.create :name => "Food"Article.create :name => "Picking the right restaurant."Article.create :name => "The perfect cherry pie!"Article.create :name => "Foods to avoid when in a hurry!"Category.create :name => "Kitchen"Article.create :name => "The buyers guide to great refrigeration units."Article.create :name => "The best stove for your money."Category.create :name => "Beverages"Article.create :name => "How to: Make your own soda."Article.create :name => "How to: Fermenting fruit." Now you have a few categories and various articles. They are not categorized using tags, however. So, we will need to do that: a = Tag.newa.taggable = Article.find_by_name("Picking the right restaurant.")a.category = Category.find_by_name("Food")a.save You could then repeat this for each, this will link your categories and articles. After doing this you will be able to access each article's categories and each categorie's articles: Article.first.categoriesCategory.first.articles Notes: 1)Whenever you want to delete an item that is linked by a link-model make sure to use "destroy." When you destroy a linked object, it will also destroy the link. This ensures that there are no bad or dead links. This is why we use ':dependent => :destroy' 2)When setting up our 'Article' model, which is one our 'taggable' models, it must be linked using :as. Since in the preceeding example we used 'taggable_type' and 'taggable_id' we use :as => :taggable. This helps rails know how to store the values in the database. 3)When linking categories to articles, we use:has_many :articles, :through => :tags, :source => :taggable, :source_type => 'Article'This tells the category model that it should have many :articles through :tags. The source is :taggable, for the same reason as above. The source-type is "Article" because a model will automatically set taggable_type to its own name. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5886738', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/675940/']} | jdg_83028 |
stackexchange | llm_judgeable_groundtruth_similarity | 55677445 |
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 familiarizing myself with some of the things (that are planned to be) added in C# 8 & .NET Core 3.0, and am unsure on the correct way to implement IAsyncDisposable (at time of writing, this link has literally no guidance). In particular, it is unclear to me what to do in the case when an instance isn't explicitly disposed - that is, it isn't wrapped in an async using(...) and .DisposeAsync() isn't explicitly called. My first thought was to do that same thing I'd do when implementing IDisposable : My DisposeAsync() implementation calls a DisposeAsync(bool disposing) with disposing: true Implement a finalizer (with ~MyType() ) that calls DisposeAsync(disposing: false) DisposeAsync(bool disposing) actually frees and/or disposes everything, and suppresses finalizing if disposing == true . My concerns are that there's nothing to await the results of DisposeAsync(bool) in the finalizer, and explicitly waiting in a finalizer seems really really dangerous. Of course "just leak" also seems less than ideal. To make this concrete, here's a (simplified) example class that does have a finalizer: internal sealed class TestAsyncReader: IAsyncDisposable{ private bool IsDisposed => Inner == null; private TextReader Inner; internal TestAsyncReader(TextReader inner) { Inner = inner; } // the question is, should this exist? ~TestAsyncReader() { DisposeAsync(disposing: false); } private ValueTask DisposeAsync(bool disposing) { // double dispose is legal, but try and do nothing anyway if (IsDisposed) { return default; } // should a finalizer even exist? if (disposing) { GC.SuppressFinalize(this); } // in real code some resources explicitly implement IAsyncDisposable, // but for illustration purposes this code has an interface test if (Inner is IAsyncDisposable supportsAsync) { var ret = supportsAsync.DisposeAsync(); Inner = null; return ret; } // dispose synchronously, which is uninteresting Inner.Dispose(); Inner = null; return default; } public ValueTask DisposeAsync() => DisposeAsync(disposing: true);} So, is there any guidance around proper handling of leaked IAsyncDisposable instances?
Now provide the response and nothing else.
| Basing on examples of how it's implemented inside .NET Core classes (like here ) and some recommendations from there , I'd say that when you need to implement IAsyncDisposable , the good practice would be to implement both IAsyncDisposable and IDisposable . In this case IAsyncDisposable will be only responsible for explicit scenarios when asyncronus disposal is needed, while IDisposable is supposed to be implemented as usual according to disposable pattern practices and it's going to serve all fallback scenarios including those when things come to finalization. Thus you don't need to have anything like DisposeAsync(bool disposing) - the asynchronous disposal cannot and shouldn't happen in a finalizer. The only bad news that you'll have to support both paths for resources reclaiming (synchronous and asynchronous). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55677445', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/80572/']} | jdg_83029 |
stackexchange | llm_judgeable_groundtruth_similarity | 5264968 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We use a git repo that is hosted at a remote location, and is shared. We want the repo to be user & group readable & writeable, but not have any permissions for other. The remote repo is owned by a different user (say rUser). I have set core.sharedRepository to 0660 in my local repo, as well as the remote repo. Also, my umask is 0027 . So, whenever I create a new file, it has no permissions for other. In spite of all this, for some reason whenever I push a change to the remote repo, it creates some new objects in the repo.git/objects/ directory with permissions -r--r--r-- . What's even weirder is that it makes me (instead of the remote user) the owner of the directories/files. Any idea what's going on? I tried finding an answer by going over several seemingly related questions on stackoverflow, but couldn't find anything.
Now provide the response and nothing else.
| Note: I am assuming that you are using an SSH-based access mechanism with each user logging into the server as their own user (i.e. you do not have multiple users login to a single account to access the repository). If this assumption is not true, then the following answer may not be wholly useful. The core.sharedrepository setting of your personal repository and the umask you use to access it are irrelevant to the ownership and permissions used on a remote repository. Setting core.sharedrepository to 0660 in the remote repository is the right way to get what you say you want. The umask of the accessing user on the remote side is also irrelevant because Git will override the mask when it sees a 0xxx value for core.sharedrepository . You do need to make sure all the files and directories are group-owned by the your common group and that the permissions are correct ( 2770 for all directories (or just 770 for BSD-ish systems); 440 for files under objects/?? and /objects/pack/ ; 660 for other files). It is normal that a new file is user-owned by the user that created it. On non-BSD systems you need the setgid bit (the 2000 bit) on directories to make new entries inherit the group-owner of its parent directory. The user-owner is rarely inherited (FreeBSD can be configured to do it with the setuid bit, but this is not used in normal configurations). Thus, all the files and directories should have the same, common, group-owner, but each write to the repository (e.g. push) will leave some files and/or directories that are user-owned by the writing user 1 (i.e. it is not required that any one user (your rUser ?) be the user-owner of all the files and directories; any user that needs access to the repository should be a member of common group). 1 Each user will obviously user-own any files/directories they create, but they will also user-own most files that they modify because Git uses “atomic rewrites” (it writes the new content to a new, separate file in the same directory, and then renames it atop the original file). Maybe there is a bug in the way Git is overriding the umask for new files. Exactly which files are getting permissions that are too wide? What version of Git are you on the remote end to access on the repository? What OS are you running on the remote end? I was unable to reproduce this problem with Git 1.7.4.1 with two users and a common group on my Unixy machine. You might try simplifying the scenario a bit. Try pushing to the remote repository directly from the server itself (i.e. make a local clone and push to a throw-away branch). Doing local-only access makes it easier to check your assumptions (umask; uids; gids; user-, and group-ownership, and permissions of files and directories before and after pushing) than when you have a transport of some kind in the middle (either Git’s own SSH-based transports, or a network filesystem that might not map ids and permissions with full fidelity). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5264968', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/137582/']} | jdg_83030 |
stackexchange | llm_judgeable_groundtruth_similarity | 22728508 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There are several answers here how to check if a property exists in an object. I was always using if(myObj.hasOwnProperty('propName')) but I wonder if there is any difference from if('propName' in myObj){
Now provide the response and nothing else.
| They are almost equal, the difference is that hasOwnProperty does not check down the prototype chain, while in does. An example var test = function() {}test.prototype.newProp = function() {}var instance = new test();instance.hasOwnProperty('newProp'); // false'newProp' in instance // true FIDDLE As noted, Object.hasOwnProperty only returns "own properties" , i.e. properties that are added directly, and not properties added to the prototype . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/22728508', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1008547/']} | jdg_83031 |
stackexchange | llm_judgeable_groundtruth_similarity | 15359341 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been writing a angularjs app and i have a number of controllers which I have placed in a 1 JS file. I was hoping for something a little more modular and separating my controllers into there own files. I thought of RequireJS but is this the recommended way? or does angularjs provide something else and any clue on where it is explained? Also having all these files is great for debugging but once a production build is required does angularJS provide some sort of merging of of the modules into 1 file and minimizing the results? If anyone can explain the best way to go about it it would be very helpful. Thanks
Now provide the response and nothing else.
| Angular dependencies injection is really great and you should create a lot of small modules. When it comes to file organization it's way easier to have a lot a small files (one per module maybe), but then you face the issue you're talking about: what do I do with all these files? How do I load them all? It is worth taking a look at these 2 sources: Brian Ford's blog and this Github repo . It helped me a lot improving my workflow and better understand/use Angular modules. TL;DR What I do for my projects is using Grunt to concat ( minify if needed) all the js files (and way more: less css compilation, assets management, javascript templates compilation ). A good example is given in the Github repo above. I don't recommend using RequireJS with AngularJS. Although it's certainly possible, I haven't seen any instance where RequireJS was beneficial in practice. [Brian Ford] Files organization My app folder looks like this: www|-dist/ = Created by Grunt. Generated files (served by my web server).|-node_modules/ = node modules (ie. Grunt modules. Grunt is based on NodeJS)|-src/ = My workspace|-test/ = Some tests|-vendor = External libraries (AngularJS, JQuery, Bootstrap, D3, ... Whatever you need)|-gruntFile.js = The Grunt configuration file: contains all the jobs for Grunt.|-package.json = App infos + dependencies (Grunt modules) I use (concat, uglify, jshint, ...) So all the different files I work on are in the src folder which then looks like this: www/src|-app = Folder for my controllers| |-Controller1.js| |-Controller2.js| |-...|-assets = Folder for the static assets (img, css, ...)| |-img/| |-css/| |-favicon.ico|-common = Folder for the shared modules (directives, resources, services, ...)| |-directives| | |-chart.js| | |-map.js| | |-...| |-resources| | |-users.js| | |-another-cool-resource.js| | |-...| |-services| | |-service1.js| | |-...|-views = Folder for my templates| |-profile.tpl.html| |-search.tpl.html| |-...|-index.html = The main and unique html file. Grunt Then I use Grunt to 'compile' everything into the dist folder. An example of a gruntFile can be found here .I have a one-time job for deployment and some watchers for development. Do you need more explanation? | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15359341', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/457172/']} | jdg_83032 |
stackexchange | llm_judgeable_groundtruth_similarity | 3578861 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In the functional analysis books that I have read, they do not explain how the ideas and theorems of functional analysis (in the sense of operators on Banach spaces) help to deal with differential equations, such as proving existence or uniqueness of solutions. Could someone give me an example of using the ideas and theorems of functional analysis to actually say something about a (partial) differential equation?
Now provide the response and nothing else.
| I am a little surprised you haven't gotten more responses here; perhaps it is because once you see the functional analytic perspective on PDEs, it becomes hard to think about PDEs without functional analysis. Anyway here is a sketch of an example. Depending on how much functional analysis you've seen, it might not totally make sense; but I wanted to keep the example short to preserve the high level point. Fix a domain $\Omega$ and consider the Laplace's equation $\Delta u = 0$ on $\Omega$ with Dirichlet boundary conditions. Multiplying by a test function $v$ and integrating by parts, we see that $$-\int_{\Omega}v\Delta u=\int_{\Omega}\nabla u\cdot\nabla v-\int_{\partial\Omega}\frac{\partial u}{\partial \nu}vd\mathcal{H}^{d-1}.$$ If we stipulate that the test function $v$ is also zero on the boundary of $\Omega$ , this implies that $$\int_\Omega \nabla u \cdot \nabla v = 0.$$ We say that this is the "weak" form of Laplace's equation. Here is where the functional analysis perspective comes in handy. The "natural" function space here is the Sobolev space $H_0^1 (\Omega)$ . On this space, it turns out[1] that $\int_\Omega \nabla u \cdot \nabla v$ is an equivalent inner product. Therefore, we can rewrite the weak form of Laplace's equation as $\langle u, v \rangle_{H_0^1 (\Omega)} = 0$ . Now, we allow $v$ to range over the entire space $H_0^1 (\Omega)$ . Defining the continuous linear functional $L$ on $H_0^1(\Omega)$ by $L(v)=0$ , we can further rewrite the weak form of Laplace's equation as $$\forall v \in H_0^1 (\Omega) \quad \langle u, v \rangle_{H_0^1 (\Omega)} = L(v).$$ In other words, there is a solution to the weak form of Laplace's equation if there is a $u$ which solves the problem above. But because $H_0^1(\Omega)$ is a Hilbert space, this is automatically true thanks to the Riesz representation theorem (and moreover, the $u$ is unique!). That is, there is a unique $u\in H_0^1 (\Omega)$ such that $\forall v \in H_0^1 (\Omega)$ , $\int_\Omega \nabla u \cdot \nabla v = 0.$ In particular, since any "bona fide" solution $u$ to $\Delta u = 0$ automatically satisfies the weak Laplace equation, this implies that there is at most one solution to $\Delta u = 0$ . In summary: we have taken a fairly standard PDE, transformed it slightly into a "weak" analogue in the "right" space, and then shown that solving the weak analogue is just a direct application of some functional analysis result. [1] See here: Norm and scalar product of $H_0^1(\Omega)$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3578861', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/619968/']} | jdg_83033 |
stackexchange | llm_judgeable_groundtruth_similarity | 5515 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I want a script to sleep unless a certain file is modifed/deleted (or a file created in a certain directory, or ...). Can this be achieved in some elegant way? The simplest thing that comes to my mind is a loop that sleeps for some time before checking the status again, but maybe there is a more elegant way?
Now provide the response and nothing else.
| On linux, you can use the kernel's inotify feature. Tools for scripting can be found there: inotify-tools . Example use from wiki: #!/bin/shEVENT=$(inotifywait --format '%e' ~/file1) # blocking without looping[ $? != 0 ] && exit[ "$EVENT" = "MODIFY" ] && echo 'file modified!'[ "$EVENT" = "DELETE_SELF" ] && echo 'file deleted!'# etc... | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/5515', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/863/']} | jdg_83034 |
stackexchange | llm_judgeable_groundtruth_similarity | 22631 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm developing a plan/strategy to manage patch deployment on Windows Clients using Windows Server Update Services. What are the some important things to consider in developing this plan? For example, auto-rebooting after an update although may seem trivial, may have considerable impact on some machines. So one solution is, to create a separate patch group in WSUS for machines that shouldn't auto-reboot. Tell me some things to keep in mind when developing a patch management plan and how to solve them. Thanks in advance
Now provide the response and nothing else.
| We stay a month behind (it's a nice round number) and also keep a separate group for machines that shouldn't auto-reboot. We also make a specific effort to exclude service packs, new versions of IE, and other major upgrades from the patch management system, taking the view that as these constitute a major upgrade you want to be physically there to see it happening, and respond to anything that needs responding to. You should certainly consider having a test group of PCs that are a good representation of what's out there that don't stay a month behind (i.e. get their patches immediately). That way, if a patch is going to cause trouble at the PC level, you will find out about it quickly enough and can make a call on how to deal with it without every PC being affected. Finally, in WSUS "update rollups" is a category separate to "critical and security updates", but yet some vital recent patches (Conficker, anyone?) were classified under that heading, so ensure that you don't miss it! | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/22631', 'https://serverfault.com', 'https://serverfault.com/users/4113/']} | jdg_83035 |
stackexchange | llm_judgeable_groundtruth_similarity | 1112566 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
for a big enough n, How to detrmine which is bigger? $2^{n^{1.001}}$ or $n!$ I have tried to make a series: $a_n = \frac{2^{n^{1.001}}}{n!}$ and then try finding the limit of $\frac{a_{n+1}}{a_n}$and see if its bigger or smaller then one, also tried to use induction but didnt really got my anywhere btw I know the answer is that $2^{n^{1.001}}$ is bigger
Now provide the response and nothing else.
| Hint: $$n!\le n^n=2^{n\log_2 n}$$ Spoiler: $2^{n\log_2 n}<2^{n^{1.001}}\iff n\log_2 n<n^{1.001}\iff \log_2n<n^{0.001}$, which is true eventually as $\log_2 n$ grows slower than any $n^\alpha$ with $\alpha>0$. (e.g. by L'Hôpital's rule on $n^{\alpha}/\log_2 n$) | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1112566', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/206911/']} | jdg_83036 |
stackexchange | llm_judgeable_groundtruth_similarity | 1589619 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Prove that, for integral values of $n\ge 1$, all the roots of the equation $$nz^n=1+z+z^2+...+z^n$$ lie within the circle $\vert z\vert=\frac{n}{n-1}$ Taking modulus on both sides, $$n\vert z\vert^n=\vert1+z+z^2+...+z^n\vert$$Using triangle inequality,$$n\vert z\vert^n\le 1+\vert z\vert+\vert z\vert^2+...+\vert z\vert^n$$$$\vert z\vert^n(n-1)\le 1+\vert z\vert+\vert z\vert^2+...+\vert z\vert^{n-1}$$ Using sum of GP formula,$$(n-1)\vert z\vert^n\le\frac{\vert z\vert^n-1}{\vert z\vert -1}$$$$(n-1)\frac{\vert z\vert^n}{\vert z\vert^n-1}\le\frac{1}{\vert z\vert -1}$$(I am not sure about the above step because I am multiplying with a number that can be negative.) How should I proceed?
Now provide the response and nothing else.
| $z=0$ is never a solution so we can safely rewrite the equation as $$n=\frac1{z^n}+\cdots+\frac1z+1.$$ If $z$ is a solution with norm strictly greater than $n/(n-1)$ then the first $n$ terms on the right hand side are strictly less (in absolute value) than $(n-1)/n$ so we would have $$n<n\frac{(n-1)}n+1$$ which is clearly impossible. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1589619', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/249297/']} | jdg_83037 |
stackexchange | llm_judgeable_groundtruth_similarity | 39193276 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two shapes: circle and rectangle. Want to convert them into one figure. Are there any ways to do that in SVG code? <svg width="400" height="400"> <defs> <g id="shape" fill="none" stroke="red"> <rect x="40" y="50" width="40" height="70" /> <circle cx="50" cy="50" r="50" /> </g> </defs> <use xlink:href="#shape" x="50" y="50" /> <use xlink:href="#shape" x="200" y="50" /></svg> Like this:
Now provide the response and nothing else.
| For anyone looking for the answer to the actual question of how to combine two outlined shapes into a single outlined shape (rather than putting a drop shadow on the combined shape), here is a possible solution: <svg width="400" height="400"> <defs> <rect id="canvas" width="100%" height="100%" fill="white" /> <rect id="shape1" x="40" y="50" width="40" height="70" /> <circle id="shape2" cx="50" cy="50" r="50" /> <mask id="shape1-cutout"> <use href="#canvas" /> <use href="#shape1" /> </mask> <mask id="shape2-cutout"> <use href="#canvas" /> <use href="#shape2" /> </mask> </defs> <use href="#shape1" stroke="red" fill="none" mask="url(#shape2-cutout)" /> <use href="#shape2" stroke="red" fill="none" mask="url(#shape1-cutout)" /></svg> This essentially draws the circle with the rectangle shape cut out of it and draws the rectangle with the circle cut out of it. When you place these "punched out" shapes one on top of the other, you get what appears to be a single outlined shape. Here's what the SVG actually does: It defines a white rectangle called "canvas" that is the same size as the SVG. It defines the two shapes that are to be combined ("shape1" and "shape2"). It defines a mask for each shape that combines the canvas (which has a fill of white) with the shape (which has a fill of black by default). Note that when you apply a mask to a shape, the part of the shape that corresponds to the white area of the mask is shown, while the part that corresponds with black part is hidden. It draws each shape with the the mask of the other shape applied. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39193276', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4354299/']} | jdg_83038 |
stackexchange | llm_judgeable_groundtruth_similarity | 38134499 |
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 getting nothing but errors from the ReactNative CameraRoll's saveImageWithTag function. Saving a local image with something like: CameraRoll.saveImageWithTag('./path/to/myimage.png'); .then(res => console.log(res)) .catch(err => console.log(err)); gives me the error: Error: The file “myimage.png” couldn’t be opened because there is no such file.(…) ./path/to/myimage.png in this case is the path I'd use to require an image for an Image source. What should the full path be for a local image be? Do I need to store them differently to make them accessible?
Now provide the response and nothing else.
| 0. Short answer Use RNFS to locate the local image. 1. For your title 'Save remote image to camera roll in React Native' The keyword is remote . Before using CameraRoll , we should link the library first. Then, I create one Image and one Button : render: function() { return ( <View style={styles.container}> <Image ref="logoImage" style={{ height:50, width: 50 }} source={{uri: 'http://facebook.github.io/react/img/logo_og.png'}} /> <TouchableHighlight style={styles.button} onPress={this._handlePressImage} underlayColor='#99d9f4'> <Text style={styles.buttonText}>Save Image</Text> </TouchableHighlight> </View> ); }, When I press the button, the program will save the image to camera roll: _handlePressImage: function() { console.log('_handlePressImage.'); var uri = this.refs.logoImage.props.source; console.log(uri); CameraRoll.saveImageWithTag(uri, function(result) { console.log(result); }, function(error) { console.log(error); }); }, React Native warns me that the API is deprecated, just use promise instead: var promise = CameraRoll.saveImageWithTag(uri);promise.then(function(result) { console.log('save succeeded ' + result);}).catch(function(error) { console.log('save failed ' + error);}); Now, we can see the logo image in our camera roll. 2. For your real problem in your content Despite your title says remote , your code uses the local path. Give the path './path/to/myimage.png' , I assume that the image path is relative to the .js file. That is, your image is not relative to the final running app, so it can not find the image file. Now change the Image to use local file: <Image ref="logoImage" style={{ height:50, width: 50 }} source={require('./logo_og.png')}/> and save the image like this: var promise = CameraRoll.saveImageWithTag('./logo_og.png'); which results in: Because CameraRoll API is corresponding to the Native Component , which belongs to the final running app, not the javascript. 3. Use RNFS to save local images First run the command below: npm install react-native-fs --save and then link the library. After Putting the image under Library/Caches : we can save the local image: var cacheImagePath = RNFS.CachesDirectoryPath+"/logo_og.png";console.log(cacheImagePath);var promise = CameraRoll.saveImageWithTag(cacheImagePath);promise.then(function(result) { console.log('save succeeded ' + result);}).catch(function(error) { console.log('save failed ' + error);}); Thanks. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38134499', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/586181/']} | jdg_83039 |
stackexchange | llm_judgeable_groundtruth_similarity | 12445488 |
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 following code to generate an ajax request: echo CHtml::dropDownList('teamA', '', EnumController::getTeamOption(), array( 'empty' => '(Team / Single)', 'ajax' => array( 'type'=>'POST', 'url'=> $url, 'update'=>"#resultA", //'data'=>"js:$('#teamA').hide().fadeIn()" ) )); In my main layout, I have the following: <?php Yii::app()->clientScript->scriptMap=array('jquery.js'=>false);?><?php Yii::app()->clientScript->scriptMap=array('jquery.min.js'=>false);?><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.js"></script><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js"></script> Yii is loading jQuery copy out of assets and then -- another copy, directly from Google. I want to use only Google copy and force Yii to not load own copy from assets. How can I do this?
Now provide the response and nothing else.
| In Yii you should never hardcode any javascript information in the main layout. Yii can determine if a client script (javascript) was already included, but for core scripts (like jquery or jqueryui) you have to modify those packages in your config file. Open the main.php configuration file and add all the js packages you need within the CClientScript component (you should add it inside components ), like this: 'clientScript'=>array( 'packages'=>array( 'jquery'=>array( 'baseUrl'=>'//ajax.googleapis.com/ajax/libs/jquery/1.8/', 'js'=>array('jquery.min.js'), 'coreScriptPosition'=>CClientScript::POS_HEAD ), 'jquery.ui'=>array( 'baseUrl'=>'//ajax.googleapis.com/ajax/libs/jqueryui/1.8/', 'js'=>array('jquery-ui.min.js'), 'depends'=>array('jquery'), 'coreScriptPosition'=>CClientScript::POS_BEGIN ) ),), Then, every time you need jquery just add this before your code: $cs = Yii::app()->getClientScript();$cs->registerCoreScript('jquery'); Yii will then include jquery (or any other script) only once, even if you call it several times in your code. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12445488', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/645421/']} | jdg_83040 |
Subsets and Splits