Proper way to install Torch Down

Question: On the recommendation of a gutter installer I hired a roofer to install torch down over the front porch awning. The gutter installer pointed out that the person who did the awning didn't do it right because they put the shingles under the drip edge instead of on top of it.  The awning is relatively flat and had a much cheaper grade of roofing than the main roof.
I hired a roofer to install torch.  The agreement I had with the roofer was that there would be 3/4" overhang all the way around the porch awning, which has a 56' square foot surface.  Upon completion, I noticed that he shorted the overhang on one side and one side has no overhang at all.  Is this a problem?
Additionally one of the corners doesn't appear to have been heated up enough and it is loose, and not making contract with the metal drip edge.  This is in the same area where there is no overhang.  The roofer said he detected a soft spot while working on the roof, but made no mention of it until after it was completed.  After pointing out the soft spot, I took a chisel and determined there was dry rot about 1/2" through the top of one of the rafters and adjacent plywood.  Additionally a fascia board in the corner was completely rotted out and will need to be replaced.  The roofer recommended I use wood filler to fill in the fascia board, even though there was nothing left of it.  And I wonder why the roofer didn't mention and repair the rot before boarding over. I assume the fascia needs to be redone, but what about the rafter with 1/2" of rot at the top, and the adjacent area that rot.  I scraped some of the dry rot out and decided to let it sit for a few days to dry out until I can figure out what to do about all this.  The torch down was applied over the existing shingle material.  A drip edge was installed over that, and another layer of torch was applied over the drip edge, but about 1/2 of one side has no overhang.  The bottom side of the awning appears to have sufficient overhang.
I need additional information.  I don't know what you mean by scab out 2".  Are you referring to scabbing out 2" on the rafter?  Or 2" in adjacent plywood?  Or 2" on the opposite side of the rafter?  Does the torch need to come off?  Also, I had made a mistake and the torch was applied over compound 90 in a two layer approach:  one layer under the drip edge, and one layer above the drip edge.
Answer: For starters, torch down is a rubber product. It should NOT be installed over asphalt shingles. Swelling and contracting will eventually allow the asphalt shingles to wear a hole in the torchdown membrane from the underside. The same applies for rubber membranes.
You are correct about the drip edge needing to be under the roofing material. This applies to ALL roof coverings.
Your roofer should have mentioned the soft spot prior to covering it up. That's complete irresponsibility. Roofers typically don't repair facia but it shouldn't be beyond a decent roofers skill set.
As for what the rafter you need repaired... Unless there's access from below, a portion of your new touchdown will need to be removed, along with the decking above. Unless the rafter is totally rotted out, I'd scab another 2x to the side of the rafter in question instead of removing it completely.
Additional details per OP questions:
The recommended overhang for torch down is 1/2".
For roof pitches below 12/4 torch down or rubber are my recommendation.
To my knowledge, it's not standard practice to double up material around the drip edge.
Since I'm unsure what your rafters are, I used a generic term "2x" ( pronounced 2 by ), which can mean anything from 2x2 to 2x12.
Yes, if there's any bad decking it should be replaced, but it can be spot fixed from rafter to rafter.
Additional Info
Decking is a generic term... Meaning your roof deck ( sheathing ). Spot fixing means cutting out the bad decking from rafter center to rafter center.
I've never heard of Timbor. I ALWAYS replace rotten/dry rotted decking.
To repair the damaged rafter, screw or nail a new rafter to the side of the bad one.
Comment: How much overhang on all sides should there be with torch down?  What type of repair would you do to the rafter?
Comment: Is it considered proper to do a double layer of torch?  one under the drip edge and one above it?
Comment: Is torch the best application for the porch awning given the conditions and age of the rest of the roof?  The rest of the house is in much better shape and has a more expensive type of composition shingle.
Comment: What do you mean by 2x to the side of the rafter?  The rafter damage is up to 2" from the top in some places, and approximately 1/2" or a little more deep from the sides.  When rot is detected in the plywood, do you remove all the plywood?  Or just where it is detected?
Comment: What do you mean by bad decking?  And spot fixing from rafter to rafter?  I only see one bad rafter, and it has a bad area from that is about 2" from the top in a 2 x 6, and extends about 2 feet, but the bad area from the top tapers off from 2" from the top to 0" from the top over the two foot length of dry rot.  And the bad area in the rafter is at least 1/2" deep from the sides.
Comment: Also, I have new information and it looks like the torch down was placed over compound 90, which is not the same material as the rest of the house.  The rest of the house has composition shingles.
Comment: How well does a product  called Timbor work for treating dry rot?  Is it worth it?  Can Timbor be used with rubbing alcohol instead of water?
Comment: Should the rafter be braced with another rafter that is screwed in?

Proper way to install Torch Down


Sql query fills /tmp and takes minutes to run

Question: I have a query, which is not operating on a lot of data (IMHO) but takes a number of minutes (5-10) to execute and ends up filling the /tmp space (takes up to 20GB) while executing. Once it's finished the space is freed again.
The query is as follows:
SELECT c.name, count(b.id), c.parent_accounting_reference, o.contract, a.contact_person, a.address_email, a.address_phone, a.address_fax, concat(ifnull(concat(a.description, ', '),''), ifnull(concat(a.apt_unit, ', '),''), ifnull(concat(a.preamble, ', '),''), ifnull(addr_entered,''))                FROM
                booking b
            join visit v on (b.visit_id = v.id)
            join super_booking s on (v.super_booking_id = s.id)
            join customer c on (s.customer_id = c.id)
            join address a on (a.customer_id = c.id)
            join customer_number cn on (cn.customer_numbers_id = c.id)
            join number n on (cn.number_id = n.id)
            join customer_email ce on (ce.customer_emails_id = c.id)
            join email e on (ce.email_id = e.id)
            left join organization o on (o.accounting_reference = c.parent_accounting_reference)
            left join address_type at on (a.type_id = at.id and at.name_key = 'billing')
            where s.company_id = 1
            and v.expected_start_date between '2015-01-01 00:00:00' and '2015-02-01 00:00:00'
            group by s.customer_id
            order by count(b.id) desc

And the explain plan for the same is:
+----+-------------+-------+--------+--------------------------------------------------------------+---------------------+---------+--------------------------------------+-------+----------------------------------------------+
| id | select_type | table | type   | possible_keys                                                | key                 | key_len | ref                                  | rows  | Extra                                        |
+----+-------------+-------+--------+--------------------------------------------------------------+---------------------+---------+--------------------------------------+-------+----------------------------------------------+
|  1 | SIMPLE      | s     | ref    | PRIMARY,FKC4F8739580E01B03,FKC4F8739597AD73B1                | FKC4F8739580E01B03  | 9       | const                                | 74088 | Using where; Using temporary; Using filesort |
|  1 | SIMPLE      | ce    | ref    | FK864C4FFBAF6458E3,customer_emails_id,customer_emails_id_2   | customer_emails_id  | 9       | id_dev.s.customer_id                 |     1 | Using where                                  |
|  1 | SIMPLE      | cn    | ref    | FK530F62CA30E87991,customer_numbers_id,customer_numbers_id_2 | customer_numbers_id | 9       | id_dev.ce.customer_emails_id         |     1 | Using where                                  |
|  1 | SIMPLE      | c     | eq_ref | PRIMARY                                                      | PRIMARY             | 8       | id_dev.s.customer_id                 |     1 |                                              |
|  1 | SIMPLE      | e     | eq_ref | PRIMARY                                                      | PRIMARY             | 8       | id_dev.ce.email_id                   |     1 | Using index                                  |
|  1 | SIMPLE      | n     | eq_ref | PRIMARY                                                      | PRIMARY             | 8       | id_dev.cn.number_id                  |     1 | Using index                                  |
|  1 | SIMPLE      | v     | ref    | PRIMARY,FK6B04D4BEF4FD9A                                     | FK6B04D4BEF4FD9A    | 8       | id_dev.s.id                          |     1 | Using where                                  |
|  1 | SIMPLE      | b     | ref    | FK3DB0859E1684683                                            | FK3DB0859E1684683   | 8       | id_dev.v.id                          |     1 | Using index                                  |
|  1 | SIMPLE      | o     | ref    | org_acct_reference                                           | org_acct_reference  | 767     | id_dev.c.parent_accounting_reference |     1 |                                              |
|  1 | SIMPLE      | a     | ref    | FKADDRCUST,customer_address_idx                              | FKADDRCUST          | 9       | id_dev.c.id                          |   256 | Using where                                  |
|  1 | SIMPLE      | at    | eq_ref | PRIMARY                                                      | PRIMARY             | 8       | id_dev.a.type_id                     |     1 |                                              |
+----+-------------+-------+--------+--------------------------------------------------------------+---------------------+---------+--------------------------------------+-------+----------------------------------------------+

It appears to be using the correct indexes and such so I can't understand why the large usage of /tmp and long execution time.
Comment: You appear to be misusing a nonstandard MySQL extension to `GROUP BY`. This makes it hard to guess the intent of your query. Read this.  https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html
Answer: Your query uses a temporary table, which you can see by the Using temporary;  note in the EXPLAIN result. Your MySQL settings are probably configured to use /tmp to store temporary tables.
If you want to optimize the query further, you should probably investigate why the temporary table is needed at all. The best way to do that is gradually simplifying the query until you figure out what is causing it. In this case, probably just the amount of rows needed to be processed, so if you really do need all this data, you probably need the temp table too. But don't give up on optimizing on my account ;)
By the way, on another note, you might want to look into COALESCE for handling NULL values.
Answer: You're stuck with a temporary table, because you're doing an aggregate query and then ordering it by one of the results in the aggregate. Your optimizing goal should be to reduce the number of rows and/or columns in that temporary table.
Add an index on visit.expected_start_date. This may help MySQL satisfy your query more quickly, especially if your visit table has many rows that lie outside the date range in your query.
It looks like you're trying to find the customers with the most bookings in a particular date range.
So, let's start with a subquery to summarize the least amount of material from your database.
        SELECT count(*) booking_count, s.customer_id
          FROM  visit v
          JOIN  super_booking s ON v.super_booking_id = s.id
          JOIN  booking b ON v.id = b.visit_id
         WHERE  v.expected_start_date <= '2015-01-01 00:00:00'
           AND  v.expected_start_date >  '2015-02-01 00:00:00'
           AND  s.company_id = 1
         GROUP BY s.customer_id

