text
stringlengths
64
81.1k
meta
dict
Q: How to rotate X-axis labels onto the bar in bar chart? I need to align x-axis labels as shown in the snapshot below: I tried: .attr("transform", function(d) { return "rotate(-90)" }) But it rotated the whole axis/scale. How do I fix this? jsFiddle EDIT: I updated my code: svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis) .selectAll("text") .style("text-anchor", "end") .attr("dx", "0em") .attr("dy", "0em") .attr("transform", function(d) { return "rotate(-90)" }); Now the labels are rotated to -90 degrees. How do I get it onto the bars? jsFiddle A: You need to rotate only text, and then translate it properly. See the updated fiddle: svg.selectAll('.tick') .select('text') .attr('transform', 'rotate(-90) translate(50, -12)'); http://jsfiddle.net/MjFgK/18/ A: I'm not that good in using translate. But this fiddle just works fine. Reason why the whole axis/scale got rotated is because when the text being created with x and y position, the origin point of it becomes (0,0). So to rotate your text labels you need to position those text using translate instead of x and y. In the fiddle I've added the below code at the bottom where it text labels are being rotated. If you wanted to rotate it more. You can just change the degree of rotation. svg.selectAll(".text") .data(data) .enter() .append("text") .attr("transform", function(d, i) { return "translate(" + (35 + x(d.age)) + ", 250)" + "rotate(-90)" }) .text(function(d) { return d.age; }) Hope this helps for you.
{ "pile_set_name": "StackExchange" }
Q: Scheduler Job not called in SpringBoot app I have this SpringBoot app: @SpringBootApplication @EnableScheduling @Import({SecurityConfig.class}) public class BlogsApplication implements CommandLineRunner { .. } and I also have this class, @Component public class UptadeCurrencyJob1 { @Scheduled(cron = "0 0/10 1 * * ?") public void reportCurrentTime() throws IOException { System.out.println("UptadeCurrencyJob1"); } } But it never calles A: @Scheduled(cron = "0 0/10 1 * * ?") Indeed, this is valid cron expresion meaning that it will fire every 10 minutes past midnight (for 1 hour only). I bet you did not wait that long nor you did mean that.
{ "pile_set_name": "StackExchange" }
Q: cumalativive the all other columns expect date column in python ML with cumsum() I have stock data set like **Date Open High ... Close Adj Close Volume** 0 2014-09-17 465.864014 468.174011 ... 457.334015 457.334015 21056800 1 2014-09-18 456.859985 456.859985 ... 424.440002 424.440002 34483200 2 2014-09-19 424.102997 427.834991 ... 394.795990 394.795990 37919700 3 2014-09-20 394.673004 423.295990 ... 408.903992 408.903992 36863600 4 2014-09-21 408.084991 412.425995 ... 398.821014 398.821014 26580100 I need to cumulative sum the columns Open,High,Close,Adj Close, Volume I tried this df.cumsum(), its shows the the error time stamp error. A: I think for processing trade data is best create DatetimeIndex: #if necessary #df['Date'] = pd.to_datetime(df['Date']) df = df.set_index('Date') And then if necessary cumulative sum for all column: df = df.cumsum() If want cumulative sum only for some columns: cols = ['Open','High','Close','Adj Close','Volume'] df[cols] = df.cumsum()
{ "pile_set_name": "StackExchange" }
Q: Problems displaying some characters I've got an XML file from which I've extracted the following text - The Sansa Clip+ MP3 player gives you more to enjoy. Enjoy up to 2,000 songs†† with an 8GB* player, FM radio, long-life battery and voice recorder. PLUS now even more! Expand your enjoyment when you add in preloaded content cards** into the new memory card slot, including slotRadio™ and slotMusic™ cards**. Or, save your own music, podcasts, and audio books onto a microSD™/microSDHC™ memory card** to expand your play.It’s brought to you by SanDisk with awesome sound to enjoy your music. Just clip it on and enjoy more music with an incredible 15 hours† battery-fueled fun. See what you’re listening to with the bright, easy-to-read screen and intuitively searchable menus. Color your world in red, blue or sleek black undertones. Why does it display on my webpage as below and how can I fix it automatically? Thanks. The Sansa Clip+ MP3 player gives you more to enjoy. Enjoy up to 2,000 songs††with an 8GB* player, FM radio, long-life battery and voice recorder. PLUS now even more! Expand your enjoyment when you add in preloaded content cards** into the new memory card slot, including slotRadioâ„¢ and slotMusicâ„¢ cards**. Or, save your own music, podcasts, and audio books onto a microSDâ„¢/microSDHCâ„¢ memory card** to expand your play.It’s brought to you by SanDisk with awesome sound to enjoy your music. Just clip it on and enjoy more music with an incredible 15 hours†battery-fueled fun. See what you’re listening to with the bright, easy-to-read screen and intuitively searchable menus. Color your world in red, blue or sleek black undertones. NOTE: I tried preinheimer's suggestion, First I tested it with a text file which worked well. $content = file_get_contents("test.txt"); echo htmlentities($content); But when I tried the same thing dynamically it didn't work and left the text just the same. $content = $responseTemp->Items->Item->EditorialReviews->EditorialReview[$j]->Content; echo htmlentities($content); They both contain the same text but for some reason the dynamically version doesn't work. ANOTHER UPDATE: I tried Juan's suggestion which is a slight improvement but still doesn't reproduce correctly, replacing many charecters with a question mark. Here's what it gives me, The Sansa Clip+ MP3 player gives you more to enjoy. Enjoy up to 2,000 songs?? with an 8GB* player, FM radio, long-life battery and voice recorder. PLUS now even more! Expand your enjoyment when you add in preloaded content cards** into the new memory card slot, including slotRadio? and slotMusic? cards**. Or, save your own music, podcasts, and audio books onto a microSD?/microSDHC? memory card** to expand your play.It?s brought to you by SanDisk with awesome sound to enjoy your music. Just clip it on and enjoy more music with an incredible 15 hours? battery-fueled fun. See what you?re listening to with the bright, easy-to-read screen and intuitively searchable menus. Color your world in red, blue or sleek black undertones. FINAL UPDATE: Aha, my mistake, I replaced $myOutputEncoding with 'utf-8' on Juan's example and add the following in the head tags to get it working, <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> A: It sounds like a character set issue. Luckily, I wrote an article that got published today. http://phpadvent.org/2009/character-sets-by-paul-reinheimer Check for a character set in the XML document (should be at the top, probably UTF-8), then try serving your page with the same character set. A: Since you dont know the original encoding, you can try guessing with mb_detect_encoding like so $content = $responseTemp->Items->Item->EditorialReviews->EditorialReview[$j]->Content; $encoding = mb_detect_encoding( $content ); $encodedText = mb_convert_encoding( $content, $myOutputEncoding, $encoding ); where $myOutputEncoding is the encoding you use. Then when you output $encodedText it should show the text correctly.
{ "pile_set_name": "StackExchange" }
Q: wireless interface: usb or pci? I have a router in my basement, and a desktop in the office upstairs, about 20 feet away through walls. With my laptop, which has a 5300 bgn card, i get a consistent 80% + signal with 100+mbps connection. I've had trouble in the past using a Airlink 101 golden N usb adapter on the desktop, not sure if that's bc it's an off brand or not. But I'm curious if going PCI would be better? Does anyone have experience using similar interfaces? I put the laptop right next to the desktop and the laptop stays strong while the desktop w usb adapter always drop to 26mbps or less, consistenly, but still maintains a 60-80% connection strength. I'm on windows 7. A: If it will be a permanent addition to that box, use PCI. There are sometimes power issues with USB (i.e. a voltage drop will cut power to it), and you will get more reliable and consistent performance from an internal card.
{ "pile_set_name": "StackExchange" }
Q: Group in Linq with Max: How do I get the full data set of the max value? what I have got so far is this: var a = from e in tcdb.timeclockevent group e by e.workerId into r select new { workerId = r.Key, Date = r.Max(d => d.timestamp) }; This Query is giving me latest "timestamp" of every workerId (Note: workerId is not the primary key of tcdb.timeclockevent). So it is only giving me pairs of two values but I need the whole data sets Does anybody know how I can get the whole datasets of tcdb.timeclock with the maximal timestamp for every workerId? OR Does anybody know how I can get the Id of the data sets of the maximal date for each worker? Thank you in advance :) A: You can order your r grouping by timestamp and select the first one var a = from e in tcdb.timeclockevent group e by e.workerId into r select r.OrderByDescending(d => d.timestamp).FirstOrDefault();
{ "pile_set_name": "StackExchange" }
Q: isset in jQuery I want check if there is class .required_selectbox in html code run function required_selectbox() and if there is class .required in html code run function required_valid(), after submit, how is it? function required_valid() { $('.required').each(function () { if (!$(this).val()) { //var cssObj=; $(this).css("background", "#ffc4c4"); result = false; } else { $(this).css("background", "#FFFFEC"); result = true; } $(this).keyup(function () { $(this).css("background", "#FFFFEC"); }) }); return result; } function required_selectbox() { $('.required_selectbox').each(function () { if (!$(this).val()) { //var cssObj=; $(this).css("background", "#ffc4c4"); result = false; } else { result = true; } }); return result; } $('.submit').submit(function () { //alert('hello'); var passed = true; passed = required_selectbox() && passed; passed = required_valid() && passed; if (!passed) { return false; } }); A: A simple approach would be to run those functions even if the elements aren't there. Because no elements would be found, the calls to each() would do nothing, so all that's needed is to have the result variable set to true by default: function required_selectbox() { var result = true; // <--- $('.required_selectbox').each(function () { if (!$(this).val()) { //var cssObj=; $(this).css("background", "#ffc4c4"); result = false; } else { result = true; } }); return result; } Also, it looks like you probably don't want the else statement in there so you might want to remove it.
{ "pile_set_name": "StackExchange" }
Q: How to set up vim allowing to use tabs and 4spaces I want normally always use four spaces to indent code. Unfortunately for example Makefiles enforce the use of tabs as separator. My idea now was to set the tab key to four spaces and some extra key (e.g. tab + shift) for the real tabs. How do I set something like this up? Currently my ~/.vimrc looks like: syntax on :set tabstop=4 :set cindent :set autoindent A: You may prefer something like this as well: set expandtab autocmd FileType make setlocal noexpandtab This will always convert tabs to spaces, except when you are editing Makefiles. A: Ctrl+V Tab will insert a literal tab, even if expandtab is set. If you prefer, you can map this to Shift+Tab with :inoremap <s-tab> <c-v><tab>.
{ "pile_set_name": "StackExchange" }
Q: Insert XML content to php Can anyone please help me fetch an email address from an XML file & insert it to a php code? Please find the codes below. XML CODE <?xml version="1.0" encoding="UTF-8"?> <document> <data> <emailaddress>[email protected]</emailaddress> </data> </document> PHP CODE if($_POST){ $to_email = "<?php $xml=simplexml_load_file("data.xml"); echo $xml->data->emailaddress;?>"; } This php code does not pull the email address from the xml file. Can anyone suggest me a fix? Thanks heaps in advance! Cheers David A: Try this one (tested): <?php if($_POST){ $xml=simplexml_load_file("data.xml"); echo $xml->data[0]->emailaddress; } ?> Or Try like your code : <?php if($_POST){ $xml=simplexml_load_file("data.xml"); $to_email =$xml->data[0]->emailaddress; echo $to_email; } ?>
{ "pile_set_name": "StackExchange" }
Q: jruby on tomcat - RackInitializationException After following http://kenai.com/projects/jruby/pages/JrubyOnRailsOnTomcat#Rails_2.0 though with tomcat 5.5, jruby 1.3.0, rails 2.3.2 tomcat gives: SEVERE: unable to create shared application instance org.jruby.rack.RackInitializationException: Please install the jdbc adapter: gem install activerecord-jdbc-adapter (no such file to load -- active_record/connection_adapters/jdbc_adapter) A: needed to do the following ... gem install activerecord-jdbcmysql-adapter gem install jruby-openssl uncomment the following line from warble.rb config.gems += ["activerecord-jdbcmysql-adapter", "jruby-openssl"]
{ "pile_set_name": "StackExchange" }
Q: Referencing SQL model in mongoengine model field I'm using mongoengine in my workout calendar Django project to store workouts with varying fields, depending on which lifts a user has done, how many of them, etc. I have defined a Workout object that represents one workout done by one person at a certain date. class Workout(Document): id = IntField(unique=True, null=False) date = DateTimeField() lifts = EmbeddedDocumentListField(LiftSerie) cardio = EmbeddedDocumentListField(CardioSerie) Some of you might notice that there is no field representing the person who did the workout. That is where my question comes in. In my Django project, I have defined a custom User model that I've used instead of the normal django.contrib.auth.models.User object: class User(AbstractUser): REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' email = models.EmailField( unique=True, }, ) This model is a normal Django model, and is represented in an SQL database, SQLite in my case. I would like this model to act as the user field in my Workout mongoengine model. Something like this: class Workout(Document): id = IntField(unique=True, null=False) date = DateTimeField() lifts = EmbeddedDocumentListField(LiftSerie) cardio = EmbeddedDocumentListField(CardioSerie) person = ReferenceField(User) #New row Is this possible to achieve in some way? Or do I need to introduce redundancy to my web app by simply adding an email field to my mongoengine model to represent a user (email is a unique field in User). A: I would implement a custom model manager that implements the query you're asking for by using db_manager You're implementing a good amount of extra complexity by using two different database types. If I were you, I'd look at simplify your database infrastructure by leveraging the NoSQL and JSON capabilities of Postgres.
{ "pile_set_name": "StackExchange" }
Q: Where can I find sample databases with common formatted data that I can use in multiple database engines? Does anybody know of any sample databases I could download, preferably in CSV or some similar easy to import format so that I could get more practice in working with different types of data sets? I know that the Canadian Department of Environment has historical weather data that you can download. However, it's not in a common format I can import into any other database. Moreover, you can only run queries based on the included program, which is actually quite limited in what kind of data it can provide. Does anybody know of any interesting data sets that are freely available in a common format that I could use with mySql, Sql Server, and other types of database engines? A: The datawrangling blog posted a nice list a while back: http://www.datawrangling.com/some-datasets-available-on-the-web Includes financial, government data (labor, housing, etc.), and too many more to list here. A: A lot of the data in Stack Overflow is licensed under the create commons. Every 3 months they release a data dump with all the questions, answers, comments, and votes. A: For Microsoft SQL Server, there is the Northwind Sample DB and AdventureWorks.
{ "pile_set_name": "StackExchange" }
Q: Content over 10,000 characters won't display with the_content() A friend of mine just noticed that their site wasn't displaying pages that had a lot of content. For some reason they are just blank, and if he removes some content from the page it will display again. The 10,000 character mark seems to be the threshold - anything above and it goes blank. I played with his templates and noticed that the content would be displayed if I used echo get_the_content() rather than the_content(), but then he loses the auto-formatting. Has anyone run into this issue before? I've googled around and searched this site but haven't been able to find anything. Thanks in advance for any light you can shed on this! A: I ran into this problem a year or so ago, and found a fix here. Open PHP.INI in a text editor of your choice (normally you can find php.ini in your php install dir) Change the recursion limit to 200x normal, that is, set: pcre.recursion_limit=20000000 Change the backtrack limit to 100x normal, that is, set: pcre.backtrack_limit=10000000 Stop and start the Apache (or IIS) service As a warning note, if you push this too far and your server is underpowered, you may end up crashing PHP as it consumes the entire stack. Your host may not be too happy about that. If you don't have access to your php.ini, you can set these variables inside wp-config.php. Somewhere before the require_once(ABSPATH . 'wp-settings.php');, maybe in the debug area (up to you), add these two lines: @ini_set('pcre.backtrack_limit', 10000000); @ini_set('pcre.recursion_limit', 20000000);
{ "pile_set_name": "StackExchange" }
Q: How/where can I find out what the frost-line is for my area? Aptos, CA, United States What service or documentation resource can I use to determine what the frost-line is for my area? I'd be inclined to ask the county building/planning office but I suspect that they'll want to charge for answering a seemingly simple (and hopefully well documented) question. A: In general you can use these guidelines. These are very good guidelines that are widely recognized. However if getting inspected I would just ask your building department for their code requirements. **NOTE***** This is how deep your footings would be in undisturbed soil. So for example if there was a regrading of the land - as often the case in new builds - you would have to go this deep past the disturbed soil or consult an engineer that would sign off on something else. So if they regraded your land to 3 feet and you lived in Arkansas you would need to go to 54 inches or gets clearance from an engineer to put the footings shallower. A: This map shows the frost line depth for each state.
{ "pile_set_name": "StackExchange" }
Q: How to reuse properties I have many different buttons in my app, yet most of them have the same properties assigned to them: login = [[UIButton alloc]initWithFrame:CGRectMake(8, CGRectGetMaxY(password.frame) + 16, loginView.frame.size.width - 16, 40)]; [login setTitle:@"Login" forState:UIControlStateNormal]; [login.titleLabel setFont:[UIFont fontWithName:@"Avenir Next" size:18]]; [login setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [login setTitleColor:[UIColor colorWithWhite:0.7 alpha:1] forState:UIControlStateHighlighted]; [login setTitleColor:[UIColor colorWithWhite:0.5 alpha:1] forState:UIControlStateDisabled]; Is there any way to create a class or something of a button that already has these default properties assigned? So I could simply go something like: CustomButtom *btn = [CustomButton alloc]init]; Then the btn will have all of the above properties assigned? Thanks. A: You can do this by creating a CustomButton class Xcode -> New File -> Cocoa Touch Class -> Next -> Name Your Button-> Select Subclass of UIButton CustomButton.h file #import <UIKit/UIKit.h> @interface CustomButton : UIButton @end CustomButton.m file #import "CustomButton.h" @implementation CustomButton // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { // Drawing code //login = [[UIButton alloc]initWithFrame:CGRectMake(8, CGRectGetMaxY(password.frame) + 16, loginView.frame.size.width - 16, 40)]; [self setTitle:@"Login" forState:UIControlStateNormal]; [self.titleLabel setFont:[UIFont fontWithName:@"Avenir Next" size:18]]; [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [self setTitleColor:[UIColor colorWithWhite:0.7 alpha:1] forState:UIControlStateHighlighted]; [self setTitleColor:[UIColor colorWithWhite:0.5 alpha:1] forState:UIControlStateDisabled]; } @end Now, Call you button CustomButton *customButton = [[CustomButton alloc]initWithFrame:CGRectMake(8, CGRectGetMaxY(password.frame) + 16, loginView.frame.size.width - 16, 40)]; [customButton addTarget:self action:@selector(loginButtonPressed:) forControlEvents:UIControlEventTouchDown]; [YourView addSubview:customButton];
{ "pile_set_name": "StackExchange" }
Q: Implementation of ll(k) to ll(1) convertor ! is there any implementation of ll(k) to ll(1) convertor ? A: IIRC; in general, no because some languages have ll(k) grammars but no ll(1) grammars. So unless I'm mistaken, not all ll(k) can be converted ll(1). However, that says nothing about the possibility of such a tool that will work the cases where it can be done. the rule for left factoring is: A := A B | A C | D | E ; turns into: A := (D | E) (B | C)* or if you don't allow () groups and *: A := D A' E A' A' := B A' | C A' | nul ; The trick becomes how to handle the translation of the action rules; if your language supports it, lambdas can be kinda handy there.
{ "pile_set_name": "StackExchange" }
Q: In which file to add the cache_clear_all function In my situation I would like a certain block on my page with real time information to not be cached for anonymous users. Literature listed below: https://www.drupal.org/node/42055 https://www.lullabot.com/blog/article/beginners-guide-caching-data-drupal-7 suggests using the cache_clear_all('modulename', 'cache') I added this on my module inside the hook_block_view() function. This does not work though. Any directions on where I can use this function. Here is the function information: Clearing specific entries in cache tables The Drupal cache API can be used to clear specific items. Caching back ends can be switched (to memcache, to flat files, etc.) without having to rewrite any code. cache_clear_all('content:' . $MYNID, 'cache_content', TRUE); The example above clears all items from cache that start with 'content:$MYNID*'. To ONLY remove one specific row, drop the $wildcard parameter (the "TRUE" statement in the function call) and change the format of the first parameter to omit the asterisk, which functions as a wildcard. cache_clear_all('content:' . $MYNID . ':' . $MYNID, 'cache_content'); A: You can set the block's caching in hook_block_info, like so: function MODULE_block_info() { $blocks = array(); $blocks["BLOCK_NAME"] = array( "info" => "BLOCK TITLE", "cache" => DRUPAL_NO_CACHE, ); return $blocks; }
{ "pile_set_name": "StackExchange" }
Q: Integration involving irrational exponent Question: If: $$I = \int_0^1\frac{dx}{1+x^{\pi/2}}$$ then: a) $\ln2 < I < \frac{\pi}{4}$ b) $I < \ln2$ c) $I > \frac{\pi}{4}$ d) None of these I have no idea how to approach this question. How am I supposed to integrate with the irrational exponent of $x$? A: Recall that $3 < \pi < 4$ so that $1.5 < \pi/2 < 2$. (Or directly recall that $\pi/2 = 1.57\ldots$ if this is at your fingertips!) Well, one technique now is to round down to the integer below, and round up to the integer above. That is, consider your definite integral where $\pi/2$ is replaced with $1$ and then with $2$. In each case, compute the result exactly. How do these results compare to -- i.e., bound! -- the initial integral?
{ "pile_set_name": "StackExchange" }
Q: SQL - Join a table and all possibles results Let's say I have the following tables SELECT C.Id, C.Color FROM Color AS C Id Color ------------------- 1 Strong Red 2 Light Red 3 Strong Blue 4 Light Blue SELECT L.Id, L.Place FROM Location AS L Id Place --------------- 1 Usa 2 Japan SELECT V.Id, V.PriceForADay, V.PriceForAWeek, V.ColorId, V.LocationId FROM Vehicules AS V Id PriceForADay PriceForAWeek ColorId LocationId ---------------------------------------------------- 1 10 15 1 1 2 15 20 2 1 3 20 25 1 2 The result I wish to get is : SELECT C.Id, C.Color, V.PriceForADay, V.PriceForAWeek, V.ColorId, V.LocationId/L.LocationId WHERE V.LocationId = 1 Id Color PriceForADAy PriceForAWeek ColorId LocationId ------------------------------------------------------------------ 1 Strong Red 10 20 1 1 2 Light Red 15 25 2 1 3 Strong Blue NULL NULL NULL 1 4 Light Blue NULL NULL NULL 1 How can I get this desired result? A simple left join + where isn't working. Thank you A: According to your result the Strong Blue and Light Blue are in Location 1. However the dataset provided do not have those color in location 1. Also for c.Id(ColorId) 2,3 in result the corresponding ColorId is null in result, which I am guessing is wrong. So the following query is just based on guessed dataset:- DECLARE @Color TABLE (Id INT IDENTITY (1,1) PRIMARY KEY, Color VARCHAR(30)) INSERT INTO @Color (Color) VALUES('Strong Red'), ('Light Red'),('Strong Blue'),('Light Blue') DECLARE @Location TABLE (Id INT IDENTITY (1,1) PRIMARY KEY, Place VARCHAR(30)) INSERT INTO @Location (Place) VALUES('USA'), ('Japan') DECLARE @Vehicules TABLE (Id INT IDENTITY (1,1) PRIMARY KEY, PriceForADay INT, PriceForAWeek INT, ColorId INT, LocationId INT) INSERT INTO @Vehicules(PriceForADay, PriceForAWeek, ColorId, LocationId) VALUES(10,15,1,1),(15,20,2,1),(20,25,1,2) ,(NULL,NULL,3,1),(NULL,NULL,4,1) --SELECT * FROM @Color --SELECT * FROM @Location --SELECT * FROM @Vehicules SELECT C.Id, C.Color, V.PriceForADay, V.PriceForAWeek, V.ColorId ,L.Id AS LocationID FROM @Color C LEFT JOIN @Vehicules V ON C.Id = V.ColorId LEFT JOIN @Location L ON V.LocationId = L.Id WHERE V.LocationId = 1
{ "pile_set_name": "StackExchange" }
Q: Which among phenol and 1,2-dihydroxybenzene has the higher boiling point? My attempt Based on symmetry: I think that looking for symmetry phenol has a higher boiling point than 1,2-dihydroxybenzene because the two -OH groups projecting out from the benzene ring of 1,2-dihydroxybenzene will not allow close packing of them which results in a lower boiling point. Based on hydrogen bonding: In this sense phenol would have a lower boiling point because 1,2-dihydroxybenzene would have more inter-molecular hydrogen bonding than phenol. How do I know which factor wins? A: Your structures (grabbed from Wikimedia Commons) Phenol: Catechol (1,2-dihydroxybenzene) The three main influences on boiling point are: Shape - molecules with a more spherical shape have lower boiling points than molecules that are more cylindrical, all else as equal as possible. Spheres have the lowest surface area to volume ratio of any of the solids. This is where symmetry comes in. More symmetric molecules are more spherical. The shape/symmetry argument does not work here since the two compounds are not isomers. The issue of close packing is relevant to the melting points of solids, since in a solid, most particles do not have translational motion - they are locked in a crystal lattice. In a liquid, such random translational motion is common. In the liquid state, molecules of most compounds are so disorderly arranged that it does not matter how well they pack as a solid. In your case, both molecules are rather like flat disks with a little bit of polarness sticking off one side. Their shapes are not so different as far as surface area to volume goes. Boiling point will be dominated by mass and polarity. Molecular mass - bigger molecules require more energy to vaporize because they have more mass, and $KE=\frac{1}{2}mv^2$, all else as equal as possible. Mass difference applies in your case because the two molecules are similar enough in shape and polarity, except one has an extra oxygen in its formula. Polarity - polarity controls the types and number of intermolecular forces, including hydrogen bonding. The more and stronger intermolecular forces between two molecules, the higher the boiling point, all else as equal as possible. Since catechol has two hydroxy groups and phenol has one, you have your strong argument for increased intermolecular forces. The other easy thing to do is use the internet to look up the boiling points, and then explain the difference using the three factors. Once you know what the boiling points are, it is easy to choose the structural features that support the difference. Phenol - $181.7 \ ^\circ\text{C}$ Catechol - $245.5\ ^\circ\text{C}$
{ "pile_set_name": "StackExchange" }
Q: Derivation of equation for self information I am trying to understand how the formula I(x) = -log(p(x)) for self information was derived. From what I have read, 2 constraints were imposed on the properties that we would like self-information to satisfy. These constraints are listed below: I(x) < I(y) if p(x) > p(y) I(x and y) = I(x) + I(y) if P(x and y) = p(x).p(y) Following this we somehow find out that I(x) = -log(p(x)) satisfies the above requirements. My exact questions are: Why did we define the requirements for self-information as above? How did we arrive at I(x) = -log(p(x))? How do we know that I(x) = log(p(x)) uniquely satisfies the above requirements? Reference: http://people.seas.harvard.edu/~jones/cscie129/nu_lectures/lecture2/info%20theory/Info_Theory_1.html#def A: Why did we define the requirements for self-information as above? Just because they seem reasonable, they fit with the concept we are trying to formalize. The first one says that an event with low probability give us high information. The second one says that the information a pair of two independent events is the sum of the individual informations. Let's state our "axioms" Information of the event should depend only on its probability: $I(X)=g(p(X))$ $g()$ should be non-negative, continuous and decreasing: lower probability means higher information Specifically $g(0)=+\infty$ and $g(1)=0$ : very improbable event has very high information; (almost) sure event has (almost) zero information. If events $X,Y$ are independent, then $I(X,Y)=I(X)+I(Y)$ It's easy to see that $g(p)= - \log_b (p)$ (arbitrary base) satisfies those requirements. To prove uniqueness is a little more difficult. Sketch: Suppose we have $n$ events with probability $p$, then the above implies (by induction) $g(p^n)=n g(p)$. By considering that $g(p)=g([p^{1/m}]^m)=m g(p^{1/m})$ we deduce that $g(p^a)=a \, g(a)$ holds also for any rational $a$ - and, by continuity for any real $a$. This leads to the unique (up to the base choice) solution $g(p)= - \log_b (p)$
{ "pile_set_name": "StackExchange" }
Q: jQuery UI select outer container and not inner container for drop target I am trying to select only the outer container for the drop target with jQuery UI. I am trying to drop in media-content but not in media-list-items. The reason is that media-list-items is not the full width of it's parent and I only want to drop to the right side which is a different background color the full height. HTML: <div class="media-content clearfix ui-droppable on" style=""> <form method="post" class="form-horizontal" action="./"> <fieldset> <div class="media-list-items clearfix"> <ul data-gallery_id="18" class="media-list ui-sortable" style=""> <li id="media_17"></li> <li id="media_15"></li> </ul> </div> </fieldset> </form> </div> JS: var $trash = $('.media-content:not(.media-list-items), .media-content'); $trash.droppable({ accept: '.media-list > li', drop: function(event, ui) { console.log('trashed'); } }); A: I'm not sure you can achieve what you want without adding another element as your "trash" droppable. With some neat css you can make it look pretty much the same :) html <div class="media-content"> <form method="post" class="form-horizontal" action="./"> <fieldset> <div class="trash"></div> <!-- added a trash element --> <div class="media-list-items"> <ul class="media-list"> <li id="media_25"></li> <li id="media_26"></li> <li id="media_27"></li> </ul> </div> </fieldset> </form> </div> css .media-content { position: relative; /* makes it contain absolutely positioned descendants */ } .media-content .trash { position: absolute; top: 0; bottom: 0; /* stretches to full height of .media-content */ right: 0; width: 100px; background:#f5f5f5; } js $('.media-content .trash').droppable({ drop: function(event, ui) { console.log('trashed'); } }); Demo at: http://jsfiddle.net/KazeG/6/
{ "pile_set_name": "StackExchange" }
Q: A " triple-sum-free " sequence? Consider the strictly increasing integer sequence $f(n)$ defined as : $$f(1) = 1$$ $ M $ is in the list If and only if $M$ is not of the form $ f(a) + f(b) + f(c) $ for Some integers $a,b,c > 0$. So the sequence starts as $$1,2,7,8,...$$ This resembles the A-sequence. http://mathworld.wolfram.com/A-Sequence.html What is known about $f(n) $ ? In particular : How fast does $f(n)$ grow ? A: The sequence continues $$1,2,7,8,13,14,19,20,...,6n+1,6n+2,...$$ The integers in the sequence are all of the form either $6n+1$ or $6n+2$. When these are added together in threes the sums that can be made are restricted to the forms $6n+3,6n+4,6n+5$ and $6n$. Since all such positive integers can be made, none of these appear in the sequence. Conversely, integers of the form $6n+1$ and $6n+2$ can never be the result of a sum. Hence the sequence contains all positive integers of the form $6n+1$ and $6n+2$ and no others. Therefore, the function grows linearly.
{ "pile_set_name": "StackExchange" }
Q: Count of Coprimes for each number I recently came across this question in a hiring challenge : Given an interval [L, R] (1 <= L,R <= 10^5), we need to tell number of coprimes of K in interval [L, R] for each K in [L, R]. e.g. L = 3, R = 7 for K = 3, number of coprimes in [3, 7] = 3 (4, 5, 7) for K = 4, number of coprimes in [3, 7] = 3 (3, 5, 7) for K = 5, number of coprimes in [3, 7] = 4 (3, 4, 6, 7) ... By my approach, I am finding prime numbers upto R and then for each K, by its prime factors, counting number of coprimes, but I need better and efficient approach than this. Thanks in advance. A: One approach would be the following. For every number K perform the following steps: find the prime factors of K (let us denote this set as D). use inclusion-exclusion principle to count the numbers in the [L, R] interval which are multiples of at least one number in D. This number will represent the count of the numbers which are NOT co-prime with K. you can see more details about this inclusion-exclusion approach in this answer (of mine). that question involved arbitrary sets D (not necessarily comprising of prime numbers) -- in our case D contains prime numbers, thus the lowest common multiple (lcm) call from that answer can be computed more directly here as the product of the numbers in the current subset. finally, to find the number of co-primes with K, subtract the previously found number from the total number of values in the [L, R] interval. Remark: in step 2 we can similarly use the inclusion-exclusion principle to directly count the numbers which are co-prime with K (however, it feels more natural to me to count the multiples of numbers in set D). This would not require step 3 anymore.
{ "pile_set_name": "StackExchange" }
Q: scalate templates won`t work couple days ago I've created spring webapp with scalate template endine. Everything worked great but from yesterday I can't get it running. This is what I get org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.VerifyError: (class: org/fusesource/scalate/spring/view/ScalateUrlView, method: renderMergedTemplateModel signature: (Ljava/util/Map;Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V) Incompatible argument to function org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:839) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574) javax.servlet.http.HttpServlet.service(HttpServlet.java:617) javax.servlet.http.HttpServlet.service(HttpServlet.java:717) root cause java.lang.VerifyError: (class: org/fusesource/scalate/spring/view/ScalateUrlView, method: renderMergedTemplateModel signature: (Ljava/util/Map;Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V) Incompatible argument to function org.fusesource.scalate.spring.view.ScalateViewResolver.buildView(ScalateViewResolver.scala:41) org.springframework.web.servlet.view.UrlBasedViewResolver.loadView(UrlBasedViewResolver.java:419) org.springframework.web.servlet.view.AbstractCachingViewResolver.createView(AbstractCachingViewResolver.java:158) org.springframework.web.servlet.view.UrlBasedViewResolver.createView(UrlBasedViewResolver.java:384) org.springframework.web.servlet.view.AbstractCachingViewResolver.resolveViewName(AbstractCachingViewResolver.java:77) org.springframework.web.servlet.DispatcherServlet.resolveViewName(DispatcherServlet.java:1078) org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1027) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574) javax.servlet.http.HttpServlet.service(HttpServlet.java:617) javax.servlet.http.HttpServlet.service(HttpServlet.java:717) When i'll switch back in my servlet-context.xml to jsp it will run but on scalate i can't this is my servlet-context.xml <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- Enables the Spring MVC @Controller programming model --> <annotation-driven /> <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> <resources mapping="/resources/**" location="/resources/" /> <beans:bean class="org.fusesource.scalate.spring.view.ScalateViewResolver"> <beans:property name="prefix" value="/WEB-INF/scalate/" /> <beans:property name="suffix" value=".ssp" /> </beans:bean> <context:component-scan base-package="org.fixus.springer" /> please help A: I've solved the problem. I`ve deleteed from my pom.xml scalate-core and it fixed the problem
{ "pile_set_name": "StackExchange" }
Q: Can we build a geometry in which $\pi = 42$? More precisely, can we build a norm $N$ on $\mathbb{R}^2$, such that the ratio circumference / diameter (computed with norm $N$) of a standard circle is $42$? (By standard circle, I mean a circle defined with the Euclidean norm, i.e. $x^2+y^2 = r^2$, and not a circle defined with the norm $N$). Thus, this question is different to this one and this one. A: It's hopeless to get anything greater than $\pi$ with your definition: Let $N$ be a norm on $\mathbb{R}^2$. By the positive homogeneity of the norm, it's enough to address only the case of the Euclidean circle $C$ centered at $(0,0)$ of radius $1$. On the one hand, the $N$-perimeter of $C$ is: $$P_N=\int_0^{2\pi}N(-\sin t,\cos t)\,\mathrm{d}t=\int_0^{2\pi}N(\cos t,\sin t)\,\mathrm{d}t.$$ For the last equality we only used the $2\pi$-periodicity of $t\mapsto N(\cos t,\sin t)$. On the other hand, the $N$-diameter of $C$ is: $$d_N=2\max_{t\in[0,2\pi]}N(\cos t,\sin t).$$ To see this: the definition of the diameter is: $$d_N=\max_{u,v\in D}N(u-v),$$ where $D$ denotes the set $$D=\bigl\{(x,y)\in\mathbb{R}^2\bigm\vert x^2+y^2\leq1\bigr\}.$$ Note that it's a maximum since $D$ is closed and bounded with respect to the $\lVert\cdot\rVert_2$ (hence compact) and the norm $N$ is continuous with respect to the topology induced by $\lVert\cdot\rVert_2$ in virtue of the equivalence of all the norms on $\mathbb{R}^2$ (since it's a finite-dimensional vector space). Now, if the max defining $d_N$ is attained for $u,v\in D$ such that $u\neq-v$ (and of course $u\neq v$) then $\lVert u-v\rVert_2<2$ hence taking $u'=(u-v)/\lVert u-v\rVert_2$ and $v'=(v-u)/\lVert u-v\rVert_2$ yields $u',v'\in D$ and $$N(u'-v')=N\bigl(2(u-v)/\lVert u-v\rVert_2\bigr)=N(u-v)\frac2{\lVert u-v\rVert_2}>N(u-v).$$ Hence the maximum for $d_N$ is attained for opposite vectors. Hence $$d_N=2\max_{u\in D}N(u).$$ By a similar argument, it is easy to show that the max is attained for a vector $u$ on $C=\partial D$, hence the result. Now we clearly have $$P_N\leq\pi d_N,$$ hence $$\pi_N=\frac{P_N}{d_N}\leq\pi.$$ The mistake in Yves Daoust's answer is in point 2 when he says by symmetry we can assume $x=y$. This is wrong for $p>2$: the vectors on $C$ that lie on the line $x=y$ will have a minimal norm, so the diameter is not attained there. It's attained on the axes, so that $r_p=1$ when $p\geq2$.
{ "pile_set_name": "StackExchange" }
Q: About Abi Encoder V2 I came across the following code and found the term "pragma experimental ABIEncoderV2". Can anybody be specific in telling what this actually means? //pragma solidity ^0.5.2; pragma experimental ABIEncoderV2; contract test { struct document{ string ipfsHash; string documentName; bytes32 accessKey; } struct grantAccess{ address owner; address single; } This is a part of the code I found over the web. A: The standard ABI coder does not allow arrays of dynamic types, structs or nested variables between the Solidity contract and the dApp. The ABI v2 coder; which allows structs, nested and dynamic variables to be passed into functions, returned from functions and emitted by events. Note: Do not use experimental features on live deployments.
{ "pile_set_name": "StackExchange" }
Q: How to group android notifications like whatsapp? I don´t know how to group two or more notifications into only one and show a message like "You have two new messages". A: Steps to be taken care from the below code. NotificationCompat.Builder:contains the UI specification and action information NotificationCompat.Builder.build() :used to create notification (Which returns Notification object) Notification.InboxStyle: used to group the notifications belongs to same ID NotificationManager.notify():to issue the notification. Use the below code to create notification and group it. Include the function in a button click. private final int NOTIFICATION_ID = 237; private static int value = 0; Notification.InboxStyle inboxStyle = new Notification.InboxStyle(); Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.push_notify_icon); public void buttonClicked(View v) { value ++; if(v.getId() == R.id.btnCreateNotify){ NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Notification.Builder builder = new Notification.Builder(this); builder.setContentTitle("Lanes"); builder.setContentText("Notification from Lanes"+value); builder.setSmallIcon(R.drawable.ic_launcher); builder.setLargeIcon(bitmap); builder.setAutoCancel(true); inboxStyle.setBigContentTitle("Enter Content Text"); inboxStyle.addLine("hi events "+value); builder.setStyle(inboxStyle); nManager.notify("App Name",NOTIFICATION_ID,builder.build()); } } For separate notifications assign different NOTIFICATION_IDs..
{ "pile_set_name": "StackExchange" }
Q: First instance of the flying saucer as a space craft? A common idea of a spaceship, especially an alien spaceship, is the classic flying saucer, like the one below: What is the first instance of a flying saucer as a space craft in science fiction? Bonus question: if the first instance is not a film or television series, then what is the first instance of a flying saucer as a space craft in television or film? A: If you look for a first reference in literature, as opposed to fiction, then the oldest reference must surely be the Vimana. Described as circular flying machines with a central dome and windows, travelling with the speed of the wind while emitting a melodious sound. The references date back some 6,000 years. The Vimana are the Chariots of the Gods. The sun itself is said to be a Vimana, they are capable of travel beyond the Earth. You will easily find many references to them around the web by the UFO hunters who consider any reference to ancient flight to be evidence of aliens. A: This article claims that the cover of the November 1929 issue of Science Wonder Stories by artist Frank R. Paul is "the first illustration of a flying saucer, almost two decades before the first sightings by Kenneth Arnold" (as described here, Arnold's 1947 claim initiated a rash of flying saucer sightings and caused 'flying saucers' to enter the public vocabulary): The bottom of this page also quotes a physicist and skeptic named Milton Rothman identifying this cover as the first inspiration for later flying saucer sightings. You can see some galleries of Frank R. Paul cover illustrations here, here and here--you can see he liked to pick unusual shapes for his spaceships, including some later disc-shaped crafts such as this one, this one, this one, and this one. A: Perhaps the earliest science-fictional flying saucers were in the 1887 novel Bellona's Bridegroom: A Romance (aka Bellona's Husband: A Romance) by "Hudor Genone", pseudonym of William James Roe. At any rate, that's the earliest of four stories listed under "flying saucers" in the Motif and Theme Index of Everett F. Bleiler's Science-Fiction: The Early Years. Here is part of Bleiler's review: A fanciful ideal society. * The narrator is Archibald Holt, a rather stupid middle-aged man who invests money in Professor Ratzinez Garrett's hydrogenium, a metallic form of hydrogen that is so light as to amount to antigravity. Garrett builds a flying disk using hydrogenium as a lifting agent, and Holt, Garrett and a third character (Trip) set out for Mars. * As they pass Phobos and Deimos they see that they are abandoned flying saucers much like their own. They later learn that the space craft came from Jupiter or Saturn, and that similar saucers have visited earth, but have flamed or crashed on entering the atmosphere. * The terrestrials land on Mars, which is like the eastern United States, and find a completely human race that speaks English. At first Garrett postulates that the similarity is due to colonists from earth (and is upset at the possibility that his patent may be invalid), but later decides that the similarity is the result of parallel evolution. The first flying saucer movie was The Flying Saucer, released January 5, 1950. Wikipedia says: The Flying Saucer is the first feature film to deal with the (then) new and hot topic of flying saucers. Flying saucers or alien craft shaped like flying disks or saucers were first identified and given the popular name in 1947 when on June 24, 1947, private pilot Kenneth Arnold reported nine silvery, crescent-shaped objects flying in tight formation. A newspaper reporter coined a snappy tagline: "flying saucers" which captured the public's imagination. All right, so that's the first flying saucer movie. What about television? I wonder if Captain Video had any flying saucers before 1950?
{ "pile_set_name": "StackExchange" }
Q: Checking permissions in Swift 2.0 No matter where I add code to check permissions for things like camera/mic/photos, the popup confirmation always kills my app or sends me back a few view controllers. An example is as follows. I have few view controllers in (part way through a registration process) when I have a page that deals with the permissions. Users tap a button to deal with the camera permission which uses the following code. if AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) != AVAuthorizationStatus.Authorized { AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (granted :Bool) -> Void in if granted == true { // do something } else { // determine whether not determined, denied etc and do something else } }); } However as soon as the iOS confirmation pops up, it throws the app back 2 view controllers. In other cases (e.g. on a viewDidLoad) permission requests kill the app as soon as the choice is made. Any ideas what am I missing in my setup or how to prevent this behaviour? Thanks. A: I think you misunderstood my comment, what I did meant was if AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) != AVAuthorizationStatus.Authorized { // here you are checking if it's not authorized i..e it's denied, NotDetermined or Restricted .... } else if if AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) == AVAuthorizationStatus.Authorized // do the something in case it's autorized I'm listing keys here - <key>NSPhotoLibraryUsageDescription</key> <string>This app requires access to the photo library.</string> <key>NSCameraUsageDescription</key> <string>This app requires access to the camera.</string>
{ "pile_set_name": "StackExchange" }
Q: Silverlight 4 Get Current User I have seen this question posed regarding Silverlight 2 but I have not seen any questions about Silverlight 4. Is there a way to get the current user running an application in Silverlight 4.0? I thought I remember seeing that as one of the features of 4.0 but I cannot find it. (Maybe it was just wishful thinking on my part.) I would imagine it would have to come from the OS running the browser or the browser itself. (The application is not being installed locally, it's running in the browser) I have a solution where I call web service method that just does the following to get the users name. However, I would like to not have to call a web service HttpContext.Current.User.Identity.Name.ToUpper(); Thanks in advance! A: You might find it easier just to pass the name into the silverlight app as a parameter
{ "pile_set_name": "StackExchange" }
Q: Opening .dat (tab delimited file) in Excel, save as .xls I am trying to open a .dat file in Excel, which is tab delimited, and then have it save out as a .xls file. So far, I can read in the file and save it as the .xls file but for some reason, all the values are in the first column and it does not tab delimit them. (If I open up the file in Excel without my program, it tab-delimits perfectly) These are the two lines of code that I am using to open and resave the file. xlWorkBook = xlApp.Workbooks.Open(f, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); xlWorkBook.SaveAs(filename + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); A: The fix for this question: xlWorkBook = xlApp.Workbooks.Open(f, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); xlWorkBook.SaveAs(filename + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); In the xlApp.Worksbooks.Open() method, the fourth arg is "Format" which if you use the value '1', it will assume that the file is tab delimited and open it accordingly.
{ "pile_set_name": "StackExchange" }
Q: Facebook Page Tab App - like page before accessing app I have a Facebook Page Tab App up and running and has been running for about a year. I need to collect more likes for our business page as opposed to the app page. Is there a way to ask new users of the app to like a page before they have access to the app? Many thanks, A: what you are looking for is called "Fan gate" - google it and you will find multiple example. In 2 words - when page is loaded, you need to check if user is logged in, and if user liked the app - and then you either redirect them to the "real" app page, or make certain div visible, or whatever you want. But if that's not the case - then you keep Please like us" div displayed, and it covers all your content. See this page for example: https://www.facebook.com/redbull/app_113185218710496 and here is a link to similar SO question: How to create a fan / like gate on Facebook?
{ "pile_set_name": "StackExchange" }
Q: .Net AES Padding Problem im currently having a problem with the padding when decrypting a utf8 encoded string. string length is not a multiple of 16, i use PKCS7 paddingmode of course i do use the cs.FlushFinalBlock() statement. whats happing is, after decrypting, the stream wont hold the last block. but when is use no paddingmode only while decrypting, the last block is there(with paddingbytes) i have no clue whats wrong ;) heres a bit code(vb.net im sry :D) encryption Dim rawPlaintext As Byte() = utf8.GetBytes(text) aes.Padding = PaddingMode.PKCS7 Using ms As New MemoryStream() Using cs As New CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write) cs.Write(rawPlaintext, 0, rawPlaintext.Length) cs.FlushFinalBlock() ms.Position = 0 End Using Return ms End Using decryption aes.Padding = PaddingMode.PKCS7 Using ms As New MemoryStream() Using cs As New CryptoStream(ms, aes.CreateDecryptor(key, iv), CryptoStreamMode.Write) ciphertext.CopyTo(cs) ciphertext.Close() ms.Position = 0 End Using Return ms End Using hope u guys can help ;) thanks A: I can see two problems with your code: The first is probably minor: I don’t think it is a good practice to pass around a disposed MemoryStream – do not return the MemoryStream, return only the contained array (use ms.ToArray()). The second is worse: you do not need to call cs.FlushFinalBlock() explicitly, it is called automatically on Dispose (when leaving the Using block of the CryptoStream). However, in the second case you do not call it, and you reset position of the output stream while the decrypting CryptoStream has not finished yet. It means that only after changing the stream position, the CryptoStream gets to flushing the final block. You can work around that by adding cs.FlushFinalBlock() before ms.Position = 0 in the decryption code. But, IMHO just remove the stream seek completely (possibly with FlushFinalBlock in the encryption code), and you should be fine, too.
{ "pile_set_name": "StackExchange" }
Q: Populate table by looping through array I got a table where first td of each tr, starting with 2nd tr, has to be populated from an array with items inserted in the order they are in the array. Here is an example of my JavaScript: terms = [ "term 1", "term 2", "term 3", "term 4", ]; var terms_length = terms.length; var r = 1; r++; for (var t=0; t < terms_length; t++) { $("#termstable tr:nth-child(" + r + ") td:nth-child(1)").html(terms[t]); } As of right now, it's populating only 2nd tr's td with last item of the array. A: put your r into the loop terms = [ "term 1", "term 2", "term 3", "term 4", ]; var terms_length = terms.length; var r = 1; for (var t=0; t < terms_length; t++) { $("#termstable tr:nth-child(" + r + ") td:nth-child(1)").html(terms[t]); r++; }
{ "pile_set_name": "StackExchange" }
Q: Setting "Show editor for creation date time" programmatically I'm trying to alter the common settings for a content type to show editor for creation date time. I know this can be done via admin, but I would also like to do this through code, for deployment in the future. The problem is, I don't know what is the right name for the common part setting and the field. So far I have this: .WithPart("CommonPart", builder3 => builder3 .WithSetting("CommonSettings.ShowCreatedUtcEditor", "true"))' But it could be wrong. I see a lot online that show commonTypePartSettings.ShowCreatedUtcEditor but these were from way back in 2011. Not sure if that still applies. Anybody know what it is exactly? Or some way to find it? Any piece of advise or information would be highly appreciated. Thanks! A: The correct setting name for date editor is now "DateEditorSettings.ShowDateEditor". And corresponding setting for owner editor is "OwnerEditorSettings.ShowOwnerEditor".
{ "pile_set_name": "StackExchange" }
Q: Is there such a thing as implicit integration? A problem I'm working on asks me at a certain point to integrate the following: $$x=2\left(\sin\left(y\right)\right)^2.$$ I've never integrated anything in this form. I can't isolate for $y$ either. Is there some sort of implicit integration technique I should be aware of, to get the indefinite integral of this? Thanks to the below comments, I was able to isolate y and get $$\sin^{-1}\left(\sqrt{\left(\frac{x}{2}\right)}\right)=y$$ ....which still looks insanely messy to integrate. I imagine I can use a u-substitution or something similar to solve this? A: The question is from a very long time ago, but I can still attempt to provide an answer. Implicit integration is kind of like the topic in differential equations called exact differential equations. It’s pretty much tracing backwards from applying multivariable chain rule on a function of multiple variables. I’d say it’s the closest thing I’ve seen to a concept of “implicit integration”.
{ "pile_set_name": "StackExchange" }
Q: Django how to debug a frozen save operation on a queryset object I have the following code in a Django project (within the create method of a Django Rest Framework serializer) def create(self, validated_data): <...> log.info("\n\n\n") log.info(f"django model: {self.Meta.model}") log.info("CREATING CASE NOW .....") case = self.Meta.model(**kwargs) log.info(f"Case to be saved: {case}") case.save() log.info(f"Case object Created: {case}") When I'm posting to the endpoint, it's just freezing up completely on .save(). Here's example output: 2020-06-15 02:47:46,008 - serializers - INFO ===> django model: <class 'citator.models.InternalCase'> 2020-06-15 02:47:46,008 - serializers - INFO ===> django model: <class 'citator.models.InternalCase'> 2020-06-15 02:47:46,009 - serializers - INFO ===> CREATING CASE NOW ..... 2020-06-15 02:47:46,009 - serializers - INFO ===> CREATING CASE NOW ..... 2020-06-15 02:47:46,010 - serializers - INFO ===> Case to be saved: seychelles8698 2020-06-15 02:47:46,010 - serializers - INFO ===> Case to be saved: seychelles8698 No error is thrown and the connection isn't broken. How can I debug this? Is there a way to get logging from the save method? A: The error likely unrelated to the use of the Django rest serializers as the code that hangs simple creates a new model and saves it. Now you did not specify how kwargs is defined, but the most likely candidate is that it gets stuck talking to the DB. To debug the code, you should learn how to step in the code. There are a number of options depending on your preferences. Visual studio code Install the debugpy package. Run python3 -m debugpy --listen localhost:12345 --pid <pid_of_django_process> Run the "Python: Remote Attach" command. CLI Before the line case.save() do import pdb; pdb.set_trace() This assumes you are running the Django server interactively and not e.g. through gunicorn. You will get a debug console right before the save line. When the console appears, type 'c' and press enter to continue execution. Then press Ctrl+C when the process appears stuck. Type bt to find out what goes on in the process. Native code If the stack trace points to native code, you could switch over to gdb. To debug this (make sure to exit any Python debugger or restart the process without a debugger). Run gdb -p <pid_of_django> when the process appears stuck. Then type 'bt' and press enter to get a native traceback of what is going on. This should help you identifiy e.g. database clients acting up.
{ "pile_set_name": "StackExchange" }
Q: Spherical law of cosines The spherical law of cosines states that $$\cos c = \cos a \cos b + \cos C \sin a \sin b,$$ where $a,b,c$ are sides of a spherical triangle, and $C$ the angle. Is there a proof for this theorem using matrices (and not vectors)? How do I modify this theorem such that it includes two spheres, say the sun and the moon (for example, with the distance between the two spheres replacing $c$ in the equation)? A: $\newcommand{\Alpha}{A}$In case it helps, consider first the Euclidean situation: We have a disk of radius $R_{0}$ centered at $(X_{0}, Y_{0})$ representing the sun at a specific time, and a disk of radius $r_{0}$ centered at $(x_{0}, y_{0})$ representing the moon at the same time. The distance between their centers is given by the Pythagorean theorem, $$ d = \sqrt{(X_{0} - x_{0})^{2} + (Y_{0} - y_{0})^{2}}. $$ The disks overlap (partial eclipse) if $d < R_{0} + r_{0}$; one disk completely occludes the other (total eclipse) if $d < |R_{0} - r_{0}|$. In the extract, all coordinates refer to the celestial sphere. The sun at 4:30 is represented on the celestial sphere as a disk of (angular) radius $R_{0}$ whose center has right ascention $\Alpha_{0}$ and declination $\Delta_{0}$; the moon at 4:30 is represented on the celestial sphere as a disk of (angular) radius $r_{0}$ whose center has right ascention $\alpha_{0}$ and declination $\delta_{0}$. The question is whether or not the centers of these disks are close enough for a partial or total eclipse. The crucial quantity is the spherical (i.e., angular) distance $\theta$ between the centers, which the author claims is given, at 4:30, by $$ \cos \theta = \sin \Delta_{0} \sin\delta_{0} + \cos\Delta_{0} \cos\delta_{0} \cos a_{0}. \tag{1} $$ Being more familiar with vectors and dot products than with spherical trigonometry, I'd derive (1) as follows: in an earth-centered coordinate system, the Cartesian positions of the sun and moon (on the celestial sphere, assuming unit radius) are, respectively, \begin{align*} (X, Y, Z) &= (\cos\Alpha \cos\Delta, \sin\Alpha \cos\Delta, \sin\Delta), \\ (x, y, z) &= (\cos\alpha \cos\delta, \sin\alpha \cos\delta, \sin\delta). \end{align*} The (angular) distance $\theta$ between the centers satisfies \begin{align*} \cos \theta &= (X, Y, Z) \cdot (x, y, z) \\ &= (\cos\Alpha \cos\alpha + \sin\Alpha \sin\alpha)\cos\Delta \cos\delta + \sin\Delta \sin\delta \\ &= \cos(\Alpha - \alpha)\cos\Delta \cos\delta + \sin\Delta \sin\delta \\ &= \sin\Delta \sin\delta + \cos\Delta \cos\delta \cos a; \end{align*} the third equality is the sum formula for cosine, and the last is simple rearrangement.
{ "pile_set_name": "StackExchange" }
Q: Visual Studio Addon that can warn developers when it detects that certain kind of references have just been added to a project? We've all done it. We create a new class and type away the constructor adding dependencies and what not. Resharper is there to offer a helping hand and add missing references for us. It's only later on that we realise that we auto-imported references to other parts of our project that we shouldn't have. So is there an addon for VS that one can configure (using wildcards etc) to have it issue warnings when/if certain .csproj projects are found to contain references to other .csproj projects that they aren't "allowed" to access (architecturally speaking). Addendum: I am aware that I can achieve this by using pre-build msbuild-logic which parses the .csproj file using regexes and of course this would work. But I just find it kind of ... cumbersome and non-intuitive. A: So is there an addon for VS that one can configure (using wildcards etc) to have it issue warnings when/if certain .csproj projects are found to contain references to other .csproj projects AFAIK there's no such kind of extension that does the checking and warning job for you. The reference to .csproj is actually project references in visual studio. You can right-click project=>Build Dependencies=>Project Dependencies to check if current project depends on other projects in same solution.But this option will check both project references(add reference to xx.csproj in current.csproj) and project dependencies(ProjectDependencies section in .sln). So only use project references in your solution to manage dependencies between projects, then this option can easily check project references for you. If the pre-build msbuild-logic which works need similar changes in every project in the solution, maybe Directory.Build.props can make some help if the changes in the project file have similar format. Fetch the pre-build logic into it and put this file in solution or repos directory, it reduces duplicate content in every project file.
{ "pile_set_name": "StackExchange" }
Q: Symfony Webpack: Could not find the entrypoints file from Webpack A relatively fresh Symfony 4.1.7 project after installing Webpack Encore throws the error An exception has been thrown during the rendering of a template ("Could not find the entrypoints file from Webpack: the file ".../public/build/entrypoints.json" does not exist.") where the template includes {{ encore_entry_link_tags('app') }} when launching http://127.0.0.1:8000/ What have I missed? $ yarn encore dev Running webpack ... DONE Compiled successfully in 1974ms I 3 files written to public\build Done in 3.33s. .../public/build contains app.css app.js manifest.json local Symfony versions: symfony/webpack-encore-bundle v1.0.0 symfony/webpack-encore-pack v1.0.3 webpack.config.js: var Encore = require('@symfony/webpack-encore'); Encore // the project directory where compiled assets will be stored .setOutputPath('public/build/') // the public path used by the web server to access the previous directory .setPublicPath('/build') .cleanupOutputBeforeBuild() .enableSourceMaps(!Encore.isProduction()) // uncomment to create hashed filenames (e.g. app.abc123.css) // .enableVersioning(Encore.isProduction()) // uncomment to define the assets of the project .addEntry('app', './assets/js/app.js') // .addEntry('js/app', './assets/js/app.js') // .addStyleEntry('css/app') // .addStyleEntry('css/app', './assets/css/app.scss') // uncomment if you use Sass/SCSS files // .enableSassLoader() // uncomment for legacy applications that require $/jQuery as a global variable .autoProvidejQuery() ; module.exports = Encore.getWebpackConfig(); A: Update your version constraint in package.json for @symfony/webpack-encore to ^0.21.0 ... "devDependencies": { "@symfony/webpack-encore": "^0.21.0", ... add .enableSingleRuntimeChunk() to your webpack.config.js ... .addEntry('app', './assets/js/app.js') // .addEntry('js/app', './assets/js/app.js') // .addStyleEntry('css/app') // .addStyleEntry('css/app', './assets/css/app.scss') .enableSingleRuntimeChunk() ... Then run yarn upgrade or yarn install PS: If you have symfony/webpack-encore-bundle installed, you can remove symfony/webpack-encore-pack composer remove symfony/webpack-encore-pack
{ "pile_set_name": "StackExchange" }
Q: Accessing Rest API with a Simple Web Token I have written REST api using Asp.Net Web.Api. It is secured using ThinkTecture's Identity Server. I have written a simple console client that allows the user to enter a username and password. The client then authenticates to the Identity Server with these credentials, gets a token on success, passes the token to my rest api, is authenticated by the api and then gets it's data from the api. Now I have written an MVC site that consumes the api. What I'm not sure on is how I query the api if I don't have the username and password to get a token? I obviously don't want the user to login each time I want to call the api. Can I do something similar to setting an auth cookie? A: Yes you need to cache the token in the client and re-use it whenever you make a request on behalf of the client.
{ "pile_set_name": "StackExchange" }
Q: Majorization form for a given set of integers in some interval. Given a set of $n$ positive integers $X=\{x_1,x_2,\ldots,x_n\}$ such that $x_i\in[a,b]$ for all $i$ and some positve integers $a$, $b$, $\sum_{i=1}^n x_i =S$ and $x_i\geq x_{i+1}$ for all $1\leq i\leq n-1$. Is there exist a set of integers $X^*=\{x^*_1,\ldots,x^*_n\}$, which can always majorize other set of integers under the same constraint? $X^*$ majorizes $X$ means that $\sum_{i=1}^jx^*_i \geq \sum_{i=1}^jx_i$ for all $1\leq j< n$, and be denoted as $X^*\succ X$. The problem formulation can be given as the following. Let $${\cal{X}}\triangleq\Bigg\{X=\{x_1,x_2,\ldots,x_n\}\Bigg|x_i\in[a,b], \sum_{i=1}^nx_i=S \mbox{ and } x_i\geq x_{i+1}\Bigg\},$$ where $a,b\in Z_+$. Does it exist an $X^*\in{\cal X}$, such that $X^*\succ X$ for all $X\in{\cal X}$ ? Remark: This problem is inspired by the Left Concave-Right Convex inequality from LCRCF Theorem in Section 3.3. It can be solved when $x_i\in[a,\infty)$, and the solution is $X^*=\{x^*_1=S-(n-1)a, x^*_2=a, x^*_3=a, \ldots, x^*_n=a\}$. However, when $x_i$ is drawn from $[a,b]$, I have no clue to find $X^*$. A: If $b\geq S-(n-1)a$, you take the $x^*$ you mention in your answer. If $b<S-(n-1)a$, put $$ x^*=(\overbrace{b,\ldots,b}^{m\ \text{ times}},r,\underbrace{a,\ldots,a}_{k\ \text{ times}}) $$ where $$ m=\left\lfloor\frac{S-na}{b-a}\right\rfloor,\ \ \ k=\left\lfloor\frac{nb-S}{b-a}\right\rfloor,\ \ \ r=S-mb-ka. $$ This will be the maximum, because it maximizes the size of the number to the left, so any $x$ with entries between $a$ and $b$ and sum $S$ will be majorized by $x^*$.
{ "pile_set_name": "StackExchange" }
Q: Excel 2013 create column w/specific value from another column? I have a spreadsheet with a column "application url" (this is a feed from Apple). Within that column/url is the id number of the product: http://itunes.apple.com/app/pntool/id852499288?uo=5 The above is a standard example of the data in the column "application url". What I'd like to do is create a new column A (moving the existing column "a" to column "b", "b" to "c", etc…) titled "ID" and populate it with just the id number (the number following "id" but preceeding the "?"). So that I end up with: Column A ID 777888999 And, of course, each row's ID would match that with the id found in that row's "application url" column. A: If B will be new column that the url is in, then use the following formula in A, and drag down. =MID(B2, SEARCH("id",B2)+2, SEARCH("~?",B2)-SEARCH("id",B2)-2)
{ "pile_set_name": "StackExchange" }
Q: Math symbol question: Vertical bar for ''evaluated at ...'' How do I insert the line "|" after the equation in LaTeX (see image below)? I'm using LyX so if you can point me to the symbol of that line is also OK. I don't know if this line has a proper name so the title of this question may be very vague. If you could provide me a name, I'll edit this question's title. A: I don't know how you would get this in LyX. However, if you're comfortable with writing things in mathmode by hand, I would write this as T(s) = \frac{1}{H(\hat S)} \bigg\rvert_{\hat S = \epsilon^{1/n} \frac{s}{\omega_P}} The relevant bit is the \bigg\rvert, which you can substitute with \Big\rvert or \Bigg\rvert to get a smaller or larger vertical stroke. If you would like to resize the vertical stroke automatically depending on what occurs to the left of it, I would recommend T(s) = \left. \frac{1}{H(\hat S)} \right\rvert_{\hat S = \epsilon^{1/n} \frac{s}{\omega_P}} where \left. puts an invisible left-bracket-like symbol on the left, whose right-side partner is the vertical stroke given by \right|. These pairs work equally for other braces/brackets. A: You could just type the symbol (|) directly. This won't scale, to get it larger you could use the same technique as Niel de Beaudrap. In the LyX GUI this is done via the Insert Delimiter button on the math toolbar: Set the left delimiter to None, and the right to |. Uncheck Keep matched, and let the Size be set to Variable: In LyX this looks like as below (left). The dotted vertical line indicates an invisible delimiter (as \left. in Niels example). Result in PDF on the right. Edit in response to Marcs answer: To use \rvert I think you have to use ERTs. If you don't have any other math constructs that use amsmath, you may have to make LyX use this package manually: Document --> Settings --> Math options. Uncheck Use AMS math package automatically, and check Use AMS math package. In your equation, add an ERT (Ctrl + L) and type \biggr\rvert. That is, the first backslash may appear automatically, in which case don't type it. \biggr is one of several commands for manually scaling a delimiter, rather than the automatic provided by \left \right. Other sizes are \bigr, \Bigr and \Biggr, with the latter being the largest. For left delimiters, replace r with l. (See section 4.14.1 Delimiter sizes in amsmaths manual.) Should you want to use \left\right, you need to add an ERT with \left. before the fraction (or whatever it is) and have \right\rvert in the one after. A: Do not use | directly. Instead I suggest you use \rvert, which is provided by the amsmath package to address the overloading of the | symbol. See section 4.14.2 of the amsmath documentation.
{ "pile_set_name": "StackExchange" }
Q: Passing a string to $ Trying to get a grip on CoffeeScript and jQuery by doing the Code School CoffeeScript course. One of the excerpts used is $("<li>" + name + "</li>"). I managed to figure out that $ is an alias for jQuery (right?), so I guess this means we're calling the jQuery function with a string (name is a string, surrounded by two literals). So... what does the jQuery function do on its own? Tried looking at api.jquery.com, having trouble figuring it out. Thank you! A: In this instance you are using jQuery to create a DOM element. An <li> with some (text I'm assuming) that is in the variable name If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it has somewhere within the string). If not, the string is interpreted as a selector expression, as explained above. But if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML. Then a jQuery object is created and returned that refers to these elements. The structure for creating DOM elements with jQuery is: $( html, props ) Check out these jQuery Docs to read more about the jQuery selector. html: A string defining a single, standalone, HTML element (e.g. or ). props: A map of attributes, events, and methods to call on the newly-created element. As we can see in your example we only pass html. $("<li>" + name + "</li>")
{ "pile_set_name": "StackExchange" }
Q: Forcing packet loss For testing purposes, to determine how a protocol implementation behaves in the presence of packet loss, I would like to force packet loss on one of my network devices. Specifically, I would like to be able to tune the packet loss anywhere between 0% and 100%. I have a little experience with iptables and it seems to me I should be able to achieve it using that, but I haven't been able to. Achieving 100% packet loss is not a problem though ;). Any ideas on how to do this? A: Look into iptables' statistic module. I guess something like iptables -A FORWARD -m statistic --mode random --probability 0.5 -j DROP should do the trick on a router.
{ "pile_set_name": "StackExchange" }
Q: A question to $\Diamond$ implies the existence of a Suslin tree I'm reading the Proof that $\Diamond$ implies the existence of a Suslin tree in Jech, Set Theory (2003), p.241. The nodes in the constructed tree are countable ordinals, so $T=\omega_1$, and every subtree $T_{\alpha}$ is a initial segment of $\omega_1$. Here is a screenshot of the construction of $T$: Later on, the author states, that it "follwos easily from the construction that for a closed unbounded set of $\alpha$'s, $T_{\alpha}=\alpha$." I can't see why this follows. Thank you for your help! A: Since $T_\alpha$ is an initial segment of $\omega_1$, the function $\alpha\mapsto\sup T_\alpha$ is an increasing function and at limit points $T_\delta=\bigcup_{\alpha<\delta}T_\alpha$. So the function is normal. And every normal function has a closed and unbounded set of fixed points, namely $\alpha$ such that $T_\alpha=\alpha$.
{ "pile_set_name": "StackExchange" }
Q: Split array of dictionaries into sub-arrays Below is a part of my JSON response where 'results' is an array of dictionaries : { "results": [ { "id": 6, "genre_name": "Action", "cover_image": "http://54.254.204.81/images/Action.png" }, { "id": 5, "genre_name": "Adventure", "cover_image": "http://54.254.204.81/images/Adventure.png" }, { "id": 4, "genre_name": "Romance", "cover_image": "http://54.254.204.81/images/Romance.png" }, { "id": 3, "genre_name": "Sci-Fci", "cover_image": "http://54.254.204.81/images/Sci-Fi.png" }, { "id": 1, "genre_name": "Guide", "cover_image": "http://54.254.204.81/images/Adventure_XHLbNfN.png" }, { "id": 2, "genre_name": "Horror", "cover_image": "http://54.254.204.81/images/Phineas-and-Ferb-Christmas-Wallpaper.jpg" }, { "id": 7, "genre_name": "Emotional", "cover_image": "http://54.254.204.81/images/a0fea991287cf41b6b9c4aa16196517f.jpg" }, { "id": 8, "genre_name": "abcd", "cover_image": "http://54.254.204.81/images/logo_text_S0KyzUW.png" } ] } Now I have another JSON response where 'genres' is an array which contains objects which are subset of 'results' array objects with key 'id'. { "genres": [ 3, 1 ] } Now, is it possible for me to split 'results' into two arrays 'results1' and 'results2' like: { "results1": [ { "id": 6, "genre_name": "Action", "cover_image": "http://54.254.204.81/images/Action.png" }, { "id": 5, "genre_name": "Adventure", "cover_image": "http://54.254.204.81/images/Adventure.png" }, { "id": 4, "genre_name": "Romance", "cover_image": "http://54.254.204.81/images/Romance.png" }, { "id": 2, "genre_name": "Horror", "cover_image": "http://54.254.204.81/images/Phineas-and-Ferb-Christmas-Wallpaper.jpg" }, { "id": 7, "genre_name": "Emotional", "cover_image": "http://54.254.204.81/images/a0fea991287cf41b6b9c4aa16196517f.jpg" }, { "id": 8, "genre_name": "abcd", "cover_image": "http://54.254.204.81/images/logo_text_S0KyzUW.png" } ] } and { "results2": [ { "id": 3, "genre_name": "Sci-Fci", "cover_image": "http://54.254.204.81/images/Sci-Fi.png" }, { "id": 1, "genre_name": "Guide", "cover_image": "http://54.254.204.81/images/Adventure_XHLbNfN.png" } ] } A: For that you need to use NSPredicate with IN and NOT like this way. First create resultArray and genresArray from your two JSON responses. NSArray *resultArray = [firstJSONResponse objectForKey:@"results"]; NSArray *genresArray = [secondJSONResponse objectForKey:@"genres"]; Now filter your resultArray using NSPredicate to get your result. For Result1 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT (id IN %@)",genresArray]; NSArray *firstSplitArray = [resultArray filteredArrayUsingPredicate:predicate]; NSLog(@"%@",firstSplitArray); For Result2 predicate = [NSPredicate predicateWithFormat:@"id IN %@",genresArray]; NSArray *secondSplitArray = [resultArray filteredArrayUsingPredicate:predicate]; NSLog(@"%@",secondSplitArray);
{ "pile_set_name": "StackExchange" }
Q: Is the 'sister' question on topic? I suspect we've all seen My sister absolutely refuses to learn math by now - it's lodged at the top of the Stack Exchange hot questions list, it's been tweeted, it's got 27k views and hundreds of votes, etc etc. But what I'm not clear on is whether it's on topic. In the on-topic-ness FAQ, it's not in any of the off-topic groups, BUT also not in any of the on-topic groups. I'm inclined to consider this makes it off topic, but I see it only stayed closed for four hours after it was for that reason closed, suggesting that there is significant disagreement. Personally I could see it perhaps falling under "Understanding mathematical concepts and theorems", but only if it was the learner coming here to ask for help. The question as it stands is a teaching question, and therefore more suited to the (currently still in Area 51) sites Education or (if relevant, which I think it might be) Homeschooling. The question's own tl;dr asks quite explicitly How do you teach..; and indeed not even "how do you teach [mathematical concept]" but rather "how do you teach someone who doesn't want to learn". This isn't about math. Relevant comments and answers would be respectively about the teaching relationship, and pedagogy in general. Bearing in mind that popularity alone is not considered a sufficient reason for a post's existence at a Stack Exchange site, why is this one still here? I did flag to this effect, which was marked helpful, but I want to know if/why this is considered an appropriate question for MSE A: I think it's on topic. The question is about how to teach mathematics to a student lacking motivation. I don't think that this is the same, as you suggest, as how to teach to someone who doesn't want to learn in general. Mathematics admits (and, in my opinion, requires) a different pedagogy than other subjects. This is due, among other things, to the cumulative nature of the material $-$ an issue mentioned explicitly in the question. As such the discussion is specific to mathematics, which makes it on topic. Furthermore, mathematicians can be very opinionated about how math should be taught, so as a place where the general public can interface with advanced students of mathematics, I consider Math StackExchange to be the perfect venue for this type of discussion.
{ "pile_set_name": "StackExchange" }
Q: Assigining values after the Apply operator I am writing a script where I need many variables and for ease of usage I denote them as f[k,l,m,n]. I create a list of 4-tuples with the integers I need and I call these values using f@@{k,l,m,n}. My problem is that I also need to assign values but writing f@@{k,l,m,n}=1 returns an error, declaring that the Tag Apply is protected. Is there any way to overcome this or do I need to assign my values using f[k,l,m,n]=1? A: Since Set have HoldFirst Attribute, f @@ {k, l, m, n} will not be evaluated. You can do Evaluate[f @@ {k, l, m, n}] = 1
{ "pile_set_name": "StackExchange" }
Q: Load raw HTML files in Kohana I'm needing to load a series of auto-generated HTML files (source code docs) that are already self-contained in a directory. How can I get Kohana to load these files? (If I try to use my existing controller/view setup Kohana doesn't recognize the HTML files - index.php for example, in the directory) A: Put the files in the same folder as your other static assets (stylesheets, javascripts, images).
{ "pile_set_name": "StackExchange" }
Q: iPhone - How to customize the UINavigationBar back button with my texture background I am able to customize the back button on my navigation bar, but in order for me to show the left arrow shape, do I need to create my customized image with the left arrow specifically? Or there is a way to use the original back button with the arrow shape, while just apply my background image onto it? Thanks in advance! A: Set yourButton the customized image with the left arrow self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:yourButton] autorelease]; You cannot modify the original BACK button.
{ "pile_set_name": "StackExchange" }
Q: Amazon AWS Simple Email Service: some email addresses NEVER receive emails I have posted this question on the Amazon AWS Forums, but figured I might get a quicker, better answer here. I apologize if you see it twice. My company uses an Amazon AWS SMTP server to send emails via a Java-based web interface. This is just a small part of our application, intended to allow users to invite other users to our application. We have discovered on a very few number of occasions that certain email addresses are not receiving the invitations. Initially we thought it was related to hyphens in the email addresses, but now I've determined that this isn't necessarily the case. I have been troubleshooting this for some time using my own email domains, and I have determined that the following two email addresses NEVER receive any emails sent using the AWS SMTP server (email-smtp.us-east-1.amazonaws.com), but there are no errors reported during the sending process -- the emails just never arrive. The second list shows similar email addresses that always DO receive invitations sent using our system. Note that the addresses on the first list NEVER receive emails, I have tried from all of our deployed instances many, many times. ADDRESSES THAT DO NOT RECEIVE EMAIL: [email protected] [email protected] ADDRESSES THAT DO RECEIVE EMAIL: [email protected] [email protected] [email protected] [email protected] There are very, very few email addresses that end up with this problem. I was somewhat lucky to find two in my own domain that are exhibiting the problem. I have of course verified that this has nothing to do with spam filtering. The application is written in Java using the play framework. Play uses Apache Commons Email library under the hood. You can read more about this here: http://www.playframework.com/documentation/1.1/emails. Here are some of the steps I have taken during my troubleshooting efforts: 1) Try with a different SMTP server (using my personal ISP SMTP -- smtp.gvtc.com) -- ALL addresses DO receive emails when I use this SMTP server. This would seem to isolate the problem as being specific to the AWS SMTP server. 2) Set up my own AWS account and use the SMTP settings for this account (after verifying the addresses in question) -- I have the exact same issues using my own AWS SMTP account settings. This would seem to indicate that the problem is not specific to our company's AWS account. 3) Turn on the play email debug setting (mail.debug=true in the configuration file). A great deal of information is shown in the console for each email sent by the system, but there is absolutely no difference between emails sent to good addresses and those sent to bad addresses. There is no indication whatsoever of any errors. Here is the contents of the log for one of the emails that never arrived. Note that this is using the AWS server I set up for myself. It looks exactly the same when I use our company's AWS SMTP server except that the from email address is different. I have removed the actual email content, since it's in HTML, somewhat confidential, and not relevant to the problem. May 15, 2013 8:44:47 AM play.Logger info DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc] DEBUG SMTP: useEhlo true, useAuth true DEBUG SMTP: useEhlo true, useAuth true DEBUG SMTP: trying to connect to host "email-smtp.us-east-1.amazonaws.com", port 465, isSSL false 220 email-smtp.amazonaws.com ESMTP SimpleEmailService-376766033 DEBUG SMTP: connected to host "email-smtp.us-east-1.amazonaws.com", port: 465 EHLO 0.1.0.5 250-email-smtp.amazonaws.com 250-8BITMIME 250-SIZE 10485760 250-AUTH PLAIN LOGIN 250 Ok DEBUG SMTP: Found extension "8BITMIME", arg "" DEBUG SMTP: Found extension "SIZE", arg "10485760" DEBUG SMTP: Found extension "AUTH", arg "PLAIN LOGIN" DEBUG SMTP: Found extension "Ok", arg "" DEBUG SMTP: Attempt to authenticate DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM AUTH LOGIN 334 VXNlcm5hbWU6 QUtJQUk3WDNURUI0NEVKNlRSU1E= 334 UGFzc3dvcmQ6 QXJwZjl4eU1FTVc1WFNFR3ZxVXVPODNhRjFkcG8xMFpSeURXY0ZsNGVHQXM= 235 Authentication successful. DEBUG SMTP: use8bit false MAIL FROM:<[email protected]> 250 Ok RCPT TO:<[email protected]> 250 Ok DEBUG SMTP: Verified Addresses DEBUG SMTP: "[email protected]" <[email protected]> DATA 354 End data with <CR><LF>.<CR><LF> Date: Wed, 15 May 2013 08:44:47 -0500 (CDT) From: "[email protected]" <[email protected]> Reply-To: "[email protected]" <[email protected]> To: "[email protected]" <[email protected]> Message-ID: <2322287.7.1368625487826.JavaMail.UGOODJ3@SAOTXWL-9X913M1> Subject: Please join the ACT Aspire Hari AV test delivery portal MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----=_Part_6_16196755.1368625487826" ------=_Part_6_16196755.1368625487826 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: 7bit >>>> HTML EMAIL BODY REMOVED <<<< ------=_Part_6_16196755.1368625487826-- . 250 Ok 0000013ea86fb2de-0bd70205-8e9a-4042-972f-ad94b28c3101-000000 QUIT 221 Bye A: I'm going to follow up here with what turned out to be the solution to the problem. The Amazon AWS SMTP service maintains a "14-Day Suppression List" which is a list of email addresses that have bounced during the last 14 days. Any email sent via the Amazon SMTP service will fail when attempting to send to an address on the Suppression List. Unfortunately, they don't report the error, but instead, send an "Undeliverable" reply to the sender. So, if you have an automating sending service, you'll never know. I happened to find it because when I set up my own AWS SMTP server, I put in one of my own email addresses as the sender of the automated email. When I logged into that email account, I saw the Undeliverable messages, which explained that the target email is on the Supression List. Amazon does allow you to log into your Email Service Console and remove email addresses from the Suppression List. You just put in the email address, click Remove, and the address is immediately removed from the list. You have no way to see which email addresses are on the Suppression List, but you can remove any address you want. So, in the case of my email failures, I believe what happened was that I tried to email to them before the email creation was complete, resulting in a bounce. Once the email address bounces, it goes on the Supression List. For the next 14 days any email sent via ANY AWS SMTP server (not just mine) would fail. After 14 days (apparently) the email address is removed from the Suppression List until the next bounce is encountered. This Amazon software is very new, they actually just announced this Suppression List service in early May. So they may still need to work out a few kinks. This particular issue seems to present a somewhat serious issue for automated senders like ours. After all bounces do occur on occasion for reasons beyond our control.
{ "pile_set_name": "StackExchange" }
Q: Sort XML nodes alphabetically on attribute name I have an XML document for which I want to sort specific nodes alphabetically. XML document <response> <lst name="facet_counts"> <lst name="facet_fields"> <lst name="professions_raw_nl"> <int name="Pharmacy">2724</int> <int name="Physiotherapy">2474</int> <int name="Doctor">2246</int> <int name="Dentist">1309</int> </lst> </lst> </lst> </response> Desired output Dentist (1309) Doctor (2246) Pharmacy (2724) Physiotherapy (2474) Current ASP.NET code dim node as XmlNode = objXML.SelectSingleNode("response/lst[@name=""facet_counts""]/lst[@name=""facet_fields""]/lst[@name=""professions_raw_nl""]") Dim sbuilder As New StringBuilder Dim navigator As XPathNavigator = node.CreateNavigator() Dim selectExpression As XPathExpression = navigator.Compile("???") <-- what expression should I use here ??? selectExpression.AddSort("????", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Text) <-- what expression should I use here ???? Dim nodeIterator As XPathNodeIterator = navigator.Select(selectExpression) While nodeIterator.MoveNext() 'how can I print the name and value of the node? End While A: Since all answers seem to work with Linq and I just wanted to use regular VB.NET I now added each node in an Arraylist and used the regular Array.Sort() on it. Does the trick.
{ "pile_set_name": "StackExchange" }
Q: using ffmpeg in C: system() or C api? I want to use ffmpeg's transcoding features multiple times in my program. This can be achieved by doing ffmpeg -i input output in a terminal. I believe I can use some shell or C code to execute these commands programmatically. I could also directly use ffmpeg's c libraries to do this. My question is, will there be a noticeable performance difference between the 2 approaches? Obviously the first will be simpler to implement, but will I pay a big performance cost? A: It's quite typical these days to use the executable (system()) version even on mobile phones. If time-to-start is not critical for you, don't bother. If it is, consider making ffmpeg executable available for immediate start, e.g. with prelink.
{ "pile_set_name": "StackExchange" }
Q: How to can I count the number of ones? The problem is: In a class of 26 students, a test with 10 questions is given. The students answer the question by tossing a coin. I have to find out how many students have two or less answers correct. This is the program that I wrote, but I'm not sure about it ... is it good? correct=0; students=0; for i=1:26 for j=1:10 answ=ceil(rand); if answ==1 correct=correct+1; if correct==2 students=students+1; end end end end disp(students) A: It's neater, faster to run, and more readable if you do it vectorized: answers = round(rand(10,26)); % 10x26 matrix of 0 / 1 values correct = sum(answers); % sum along each column students = sum(correct<=2) % how many values of correct are 2 or less By the way, from your code it appears you want to know how many students have 2 or more correct answers (not 2 or less as you state). In that case change last line to students = sum(correct>=2) % how many values of correct are 2 or more A: Slight modification to your code: correct=0; students=0; for i=1:26 for j=1:10 answ=round(rand); % Use round instead of ceil if (answ==1) correct=correct+1; if correct==2 students=students+1; break; end end end correct=0; % Was missing in original code end disp(students) Additional Note: Try testing code for correct ans 5 as this will have more chances of variation to result because of uniform distribution of random number. Most of the students will get at-least 2 correct ans assuming equal probability, which is not the practical case. Try maintaining habit of proper indentation. It will be more readable and less prone to errors.
{ "pile_set_name": "StackExchange" }
Q: Laravel Personal Access token Expiration When do Passport Personal Access tokens exactly expire? Is it one year or they never expire? In the doc, it says "Personal access tokens are always long-lived. Their lifetime is not modified when using the tokensExpireIn or refreshTokensExpireIn methods." How much is long-lived? Is there any way to make them NEVER expire? A: It is 1 year from date of creation.
{ "pile_set_name": "StackExchange" }
Q: Set placeholder of JavaFX TableView in FXML I know the following problem is a bit of a luxury problem: I would like to keep the initialize of my FXML Controller as clean as possible, and therefore I would like to set the placeholder of my TableView in the FXML file (as I think it is the best place to keep it, because it is just a property and in my case also a constant). I already tried to set it in the FXML file like this: <TableView placeholder="Some text"> This obviously does not work, because the placeholder property expects a Node. That is why I set the placeholder like this in the initialize of the FXML controller: Label placeholder = new Label(); placeholder.setText("Some text"); tableview.setPlaceholder(placeholder); This works, but as I said, I would like to manage this from the FXML file only. Some my question is: How can I set the placeholder from within the FXML file? Note: please let me know if this i even possible, because when it is not, I will fill a feature request (with a low priority of course!). A: Quite simple, just the usual FXML Syntax: <BorderPane xmlns:fx="http://javafx.com/fxml/1"> <center> <TableView> <placeholder> <Label text="some text"/> </placeholder> </TableView> </center> Note: Not everything is a primitive value (can be expressed inline) and therefore needs its own element.
{ "pile_set_name": "StackExchange" }
Q: Grouping rows in sql query with different tables how can i write a query that shows a result like below 1 Beverages NULL NULL 1 Beverages Chai Exotic Liquids 1 Beverages Cheng Exotic Liquids 1 Dairy Products NULL NULL 1 Beverages Gorgonzola Telino Tokyo Traders 1 Beverages Geitost Tokyo Traders 1 Beverages Gudbrandsdalsost Tokyo Traders I used Northwind and I will write the normal query SELECT c.CategoryId, c.CategoryName, p.ProductName,s.CompanyName FROM Categories c INNER JOIN Products p ON c.CategoryId = p.CategoryId INNER JOIN Suppliers s ON s.SupplierId = p.CategoryId A: You can get needed results with that query: SELECT c.CategoryId, c.CategoryName, p.ProductName,s.CompanyName FROM Categories c LEFT JOIN Products p ON c.CategoryId = p.CategoryId LEFT JOIN Suppliers s ON s.SupplierId = p.SupplierID UNION ALL SELECT c.CategoryId, c.CategoryName, NULL, NULL FROM Categories c ORDER BY CategoryId, ProductName
{ "pile_set_name": "StackExchange" }
Q: Best CLOD Method for Planet Rendering I'm currently working on my thesis, it is an engine to render terrains of planetary size. I'm still finishing my researh and I have encountered a lot of stuff about this subject, the problem is that I can't decide on wich LOD method I should use. I know about geomipmapping, geometry clipmaps (GPU) and chunked LOD by Ulrich that work good on large terrains and can be used to render 6 faces of a cube and then "spherify" the cube by this method and I understand how to implement all of these methods on GPU using C++/OpenGL/GLSL (using methods like ROAM or any other method that doesn't use a cube is out of my reach because of texturing is a pain). So, I don't have the time to implement ALL the methods and see wich one is the best and more suitable for a planetary scale and I'm asking here to see if someone has made this kind of comparison and help me decide wich method should I implement and use (my tutor is kind of crazy and wants me to do something with an icosahedron, but I can't understad that method unless using ROAM) Anyways, if you can help me decide or have any other suggestion or method I really will appreciate. One condition is that the method should be able to implement GPU side (at least most of it) to prevent CPU bottleneck. Another request is that I know there are numerical problems about precision with floats when getting a lot of detail in the terrain, I don't know how to solve it, I read a solution in a forum but can't get to understand how to implement, I lost track of that thread and I would like to know how to solve this precision problem. PD: Sorry for my english. [EDIT] I'm currently reading about some matrix transformations to solve the float precision, z-fighting issues, frustrum culling with dynamic z-values, and data representation for chunks (using patch space with floats and its position in the world coordinates as double) so I think I can solve the precision problem easily. I still need a comparison between LOD methods with your opinions and suggestions to decide which is better for this project. Take in count difficulty of implementation vs visual quality vs performance, I want the best. Something I forgot to mention is that the generation is hybrid, I mean, I should be able to render the planet entirely using GPU (heights calculated on the fly) and/or using a base heightmap image and add details with GPU (vertex shader). Texturing will be a side part I will trouble latter, right now I'm happy using just colors depending on the height, or maybe using some kind of noise texture generated on the fragment shader. A: Finally, after a lot of researching I can conclude that, as some one said before, There is not universally "best" method. But my research led me to the knowledge of the following things: Depending on the mesh you will finally use: Spherified Cube: any LOD method with quadtree implementation will work just fine, you just have to take care on special cases like borders between faces, in wich case, your quadtree has to have a pointer to the neighbor in the adyacent face in each level. Any other: I think that ROAM (newer version 2.0 or any other extension as BDAM, CABTT or RUSTIC) will do well, however, these algorithms are hard to work with, require more memory and are a bit slower than other aproaches with cubes. There are many LOD methods that can fit well, but my personal top 5 are: Continous Distance-Dependent LOD (CDLOD) GPU Based Geomety Clipmaps (GPUGCM) Chunked LOD Rendering Terrains with OpenGL GPU Tessellation (Book: OpenGL Insight, Chapter 10) Geometrical MipMapping Each one offers an unique way to render terrains, for example, CDLOD has a very easy implementation using shaders (GLSL or HLSL) but is also capable to be implemented on CPU (for legacy hardware) however the goal on Planet Rendering is to explode the best on moderns GPUs, so GPUGCM is the best when you want to squeeze your GPU. They both work very well with data-based, procedural or mixed (terrain based on fixed data or heightmaps and detail added with procedural work) rendering of large terrains. Also Spherical extension to the basic Geometrical Clipmaps method exists but has some problems because the planar samples of the heightmap has to be parametrized using spherical coordinates. Chunked LOD, in the other hand, is perfect for legacy hardware, doesn't need any GPU side calculations to work, it's perfect for large datasets but can't handle procedural data in real time (maybe with some modifications, it could) Using Tessellation shaders is another technique, very new, since OpenGL 4.x came out, in my opinion it could be the best, but, we are talking about Planet Rendering, we encounter a problem that other methods can handle very easy and it is about precision. Unless you only want your precision to be 1Km between verticies, go for Tessellation shaders. The problem with really big terrains with this method is that jitter is kind of hard to solve (or at least for me, since I'm new to tessellation shaders). Geomipmapping is a great technique, takes advantage of the quadtree and has a low projected pixel error, but, for planetary rendering you will need to set at least 16+ levels of details, that means you will need (for stitching pourposes) some extra patches to connect different levels and take care of your neighbor's level, this can be tedious to solve, especially using 6 terrain faces. There is another method, very particular in its own: "Projective Grid Mapping for Planetary Terrain" excellent for visualization, but has its disadvantages, if you want to know more, go to the link. Problems: Jitter: Most of today’s GPUs support only 32-bit floating-point values, which does not provide enough precision for manipulating large positions in planetary scale terrains. Jitter occurs when the viewer zooms in and rotates or moves, then the polygons start to bounce back and forth. The best solution for this is to use "Rendering Relative to Eye Using the GPU" method. This method is described in the book "3D Engine Design for Virtual Globes" (I'm sure you can find it on the internet aswell) in where basically you have to set all your positions with doubles on CPU (patches, clipmaps, objects, frustrum, camera, etc) and then MV is centered around the viewer by setting its translation to (0, 0, 0)T and the doubles are encoded in a fixed-point representation using the fraction (mantissa) bits of two floats, low and high by some method (read about Using Ohlarik’s implementation and The DSFUN90 Fortran library). Although the vertex shader requires only an additional two subtractions and one addition, GPU RTE doubles the amount of vertex buffer memory required for positions. This doesn’t necessarily double the memory requirements unless only positions are stored. Depth Buffer Precision: Z-fighting. As we are rendering very large terrains, in this case: planets, the Z-buffer has to be HUGE, but it doesn't matter wich values you set for znear and zfar, there will always be problems. As the Z-buffer depends on a float point interval, and also it is linear (although perspective projection is non linear) values near the eye suffer from Z-fighting because the lack of precision 32-bit floats have. The best way to solve this problem is to use a "Logarithmic Depth Buffer" http://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html A logarithmic depth buffer improves depth buffer precision for distant objects by using a logarithmic distribution for zscreen. It trades precision for close objects for precision for distant objects. Since we are rendering with a LOD method, far objects require less precision because they have less triangles. Something important to mention is that all the methods listed (except for the projective grid) are very good when doing physics (collisions mostly) because of the Quadtree base, that is something mandatory if you plan to make a game. In conclusion, just check all the options available and go for the one you feel more confortable, in my opinion CDLOD does a great work. Don't forget to solve the jitter and Z-buffer problems, and most important: have fun making it! For more information about LOD check this link. For a complete demostration about spherifying a cube check this link. For a better explanation about solving jittering and Z-Buffer precisions, check this book. I hope you find this little review useful.
{ "pile_set_name": "StackExchange" }
Q: Lazy loading class not loading - MVC I have clients: public class Client { public int ClientID { get; set; } public string ClientName { get; set; } public virtual List<Project> Projects { get; set; } } And projects: public class Project { public int ProjectID { get; set; } public string ProjectName { get; set; } } The client controller has a details get action: public ActionResult Details(int id) { Client client = db.Clients.Find(id); return View(client); } And a details post action: [HttpPost] public ActionResult Details(Client client) { if (ModelState.IsValid) { db.Entry(client).State = EntityState.Modified; db.SaveChanges(); // reload object from db to populate projects property client = db.Clients.Find(client.ClientID); } return View(client); } My client details view: @model Client <h1>@Html.DisplayFor(model => model.ClientName)</h1> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>Client</legend> @Html.HiddenFor(model => model.ClientID) <div class="editor-label"> @Html.LabelFor(model => model.ClientName) </div> <div class="editor-field"> @Html.EditorFor(model => model.ClientName) @Html.ValidationMessageFor(model => model.ClientName) </div> <p> <input type="submit" value="Save" /> </p> </fieldset> } <h2>Projects</h2> <ul> @foreach (Project project in Model.Projects) { <li>@Html.ActionLink(project.ProjectName, "Details", "Project", new { id = project.ProjectID }, null)</li> } </ul> Now if I go to a client which has projects, it works fine, I see the client name in the textbox, and a list of projects. I edit the name and click Save. But then the view errors on the subclass list iteration, "Object reference not set to an instance of an object." I added in this line specifically to reload the instance from the db, assuming it would then repopulate the lazy-loading list class, and I would have the same instance data as I had in the get request, just with the name changed: client = db.Clients.Find(client.ClientID); Why is it not loading the subclass on the postback? Once I have this fixed, would it be a good idea in the Client class, to add a constructor that instantiates the List class, in case I navigate to a Client that doesn't have any records in the database? A: The reason is that on post MVC is constructing an instance of the actual POCO, NOT an instance of the proxy class that derives from the POCO. Therefore, there is no overridden virtual property to perform the lazy loading. The solution is to explicitly load the collection via the entry (to replace your Clients.Find(id) call): db.Entry(client).Collection( c => c.Projects ).Load(); A: I'm going to have to look into ApplyCurrentValues, but for the moment, this is how I've got it to work: [HttpPost] public ActionResult Details(Client client) { if (ModelState.IsValid) { db.Entry(client).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Details", new { msg = "saved" }); } client.Projects = db.Clients.Find(client.ClientID).Projects; return View(client); } The Projects are re-attached if the validation fails, before being passed back to the view. In theory, this should work instead of an Action redirect. I'll try that out too.
{ "pile_set_name": "StackExchange" }
Q: Пунктуация в предложениях типа определение при перестановке В конструкциях типа: "Какая прелесть - быть на высоте!", "Какое это чудо: летать в облаках" ставится тире или двоеточие? A: Вот что пишет Розенталь (§ 5. 2. Тире между подлежащим и сказуемым): Тире ставится между подлежащим и сказуемым, если оба они выражены неопределенной формой глагола (инфинитивом) или если один из главных членов выражен формой именительного падежа существительного, а другой — неопределенной формой глагола: Конечно, это большое искусство — ждать (Л. Соболев). Какая прелесть — быть на высоте! Какое это чудо — летать в облаках.
{ "pile_set_name": "StackExchange" }
Q: What is wrong with this class? (design wise) Following up from this question: designing application classes What is wrong (from a design point of view) with this class: I'm trying to refactor this class and it's abstract base class (Logon) and the fact it's actually horrible design. I wrote it myself (pretty much when I was a newbie). I'm finding it hard to refactor and want some input on it? class NewUserLogon : Logon, ILogonNewUser, IDisposable { #region Member Variables System.Windows.Forms.Form _frm = new MainWindow(); SQLDatabase.SQLDynamicDatabase sql; SQLDatabase.DatabaseLogin dblogin; LogonData lgndata; System.Security.SecureString securepassword; PasswordEncrypt.Collections.CreatedItems items; LogonEventArgs e = new LogonEventArgs(); #endregion #region Constructors // for DI public NewUserLogon(PasswordEncrypt.Collections.CreatedItems items) : base (items) { this.items = items; } #endregion #region Public Methods public new void Dispose() { } public bool? ReadFromRegistry(HashedUsername username, HashedPassword hashedpassword) { return RegistryEdit.ReadFromRegistry(username, hashedpassword); } public bool WriteToRegistry(HashedUsername username, HashedPassword hashedpassword) { return RegistryEdit.WriteToRegistry(username, hashedpassword); } public override void Login(TextBox username, TextBox password) { base.Login(username, password); Login(username.Text, password.Text); } #endregion #region Protected Methods protected override void Login(string username, string password) // IS INSECURE!!! ONLY USE HASHES { base.Login(username, password); if (_user is NewUserLogon) // new user { sql = new PasswordEncrypt.SQLDatabase.SQLDynamicDatabase(); dblogin = new SQLDatabase.DatabaseLogin(); lgndata = base._logondata; securepassword = new System.Security.SecureString(); // Set Object for eventhandler items.SetDatabaseLogin = dblogin; items.SetSQLDynamicDatabase = sql; // recreates L items.Items = items; string generatedusername; // write new logondata to registry if (this.WriteToRegistry(lgndata.HahsedUserName, lgndata.HashedPsw)) { try { // Generate DB Password... dblogin.GenerateDBPassword(); // get generated password into securestring securepassword = dblogin.Password; //generate database username generatedusername = dblogin.GenerateDBUserName(username); if (generatedusername == "Already Exists") { throw new Exception("Username Already Exists"); } //create SQL Server database try { sql.CreateSQLDatabase(dblogin, username); } catch (Exception ex) { //System.Windows.Forms.MessageBox.Show(ex.Message); e.ErrorMessage = ex.Message; e.Success = false; OnError(this, e); } } catch (Exception exc) { e.Success = false; e.ErrorMessage = exc.Message; OnError(this, e); } OnNewUserLoggedIn(this, e); // tell UI class to start loading... } else { System.Windows.Forms.MessageBox.Show("Unable to write to Registry!", "Registry Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); } } else if (_user is ExistingUserLogon) // exising user { bool? compare = base._regRead; lgndata = base._logondata; if (compare == true) { //Tell GUI to quit the 'busydialog' thread OnMessage(this, e); LogonFrm frm = LogonFrm.LogonFormInstance; // tell user he already exists and just needs to login // ask if user wants to logon straight away System.Windows.Forms.DialogResult dlgres; dlgres = System.Windows.Forms.MessageBox.Show("Your login already exists, do you wan to login now?", "Login Exists", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question); if (dlgres == System.Windows.Forms.DialogResult.Yes) { ExistingUserLogon existinguser = new ExistingUserLogon(compare, lgndata); existinguser.Error += new ErrorStatus(frm._newuser_Error); existinguser.loginname = username; existinguser.LoginNewUser(); ///TELL GUI THAT USER LOGIN SUCCEEDED, THROUGH EVENT e.Success = true; OnNewUserLoggedIn(this, e); } else { e.Success = false; e.ErrorMessage = "Failed"; OnError(this, e); } } } } #endregion } A: Your class tries to do too many things. Try to separate different responsibilities into separate classes (eg database access and UI stuff). And why are you instantiating a new Form at the beginning of your class and don't seem to use it further on?
{ "pile_set_name": "StackExchange" }
Q: why is ajax failing for partial data serialization? I have this working: jQuery( "input" ).on("blur", function(){ jQuery.ajax({ type: "POST", url: jQuery(this).closest("form").attr("action"), data: jQuery(this).closest("form").serialize() }); }); Unfortunately, the above serializes the entire form, which I don't want. I only want to pass the field that was changed. By the way, I don't have access to the form, just the html. Any help? Could the form.php REQUIRE that all parameters are sent? It is a framework I'm sending this to that processes all the database injections. Any idea why the following won't work? jQuery( "input" ).on("blur", function(){ jQuery.ajax({ type: "POST", url: jQuery(this).closest("form").attr("action"), data: jQuery(this).serialize() }); }); A: Use: jQuery( "input" ).on("blur", function(){ var obj = {}; obj[this.name] = this.value; jQuery.ajax({ type: "POST", url: jQuery(this).closest("form").attr("action"), data: obj }); }); serialize() function is used for form submit, not just input. Then if you want to pass just current edited input, pass name and value as object to data parameter. jQuery will serialize data in object for you.
{ "pile_set_name": "StackExchange" }
Q: Prevent writing any changes to bootable USB I'm creating a reusable Ubuntu Server 16.04 image. The idea is that it would boot up from a USB drive, provide some services for a while, and then shut down. Unfortunately, if a user removes the drive it's very likely to become corrupted. I don't have a swap partition (it's awful for USB anyways) but is there another step I could take to prevent any persistent writes? Ideally you would reboot and the drive would be back to its original state, kind of like the live USB but with all my stuff on it. A: The solution I ended up with was to mark the partition as read-only in /etc/fstab. I changed the line for the root partition, /, from this: UUID=949e37ad-bc64-47bd-8478-fa6661267d9f / ext4 errors=remount-ro 0 1 To: UUID=949e37ad-bc64-47bd-8478-fa6661267d9f / ext4 ro,errors=remount-ro 0 1 Note the ro, before the errors bit. You can see more on the Fstab wiki page. This is also nice because once the system is booted you can also remount it as read-write if necessary. rootMount=$(findmnt / -o source -n) mount -o remount,rw "${rootMount}" /
{ "pile_set_name": "StackExchange" }
Q: From book : Putnam and beyond Original at https://i.stack.imgur.com/Zn8RE.jpg Lucas' theorem. The zeros of the derivative $P'(z)$ of a polynomial $P(z)$ lie in the convex hull of the zeros of $P(z)$. Proof. Because any convex domain can be obtained as the intersection of half-planes, it suffices to show that if the zeros of $P(z)$ lie in an open half-plane, then the zeros of $P'(z)$ lie in that half-plane as well. Moreover, by rotating and translating the variable $z$ we can further reduce the problem to the case in which the zeros of $P(z)$ lie in the upper half plane $\text{Im } z > 0$. Here $\text{Im } z$ denotes the imaginary part. So let $z_1, z_2, \ldots, z_n$ be the (not necessarily distinct) zeros of $P(z)$, which by hypothesis have positive imaginary part. If $\text{Im } w \leq 0$, then $\text{Im } \frac{1}{w-z_k} > 0$, for $k = 1, \ldots, n$, and therefore $$ \text{Im } \frac{P'(w)}{P(w)} = \sum_{k=1}^n \text{Im } \frac{1}{w-z_k} > 0. $$ This shows that $w$ is not a zero of $P'(z)$ and so all zeros of $P'(z)$ lie in the upper half-plane. The theorem is proved. We assumed that $ z_1,z_2,...,z_n $ have positive imaginary part. Then if $ Im(w)\leq 0$ how the conclusion $ Im \frac{1}{w-z_k} $ ,for $ k=1,2,...,n $ occurs? A: I can't fit this in a comment. We have $$ {1\over \omega-z_k}={\overline{\omega-z_k}\over(\omega-z_k)\overline{(\omega-z_k})} ={\overline{\omega}-\overline{z_k}\over|\omega-z_k|^2}$$ Now the denominator on the right-hand side is real and positive, so we just have to figure out the sign of the imaginary part of the numerator. I leave that to you.
{ "pile_set_name": "StackExchange" }
Q: Cura projecting floating print onto build plate during slicing I'm trying to do a multifilament print on my single extruder machine. So I separated out the models based on filament, and imported the parts into Cura. I ensured that "Automatically drop models to build plate" was disabled and in the "Prepare" phase that seems to work. However, when I slice the model it gets pushed back down to the build plate as can be seen in the picture below. Any recommendations? Do I just need to write a script to go in and shift the z location? A: I've been playing with this and came up with a solution, so I thought I would share in case anyone else had this issue in the future. In Ultimaker Cura I enabled supports and z-hopping before I sliced the part, then I ran this Python function to remove the supports and get the extruder setup. import re def float_part(file): printString = ';LAYER:' partString = ';(.*?).stl' with open( file , 'r') as content_file: content = content_file.read() printArea = re.search( printString , content ).span(0)[0] partArea = re.search( partString , content ).span(0)[0] uncommentedLine = partArea - re.search( '\n.*?(?<!;)\n' , content[ partArea:printArea:-1 ] ).span(0)[0] lastExtrusion = uncommentedLine - re.search( 'E' , content[ uncommentedLine:printArea:-1 ] ).span(0)[0] secondLastExtrusion = lastExtrusion - re.search( 'E' , content[ lastExtrusion-1:printArea:-1 ] ).span(0)[0] lastExtrusionAmount = float(re.search( '\d+(\.\d+)?', content[lastExtrusion:] ).group(0)) secondLastExtrusionAmount = float(re.search( '\d+(\.\d+)?', content[secondLastExtrusion:] ).group(0)) ResetCommand = '\nG92 E' + str(lastExtrusionAmount) + '\n' with open( file , 'w') as content_file: content_file.write( content[0:printArea] + ResetCommand + content[uncommentedLine:] )
{ "pile_set_name": "StackExchange" }
Q: Galois Group Calculation Calculate the Galois Group $G$ of $K$ over $F$ when $F=\mathbb{Q}$ and $K=\mathbb{Q}\big(i,\sqrt2,\sqrt3 \big)$. My thoughts are as follows: By the Tower Lemma, we can see that $|\text{Gal}(K/F)|=8$, since $K$ is a degree $8$ extension over $F$. Now, $\phi \in\text{Gal}(K/F)$ where $\phi$ represents complex conjugation. This satisfies $\phi ^2 =\text{Id}$. Similarly, the map which switches $\sqrt2$ and $\sqrt3$ around is also an automoprhism fixing $\mathbb{Q}$, say $\tau$, satisfying $\tau ^ 2=\text{Id}$. How can I find the other elements of the Galois Group? Have I missed an easier method? A: It's just $(\mathbb{Z}/2\mathbb{Z})^3$. To see this, indeed complex conjugation is an automorphism of order 2. However, so are the automorphisms sending $\sqrt{2}\mapsto -\sqrt{2}$, and $\sqrt{3}\mapsto-\sqrt{3}$ (and fixing the rest). Hence, you have 3 elements of order 2, which commute and generate your group (check this!). These three automorphisms then give you a nice isomorphism to $(\mathbb{Z}/2\mathbb{Z})^3$.
{ "pile_set_name": "StackExchange" }
Q: How to use NSIS Internet plugin? I have some code that defines a variable like so: .... Var IP ... I have some other code that runs on init Function .onInit ;Default installation folder StrCpy $INSTDIR "C:\PTL\${Project}" Internet::GetLocalHostIP ${IP} FunctionEnd When I run the interpreter against the script, I get a warning: [exec] Variable "IP" not referenced or never set, wasting memory! I figure this is because im not assigning some constant value to IP, and it doesnt recognize the set operation thats happening with the Internet plugin, but when I run the installer it generates, and check the JVM args which use this value (-Djava.rmi.hostname) I have this value: -Djava.rmi.server.hostname= I tried using a value like $8 but it does the same thing, only the value becomes: -Djava.rmi.server.hostname=0 How do I use this plugin correctly? In terms of setup, I just dropped the plugin into ./Plugins/x86-ansi A: ${x} is for !define's, the syntax for variables is $x so in your case $IP but the NSIS plugin API does not allow output into a variable like that. This plugin has a unusual design, if you take a look at its included .nsh file you see it has some defines where VAR_0 = 0 etc. This means you have to do something like this: Internet::GetLocalHostIP 1 ; Tells the plugin to put the result in $1 StrCpy $IP $1 ; Copy into your variable
{ "pile_set_name": "StackExchange" }
Q: Help locating a file in Magento that contains HTML I'm trying to change the class name in the HTML output from "price". I was hoping to find it in the code block below. The following code (frontend/default/theme/template/page/html/cart.phtml): <div class="shopping_cart_b"> <a href="#" class="open"> <?php echo $this->__('Shopping Cart:'); ?> <?php echo $_cartQty; ?> <span><?php echo $this->__('Item(s) - '); ?></span> <?php if ($this->canApplyMsrp()): ?> <?php echo $this->__('ORDER TOTAL WILL BE DISPLAYED BEFORE YOU SUBMIT THE ORDER'); ?> <?php else: ?> <?php echo Mage::helper('checkout')->formatPrice($this->getSubtotal()) ?> <?php if ($_subtotalInclTax = $this->getSubtotalInclTax()): ?> (<?php echo Mage::helper('checkout')->formatPrice($_subtotalInclTax) ?> <?php echo Mage::helper('tax')->getIncExcText(true) ?>) <?php endif; ?> <?php endif; ?> </a> </div> Produces the following output (in Header): <div class="shopping_cart_b"> <a href="#" class="open"> Shopping Cart: <span>Item(s) - </span> <span class="price">£0.00</span> </a> </div> Block Name Hint: Mage_Checkout_Block_Cart_Sidebar I've determined that <?php echo Mage::helper('checkout')->formatPrice($this->getSubtotal()) ?> is responsible for calling <span class="price">£0.00</span>, but I've no idea where to find the actual file to change the CSS class. I've used grep to try and find the file, but there are too many results. Any help appreciated. A: What you are looking for is something that you won't find in a phtml file. The magento helper function has a second parameter that is by default, set true. The parameter, I believe is whether to include the container or not. The container, if my memory is correct, is where html is being included and perhaps the class name is within the code. I strongly suggest NOT updating the code, but rather apply a second parameter of false and see what sort of output you can then work with. If what I say is correct, it should be simply the price. Therefore, try this as a solution: <span class="price price-customclass"><?php echo Mage::helper('checkout')->formatPrice($this->getSubtotal(), false) ?></span> I strongly suggest to append your new class name, instead of replacing the original. Keeping the original class name price would be helpful to ensure that anything referencing or depending on that class is not affected. CORRECTION The code above is incorrectly assumed, but ultimately correct if you trace the function calls. The call I have in the code snippet actually doesn't allow for a second parameter. Tracing call hierarchy reveals that you may substitute that code with: Mage::getSingleton('checkout/session')->getQuote()->getStore()->formatPrice($price, false); UPDATE As I had suggested above, the class name is, in fact, applied by code not found within a template file. The code below was found within: magento/app/code/core/Mage/Directory/Model/Currency.php if ($includeContainer) { return '<span class="price">' . ($addBrackets ? '[' : '') . $this->formatTxt($price, $options) . ($addBrackets ? ']' : '') . '</span>'; }
{ "pile_set_name": "StackExchange" }
Q: Extract datatype information from an interface instance Supposing we have two classes that implement a common interface. public interface IContract { int Type { get; } } public class XClass : IContract { public int Type { get; set; } public int X { get; set; } } public class YClass : IContract { public int Type { get; set; } public int Y { get; set; } } Now, As you know, when we assign a class to the implemented interface, the interface instance contain all the data of the assigned class boxed inside. IContract ic = new XClass(); There should be a way to detect the datatype of the value within the interface variable ic. If(ic contains XClass datatype) Then ... If(ic contains YClass datatype) Then ... I'd be glad if anyone can help me to detect the datatype assigned to the interface instance. Thanks. A: Have you tried: if (ic is XClass) You can use the "is" keyword to determine the class. Then there's always .GetType(), but that isn't as clean. if (ic.GetType() == typeof(XClass)) Also, it's worth mentioning the as keyword. If you want to declare a new object from a current object, guaranteeing it's a specific class: var d = ic as XClass If ic isn't XCLass, it will set d to null.
{ "pile_set_name": "StackExchange" }
Q: Routing fails in spring vmware vFabric I was following this tutorial http://manueljordan.wordpress.com/2011/12/12/creating-a-spring-web-mvc-project-with-springsource-tool-suite/ However it looks as if my spring project does not get recognised. What I mean is that when I navigate to localhost:8080/Spring-default I get a 404 error. Here are some screen shots that show my configuration: This screenshot shows that my VMware vFabric tc Server is configured correctly: The project directory structure is the same as the template that spring tool suit offers. My controller is the controller that comes with the template: package com.vlad.myapp; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Handles requests for the application home page. */ @Controller public class HomeController { private static final Logger logger = LoggerFactory.getLogger(HomeController.class); /** * Simply selects the home view to render by returning its name. */ @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { logger.info("Welcome home! The client locale is {}.", locale); Date date = new Date(); DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale); String formattedDate = dateFormat.format(date); model.addAttribute("serverTime", formattedDate ); return "home"; } } If I go to localhost:8080 I get the default page that VMware offers however as mentioned above localhost:8080/Default-spring gives me a 404. Here is the pom.xml if it's of any help: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.vlad</groupId> <artifactId>myapp</artifactId> <name>Spring-default</name> <packaging>war</packaging> <version>1.0.0-BUILD-SNAPSHOT</version> <properties> <java-version>1.6</java-version> <org.springframework-version>3.1.1.RELEASE</org.springframework-version> <org.aspectj-version>1.6.10</org.aspectj-version> <org.slf4j-version>1.6.6</org.slf4j-version> </properties> <dependencies> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework-version}</version> <exclusions> <!-- Exclude Commons Logging in favor of SLF4j --> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework-version}</version> </dependency> <!-- AspectJ --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${org.aspectj-version}</version> </dependency> <!-- Logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${org.slf4j-version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${org.slf4j-version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${org.slf4j-version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.15</version> <exclusions> <exclusion> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> </exclusion> <exclusion> <groupId>javax.jms</groupId> <artifactId>jms</artifactId> </exclusion> <exclusion> <groupId>com.sun.jdmk</groupId> <artifactId>jmxtools</artifactId> </exclusion> <exclusion> <groupId>com.sun.jmx</groupId> <artifactId>jmxri</artifactId> </exclusion> </exclusions> <scope>runtime</scope> </dependency> <!-- @Inject --> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <!-- Servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- Test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.7</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-eclipse-plugin</artifactId> <version>2.9</version> <configuration> <additionalProjectnatures> <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature> </additionalProjectnatures> <additionalBuildcommands> <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand> </additionalBuildcommands> <downloadSources>true</downloadSources> <downloadJavadocs>true</downloadJavadocs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>1.6</source> <target>1.6</target> <compilerArgument>-Xlint:all</compilerArgument> <showWarnings>true</showWarnings> <showDeprecation>true</showDeprecation> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <configuration> <mainClass>org.test.int1.Main</mainClass> </configuration> </plugin> </plugins> </build> </project> Here is the web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- The definition of the Root Spring Container shared by all Servlets and Filters --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value> </context-param> <!-- Creates the Spring Container shared by all Servlets and Filters --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Processes application requests --> <servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> Here is servlet-context.xml <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> <!-- Enables the Spring MVC @Controller programming model --> <annotation-driven /> <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> <resources mapping="/resources/**" location="/resources/" /> <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix" value="/WEB-INF/views/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean> <context:component-scan base-package="com.vlad.myapp" /> </beans:beans> A: Check that you are using the appropriate context root: Right click the project > Properties > Web Project Settings This value will be the context root for your application and will govern how the URL is constructed. localhost:8080/context-root/
{ "pile_set_name": "StackExchange" }
Q: Can a person die due to a heart attack caused by extreme happiness? I have heard that some people die of a heart attack caused by extreme happiness. Is it possible? A: MedicineNet - Heart Attack (Myocardial Infarction) Increased adrenaline, as previously discussed, may contribute to rupture of cholesterol plaques. I can only assume that any stress to a heart on the brink of disaster can be a trigger that send it over the edge. Getting some piece of extremely good news like winning the lotto is bound to cause an elevation in blood pressure and heart rate that could trigger this. However, I'm not sure if you are asking about a quick onset of extreme happiness like in the lottery example or if you just meant to ask if being an extremely happy person in general could cause you to be at a higher risk for a heart attack? This study seems to suggest the opposite Dropping dead of a heart attack upon receiving some news of outrageously good fortune seems to be commonly assumed to be something that can and does happen but in searching for heart attack and lottery I was unable to find any documented stories of something like that happening, although there are plenty of documented stories of people dying from heart attacks weeks or months after winning a lotto. This could be because of a newly active lifestyle or an increase in excessive indulgences with one's new found wealth. In any event, given that any trigger that causes a substantial increase in heart rate or blood pressure is potentially a trigger for an unhealthy heart to go in to cardiac arrest, I think it's safe to assume that the answer to your question is yes, potentially, although there does not seem to be very many documented cases of this, or any published studies of the phenomena that I was able to find.
{ "pile_set_name": "StackExchange" }
Q: SQL Server Determine Physical Size of Table Columns Is it possible to find out how big the data is in KB or MB for individual columns in a table? I have a script which tells me the physical size of each table, but I would like to know how much of that is taken up by certain columns in the database, especially when I have XML stored in a column. Any help much appreciated Cheers A: You should be able to use the datalength function, something like select sum(datalength(yourfield)) from yourtable This will summate the datalengths of all the entries of that field in the table - it will not account for overheads such as variable length field pointers, space in the nullability bitmap etc.
{ "pile_set_name": "StackExchange" }
Q: How to PXE boot an IPCop installation? I need to PXE boot my IPCop installation on a computer, but I don't know how to boot the OS over PXE, since I cannot find a pxelinux.0 file. I've put all IPCop files and folders in the /srv/tftp folder on the PXE server. The PXE server's udhcpd.conf file contains the following line: boot_file /srv/tftp/pxelinux.0 What should I do in order to get this working with my IPCop OS? As far as I know, there is no pxelinux.0 file. The boot folder of my IPCop installation contains (I am not sure if this is important): A: Seems to me like your installation folder is incomplete. The *.c32 files are definetely a part of PXELINUX/SYSLINUX, but the pxelinux.0 binary is obviously missing. You could manually download PXELINUX. Place the pxelinux.0 file in that folder and make sure that you replace all the *.c32 files with the respective copies from the downloaded PXELINUX version. Rename extlinux.conf to default and place it inside a folder called pxelinux.cfg. If PXELINUX shows error messages about missing *.c32 files while trying to boot, copy those files into the tftpboot folder as well.
{ "pile_set_name": "StackExchange" }
Q: How can I loop through macros with \foreach and pass them to \xapptocmd? Can I use pgffor to loop through macros (control sequences)? e.g. \foreach \macro in {\lions,\tigers,\bears} In case you haven't figured it out, I love modularization! Let's say I have three commands to patch: \a1 \a2 \a3 Pseudo-Code This code was an attempt to achieve what I want. For fun and to test my understanding, I used \csname to create macros with numbers in their names. \documentclass{article} \usepackage{tikz} \usepackage{regexpatch} \expandafter\newcommand\csname a1\endcsname[1]{} \expandafter\newcommand\csname a2\endcsname[1]{} \expandafter\newcommand\csname a3\endcsname[1]{} \foreach \macro in {\csname a1\endcsname,\csname a2\endcsname,\csname a3\endcsname} {% \expandafter\xapptocmd{\macro}{\unexpanded{#1}, oh my!}{}{}% Apply patches to all macros in list }% \begin{document} \csname a1\endcsname{Lions} \csname a2\endcsname{tigers} \csname a3\endcsname{and bears} \end{document} Expected Page Output Lions, oh my! tigers, oh my! and bears, on my! Alternative semi-working Example without \csname \documentclass{article} \usepackage{tikz} \usepackage{regexpatch} \newcommand\lions[1]{} \newcommand\tigers[1]{} \newcommand\bears[1]{} %\foreach \macro in {\lions,\tigers,\bears} {% Loop up the following junk \xapptocmd{\lions}{\unexpanded{#1}, oh my!}{}{}% inefficient use of my time \xapptocmd{\tigers}{\unexpanded{#1}, oh my!}{}{}% inefficient use of my time \xapptocmd{\bears}{\unexpanded{#1}, oh my!}{}{}% inefficient use of my time %}% \begin{document} \lions{Lions} \tigers{tigers} \bears{and bears} \end{document} Output A: You can use, apart from using expl3 loops (like \clist_map_inline:nn), the provided by etoolbox. \documentclass{scrartcl} \usepackage{etoolbox,regexpatch} \csdef{a1}#1{} \csdef{a2}#1{} \csdef{a3}#1{} \begin{document} \renewcommand*\do[1]{\expandafter\xapptocmd\csname#1\endcsname{##1, oh my!}{}{\typeout{Misreable filure}}} \docsvlist{a1,a2,a3} \csuse{a1}{Lions}\par \csuse{a2}{tigers}\par \csuse{a3}{and bears} \end{document} I used \csdef and \csuse just to show them, you can use \expandafter\newcommand\csname .. \endcsname and \csname .. \endcsname, like always. As egreg says, the always repeating problem with \foreach is the fact that everything is inside a group. I've never thought about it, but I don't know why isn't it defined something like \foreach \foo in { a, b } { <code> } to be \let\save\foo \def\foo{a} <code> \def\foo{b} <code> \let\foo\save, which would solve many things. In any case, if you want to define yourself a complete macro that will automate everything you can do, for example, this two options: \usepackage{etoolbox} \newcommand\doforeach[2]{\renewcommand\do[1]{#2}\docsvlist{#1}} or \usepackage{expl3} \ExplSyntaxOn \NewDocumentCommand \doforeach { +m +m } { \clist_map_inline:nn { #1 } { #2 } } \ExplSyntaxOff and then you can use easily \doforeach{a1,a2,a3}{\expandafter\xapptocmd\csname#1\endcsname{##1, oh my!}{}{\typeout{Misreable filure}}} and you don't have to type difficult things.
{ "pile_set_name": "StackExchange" }
Q: Number of sub-intervals for an array? What's the number of continuous subintervals for an array of size n? For example for array [1,2,3,4,5] this set would be [1,2,3,4,5] + [1 2, 2 3, 3 4, 4 5] + [1 2 3, 2 3 4, 3 4 5] + [1 2 3 4, 2 3 4 5] + [1 2 3 4 5] So the total number of subintervals for array of 5 elements is 15, for array of 4 elements it is 10. I don't see any particular pattern here... Any ideas how to express this number of a function of n? A: Let $i,j$ be indices marking the start and end of the sub-interval respectively. We can select $i,j\in\{1,2,...,n\}$ such that $i\ne j$ in $\binom n2$ ways, and assign $i$ as the smaller index and $j$ as the larger index of the selected indices. We can select $i,j$ such that $i=j$ in $n$ ways. The total is $\displaystyle\binom n2+n=\frac{n(n-1)}2+n=\frac{n(n+1)}2$
{ "pile_set_name": "StackExchange" }
Q: How to use two (or more) xml files in one xsl document? I've been struggling for a while to get two (or more) XML files to be processed by the same xsl file. I followed the steps in this post: Including an XML file in an XML/XSL file but I haven't been able to get this to work. I can't seem to get the file loaded to be processed, no error. This is the first xm file - Dial_Stats_MWB: <?xml version="1.0" encoding="utf-8"?> <UK_Products_Pipeline> <LastFinishCode> <SiteName>UK</SiteName> <LastFinishCode>Agent Logout</LastFinishCode> <Numbers>1</Numbers> </LastFinishCode> <LastFinishCode> <SiteName>UK</SiteName> <LastFinishCode>Busy</LastFinishCode> <Numbers>1</Numbers> </LastFinishCode> <LastFinishCode> <SiteName>UK</SiteName> <LastFinishCode>BW Sale</LastFinishCode> <Numbers>1</Numbers> </LastFinishCode> </UK_Products_Pipeline> The second file - Dial_Stats_UK: <?xml version="1.0" encoding="utf-8"?> <UK_Products_Pipeline> <LastFinishCode> <SiteName>MWB</SiteName> <LastFinishCode>Bearer Capability Not Presently Authorized (ISDN Cause Code 57)</LastFinishCode> <Numbers>1</Numbers> </LastFinishCode> <LastFinishCode> <SiteName>MWB</SiteName> <LastFinishCode>Confirmed Booking</LastFinishCode> <Numbers>1</Numbers> </LastFinishCode> <LastFinishCode> <SiteName>MWB</SiteName> <LastFinishCode>Lost</LastFinishCode> <Numbers>1</Numbers> </LastFinishCode> </UK_Products_Pipeline> And the XSL file: <?xml version="1.0" encoding='utf-8'?> <xsl:stylesheet xmlns:msxsl="urn:schemas-microsoft-com:xslt" version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html"/> <xsl:template match="/"> <html> <head> <title> XSLT with XML included </title> </head> <body style="background-color:lightblue;color:green"> <table cellSpacing="0" border="1" cellPadding="2"> <!-- Set Variables --> <xsl:variable name="external"> <xsl:copy-of select="document('D:\DATA\Marquee\dial_stats_UK.xml')/*"/> </xsl:variable> <!-- Process Data Start --> <xsl:for-each select="//UK_Products_Pipeline/LastFinishCode"> <tr> <xsl:if test="SiteName ='MWB'"> <td> <xsl:value-of select="SiteName"/> </td> <td> <xsl:value-of select="LastFinishCode"/> </td> <td> <xsl:value-of select="Numbers"/> </td> </xsl:if> </tr> </xsl:for-each> <!-- Process File Data Start --> <xsl:call-template name="ExternalData"> <xsl:with-param name="data" select="$external"/> </xsl:call-template> </table> </body> </html> </xsl:template> <xsl:template name="ExternalData"> <xsl:param name="data"/> <xsl:variable name="external"> <xsl:copy-of select="document('D:\DATA\Marquee\dial_stats_UK.xml')/*"/> </xsl:variable> <table cellSpacing="0" border="1" cellPadding="2" style="background-color:white;color:black"> <tr> <td> I do see this. </td> </tr> <!-- Process External Data --> <xsl:for-each select="//UK_Products_Pipeline/LastFinishCode"> <tr> <td> <xsl:value-of select="SiteName"/> </td> </tr> <tr> <xsl:if test="SiteName ='UK'"> <td> <xsl:value-of select="SiteName"/> </td> <td> <xsl:value-of select="LastFinishCode"/> </td> <td> <xsl:value-of select="Numbers"/> </td> </xsl:if> </tr> </xsl:for-each> </table> </xsl:template> </xsl:stylesheet> When the processing takes place the same file is processed again not the second file. I don't know whether or not you can give me any suggestions on what I do wrong here please? A: Change `<xsl:for-each select="//UK_Products_Pipeline/LastFinishCode">` to `<xsl:for-each select="document('file:///D:/DATA/Marquee/dial_stats_UK.xml')/UK_Products_Pipeline/LastFinishCode">` in the template where you want to process data from the second input file. Although a cleaner approach is to write matching templates with a mode for the nodes from the second file you want be processed. Then you just would do: `<xsl:apply-templates select="document('file:///D:/DATA/Marquee/dial_stats_UK.xml')/UK_Products_Pipeline" mode="my-mode"/>` and your templates for that mode would output the table you want.
{ "pile_set_name": "StackExchange" }
Q: NSPredicate multiple conditions no results i'm using a NSPredicate to filter an array in my searchbar. This is my code which works perfectly. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains[cd] %@",searchText]; filteredArray = [NSMutableArray arrayWithArray:[storesArray filteredArrayUsingPredicate:predicate]]; The problem is i want to add a second condition as the name which is the address. How can i do this? I've tried this, but then none of the predicates are working. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains[cd] %@",searchText]; NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"SELF.address contains[cd] %@",searchText]; NSPredicate *fullPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[predicate, predicate1]]; filteredArray = [NSMutableArray arrayWithArray:[storesArray filteredArrayUsingPredicate:fullPredicate]]; A: You can use the OR comparison operator: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains[cd] %@ OR SELF.address contains[cd] %@", searchText, searchText];
{ "pile_set_name": "StackExchange" }
Q: At what height should a door knob be? I'm installing a few new doors, and bought slab doors to save some money. I have a jig for boring the door knob holes, but I'm not sure where on the door to put the hole. Is there a standard height for door knobs? A: According to the International Building Code, door knobs should be between 34" - 48" above the finished floor. International Building Code 2012 Chapter 10 Means of Egress Section 1008 Doors, Gates and Turnstiles 1008.1.9.2 Hardware height. Door handles, pulls, latches, locks and other operating devices shall be installed 34 inches (864 mm) minimum and 48 inches (1219 mm) maximum above the finished floor. Locks used only for security purposes and not used for normal operation are permitted at any height.
{ "pile_set_name": "StackExchange" }
Q: Image button generator for language names I am looking to create jpg/png buttons with text as various language names. But the online tools don't seem to recognize the non-english words like language names for arabic, thai and hindi etc. I tried http://dabuttonfactory.com/ with text as name of the language in local characters and all I see is ??????. Any pointer or online resource to create non-css image buttons would be of great help? Thanks in advance. A: The issue is with the fonts. The online tool you mentioned has limited fonts and none of them support the scripts you want to create buttons for. I just searched around and found this service which apparently has a wider variety of fonts and also lets you to upload your own font. The caveat is that it seems to be a paid service.
{ "pile_set_name": "StackExchange" }
Q: .NET decompiled assembly has an '&' after the type producing build error I have inherited a few assemblies which as far as I know were produced using Visual Studio 2005, .NET Framework 1.1(?), and VB.NET. Unfortunately, the source code is no longer available to me. As a result, I have used dotPeek to decompile the assemblies (as C#) and attempt to reverse engineer the projects. The resulting source code has a few lines that look similar to: // ISSUE: explicit reference operation // ISSUE: variable of a reference type string& szDataDescr = @str; The 'string&' is foreign to me (and Visual Studio too apparently). Visual Studio 2015 is not recognizing this as valid, and I am getting compilation errors. Is the '&' something that dotPeek has added, or is it some legacy .NET construct that was valid way back then? Similar comment appears everywhere the 'type&' pattern is used, so I assume it is associated. A: The & sign after a type name indicates that it's a reference type, and the @ before a variable name generates a reference to that variable. If you tried to compile the code, you'll get an error because the compiler treats & as the bitwise and, and will complain that you used a type as if it were a variable. But that's ok because you didn't get it from a C# source file. Best solution is to use a different decompiler. ILSpy: http://ilspy.net/ .Net Code Reflect: http://www.devextras.com/decompiler/ .Net Reflector: http://www.red-gate.com/products/dotnet-development/reflector/ Check here for more info on what the & does in IL.
{ "pile_set_name": "StackExchange" }
Q: Merging 2 dataframes I am trying to merge the following 2 dataframes. df.head(): x y z w 0 0.0056 11 824 51 1 0.0056 138 546 16 2 0.0056 328 1264 40 3 0.0056 1212 553 91 4 0.0056 1839 388 48 df1.head(): x y z 0 5539.0567 12243 27 1 5873.2923 14474 1540 2 3975.9776 11353 699 3 1508.5975 8250 628 4 66.7913 11812 538 using the following command: df1 = df1.merge(df, how='left',left_on=(['x','y','z']),right_index=True) and the following error crops up: ValueError: len(left_on) must equal the number of levels in the index of "right" In total df has 11458060 rows and df1 has 2528243 rows I don't really know what this means. Can anyone tell me what I might be doing wrong? A: I think you need merge on columns x, y and z: print df1.merge(df, how='left', on=['x','y','z']) Docs. Parameter on in merge: on: Columns (names) to join on. Must be found in both the left and right DataFrame objects. If not passed and left_index and right_index are False, the intersection of the columns in the DataFrames will be inferred to be the join keys
{ "pile_set_name": "StackExchange" }
Q: How to return number of times a base case is reached Just started learning functional programming and I'm having problem getting my head wrapped around it. This is what I currently have, I know why it doesn't work (because comb is immutable) but I can't seem to think how to do what I want to. def countChange(money: Int, coins: List[Int]): Int = { def rCountChange(money: Int, coins: List[Int], comb: Int): Int = { if (money >= coins(0)) rCountChange(money - coins(0), coins, comb) if (money == 0) comb + 1 //base case sequence found if (coins.isEmpty) comb //base case sequence not found rCountChange(money, coins tail, comb) } rCountChange(money, coins, 0) } I thought of making way an array and just appending to it and .length'ing the result but it seems like its just a gimmicky way of getting around using a mutable var. If I replace comb + 1 with println("combination found") it prints the right amount of base cases found so I'm pretty sure it's iterating through all the possibilities properly. Thanks A: You're missing else's at the end of your if's, alternatively you could use return. As it is the function keeps evaluating after it hits the case and doesn't return as you intend it to. In the absence of return keyword Scala treats the result of last expression evaluated as part of a function as return value, in your case it's always rCountChange(money, coins tail, comb) causing infinite recursion. Here: def countChange(money: Int, coins: List[Int]): Int = { def rCountChange(money: Int, coins: List[Int], comb: Int): Int = { if (money >= coins(0)) rCountChange(money - coins(0), coins, comb) else if (money == 0) comb + 1 //base case sequence found else if (coins.isEmpty) comb //base case sequence not found else rCountChange(money, coins tail, comb) } rCountChange(money, coins, 0) } Alternatively: def countChange(money: Int, coins: List[Int]): Int = { def rCountChange(money: Int, coins: List[Int], comb: Int): Int = { if (money >= coins(0)) return rCountChange(money - coins(0), coins, comb) if (money == 0) return comb + 1 //base case sequence found if (coins.isEmpty) return comb //base case sequence not found rCountChange(money, coins tail, comb) } rCountChange(money, coins, 0) }
{ "pile_set_name": "StackExchange" }
Q: list all packages from a repository in ubuntu / debian is there a command to see what packages are available from a certain ppa repository? A: Simple: grep ^Package: /var/lib/apt/lists/ppa.launchpad.net_*_Packages Or more flexible: grep-dctrl -sPackage . /var/lib/apt/lists/ppa.launchpad.net_*_Packages For fancier querying, use apt-cache policy and aptitude as described here: aptitude search '~O LP-PPA-gstreamer-developers' A: grep Package /var/lib/apt/lists/(repo name)_Packages A: I don't know if this is what you're looking for: https://superuser.com/questions/132346/find-packages-installed-from-a-certain-repository-with-aptitude Like it says, Synaptic Package Manager allows you to search by "origin". This isn't programmatic, but it should give you what you're looking for.
{ "pile_set_name": "StackExchange" }
Q: Android RatingBar I'm new to android development I need to create a RatingBar that shows rating according to Application details . My App calculate a value according to user input and it will be shown in RatingBar . That bar only shows the value (eg. 4/5 stars ) according to the calculated value I need to create it that users can't change RatingBar's value directly .They only enter the input and that input calculate some value and that value need to be displayed in RatingBar. Can you please help me to do this? This is the only way than I can think of using RatingBar (according to my knowledge). A: Try this out.I think this will solve your problem This is java code RatingBar ratingBar = (RatingBar)findViewById(R.id.ratingBar1); ratingBar.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { return true; } }); XML code <RatingBar android:id="@+id/ratingBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:numStars="5" android:progress="30" android:clickable="false" android:focusableInTouchMode="false" android:focusable="false" />
{ "pile_set_name": "StackExchange" }
Q: MYSQL: How to JOIN two tables on the same query referencing the same table twice I have two tables. I'm trying to JOIN the sample two tables below with table 1 referencing Table 2 twice. For example if I look at Table 1: Group 2 and Members 7, it should look up the ID in Table 2 and give me an output of: Group Members Name Name 2 7 Blue Dog Table 1 Group Members 2 7 3 8 5 10 Table 2 ID Name 1 Green 2 Blue 3 Yellow 4 Orange 5 Red 6 Elephant 7 Dog 8 Cat 9 Chicken 10 Mouse Any Advice? Thanks A: SELECT Table_1.*, g.Name, m.Name FROM Table_1 INNER JOIN Table_2 AS g ON Table_1.Group=g.ID INNER JOIN Table_2 AS m ON Table_1.Group=m.ID WHERE Table_1.Group=2 AND Table_1.Member=7
{ "pile_set_name": "StackExchange" }
Q: Can we talk to Pioneer 6? My question is relatively simple in the essence that it takes few words to ask, but scientifically may be a nightmare. In 2000, the Goldstone Deep Space Communications Complex sent a message to Pioneer 6, a solar observation probe somewhere out there in space, and successfully communicated with it for a few hours. The question is this: Is there any feasible way of communicating with 6 if one acquired the right antenna and sent the right commands to it? If so, how would one do it, or even find out how to do it? A: It's been done before: in 2014, an amateur group established contact with ISEE-3, another old space probe (launched in 1978) on a heliocentric trajectory. The main obstacles: you need access to a large antenna. There are a few large dishes (25 m) operated by amateurs. The ISEE-3 effort was given time on the (even larger) Arecibo dish. you need to know the communications protocol. For ISEE, NASA assisted by giving information and hardware (a custom transmitter, IIRC). As of 2000, NASA still knew how to contact Pioneer 6, so chances are they'll be able to tell you everything you need to know. you need to know where the spacecraft is. JPL Horizons only has ephemerides until 1999, it seems. I don't know if NASA has better information somewhere else. the probe still has to work, obviously. The ISEE example shows it's possible, and these old designs should be pretty robust (no microelectronics to go haywire from a single cosmic ray strike, for example) Pioneer 6 is in a heliocentric orbit with a period of 311 days. Periapsis 0.81 AU, Apoapsis 0.98 AU. It had a close approach to Earth in 1988. Every ~year it'll pass us at a distance of less than 0.2 AU, your best timeframe for contact is just before and after closest approach (not during, as it'll be on a straight line between us and the Sun at that time).
{ "pile_set_name": "StackExchange" }
Q: array from web content in viewdidload order of operations is weird I'm working on a new app which is all about organizing information from web content. It will be a finance app for monitoring the dividend yields of the dow jones. To do this will require a few steps, but I'm working on step one right now. I want to take the 30 companies in the dow jones, look up their current yield, and then rank them according to that number. Right now I'm updating an array to give me the yields of all 30 companies (i.e. [2.7, 3.6, 5.5, 1.3,etc...]). Here is my current code with my question below: let dowDic = ["MMM", "AXP", "AAPL", "BA", "CAT", "CVX", "CSCO", "KO", "DIS", "DD", "XOM", "GE", "GS", "HD", "IBM", "INTC", "JNJ", "JPM", "MCD", "MRK", "MSFT", "NKE", "PFE", "PG", "TRV", "UTX", "UNH", "VZ", "V", "WMT"] var dowYield = [1.11, 2.11, 3.11, 4.11, 5.11, 6.11, 7.11, 8.11, 9.11, 1.11, 1.11, 2.11, 3.11, 4.11, 5.11, 6.11, 7.11, 8.11, 9.11, 1.11, 1.11, 2.11, 3.11, 4.11, 5.11, 6.11, 7.11, 8.11, 9.11, 1.11] var counter = 0 @IBOutlet var label: UILabel! @IBAction func refresh(sender: AnyObject) { print(dowYield) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. print(dowDic.indexOf("WMT")) for x in dowDic { print(x) let url = NSURL(string:"http://finance.yahoo.com/q?s=\(x)")! print(url) let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in //will happen after complete if let urlContent = data { let webContent = NSString(data: urlContent, encoding: NSUTF8StringEncoding) let websiteArray = webContent?.componentsSeparatedByString("<th scope=\"row\" width=\"48%\">Div &amp; Yield:</th><td class=\"yfnc_tabledata1\">") if websiteArray!.count > 0 { let nextWebsiteArray = websiteArray![1].componentsSeparatedByString(" </td></tr>") if nextWebsiteArray.count > 0 { let websiteSum = nextWebsiteArray[0].componentsSeparatedByString(" (") if websiteSum.count > 0 { let finalYield = websiteSum[1].componentsSeparatedByString("%") let WTF = Double(finalYield[0]) print(finalYield[0]) self.dowYield[self.counter] = WTF! self.counter++ } } } } } task.resume() } print("flag") print(dowYield) } I want the app to update the array 'dowYield' and access it later in the viewDidLoad, but I can only get the updated print out using a button. The print screen currently prints out the stock symbol and url first, all of them. Then it jumps down to the bottom of the code and prints the 'flag' text and then the original, unedited array of 'dowYield'. Then it one by one prints out the new Yields. Any insight on the order of operations here and how to access the updated array within the viewDidLoad for future operations i want to do with that new information? Thank you! A: This is how async code works. You start an async job running and it continues on it's own until it's done, some time later. Think of this as sending somebody off to run an errand for you. The instant after you ask them to run the errand, it still isn't done, and you don't know exactly how long it will take for them to finish. So you go off and do other things, waiting for them to come back and tell you the work is done. That is what the completion block in your data task is for. It's code that gets saved for later and executed once the data task is finished running. You can be certain that that code won't be called until after viewDidLoad exits. What you want to do is to add a call, inside the completion block that uses dispatch_async(dispatch_get_main_queue()) to update your UI on the main thread once the data has been downloaded.
{ "pile_set_name": "StackExchange" }
Q: Writing a Go program that acts as an executable as well as a module I am currently trying to do my first steps in Go. Now I've ported a tool that I once written in Node.js, and I was surprised how easy that was, and how clean and concise the code is. Anyway, I've got a question that I was not able to figure out by myself so far: In Node.js it's possible to add the main entry as well as the bin entry to the package.json file. This basically means that you can create a module that works as a executable when installed using $ npm install -g <module> but as a library when installed using $ npm install <module> The trick here is that the first one uses the bin entry, which then internally uses a file from the module's lib folder, but the second version directly points to this lib file. So ... now I would like to have the same behavior in Go: I would like to write a package that you can directly run as an executable, but that as well you can import into another application as a library. How would I do that? Obviously I can't put two calls to package into a .go file. Any hints? A: What about the solution in the following blog post? http://dan.munckton.co.uk/blog/2013/06/21/go-lang-packaging-creating-a-library-that-bundles-an-executable/
{ "pile_set_name": "StackExchange" }
Q: usermod says account doesn't exist but adduser says it does I run the command usermod -a -G dialout amashreghi but I get amashreghi doesn't exists, however, when I try to add the user using adduser adduser amashreghi It says that amashreghi already exists. What's going on?! A: To edit /etc/group directly use vigr From man vigr NAME vipw, vigr - edit the password, group, shadow-password or shadow-group file SYNOPSIS vipw [options] vigr [options] DESCRIPTION The vipw and vigr commands edits the files /etc/passwd and /etc/group, respectively. With the -s flag, they will edit the shadow versions of those files, /etc/shadow and /etc/gshadow, respectively. The programs will set the appropriate locks to prevent file corruption. When looking for an editor, the programs will first try the environment variable $VISUAL, then the environment variable $EDITOR, and finally the default editor, vi(1). Hence, you can edit the /etc/group file with sudo vigr The format of group entries can be found in man. From man group: NAME group - user group file DESCRIPTION The /etc/group file is a text file that defines the groups on the system. There is one entry per line, with the following format: group_name:password:GID:user_list The fields are as follows: group_name the name of the group. password the (encrypted) group password. If this field is empty, no password is needed. GID the numeric group ID. user_list a list of the usernames that are members of this group, separated by commas. FILES /etc/group
{ "pile_set_name": "StackExchange" }
Q: Rails 3 recommendations for good javascript tutorials I am very familiar with javascript and jquery in general, but I am looking for a good guide on how it works in rails 3.0. I understand that the javascript libraries have been rewritten in rails 3. (I never used rails 2.0) It seems there are no railsguides for this. A: I found this tutorial useful: http://www.simonecarletti.com/blog/2010/06/unobtrusive-javascript-in-rails-3/
{ "pile_set_name": "StackExchange" }
Q: Python - I dont understand this ID situation I have read documentation about id() this work like this myvar='asd' print id(myvar) But in this code i cant understand how is it work from Tkinter import * import time import random class pelota: def __init__(self,canvas,raqueta,color): self.canvas=canvas self.raqueta=raqueta self.id=canvas.create_oval(10,10,25,25, fill=color) self.canvas.move(self.id,250,125) empezar=[-5,-4,-3,-2,-1,1,2,3,4,5] random.shuffle(empezar) self.x=empezar[0] self.y=-3 self.canvas_height = self.canvas.winfo_height() self.canvas_width = self.canvas.winfo_width() def golpea_raqueta(self, pos): raqueta_pos = self.canvas.coords(self.raqueta.id) if pos[2] >= raqueta_pos[0] and pos[0] <= raqueta_pos[2]: if pos[3] >=raqueta_pos[1] and pos[3] <= raqueta_pos[3]: Im talking about this specific lines self.raqueta=raqueta raqueta_pos = self.canvas.coords(self.raqueta.id) How id can work on (self.raqueta.id)? FULL CODE from Tkinter import * import time import random class pelota: def __init__(self,canvas,raqueta,color): self.canvas=canvas self.raqueta=raqueta self.id=canvas.create_oval(10,10,25,25, fill=color) self.canvas.move(self.id,250,125) empezar=[-5,-4,-3,-2,-1,1,2,3,4,5] random.shuffle(empezar) self.x=empezar[0] self.y=-3 self.canvas_height = self.canvas.winfo_height() self.canvas_width = self.canvas.winfo_width() def golpea_raqueta(self, pos): raqueta_pos = self.canvas.coords(self.raqueta.id) if pos[2] >= raqueta_pos[0] and pos[0] <= raqueta_pos[2]: if pos[3] >=raqueta_pos[1] and pos[3] <= raqueta_pos[3]: return True return False def dibujar(self): self.canvas.move(self.id,self.x,self.y) pos = self.canvas.coords(self.id) if pos[1]<=0: self.y=3 if pos[0]<=0: self.x=3 if pos[2]>= self.canvas_width : self.x=-3 if self.golpea_raqueta(pos) == True: self.y=-3 if pos[3] >= self.canvas_height : self.y=-3 class raqueta: def __init__(self,canvas,color): self.canvas=canvas self.id=self.canvas.create_rectangle(10,10,100,20, fill=color) self.canvas.move(self.id , 200,300) self.x = 0 self.canvas_width = self.canvas.winfo_width() self.canvas.bind_all('<KeyPress-Left>', self.izqu) self.canvas.bind_all('<KeyPress-Right>', self.dere) def dibujar(self): self.canvas.move(self.id,self.x,0) pos = self.canvas.coords(self.id) if pos[0]<=0: self.x=0 if pos[0]>0: self.x=0 elif pos[2]>=self.canvas_width: self.x=0 def izqu(self,evt): self.x=-20 def dere(self,evt): self.x=20 vent= Tk() vent.title('mipong') vent.resizable(0,0) vent.wm_attributes('-topmost',1) canvas= Canvas(vent, width=500,height=500, bd=0,highlightthicknes=0) canvas.pack() vent.update() raqueta= raqueta(canvas,'blue') pelota=pelota(canvas,raqueta,'red') #help(Tkinter.Canvas.winfo_height) while 1: pelota.dibujar() raqueta.dibujar() vent.update_idletasks() vent.update() time.sleep(0.01) A: When you create an item on the canvas, it returns a unique identifier. In the code you posted, you assign the identifier to self.id. While the name is similar to the built-in function named id, they are completely unrelated. To avoid confusion, you can rename self.id to self.canvas_id
{ "pile_set_name": "StackExchange" }
Q: Avoiding floating xtable in knitr hides the caption of the table I am using knitr to create the output of the table. The problem here is when I try to avoid float to the xtable the caption doesn't appear. The option I used to avoid float is floating="F" in print(xtable) I have the following sample code used on the knitr. \documentclass[12pt,Arial]{article} \usepackage[sc]{mathpazo} \usepackage[T1]{fontenc} \usepackage[left=0.7in, right=0.8in, bottom=0.6in, top=0.8in]{geometry} \usepackage{float} \begin{document} \section{start} <<comment=NA,results='asis',echo=FALSE>>= library(xtable) jd1 <- structure(c(23.16, 27.14, 31.03, 30.11, 33.03, 38.78, 23.45, 26.96, 30.93, 29.85, 32.53, 35.99, -2.965, -0.1998, 0.08065, 0.2588, 0.5829, 6.042, 0.0001466, 0.1369, 0.3252, 0.629, 0.9057, 6.042), .Dim = c(6L, 4L), .Dimnames = list(c("Min.", "1st Qu.", "Median", "Mean", "3rd Qu.", "Max."), c("observed", "modeled", "obsdmod", "aobsdmod"))) names(jd1)<- c("Observed","Modeled","Observed-Modeled","|Observed-Modeled|") print(xtable(jd1,caption="Summary of table for observed and modeled temperatures at station T1"),type="latex",floating="F") @ \end{document} A: Yes, only floats have captions. If it's not floating, you'll have to use some other mechanism to document it. Maybe just put text immediately before it telling what it is? It does feel, though, like you're not really asking the question you want to ask. Why don't you want it to float? If you want it to look like a float, but don't want LaTeX to have any say in the placement, there are better methods. EDIT: Aha, I thought so. You can achieve \begin{table}[H] with the table.placement option. > print(xtable(cbind(1,2)), table.placement="H") % latex table generated in R 2.15.1 by xtable 1.7-0 package % Sat Jul 6 08:06:52 2013 \begin{table}[H] ...
{ "pile_set_name": "StackExchange" }
Q: Is it haram to visit other religious places, e.g. temples and churches? I often go out with my friends (most of them are non-Muslim) and visit their place of worship and it feels good as I gain knowledge about what and how they worship (I never worship or pray with them). Is it haram to visit other religious places in Islam? NOTE: ALLAH(Swt) has implied that it is incumbent on every Muslim to gain knowledge. A: https://m.youtube.com/watch?v=L5Cyv5bDEe0 ^ This is Ahmed Deedat. A fine example of what would happen if Muslims studied other religions for knowledge. Whether it being by reading a book or going to the source itself (church, temple, etc). Being open minded and having discourse with one another would eventually lead to great things. Sharing ideas is crucial to a healthy society and much can be learned, even if you are reading about another religion. You never know when it could be useful, and because of your knowledge you may even get a few other people to switch to the halal side. You can all thank me in the hereafter for contributing to good deeds.
{ "pile_set_name": "StackExchange" }
Q: How to avoid reflections on glass pane in museum? I want to photograph objects exhibited behind a glass pane in a museum. How can I avoid the annoying reflections on the glass pane? The example shown here is from the Kunstkammer of the Kunsthistorisches Museum in Wien, a large collection of valuable artwork belonging to the Habsburg dynasty. This one is a lead statuette of about 0.5 m size from 1759, titled Gefesselter Prometheus (Prometheus Bound), by the sculptor Johann Baptist Hagenauer (1732–1810). The sculpture is behind a glass pane, and you can see that other objects in the same room are reflected on the glass pane. See on Prometheus's right arm for example. I'd like to reduce the annoying reflections as much as possible. Click on the pictures to get the full versions. That museum allows photography, as long as you don't use a flash or tripod. This is great for visitors like me, and certainly refreshing compared to the strict attitude of some museums around here. But I'm still just an ordinary visitor, so I can't put up curtains or change the lighting of the room. But I hope you can still give me hints I can use even with these constraints. I know that the single most important way to avoid reflections on glass is to change the position of the camera. Indeed, if I were to lower the camera, I'd get even worse reflections as you can see on the photo below. The above photo is after choosing the position of the camera the best I can, while still showing the eagle eating Prometheus's liver. I will note also that the above photograph is a bit blurry from motion. I know I can avoid that by retaking the photo until I manage to hold the camera more steady, or using a larger lens. That is not the topic of this question, I'm asking how to reduce the reflections. The above photo is cropped, I took it with a Panasonic DMC-TZ70 compact camera at 1/2 s exposure time, f/3.3 aperture (the largest for this camera); the photo below uses 1/3 s exposure time. A: Your only remedy will be careful selection of the camera position and mounting a polarizing filter. As you are composing and focusing, you rotate the polarizing filter for maximum reflection mitigation. If the reflections remain, select another viewpoint. Rotating the polarizing filter as you compose is the key to finding a setup with minimum reflections.
{ "pile_set_name": "StackExchange" }
Q: To get the name from input file type and display in a p tag through javascript. I am trying to get the name from input file type to display the name in a p tag, below is my code, advance thanx to all. <script type="text/javascript"> var path = document.getElementById("photo").value; var filename = path.substring(path.lastIndexOf("/") + 1); document.getElementById("log").innerHTML = filename; </script> <input type="file" id="photo"/> <p id="log"></p> A: Try below code... Demo Fiddle var input = document.getElementById("photo"); input.onclick = function () { this.value = null; }; input.onchange = function () { var path = input.value; var filename = ""; if(path.lastIndexOf("\\") != -1) filename = path.substring(path.lastIndexOf("\\") + 1,path.length); else filename = path.substring(path.lastIndexOf("/") + 1,path.length); document.getElementById("log").innerHTML = filename; };
{ "pile_set_name": "StackExchange" }
Q: google play warns about added permission 'android.permission.READ_CALL_LOG' I've just tried to submit a new version of my app without any changes in the permissions. However, google play's upload apk tells me that I've added the permission 'android.permission.READ_CALL_LOG', which I didn't. These are currently my permissions: <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_CONTACTS"/> <uses-permission android:name="android.permission.READ_PHONE_STATE"/> Any ideas what the reason could be for this? (I don't want to add a new permission, my users don't like that very much) A: I had this: <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="14" /> Which led to that in aapt dump badging: uses-permission:'android.permission.READ_CALL_LOG' uses-implied-permission:'android.permission.READ_CALL_LOG','targetSdkVersion < 16 and requested READ_CONTACTS' Then I changed it to that: <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="16" /> Now the implied permission went away.
{ "pile_set_name": "StackExchange" }
Q: What happens to the drones at the end of episode 6? At the end of the sixth episode of Jinrui wa Suitai Shimashita the two drones in form of black panels have handles attached to them and placed in a wooden shelf with a note near them saying "1 hour of winding = 1 minute". It's not very clear from the characters' lines what this all means. Can't drones recharge from electric sockets? I thought Pion just did at the beginning of the episode? Why resort to manual winding mechanism? What's really going on? A: Okay, I was a bit confused as well, but I think I know what happened at the end. So that Pion and Oyage could stay on Earth instead of going back into space, the main character (Watashi) destroys the electric generator, their only source of power. Near the end, Pion and Oyage are at about 15% power. So, Watashi converts their batteries into wind-up batteries to get past the electricity problem. As said on the sign, 1 hour of winding= 1 minute. They're still okay. :) And, if it helps, Chris Seibenmann on https://cks.mef.org/space/rtblog/anime/JinruiChronologicalOrder provided an explanation on the timeline of Jinrui wa Suitai Shimashita, and the episodes go: 12, 7-8, 5-6, 1-2, 9, and ending with 3-4. This explains why you don't see them anymore, because the later episodes are flashbacks, albeit episode 9.
{ "pile_set_name": "StackExchange" }