source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0023222713.txt" ]
Q: Place div at center and update function when user try to re-size window var wH = $(window).height(); var wW = $(window).width(); var sT = $(window).scrollTop(); var sL = $(window).scrollLeft(); jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", Math.max(0, ((wH - $(this).outerHeight()) / 2) + sT) + "px"); this.css("left", Math.max(0, ((wW - $(this).outerWidth()) / 2) + sL) + "px"); return this; } $('div').center(); I try to place div at center of page and I have found a function can do this. However, when windows re-size or user try to zoom in out, this function didn't update new position. Is anyway to run this function when user try to re-size windows or zoom in out? A: I believe the jQuery resize method should do exactly what you want: $(window).resize(function () { $('div').center(); }); Alternatively, you can do this with a plain DOM method: window.onresize = function () { $('div').center(); }; However, the plain DOM method will remove any existing handlers bound to the window resize event and may not behave identically between browsers. Also, you'll need to move these lines into your function so that they update when the handler gets called: var wH = $(window).height(); var wW = $(window).width(); var sT = $(window).scrollTop(); var sL = $(window).scrollLeft();
[ "worldbuilding.stackexchange", "0000101203.txt" ]
Q: How to safely capture someone when you have super-strength In the question How to safely knock someone out, it was explained to me that there isn't such a way. In which case, for a prospective superhero with super-strength and super-durability, what would be the safest way to capture random thugs off the street for the police to collect? Assume that the thugs pose negligible threat to the superhero. EDIT: When I said safely, I meant safely for the thug. The hero doesn't want to risk Grievous Bodily Harm charges later. A: If a lion, a tiger or an alligator, though being able of crunching an animal with a bite of their jaw, can gently hold and carry their cubs using the very same jaws, I can imagine that also a superhero, though being super strong, is able of modulating the strength he exercises. Using this modulation he can restrain the tug and, once restrained, use conventional immobilizers like handcuff or ropes to secure that the felon won't escape justice. A: Handcuffs and gentle handling is possible, of course, but what about using mere intimidation? From your questions it seems that we're mostly dealing with common thugs, not some insane revenge-fueled supervillain. Common thugs are very much human. If your superhero is able to show a display of overwhelming raw power, such as shrugging off any attack the thugs do or bend/crush nearby solid objects, then perhaps the thug would realize that giving up is the best thing they can do in the situation. Having increased speed may help too, to make the idea of escaping all but impossible. "Just give up and nobody needs to get hurt" and all that. Only once all of that fails would you resort to physical capture, preferably as effortlessly as possible (Swiftly handcuffing them, easily lifting them off the ground as if they're small children, etc) so it would further cement the image of overwhelming power once the story spreads all over media. In fact, once you've done this often enough, your reputation will probably precede you and your mere presence would be enough to intimidate nearby thugs to turn themselves in. A: Big bag. from https://www.youtube.com/watch?v=S-frp2gYp2I "Getting them in the sack is the hard part". Your super has a roll of big fabric bags. He has them made special. They are tough. He opens one up and then pulls it over the criminal. Then he closes up the top. It is easy for one super to carry a lot of criminals in their bags. If you have a knife you might cut your way out. These bags have steel threads (like those in steel belted tires) woven in which makes the cutting very slow. If you have a gun you could shoot through the bag. That would let individuals express their frustration at being in the bag but will not otherwise help much. Other criminals in other nearby bags will probably yell at the shooter to stop. A fabric bag will not cause a criminal to suffocate. The criminal could still use a phone from within the bag. Bags are washable and reusable which helps the earth. When you want to ask a criminal something you could let him poke his head out of the bag. If he is helpful you could let him leave it out. I do not think you should do that with a raccoon.
[ "stackoverflow", "0010654174.txt" ]
Q: How do I add instance storage to an existing Windows EC2 instance? I have a Windows 2008 EC2 instance to which I have done some customizing on the EBS boot drive. I started the instance as m1.small (or m1.large) and the instance storage does not appear as an additional drive. I've read that the -b switch in the ec2-run-instances command allows you to create mappings for the ephymeral instance storage. The ec2-run-instances command creates a new instance, however, in my case, the instance already exists and therefore I start it as ec2-start-instances, which does not have a -b switch for ephymeral instance storage. Is there any way I can get to the ephymeral instance storage that comes with an m1.small instance for my existing EBS-booted instance? UPDATE: It seems that nowadays (Feb 2015) Windows machines mount ephymeral instance storage in the Z: drive. A: I'm afraid this functionality isn't available (yet) for Amazon EC2, but it's a very good question in fact - the common answer used to refer to the explicated launch time requirement, see e.g. ec2-modify-instance-attribute: Note If you want to add ephemeral storage to an Amazon EBS-backed instance, you must add the ephemeral storage at the time you launch the instance. For more information, go to Overriding the AMI's Block Device Mapping in the Amazon Elastic Compute Cloud User Guide, or to Adding A Default Instance Store in the Amazon Elastic Compute Cloud User Guide. [emphasis mine] That hasn't been that much of an issue in the past, but given the recent introduction of 64-bit ubiquity implies a significant improvement of vertical scaling versatility (see EC2 Updates: New Medium Instance, 64-bit Ubiquity, SSH Client), this is suddenly a topic indeed - your question yields even more questions in turn: What happens for the converse case, i.e. when I start a sufficiently large instance with lots of ephemeral storage and scale it down (and possibly up again) thereafter? In case the initial block device mapping is retained somehow, should we always start with a large instance therefore? (I actually doubt that this is the case though.) This question can only be addressed by the AWS team I guess, so you may want to file a support request or relay the question to the Amazon Elastic Compute Cloud forum at least. A: I think what you're asking (but correct me if I'm wrong) is "how do I add additional storage to an EC2 instance?". In which case, the answer is: Select the Volumes panel in the AWS console and create a new volume of the size you want, making sure it's in the same Availability Zone as the instance you want to attach it to. Then select that new Volume, and click 'Attach' - select the instance you want to attach it to, and click OK. Now log-on to the instance, and in Computer Management select the Disk Management plugin, format the new unassigned partition, and give it whatever drive letter you wish. It will then show up in Explorer as a standard Windows drive.
[ "stackoverflow", "0043190651.txt" ]
Q: Trying to add a table with SQL, getting "invalid identifier" error with foreign key This is a block of code that SHOULD create a new table (vehicles) with the primary key being 'VNo' and the foreign key being 'did'. create table vehicles (VNo integer, model varchar(20), year integer, constraint vehicles_VNo_pk primary key (VNo), constraint vehicles_did_fk foreign key (did) references division(did) ); however, running this code yields a: ORA-00904: "DID": invalid identifier error, no matter what I do. Please help! This is for an important assignment. A: You need to include the did field in your table creation statement for vehicles: create table vehicles (VNo integer, model varchar(20), year integer, did column_type, constraint vehicles_VNo_pk primary key (VNo), constraint vehicles_did_fk foreign key (did) references division(did) ); replacing column_type with whatever type did should be.
[ "stackoverflow", "0053686810.txt" ]
Q: How to retrieve a specific object from a JSON value stored in sessionStorage? I have this stored in the session: What I'm looking to do is assign each object in the JSON as a variable so I can add them to the DOM appropriately. This works but prints everything out: if (sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9') != null) { $(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9')).appendTo('.div'); } What I'd like is something like this, but it doesn't work: var div1 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'a.cart-contents'))); var div2 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'a.footer-cart-contents'))); var div3 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'div.widget_shopping_cart_content'))); Any help would be greatly appreciated. Thank you! A: Getting the same value from the storage several times is not a good idea. In addition, you need better names for your variables. var json = sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9'); if (json) { var data = JSON.parse(json); if (data) { var cart_link = $(data['a.cart-contents']), footer_link = $(data['a.footer-cart-contents']), widget_div = $(data['div.widget_shopping_cart_content']); } }
[ "workplace.stackexchange", "0000023208.txt" ]
Q: Should I answer personalized job posting emails? I've got a few emails recently from recruiters (who I have not met before) about jobs which are related to my skills/fields. For example, one of them get my email address from my github profile (I'm using that email address for only github commits) and put some effort to the email (she used my last name, the location of the job is the same city as can be googled about me). However, I'm not really interested in those jobs. Should I answer these emails? Could there be any negative consequences if I just delete them? (I'm living in a small country/city.) A: You do have a couple of choices: ignore the email; respond with a polite no. As someone who gets hundreds of "spam" recruiter emails, I do tend to ignore the unsolicited one. Since they keep coming in, it appears to me that it doesn't cause an issue to ignore them. However, when I see one that is addressed correctly or otherwise catches my eye as important, I do send a note. The note usually goes like this: Thank you for your interest in my availability for position x. I am not currently looking to change positions, but am always open to future possibilities. Please feel free to contact me any time you run across a position that matches my skills. Thank you. Being polite can't hurt you with someone who might be able to help you find a new position at a later date.
[ "stackoverflow", "0004605365.txt" ]
Q: Python 3 C-API IO and File Execution I am having some serious trouble getting a Python 2 based C++ engine to work in Python3. I know the whole IO stack has changed, but everything I seem to try just ends up in failure. Below is the pre-code (Python2) and post code (Python3). I am hoping someone can help me figure out what I'm doing wrong.I am also using boost::python to control the references. The program is supposed to load a Python Object into memory via a map and then upon using the run function it then finds the file loaded in memory and runs it. I based my code off an example from the delta3d python manager, where they load in a file and run it immediately. I have not seen anything equivalent in Python3. Python2 Code Begins here: // what this does is first calls the Python C-API to load the file, then pass the returned // PyObject* into handle, which takes reference and sets it as a boost::python::object. // this takes care of all future referencing and dereferencing. try{ bp::object file_object(bp::handle<>(PyFile_FromString(fullPath(filename), "r" ))); loaded_files_.insert(std::make_pair(std::string(fullPath(filename)), file_object)); } catch(...) { getExceptionFromPy(); } Next I load the file from the std::map and attempt to execute it: bp::object loaded_file = getLoadedFile(filename); try { PyRun_SimpleFile( PyFile_AsFile( loaded_file.ptr()), fullPath(filename) ); } catch(...) { getExceptionFromPy(); } Python3 Code Begins here: This is what I have so far based off some suggestions here... SO Question Load: PyObject *ioMod, *opened_file, *fd_obj; ioMod = PyImport_ImportModule("io"); opened_file = PyObject_CallMethod(ioMod, "open", "ss", fullPath(filename), "r"); bp::handle<> h_open(opened_file); bp::object file_obj(h_open); loaded_files_.insert(std::make_pair(std::string(fullPath(filename)), file_obj)); Run: bp::object loaded_file = getLoadedFile(filename); int fd = PyObject_AsFileDescriptor(loaded_file.ptr()); PyObject* fileObj = PyFile_FromFd(fd,fullPath(filename),"r",-1,"", "\n","", 0); FILE* f_open = _fdopen(fd,"r"); PyRun_SimpleFile( f_open, fullPath(filename) ); Lastly, the general state of the program at this point is the file gets loaded in as TextIOWrapper and in the Run: section the fd that is returned is always 3 and for some reason _fdopen can never open the FILE which means I can't do something like PyRun_SimpleFile. The error itself is a debug ASSERTION on _fdopen. Is there a better way to do all this I really appreciate any help. If you want to see the full program of the Python2 version it's on Github A: So this question was pretty hard to understand and I'm sorry, but I found out my old code wasn't quite working as I expected. Here's what I wanted the code to do. Load the python file into memory, store it into a map and then at a later date execute that code in memory. I accomplished this a bit differently than I expected, but it makes a lot of sense now. Open the file using ifstream, see the code below Convert the char into a boost::python::str Execute the boost::python::str with boost::python::exec Profit ??? Step 1) vector<char> input; ifstream file(fullPath(filename), ios::in); if (!file.is_open()) { // set our error message here setCantFindFileError(); input.push_back('\0'); return input; } file >> std::noskipws; copy(istream_iterator<char>(file), istream_iterator<char>(), back_inserter(input)); input.push_back('\n'); input.push_back('\0'); Step 2) bp::str file_str(string(&input[0])); loaded_files_.insert(std::make_pair(std::string(fullPath(filename)), file_str)); Step 3) bp::str loaded_file = getLoadedFile(filename); // Retrieve the main module bp::object main = bp::import("__main__"); // Retrieve the main module's namespace bp::object global(main.attr("__dict__")); bp::exec(loaded_file, global, global); Full Code is located on github:
[ "stackoverflow", "0027144097.txt" ]
Q: Which elliptic curves does jarsigner support? I will be signing JARs with an ECDSA key, and I can choose now which elliptic curve I will use. I at least need to be able to generate the signature with jarsigner. Where can I see, what elliptic curves jarsigner supports? I tested that out of 65 elliptic curves supported by my OpenSSL installation, my jarsigner supports 46. Oracle documentation on jarsigner does not say anything about what is supported. Is it documented anywhere at all? A: Here is an answer: "Support for elliptic curves by jarsigner". To quote the conclusion: Support of elliptic curves by jarsigner depends on jarsigner itself and on the JRE configuration. There is no command-line option to list all supported curves.
[ "crypto.stackexchange", "0000031717.txt" ]
Q: Finding differentials and space complexity Most of article about differential cryptanalysis present the generic method, the way to find sub keys. But I can't find a clear explanation about how to find the differentials used in examples. In Differential Cryptanalysis of DES-like Cryptosystems by Biham and Shamir, the provide examples using differentials inputs such as $\Omega_p = 00\ 80\ 82\ 00\ 60\ 00\ 00\ 00_x$. I do get the idea about feeding S-box in order to retrieve the differentials but these S-box are only 6 bit input for 4 bit outputs (in DES). So the memory space required in order to do such analysis is $2^6 \times 2^4 = 1024$ integers $\approx 4\ Ko$. This can be easily placed in the RAM. The method is presented in Modern Cryptanalysis by Christopher Swenson. However given an S-box with a bigger input such as the one used in FEAL-X (while remaining broken), we need a table of the following given size : $2^{32} \times 2^{32} = 2^{64}$ integers $\approx 2^{32}\times 16\ Go$. Such thing can't be stored on current sized computer. Hence my question how is it possible to find the right differential for bigger input round functions without the size constraint of this analysis. A: If such a large Sbox with no structure were to be analysed you'd treat the analysis as a one-off precomputation. Considering only classical differential cryptanalysis as an example, after the precomputation you'd only need to keep track of the highest probability differentials since if you combine a high probability differential with a low probability one, you've already lost quite an edge and over multiple rounds your attack will fail. As for FEAL, there is lots of structure in the 32x32 round function and divide and conquer is the way to go. If there was a randomly chosen huge Sbox, life would be difficult, but it is also difficult for the designer who'd have a hell of a time proving the strength of his/her randomly chosen Sbox, with any kind of guarantee. Blowfish Sboxes which are key dependent, for example, are only 8x32 (thanks @J.D.) and this helps by limiting the number of input differences that need to be considered.
[ "ru.stackoverflow", "0000876000.txt" ]
Q: В консоли на странице с каптчей вылетает ошибка прошу помочь. У меня на сайте есть две страницы с каптчей 2.0 от гугл, на них в консоли вылетает ошибка Uncaught TypeError: Cannot read property 'channel' of null at sso.js:1 Вот ссылки на страницы: Страница с регистрацией Баг репорт Заранее спасибо! A: Простите, затупил Это ошибка chrome расширения office online. Но выходит оно только на страницах с каптчей
[ "stackoverflow", "0011347319.txt" ]
Q: HTML no break when expected I've got a strange splitting bug in a website I am making. Everywhere on the website the text is split in the correct way. But in one block it isn't. http://www.spanjevakantiewinkel.nl/ At the bottom: "aankomende evenementen". Bunol, the last words are under the words of the next block! But all CSS of these blocks is the same. I have no idea how to solve this. A: The text content of that paragraph has &nbsp; (probably \u00A0 in the original data) between the last words instead of normal spaces. Get rid of those and it will line break correctly.
[ "cogsci.stackexchange", "0000008234.txt" ]
Q: Can prosopagnostic (face-blind) people draw other people recognizably? Is it possible for people with face blindness / prosopagnosia to draw other people (whose faces they cannot recognize) such that non-face-blind people can recognize the people being drawn ? A: According to Bruce & Young model (1986), face recognition is composed of 2 main sub-processes, one more "perceptive" (called structural encoding) and the other one more "associative" (fru, pin, name generation). Bruce & Young model A person with "apperceptive prosopagnosia" cannot create a precise percept, that is a mental representation of who he's looking at. He's unlikely to be able to draw other people face. A person with "associative prosopagnosia" can create a percept of who he sees, but he cannot understand who the person is, deficit is semantic not perceptive. In this case, he is able to draw other people face, even though he cannot recognize it. This subdivision can be found also in object recognition process and its related impairments: apperceptive agnosia and associative agnosia. It's important to note that all this stuff is heavily theoretical. Reality is much more complex and sometimes unclear. Bruce, V., & Young, A. (1986). Understanding face recognition. British journal of psychology, 77(3), 305-327.
[ "stackoverflow", "0000526903.txt" ]
Q: Web Service and Report Manager don't load (Sql Server Express 2008 with Reporting Services) I've just installed Microsoft SQL Server Express 2008 (with Reporting Services). My installation is side by side with SQL Server 2005. So far creating reports and testing them in the development environment has worked fine, however I can't get the web server or report manager working. In the Reporting Services Configuration Manager, it appears that they have been configured and have a working address (eg: http://mymachine:8080/ReportServer_EXPRESS2008/ and http://mymachine:8080/Reports_EXPRESS2008/). The Virtual Directories don't exist in IIS, and clicking on the links in the config manager results in a "The page cannot be found". If I create the Virtual Directories in IIS, and then use Reporting Services Configuration Manager to modify the two sites, Reporting Services Configuration Manager appears to be working correctly (all the right messages appear, indicating that it created the new site and dropped the old site successfully). However, it only drops the existing Virtual Directory and does not create a new one. Has anyone had this problem before and/or know of a possible solution? A: Basically, Reporting Services 2008 doesn't use IIS anymore. By coincidence (or default?), I already had IIS (with Reporting Services 2005) running off port 8080. Reporting Services 2008 also wanted to run off port 8080. It appears that the new IIS free address reservation system doesn't work in this situation. Changing the port number fixes the problem.
[ "stackoverflow", "0016970192.txt" ]
Q: Hide US on google geochart when region is set to Canada I need to hide US on geo chart, when region is set to Canada: google.load('visualization', '1', {'packages': ['geochart']}); google.setOnLoadCallback(drawVisualization); function drawVisualization() {var data = new google.visualization.DataTable(); data.addColumn('string', 'Country'); data.addColumn('number', 'Value'); data.addColumn({type:'string', role:'tooltip'});var ivalue = new Array(); data.addRows([[{v:'CA-BC',f:'CA-BC'},0,'Test']]); var options = { backgroundColor: {fill:'#FFFFFF',stroke:'#FFFFFF' ,strokeWidth:0 }, colorAxis: {minValue: 0, maxValue: 0, colors: ['#0000ff',]}, legend: 'none', backgroundColor: {fill:'#FFFFFF',stroke:'#FFFFFF' ,strokeWidth:0 }, datalessRegionColor: '#f5f5f5', displayMode: 'markers', enableRegionInteractivity: 'true', resolution: 'provinces', region:'CA', keepAspectRatio: true, width:700, height:500, tooltip: {textStyle: {color: '#444444'}, trigger:'focus'} }; var chart = new google.visualization.GeoChart(document.getElementById('visualization')); chart.draw(data, options); } http://jsfiddle.net/jk171505/VJtBR/ A: With the API options, you can't really do it. You can use advanced CSS selectors to hide the SVG shapes. Add this CSS and it will hide the US shapes: #visualization path:nth-child(237), #visualization path:nth-child(236) { display:none; } http://jsfiddle.net/cmoreira/mMadX I have built a page with some information on how to use this and other CSS techniques with the Google Geochart API. In case it helps, here's the link: http://cmoreira.net/interactive-world-maps-demo/advanced-customization/
[ "stackoverflow", "0017305490.txt" ]
Q: Overlapping labels in side-by-side chart I am working with a side-by-side bar chart and facing a common issue of overlapping labels. I have looked through previous queries and none seem to work for me and I don't know why. Below is the command I have and the results ggplot(data=SEM_Breakdown_2,aes(x=DMA_Clean, y=AQH)) + geom_bar(aes(fill=SEM), stat="identity",position=position_dodge(width=1)) + geom_text(aes(label=round(AQH,digit=0),ymax=AQH), position=position_dodge(width=1),vjust=-1,size=5) Just want to show the labels at each columns so I can actually ready them. Thanks modified my code and below, while not perfect it works geom_text(aes(label=round(Unique..IPs,digit=0),ymax=Unique..IPs),position=position_dodge(width=1),vjust=-1,hjust=ifelse(SEM_Breakdown_2$SEM=="Yes",-0.4,1.4),size=4) A: Add an additional parameter to the aes() call, x=offset, and make the value dependant on whether the bar is a "yes" bar or a "no" bar. For instance, x = ifelse( test.if.yes.bar, 5, -5)
[ "stackoverflow", "0021069340.txt" ]
Q: How to make a behavior of a variable final when its obtained only once through a setter Assume this imaginary scenario where a variable value is obtained only through a setter but once obtained it cannot be modified. class Foo { Bar bar; public void setBarOnlyOnce(Bar bar) { this.bar = bar } } Now since I dont want to change the value of bar, once being set, I would add a check in setter. public void setBarOnlyOnce(Bar bar) { if (bar != null) { this.bar = bar } } Quite an obvious handicap is that class is hard to maintain, as anyone can add a method to this class which can modify value of bar negligently. Is there some link/guidelines/design patterns instructing how to deal with those variables which you want to be final, but cant keep it final as they would be obtained only through setter ? A: One can implement a property wrapper to control field access: class ImmutableProperty<T>{ private T value; public T get() { return value; } public void set(T value) { if (this.value == null) { this.value = value; } else { throw new IllegalStateException("Once set, ImmutableProperty cannot be modified"); } } } use it like this to prevent unwanted modifications: private final ImmutableProperty<String> name = new ImmutableProperty<>(); ... name.set("I can do that!"); name.set("But here I'm going to fail("); This approach prevents anyone from reassigning name variable itself and clearly expresses your initial intention for this variable to be immutable. EDIT: This implementation is a bit smarter and allow null values to be set if necessary: class ImmutableProperty<T>{ private boolean set; private T value; public T get() { return value; } public void set(T value) { if (!set) { set = true; this.value = value; } else { throw new IllegalStateException("Once set, ImmutableProperty cannot be modified"); } } } and this one also pretends to be thread-safe: class ImmutableProperty<T> { class DataHolder { final T value; DataHolder(T value) { this.value = value; } } private final DataHolder defaultValue = new DataHolder(null); private final AtomicReference<DataHolder> holder = new AtomicReference<>(defaultValue); public T get() { return holder.get().value; } public void set(T value) { if (!holder.compareAndSet(defaultValue, new DataHolder(value))) { throw new IllegalStateException("Once set, ImmutableProperty cannot be modified"); } } } Choose the one that better suits your needs.
[ "stackoverflow", "0044033762.txt" ]
Q: Testing if a Decimal is a whole number in Swift Using Swift 3. I am finding a lot of strange solutions online for checking if a Decimal object is a whole number. Everything feels far more complicated then it needs to be. Here is my solution: extension Decimal { var isWholeNumber: Bool { return self.exponent == 1 } } In my tests this works. My question is am I missing something obvious? A: Thanks for the comments! Here is what I am using now. extension Decimal { var isWholeNumber: Bool { return self.isZero || (self.isNormal && self.exponent >= 0) } } A: Here is a translation of the Objective-C solution in Check if NSDecimalNumber is whole number to Swift: extension Decimal { var isWholeNumber: Bool { if isZero { return true } if !isNormal { return false } var myself = self var rounded = Decimal() NSDecimalRound(&rounded, &myself, 0, .plain) return self == rounded } } print(Decimal(string: "1234.0")!.isWholeNumber) // true print(Decimal(string: "1234.5")!.isWholeNumber) // false This works even if the mantissa is not minimal (or the exponent not maximal), such as 100 * 10-1. Example: let z = Decimal(_exponent: -1, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (100, 0, 0, 0, 0, 0, 0, 0)) print(z) // 10.0 print(z.exponent) // -1 print(z.isWholeNumber) // true
[ "stackoverflow", "0021306667.txt" ]
Q: Why does System.Convert has ToDateTime that accepts DateTime? // // Summary: // Returns the specified System.DateTime object; no actual conversion is performed. // // Parameters: // value: // A date and time value. // // Returns: // value is returned unchanged. public static DateTime ToDateTime(DateTime value); Why does System.Convert has ToDateTime that accepts DateTime ? The method documentation states the value remain unchanged. A: Convention, predictability and because the IConvertable defines the method ToDateTime. My believe is that under the covers System.Convert simply runs through all the combinations of the IConvertable classes.
[ "scifi.stackexchange", "0000158476.txt" ]
Q: Is there evidence which supports the existence of gunpowder in Middle-earth? Gunpowder is often referred to as the source of Gandalf's fireworks. But, it is never clearly stated what Gandalf's fireworks were made up of. The fireworks were by Gandalf: they were not only brought by him, but designed and made by him; and the special effects, set pieces, and flights of rockets were let off by him. But there was also a generous distribution of squibs, crackers, backarappers, sparklers, torches, dwarf-candles, elf-fountains, goblin-barkers and thunder-claps. A more likely possibility is that the fireworks were made with the power of Narya, the Ring of Fire, but that too is not confirmed. Another reference to gunpowder is through Saruman's inventions. Even as they spoke there came a blare of trumpets. Then there was a crash and a flash of flame and smoke. The waters of the Deeping-stream poured out hissing and foaming: they were choked no longer, a gaping hole was blasted in the wall. A host of dark shapes poured in. ‘Devilry of Saruman!’ cried Aragorn. It is never said that this 'bomb' was made up of gunpowder or Saruman's magical capabilities, but Peter Jackson used the former in the 2nd film. Of course, this is completely non-canonical and doesn't prove that gunpowder exists in Tolkien's Middle-earth. Also, when Isengard was attacked by the Ents: ‘Isengard began to fill up with black creeping streams and pools. They glittered in the last light of the Moon, as they spread over the plain. Every now and then the waters found their way down into some shaft or spouthole. Great white steams hissed up. Smoke rose in billows. There were explosions and gusts of fire. One great coil of vapour went whirling up, twisting round and round Orthanc, until it looked like a tall peak of cloud, fiery underneath and moonlit above. And still more water poured in, until at last Isengard looked like a huge flat saucepan, all steaming and bubbling.’ Also, during the Siege of Gondor: But the engines did not waste shot upon the indomitable wall. It was no brigand or orc-chieftain that ordered the assault upon the Lord of Mordor’s greatest foe. A power and mind of malice guided it. As soon as the great catapults were set, with many yells and the creaking of rope and winch, they began to throw missiles marvellously high, so that they passed right above the battlement and fell thudding within the first circle of the City; and many of them by some secret art burst into flame as they came toppling down. But again, though speculated, it is never stated in these 2 instances that it was gunpowder, Therefore, is it even plausible to say that gunpowder exists in Middle-earth? Note: This is not a duplicate of: Why wasn't gunpowder more common in Middle Earth? I am asking about the evidence concerning the existence of gunpowder. Whereas the accepted answer in the linked post merely describes the existence of magic and it's different forms in Tolkien's legendarium and does nothing to describe the existence of gunpowder. The answer by Dronz is reasonable, but it seems speculative and there was no evidence given. A: It's possible, but also likely is just magical There's evidence to suggest gunpowder existed in Middle-earth, but it's only mentioned explicitly on a one occasion (within Tolkien's Legendarium1). This is in The Hobbit when Gandalf's explosion of light, to distract the orcs and escape, is described as smelling like gunpowder. (Emphasis mine) “But not Gandalf. Bilbo’s yell had done that much good. It had wakened him up wide in a splintered second, and when goblins came to grab him, there was a terrific flash like lightning in the cave, a smell like gunpowder, and several of them fell dead. The Hobbit - Chapter IV, Over Hill and Under Hill However, after this everything is left to subtleties. Tolkien left it vague enough that it could be some form of "Magical Engineering". However, whether he intended it to be gunpowder, or a similar magical or fantastical invention to stray minds away from the early invention, the evidence of the existence of something of the like is extensive. To begin, in the Battle of Isengard, after the Ents flooded the ring, Saruman's machinery is described as having exploded. Isengard began to fill up with black creeping streams and pools. They glittered in the last light of the Moon, as they spread over the plain. Every now and then the waters found their way down into some shaft or spouthole. Great white steams hissed up. Smoke rose in billows. There were explosions and gusts of fire. One great coil of vapour went whirling up, twisting round and round Orthanc, until it looked like a tall peak of cloud, fiery underneath and moonlit above. And still more water poured in, until at last Isengard looked like a huge flat saucepan, all steaming and bubbling. The Two Towers: Book Three - Chapter IX, Flotsam and Jetsam Continuing on earlier into the same book, when the walls of the Hornburg are breached. The explosion is described as having a blast of flame and smoke. Even as they spoke there came a blare of trumpets. Then there was a crash and a flash of flame and smoke. The waters of the Deeping-stream poured out hissing and foaming: they were choked no longer, a gaping hole was blasted in the wall. A host of dark shapes poured in. ‘Devilry of Saruman!’ cried Aragorn. ‘They have crept in the culvert again, while we talked, and they have lit the fire of Orthanc beneath our feet. The Two Towers: Book Three - Chapter VII, Helm's Deep [...] They have a blasting fire, and with it they took the Wall. ibid. Again although this could be argued to be something other than gunpowder, if it was magic, it would be strange for the orcs to have been able to set it off themselves.2 Finally, further references to "blasting" are found in The Return of the King ‘They have taken the wall!’ men cried. ‘They are blasting breaches in it. They are coming!’ The Return of the King: Book Five - Chapter IV, The Siege of Gondor [...] But the engines did not waste shot upon the indomitable wall. [...] As soon as the great catapults were set, with many yells and the creaking of rope and winch, they began to throw missiles marvellously high, so that they passed right above the battlement and fell thudding within the first circle of the City; and many of them by some secret art burst into flame as they came toppling down. ibid. The Return of the King, again, does nothing to suggest this has to be gunpowder, however this time the orcs are using inventions of Sauron, and unless Sauron and Saruman had shared their magic, it seems more likely that they had a common weapon, gun powder. I am of this opinion as both were very skilled Maiar of the Valar Aulë, known as The Smith of the Valar. The final argument for the existence of gunpowder is it Gandalf's fireworks. Although entirely plausible these are entirely magical, it is likely, from the above examples that there is some gunpowder in them. ... the special effects, set pieces, and flights of rockets were let off by him. The Fellowship of the Ring: Book One - Chapter I, An Unexpected Party The distinguishing of the three parts of the fireworks suggest that they were different. From films, we see that the special effects are likely magical, as a giant Dragon flies around as a firework. However the rockets themselves are likely powered by some form of gunpowder. Gandalf is described as being an expert of pyrotechnics, which suggest possibly "Magical Pyrotechnics" but not necessarily. In conclusion, I am of the opinion, the Tolkien's inclusion of explosions, likely from his involvement at the Somme, was inspired by gunpowder but left vague enough to be described as the aforementioned "Magical Engineering" to stray doubts of the extremely early existence of gunpowder. 1 Fireworks are mention in Farmer Giles of Ham as used in fireworks, this is however not part of the Legendarium, and therefore not canonical. 2 From the following we can see that the explosive needed fire to be set off, this however is not necessarily canonical as it comes from one of Jackson's films.
[ "stackoverflow", "0039047780.txt" ]
Q: TypeError: getState is not a function when adding middleware to Redux Using this code in my configureStore.dev.js file, I get an Uncaught TypeError: getState is not a function when adding applyMiddleware(reduxImmutableStateInvariant). When I remove this added middleware, my project runs fine. What is the proper way to add this middleware? Here is the full file: import {createStore, compose, applyMiddleware} from 'redux'; import rootReducer from '../reducers'; import reduxImmutableStateInvariant from 'redux-immutable-state-invariant'; export default function configureStore(initialState) { const store = createStore(rootReducer, initialState, compose( // Add other middleware on this line... applyMiddleware(reduxImmutableStateInvariant), window.devToolsExtension ? window.devToolsExtension() : f => f // add support for Redux dev tools ) ); if (module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept('../reducers', () => { const nextReducer = require('../reducers').default; // eslint-disable-line global-require store.replaceReducer(nextReducer); }); } return store; } A: reduxImmutableStateInvariant is a function that you need to call before passing it into applyMiddleware. const store = createStore(rootReducer, initialState, compose( // Add other middleware on this line... applyMiddleware(reduxImmutableStateInvariant()), window.devToolsExtension ? window.devToolsExtension() : f => f // add support for Redux dev tools ) ); Where is this in the docs? In the github README docs, is called after being imported (via require) reduxImmutableStateInvariant. See the third line, below: // Be sure to ONLY add this middleware in development! const middleware = process.env.NODE_ENV !== 'production' ? [require('redux-immutable-state-invariant')(), thunk] : [thunk]; // Note passing middleware as the last argument to createStore requires redux@>=3.1.0 const store = createStore( reducer, applyMiddleware(...middleware) ); Why isn't thunk a function, though? In the thunk middleware, the thunk function is called before it is returned. const thunk = createThunkMiddleware(); thunk.withExtraArgument = createThunkMiddleware; export default thunk; So why is redux-immutable-state-invariant a function? Based on the code, it looks like you can pass in a function (isImmutable), that is used to determine which properties in your redux state are immutable. I think that providing your own isImmutable function is what allows this middleware to work nicely with other immutable libraries. export default function immutableStateInvariantMiddleware(isImmutable = isImmutableDefault) { That method is used here https://github.com/leoasis/redux-immutable-state-invariant/blob/5ed542246e32b7eec06879b25e5a0a478daf4892/src/trackForMutations.js#L5
[ "stackoverflow", "0030492087.txt" ]
Q: Show all results in postgresql? My postgres windows client, upon receiving a query with many results, only shows some of them initially, showing -- More -- at the bottom and making you hit "enter" to show each new result line. This is cumbersome and silly. What can I do to make it show me absolutely every result from the start? A: Assuming you mean psql with "my postgres windows client", you can turn off the use of the pager using the \pset command: \pset pager off If you want to permanently turn the pager off, add that line to your psqlrc.conf file.
[ "stackoverflow", "0020793351.txt" ]
Q: passing variable using void * I was writing an interface(using FLTK but this doesn't matter). I made a button and its callback function. In this callback function I need to use data in a variable outside the callback function(which is Myclass mc in the code). The code looks like the following (I didn't paste the unnecessary parts): class Myclass { ... } void button_callback( Fl_Widget* o, void* data) { Fl_Button* button=(Fl_Button*)o; Myclass *a; a=data; a->MyMemberFunction(); } int main() { Myclass mc; ... Fl_Button button( 10, 150, 70, 30, "A button" ); button.callback( button_callback,&mc ); ... } However at the place of "a=data;" I got an error saying void * cannot be assigned to Myclass *, what should I do? Many thanks! A: Assuming that the data coming in through the void* is a pointer to Myclass, you need to add a reinterpret_cast from the void*, like this: Myclass *a = reinterpret_cast<Myclass*>(data); This will tell the compiler that you know for sure that the data is a pointer to Myclass, letting you call MyMemberFunction() through that pointer.
[ "stackoverflow", "0025219534.txt" ]
Q: What are nested routes for in Rails? I am new to learning Rails and have just encountered nested routes. The example I am looking at involves blog articles and comments. I am trying to undestand what the benefit of nested routes are in Rails. As far as I can tell all the information contained in a nested route for a comment such as /articles/:article_id/comments/:id(.:format) is all contained in the comment object itself so it does not communicating additional information to the Action. Why not just have unnested routes such as /comments/:id(.:format)? There is obviously a very good reason for using nested routes but I havent been able to work it out. The only benefit I can see so far is it gives a better illustration of the relation between articles and comments when reading the URL but all this information is contained in the comment object anyway. Could someone explain this? A: In your model you would have setup this association class Article< ActiveRecord::Base has_many :comments end class Comment< ActiveRecord::Base belongs_to :article end So each comment is associated with an article and you need some logic to find corresponding article for a comment This is where nested route comes in and lets you find article for that comment in your controller action. If you look at that route again /articles/:article_id/comments/:id(.:format) This is the comment controllers show action and this route allows you to find both article and your comment inside show action def show @article = Article.find(params[:article_id]) @comment = Comment.find(params[:id]) # if you are not using nested routes then you can find out associated article by @article = @comment.article # but you'll have to query your database to get it which you can simply find if you are using nested route end More than the show action(where you can use some other logic to find article associated with that comment) you need nested route for your new action where you have to find that article and then build a comment for that article by something like def new @article = Article.new @comment = @article.comments.build end As @August pointed out you can separate out actions for which you want your route to be nested by using shallow nesting, you can do: resources :articles do resources :comments, shallow: true end Checkout nested routes for more information
[ "stackoverflow", "0002114823.txt" ]
Q: How do I check if an object contains a byte array? I'm having an issue with the following code. byte[] array = data as byte[]; // compile error - unable to use built-in conversion if (array != null) { ... I only want to assign the data to array variable if the data is actually a byte array. A: How about this: byte[] array = new byte[arrayLength]; if (array is byte[]) { // Your code } A: Try if(data.GetType().Name == "Byte[]") { // assign to array }
[ "stackoverflow", "0013162354.txt" ]
Q: postData method not executing function I have two jqGrids. In the first grid I select a row and the second grid refreshes with data based on the id of the first grid. At least that is how it is supposed to work. //This is code from the second grid postData: '{ lobId: ' + BudgetCore.getLobId() + ' }', //Snippet from BudgetCore... getLobId: function () { var row = jQuery(BudgetCore.GridTables.Lob).jqGrid('getGridParam', 'selrow'); return row; } In Chrome I try to debug the function, getLobid() but it is never executed. The postData request sent: { lobId:null }. If I change the code above to '{ lobId: ' + 1 + ' }' it works, so there must be something wrong that is causing this function not to execute. In the Chrome JS console executing BudgetCore.getLobId() works fine. A: You should use postData: { lobId: function () { return $(BudgetCore.GridTables.Lob).jqGrid('getGridParam', 'selrow'); } } See the answer for more details. UPDATED: If you need to use JSON.stringify additionally inside of serializeGridData then you can't use more the simplest version of serializeGridData: serializeGridData: function (postData) { return return JSON.stringify(postData); } Instead of that you should use a little more complex version of serializeGridData which I described in the answer: serializeGridData: function (postData) { var propertyName, propertyValue, dataToSend = {}; for (propertyName in postData) { if (postData.hasOwnProperty(propertyName)) { propertyValue = postData[propertyName]; if ($.isFunction(propertyValue)) { dataToSend[propertyName] = propertyValue(); // call the function } else { dataToSend[propertyName] = propertyValue; } } } return JSON.stringify(dataToSend); }
[ "stackoverflow", "0000867966.txt" ]
Q: The regular expression for finding the image url in tag in HTML using VB .Net code I want to extract the image url from any website. I am reading the source info through webRequest. I want a regular expression which will fetch the Image url from this content i.e the Src value in the <img> tag. A: I'd recommend using an HTML parser to read the html and pull the image tags out of it, as regexes don't mesh well with data structures like xml and html. In C#: (from this SO question) var web = new HtmlWeb(); var doc = web.Load("http://www.stackoverflow.com"); var nodes = doc.DocumentNode.SelectNodes("//img[@src]"); foreach (var node in nodes) { Console.WriteLine(node.src); }
[ "stackoverflow", "0061835927.txt" ]
Q: python - how to sum the average of the amount per month per year I have data records look like this category dt userid amt 1 4/14/2019 1 140 1 5/1/2019 1 500 2 5/5/2019 1 300 3 5/19/2019 1 230 2 6/17/2019 1 200 4 6/18/2019 1 400 1 7/30/2019 1 400 1 8/17/2019 1 300 2 12/2/2019 1 200 2 12/23/2019 1 500 1 1/10/2019 2 470 1 2/25/2019 2 450 2 10/4/2019 2 350 Q1: How can I sum the average of the amount per month per year? user month1 month2 month3 month4 month5 month6 month7 month8 month9 month10 month11 month12 avg_all_month 1 0 0 0 140 343.33 300 400 300 0 0 0 350 305.55 2 470 450 0 0 0 0 0 0 0 350 0 0 423.33 Q2: How to count transaction per category user pro_cat1 pro_cat2 pro_cat3 pro_cat4 total_product 1 4 3 1 1 7 2 2 1 0 0 3 A: If there is same year you can use DataFrame.pivot_table with DataFrame.reindex and DataFrame.add_prefix with mean per all months: df['dt'] = pd.to_datetime(df['dt']) df2 = (df.pivot_table(index='userid', columns=df['dt'].dt.month, values='amt', aggfunc='mean', fill_value=0) .reindex(range(1, 13), axis=1, fill_value=0) .add_prefix('month') .assign(avg_all_month = lambda x: df.groupby('userid')['amt'].mean()) .reset_index() .rename_axis(None, axis=1)) print (df2) userid month1 month2 month3 month4 month5 month6 month7 month8 \ 0 1 0 0 0 140 343.333333 300 400 300 1 2 470 450 0 0 0.000000 0 0 0 month9 month10 month11 month12 avg_all_month 0 0 0 0 350 317.000000 1 0 350 0 0 423.333333 And then for second is used crosstab with sum: df3 = (pd.crosstab(df['userid'], df['category']) .add_prefix('pro_') .assign(total_product = lambda x: x.sum(axis=1)) .reset_index() .rename_axis(None, axis=1) ) print (df3) userid pro_1 pro_2 pro_3 pro_4 total_product 0 1 4 4 1 1 10 1 2 2 1 0 0 3
[ "stackoverflow", "0002056948.txt" ]
Q: .NET JIT potential error? The following code gives different output when running the release inside Visual Studio, and running the release outside Visual Studio. I'm using Visual Studio 2008 and targeting .NET 3.5. I've also tried .NET 3.5 SP1. When running outside Visual Studio, the JIT should kick in. Either (a) there's something subtle going on with C# that I'm missing or (b) the JIT is actually in error. I'm doubtful that the JIT can go wrong, but I'm running out of other possiblities... Output when running inside Visual Studio: 0 0, 0 1, 1 0, 1 1, Output when running release outside of Visual Studio: 0 2, 0 2, 1 2, 1 2, What is the reason? using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Test { struct IntVec { public int x; public int y; } interface IDoSomething { void Do(IntVec o); } class DoSomething : IDoSomething { public void Do(IntVec o) { Console.WriteLine(o.x.ToString() + " " + o.y.ToString()+","); } } class Program { static void Test(IDoSomething oDoesSomething) { IntVec oVec = new IntVec(); for (oVec.x = 0; oVec.x < 2; oVec.x++) { for (oVec.y = 0; oVec.y < 2; oVec.y++) { oDoesSomething.Do(oVec); } } } static void Main(string[] args) { Test(new DoSomething()); Console.ReadLine(); } } } A: It is a JIT optimizer bug. It is unrolling the inner loop but not updating the oVec.y value properly: for (oVec.x = 0; oVec.x < 2; oVec.x++) { 0000000a xor esi,esi ; oVec.x = 0 for (oVec.y = 0; oVec.y < 2; oVec.y++) { 0000000c mov edi,2 ; oVec.y = 2, WRONG! oDoesSomething.Do(oVec); 00000011 push edi 00000012 push esi 00000013 mov ecx,ebx 00000015 call dword ptr ds:[00170210h] ; first unrolled call 0000001b push edi ; WRONG! does not increment oVec.y 0000001c push esi 0000001d mov ecx,ebx 0000001f call dword ptr ds:[00170210h] ; second unrolled call for (oVec.x = 0; oVec.x < 2; oVec.x++) { 00000025 inc esi 00000026 cmp esi,2 00000029 jl 0000000C The bug disappears when you let oVec.y increment to 4, that's too many calls to unroll. One workaround is this: for (int x = 0; x < 2; x++) { for (int y = 0; y < 2; y++) { oDoesSomething.Do(new IntVec(x, y)); } } UPDATE: re-checked in August 2012, this bug was fixed in the version 4.0.30319 jitter. But is still present in the v2.0.50727 jitter. It seems unlikely they'll fix this in the old version after this long. A: I believe this is in a genuine JIT compilation bug. I would report it to Microsoft and see what they say. Interestingly, I found that the x64 JIT does not have the same problem. Here is my reading of the x86 JIT. // save context 00000000 push ebp 00000001 mov ebp,esp 00000003 push edi 00000004 push esi 00000005 push ebx // put oDoesSomething pointer in ebx 00000006 mov ebx,ecx // zero out edi, this will store oVec.y 00000008 xor edi,edi // zero out esi, this will store oVec.x 0000000a xor esi,esi // NOTE: the inner loop is unrolled here. // set oVec.y to 2 0000000c mov edi,2 // call oDoesSomething.Do(oVec) -- y is always 2!?! 00000011 push edi 00000012 push esi 00000013 mov ecx,ebx 00000015 call dword ptr ds:[002F0010h] // call oDoesSomething.Do(oVec) -- y is always 2?!?! 0000001b push edi 0000001c push esi 0000001d mov ecx,ebx 0000001f call dword ptr ds:[002F0010h] // increment oVec.x 00000025 inc esi // loop back to 0000000C if oVec.x < 2 00000026 cmp esi,2 00000029 jl 0000000C // restore context and return 0000002b pop ebx 0000002c pop esi 0000002d pop edi 0000002e pop ebp 0000002f ret This looks like an optimization gone bad to me... A: I copied your code into a new Console App. Debug Build Correct output with both debugger and no debugger Switched to Release Build Again, correct output both times Created a new x86 configuration (I'm on running X64 Windows 2008 and was using 'Any CPU') Debug Build Got the correct output both F5 and CTRL+F5 Release Build Correct output with Debugger attached No debugger - Got the incorrect output So it is the x86 JIT incorrectly generating the code. Have deleted my original text about reordering of loops etc. A few other answers on here have confirmed that the JIT is unwinding the loop incorrectly when on x86. To fix the problem you can change the declaration of IntVec to a class and it works in all flavours. Think this needs to go on MS Connect.... -1 to Microsoft!
[ "stackoverflow", "0004559204.txt" ]
Q: Unique names in INSTALLED_APPS Django limitation Django docs says: the final dotted part of the path to the module defined in INSTALLED_APPS must be unique I'm developing a CMS based on Django. And here comes the problem: the moment will come when two 3rd-party developers create two different apps with the same name. Why is it so? Is there any possibility to overcome this limitation? A: For the time being, the only solution is to use unique application names. This is a known limitation which is currently being worked on. For reference, it was one of the accepted projects during the 2010 Google Summer of Code by Arthur Koziel, and you can see some of the background and design considerations on Django's 2010 GSOC wiki page. My current understanding is that Arthur's work was largely successful, but due to concerns about making the 1.3 release a feature-light/bugfix-heavy release it was decided to delay merging the app loading refactor branch into trunk until the 1.4 development cycle.
[ "ux.stackexchange", "0000040098.txt" ]
Q: Action menu placement for bulk actions in a grid I have been playing with an idea of placing a bulk action drop down menu for a grid/table in the header of the column where the selections are done. This is to save some precious space above the table for some other tools, such as filters. I have not seen this done anywhere, the typical solution would be something along the lines of gmail, placing the action menu above the table. I think it is pretty straight forward - wondering if anyone can come up with downsides for this solution? A: Quite straight forward, and not an uncommon solution. There are two possible downsides here however, which I've heard users reaction in training sessions. Users can't find the control. They see it, but it's not entirely obvious that you should use this one for delete or move to another location. The drop down menu hides the selected items. When deleting records you want to be sure that you delete the right items. If you hide selected items, users feel insecure, and that's bad. Recommendations are: make the control very prominent and don't hide items with the drop down. A: Users might confuse the triangular dropdown symbol with the more common "column sort order indicator" symbol and therefore don't recognize the dropdown as such. A: Yes it is safe and pretty common solution to perform "Group Actions". But when you implement that, keep following aspects in mind. A group actions button must be more visible than the standard buttons It's label should be different from elements lying underneath I had implemented something similar which looked like that
[ "stackoverflow", "0039197421.txt" ]
Q: Multiply array with diagonal matrix stored as vector I have a 1D array A = [a, b, c...] (length N_A) and a 3D array T of shape (N_A, N_B, N_A). A is meant to represent a diagonal N_A by N_A matrix. I'd like to perform contractions of A with T without having to promote A to dense storage. In particular, I'd like to do np.einsum('ij, ikl', A, T) and np.einsum('ikl, lm', T, A) is it possible to do such things while keeping A sparse? Note this question is similar to dot product with diagonal matrix, without creating it full matrix but not identical, since it's not clear to me how one generalizes to more complicated index patterns. A: np.einsum('ij, ikl', np.diag(a), t) is equivalent to (a * t.T).T. np.einsum('ikl, lm', t, np.diag(a)) is equivalent to a * t. (found by trial-and-error)
[ "physics.stackexchange", "0000025082.txt" ]
Q: What is an asterism compared to a constellation? I'm doing an astronomy exam tomorrow and in the practice paper it asks for the difference between constellation and asterism. It seems asterism is a group of recognizable stars; however I thought that is what a constellation is. So what exactly is the difference? A: The constellations are the 88 internationally recognized stellar groupings in the sky that toghether cover the entire celestial sphere. They typcially correspond to a recognziable pattern and many are named from mythology. However, in modern usage, a specified constellation tecnically referres to the entire region of the sky, not just the recognizable star pattern. An asterism is also a group of stars that don't correspond to the recognized constellations. Some, like the Big Dipper, are a subset of the stars in a larger constellation (in the case of the Big Dipper, the constellation is Ursa Major). Others are made up of stars from multiple constellations. An example of this type is the Summer Triangle, which is composed of the three bright stars Vega, Deneb, and Altair, which are the brightest stars in the Constellations Vega, Cyngus and Aquila, respectively. These are all first magnitude stars and when the triangle is up, it is summer time in the Northern Hemisphere. A: An asterism is a group of recognizable stars, like your definition says. However, it's usually a group within a constellation. A good example of an asterism is the Big Dipper (or the Plough, if you're in the UK). It's a familiar group of stars, but by itself it's not a constellation. It's a group of stars within the Ursa Major constellation. Another asterism is the Pleiades, which is a small cluster of stars found in Taurus. Edit: And to be precise, a constellation actually refers to an area of the sky and not the pattern of stars. The constellation Orion is made up of a specific area of the sky and not just the stars that look like a hunter. A: The difference is minor. Constellations are well known groups of "recognizeable" stars. An Asterism is any group of stars that seems visually related, but may not be one of the generally recognized constellations. An Asterism might be a sub group of a larger constellation, or it could span across multiple constellations.
[ "stackoverflow", "0016785300.txt" ]
Q: Make the image DIV visible on every tab click In the current example the image DIV tag is placed inside each tab div's; $(function() { $( "#tabs" ).tabs(); }); Is there any other way by which only one image DIV tag is used across all the tab div's? or show only one image div tag across all the tab click events? Note: I dont want to use the CSS trick by making image DIV with absolute position A: How about this Just take the div outside the panels <div id="tabs"> <ul> <li><a href="#tabs-1">Nunc tincidunt</a> </li> <li><a href="#tabs-2">Proin dolor</a> </li> <li><a href="#tabs-3">Aenean lacinia</a> </li> </ul> <div align="center"> <img src="http://www.w3schools.com/tags/smiley.gif" alt="Smiley face" height="42" width="42"> </div> <div id="tabs-1"> <p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.</p> </div> <div id="tabs-2"> <p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.</p> </div> <div id="tabs-3"> <p>Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.</p> <p>Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.</p> </div> </div> here is an example: http://jsfiddle.net/RUTLr/1/
[ "ru.stackoverflow", "0000476643.txt" ]
Q: Как писать Property на Swift? @interface ViewController () @property (strong, nonatomic) LGFilterView *filterView1; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [_filterView1 initWithTitles:<#(NSArray *)#>];} Так я сделал на Obj-C необходим метод initWithTitles из LGFilterView class MainViewController: UIViewController, UITableViewDelegate,UITableViewDataSource { var filterView1:LGFilterView! Так я сделал на Swift, но он вообще не видит методы при вызове Вот сама библиотека: https://github.com/Friend-LGA/LGFilterView A: Когда вы в своем проекте создаете первый swift класс, xcode вас спросит, хотите ли вы создать bridging header. жмите 'да' и в созданном хедере импортируйте свой LGFilterView // // Use this file to import your target's public headers that you would like to expose to Swift. // #import "LGFilterView.h"
[ "salesforce.stackexchange", "0000010740.txt" ]
Q: Import articles via UI import feature using Zip file I am trying to prepare a zip file to import new articles into my org/sandbox but having trouble with mapping some key rich text area fields such as solution__c and Description__c. When I add them to the csv file that I am using in the zip file. I get the following error: "This value [Description] in the header for column 6 cannot be mapped (check both the header and its matching FLS). [MESSAGE 4/16/2013 8:34 PM] -- Import Failed --" I get the same error for both fields and some other standard fields such as publishstatus. I checked the field level security including all the required knowledge permissions and everything looks fine to me. Does anyone know what I am doing wrong? A: The column headers are case sensitive. So if your field is named Description_c, and the csv file column is named 'description_c', it won't work. Publishstatus is a field that cannot be imported. All the imported articles are set to draft by default. As far as I know, all the commas and quotes get escaped automatically if you're using MS Excel.
[ "stackoverflow", "0015484037.txt" ]
Q: Looping through and modifying a list in unix I am trying to take the contents of a list list1 and loop through them comparing them to another list generated by finger. When a name from list1 is found in finger it should be removed from list1. for i in $(cat list1); do if finger | grep $i echo "$i is online" sed '/$i/d' <list1 >templist mv templist list1 fi done list1 does not change. Once the script has run, the contents of list1 are the same. I think the problem has to do with the cat at the beginning but I'm not sure. Thanks, Ryan A: Try double quotes: sed "/$i/d" <list1 >templist (There isn't actually any $i in the list.)
[ "stackoverflow", "0023427646.txt" ]
Q: i have one Issue in My Query not get Group Record hi i have one issue in get query like 3 column ID Grp Name 1 10 aa 2 11 bb 3 11 cc 4 11 dd 5 12 ee 6 12 ff i want ans is ID Grp Name 1 10 aa 2 11 bb 5 12 ee so what can id Do ? A: In sql server Try this ! select * from ( select *,rn=row_number()over(partition by Grp order by ID) from table )x where x.rn=1
[ "stackoverflow", "0036097340.txt" ]
Q: GCD vs @synchronized vs NSLock Can someone give a rundown of the benefits and drawbacks of these 3 systems in how they relate to thread safety? From watching more recent WWDC videos, I get the feeling that Apple is pushing the usage of GCD to create performant reader-writer that are thread safe. What's the idea/backing behind this? Is it the time to access a lock having to enter the kernel that leads to this GCD push, and shying away from @synchronized and NSLock? Are @synchronized and NSLock being pushed out of what would be considered best practice, or is there still a place for them? A: There are many many details that could be discussed at great length in regards to this. But, at the core: These always require a lock to be taken somewhere or somehow: @synchronized(...) { ... } [lock lock]; Locks are very expensive for the reasons you mention; they necessarily consume kernel resources. (The @synchronized() case actually may avoid kernel locks these days, but it is a hash based exclusion mechanism and that, in itself, is expensive). And these do not always require a lock (but sometimes maybe do): dispatch_sync(...concurrent q...., ^{ ... }); dispatch_async(...queue of any kind...., ^{ ... }); There is a fast path through the dispatch functions that are effectively lockless (though they will use test-and-set atomic primitives that can cause performance issues under load). The end result is that a synchronous dispatch to a concurrent queue can effectively be treated as "execute this on this thread right now". A synchronous dispatch to a serial queue can do the atomic test-and-set to test if the queue is processing, mark it as busy, and, if it wasn't busy, execute the block on the calling thread immediately. Asynchronous dispatches can be similarly as fast, though asynchronous dispatch requires copying the block (which can be very cheap, but something to think about). In general, GCD can do anything a lock can do, can do it at least -- if not more -- efficiently, and you can use the GCD APIs to go way beyond just simple locking (using a semaphore as a computation throttle, for example). BTW: If your tasks are relatively coarse grained, have a look at NSOperationQueue and NSOperation.
[ "gaming.stackexchange", "0000041434.txt" ]
Q: Why do so many games for PS3 have 'restricted/locked' save-games? Many of the games I played had 'locked' save-games, so they can't be copied to an USB-Stick, for example. But I'm wondering why? Is it an agreement between Sony and the development studios to force the Playstation Plus features? What motivations have these developers to block the copying? Personally, for me it's very uncomfortable because I have to switch between two systems. A: Games which have copy protection often have player-unique features that prevent them from being usable by other users it could be online progress/stats (the case for Demon's Souls) and I believe sometimes it's because some saves include DLC data that might be problematic when transferred between users who don't own it (I believe that's the reason for Dragon Age's saves being copy protected). Personally I think a solution where a save is transferable but only usable by the original PSN ID is the best, however I think Sony's afraid users would modify those saves and copy them back, if you look at Borderlands, for example, where the saves aren't copy protected, item hacking and duping is abundant. I agree with you on the comfort issue, I myself lost a few copy protected saves lately because a backup went wrong and I only had backups of my non-protected saves I copied before.
[ "stackoverflow", "0005866493.txt" ]
Q: Retrieving and caching HTML from website using ASP.NET MVC 3 I want a partial view that display some stuff from a website that is not under my control. The data on the website is only available through HTML, and thus I can only retrieve it by querying the web site and parsing the HTML. (The website holds a list of 50 elements, and I only want the top 10.) Now, the data from the website is not changing very frequently, so I imagine that I can retrieve the HTML on an hourly basis, and displaying a cached version on my web site. How can I accomplish this in ASP.NET MVC 3? A: Ignoring the MVC3 requirement for now, you should look to using WebClient to grab the html from the website. You can do something like: var client = new WebClient(); var html = Encoding.UTF8.GetString(client.DownloadData("http://www.somedomain.com")); If you need to tailor your request, I'd recommend looking at HttpWebRequest, HttpWebResponse. Now that you can grab the html, you need to consider your caching mechanism, possibly in the ASP.NET runtime? public ActionResult GetHtml() { if (HttpRuntime.Cache["html"] == null) GetHtmlInternal(); return Content((string)HttpRuntime.Cache["html"], "text/html"); } private void GetHtmlInternal() { var html = // get html here. HttpRuntime.Cache.Insert("html", html, null, DateTime.Now.AddMinutes(60), Cache.NoSlidingExpiration); } A: The first solution that comes to mind is to create an action in a controller that makes an Http request to the remote web page and parses the html you want to return to your own page and then set output caching on your action. Edit: What controller to put the action in would depend on the structure of your web site and whether the partial view would be visible on all views or just a specific view. If the partial is visible in all views I'd either place it in the Home controller or create a "General" controller (if I anticipated more actions would go in such a controller). If you want to manipulate the result I would probably make a model and partial view for the list. If you want to take a part of the returned html and output it as it is I would use the same method as in the answer by Matthew Abbott: return Content(yourHtmlString); The end would look something like this: [OutputCache(Duration = 3600)] public ActionResult RemoteList() { var client = new WebClient(); var html = Encoding.UTF8.GetString(client.DownloadData("http://www.somedomain.com")); // Do your manipulation here... return Content(html); } (Some of the above code was borrowed from the post by Matthew Abbott.)
[ "stackoverflow", "0003703926.txt" ]
Q: Ruby Facets 2.9.0 work with Ruby 1.9.2? Does Ruby Facets 2.9.0 work with Ruby 1.9.2? Cause I can't get rekey method to work: http://rubyworks.github.com/facets/doc/api/core/Hash.html#method-i-rekey A: In general you can find out if a ruby library is 1.9 compatible by checking http://isitruby19.com/ It looks like other people have used Facets as early as version 2.5.0, and as recent as 2.8.1. http://isitruby19.com/facets
[ "scifi.stackexchange", "0000216056.txt" ]
Q: How does Tekka know Kylo Ren? At the beginning of The Force Awakens, when the Stormtroopers grab Lor San Tekka and bring him to Kylo Ren, Ren says "Look how old you've become". To me this suggests they were acquainted in the past- does anyone know more than that? A: Lor was apparently an ally of the New Republic and Leia's fledgling Resistance, working with them to provide intel and Luke with information about the pre-Imperial Era Jedi Order. A legendary traveler and explorer, Lor San Tekka is a longtime ally of the New Republic and the Resistance. After the Battle of Endor, San Tekka helped Luke Skywalker recover secret Jedi lore that the Empire had tried to erase, and Leia Organa hopes the old scout can now help find her brother. Following decades of adventure, San Tekka retired to live simply on Jakku, where he follows the dictates of the once-forbidden Church of the Force. But his retirement is fated to be anything but peaceful. Star Wars - Databank Article: Lor San Tekka and AS THE EMPIRE TOPPLED, retreating Imperial officials destroyed records that would have been vital to the New Republic's attempts at galactic reconstruction. New Republic bureaucrats turned instead to firsthand accounts from well-traveled locals to fill in the gaps. A seasoned traveler and explorer of the more remote fringes of the galaxy, Lor San Tekka has proven his worth to the New Republic and the Resistance many times over. Ready to retire after decades of exploration and adventure, the spiritual San Tekka has settled with a colony of villagers in the remote Kelvin Ravine on the frontier world of Jakku. Star Wars - The Force Awakens: The Visual Dictionary Given that he was working with both Luke and Leia at various points, it's hardly surprising that he would have met young Ben prior to him becoming a whiny emo tantrum baby powerful adept of the dark side of The Force.
[ "math.stackexchange", "0001452908.txt" ]
Q: Property of a spanning list in a finite-dimensional vector space Suppose $ V $ is a finite-dimensional vector space and the list $ (w_{1}, w_{2}, ..., w_{n}) $ spans $ V $. Let $ u_{1} \in V $, prove that the list $ (u_{1}, w_{1}, w_{2}, ..., w_{n}) $ is linearly dependent. This is one of the property in Axler's book "Linear Algebra Done Right" where he gives the claim but leaves no proof and I'm still stuck on it. Any help would be appreciated. A: If $w_1,\dots,w_n$ span $V$ and $u_1\in V$ then it follows we can write $u_1$ as a linear combination of $w_i$: $$u_1=\sum_{i=1}^n c_i w_i$$ for some coefficients $c_i$. It follows that $$u_1-\sum_{i=1}^n c_i w_i=0$$ What does this tell us about the linear dependence of $u_1,w_1,\dots,w_n$?
[ "stackoverflow", "0035279287.txt" ]
Q: WCF ServiceHost instantiation confusion with multiple endpoint contracts I am a bit confused on what exactly I am instantiating with the WCF ServiceHost when I have multiple endpoint contracts that I am adding to it. The instantiation has included a typeof argument - which seems to be the contract and is so in everything I have read and done. However when I come across adding additional contracts - this is where my confusion about it is. ServiceHost shost = new ServiceHost(typeof(MyService), NetTcpBinding, xyz); So let's say I have several contracts - ProductService, BatchService, CustomerService these are endpoint contracts that each have an interface. Let's keep it simple there is an Add Method and a Get Method in each of these contracts. I can then add these endpoints which are contracts to the ServiceHost .. shost.Endpoint.Add(ProductService); shost.Endpoint.Add(BatchService); shost.Endpoint.Add(CustomerService); This is my confusion if I create it with MyService, then does MyService need to incorporate the methods of all of my endpoint contracts or does this just pass in the first Endpoint Contract just to instantiate it and then all the additional ones are (forgive my lack of a better way of saying this) - additional services provided by the service that was instantiated with one of my endpoints ? I have read on SO and looking here seems relevant and close - but does not give an explanation of the instantiation of the ServiceHost Run WCF ServiceHost with multiple contracts I mean what is the point of instantiating the thing ; and then adding endpoints if you have to place all of the endpoint methods into the host contract anyway where btw you can specify namespaces for the contract as well..- that just seems so un oop .. is the answer found at the link really the viable answer (it smells WET ~ W'peat Every Thing - AKA not DRY]. A: The ServiceHost can host one service - that is one service class (implementation class). But that single class can implement multiple WCF service contracts. So if you have three service contracts (as interfaces IProductService, IBatchService, ICustomerService) and a single class MyServiceClass which implements all three of those interface contracts public class MyServiceClass : IBatchService, ICustomerService, IProductService then you can host this class in a ServiceHost and you can define endpoints for each of those three service contracts.
[ "stackoverflow", "0014489664.txt" ]
Q: Mock file input as file path on Rspec I have a question on how to use rspec to mock a file input. I have a following code for the class, but not exactly know a why to mock a file input. filepath is /path/to/the/file I did my search on Google and usually turns out to be loading the actual file instead of mocking, but I'm actually looking the opposite where only mock, but not using the actual file. module Service class Signing def initialize(filepath) @config = YAML.load_file(filepath) raise "Missing config file." if @config.nil? end def sign() … end private def which() … end end end Is it possible to use EOF delimiter for this file input mocking? file = <<EOF A_NAME: ABC A_ALIAS: my_alias EOF A: You could stub out YAML.load_file and return parsed YAML from your text, like this: yaml_text = <<-EOF A_NAME: ABC A_ALIAS: my_alias EOF yaml = YAML.load(yaml_text) filepath = "bogus_filename.yml" YAML.stub(:load_file).with(filepath).and_return(yaml) This doesn't quite stub out the file load itself, but to do that you'd have to make assumptions about what YAML.load_file does under the covers, and that's not a good idea. Since it's safe to assume that the YAML implementation is already tested, you can use the code above to replace the entire call with your parsed-from-text fixture. If you want to test that the correct filename is passed to load_file, replace the stub with an expectation: YAML.should_receive(:load_file).with(filepath).and_return(yaml)
[ "stackoverflow", "0008951606.txt" ]
Q: What support does the Play Framework have for the synchronization of client/server state? Play Framework looks very interesting but it encourages minimal state on the server side. My question is how can I synchronize client state with server state easily? What if I want to have server state such as in the development of a chat application, how easy or difficult is it to keep server state and synchronize client and server state? A: For standard web applications, state is held in either the cookie, in the database, or in a cache (remembering that cache is unreliable and must be accessible from the DB if the cache does not contain the data you want). Nothing is therefore held in state in server side sessions. However, there is a slight nuance here as far as what is defined as stateless for a Play application for a chat type application. If you look at the chat application in the early versions of the Play (before Websocket support), you would have found all 'Message' objects which are individual lines in a chat, stored in the database. However, in the most recent version, which includes WebSocket support, you will find that the state of the chat is stored in a Singleton object, which will last for the enter length of the chat. The argument from the Play devs is that a Websocket communication, therefore a full chat can be thought of as a single request, over many back and forth communications. Therefore, by keeping the state held in a singleton on the serverside does not break the rules of a stateless architecture. The reason why this is true, is because once a websocket communication is set up, the conversation along the socket will always be between the client and the single server, until the websocket is closed.
[ "stackoverflow", "0007813944.txt" ]
Q: Callback functions in javascript/google hangouts api So I was messing around with google's hangouts api and there is a function called addStateChangeListener( callback ) which allows you to register a callback function that will be called whenever the state of the application changes. An example callback function that could be registered is function onStateChanged(add, remove, state, metadata) { state_ = state; metadata_ = metadata; if (<some boolean>) { doFunction(); //this function alters the state } //more stuff below } My question is: If doFunction() did something that altered the state, (and triggered the addStateChangeListener) would onStateChange be called again before the rest of function after the if statement ran? Or would the first iteration of onStateChange() run to its completion first and then onStateChange would get called again. Or would it possibly just completely ignore the rest of the first onStateChange function, and just recall onStateChange when doFunction changes the state? Thanks for your help. A: Looking at the Google Hangouts API reference, it would appear that it would run the callback function again if you changed the state. Specifically: the callback will be called for changes in the shared state which result from submitDelta calls made from the local participant's app. It would definitely not ignore the rest of the first callback function, and it would probably (although it may not, for example, if it checks with the server via an Ajax call that the state has actually changed) also run the second immediately, without waiting for the first callback function to finish. If you wanted to ensure that the first function always completes before the second is called, you could always delay your call to change the state with window.setTimeout() around the call to doFunction(). Specifying a 1 millisecond delay will be enough.
[ "joomla.stackexchange", "0000026578.txt" ]
Q: Joomla 4 addfieldpath Has the addfieldpath parameter in custom extension forms changed in Joomla 4? The Joomla admin is no longer finding my component's customized field types. I'm using addfieldpath="/administrator/components/com_mycomponent/Field"> in the form xml definition, since all my fields have been moved to the new Field directory, and my field names have been changed to something like HeaderField and are referenced in the XML field like: <field name="header" type="header" default="COM_MYCOMPONENT_DEFAULT" description="COM_MYCOMPONENT_DESC" tag="info" /> I'm not sure if there's something that has to be done to let the xml form correctly map to the new namespaced fields. A: The new format appears to be addfieldprefix instead of addfieldpath, using the namespace for your Field directory: addfieldprefix="MyCompany\Component\MyComponent\Administrator\Field"
[ "stackoverflow", "0018427457.txt" ]
Q: Adding paths to RequireJS configuration on runtime Ok, I already know that you should configure paths with RequireJS like this require.config({ paths: { name: 'value' } }); And call it like this. require(['name'], function() { /* loaded */ }); But the thing is, I'm working in environment in which I don't have access to the existing call to require.config(...). For those who care, the environment is Azure Mobile Services scheduled job. Microsoft has already included RequireJS in the environment and configured the paths. My question is two-fold. 1. How do I add paths to the existing require.config()? I know calling require.config() again will destroy the existing configuration. Which is what I do not want to do. 2. How do I get to know which paths have already been configured? I really wouldn't like to overwrite any existing path name or overwrite any existing library by accident. A: Running require.config() again does not override your original config file. It actually extends it and adds your new paths to it. Right now I am using it this way, where configfile is also a require.config({}) <script data-main="configfile" src="require.js"></script> <script> require.config({ paths: { prefix-name: 'path/to/file' } }); </script> One way to avoid name collisions with Azure Mobile paths would be to simply prefix all your custom paths. Disclaimer: I have never used Azure Mobile, just RequireJs. You may have to implement it a little differently but it is possible.
[ "stackoverflow", "0012721735.txt" ]
Q: How to receive difference of maps in java? I have two maps: Map<String, Object> map1; Map<String, Object> map2; I need to receive difference between these maps. Does exist may be apache utils how to receive this difference? For now seems need take entry set of each map and found diff1 = set1 - set2 and diff2 = set2- set1. After create summary map =diff1 + diff2 It looks very awkwardly. Does exist another way? Thanks. A: How about google guava?: Maps.difference(map1,map2) A: Here is a simple snippet you can use instead of massive Guava library: public static <K, V> Map<K, V> mapDifference(Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) { Map<K, V> difference = new HashMap<>(); difference.putAll(left); difference.putAll(right); difference.entrySet().removeAll(right.entrySet()); return difference; } Check out the whole working example A: If I understood well you are trying to calculate symmetric difference beetween the two maps entry sets. Map<String, Object> map1; Map<String, Object> map2; Set<Entry<String, Object>> diff12 = new HashSet<Entry<String, Object>>(map1.entrySet()); Set<Entry<String, Object>> diff21 = new HashSet<Entry<String, Object>>(map2.entrySet()); Set<Entry<String, Object>> result; diff12.removeAll(map2.entrySet()); diff21.removeAll(map1.entrySet()); diff12.addAll(diff21); Considering the awkward behavior you mentioned, let's take a closer look at the above code behavior. For example if we take the numerical example from the above given link: Map<String, Object> map1 = new HashMap<String, Object>(); map1.put("a", 1); map1.put("b", 2); map1.put("c", 3); map1.put("d", 4); Map<String, Object> map2 = new HashMap<String, Object>(); map2.put("a", 1); map2.put("d", 4); map2.put("e", 5); After you calculate the difference as shown, the output: System.out.println(Arrays.deepToString(diff12.toArray())); gives: [e=5, c=3, b=2] which is the correct result. But, if we do it like this: public class CustomInteger { public int val; public CustomInteger(int val) { this.val = val; } @Override public String toString() { return String.valueOf(val); } } map1.put("a", new CustomInteger(1)); map1.put("b", new CustomInteger(2)); map1.put("c", new CustomInteger(3)); map1.put("d", new CustomInteger(4)); map2.put("a", new CustomInteger(1)); map2.put("d", new CustomInteger(4)); map2.put("e", new CustomInteger(5)); the same algorithm gives the following output: [e=5, a=1, d=4, d=4, b=2, a=1, c=3] which is not correct (and might be described as awkward :) ) In the first example the map is filled with int values wich are automatically boxed to Integer values. The class Integer has its own implementation of equals and hashCode methods. The class CustomInteger does not implement these methods so it inherits them from the omnipresent Object class. The API doc for the removeAll method from the Set interface says the following: Removes from this set all of its elements that are contained in the specified collection (optional operation). If the specified collection is also a set, this operation effectively modifies this set so that its value is the asymmetric set difference of the two sets. In order to determine which elements are contained in both collections, the removeAll method uses the equals method of the collection element. And that's the catch: Integer's equals method returns true if the two numeric values are the same, while Object's equals method will return true only if it is the same object, e.g. : Integer a = 1; //autoboxing Integer b = new Integer(1); Integer c = 2; a.equals(b); // true a.equals(c); // false CustomInteger d = new CustomInteger(1); CustomInteger e = new CustomInteger(1); CustomInteger f = new CustomInteger(2); d.equals(e); //false d.equals(f) // false d.val == e.val //true d.val == f.val //false If it's still a bit fuzzy I strongly suggest reading the following tutorials: Learning the Java language Collections
[ "gaming.meta.stackexchange", "0000012635.txt" ]
Q: A proposed change to the This is Fine news policy Yesterday, a bit of an argument formed in The Bridge after a moderator moved a set of posts mentioning a fidget spinner to This Is Fine, citing the "Horrific news belongs in This is Fine" rule. During this argument, A user voiced the complaint that they "haven't been thrilled with the way it feels like we're not even allowed to mention news in this room anymore." and that they miss the older days of casually discussing news events in the Bridge. The discussion can be found in the transcript at https://chat.stackexchange.com/transcript/message/40071267#40071267 What I suggested during that discussion, and officially propose in this meta post as a general rule (with exceptions possible), is that we amend the rules of news in The Bridge from "all news and discussion of news belongs in This is Fine" to "some minor discussion of news is fine in The Bridge, but once it gets deeper and more involved, it is moved to This Is Fine", similar to how extended discussion in comments is frequently moved to a chat room on the main site. Since we need to have an objective definition of "deeper discussion", I suggest we use the number of posts made in relation to the news item. I am not sure when the suggestion to move a discussion to chat is triggered on comments, but I think it's after 6 or so comments, or 7 including the question or answer that triggered the comments. This seems like a reasonable limit: 7 chat posts including the news item itself, after which chat is encouraged to continue the discussion in This is Fine (possibly through a moderator moving the chat messages as a gentle reminder to continue the discussion in This Is Fine.) TL;DR: allow limited discussion of news items in The Bridge, but move the discussion to This Is Fine after 7 posts about the news item. A: I don't like this proposal. I agree that what happened yesterday was an issue, but not for the reasons you outline. The messages that were moved were not news related. Why a store page for a fidget spinner would be moved to TIF is beyond me. From context, it appears to be for a joke, but in my opinion the enforcement of policy, especially in the formative time, is not the right time or place to make jokes like this. News discussions should begin and end in TIF. Non-news discussion should stay in the Bridge without being moved to TIF, for jokes or any other reasons. Moderators should be trusted with the power to subjectively understand context and guide discussion to the correct location without specific hard guidelines. In this case, I believe the moderator simply made a mistake.
[ "academia.stackexchange", "0000064933.txt" ]
Q: Is it feasible to become a paramedic full time and do a PhD in an unrelated field? Do you think this is reasonable? I am graduating with a BSc in neuroscience next year. I would like to be a paramedic for a little while (throughout my 20's) before switching careers and becoming a researcher in Neuroscience (for my 30's +). Scenario A: After completing my BSc I want to do the 2 years of training to become an EMT. A full time work schedule as an EMT would be something like 12 hour shifts, 3 days on, 3 days off, 4 nights on, 4 nights off, etc. Would it be possible to pursue a masters and a PhD in Neuroscience while working a schedule like that? I imagine that this way I would graduate towards the end of my 20's or early thirties with a PhD. Then I would like to begin a career as a researcher/lecturer. Does this sound impossibly difficult? Scenario B: After graduating, spend the next 2 years to become an EMT. Work as an EMT for a few years, then reduce to part-time or quit and pursue funding for a masters + PhD in my mid 20's. I hear that returning to university after a few years off might be more difficult, both to apply, and to be competitive. Is this true? Scenario C: Pursue my masters after I finish my BSc. Then do the 2 years to become an EMT, work as an EMT for a few years, then do a PhD. Will the relevance of the masters depreciate over time? If I already have a master's done, how long would it take to finish a PhD? I guess in general, is this just an insane plan? Or is it possible? A: A does sound impossibly difficult to me. The first few years of a masters/PhD sequence are usually based on coursework. You will need to attend classes regularly on weekdays, which seems like it would probably be incompatible with a paramedic's work schedule. Even beyond coursework, particularly in lab sciences, you may find that parts of your research have to be done on a particular schedule. Moreover, at all stages of graduate study, you should expect that your coursework and/or research will require a time commitment at least comparable to a full time job (40 hours per week), likely substantially more. Many graduate students struggle with the workload, even without added commitments. Adding a full time job, especially one with as much stress, long hours, and sleep disruption as a paramedic must have, seems to me like a burden well beyond what any human could be expected to successfully bear.
[ "askubuntu", "0000364270.txt" ]
Q: Mount error: "unknown filesystem type 'exfat'" When trying to mount an exfat filesystem, I get the following error: Error mounting /dev/sda6 at /media/gkp/Backup: Command-line `mount -t "exfat" -o "uhelper=udisks2,nodev,nosuid" "/dev/sda6" "/media/gkp/Backup"' exited with non-zero exit status 32: mount: unknown filesystem type 'exfat' Exfat is used on some USB sticks and camera sd cards. What can I do to mount this type of filesystem? A: You get this error because the exfat filesystem is not installed in Ubuntu by default. exFAT is proprietary and patented by Microsoft. Ubuntu 13.10 or higher Since Ubuntu 13.10, this package is in the main repository. Just install exfat-fuse and exfat-utils: sudo apt-get install exfat-fuse exfat-utils Ubuntu 12.04 For ubuntu 13.04 and lower, you'll need a ppa to install the exfat support. Installation procedure: sudo apt-add-repository ppa:relan/exfat sudo apt-get update sudo apt-get install fuse-exfat If you see the error gpg: "tag:launchpad.net:2008:redacted" not a key ID: skipping during the apt-add-repository step, then you'll need to manually install the signing key and run the apt-get update and apt-get install steps after that: sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 4DF9B28CA252A784 ​​​​​​
[ "stackoverflow", "0060126523.txt" ]
Q: Interface with keys declared by string array I have an interface. interface ICalculateFieldProps { fields: string[] set: string updateFunc: (valuesObj: object, oldValue: any) => any } I want valuesObj keys to be limited to fields: string[] items. So for example, if pass ['width', 'height'] to fields. Then valuesObj must be { height: any width: any } A: ...if pass ['width', 'height'] to fields... If you mean at runtime, you can't do this using TypeScript's type system. TypeScript does its work at compile time. You can, of course, do it at runtime with runtime checks in the implementation of updateFunc: // ...in a class implementing the interface... updateFunc(valuesObj: object, oldValue: any): any { if (Reflect.ownKeys(valuesObj).some(key => !this.fields.includes(key))) { throw new Error(`Invalid property ${key} found in valuesObj.`); } // ... } ...though it would probably be better if fields were a Set rather than an array.
[ "stackoverflow", "0015453410.txt" ]
Q: Independent column scroll in HTML page I have two columns in my HTML page. <div id="content"> <div id="left"></div> <div id="right"></div> </div> Each of them occupies half of the page #left { float: left; width: 50%; } #right { float: left; width: 50%; } Is it possible to make it so that they flow independently? I mean, I want to be able to scroll down the left column, but remain at the top of the right column, instead of having to scroll down both columns at the same time. A: See this fiddle #content, html, body { height: 98%; } #left { float: left; width: 50%; background: red; height: 100%; overflow: scroll; } #right { float: left; width: 50%; background: blue; height: 100%; overflow: scroll; } A: The earlier postings improved a little: 100% html and body size .... without scroll bar margins for the left and right boxes individual scrollbars only when needed ("auto") some other details: Try it! Fiddle: 2 independently scrolling divs html, body { height: 100%; overflow: hidden; margin: 0; } #content { height: 100%; } #left { float: left; width: 30%; background: red; height: 100%; overflow: auto; box-sizing: border-box; padding: 0.5em; } #right { float: left; width: 70%; background: blue; height: 100%; overflow: auto; box-sizing: border-box; padding: 0.5em; } A: Yes. You will have to restrict their height. See this fiddle for a working example. #content { height: 10em; } #left { float: left; width: 50%; background-color:#F0F; max-height:100%; overflow: scroll; } #right { float: left; width: 50%; background-color:#FF0; max-height:100%; overflow: scroll; }
[ "stackoverflow", "0025972040.txt" ]
Q: SimpleDateFormat android not formatting as expected I'm trying to use SimpleDateFormat for formatting a date represented by 3 ints. It looks like this: ... SimpleDateFormat sdfHour = new SimpleDateFormat("HH"); SimpleDateFormat sdfMinute = new SimpleDateFormat("mm"); SimpleDateFormat sdfSecond = new SimpleDateFormat("ss"); Calendar c = Calendar.getInstance(); c.setTimeZone(TimeZone.getDefault()); int hours = c.get(Calendar.HOUR_OF_DAY); int minutes = c.get(Calendar.MINUTE); int seconds = c.get(Calendar.SECOND); String string_hours = sdfHour.format(hours); String string_minutes = sdfMinute.format(minutes); String string_seconds = sdfSecond.format(seconds); and the output of Log.d("tag", "Time string is: " + string_hours + ":" + string_minutes + ":" + string_seconds); is always Time string is: 19:00:00 What am I doing wrong here? A: SimpleDateFormat.format expects a Date, not an int. The method you're using, which is the overloaded version that accepts a long, is actually expecting milliseconds from the epoch, not an hour a minute or a second as you're doing. The right way of using it should be : SimpleDateFormat sdfHour = new SimpleDateFormat("HH:mm:ss"); String timeString = sdfHour.format(new Date()); Using "new Date()" as in this example, will give you the current time. If you need to format some other time (like one hour ago, or something from a database etc..) pass to "format" the right Date instance. If you need the separated, for some reason, then you can still use it, but this other way : SimpleDateFormat sdfHour = new SimpleDateFormat("HH"); SimpleDateFormat sdfMinute = new SimpleDateFormat("mm"); SimpleDateFormat sdfSecond = new SimpleDateFormat("ss"); Date now = new Date(); String string_hours = sdfHour.format(now); String string_minutes = sdfMinute.format(now); String string_seconds = sdfSecond.format(now);
[ "stackoverflow", "0025909899.txt" ]
Q: Poor picture quality from Custom Camera Currently I'm using a custom camera application, the preview looks just fine. But when I take the picture and display it in my other activity the picture has decreased with like 80%. Anyone knows why this is happening? Also in gallery the quality is poor. I'm using the Camera API Demo from android. My parameters : public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { parameters = mCamera.getParameters(); parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height); parameters.setFlashMode(Parameters.FLASH_MODE_AUTO); parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); parameters.setJpegQuality(100); parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height); parameters.setRotation(90); Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); if (display.getRotation() == Surface.ROTATION_0) { mCamera.setDisplayOrientation(90); } else if (display.getRotation() == Surface.ROTATION_270) { mCamera.setDisplayOrientation(180); } mCamera.setParameters(parameters); mCamera.startPreview(); } Code saving image: private PictureCallback mPicture = new PictureCallback() { private String TAG = "DocsPro"; @Override public void onPictureTaken(byte[] data, Camera camera) { File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE); if (pictureFile == null) { Log.d(TAG, "Error creating media file, check storage permissions : PICTURE FILE IS NULL"); return; } try { FileOutputStream fos = new FileOutputStream(pictureFile); fos.write(data); fos.close(); String filepath = pictureFile.getAbsolutePath(); Intent edit = new Intent(TakePhoto.this, EditPhoto.class); edit.putExtra("filepath", filepath); startActivity(edit); finish(); } catch (FileNotFoundException e) { Log.d(TAG, "File not found: " + e.getMessage()); } catch (IOException e) { Log.d(TAG, "Error accessing file: " + e.getMessage()); } } }; private static File getOutputMediaFile(int type) { // To be safe, you should check that the SDCard is mounted // using Environment.getExternalStorageState() before doing this. File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), "DocsPro"); // This location works best if you want the created images to be shared // between applications and persist after your app has been uninstalled. // Create the storage directory if it does not exist if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d("MyCameraApp", "failed to create directory"); return null; } } // Create a media file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); File mediaFile; if (type == MEDIA_TYPE_IMAGE) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); } else { return null; } return mediaFile; } A: Problem Solved : I just put this in the surface changed on my preview class. List<Camera.Size> sizes = parameters.getSupportedPictureSizes(); Camera.Size size = sizes.get(0); for(int i=0;i<sizes.size();i++) { if(sizes.get(i).width > size.width) size = sizes.get(i); } parameters.setPictureSize(size.width, size.height); And then just resize the bitmap because the picture was to big : imageView = (ImageView) findViewById(R.id.Image); Bitmap bp = BitmapFactory.decodeFile(imagePath); Bitmap resized = Bitmap.createScaledBitmap(bp,(int)(bp.getWidth()*0.7), (int)(bp.getHeight()*0.7), true); imageView.setImageBitmap(resized);
[ "japanese.stackexchange", "0000047744.txt" ]
Q: Can もすこし遠かったら be used to mean "too far"? Can もすこし遠かったら be used in the following sentence to mean if it is too far I will not go. もすこし遠かったら行かないんですが。 A: もう少し means 'a little more', similar to もう一つ and the like meaning 'one more'. 「もう少し遠かったら行かないんですが」 means 'If it were a little farther I wouldn't go, though.'
[ "math.stackexchange", "0003555849.txt" ]
Q: Greatest value of $xz$ in expression Let $x,y,z,t\in\mathbb{R}$ and $x^2+y^2=9,z^2+t^2=4$ and $xt-yz=6$. Then greatest value of $xz$ is What i try I am trying to solve without trigonometric substution $$(xt-yz)^2+(xz+yt)^2=(x^2+y^2)(z^2+t^2)$$ $6^2+(xz+yt)^2=4\cdot 9\Longrightarrow (xz+yt)^2=0$ $$xz=-yt$$ How do i solve it Help me please A: Notice that: $$4(x^2+y^2) + 9(t^2 + z^2) = 12(xt - yz)$$ and this is equivalent with $$(2x - 3t)^2+ (2y + 3z)^2 = 0$$ Thus $z=-\frac{2}{3}y$, and we want to maximize $-\frac{2}{3}xy$. This is simple, given that $x^2+y^2=9$ because: $$0\leq (x+y)^2\Rightarrow -2xy \leq x^2+y^2=9$$ Therefore: $$zx=-\frac{2}{3}xy\leq 3$$ with equality when $(x,z)=\left(\pm \frac{3}{\sqrt{2}},\pm \sqrt{2}\right)$. A: A bit late answer but I think worth mentioning it. You can find the searched for maximum exploiting the relation you have already found: $xz=-yt$ You can do this, for example, by using basic facts about complex numbers writing $u = x+iy$ and $v = t+iz \Rightarrow |u|=3, |v|=2$ $\Rightarrow 6= xt-yz = \Re(uv) =|uv|=|u||v|=6$ $\Rightarrow \Im(uv)=xz+yt =0$ (The intermediate result you have already found.) Now, we can exploit this by considering $\Im(\bar u v) = xz-ty \stackrel{xz=-yt}{=}2xz \leq |\bar u v|=6$ $\Rightarrow \boxed{xz \leq 3}$ Addendum concerning the maximum: You are either fully aware that the maximum must be reached. Otherwise, it is easy to indicate specific $u,v$ and, hence, $x,z$ for which the maximum is reached: $u=3, v=2$ obviously satisfy the initially given condition. $\Rightarrow u_{\phi}=3e^{i\phi}, v_{\phi}=2e^{-i\phi}$ satisfy the initially given condition, as well. $\Rightarrow \Im(\bar u_{\phi}v_{\phi}) = 6\Im\left(e^{-2i\phi}\right)=6$ for $\phi = -\frac{\pi}{4}$ $\Rightarrow$ Maximum is reached for $$u= 3e^{-i\frac{\pi}{4}} = \underbrace{\frac{3\sqrt{2}}{2}}_{=x}-i\frac{3\sqrt{2}}{2}, v=2e^{i\frac{\pi}{4}} = \sqrt{2}+i\underbrace{\sqrt{2}}_{=z}$$
[ "stackoverflow", "0040507552.txt" ]
Q: PowerShell order sensitive Compare-Objects diff Is it possible to do the order comparison of items in arrays with Compare-Object aka diff in PowerShell? if not, suggest a workaround. $a1=@(1,2,3,4,5) $b1=@(1,2,3,5,4) if (Compare-Object $a1 $b1) { Write-Host 'Wrong order ' } else { Write-Host 'OK' } A: Use -SyncWindow 0: $a1=@(1,2,3,4,5) $b1=@(1,2,3,5,4) if (Compare-Object $a1 $b1 -SyncWindow 0) { Write-Host 'Wrong order ' } else { Write-Host 'OK' } More info: Comparing Arrays in Windows PowerShell.
[ "stackoverflow", "0018324053.txt" ]
Q: R return the index of the minimum column for each row I have a data.frame that contains 4 columns (given below). I want to find the index of the minimum column (NOT THE VALUE) for each row. Any idea hiw to achieve that? > d V1 V2 V3 V4 1 0.388116155 0.98999967 0.41548536 0.76093748 2 0.495971331 0.47173142 0.51582728 0.06789924 3 0.436495321 0.48699268 0.21187838 0.54139290 4 0.313514389 0.50265539 0.08054103 0.46019601 5 0.277275961 0.39055360 0.29594162 0.70622532 6 0.264804739 0.86996266 0.85708635 0.61136741 7 0.627344463 0.54277873 0.96769568 0.80399490 8 0.814420492 0.35362949 0.39023446 0.39246250 9 0.517459983 0.65895805 0.93662382 0.06762166 10 0.498319937 0.67081260 0.43225997 0.42139151 11 0.046862110 0.97304915 0.06542971 0.09779383 12 0.619009734 0.82363618 0.14514799 0.52858058 13 0.007262782 0.82203403 0.08573499 0.61094206 14 0.001602586 0.33241230 0.57762669 0.45285004 15 0.698388370 0.83541257 0.21051568 0.84431347 16 0.296088411 0.34363164 0.02179999 0.70551493 17 0.897869571 0.50625928 0.92861583 0.61249019 18 0.372497428 0.29025182 0.23201891 0.55737699 19 0.172931860 0.03604668 0.50291560 0.10850847 20 0.988827604 0.15800337 0.87999839 0.09899663 So I want the following output: 1 1 2 4 3 3 4 3 which continues for all the rows. Thanks A: Your English description suggests you want: apply( df, 1, which.min) But the answer you give is not formatted as a vector and is not the correct answer if the above interpretation is correct. Oh wait, you were expecting rownumbers. as.matrix(apply( d, 1, which.min)) [,1] 1 1 2 4 3 3 4 3 5 1 6 1 7 2 8 2 9 4 10 4 11 1 12 3 13 1 14 1 15 3 16 3 17 2 18 3 19 2 20 4 A: Another option is max.col of d multiplied by -1 max.col(-d) # [1] 1 4 3 3 1 1 2 2 4 4 1 3 1 1 3 3 2 3 2 4 If you need a matrix as output, use cbind(1:nrow(d), # row max.col(-d)) # column position of minimum Here is a benchmark of the two approaches set.seed(42) dd <- as.data.frame(matrix(runif(1e5 * 100), nrow = 1e5, ncol = 100)) library(microbenchmark) library(ggplot2) b <- microbenchmark( apply = apply(dd, 1, which.min), max_col = max.col(-dd), times = 25 ) autoplot(b) b #Unit: milliseconds # expr min lq mean median uq max neval cld # apply 705.7478 855.7112 906.2340 892.3214 933.4655 1211.5016 25 b # max_col 162.8273 175.6363 227.1156 206.0213 225.2973 406.9124 25 a
[ "stackoverflow", "0043346745.txt" ]
Q: JPA using one join table for two OneToMany entity There's an Entity Class 'A' (supposed to be a Person),There's another Entity Class 'B' (supposed to be a Contract). Entity 'A' has a relation @OneToMany to Class 'B' ( a person can sign alot of contracts). Entity 'B' also has a relation @OneToMany to Class 'A' (a contract can have many person signing it). In this case, there's gonna be 2 JoinTable in database, but actually they both are somehow the same. Is there anyway that i make them just using One JoinTable? tnx for any help! A: Looks like a @ManyToMany relation to me... in class Person @ManyToMany @JoinTable(name="PERS_CONTRACTS") public Set<Contract> getContracts() { return contracts; } in class Contract @ManyToMany(mappedBy="contracts") public Set<Person> getSigners() { return signers; }
[ "parenting.stackexchange", "0000014533.txt" ]
Q: My 6-year-old has angry outbursts, possibly related to a newborn sibling. How can we help her? Our six-year-old daughter is the eldest of 3 girls: her sisters are 3 years, and 3 months respectively. At varying points during the day she will flare up with rage; the triggers can be play-related (sharing, something not going as expected); conversation-related (us not understanding her, or making decisions she doesn't like); or sibling-related (annoyed by her middle sister). They're strong outbursts: screaming, throwing herself around and lashing out verbally. Between the outbursts she's loving, humorous and good-natured. She's always affectionate towards her baby sister, but this anger does seem to have surfaced since around the time the baby was born, suggesting a possible link. Stuff we've tried: Conversations about it when she's not angry (reasons why, and tactics for helping, namely taking herself away, breathing deeply): she doesn't engage, or if it does register it doesn't seem to help her Time outs: used consistently ("you need to calm down before we can carry on") Consequences: used very rarely (denied a story, or play opportunity) Holding her and talking calmly: tried occasionally - she hates this, and can't wait to get away (she's normally tactile) Time spent with her alone: not often (1-2 times/week? siblings' needs make this hard). Those times generally pass without incident and happily. We'd like to be consistent, but with greater confidence that we've chosen the best tactic. I'm certainly starting to doubt the wisdom of the time outs, but don't have any ideas about alternatives. A: You say you've tried time outs. I wonder if you've employed a systematic approach to this. 1-2-3 Magic is one of (if not the) most effective approaches to behavioral (self-) correction I've ever encountered. When applied correctly and consistently, it allows time outs to be applied without the parent losing their cool (very important, especially if younger siblings are observing) while it gives your daughter an opportunity to correct herself if she is able to before the time out, gaining some experience in self control and earning high praise for doing so. It was given to me (free back then) by our pediatrician, and I recommended it to all new parents. While I agree with spending more time with your daughter to some degree, I think the behavior must improve first lest she make the connection that if she throws enough tantrums, she gets rewarded with more one-on-one time. Rather, I would use a star/sticker chart and keep significant chunks of one-on-one time (a trip to the frozen yoghurt shop, a movie, etc) as rewards for self-control. You can use other rewards as well - some of the things she values highly (others should be allowed regardless). But the star/sticker chart will give her something to reflect on when she both controls herself (and gains a star) and when she questions why she has not gotten something she wants. It sounds like she might have been acting out at school as well? You don't state this explicitly. In any case, it does sound like a reaction to a new sibling. My oldest started biting when his brother was born, never before. It's common for kids to regress to some inappropriate behavior when a sibling arrives.
[ "math.stackexchange", "0000077694.txt" ]
Q: Quadratic equation / why does $x(x-2)=0$ imply $x = 0 \lor x = 2$? I feel silly asking such elementary questions, but hopefully this is appropriate for math.stackexchange. I'm studying to take calculus next semester but I haven't done any math in a long time, so I've been trying to brush up on my algebra and my trig. I'm stuck on this problem here: $$ (4 x-2)^2-2 (4 x-2) = 15 $$ I was able to get to this step: $$ 8-24 x+16 x^2 = 15 $$ But after I'm confused on what to do after this step. Also(a related question): I got some help with this equation earlier: $$(u+1)/(u+4)+1 = (u-5)/(u-4)$$ The last step ended up being $$x (x -2) = 0$$ The explanation I recieved was that "this implied that $x = 0$ or $x = 2$" I was wondering if someone can help me understand why this is so, I feel as if I'm missing a vital piece of information preventing me from understanding these problems. I'd be much obliged if someone can point me in the right direction. Here are the wolfram links for both equations: http://www.wolframalpha.com/input/?i=%284x-2%29%5E2-2%284x-2%29%3D15 http://www.wolframalpha.com/input/?i=%28u%2B1%29%2F%28u%2B4%29%2B1+%3D+%28u-5%29%2F%28u-4%29 A: It's one of the basic features of numbers that if you multiply two numbers and the result is $0$, then at least one of the factors must have been $0$. Namely if $ab=0$ and $a$ is not $0$, then we're allowed to divide both sides of the equation by $a$ and get $b=\frac0a=0$. So either $a$ is $0$ or $b$ is. Therefore $x(x-2)=0$ implies that $x=0$ or $x-2=0$ and the latter is just a different way to write $x=2$.
[ "stackoverflow", "0027029067.txt" ]
Q: Make Angular Bootstrap Typeahead go up The typeahead suggestion box goes down - its a drop down list. How can I make it go up so that the base of the suggestions box is at the top of the text field? Like this for example... A: I managed this by removing the following from the template: top: position.top+'px', This from my CSS: top: 100%; And adding the following to the CSS: bottom: 38px; Where 38px is the height of the text box. Unfortunately the top declarations had to be removed because there's no way as far as I know to unset top without using script and it takes precedence over bottom. I own the CSS and I can put the template in a separate file that overrides the default so I won't lose my changes.
[ "wordpress.stackexchange", "0000160169.txt" ]
Q: Wordpress address URL and bloginfo I have updated my Wordpress Address (URL) and Site Address (URL) to be https:// in the General Settings of Wordpress as I have added a secruity certificate to the hosting. Should the css url automatically update to reflect the new address if I'm using <link rel="stylesheet" type="text/css" href="<?php bloginfo('stylesheet_url'); ?>" /> in the header code. The url is now https:// but the css url is still pointint to http:// A: You will need to use site_url($path_to_style_sheet, 'https') instead of bloginfo(). The home_url() method also supports https.
[ "rpg.stackexchange", "0000172176.txt" ]
Q: Can you designate a creature you haven't met for Illusory Script? A military general wishes to deliver important instructions to an allied leader who is a long distance away. To safeguard the message from being read by enemy spies during delivery, the general employs the services of a wizard. The wizard is able to cast illusory script, which provides a desirable level of security. However, the wizard has never met or seen the intended recipient, although the general has. The general can give the wizard the recipient's name and description. The description of the illusory script spell says: To you and any creature you designate when you cast the spell, the writing appears normal. Can the wizard designate a specific creature they have not met as being able to read their illusory script? How much does the wizard need to know about a creature to be able to designate them? For context, I am the GM. I am doing a plausibility check on this plan. In the event of ambiguity, I can make an appropriate ruling. A: It seems like this would work The spell description poses no limits or conditions on who can be designated or how they must be designated. Therefore, any unambiguous designation (which name and description should be) would suffice.
[ "stackoverflow", "0036805920.txt" ]
Q: Reshaping when year and countries are both columns I am trying to reshape some data. The issue is that usually data is either long or wide but this seems to be set up in a way that I cannot figure out how to reshape. The data looks as follows: year australia canada denmark ... 1999 10 15 20 2000 12 16 25 2001 14 18 40 And I would like to get it into a panel format like the following year country gdppc 1999 australia 10 2000 australia 12 2001 australia 14 1999 canada 16 2000 canada 18 A: The problem is just in the variable names. See e.g. this FAQ for the advice that you may need rename first before you can reshape. For more complicated variants of this problem with similar data, see e.g. this paper. clear input year australia canada denmark 1999 10 15 20 2000 12 16 25 2001 14 18 40 end rename (australia-denmark) gdppc= reshape long gdppc , i(year) string j(country) sort country year list, sepby(country) +--------------------------+ | year country gdppc | |--------------------------| 1. | 1999 australia 10 | 2. | 2000 australia 12 | 3. | 2001 australia 14 | |--------------------------| 4. | 1999 canada 15 | 5. | 2000 canada 16 | 6. | 2001 canada 18 | |--------------------------| 7. | 1999 denmark 20 | 8. | 2000 denmark 25 | 9. | 2001 denmark 40 | +--------------------------+
[ "judaism.stackexchange", "0000048772.txt" ]
Q: What to do if you made hamotze on something requiring mezonot? If you accidentally made a hamotze on a food item only requiring mezonot, do you say al hamichya or birkat hamazon for the beracha acharona? A: I asked my rav (who is from Ner Yisrael in Baltimore) and he said that that the bracha on a item is conected to the food that is eaten only. The bracha acharonah is not (in that sense) connected to the bracha rishona. Thus if one makes the wrong bracha rishona, one should still make the correct bracha acharona. He said that since the bracha rishona and the bracha acharona are separate bodies of halacha, the poskim do not discuss your case. He also pointed out that the example given ("mezonos" bagels) is incorrect and you should have used cake. For example see What is mazonot? That is, your question is about making the wrong bracha rishona and you are giving a case in which the correct bracha rishona is indeed hamotzi, which would require birchas hamazon (according to many poskim). That example makes the premise of your question wrong. It would have been better to have given an example which is definitely (according to all poskim) mezonos. He also pointed out that you could have used the example of water or fruit to show why the correct brachah acharona must be made even if the wrong bracha rishona was made and why it is not given as an explicit halacha. There are discussions as to what must be done if the wrong bracha rishona is made (and how to fix it). However, especially with pas haba be'kisnin (mezonos), the matter is too complicated to put into a post like here and I would probably make mistakes in trying to write about it.
[ "stackoverflow", "0008946704.txt" ]
Q: getTop()/getLeft for Views in XML file in RelativeLayout doesn't work My Layout: <RelativeLayout...> <Button android:id="@+id/button_1" ... /> <Button android:id="@+id/button_2" android:layout_toRightOf="@+id/button_1" ... /> ... </RelativeLayout> I want to save the x and y positions of all buttons. I tried this: Button b[] = new Button[40]; int parX [] = new int[40]; int parY [] = new int[40]; String temp; int resID; for (int i=0;i<=39;i++) { temp = "id/button_" + String.valueOf(i+1); resID = getResources().getIdentifier("com.myapp.test:"+temp, null, null); b[i] = (Button) findViewById(resID); parX[i] = b[i].getTop(); parY[i] = b[i].getLeft(); } But b[i].getTop() and b[i].getLeft() are always 0. But it can't be because it is correctly drawn a field of 40 buttons so they must have all different x and y positions. How can I find out the x/y positions of the buttons of my xml file? A: getLeft/getTop will return the correct value only after the first layout pass.
[ "stackoverflow", "0019027595.txt" ]
Q: JSF2: How are the *.taglib.xml files discovered in jsf-impl.jar? In jsf-impl.jar (which can be found on mvnrepository.com), the *.taglib.xml files are located in directory com/sun/faces/metadata/taglib/. I don't understand how they're discovered in this case, because chapter 10.3.2 of the JSF 2 specification says: 10.3.2 Facelet Tag Library mechanism ... The run time must support two modes of discovery for Facelet tag library descriptors Via declaration in the web.xml, as specified in Section 11.1.3 “Application Configuration Parameters” Via auto discovery by placing the tag library descriptor file within a jar on the web application classpath, naming the file so that it ends with “.taglib.xml”, without the quotes, and placing the file in the META-INF directory in the jar file. ... Here, they're not located in directory META-INF, so how does it work? Note: in META-INF, they are some .tld files, but I'm not interested in them since I'm not using JSP as the view, but Facelets. A: It isn't using the taglib.xml for that. It's programmatically registering them via com.sun.faces.facelets.tag.jsf.html.HtmlLibrary in com.sun.faces.application.ApplicationAssociate which is executed during startup. Here are the relevant lines from Mojarra 2.2.1 (copypasted from Grepcode): 954 c.addTagLibrary(new CoreLibrary()); 955 c.addTagLibrary(new CoreLibrary(CoreLibrary.XMLNSNamespace)); 956 c.addTagLibrary(new HtmlLibrary()); 957 c.addTagLibrary(new HtmlLibrary(HtmlLibrary.XMLNSNamespace)); 958 c.addTagLibrary(new UILibrary()); 959 c.addTagLibrary(new UILibrary(UILibrary.XMLNSNamespace)); 960 c.addTagLibrary(new JstlCoreLibrary()); 961 c.addTagLibrary(new JstlCoreLibrary(JstlCoreLibrary.IncorrectNamespace)); 962 c.addTagLibrary(new JstlCoreLibrary(JstlCoreLibrary.XMLNSNamespace)); 963 c.addTagLibrary(new PassThroughAttributeLibrary()); 964 c.addTagLibrary(new PassThroughElementLibrary()); 965 c.addTagLibrary(new FunctionLibrary(JstlFunction.class, FunctionLibrary.Namespace)); 966 c.addTagLibrary(new FunctionLibrary(JstlFunction.class, FunctionLibrary.XMLNSNamespace)); 967 if (isDevModeEnabled()) { 968 c.addTagLibrary(new FunctionLibrary(DevTools.class, DevTools.Namespace)); 969 c.addTagLibrary(new FunctionLibrary(DevTools.class, DevTools.NewNamespace)); 970 } 971 c.addTagLibrary(new CompositeLibrary()); 972 c.addTagLibrary(new CompositeLibrary(CompositeLibrary.XMLNSNamespace));
[ "movies.stackexchange", "0000073238.txt" ]
Q: How was the photography Samurai Fiction/Kill Bill shadow scene made? Kill Bill: Fiction Samurai: Help please! A: It looks to me like they have a rice-paper wall and either have a strongly colored light behind it, or a strong white light and the wall itself is colored. (My guess is that the light is colored, but I don't know for sure.) They then don't light the foreground subjects at all, leaving them as only silhouettes.
[ "stackoverflow", "0014738850.txt" ]
Q: installing sphinx on mac OS X version 10.8.2 and configuring can anyone pls tell me how to install sphinx on mac OS X version 10.8.2 Now, How can I check whether its properly installed or mot?? where can i find the files i installed getting error while trying to run ./configure command got this error unknown-5c:96:9d:7d:44:c7:sphinx-2.0.1-beta username$ ./configure checking build environment -------------------------- checking for a BSD-compatible install... /usr/bin/install -c checking whether build environment is sane... yes checking for a thread-safe mkdir -p... config/install-sh -c -d checking for gawk... no checking for mawk... no checking for nawk... no checking for awk... awk checking whether make sets $(MAKE)... no checking whether to enable maintainer-specific portions of Makefiles... no checking for compiler programs ------------------------------ checking whether to compile debug version... no checking for gcc... no checking for cc... no checking for cl.exe... no configure: error: in `/Users/username/Downloads/sphinx-2.0.1-beta': configure: error: no acceptable C compiler found in $PATH See `config.log' for more details. how can resolve this? Many Thanks A: Surely configure: error: no acceptable C compiler found in $PATH Is pretty clear...? https://www.google.com/search?q=install+c+compiler+mac+os
[ "gis.stackexchange", "0000104611.txt" ]
Q: ArcGIS arcpy code fails in Toolbox mode This code executes correctly in Python window but fails with ERROR 000732: Input Table: Dataset JHJ does not exist or is not supported # Import ArcPy and other required modules import arcpy from arcpy import env import fileinput import string import os env.overwriteOutput = True filud=file(r"c:\temp\dum.txt","w") # Open file for debug output filud.write("Hello \n") try: # Will create shape file fcname.shp arcpy.CreateFeatureclass_management(r"C:\temp\TestArcGis\FraFil","JHJ","Polyline") filud.write(str(time.time()) + " After create \n") except Exception as e: filud.write(str(time.time()) + "Error: " + e.message + "\n") try: # Add fields for data filud.write(str(time.time()) + " Before Addfield " + "JHJ" + "\n") arcpy.AddField_management("JHJ","Sbet","TEXT") except Exception as e: print e.message filud.write("Error: " + e.message) filud.close() A: It works in the python window because JHJ is likely a layer in the map and therefore can be reference in your script as "JHJ". When run outside of Arcmap, you need to tell arcpy where to look. Here are just a few ways you can do this (untested, but it should give you a few ideas): 1) jhj = arcpy.CreateFeatureclass_management(r"C:\temp\TestArcGis\FraFil","JHJ","Polyline") ...... arcpy.AddField_management(jhj,"Sbet","TEXT") 2) env.workspace=r"C:\temp\TestArcGis\FraFil" arcpy.CreateFeatureclass_management(r"C:\temp\TestArcGis\FraFil","JHJ","Polyline") ...... arcpy.AddField_management("JHJ","Sbet","TEXT") 3) jhj = r"C:\temp\TestArcGis\FraFil\JHJ" arcpy.CreateFeatureclass_management(*os.path.split(jhj),"Polyline") ...... arcpy.AddField_management(jhj,"Sbet","TEXT")
[ "stackoverflow", "0045089296.txt" ]
Q: How to have ingrained navigation bar look? I am trying to have a navigation bar that doesn't have any extra space on the sides and on the top and bottom. However nothing seems to be. Is there a way I can fix this. An example of how I would like my navigation bar to look is dootrix.com Here is an image to illustrate what the problem is: image ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: mediumblue; text-align: center; object-position: fixed; width: 100%; top: 0; } li { display: inline-block; } li a { display: block; color: white; padding: 14px 50px; text-decoration: none; } li a:hover:not(.active) { background-color: darkblue; font-style: italic; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title></title> </head> <body> <!-- Navigation Bar --> <ul> <li> <a href="test_webpage.html#about">ABOUT</a> </li> <li> <a href="test_webpage.html#products">PRODUCTS</a> </li> <li> <a href="test_webpage.html#coupons">COUPONS</a> </li> <li> <a href="test_webpage.html#feedback">FEEDBACK</a> </li> </ul> <div id='about'> <a id="about" name='about'></a> <img src="https://image.ibb.co/ft1bSv/cover.jpg" alt="cover"> <div id='about.container'> <h2>About:</h2> <p>We are a small family owned convenience store! We have operating since the early 2000s.</p> </div> </div> <div id='products'> <a id="products" name='products'></a> </div> <div id='coupons'> <a id="coupons" name='coupons'></a> </div> <div id='feedback'> <a id="feedback" name='feedback'> </a></div> </body> </html> A: You have to disable the margin (https://www.w3schools.com/css/css_margin.asp) of your body tag. You can do this in your css. Look at what I did at the top of this css file. That should work. body { margin: 0; } ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: mediumblue; text-align: center; object-position: fixed; width: 100%; top: 0; } li { display: inline-block; } li a { display: block; color: white; padding: 14px 50px; text-decoration: none; } li a:hover:not(.active) { background-color: darkblue; font-style: italic; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title></title> </head> <body> <!-- Navigation Bar --> <ul> <li> <a href="test_webpage.html#about">ABOUT</a> </li> <li> <a href="test_webpage.html#products">PRODUCTS</a> </li> <li> <a href="test_webpage.html#coupons">COUPONS</a> </li> <li> <a href="test_webpage.html#feedback">FEEDBACK</a> </li> </ul> <div id='about'> <a id="about" name='about'></a> <img src="https://image.ibb.co/ft1bSv/cover.jpg" alt="cover"> <div id='about.container'> <h2>About:</h2> <p>We are a small family owned convenience store! We have operating since the early 2000s.</p> </div> </div> <div id='products'> <a id="products" name='products'></a> </div> <div id='coupons'> <a id="coupons" name='coupons'></a> </div> <div id='feedback'> <a id="feedback" name='feedback'> </a></div> </body> </html>
[ "stackoverflow", "0055628768.txt" ]
Q: Custom GIS Routes I have a list of GIS point that creates a route network. My goal is to let agents move from a point to another using ONLY the network I provided. I don't want to use all the possible routes from a point A to a point B, just the ones that I can follow based on my own network. I know that it should be possible by implementing a custom RouteProvider, but I was not able to figure out how to do it. Thank you very much for your help! A: I assume you have a collection "locations" of type ArrayList containing all your GISPoints, here is what you do: //create a new GIS network and attach it to your map element GISNetwork network = new GISNetwork(map,"myNetwork"); //add all GISPoints to this network for(GISPoint p:locations){ network.add(p); } //somehow iterate through your points to create Routes between them (here just connect one after another, no cross connections) for(int i=0;i<locations.size()-1;i++){ //create segment (neccessary for Curve) GISMarkupSegment segment = new GISMarkupSegmentLine(locations.get(i).getLatitude(), locations.get(i).getLongitude(), locations.get(i+1).getLatitude(), locations.get(i+1).getLongitude()); //create curves (neccessary for the GISRoutes) Curve<GISMarkupSegment> curve = new Curve<>(); curve.addSegment(segment); curve.initialize(); network.add(new GISRoute(map,curve,locations.get(i), locations.get(i+1), true)); } network.initialize();
[ "stackoverflow", "0022227871.txt" ]
Q: OpenGL SuperSampling Anti-Aliasing? At office we're working with an old GLX/Motif software that uses OpenGL's AccumulationBuffer to implement anti-aliasing for saving images. Our problem is that Apple removed the AccumulationBuffer from all of its drivers (starting from OS X 10.7.5), and some Linux drivers like Intel HDxxxx don't support it neither. Then I would like to update the anti-aliasing code of the software for making it compatible with most actual OSs and GPUs, but keeping the generated images as beautiful as they were before (because we need them for scientific publications). SuperSampling seems to be the oldest and the best quality anti-aliasing method, but I can't find any example of SSAA that doesn't use AccumulationBuffer. Is there a different way to implement SuperSampling with OpenGL/GLX ??? A: You can use FBOs to implement the same kind of anti-aliasing that you most likely used with accumulation buffers. The process is almost the same, except that you use a texture/renderbuffer as your "accumulation buffer". You can either use two FBOs for the process, or change the attached render target of a single render FBO. In pseudo-code, using two FBOs, the flow looks roughly like this: create renderbuffer rbA create fboA (will be used for accumulation) bind fboA attach rbA to fboA clear create texture texB create fboB (will be used for rendering) attach texB to fboB (create and attach a renderbuffer for the depth buffer) loop over jitter offsets bind fboB clear render scene, with jitter offset applied bind fboA bind texB for texturing set blend function GL_CONSTANT_ALPHA, GL_ONE set blend color 0.0, 0.0, 0.0, 1.0 / #passes enable blending render screen size quad with simple texture sampling shader disable blending end loop bind fboA as read_framebuffer bind default framebuffer as draw framebuffer blit framebuffer Full super-sampling is also possible. As Andon in the comment above suggested, you create an FBO with a render target that is a multiple of your window size in each dimension, and in the end do a down-scaling blit to your window. The whole thing tends to be slow and use a lot of memory, even with just a factor of 2.
[ "stackoverflow", "0023106557.txt" ]
Q: printing last line in a method with puts Given def sayMoo numberOfMoos puts 'mooooooo...'*numberOfMoos 'yellow submarine' end I am having trouble understanding why x = sayMoo 2 puts x gives me mooooooo...mooooooo... yellow submarine and sayMoo 2 gives me mooooooo...mooooooo... I am hoping someone could explain it. A: Calling the functionputs moooooos. The first example puts the function's return value, which is yellow submarine, in addition to that. The second, in contrast, just calls the function.
[ "tex.stackexchange", "0000477986.txt" ]
Q: Biblatex: how can I get full first names in bibliography? I'd like BibLaTeX to not display any first names or initials when citing in text. But I would like to have full first names in the Bibliography. From what I read, this can be achieved by giveninits=false. But this command does not affect the citation style at all. I set up BibLaTeX like this: \documentclass[a4paper]{article} \usepackage[utf8]{inputenc} \usepackage[ backend=biber, style=apa, maxcitenames = 2, mincitenames = 1, uniquename = false, uniquelist = false, maxbibnames = 99, apamaxprtauth=99, giveninits=false ]{biblatex} \DeclareLanguageMapping{english}{english-apa} \usepackage{filecontents} \begin{filecontents*}{test.bib} @article{marquard1975, author = {Donald W. Marquardt and Ronald D. Snee}, title = {Ridge Regression in Practice}, journal = {American Statistician}, volume = {29}, number = {1}, pages = {3-20}, year = {1975}, publisher = {Taylor & Francis}, } } \end{filecontents*} \addbibresource{test.bib} \begin{document} \title{asdf} \author{myself} \date{\today} \maketitle TEST \cite{marquard1975} \printbibliography \end{document} What I get is (in text citation is fine, bibliography not) TEST Marquardt and Snee, 1975 References Marquardt, D. W., & Snee, R. D. (1975). Ridge regression in practice. American Statistician, 29(1), 3–20. What I would like to get: TEST Marquardt and Snee, 1975 References Marquardt, Donald W., & Snee, Ronald D. (1975). Ridge regression in practice. American Statistician, 29(1), 3–20. A: As mentioned in the comments the APA style requires that first names be abbreviated to initials and that the full name only be added in (square brackets) in case initials would be ambiguous. biblatex-apa implements this requirement as far as possible. Since this is quite tricky, the normal option giveninits does not work as expected with biblatex-apa. This is similar to how the (max|min)(bib|cite)?names options don't quite work as expected. You have to redefine two name bibmacros to get full names, one for names in given-family order and one for family-given. The original definitions can be found in apa.bbx, we only removed the \ifthenelse{\value{uniquename}>1} test and make sure to print the full given name with \mkbibnamegiven{#2} instead of \mkbibnamegiven{#3}. \documentclass[a4paper]{article} \usepackage[utf8]{inputenc} \usepackage[ backend=biber, style=apa, uniquename = false, uniquelist = false, apamaxprtauth=99, giveninits=false, ]{biblatex} % argument meanings from apa.bbx % #1 = family name % #2 = given name % #3 = given name (initials) % #4 = name prefix % #5 = name suffix \renewbibmacro*{name:apa:family-given}[5]{% \ifuseprefix {\usebibmacro{name:delim:apa:family-given}{#4#1}% \usebibmacro{name:hook}{#4#1}% \ifdefvoid{#4}{}{% \mkbibnameprefix{#4}\isdot% \ifprefchar{}{\bibnamedelimc}}% \mkbibnamefamily{#1}\isdot% \ifdefvoid{#2}{}{\revsdnamepunct\bibnamedelimd\mkbibnamegiven{#2}\isdot}% \ifdefvoid{#5}{}{\addcomma\bibnamedelimd\mkbibnamesuffix{#5}\isdot}} {\usebibmacro{name:delim:apa:family-given}{#1}% \usebibmacro{name:hook}{#1}% \mkbibnamefamily{#1}\isdot \ifboolexpe{% test {\ifdefvoid{#2}} and test {\ifdefvoid{#4}}} {} {\revsdnamepunct}% \ifdefvoid{#2}{}{\bibnamedelimd\mkbibnamegiven{#2}\isdot}% \ifdefvoid{#4}{}{% \bibnamedelimc\mkbibnameprefix{#4}% \ifprefchar{}{\bibnamedelimc}}% \ifdefvoid{#5}{}{\addcomma\bibnamedelimd\mkbibnamesuffix{#5}\isdot}}} \renewbibmacro*{name:apa:given-family}[5]{% \usebibmacro{name:delim}{#2#4#1#5}% \usebibmacro{name:hook}{#2#4#1#5}% \ifdefvoid{#2}{}{\mkbibnamegiven{#2}\isdot% \bibnamedelimd}% \ifdefvoid{#4}{}{% \mkbibnameprefix{#4}\isdot \ifprefchar{}{\bibnamedelimc}}% \mkbibnamefamily{#1}\isdot% \ifdefvoid{#5}{}{\bibnamedelimd\mkbibnamesuffix{#5}\isdot}} \usepackage{filecontents} \begin{filecontents*}{\jobname.bib} @article{marquard1975, author = {Donald W. Marquardt and Ronald D. Snee}, title = {Ridge Regression in Practice}, journal = {American Statistician}, volume = {29}, number = {1}, pages = {3-20}, year = {1975}, } \end{filecontents*} \addbibresource{\jobname.bib} \begin{document} TEST \cite{marquard1975} \printbibliography \end{document} Note that the & in publisher = {Taylor & Francis}, should be escaped to \&. There was no error here, because biblatex does not print the publisher field for @articles, but it is good to remember to treat & correctly.
[ "stackoverflow", "0052155234.txt" ]
Q: Is there a way to allow SSH from specific machines on Centos? I need to restrict SSH on a Centos7 server and limit it to one workstation per user. I cannot use IP address, since it is assigned dynamically by VPN and can be different in each session. Bottom line is, each user should only be able to access the server from one workstation at a time. Is there a way to achieve this? A: You can do this by editing the limits.conf file - /etc/security/limits.conf Add username - maxlogins 1
[ "stackoverflow", "0047785785.txt" ]
Q: When parsing a html file, how to get the table with some specific child in R? I get a html with nested table: html='<html> <body><table><tr class="notChooseMe"> <td><table><tr class="chooseMe"></td> <td><table><tr class="notChooseMe"></tr></table></td> </tr></table> </body></html>' How can I extract the table with a "tr", which has the "chooseMe" class within the table? Please do not use the index to return the table since the position could change at anytime, for example, html='<html> <body> <table><tr class="notChooseMe0"></tr><tr> <td><table><tr class="notChooseMe1"></tr></table></td> ... <td><table><tr class="notChooseMe2"></tr></table></td> ... <td><table><tr class="chooseMe"></td> ... <td><table><tr class="notChooseMeX"></tr></table></td> </tr></table> </body></html>' Thanks! A: You can find the matching tr and then go back up to the parent: library(rvest) tab = read_html(html) %>% html_node("table tr.chooseMe") %>% xml_parent() Output: {xml_node} <table> [1] <tr class="chooseMe"><td>\n<table><tr class="notChooseMe"></tr></table>\n</td></tr>
[ "stackoverflow", "0030803946.txt" ]
Q: Searching an Array of Cells in Excel I am trying to search an array of cells in excel to find if it contains a word to then further evaluate. so for example; I have named the array (A1:A5) as 'cList'. A1 = apple A2 = pear A3 = orange A4 = banana A5 = cherry I want to =SEARCH("pear",cList) but i keep getting FALSE - which is not true because it is contained in A2. My thought here is that Search cannot be used on an array, because if I instead used =SEARCH("pear",A2) I will get my desired TRUE. So is there another way to test an array if it contains and answer? A: SEARCH only searches a single cell. The easiest way to find if a range contains a word is just to use COUNTIF =COUNTIF($A$1:$A$5,"pear") This tells you how many matches there are, or to get it as a TRUE/FALSE value =COUNTIF($A$1:$A$5,"pear")>0 You can also use wildcards, so this would find things like "pearmain" and "prickly pear" =COUNTIF($A$1:$A$5,"*pear*")>0
[ "math.stackexchange", "0002986102.txt" ]
Q: How do we use the hint to show the divisibility? I want to show that if $m=n^{13}-n$ and $n>1$ then $30290 \mid F_m$. (Hint: Show first that $a^{13} \equiv a \mod{2730}$.) $F_m$ is the $m$-th Fibonacci number. I have shown the hint as follows: $2730=2 \cdot 3 \cdot 5 \cdot 7 \cdot 13$. Using Fermat's little theorem, we deduce that $a^{13}\equiv a \pmod{5}$, $a^{13}\equiv a \pmod{2}$, $a^{13}\equiv a \pmod{3}$, $a^{13}\equiv a \pmod{7}$ and $a^{13}\equiv a \pmod{13}$. Since $2,3,6,7,13$ are all relatively prime, we deduce that $2730 \mid a^{13}-a$. But how can we use the fact that $a^{13} \equiv a \mod{2730}$ in order to deduce that $30290 \mid F_m$ ? A: Let's look at the first few Fibonacci numbers. In particular $F_2$, $F_3$, $F_5$, $F_7$, and $F_{13}$. The sequence is $$ 1,\mathbf{1},\mathbf{2},3,\mathbf{5},8,\mathbf{13},21,34,55,89,144,\mathbf{233}.$$ We can ignore $F_2=1$, but $F_3=2$, $F_5=5$, $F_7=13$, and $F_{13}=233$ are all distinct primes, and their lcm is therefore the product $2\cdot 5\cdot 13\cdot 233=30290$. Finally we link this fact with the part that you have shown by noting that if $n\mid m$, then $F_n\mid F_m$. Proof of the fact: The Fibonacci sequence is also given by the following formula: $$\newcommand\bmat{\begin{pmatrix}}\newcommand\emat{\end{pmatrix}} \bmat F_{n+1}\\F_n\emat=\bmat 1&1\\1&0 \emat^n\bmat 1\\ 0\emat.$$ Now suppose for contradiction that $F_n\nmid F_m$ for some integers $n$ and $m$ with $n\mid m$. Then let $k$ be the least positive integer such that $F_n\nmid F_{kn}$. Then we have that $$\bmat F_{kn+1}\\F_{kn}\emat =\bmat 1&1\\1&0 \emat^{kn}\bmat 1\\ 0\emat =\bmat 1&1\\1&0 \emat^{(k-1)n}\bmat 1&1\\1&0 \emat^{n}\bmat 1\\ 0\emat =\bmat 1&1\\1&0 \emat^{(k-1)n}\bmat F_{n+1} \\ F_n \emat. $$ Taking this equation mod $F_n$, we see that $$\bmat F_{kn+1}\\F_{kn}\emat =\bmat 1&1\\1&0 \emat^{(k-1)n}\bmat F_{n+1} \\ 0 \emat =F_{n+1} \bmat 1&1\\1&0 \emat^{(k-1)n}\bmat 1 \\ 0 \emat =F_{n+1} \bmat F_{(k-1)n+1} \\ F_{(k-1)n} \emat, $$ so mod $F_n$, we have $F_{kn}=F_{n+1}F_{(k-1)n}$, but by assumption $k$ was the least positive integer such that $F_n\nmid F_{kn}$, so $F_n\mid F_{(k-1)n}$ contradiction.
[ "superuser", "0001475606.txt" ]
Q: Windows 10: Move folders that contains directory symbolic links across partitions Suppose I have a folder under partition D that is D:\folder\link_folder which is a directory symbolic link whose target is E:\real_folder, i.e. it was created by: mklink /d D:\folder\link_folder E:\real_folder Now I need to move D:\folder to F:\ by the Explorer UI like cut/paste. But I found that now there is a full copy of E:\real_folder under F:\folder\link_folder which is not a link anymore. Is there a way to just create F:\folder\link_folder as a link to E:\real_folder during the folder move process? There is a lot of such links under D:\folder. A: You can use robocopy to move folders that contain directory symbolic links by using the /move /SL and /e parameters. Following your example, you could then use the command as follows: robocopy D:\folder F:\folder /move /e /SL /move will move the target instead of copy. /e will copy (move) all sub-directories including empty ones. /SL will copy (move) the symbolic link instead of following it. note: elevated command prompt is required for moving symbolic links in windows 10. note: For symbolic links created using mklink /d. References: Microsoft Docs robocopy contains syntax and details on robocopy, examples can be found at Technet robocopy examples. Related forum post on copying directory symlinks in Windows 7.
[ "stackoverflow", "0010132526.txt" ]
Q: Nonempty Array Has .length of 0 I have this function that seems to be doing what it should: var getData = function(query) { var data = []; db.transaction(function(tx) { tx.executeSql(query, [], function (tx, results) { var len = results.rows.length, i; for (i = 0; i < len; i++) { data.push(results.rows.item(i)); } }, error); }); return data; } When I do a console.log(data), it shows an array of objects with correct data, as you can see in an example from Chrome's console: However, data.length is 0, making it impossible to iterate. I've tried for(var i = 0; i < data.length; i++) { $('.regions').append(data[i].region + '<br>'); }; which is no good since data.length is 0. I've tried for(var key in data) { $('.regions').append(data[key].region + '<br>'); }; which doesn't work, presumably for the same reason. I even tried $.each() from jQuery, but nothing even enters the loop. I do a console.log(data) right before these loops to double check it still has the data as I would expect. I manually recreated the data by hand with data = [ { available: "1", company_id: 1, cultivar: "Cultivar 2.0", cultivar_id: 18, id: 18, image: "b0c2dd4765422fc0acce9461a040ebaf.png", logo: "980f2a610d681ade5b5b42511f89655c.png", maintenance: "Fairway", maintenance_id: 7, name: "Cultivar 2.0", region: "Midwest", region_id: 24, species: "Perennial Ryegrass", species_id: 7, trait_disease: "Disease 2", trait_disease_id: 6, available: "1" }, { company_id: 1, cultivar: "Cultivar 2.0", cultivar_id: 18, id: 18, image: "b0c2dd4765422fc0acce9461a040ebaf.png", logo: "980f2a610d681ade5b5b42511f89655c.png", maintenance: "Fairway", maintenance_id: 7, name: "Cultivar 2.0", region: "Midwest", region_id: 24, species: "Perennial Ryegrass", species_id: 7, trait_disease: "Disease 2", trait_disease_id: 6 } ]; and that type of thing appeared exactly the same in the console, but it worked when I iterated over it. I have done a few other things I found around StackOverflow, including making sure that it indeed was recognized as an array. Even if I knew the length, data[0] is undefined. I have spent some sweet time on this and wondered if anything else had any ideas. This has been tested in Chrome 18.0.1025.151 (Firefox doesn't have sqlite) and it will eventually go onto a phone with jQuery Mobile and PhoneGap, but we're not at that point, yet. Just a simple HTML page with a sqlite database. Thanks! A: Your fundamental problem is that you're expecting to be able to return the result of an asynchronous operation from the function that initiates it. The call to ".executeSql()" returns immediately. At some point after that, the database operation completes and your callback function is invoked. However, the containing function ("getData()") has long since returned. The way to make an API around asynchronous operations is to make your own API asynchronous. Give "getData()" another parameter so that its clients can pass in a handler function. Then, from the callback, invoke the handler and pass it the array as a parameter.
[ "gis.stackexchange", "0000033208.txt" ]
Q: Georeferencing vector layer with control points using QGIS? I have a non-georeferenced vector layer that I need to be georeferenced. With raster layers the task is easy and straightforward, but I have no idea what should I do with my vector layer. I have a few control points with known coordinates which should provide some basis to transformation. So, let's say I know points with id-s of 1, 2 and 3 should have the coordinates of x1,y1 ; x2,y2 ; x3,y3. There might be some rotation and scale transformation in addition to simple shifting. Any ideas? A: To georeference a vector layer, try the qgsAffine plugin. There is more info at Where to find qgsaffine in the menu? A: I recommend the Vector Bender plugin for QGIS. I tried it and it works fine and is user friendly. Depending on amount of pair of points that you define, you can either do: translations: translation from one starting to ending point (1 pair) uniform: translation, scaling and rotation (2 pairs) bending: additional deformation (3 pairs or more) You find a short video here and I advice you to read the Vector Bender help once you installed the plugin. A: Given the fact that you have some points of control, you should be able to use an Affine transformation to shift your vector data. Have a look at this recipe. The process is a two part process: Use your control points to define the coefficients of your affine function required take the coefficients and apply them to the ST_Affine() in postgis. If you put your control points into a CSV file (old_x,old_y,new_x,new_y), you can just about cut'n paste the R commands from the link to solve the coefficients part.
[ "stackoverflow", "0025915522.txt" ]
Q: All SubDirectories and a file count for each in a lable How can i have the list of all SubDirectories and for each SubDirectory a file count? And most important it must be in a form of continuos text, not as a listbox. My example just prints the last Directory. How can i get it to print them all like this: Adobe: 45 / Adobe Media Player:5 / Java: 22 / etc.... Private Sub GetDir() For Each x As String In System.IO.Directory.GetDirectories("C:\ProgramFiles") y = x & " : " & CStr(x.Count) Next Label1.Text = y End Sub I need it in continuos text so i can mail it actually. That's why i can't work with listbox. A: You can use a StringBuilder object to build the output and a DirectoryInfo object to easily get name and files count for each directory. Dim list As New StringBuilder For Each directory As String In IO.Directory.GetDirectories("C:\ProgramFiles") Dim subDirectory As New IO.DirectoryInfo(directory) list.Append(subDirectory.Name & ": " & subDirectory.GetFiles.Length & " / ") Next Dim text As String = list.ToString.Remove(list.Length - 3)
[ "buddhism.stackexchange", "0000002280.txt" ]
Q: Euthanasia and Buddhism The first precept makes it clear that we should refrain from killing. However let's say you have an animal (or worse, a human) who is going to die anyway (say from being attacked by another animal, or some incurable disease). He can either die on his own in agony, or you could end his life quickly. The intention is not to end his life out of hate or anger, but out of love and compassion - and anyway, nothing you or anyone will do will change that their going to die. Looking through the other questions on the topic, it's clear that you're going to get bad karma for killing something, even if it's (in your head) justified by self-defence or whatever - but in those cases you have a choice of killing vs something bad happening , while in this case you have a choice of killing vs watching die. A: I've been to a lecture in which a Tibetan Buddhist monk (specifically, a nyingmapa) was asked the same question by a teenage girl. Basically, his answer was, such killing would both end some existing suffering and create some new suffering. Because regular person does not see all complexity of karma network spanning multiple lives, his or her acts are very likely to make the karmic situation even worse. According to that monk, compassionate killing should be left to either dakas/dakinis (the crazy yogis capable of "eating icecream and shit at the same time" -- i.e. skilfully dealing with consequences of the bad karma they take on) or omniscient buddhas who can grant liberation at the time of killing, or at least create a favorable karmic condition in subsequent lives.
[ "french.stackexchange", "0000029482.txt" ]
Q: Term for "substantivized adjectives" in French grammar what is the term for substantivised adjectives in French grammar. I googled "substantivised adjectives in french" but very few pages are in this title. A: J'ai trouvé deux variantes. Soit: L’adjectif employé comme nom http://research.jyu.fi/grfle/038.html Soit: L'adjectif substantivé http://perso.numericable.fr/eric.alglave/Grammaire/adjsubs.htm Il existe aussi : Substantivation (voir le commentaire)
[ "stackoverflow", "0053659837.txt" ]
Q: TICKScript never resets Level to OK I’m writing a TickScript that acts on a series of points that can have exactly two outcomes. Either the result is pass or “not pass” (usually some variant of exit NUM). The script I have looks sort of like this: // RP: autogen // Monitor the result of updates // WARNING if the result is anything other than pass batch |query('''SELECT * FROM "mydb"."autogen"."measurement"''') .period(25h) .every(24h) .groupBy('host') |alert() .id('kapacitor/{{ .TaskName }}/{{ .Group }}') .infoReset(lambda: TRUE) .warn(lambda: "result" != 'pass') .message( '{{ index .Tags "host" }}' + '{{ if eq .Level "OK" }} are updating again.' + '{{ else }}' + 'are failing to update.' + '{{ end }}' ) .idField('id') .levelField('level') .messageField('description') .stateChangesOnly() @alertFilterAdapter() @alertFilter() The script does seem to sort of do its thing, but has a critical issue of never setting the Level back to OK. If I feed influx these 4 points: time host name result ---- ---- ---- ------ 1544079584447374994 fakeS176 /usr/bin/yum update -y pass 1544079584447374994 fakeS177 /usr/bin/yum update -y exit 1 1544129084447375177 fakeS176 /usr/bin/yum update -y exit 1 1544129084447375177 fakeS177 /usr/bin/yum update -y pass I would expect 1 warning, and 1 OK. Where all of the timestamps listed above are within the 25 hour period. However what actually happens is that I get 2 warns and no OKs. Could someone give some advice on how to move forward? A: Update - a coworker told me about a nodes I had no idea about. Adding a last() node and adding an as(), then removing the infoReset() node seemed to do it. // RP: autogen // Monitor the result of updates // WARNING if the result is anything other than pass batch |query('''SELECT * FROM "mydb"."autogen"."measurement"''') .period(25h) .every(24h) .groupBy('host') |last('result') .as('result') |alert() .id('kapacitor/{{ .TaskName }}/{{ .Group }}') .warn(lambda: "result" != 'pass') .message( '{{ index .Tags "host" }}' + '{{ if eq .Level "OK" }} are updating again.' + '{{ else }}' + 'are failing to update.' + '{{ end }}' ) .idField('id') .levelField('level') .messageField('description') .stateChangesOnly() @alertFilterAdapter() @alertFilter() Screw this blasted language.
[ "stackoverflow", "0005092152.txt" ]
Q: How can I copy value from ostringstream to string? I tried : ostringstream oss; read a string from file and put to oss; string str; str << oss.str();// error here "error: no match for ‘operator>>’ in 'oss >> str' " If I use str = oss.str(); Instead of printing the value of the string, it prints out "....0xbfad75c40xbfad75c40xbf...." likes memory address. Can anybody tell me why? Thank you. A: string str = oss.str(); // this should do the trick A: If you're trying to copy the whole file to a stringstream, then this: oss << ifs; is wrong. All that does is prints the address of ifs. What you want to do is this: oss << ifs.rdbuf(); And then of course, to copy that to a string, like the others are saying: str = oss.str(); If you just want to get a single line, then skip the stringstream, and just use getline: std::getline(ifs,str);
[ "stackoverflow", "0028574035.txt" ]
Q: MVC Model Navigation Links I am trying to do a simple MVC project. The idea is to select information from the database and display it on a map. This is an upgrade/replacement of a previous job not written in MVC. New features are desired that MVC should make easy (to maintain). The database is a vendor database, and I can make no changes. I have added 4 views: vwMapsDrivers Driver Details vwMapsVehicles Vehicle Details vwMapsIncidents Incident Details vwMapsLogs Log Entries The basic plan is to list Incidents, with attached driver and vehicle info, and a collection of Logs from the start of the incident to the end of the incident (+ a threshold either way). This is the MainContext class using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; namespace MapsMVC.Models { public class MainContext : DbContext { public DbSet<VehicleModel> Vehicles { get; set; } public DbSet<IncidentModel> Incidents { get; set; } public DbSet<DriverModel> Drivers { get; set; } public DbSet<LogsModel> Logs { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<VehicleModel>().ToTable("vwMapsVehicles"); modelBuilder.Entity<IncidentModel>().ToTable("vwMapsIncidents"); modelBuilder.Entity<DriverModel>().ToTable("vwMapsDrivers"); modelBuilder.Entity<LogsModel>().ToTable("vwMapsLogs"); base.OnModelCreating(modelBuilder); } } } This is the IncidentModel class using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using DataAnnotationsExtensions; namespace CtrackMapsMVC.Models { public class IncidentModel { [Key] [Integer] [Min(0)] [Display(Name = "Incident Id")] public int IncidentId { get; set; } [Integer] [ForeignKey("Vehicles")] [Display(Name = "Vehicle Id")] public string NodeId { get; set; } [DataType(DataType.DateTime)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm:ss}", ApplyFormatInEditMode = true)] [Display(Name = "Incident Start")] public DateTime IncidentStart { get; set; } [DataType(DataType.DateTime)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm:ss}", ApplyFormatInEditMode = true)] [Display(Name = "Incident End")] public DateTime IncidentEnd { get; set; } [Required] [DataType(DataType.Text)] [Display(Name = "Location")] public string Location { get; set; } [Required] [DataType(DataType.Text)] [Display(Name = "Incident Type")] public string IncidentType { get; set; } [Integer] [Min(0)] [ForeignKey("Logs")] [Display(Name = "First Log Id")] public int FirstLogId { get; set; } [Integer] [Min(0)] [ForeignKey("Logs")] [Display(Name = "Last Log Id")] public int LastLogId { get; set; } [Integer] [Min(0)] [ForeignKey("Drivers")] [DisplayFormat(NullDisplayText = "No Driver")] [Display(Name = "Driver Node Id")] public int DriverNodeId { get; set; } public virtual VehicleModel Vehicle { get; set; } public virtual DriverModel Driver { get; set; } public virtual ICollection<LogsModel> Logs { get; set; } } } This is the VehicleModel using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using DataAnnotationsExtensions; namespace CtrackMapsMVC.Models { public class VehicleModel { [Key] [Integer] [Min(0)] [Editable(false)] [Display(Name = "Node Id")] public int NodeId { get; set; } [Required] [DataType(DataType.Text)] [Editable(false)] [Display(Name = "Vehicle Name")] public string VehicleName { get; set; } [DataType(DataType.Text)] [Editable(false)] [Display(Name = "Vehicle Description")] public string VehicleDescription { get; set; } [DataType(DataType.Text)] [Editable(false)] [Display(Name = "Cellnumber")] public string Cellnumber { get; set; } [DataType(DataType.DateTime)] [Editable(false)] [Display(Name = "Last Received")] public DateTime LastReceived { get; set; } [DataType(DataType.Text)] [Editable(false)] [Display(Name = "Unit Type")] public string NodeTypeDesc { get; set; } [DataType(DataType.Text)] [Editable(false)] [Display(Name = "Site Code")] public string SiteCode { get; set; } } } The LogsModel and DriverModel are pretty straightforward. The site compiles with no problem, with the Controllers being default generated boilerplate. The Views are also generated, but the Edit/Delete pages are removed, as are link references in the Index. The home page loads. When trying to load /Vehicle/Index I get the following exception: The ForeignKeyAttribute on property 'NodeId' on type 'CtrackMapsMVC.Models.IncidentModel' is not valid. The navigation property 'Vehicles' was not found on the dependent type 'CtrackMapsMVC.Models.IncidentModel'. The Name value should be a valid navigation property name. What am I doing wrong with my Foreign key declaration? How can I fix it? Some reading has implied it won't work because the SQL VIews dont actually have FK relationships (not possible to define). Is there an extension that will help? Sure coding against views isn't that uncommon? A: The property you set here: [ForeignKey("Vehicles")] is your navigation property which you set to Vehicles but you included public virtual VehicleModel Vehicle { get; set; } which is Vehicle and not Vehicles. Ref: http://peterkellner.net/2012/04/07/gaining-some-control-back-from-microsofts-entity-framework-code-first-name-your-own-foreign-keys/
[ "english.stackexchange", "0000143251.txt" ]
Q: What does this "expose" mean? “The novelist must begin by playing the sedulous ape, assimilating the craft of his predecessors; but he does not master his own form until he has somehow exposed and surpassed them.”Source Does "expose" mean that the secrets of the predecessors are now revealed? Or does it have another meaning? A: Melville remains one of the best American examples of how every important writer is foremost an indefatigable reader of golden books, someone who kneels at the altar of literature not only for wisdom, sustenance, and emotional enlargement, but with the crucial intent of filching fire from the gods. It is clear from this passage that the fire filched from the gods of the best literature was form. To really find his own form, he need to analyze the form of others, exposing them so to speak, so that he could learn from them, and in so doing, improve upon his own, until it became a new, individual form - his own.
[ "stackoverflow", "0014809235.txt" ]
Q: TreeSet Java Code working in java application but not in android project This is my code when i doing as java application import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.ArrayList; import java.util.Locale; import java.util.TreeSet; public class DateRounding { public static void main(String[] args) throws ParseException { List ls=new ArrayList(); ls.add (new SimpleDateFormat("yyyy-MM-dd-HH-mm", Locale.ENGLISH).parse("2010-02-31-14-30")); ls.add(new SimpleDateFormat("yyyy-MM-dd-HH-mm", Locale.ENGLISH).parse("2010-02-31-14-50")); ls.add(new SimpleDateFormat("yyyy-MM-dd-HH-mm", Locale.ENGLISH).parse("2010-02-31-14-10")); ls.add(new SimpleDateFormat("yyyy-MM-dd-HH-mm", Locale.ENGLISH).parse("2010-02-31-14-01")); final Calendar c = Calendar.getInstance(); String string = "2010-02-31-14-00"; Date date = new SimpleDateFormat("yyyy-MM-dd-HH-mm", Locale.ENGLISH).parse(string); Date x=getDateNearest(ls , date); System.out.println("date:"+x); System.out.println(ls.indexOf(x)); System.out.println("index:"+ls.indexOf(new SimpleDateFormat("yyyy-MM-dd-HH-mm", Locale.ENGLISH).parse("2010-02-31-14-10"))); } private static Date getDateNearest(List<Date> dates, Date targetDate){ return new TreeSet<Date>(dates).higher(targetDate); // return targetDate; } } when i add same code to android project is showing error "The method higher(Date) is undefined for the type TreeSet" ,but this higher() is working perfectly in java application.....how can i use higher method in android? A: The compliance settings of your compiler are set to JRE 1.4 (higher first appeared in 1.5). Check the configuration of your project (difficult to give details without even knowing which tool or IDE it is). Recent versions of Android not just support but even require compliance with JRE 1.5 or 1.6. From that I can quickly test, Android 2.2 API level 8 complains and Android 3.1 level 12 already do not. As of today, the most recent level is 17. Check the developer manual on how to build the right application for Android. public static void main(String[] args) is not the right way to do this.
[ "askubuntu", "0001189308.txt" ]
Q: Software Update problem libplacebo18 on ubuntu 18.04 This has been since the last update message I can't install any other programs because of this error, please help. If you are using third party repositories then disable them, since they are a common source of problems. Now run the following command in a terminal: apt-get install -f Transaction failed: The package system is broken The following packages have unmet dependencies: mpv: Depends: libplacebo18 (>= 1.18.0) but it is not installed Depends: libxrandr2 (>= 2:1.2.99.3) but 2:1.5.1-1 is installed That's the message that appears after I run the installer. Than I tried to run sudo apt update And many other commands in order to update the package but it seems to not working every time. sudo apt --fix-broken install Reading package lists... Done Building dependency tree Reading state information... Done Correcting dependencies... Done The following packages were automatically installed and are no longer required: libdav1d2 libplacebo7 Use 'sudo apt autoremove' to remove them. The following additional packages will be installed: libplacebo18 The following NEW packages will be installed libplacebo18 0 to upgrade, 1 to newly install, 0 to remove and 29 not to upgrade. 1 not fully installed or removed. Need to get 0 B/129 kB of archives. After this operation, 360 kB of additional disk space will be used. Do you want to continue? [Y/n] y (Reading database ... 249564 files and directories currently installed.) Preparing to unpack .../libplacebo18_1.18.0-1~bionic1_amd64.deb ... Unpacking libplacebo18:amd64 (1.18.0-1~bionic1) ... dpkg: error processing archive /var/cache/apt/archives/libplacebo18_1.18.0-1~bionic1_amd64.deb (--unpack): trying to overwrite '/usr/lib/x86_64-linux-gnu/libplacebo.so.18', which is also in package libplacebo7:amd64 1.8.0-1~bionic dpkg-deb: error: paste subprocess was killed by signal (Broken pipe) Errors were encountered while processing: /var/cache/apt/archives/libplacebo18_1.18.0-1~bionic1_amd64.deb E: Sub-process /usr/bin/dpkg returned an error code (1) That's something that could help I have no idea what's happening. A: I fixed it by force overwriting the package sudo dpkg -i --force-overwrite /var/cache/apt/archives/libplacebo18_1.18.0-1~bionic1_amd64.deb And then I used this command to fix any broken packages. sudo apt -f install
[ "stackoverflow", "0044195324.txt" ]
Q: How to replace value in map for a key based on a condition in scala I have several immutable map records like : val map = Map("number"->7,"name"->"Jane","city"->"New York") I need to identify the "name" key for each record and check its value.If value is "Jane" , I need to replace with "Doe" and update the map record. A: This can be achieved by a simple map operation and pattern matching. scala> val dictionary = Map("number"->7,"name"->"Jane","city"->"New York") map: scala.collection.immutable.Map[String,Any] = Map(number -> 7, name -> Jane, city -> New York) scala> dictionary map { | case ("name","Jane") => "name" -> "Doe" | case x => x | } res3: scala.collection.immutable.Map[String,Any] = Map(number -> 7, name -> Doe, city -> New York)
[ "stackoverflow", "0011622025.txt" ]
Q: Comparing two arraylists with multiple set fields I am trying to compare two ArrayLists, but I can't seem to get it work. Suppose: My main arrayList called List 1 gets its value through: ArrayList<xTypeClass> List1 = new ArrayList<xTypeClass>(); xTypeClass tmp = new xTypeCLass(); tmp.setName(name); tmp.setaddress(address); tmp.setPhone(phone); tmp.setMonth(mo); ..etc List1.add(tmp); Now I have another list2 that holds the exact type format, but has different values. And I want to compare List2 to 1 and see which ones does not exist in List2 that does in List1 and add it to List2. I am having problem using double for loops to go around both list to find which exists and which doesn't. Can someone point me in the right direction? Comment below if you need any more information. A: Assuming you've implemented equals() and hashCode() for xTypeClass, is there any reason why you can't just do: for (xTypeClass x : List1) { if (!List2.contains(x)) { List2.add(x); } }
[ "stackoverflow", "0061618242.txt" ]
Q: How to solve a php strtotime language issue not sincronyzed with server bash language I have a server which is running a German local language for Bash. When I try to change maillog time in this server in Unix timestamp using .. $time1="Mai-05-20 17:22:36"; $unix_time=strtotime($time1); $unix_time returns empty, I think because bash is using German but PHP is running english (?). How can I set the php script to run in the same language of Bash local language ? A: From docs (emphasis mine): strtotime — Parse about any English textual datetime description into a Unix timestamp In case you don't need the full power of strtotime() (after all, you seem to be parsing logs from one single program) you can try IntlDateFormatter::parse(). Here's a quick and dirty demo: $fmt = new IntlDateFormatter('de_DE', null, null); $fmt->setPattern('M-dd-yy hh:mm:ss'); $log_time = "Mai-05-20 17:22:36"; $unix_time = $fmt->parse($log_time); echo date('r', $unix_time); Tue, 05 May 2020 17:22:36 +0200 Note that a Unix time is a fixed moment in time, thus unaffected by time zones. I get +0200 when casting to local time because my PHP default time zone is currently CEST.
[ "stackoverflow", "0057056325.txt" ]
Q: How to set a maximum per page in laravel dynamically? I have a Products class that looks for these paginated items, but in the front end I allow the user to define how many items he wants to display per page (10, 30, 50, 100) the problem is that if someone passes 1000, the api returns 1000 records per page. How can I validate this for all controllers and models dynamically? I could do this "easily" by validating each request ('limit') on each controller, but it would not be practical, how can I do that? public function index(Request $request) { $perPage = $request->input('limit'); // User input $sort = 'global_performance'; $descending = 'desc'; $products = Product::where('status', 1) ->orderBy($sort, $descending) ->paginate($perPage); // return $products; } A: You can validate the limit like this: public function index(Request $request) { $this->validate($request, [ 'limit' => ['required', 'integer', Rule::in([10, 30, 50, 100])] ]); $perPage = $request->input('limit'); // User input $sort = 'global_performance'; $descending = 'desc'; $products = Product::where('status', 1) ->orderBy($sort, $descending) ->paginate($perPage); // return $products; } Now, add following line in just before controller class: use Illuminate\Validation\Rule; Update More dynamic way might be creating custom request class like this: Run following command to create a new form request class: php artisan make:request PaginateRequest This will create PaginateRequest class at App\Http\Requests directory like this: <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class PaginateRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return false; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ // ]; } } Now change this class into following: <?php namespace App\Http\Requests; use Illuminate\Validation\Rule; use Illuminate\Foundation\Http\FormRequest; class PaginateRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'limit' => ['required', 'integer', Rule::in([10, 30, 50, 100])] ]; } } After this, you can use in controller function by adding it as function parameter. public function index(PaginateRequest $request) { $perPage = $request->input('limit'); // User input $sort = 'global_performance'; $descending = 'desc'; $products = Product::where('status', 1) ->orderBy($sort, $descending) ->paginate($perPage); // return $products; } Please don't forget to import it just before controller class like this: use App\Http\Requests\PaginateRequest; In this way, You can use this request class everywhere you need. You can see more at documentation here: https://laravel.com/docs/5.8/validation A: You could easily create a middleware. Apply it simply from kernel to each and every route or make a group in your route file to apply it to selective routes. Inside the middleware just check the limit, if empty or more than the max limit you want let's say 100, make it 100 like so: $limit = $request->input('limit'); if (empty($limit) || ($limit > 100)) { $request['limit'] = 100; } wouldn't that work? Here is link for middlewares in Laravel.
[ "stackoverflow", "0033266678.txt" ]
Q: How to extract information from the content of /proc files on Linux using C? I have been working on this for over 7 hours a day for 5 days. I am not exactly the best coder, so I need some help. I need to know how should I get the info from /proc using a C program on Linux. The info has to be printed out and include the following: The complete command line for the process. State of the process. The PID of the parent. Priority. The nice value. Real­time  scheduling priority. CPU number last executed on. Amount of time that this process has been scheduled  in  user  mode. Amount of time that this process has been scheduled in kernel  mode. Virtual memory size in bytes. Total program size in pages. Resident Set Size (RSS) in bytes. Resident Set Size (RSS): number of pages the process has in real memory in  pages. Text (code) size in pages. Data + stack size in pages. Page table entries size in KB. Size of data in KB. Size of stack in KB. Size of text segment KB. A: It sounds like you don't know where to start. Let me try to explain the information in /proc: If we cat /proc/29519/stat, we get this info: 29519 (vim) S 5997 29519 5997 34835 29519 24576 1275 0 47 0 5 0 0 0 20 0 2 0 49083340 188043264 3718 18446744073709551615 4194304 6665820 140737488349264 140737488347024 140737280970147 0 0 12288 1837256447 18446744073709551615 0 0 17 3 0 0 21 0 0 8764120 8861948 8925184 140737488349925 140737488349929 140737488349929 140737488351211 0 What do all those numbers represent? The answer is in man proc, in the section called /proc/[pid]/stat. From this we see the first four things are: pid %d (1) The process ID. comm %s (2) The filename of the executable, in parentheses. This is visible whether or not the executable is swapped out. state %c (3) One character from the string "RSDZTW" where R is running, S is sleeping in an interruptible wait, D is waiting in uninterruptible disk sleep, Z is zombie, T is traced or stopped (on a signal), and W is paging. ppid %d (4) The PID of the parent. With this knowledge we can parse it out with fscanf(f, "%d %s %c %d", ...): #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> void main(int argc, char **argv) { int pid; sscanf(argv[1], "%d", &pid); printf("pid = %d\n", pid); char filename[1000]; sprintf(filename, "/proc/%d/stat", pid); FILE *f = fopen(filename, "r"); int unused; char comm[1000]; char state; int ppid; fscanf(f, "%d %s %c %d", &unused, comm, &state, &ppid); printf("comm = %s\n", comm); printf("state = %c\n", state); printf("parent pid = %d\n", ppid); fclose(f); } Now if I compile that file and run ./a.out 29519, I get pid = 29519 comm = (vim) state = S parent pid = 5997 Does that give you enough information to get started?