This gives back a list of booking counts and customer ids for the date range and company id in question.  It will be pretty efficient, especially if you put an index on expected_start_date in the visit table
Then, let's join that subquery to the one that pulls out all that information you need.
 SELECT c.name, booking_count, c.parent_accounting_reference,
        o.contract,
        a.contact_person, a.address_email, a.address_phone, a.address_fax,
        concat(ifnull(concat(a.description, ', '),''),
               ifnull(concat(a.apt_unit, ', '),''),
               ifnull(concat(a.preamble, ', '),''),
               ifnull(addr_entered,''))
   FROM (
        SELECT count(*) booking_count, s.customer_id
          FROM  visit v
          JOIN  super_booking s ON v.super_booking_id = s.id
          JOIN  booking b ON v.id = b.visit_id
         WHERE  v.expected_start_date <= '2015-01-01 00:00:00'
           AND  v.expected_start_date >  '2015-02-01 00:00:00'
           AND  s.company_id = 1
         GROUP BY s.customer_id
         ) top
   join customer c on top.customer_id = c.id
   join address a on (a.customer_id = c.id)
   join customer_number cn on (cn.customer_numbers_id = c.id)
   join number n on (cn.number_id = n.id)
        join customer_email ce on (ce.customer_emails_id = c.id)
        join email e on (ce.email_id = e.id)
        left join organization o on (o.accounting_reference = c.parent_accounting_reference)
        left join address_type at on (a.type_id = at.id and at.name_key = 'billing')
  order by booking_count DESC

That should speed your work up a whole bunch, by reducing the size of the data you need to summarize.
Note: Beware the trap in date BETWEEN this AND that.  You really want
     date >= this
 AND date < that

because BETWEEN means
    date >= this
AND date <= that


What should I do when I see blank screen?

Question: i was installing an application using ubuntu software center and screen went blank i waited a while but nothing appearing no desktop so pretty much expected result is that i rebooted manually please correct this or tell me what should i do,iam not running any screensavers nor
does the virtual console work
Comment: STOP! HAMMERTIME?!
Comment: @garbagecollector: Why to flag it as screensaver when he is saying that he is NOT running a screensaver?. I remove the tag as I felt that it was a mistake.
Comment: @Javier he had that there from the beginning, I assumed it was there for a reason. probably for the best. Thanks.
Answer: REISUB time!!!
Just press ALT+Pet Sys and type slowly REISUB, one key at time. If it happens often you should probably investigate why is it happening. Ubuntu (and linux) is supposed to be rock-solid because it's usually rock-solid ;). This behaviour is anything but normal.


All the columns are in one column

Question: All I did was to import libraries and read the data. This is what I get:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 181691 entries, 0 to 181690
Data columns (total 1 columns):
eventid,iyear,imonth,iday,approxdate,extended,resolution,country,country_txt,region,region_txt,provstate,city,latitude,longitude,specificity,vicinity,location,summary,crit1,crit2,crit3,doubtterr,alternative,alternative_txt,multiple,success,suicide,attacktype1,attacktype1_txt,attacktype2,attacktype2_txt,attacktype3,attacktype3_txt,targtype1,targtype1_txt,targsubtype1,targsubtype1_txt,corp1,target1,natlty1,natlty1_txt,targtype2,targtype2_txt,targsubtype2,targsubtype2_txt,corp2,target2,natlty2,natlty2_txt,targtype3,targtype3_txt,targsubtype3,targsubtype3_txt,corp3,target3,natlty3,natlty3_txt,gname,gsubname,gname2,gsubname2,gname3,gsubname3,motive,guncertain1,guncertain2,guncertain3,individual,nperps,nperpcap,claimed,claimmode,claimmode_txt,claim2,claimmode2,claimmode2_txt,claim3,claimmode3,claimmode3_txt,compclaim,weaptype1,weaptype1_txt,weapsubtype1,weapsubtype1_txt,weaptype2,weaptype2_txt,weapsubtype2,weapsubtype2_txt,weaptype3,weaptype3_txt,weapsubtype3,weapsubtype3_txt,weaptype4,weaptype4_txt,weapsubtype4,weapsubtype4_txt,weapdetail,nkill,nkillus,nkillter,nwound,nwoundus,nwoundte,property,propextent,propextent_txt,propvalue,propcomment,ishostkid,nhostkid,nhostkidus,nhours,ndays,divert,kidhijcountry,ransom,ransomamt,ransomamtus,ransompaid,ransompaidus,ransomnote,hostkidoutcome,hostkidoutcome_txt,nreleased,addnotes,scite1,scite2,scite3,dbsource,INT_LOG,INT_IDEO,INT_MISC,INT_ANY,related    181691 non-null object
dtypes: object(1)

Why did this happen and how can I fix it?
Please help.
Comment: Do you mind providing information about the how did you read the dataframe?
Comment: data = pd.read_csv("/kaggle/input/gtd/globalterrorismdb_0718dist.csv", "encoding='ISO-8859-1")
Comment: You should probably read stackoverflow's [how to ask](https://stackoverflow.com/help/how-to-ask) article. Notably: _DO NOT post images of code, data, error messages, etc. - copy or type the text into the question. Please reserve the use of images for diagrams or demonstrating rendering bugs, things that are impossible to describe accurately via text._
Comment: Oh, thank you. I am new to these things, sorry.
Answer: Probably you are just missing the separator.
data = pd.read_csv("/kaggle/input/gtd/globalterrorismdb_0718dist.csv", encoding='ISO-8859-1', sep=",")

Comment: I am getting this error:

TypeError: parser_f() got multiple values for argument 'sep'
Comment: Thank you so much! I would upvote but my reputation is under 15, sorry.
Comment: Mark the answer as correct so it is not searchable as open any more.

All the columns are in one column


"An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported."

Question: When I run following code:
public ActionResult Complete()
        {
            try
            {
                VeriTabanDataContext db = new VeriTabanDataContext();
                db.Persons.InsertOnSubmit(_person);
                db.SubmitChanges();
                return View(_person);
            }
            catch (Exception ex)
            {
                return RedirectToAction("Error", ex);
            }
        }

I'm getting following Exception, on SubmitChanges();
"An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext.  This is not supported."

Here "_person" object is taken from Session and is a good standing. Note: _person is a result of multistep wizard and this is the place where I add new Person object to the DB.
My Person table has 9 relations and it's not ok for me to add version column for each of them as is suggested by some geeks around
I've investigated this problem  a lot and spend 2 days on it and still couldn't solve it.  Some of the  workarounds that other suggest don't solve my problem, and others seem to be just dirty workaround. Do you experts have a good solution for this problem, considering that Person class has many relations and also it isn't ok to add a column to the tables.
I also want to note that I've tried to use 'db.Persons.Attach(_person) ' and setting  db.DeferredLoadingEnabled = false; THis time I'm not getting any Exception but data is NOT saved to DB
Answer: I create a class called applicationController which derives from Controller. Then i make all of my controller classes derive from this. The applicationController class has a constrcutor which creates a new instance of my repository (or datacontext in your instance) which is used throughout the application:
     public class ApplicationController : Controller
     {
          private VeriTabanDataContext _datacontext;

          public ApplicationController() : this(new VeriTabanDataContext())
          {
          }

          public ApplicationController(VeriTabanDataContext datacontext)
          {
               _datacontext = datacontext;
          }

          Public VeriTabanDataContext DataContext
          {
               get { return _datacontext; }
          }
     }

Then you can use this in all of your controllers
public class MyController : ApplicationController
{
     public ActionResult Complete()
     {
           DataContext.Persons.InsertOnSubmit(_person);
           DataContext.SubmitChanges();
           return View(_person);
     }
}

Not on my PC with VS installed at the moment so not tested this code....
Hope this resolves the issue -Mark
Comment: I've not tried it yet, but this would solve the problem if my object was taken from on context and being tried to be inserted in another context. But my object is newly created and is not tracked by any context yet. So I suspect this will not work. I just wanted so say my opinion before trying it and try later if my thinking is proved to be wrong.
Comment: should work as you will only have one instance of the datacontext where at the moment it looks like you are creating multiple instances within each controller action.
Comment: does this approach have any negative side effects?. Is this context-persistent through all requests? I guess not.
Answer: Can you do the following:
var foundPerson = db.Person.FirstOrDefault( p => p.Id == _person.Id);

if(foundPerson == null)
{
  db.InsertOnSubmit(_person);
}else{
  Mapper.Map(_person,foundPerson);
}

db.SubmitChanges();
return View(_person);

Where I have used AutoMapper to map from one entity to another. To do this add the reference to AutoMapper to your project and in your start up code for the application you will need to configure your mappings, for the above to work you would need:
Mapper.CreateMap<Person, Person>().ForMember(src => src.Id, opt => opt.Ignore());

Comment: `foundPerson.Name = _person.Name` will not work for me, because this way I'll have to copy more than 30 fields. Also if count dependent childe objects then I'll have to do this kind of assignment for more than 100 fields. So this solution is not acceptable unless there is easier way to update `foundPerson`. Thanks for answer.


Attribute Already Defined When Using HoloEverywhere and UnifiedPreference

Question: I have a project that is currently using ActionBarSherlock, Crouton, and UnifiedPreference which works (compiles, runs without issue on devices and emulator for Android 2.3.3+). I want to add HoloEverywhere so that I can keep a unified interface when it runs on Gingerbread devices. Once I added HoloEverywhere to the mix I get the following AAPT errors:
[2012-12-14 12:47:04 - MyApp] C:\git\myrepo\UnifiedPreference\library\res\values\atrs.xml:7: error: Attribute "id" has already been defined
[2012-12-14 12:47:04 - MyApp] C:\git\myrepo\UnifiedPreference\library\res\values\atrs.xml:11: error: Attribute "summary" has already been defined
[2012-12-14 12:47:04 - MyApp] C:\git\myrepo\UnifiedPreference\library\res\values\atrs.xml:13: error: Attribute "breadCrumbTitle" has already been defined
[2012-12-14 12:47:04 - MyApp] C:\git\myrepo\UnifiedPreference\library\res\values\atrs.xml:15: error: Attribute "breadCrumbShortTitle" has already been defined
[2012-12-14 12:47:04 - MyApp] C:\git\myrepo\UnifiedPreference\library\res\values\atrs.xml:19: error: Attribute "fragment" has already been defined

The AAPT errors reference whichever library project is first (either UnifiedPreference OR HoloEverywhere) in my android library dependency list. I've also discovered that all of the offending attributes are defined as part of <declare-styleable name="PreferenceHeader"> My current Android Dependency order and structure is:
MyApp
   ActionBarSherlock
   HoloEverywhere
   UnifiedPreference
   Crouton
HoloEverywhere
   ActionBarSherlock
UnifiedPreference
   ActionBarSherlock
Crouton

I have tried changing the order of HoloEverywhere and UnifiedPreference, removing ActionBarSherlock from one and making it dependent on the other, and tried pulling them down from git again.
Does anyone know how to get UnifiedPreference and HoloEverywhere to play nicely together since they both have attributes with the same name?
Answer: Yeah, you're  gonna have to rename some attributes to get rid of that AAPT problem. Once the resources get merged into your project, you can't have attributes with the same name. If in reality these are duplicate attributes (meaning, ones that happened to been defined from scratch in its respective project and actually identical to the other), then simply delete them leave in the highest dependency that contains those and delete them from the lower ones.
Comment: I haven't added any custom attributes that conflict in my project, and was hoping to not have to edit the library code. With that said I did try removing the xml definitions from one project and changing the dependency order. When I did this I was getting build errors in the project where it was removed even though one of it's dependencies included those Attributes.
Comment: If I understand it correctly, your app depends on ABs, HE, UP and Crouton? And HE depends on ABS and UP depends on ABS? I think the problem is that you need to only have the highest dependency depend on ABS and then make sure its dependency (namely ABS) be exported. Otherwise you're using ABS 3 times. Does that make sense?
Comment: @nissemand I was unable to get this working after trying the solution described above and messing around with it for a few days. I eventually dropped HoloEverywhere but kept UnifiedPreference. I haven't tried using it yet, however I wonder if things will work better with the new ActionBar support library implementation instead of ABS.
Comment: @MikeS., cheers for the response!  I eventually got HoloEverywhere to work with ABS following [this answer](http://stackoverflow.com/a/10888882/1438809).


Mysql2::Error Access denied for user 'root'@'localhost' (using password: NO) ruby on rails

Question: I installed Ruby on Rails 4.2 on Ubuntu successfully and am using MySQL as my database but when I want to see the new app I created on the browser using localhost:3000
I get this error message:
<code>Mysql2::Error
Access denied for user 'root'@'localhost' (using password: NO)

Extracted source (around line #70):

        socket = socket.to_s unless socket.nil?

70      connect user, pass, host, port, database, socket, flags
      end

      def self.default_query_options
</code>
Any help?
Comment: This is a connection problem, are the configurations in your `config/database.yml` correct?
Comment: what is your mysql password for root user ? update your `config/database.yml` with password of your root user.
Comment: Have you tested that your database allows access for user root with no password at host localhost?
Answer: I installed Ruby 2.2, ROR 4.2.0, mysql server 5.6 on my Mac OS 10.9 and tested my first ROR application.
Rails App use sqlite3 database as default and I try to use mysql this time.
Here's my steps:

Use the CLI: rails new my_app -d mysql.
Go to my_app directory and start rails server by CLI: rails s.
Visit address with http://localhost:3000
Then, got the same question like yours: an Mysql2 Error.
Just try to check the file: my_app/config/database.yml
Solution: Give password value to the root user. ( which should keep consistent with mysql that configured before).
Restart rails server.
Then, Got another Mysql2 error saying: unknown database XXX.
Solution: which because ROR cannot find the database XXX. Go to my_app directory and create database with CLI: rake db:create.
Restart rails server and visit http://localhost:3000. OK!


Mob spawning radius?

Question: I have my mob farm. It is 23 blocks above the ground.
I stayed at the bottom of it, but no mobs are spawning. After leaving and exploring a nearby cave, 2 zombies spawned.
My question is, do mobs only spawn with a x/z radius, not y?
Reference to my world: https://drive.google.com/file/d/11mI8T22wTDw-8Z1MqMSb9sA98DDMaxyT/view
Comment: You basically just need to not be right there looking at it for it to work.
Comment: I should brush up on it but I think Minecraft has a spawn system that tries to not spawn a mob on you so if you were right there, it will not spawn probably within a 5-10 blocks from you. So if you were right there waiting for a spwn it might be that.
Comment: but is there any flaws with my xp farm? Note there is 2 floors @Fredy31
Answer: From the wiki: https://minecraft.wiki/w/Spawn

Mobs spawn naturally within a square group of chunks centered on the player, 15×15 chunks (240×240 blocks). When there are multiple players, mobs can spawn within the given distance of any of them.

and later

Spawn conditions
Whether a spawn condition fails differs from the above determination if the game tries to spawn them in that biome. For example, dolphins can have pack spawns that occur inside of frozen ocean and deep frozen ocean biomes, but no other biomes. These rules apply to variants of the same mob, such as baby zombies and spider jockeys.
Each individual spawn attempt succeeds only if all of the following conditions are met:
There must be no players or the world spawn point within a 24 radius block distance (spherical) of the spawning block
[...]

So basically, mobs can spawn within a radius of about 120 blocks in any direction, but not within 24 blocks of you.
Comment: Aha spherical thats the answer I needed
Comment: but i went far and wide and stayed there for a bit, but it didn't work
could you check for flaws and conduct some tests?
Comment: A thing that is important to note is... nothing was developped in Minecraft vanilla (without mods) to help with mob farms. So you have 2 things that make it difficult: be too close, the mobs wont spawn. Go too far, the mobs are despawned (so even if they were there, they are removed by the game). So yeah its rough, to make a mob spawner work you need to stay between the two rings that I talked about and stay there always. Go to a mine just a little too far? boom, your mobs in the farm are gone so you reset from 0
Comment: could you send me a copy of the map I linked with the areas best for standing highlighted with red wool?
Answer: The mob cap may be the issue
Each time Minecraft attempts to spawn a mob, it will check if it is below the mob cap.  Other zombies and creatures are spawning inside caves or dark places and take up the mob cap.
Try:

rebuilding the farm above an ocean (there will be no caves) (also the easiest)
lighting up all the caves below the farm
afking 100 blocks above the farm, so that you only load the chunks the farm is in (160 worked best for me)

The design of the mob farm can also be an issue.  Farms that rely on passive wandering (random walking around) are fairly slow (in my experience).  The most efficient kinds of mob farms use some sort of water to push the mobs down.
This one works very well for me:

(might need to switch it up a little bit as it relies on QC and it doesn't work in BE)
Comment: It did work, but only after the doing adventures in the nether, so it prob not design
Comment: @Coder2195 its probably the mob cap then
Comment: Then shall I build 100 blocks above?
Comment: I think that'll work, but building it in on top of a deep ocean or lighting the up caves would be better
Comment: it is near a deep ocean
Comment: imma causally go get 462 bamboo for 99 ladders
Comment: on top and in the middle of a deep ocean, so when you stand on top it, so mobs only spawn in the farm
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/124810/discussion-between-giilbert-and-coder2195).

Mob spawning radius?


Could not load JasperReports report from class path resource. The html postfix was added to template's name

Question: I use springboot1.4 + jasperreports 6.2   in my project .I can download  rpt_monthreport_boxsales.jrxml when i start tomcat server, after 2~3 days exception will be shown and restart tomcat server system will be normally. It  confused me that where ".html" comes from?
<code>org.springframework.context.ApplicationContextException:
Could not load JasperReports report from class path resource [jasperreports/rpt_monthreport_boxsales.html.jrxml];
nested exception is java.io.FileNotFoundException:
class path resource [jasperreports/rpt_monthreport_boxsales.html.jrxml] cannot be opened because it does not exist
</code>
My code:
<code>@Bean(name = "velocityViewResolver")
    public VelocityLayoutViewResolver velocityViewResolver(VelocityProperties properties) {
         VelocityLayoutViewResolver resolver = new VelocityLayoutViewResolver();
            properties.applyToViewResolver(resolver);
            resolver.setSuffix(".vm");
            resolver.setLayoutUrl("include/layout.vm");
            resolver.setOrder(1);
            return resolver;
    }

    @Bean
    public JasperReportsViewResolver getJasperReportsViewResolver() {
      JasperReportsViewResolver resolver = new JasperReportsViewResolver();
      resolver.setPrefix("classpath:/jasperreports/");
      resolver.setSuffix(".jrxml");
      resolver.setReportDataKey("datasource");
      resolver.setViewNames("rpt_*");
      resolver.setViewClass(JasperReportsMultiFormatView.class);
      resolver.setOrder(0);
      return resolver;
    }

    @RequestMapping(value = "/exportMonthReportBoxSales")
public ModelAndView exportMonthReportBoxSales(ModelMap modelMap, ModelAndView modelAndView,@RequestParam(value = "month_str", required = true)String month_str) throws Exception {
    List<MonthReport> monthReport_list = g20spaReportService.queryMonthReportBoxSales(month_str);
    JRDataSource jrDataSource = new JRBeanCollectionDataSource(monthReport_list);
    modelMap.put("datasource", jrDataSource);
    modelMap.put("format","xls");
    modelAndView = new ModelAndView("rpt_monthreport_boxsales", modelMap);
    return modelAndView;
}
</code>
Comment: `It confused me that where ".html" comes from?` - Looks like some part of a code add this postfix. Did you try to debug?
Comment: thanks for Alex's response.   Looks like some part of a code add this postfix. Did you try to debug?  >>>> this bug can't be reproduced in local enviroment.    and I had not added '.html' in my project.
Answer: I resolved this question by forbid the default html suffix.
<code> @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false).
            favorParameter(false).
            ignoreAcceptHeader(false).
            useJaf(false).
            defaultContentType(MediaType.TEXT_HTML).
            mediaType("json", MediaType.APPLICATION_JSON);
    }
</code>


Quotationmark problem with Knex and SQL-database

Question: I'm trying to save a query to a database using Knex. But if this query I'm trying to save includes quotation marks I'm getting an error.
Here's an example of how the code might look like:
db.query(`INSERT INTO test.searches VALUES ('TestUser', 'testqueryname', ''SELECT * FROM table WHERE team='rocket'')`, info, () =>{}

Of course in the real case I'm not sending in hardcoded values but variables as strings.
Trying to save this gets me the error

error: syntax error at or near "rocket"
Answer: To start with looks like your code has javascript syntax error at least closing parenthesis is missing.
Secondly knex does not have .query() method (maybe you are using database driver directly?). You should probably be using knex.raw() even that query above could be easily written with normal knex methods.
If you are using knex.raw you can do quoting with ?? replacements and value bindings wit ?.
If you are writing your code like in the question you have no advantage at all from using knex and you should be using database driver directly instead.
Answer: If you are running MySQL, you need to slash escape quotation marks:
db.query(`INSERT INTO test.searches VALUES ('TestUser', 'testqueryname', 'SELECT * FROM table WHERE team=\'rocket\'')`, info, () =>{}

If you are running PostgreSQL, you need to double escape quotation marks:
db.query(`INSERT INTO test.searches VALUES ('TestUser', 'testqueryname', 'SELECT * FROM table WHERE team=''rocket''')`, info, () =>{}

Please consider using parameterised SQL queries or at least appropriately escaping input to avoid SQL injection attacks.
Comment: Thank you for the quick response! I will have a look at this!


How to set timezone in gnuplot?

Question: I have a simple gnuplot command file:
 ....
set xdata time
set timefmt "%s"
set format x "%H:%M"
....

where x - timestamp column.
Result - time in UTC format. Can I change local timezome for x axis ?
Comment: can you provide some sample data?
Comment: I've made some attempts at this and am afraid that I failed ... but I'm not big on timezone `strptime` magic, so maybe someone else will manage.
Comment: I see this question is quite old and it seems the answer has not changed since. I find awful to have to modify the data to get a proper date rendering. Any change in newer versions ?
Answer: Just came across this in the docs today:

The conversion to and from seconds assumes Universal Time (which is the same
   as Greenwich Standard Time).  There is no provision for changing the time
   zone or for daylight savings.  If all your data refer to the same time zone
   (and are all either daylight or standard) you don't need to worry about these
   things.  But if the absolute time is crucial for your application, you'll
   need to convert to UT yourself.

From help time/date
Answer: I just ran across this today. You don't need to change the format, just change the data. If data.txt contains timestamps in UTC, and you want to display them in PDT (-7 hours off from UTC), simply use:
plot 'data.txt' using ($1+(-7*3600)):2

This subtracts 7 hours (in seconds) from each x value.
Comment: You can get the offset using date command:  date +%s -d '1 Jan 1970'
Comment: A refinement to anthonie's comment: `date +%z` yields the current numeric time zone and `date +%z --date=@1520000000` yields the numeric time zone for the epoch time 1520000000.
Answer: A bit late to the party, and I don't have enough reputation points to comment, but to add to anthony and hermannk's answer, this is how I implemented it with their information:

in command.gnuplot, assuming that the first field contains the date/time and the second field contains the value for the Y axis:

plot "inputfile" using ($1 - offset):2

from the (bash) command line, when invoking gnuplot:

gnuplot -e "offset=$(date +%s -d '1 Jan 1970')" command.gnuplot
The offset generally will work OK because gnuplot internally interprets date/time as seconds from epoch. I don't know if the form "offset=$(date ...)" is a bash specific thing, but you could always use "offset=`date ...`" instead.
EDIT --
I found this not to work very well when dealing with DST/Summer Time changes. I changed the offset calc to this, and now it works better:

in command.gnuplot, assuming that the first field contains the date/time and the second field contains the value for the Y axis:

plot "inputfile" using ($1 + offset):2

from the (bash) command line, when invoking gnuplot:

gnuplot -e "offset=$(echo "$(date +%z) * 36" | bc)" command.gnuplot
How does this work?
date +%z provides the timezone offset in the form -0400 or similar, which means Local_Time = UTC - 4 hours. If we consider this a number (-400), then the offset, in seconds, is -400 / 100 * 3600 = -400 * 36.
Note that this won't work with timezones that have 30 minutes increments (India?), but I'm sure with some creating math, you can cover that as well.
Answer: The snippet posted here did not work for me, but this seems to do the trick:
TZ=Europe/Amsterdam tzoff=$(printf "%(%z)T")
tzoff=${tzoff:0:1}$(( ( 10#${tzoff:1:2} * 3600 + 10#${tzoff:3:2}* 60 ) ))
echo $tzoff

Answer: Moin,
I formely had similar problems as the thread-opener and came across a syntax like
plot "wave/timeseries.csv" using ($1+(2*3600)):2 title "swh" with l lw 2

to display forcast of significant-wave-height forecast (bsh.de).
That was fine until a few days ago when I wanted to plot from a bash script to automatically upload gnuplot diagrams for sharing with friends.
#!/bin bash
tz=`date +%j`
tz=`echo "0$tz / 100 * 3600" | bc`
xyz...
gnuplot --persist <<EOF
abc...
plot "wave/timeseries.csv" using ($1+$tz):2 title "swh" with l lw 2
EOF

The problem was, that bash replaces the $1 (data field) by the not existing (NULL) cli argument. Escaping, brackets,... nothing did help.
My workaround is now to from within the script I do write the plot command with escaping to tmp-file like
echo "plot \"wave/timeseries.csv\" using (\$1+$tz):2 title \"swh\" with l lw 2" > plotcmd.tmp

and "load plotcmd.tmp" it from within the gnuplot section.
This way it works
All the best from the baltic sea
Chris

How to set timezone in gnuplot?


Correct way of adding new columns/headers to a dataframe

Question: I need to add new columns to a dataframe. Every column has a header and a value across all the rows (the value is the same for all the columns).
Right now im doing something like this:
array_of_new_headers = [...]
for column in array_of_new_headers:
   df[column] = 0

As a result I'm getting this message:

PerformanceWarning: DataFrame is highly fragmented.  This is usually the result of calling frame.insert many
times, which has poor performance.  Consider joining all columns at once using pd.concat(axis=1) instead.  To get a de-fragmented frame, use newframe = frame.copy()

It tells me to use concat, but, I don't need to concatenate two dataframes really, should I use concat for better performance and better code? To me it doesn't really make sense unless I think of the arrays as also dataframes maybe.
Comment: Maybe you can create a new df and concetrate em then?
Answer: You can pass an unpacked dictionary with keys as column names, and values as value for the columns to pandas.DataFrame.assign :
>>> array_of_new_headers = [...]
>>> df.assign(**{c:0 for c in array_of_new_headers})

But the operation is immutable, so make sure to assign it back to the required variable.
Answer:
should I use concat for better performance

Beware so-called premature optimization, if your code does work rapidly enough for your needs then you might end simply wasting your time on trying to make it faster.


What's the best way to unify date formats after retrieving them from cells and ranges in Google Sheets to Apps Script?

Question: Goal: I need to iterate through rows and match the values within column 'A2:A' with cell 'C2', and then console.log only the matching values from the column.
Problem: The values in 'C2' and 'A2:A' are set to be in 'MM/dd/yyyy' format in Google Sheets. But as I try to retrieve them via Apps Script, sheet1.getRange('C2).getValue() seems to return a different date format than sheet2.getRange('A2:A').getValues() (see snippet comment), so the 'if' statement failed to find any matching value.
What I need help with: Coming up with the best way to unify the date formats after retrieving the values such that the 'if' statement can recognize them and validate the condition.
The snippet:

function matchDates() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var database = ss.getSheetByName("Database");
  var form = ss.getSheetByName("Form");

  var formDate = form.getRange("C2").getValue(); // Console.log returns: 'Fri Jan 07 2022 12:00:00 GMT-0500 (Eastern Standard Time)'
  var dbDate = database.getRange("A2:A").getValues(); // Console.log returns: [ Sat Jan 08 2022 12:00:00 GMT-0500 (Eastern Standard Time) ],[ Fri Jan 07 2022 12:00:00 GMT-0500 (Eastern Standard Time) ],..

  for(let i = dbDate.length - 1 ; i >= 0 ; i--){
    if(dbDate[i] == formDate){
      console.log(i+1,dbDate[i]) // Console.log all rows in 'Date' column of 'Database' sheet that match the value stored in formDate
    }
  }
}

// Console.log this whole function returns nothing because the 'if' statement cannot find any matching dates (due to the stated problem).

Research results so far:

Use getDisplayValue() instead of getValue() - Still didn't work for the 'if' statement. The display value retrieved from 'C2' is different from 'A2:A', something to do with array dimension (red it somewhere but lost the reference), as shown here;

var formDate = form.getRange('C2').getDisplayValue(); // Console.log returns 1/8/2022
var dbDate = database.getRange('A2:A').getDisplayValues(); // Console.log returns [ '1/8/2022' ],[ '1/7/2022' ],..

Using Utilities.formatDate() - Only works for 'C2', even then the value returned by console.log is 1 day behind what's shown on the sheet. I don't know how to format an entire column of 'A2:A' using this because doing it the same way returned me only a single row while it should be the whole range.

Using new Date() as suggested by @Cooper in the comment. Again, worked for 'C2', but not for 'A2:A'. Snippet;

var formDate = new Date(form.getRange("C2").getValue()).valueOf(); // Returns the date in this format : 1641574800000
var dbDate = new Date(database.getRange("A2:A").getValues()).valueOf(); //Returns NaN

I'm a complete newbie and running out of references for this so please, really appreciate the help!
Comment: Try using the new Date() constructor and hope that it recognizes the format otherwise you may have to split them apart and put them in a more appropriate format. [Date Constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date)
Comment: @Cooper OK tried it like this 'var formDate = new Date(sheet1.getRange("C2").getValue()).valueOf();' which returns the date in this format : 1641574800000 . Which is fine as long as I can get the values of 'A2:A' in that format, which in this case I can't. I'll update this in the question.
Answer: Transform your dates in epoch individually
valueOf()

var dbDate = [[ 'Sat Jan 08 2022 12:00:00 GMT-0500 (Eastern Standard Time)' ],[ 'Fri Jan 07 2022 12:00:00 GMT-0500 (Eastern Standard Time)' ]]
var dbDateEpoch = []
dbDate.forEach(function(d){
  dbDateEpoch.push(new Date(d).valueOf().toString())
})
console.log(dbDateEpoch)
Comment: Works like a charm! I was suspecting it had something to do with processing the values in the range individually, I just didn't have enough knowledge to construct the solution. Now I learn the use of forEach. Thanks a bunch!!


Laminate Stair Nose Installation

Question: Below are all the pictures that correspond to my question.
Last night I installed some stair nose molding and tried to follow the instructions the best I could (the part of the instructions in question is below). Now, I do not own a countersink bit, but did my best to do so with what I had.
The board fits perfect, it is ready to go except the screwheads are a little unsightly. I am concerned that the "filler" that the instructions suggest I used can't be blended properly. Has anyone come across this?
As I see it I have two options:
1) Buy a countersink bit to clean up the holes and tidy things up, the fill as instructed.
2) Replace this board and fasten a way that you guys suggest?
Any advice would be great on either option.
I apologize I only was able to post one of the pics of the screws used in installation I am posting this from the office and the other pictures is just a blurry, poorly lit mess. But both are roughly the same.
Thanks for your insights.
Answer: You should get yourself the counter sink drill bit for the screws. They are not expensive and will create a much nicer appearance as they can let you drill down into the molding so that the screw head is fully below the surface and much easier to conceal with the matching trim putty.
Another thing to consider is that when installing with the trim piece with construction adhesive this is the primary thing holding the trim in place. The main job of the screws is to hold the trim in place until the construction adhesive dries. For this reason it is not necessary to use screws with huge diameter heads. A smaller screw like a #6 or #8 that is the length specified by the trim manufacturer should be more than adequate.
If this were my application and only installing such molding at the head of the stairs I would consider using only construction adhesive and placing heavy weights on the molding for 24-36 hours. If you use something like concrete blocks for the weights protect the surface of the trim and floor using some rosin paper.
Another thing I notice from your picture is that it appears that you are installing this molding before you have dealt with baseboard moldings at the wall. This is the incorrect order to do this. Instead install the baseboard first and the fit the molding full length up to the baseboard. There is no real need for an expansion gap for the molding itself because it is relatively short.
Comment: Thanks for all the insights...and now I have a couple of clarification seeking questions. If it's the adhesive that does most of the work, could I not just use a few brad nails instead of screws? And, in regards to your last paragraph, the instructions (portion not pictured) suggested that I leave an expansion gap...so I did. In your experience you find it not necessary? Even though that this piece is ~35" long (I don't remember the exact number).
Comment: You could use brad nails to secure while an adhesive dries, assuming they will hold the board flat in place. If not sitting well in the spot, you may need to do some fitting first with a chisel or hand plane. Be sure to use long enough brads, say the thickness of the board you're attaching + 3/4". It might be good to pre-drill first with a drillbit smaller in diameter than the brads. Use a punch or small nailset to knock brads below finished surface and finish putty or colored wax (sold for the purpose) to hide the brad holes.
Comment: @JCrosby - I have installed a number of flooring projects and have never had expansion issues with the trim molding including a 63" long nose molding installed at the step down from a dining room into a living room. Several installations have been click together floating flooring product that needed trim molding in doorways or along a bathtub. In all cases these moldings were installed as a final step to fit between the base trim or door jambs after any other trim that covers the flooring gap has been installed. Also most of these were installed with construction adhesive and (continued)
Comment: weighted down till dried/set. In the case of the long nose molding piece it was nailed in place using finish nails that were then set below the wood surface using a nailset tool.

Laminate Stair Nose Installation


Left mouse button not working in Xubuntu session

Question: I recent changed from Ubuntu to Xubuntu 12.04. The install worked great for a few days, but suddenly the left mouse button stopped working. The right click and scroll bars work fine.
After a bit of experimenting I discovered that the problem only happens when I set the session to Xubuntu at login. The mouse also works fine in my dual-booted Windows vista.
What could make my mouse stop working like that?
Comment: *X now automatically configures itself*, see this   https://wiki.ubuntu.com/X/Config/, so you will not see `/etc/X11/xorg.conf`. To create a new one use `sudo Xorg :1 -configure`
Comment: Can you post the contents of `/etc/X11/xorg.conf`?
Comment: That file does not exist on my system. Weird.
Comment: Try `sudo nano /etc/X11/xorg.conf`
Comment: Nope it opens me up for a new file.
Answer: Check if you have xserver-xorg-input-evdev installed on your system:
sudo dpkg -s xserver-xorg-input-evdev

If yes, do:
sudo add-apt-repository ppa:xorg-edgers/ppa
sudo apt-get update
sudo apt-get upgrade

If no, do:
sudo add-apt-repository ppa:xorg-edgers/ppa
sudo apt-get update
sudo apt-get install xserver-xorg-input-evdev

Reboot.
Comment: If this is a known issue, there should be a launchpad bug number. Since the problem only exists under the Xubuntu session, replacing the entire X stack sounds extreme.
Comment: I see no reason why using the beta-quality xorg-edgers PPA would provide a solution to this. I doubt that his mouse driver is outdated.
Comment: Because this is a known issue, and this PPA will hopefully fix the problem.
Comment: Thanks for the upvote, this means that my method helped you?
Answer: Your left mouse button might be remapped or disabled.  Try adjusting the configuration or resetting to defaults in the Xfce control panel, as described here:
http://docs.xfce.org/xfce/xfce4-settings/mouse
You can check the current mappings using the xinput command from the Terminal.
$ xinput list
⎡ Virtual core pointer                      id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ Mouseemu virtual mouse                    id=14   [slave  pointer  (2)]
⎜   ↳ bcm5974                                   id=11   [slave  pointer  (2)]

Look for your mouse in the list and note its id, presented as id=x; e.g., 11
The use xinput again to get the current button map:
$ xinput get-button-map 11
1 2 3 4 5 6 7

If the first number is "0", your mouse button 1 is disabled. Test re-enabling it with:
$ xinput set-button-map 11 1

Remember to replace "11" with the mouse's id from xinput list.
If this gets reset every time you login to your desktop, see if there's a file in your home directory called ".xinputrc" or a directory called .xinput.d/ containing files. Also see if there's an errant ".xinitrc" that might have xinput commands.
Answer: Try this command in terminal: sudo modprobe -r psmouse this command removes the mouse driver from the kernel, this should solve the problem, but if the mouse still doesn't work try this after the first command: sudo modprobe psmouse proto=imps and this should reinstates it. It is like of turning it off then on
Answer: Freantique's solution does not work for my Samsung N210 with Xubuntu 12.04. I find a solution that it works and I posted a step by step tutorial here: http://ubuntuforums.org/showthread.php?p=12489693#post12489693
Comment: Welcome to Ask Ubuntu! Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.


Pandas: Knowing when an operation affects the original dataframe

Question: I love pandas and have been using it for years and feel pretty confident I have a good handle on how to subset dataframes and deal with views vs copies appropriately (though I use a lot of assertions to be sure). I also know that there have been tons of questions about SettingWithCopyWarning, e.g. How to deal with SettingWithCopyWarning in Pandas?
and some great recent guides on wrapping your head around when it happens, e.g. Understanding SettingWithCopyWarning in pandas.
But I also know specific things like the quote from this answer are no longer in the most recent docs (0.22.0) and that many things have been deprecated over the years (leading to some inappropriate old SO answers), and that things are continuing to change.
Recently after teaching pandas to complete newcomers with very basic general Python knowledge about things like avoiding chained-indexing (and using .iloc/.loc), I've still struggled to provide general rules of thumb to know when it's important to pay attention to the SettingWithCopyWarning (e.g. when it's safe to ignore it).
I've personally found that the specific pattern of subsetting a dataframe according so some rule (e.g. slicing or boolean operation) and then modifying that subset, independent of the original dataframe, is a much more common operation than the docs suggest. In this situation we want to modify the copy not the original and the warning is confusing/scary to newcomers.
I know it's not trivial to know ahead of time  when a view vs a copy is returned, e.g.
What rules does Pandas use to generate a view vs a copy?
Checking whether data frame is copy or view in Pandas
So instead I'm looking for the answer to a more general (beginner friendly) question: when does performing an operation on a subsetted dataframe affect the original dataframe from which it was created, and when are they independent?.
I've created some cases below that I think seem reasonable, but I'm not sure if there's a "gotcha" I'm missing or if there's any easier way to think/check this. I was hoping someone could confirm that my intuitions about the following use cases are correct as the pertain to my question above.
import pandas as pd
df1 = pd.DataFrame({'A':[2,4,6,8,10],'B':[1,3,5,7,9],'C':[10,20,30,40,50]})

1) Warning: No
   Original changed: No
# df1 will be unaffected because we use .copy() method explicitly
df2 = df1.copy()
#
# Reference: docs
df2.iloc[0,1] = 100

2) Warning: Yes (I don't really understood why)
   Original changed: No
# df1 will be unaffected because .query() always returns a copy
#
# Reference:
# https://stackoverflow.com/a/23296545/8022335
df2 = df1.query('A < 10')
df2.iloc[0,1] = 100

3) Warning: Yes
   Original changed: No
# df1 will be unaffected because boolean indexing with .loc
# always returns a copy
#
# Reference:
# https://stackoverflow.com/a/17961468/8022335
df2 = df1.loc[df1['A'] < 10,:]
df2.iloc[0,1] = 100

4) Warning: No
   Original changed: No
# df1 will be unaffected because list indexing with .loc (or .iloc)
# always returns a copy
#
# Reference:
# Same as 4)
df2 = df1.loc[[0,3,4],:]
df2.iloc[0,1] = 100

5) Warning: No
   Original changed: Yes (confusing to newcomers but makes sense)
# df1 will be affected because scalar/slice indexing with .iloc/.loc
# always references the original dataframe, but may sometimes
# provide a view and sometimes provide a copy
#
# Reference: docs
df2 = df1.loc[:10,:]
df2.iloc[0,1] = 100

tl;dr
When creating a new dataframe from the original, changing the new dataframe:
Will change the original when scalar/slice indexing with .loc/.iloc is used to create the new dataframe.
Will not change the original when boolean indexing with .loc, .query(), or .copy() is used to create the new dataframe
Comment: I always use #3 and I hate the warning
Comment: Hm, a recent, [related question](https://stackoverflow.com/questions/47972633/in-pandas-does-iloc-method-give-a-copy-or-view/47972710#47972710)
Answer: This is a somewhat confusing and even frustrating part of pandas, but for the most part you shouldn't really have to worry about this if you follow some simple workflow rules.  In particular, note that there are only two general cases here when you have two dataframes, with one being a subset of the other.
This is a case where the Zen of Python rule "explicit is better than implicit" is a great guideline to follow.
Case A: Changes to df2 should NOT affect df1
This is trivial, of course.  You want two completely independent dataframes so you just explicitly make a copy:
df2 = df1.copy()

After this anything you do to df2 affects only df2 and not df1 and vice versa.
Case B: Changes to df2 should ALSO affect df1
In this case I don't think there is one general way to solve the problem because it depends on exactly what you're trying to do.  However, there are a couple of standard approaches that are pretty straightforward and should not have any ambiguity about how they are working.
Method 1:  Copy df1 to df2, then use df2 to update df1
In this case, you can basically do a one to one conversion of the examples above.  Here's example #2:
df2 = df1.copy()
df2 = df1.query('A < 10')
df2.iloc[0,1] = 100

df1 = df2.append(df1).reset_index().drop_duplicates(subset='index').drop(columns='index')

Unfortunately the re-merging via append is a bit verbose there.  You can do it more cleanly with the following, although it has the side effect of converting integers to floats.
df1.update(df2)   # note that this is an inplace operation

Method 2:  Use a mask (don't create df2 at all)
I think the best general approach here is not to create df2 at all, but rather have it be a masked version of df1.  Somewhat unfortunately, you can't do a direct translation of the above code due to its mixing of loc and iloc which is fine for this example though probably unrealistic for actual use.
The advantage is that you can write very simple and readable code.  Here's an alternative version of example #2 above where df2 is actually just a masked version of df1.  But instead of changing via iloc, I'll change if column "C" == 10.
df2_mask = df1['A'] < 10
df1.loc[ df2_mask & (df1['C'] == 10), 'B'] = 100

Now if you print df1 or df1[df2_mask] you will see that column "B" = 100 for the first row of each dataframe.  Obviously this is not very surprising here, but that's the inherent advantage of following "explicit is better than implicit".
Answer: I have the same doubt, I searched for this response in the past without success. So now, I just certify that original is not changing and use this peace of code to the program at begining to remove warnings:
 import pandas as pd
 pd.options.mode.chained_assignment = None  # default='warn'

Answer: I keep coming back to this question.
Here is an example of why you might need .copy()
#Code Block 1 - Create dataframe
df1=pd.DataFrame({'ColA':['123456789'],'ColB':['123456789']})
df1

Output:
df1
 |ColA       |ColB
0| 123456789 | 123456789

When the second block of code below is executed the first time it will cut off the "12". The same code the second time will cut of "34", etc.
#Code Block 2
df2=df1
df2['ColA'] = df2['ColB'].[2:]

Gives this output:
df2
 |ColA     |ColB
0| 3456789 | 123456789

Same code again, you'd think you'd get the same output above, but it is not the case:
#Code Block 2 (same code again)
df2=df1
df2['ColA'] = df2['ColB'].[2:]

Gives this output:
df2
 |ColA   |  ColB
0| 56789 | 123456789

The fix, as mentioned is to change the second block. This will give the same result repetitively:
df2=df1.copy()
df2['col1'] = df2['col1'].[2:]

Answer: You only need to replace .iloc[0,1] with .iat[0,1].
More in general if you want to modify only one element you should use .iat or .at method. Instead when you are modifying more elements at one time you should use .loc or .iloc methods.
Doing in this way pandas shuldn't throw any warning.


What´s the difference between NSWeekOfYearCalendarUnit and NSWeekCalendarUnit

Question: I have a NSCalendar:
what´s the Differnece beteween:
<code>NSDateComponents *dateComponents;
dateComponents = [cal components:(NSWeekOfYearCalendarUnit ) fromDate: testDate ];
dateComponents = [cal components:(NSWeekCalendarUnit ) fromDate: testDate ];
</code>
They both return 10 for this week.
Thanks
Answer: They are supposed to be the same.
As shown in How to get a week number from NSDate consistently in all iOS versions?, there's apparently a bug in iOS 5 where they give different results.


select last 25 records from SQL table

Question: I want to retrain last 25 entered records and delete remaining records according to id.
DELETE * FROM list
WHERE id NOT IN
(
    SELECT *
    FROM (
        SELECT *
        FROM 'list'
        ORDER BY id DESC LIMIT 25
    ) as rows
)

Comment: Which DBMS are you using?
Comment: mysql database system i am using
Answer: DELETE *
FROM 'list'
WHERE id NOT IN ( SELECT id
                  FROM 'list'
                  ORDER BY id DESC
                  LIMIT 25 )

Comment: Not getting the meaning of your last message. Can you please re-phrase?
Answer: Deleting while selecting from the same table isn't permitted in MySQL.
You can try something like this:
 SELECT @rows_to_delete:=COUNT(*)-25 FROM list;
 DELETE FROM list ORDER BY id ASC LIMIT 0, @rows_to_delete;

NB: this is not tested please test before running it on real data.
Answer: I think your query is close, but what you need to change is just to filter for id in your subquery, don't select everything, because that doesn't make sense. You want to see if a single item (id) is not in a group of things (all columns).
Try changing your query to this:
DELETE FROM list
WHERE id NOT IN(
  SELECT id
  FROM list
  ORDER BY id DESC
  LIMIT 25);

I would test this with some dummy data first, but I believe it will do what you want.

select last 25 records from SQL table


When my driveway gate opens (powered by 12v battery) i want a light to illuminate the driveway for safety

Question: Is there a switch that can turn on the 110v lights?
Comment: Not knowing the layout, so this is a general suggestion.  Have you considered a motion activated light?
Comment: Hello, and welcome to Home Improvement. Unfortunately, "shopping" questions are off-topic here. Please [take our tour](//diy.stackexchange.com/tour) so you'll know how best to participate here.
Comment: Do you have a wiring diagram for your driveway gate opener?
Answer: What I think that you might be after is called a relay. A relay is an electrically operated switch. It takes a low voltage signal to switch a higher voltage, so instead of you physically flipping a light switch, the switcher in your case would be the power to the gate. When the gate receives power the the relay receives power and 'flips' the switch.
Comment: Yes, a RIBU1C is readily available, UL *listed* (not just component recognized!), and fits the application well
Comment: Niggling detail - the type of relay applicable to THIS question is *"takes a low voltage signal to switch a higher voltage"* - relays ALSO come in many OTHER configurations suited to other applications...
Comment: @Ecnerwal, I know right after I posted that I was going to take a hit on it (all good). Tis 100% true
Answer: A relay with 12V coil like a finder 62-829-012-xxxx, this particoular is handy because it requires fastons and not a specific docking.
In any case my suggestion is to check on your garage door ECU if there's an auxiliary contact (usually there are) exactly for this purpose.
Comment: I don't see any supportable way to mount that relay, though.
Comment: Yeah, those relays are Rather Useless to folks in the USA (UL Component Recognized)
Comment: @Harper-ReinstateMonica just add fastons to the wires and enclose it in a junction box. Other models require din-rail but as far as I know in the it's not as common as it's here.
Comment: @ThreePhaseEel I think you shoul research a little, all those relays are UL rated, just check here: https://www.findernet.com/sites/default/files/2017-06/Finder%20UL%20Cert.pdf
Comment: @DDS -- no, *you* need to research a little, that cRUus at the top of the page means that those relays are UL *Component Recognized*, which means that UL needs to re-examine their use in a finished product, instead of just putting them out there for anyone electrically qualified to install however the directions permit
Comment: The Eel is right about the RU mark.  Having one of those flappy-dappying inside a junction box is a recipe for, at the very least, getting written up.  Your jurisdiction may vary.


How to find escape routes from one point to another in a matrix?

Question: This is not a homework. It's just a practice question.
Given a matrix find the number of possible escape routes from (0,0) to  (N,N). You cannot move diagonally.
A '0' position represents an open cell, while a '1' represents a blocked cell. I started my journey from (0,0) and had to reach (N,N).
Input format
First line is a single odd positive integer, T (<= 85), which indicates the size of the matrix. T lines follow, each containing T space separated numbers which are either '0' or '1'.
Output format
Output the number of ways in which I could have escaped from (0,0) to (N,N).
Sample Input
7
0 0 1 0 0 1 0
1 0 1 1 0 0 0
0 0 0 0 1 0 1
1 0 1 0 0 0 0
1 0 1 1 0 1 0
1 0 0 0 0 1 0
1 1 1 1 0 0 0

Sample Output
4

According to my solution I have taken four directions - left (l), right(r), up(u), down(d).
The problem is that it is giving a wrong answer or a stackoverflow error. What is missing?
And is this the optimal solution to this question?
My Solution (Java)
import java.io.BufferedReader;
import java.io.InputStreamReader;

class testclass {
int no_of_escapes = 0 ;
int[][] arr;
int matrixlength;
public static void main(String[] args) throws Exception
{

    testclass obj = new testclass();
    obj.checkpaths(0,0,"");
    System.out.print(obj.no_of_escapes);

}//main

testclass()
{
    try
    {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    matrixlength =Integer.parseInt(br.readLine());
     arr = new int[matrixlength][matrixlength];
    for( int k = 0; k < matrixlength; k++){

        String str = br.readLine();
        int count = 0;
        for(int j=0 ; j< ((2*matrixlength)-1); j++){
            int v = (int)str.charAt(j) - 48;
            if(v == -16){}
            else{
            arr[k][count] = v;
            count++;
            }

        }//for j

    }//for k

}
catch(Exception e){}
}

public void checkpaths(int m, int n,String direction){

    if((m == matrixlength -1) && (n == matrixlength-1))
    {
        no_of_escapes = no_of_escapes +1;
        return;
    }

    if(!direction.equals("l"))
    {
        if(m < matrixlength && n < matrixlength)
            {
                if((n+1) < matrixlength )
                    {
                        if(arr[m][n+1]==0 )
                            {
                                checkpaths(m,n+1,"r");
                            }
                    }
            }
    }

    if(!direction.equals("u"))
    {
        if((m+1) < matrixlength )
        {
            if(arr[m+1][n]==0 )
            {
            checkpaths(m+1,n,"d");
            }
        }
    }

    if(!direction.equals("r"))
    {
        if(m < matrixlength && n < matrixlength)
            {
                if((n+1) < matrixlength )
                    {
                        if(arr[m][n+1]==0 )
                            {
                                checkpaths(m,n+1,"l");
                            }
                    }
            }
    }

    if(!direction.equals("d"))
    {
        if((m-1)>=0)
        {
            if(arr[m-1][n]==0 )
            {
            checkpaths(m-1,n,"u");
            }

        }

    }

}
}//class

Comment: I think you get a stackoverflow because there is a possible cycle in the instance you showed. When checking a path, make sure you don't use the same cell twice.
Comment: How should I keep a check on that ? Another data structure or there is a simpler way ?
Answer: I would keep a second 2D array of booleans to mark the cells you already visited, as shown in the snippet below. I also simplified some other parts of the code, to reduce code-duplication.
Of course, you need to initialize visited in your constructor, just as you initialized arr, by using visited = new boolean[matrixLength][matrixLength].
int[][] arr;
boolean[][] visited;
final int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

public boolean isValid(int x, int y) {
    return 0 <= x && x < matrixLength
        && 0 <= y && y < matrixLength
        && arr[x][y] == 0
        && !visited[x][y];
}

public void checkPaths(int x, int y) {
    if (x == matrixLength-1 && y == matrixLength-1) {
        no_of_escaped++;
    } else {
        for (int[] d : directions) {
            if (isValid(x + d[0], y + d[1])) {
                visited[x + d[0]][y + d[1]] = true;
                checkPaths(x + d[0], y + d[1]);
                visited[x + d[0]][y + d[1]] = false;
            }
        }
    }
}


How to choose only two years in R using lubridate (not including years in between)

Question: I am using RStudio and a semi-large data set in which I want to only select the years 2016 and 2023 in the data set in the column observation_date. I tried using the lubridate to do this. However, I have only found how to select in between the two years and even then I got an error and it does a range rather than the two years themselves. Also in the data set 2016 and 2023 end at different times as the data for 2023 ends in October. I would appreciate any help as I am new at this.
I have listed below my first code chunk that I have so far. I will attach  a screenshot of what the column looks like. Unfortunately I am unable to attach the full data. Here is what the column looks like
Here is what my code looks like so far:
enter image description here
Also here is what the error looks like:
Error in mutate():
ℹ In argument: Date = lubridate::dmy(Date).
Caused by error in as.character():
! cannot coerce type 'closure' to vector of type 'character'
Backtrace:

BudburstObs %>% mutate(Date = lubridate::dmy(Date)) %>% ...
lubridate::dmy(Date)
lubridate:::.parse_xxx(...)
base::lapply(list(...), .num_to_date)
lubridate (local) FUN(X[[i]], ...)
Error in mutate(., Date = lubridate::dmy(Date)) :
Caused by error in as.character():
! cannot coerce type 'closure' to vector of type 'character'

library(dplyr)
df %>%
  mutate(Date = lubridate::dmy(Date)) %>%
  filter(Date >= as.Date('01-01-2016') & Date <= as.Date('2023-10-31'))
select()

BudburstObs$observation_date_NEW <- mdy(BudburstObs$observation_date)
str(BudburstObs)

I tried looking through lubridate for a way to select two years only and have not figured it out. I have found out how to do a range but that is not what I would like. I am also getting an error.
Comment: In the posted image the column name is `observation_date`, not `Date`. Also, images are not a good way for posting data (or code). See [this Meta](https://meta.stackoverflow.com/a/285557/8245406) and a [relevant xkcd](https://xkcd.com/2116/). Can you post sample data in `dput` format? Please edit the question with the output of `dput(df)`. Or, if it is too big with the output of `dput(head(df, 20))`.
Answer: There are two issues in your code:

it is not dmy(Date), in your case it is mdy(Date)
In your code you try to filter Date between 2016 and 2023 and not only 2016 and 2023 as you state in your intro.

Here is an adapted code (not tested):
library(dplyr)
library(lubridate)
df %>%
  mutate(Date = lubridate::mdy(Date)) %>%
  filter(year(Date) == 2016  | year(Date) == 2023) # year is from lubridate


What does __init__ method of Python immutable class, e.g. float look like?

Question: It seems the __init__ method of Python immutable class is meaningless, as after the creation of an object, attribute assignment is not allowed. But obviously the __init__ method does exist for immutable object. How is it implemented? Does it have empty method body?
Comment: Often if you want to cache instances you'll use `__new__` to return a previously constructed object.  A common pattern we use is inheriting a tuple (immutable) through namedtuple and setting `__slots__ = ()` to prevent assignment to arbitrary attributes.
Comment: Are you looking for an *immutable* or *builtin* pattern?  From what I can tell, the builtin for a new float [is only defined in C](https://hg.python.org/cpython/file/c6880edaf6f3/Objects/floatobject.c#l1788).
Answer: __init__ does nothing and is simply inherited from object. All the work is done in __new__.
In [1]: float.__init__
Out[1]: <slot wrapper '__init__' of 'object' objects>

In [2]: float.__new__
Out[2]: <function float.__new__>

The definition of the float class's tp_new is float_new, which can be seen here.


Excel VBA - Custom Function; #VALUE error; VLOOKUP on different worksheet

Question: I am attempting to do a VLOOKUP on a different worksheet based on given parameters in the function. I've played around with it for several hours and can not figure out why it is not working. I cut down the code as much as I could to test, but am unable to effectively find a solution. I think it might be an issue of how I am calling the range from the other worksheet for the VLOOKUP. Code is below. Please advice. If I'm unclear about what I'm asking just ask and I will provide feedback. Thank you
Function GraphDataA(cR As String, time As String, aClient As String, tps As String, dat As String)

Dim client As Boolean
Dim day As Boolean
Dim tot As Boolean

Dim dayTotData As Range
Dim dayTotDatas As Worksheet

Set dayTotDatas = ActiveWorkbook.Sheets("DayTot")
Set dayTotData = dayTotDatas.Range("A3:AI168")

client = False
day = False
tot = False

If date = "" Then
    GraphDataA = ""
End If

If aClient = "" Then
    GraphDataA = ""
End If

If cR = "Client" Then
    client = True
End If

If time = "Day" Then
    day = True
End If

If tps = "Total" Then
    tot = True
End If

If client = True Then
    If day = True Then
        If tot = True Then
            GraphDataA = WorksheetFunction.VLookup(aClient, dayTotData, WorksheetFunction.Match(dat, dayDate, 0) + 8, _
        False)
        End If
    End If
End If
End Function

Answer: VLOOKUP() will throw an error if nothing matches. So you need to add error catching code to your function.
You need to modify the function as
Function MyFunction() as Something
    On Error Goto ErrorHandler
    ' Your existing code goes here
    Exit Function
ErrorHandler:
    MyFunction = -1 ' Or something which indicates that the value isn't found
End Function

Comment: I am able to catch the error now, but I am still not even able to conduct the Match function alone.

GraphDataA = WorksheetFunction.Match(dat, Worksheets("DayTot").Range("I3:EK3"), 0)

Should this function work based on the assumption that dat is in the DayTot!I3:EK3 array?
Comment: Split the `MATCH` and `VLOOKUP` into separate lines in your code i.e. store the intermediate matched value in one variable and then use it in your `VLOOKUP`. Find out which step is generating the error by using breakpoints on both, then
Comment: I split up VLOOKUP and Match and identified the error in Match. It was a problem with the range. Thank you.
Answer: You don't appear to be returning any value from your function. Try adding As Variant to the end of the first line like so:
Function GraphDataA(cR As String, time As String, aClient As String, tps As String, dat As String) As Variant

Comment: but the OP is returning value from the function. In VBA you replace `return` with the function name.
Comment: @ArmenSafieh-Garabedian default return type is a Variant
Comment: @mehow doesn't he have to specify the return type though, as Gareth has pointed out?


Named router outlet and lazy loaded modules

Question: I have problem with named router outlet and lazy loading module.
I have 2 router outlets first without name and second is named mainapp.
app.component.html
<router-outlet></router-outlet>

app.main.component.html
<router-outlet name="mainapp"></router-outlet>

app.routes.ts
export const routes: Routes = [
    {path: 'login',  component: LoginComponent},
    {path: 'app', component: AppMainComponent, children:[
        {path: '', loadChildren: 'app/client/client.module#ClientModule'}
    ]}
];

client.module.ts
@NgModule({
  imports: [
    SharedModule,
    RouterModule.forChild([
      {path: 'client', component: ClientListComponent, outlet: "mainapp" },
      {path: 'client/:id', component: ClientComponent, outlet: "mainapp" }
    ])
  ],
  declarations: [ClientListComponent, ClientComponent],
  exports: [ClientListComponent, ClientComponent]
})
export class ClientModule { }

LoginComponent is loaded into router outlet
After login AppMainComponent is loaded into router outlet
Now I try load ClientComponent to named router outlet mainapp

I get error
ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'app'
Error: Cannot match any routes. URL Segment: 'app

When I modified routes to this it works:
export const routes: Routes = [
    {path: 'login',  component: LoginComponent},
    {path: 'app', component: AppMainComponent, children:[
        {path: 'client', component: ClientListComponent, outlet: "mainapp" },
        {path: 'client/:id', component: ClientComponent, outlet: "mainapp" }
    ]}
];

Answer: Seems to be known bug that you can follow at:
https://github.com/angular/angular/issues/10981


Is it necessary to wait for window load event before initialising a ReactJS app?

Question: Is there any reason to wait for a window load event before initialising a react app?
window.addEventListener('load', () => {
   ReactDOM.render(

Reactastic!
,
     document.getElementById('rootElement')
   );
}, false);

As long as rootElement is defined in html, not hidden or created dynamically by javascript, is there any possibility that it won't be available in time for React to init?
Edit: This is also assuming that the javascript is loaded in the footer.
Comment: to be honest, never thought about it before, I just use the default React lifecycle methods... gonna try.
Comment: If you locate your JavaScript after html then rooltElement should be loaded.
Comment: you should also assume that this is either the last script element or that all following scripts ( including html5 async scripts ) don't invasively change the rendered dom tree inside 'root'...
Answer: Assuming the javascript is loaded at the bottom of the page, there is no reason to wait for the document to be loaded since the rootElement will already be available in the DOM.
Comment: Is that guaranteed 100% of the time in all browsers? Assuming that the html is set normally (and is not manipulated in any way by other scripts) and the javascript is loaded in the footer
Comment: Yes it holds true in all browsers. If the script is added to the DOM below the `rootElement`, it will be returned by the `document.getElementById` or `document.querySelector` APIs.
Answer: the ReactDom renderer will mount everything in the container element, so, the only thing react needs(*) is an existing 'root' element at render call.
Given your assumptions, this holds true hence you don't need to wait onload() in this case.
(*)of course, any script evaluated after rendering() invasively manipulating the dom inside your 'root' element can ( and probably will ) break the react logic ...


Using back button Mobile Single Page application AngularJS

Question: I'm using AngularJS to create a Single Page App (SPA) and am wondering how best to manage using the back button on mobile devices.
I created my application without views. One js form, one html page and no partials. The info is displayed using ng-show and a controller that helps hide
 tags according to tab numbers assigned to them.
What I need to happen is for the application to NOT CLOSE when the back button is pushed.  But since I am not passing any params to the URL (because the URL never changes) is there a really good way to give functionality to the back button on the mobile device?
Here's a code sample, but I also included a plunk to try and better help clarify my need.

=

Home

About

Contact

or

or

Answer: If you're simply looking to prevent the back button from leaving the SPA right away, you could use window.onbeforeunload() to warn the user that the back button will exit the app.
window.onbeforeunload = function () {
   return "Are you sure you want to leave?"
}

Otherwise to get your app to be stateful and allow the user to use back/forward buttons, you will want to use ui-router or angular-routes.
Comment: Ok. I can use this as an option. I was trying to avoid using the ui-router.
Comment: I've messed around with this a bit and even expanded my reading on it to try and better understand it, but this function doesn't seem to be working for me. @pascal-winter


How to add two panels and resize them when frame change sizes?

Question: I have three classes. GameFrame extends JFrame, GamePanel & InfoPanel extend JPanel.
I am looking for the best solution how to add those two panels to frame like on the picture:

The initial size of GamePanel must be (800x800). I would like that when changing the size of the window, both panels also change the size to fit the window. How to do it?
Comment: *"`GameFrame` extends `JFrame`, `GamePanel` & `InfoPanel` extend `JPanel`."* I bet that there is no need to extend `JFrame`, and possibly that the `InfoPanel` should not extend `JPanel`. Is `GamePanel` custom painted? That's probably the only good case for extending a container. Put `InfoPanel` in the `PAGE_START` & `GamePanel` in the `CENTER` of a `BorderLayout`. Both panels will be stretched to the available width. The `GamePanel` will get the extra height.
Answer: Sounds like you need to set the layout of GameFrame to Border Layout and add InfoPanel to the NORTH of GameFrame and GamePanel to the CENTER. BorderLayout will automatically resize its components to match the size of the JFrame.
Comment: Ok thanks. And how can i get the current size of my GamePanel?
Comment: you should be able to call `gamePanel.getSize()`
Comment: Yeah it works :D But can you explain me why when i call frame.getWidth() it returns 734, but when I call gamePanel.getWidth() it returns 718? I am setting gamePanel size 718. But i don't understand why frame has 734.
Comment: If you call `setBorder(new LineBorder(Color.RED))` on your JPanels, you should be able to see the exact border of each panel and see why the widths display as they do compared to the JFrame.
Comment: Great. Thank You :)
Comment: Would you mind accepting the solution, glad I could help!


Question concerning linear combinations of vectors and linear independence in Linear Algebra.

Question: My question concerns the definition of linear combinations and a criteria for linear independence of a Set (either finite or infinite).
Here is the following Definition and Criteria given:
A vector $v$ in vector space $V$ is a linear combination of vectors of set $S$ if there is a a finite number of vectors $x_1, \cdots , x_n$ and scalars $a_1, \cdots , a_n$ such that
$$v= a_1x_1 + \cdots + a_nx_n$$
Question:
Here is finite restricted to more than $1$ vector. Or does this definition include the possibility of a vector $v$ being a linear combination of no vectors?
Also, can these finite vectors in set S be the same. That is must they all be distinct?
Criteria for Linear Independence:
My book writes the following fact:
A set is linearly independent if and only if the only representations of the zero vector as linear combinations of its vectors are trivial representations.
Question:
Taking in mind the definition of linear dependence requires a nontrivial representation of the zero vector as a linear combination of DISTINCT vectors of the set examined for linear dependence, why does this criteria for linear Independence say "as linear combinations of its vectors" as opposed to "as linear combinations of its distinct vectors" ?
Lastly, if a set is linear independent, does that imply the set contains distinct vectors?
Does it make sense to talk about linear dependence and linear independence in the context of a set of vectors with some vectors repeated. That is with a set of vectors with element all not distinct?
Thanks in Advance.
Comment: To your concern of distinctiveness, since you're talking about "set", so vectors in a set are distinct by default.
Comment: I'm reading the same book, my question may be helpful to you: https://math.stackexchange.com/q/2675139/390226
Answer: The empty set is a finite set by all standards, so this definition also allows for taking $n=0$. That choice requires knowing what is the value of the linear combination of no vectors at all, and that value is the zero vector. As a consequence, the zero vector always is a linear combination of whatever set$~S$ of vectors you specify. Using $n=0$ is essential when $S$ itself the empty set, in which case the zero vector is the only linear combination that one can form.
The formulation is not very clear about whether one could select the same vector more than once when forming a linear combination (it depends on whether one reads a finite "number of vectors" as a finite set or as a finite sequence). However it does not matter since allowing such repetition does not allow any more linear combinations to be formed (one can use $ax+bx=(a+b)x$ to reduce the number of occurrences of the same vector $x$ until no more repetitions occur), and in practice it is most convenient to not forbid it. For instance this allows seeing without any complications that the sum of two linear combinations from the set $S$ is again a linear combinations from the set $S$.
The definition of linear of independence uses a slightly different view on linear combinations, as is it not so much about which vectors are or are not linear combinations of elements of$~S$, but about specific linear combinations (which may be trivial combinations or not). To this end a specific linear combination of elements of$~S$ is determined by specifying for each element of$~S$ a corresponding coefficient, which association must be so that it associates a nonzero scalar only to a finite number of elements of$~S$. The value of such a linear combination is found by forming $a_1x_1+\cdots+a_nx_n$ where the sequence of vectors $x_1,\ldots,x_n$ contains each vector of$~S$ with a nonzero associated scalar exactly once, and each $a_i$ is the scalar associated to$~x_i$. A specific linear combination is trivial if the scalars associated to the vectors are all$~0$. The set$~S$ is defined to be linearly independent if the only specific linear combination of elements of$~S$ whose value is the zero vector is the trivial linear combination.
Note that this formulation arranges for the same vector to be used only once in a specific linear combination. It must do so, or else a nonzero set could never be linearly independent, because one could take any vector $x$ from the set and form for instance $1x+(-3)x+2x$ as a "nontrivial linear combination" with value the zero vector. Talking as you suggest about a "linear combinations of its distinct vectors" might convey the right idea, but does not make any precise sense (the is no definition of what such a phrase means).
You final question "if a set is linear independent, does that imply the set contains distinct vectors" is pointless, since elements of a set are always distinct: a set cannot contain a given value more than once as element. Your question would make sense if instead it was talking about sequences of families of vectors (since these may have repeated occurrences of the same values). And the answer then is that when there is at least one repetition, the sequence/family is never independent, as the difference between two instances of the same vector would be a nontrivial specific linear combination whose value is the zero vector. By the same token, and set/sequence/family containing the zero vector cannot be linearly independent (taking that vector with scalar $1$ would be a nontrivial linear combination with zero value).
Answer: Here are answers to your questions:-

Firstly, when you say scalars, $a_1, a_2, \cdots, a_n$, they are real numbers and hence can also be $0$. Keeping this in mind, suppose there is a set $S = \left\lbrace v_1, v_2, \cdots, v_n \right\rbrace \subseteq V$. Then, quite obviously, the vector $\textbf{0} \in V$ cab ve written as
$$0 \cdot v_1 + 0 \cdot v_2 + \cdots + 0 \cdot v_n = \textbf{0}$$
This is what we call the "trivial linear combination".

In fact, what confusion you have in mind is that when you say that a vector is a linear combination of other vectors, there must be at least one vector and one scalar with which you can construct your "linear combination".

When you talk about a "set", elements cannot be repeated. So, there is no point of asking if the elements of the set are distinct.

Lastly, I do not know what book you are following, but I feel that a better version of definitions of linear dependence and independence is the following:-
Linear Independence
A finite set $S = \left\lbrace v_1, v_2, \cdots, v_n \right\rbrace \subseteq V$ is said to be linearly independent iff
$$\alpha_1 \cdot v_1 + \alpha_2 \cdot v_2 + \cdots + \alpha_n \cdot v_n = \textbf{0}$$
implies that $\alpha_1 = \alpha_2 = \cdots = \alpha_n = 0$. This actually means that the only way you can obtain the zero vector $\textbf{0}$ from a linearly "independent" set is by setting the scalars (coefficients) to be $0$, which we call the "trivial" combination.
In case of an infinite set $S \subseteq V$, it is said to be linearly independent iff every finite subset of $S$ is linearly independent. We have definition of linear independence of finite sets which can be used.
Linear Dependence
A finite set $S = \left\lbrace v_1, v_2, \cdots, v_n \right\rbrace \subseteq V$ is said to be linearly "dependent" iff it is not linearly independent. Thus, we need to negate the statement for linear independence. The negation of the statement
"$\exists \alpha_1, \alpha_2, \cdots, \alpha_n \in \mathbb{R}$ and $i \in \left\lbrace 1, 2, \cdots, n \right\rbrace$ such that $\alpha_1 \cdot v_1 + \alpha_2 \cdot v_2 + \cdots + \alpha_n \cdot v_n = \textbf{0}$ and $\alpha_i \neq 0$"
This statement means that the vector $v_i \in S$ can be actually written as a linear combination of the other vectors. In particular,
$$v_i = \left( - \dfrac{\alpha_1}{\alpha_i} \right) \cdot v_1 + \left( - \dfrac{\alpha_2}{\alpha_i} \right) \cdot v_2 + \cdots + \left( - \dfrac{\alpha_{i - 1}}{\alpha_i} \right) \cdot v_{i - 1} + \left( - \dfrac{\alpha_{i + 1}}{\alpha_i} \right) \cdot v_{i + 1} + \cdots + \left( - \dfrac{\alpha_n}{\alpha_i} \right) \cdot v_n$$
and therefore the vector $v_i \in S$ is "dependent" on the other vectors.
In fact, the linear combination $\alpha_1 \cdot v_1 + \alpha_2 \cdot v_2 + \cdots + \alpha_n \cdot v_n = \textbf{0}$ is called the "non - trivial" linear combination.
For an infinite set $S \subseteq V$, it is said to be linearly dependent iff it is not linearly independent. Again, we need to negate the statement for linear independence of infinite set. The negation of the statement would be
"There exists a finite set $A \subset S$ such that $A$ is not linearly independent". And now, we do have the definition of linear dependence (not linear independence) for finite sets which can be used.
I hope your confusion about distinct elements will be cleared by this. And if you are still confused, try forming sets which are linearly dependent and independent in $\mathbb{R}^2$ and $\mathbb{R}^3$ which you can easily visualize. Also read some material on span of a set and how we can connect linear combination and span with linear dependence and independence.
Comment: Thanks for the insights. I am using linear algebra by Friedberg . It defines linear dependence  of a set as a non trivial linear combination of distinct vectors in the set. Then defines linear independence as the negation of it. However, I'll stick to your given definition as it makes more sense this way.


Pact of Research in Civilization V

Question: What are the requirements to have the option to sign a Pact of Research with another Civ?
Comment: Note that if you can't select Research Pact in the diplomacy screen, if you mouse-over it will tell you why it's unavailable.
Answer: Both sides need enough money for the agreement, and at least one side has researched Philosophy.
The cost for a research agreement scales with the era of the more advanced player and with the game speed:
<code>Era         Quick  Standard  Epic  Marathon
-------------------------------------------
Classical   134    200       300   600
Medieval    167    250       375   750
Rennaisance 167    250       375   750
Industrial  201    300       450   900
Modern      234    350       525   1050
Future      234    350       525   1050
</code>
You can also have only one active research agreement per civilization, and research agreements are not possible during war (as bwarner pointed out).
If the enemy civilization has not enough money for the research agreement you can also gift (or loan it against gold per turn) the necessary gold to them.
Comment: I've had it cost as little as 167 and as much as 400. The cost goes up based on the lowest tech you (or they) have.
Comment: You also can't be at war with each other, and you can only have a single research agreement active with each civ.
Comment: How much money I need?
Comment: I've signed a research agreement before for 200 gold.  Maybe the difficulty level plays into the cost as well as the era?
Comment: I think gamespeed alters it as well.
Comment: @Raven That could very well be so, I only play standard speed.
Comment: @Raven You were right. I've added the costs depending on game speed.
Answer: To enter a research agreement, both parties need to have the required amount of gold and both need to have researched Philosophy.
Comment: It is enough if one side has researched philosophy.
Comment: Does it matter which side?

Pact of Research in Civilization V


HTML table with multiple fixed rows and columns

Question: I have a table like this:

Now, in reality, there would be in excess of 100 rows and/or columns. Naturally, in such a table, someone might lose track of what they're looking at.
So I'd like a couple (or more) rows and columns to stay fixed in their positions, while only the remaining part of the table scrolls. (So in the picture it'd be only the Cells containing 'Data' should scroll, the rest should stay in place.)
I've tried a couple plugins and they either failed miserably for some reason or were too slow for large tables.
So I'm asking here, is there a way to do this simply through CSS/html/js? Even if it is complicated. The table would be wrapped in a position: relative div
if this matters at all.
Even tho code would be very welcome, I am also open to suggestions. (Kind of new to the whole front end part).
Comment: if i understood your question this is a post talk about fixed table: [fixed table](https://stackoverflow.com/questions/8913118/how-to-make-table-row-fixed-at-the-top)
Answer: You could use DataTables.
Here's a link
https://datatables.net/examples/styling/bootstrap4