Add a unique Banner Image to each page

Question: I've been teaching myself Drupal 7 for the past 2 weeks. So far, I've gotten the general idea, and figured out how to use Views (i think) but it's the most difficult CMS I've ever had to learn and I've pulled out lots of hair.
The problem I'm stuck on now is that I want to be able to let the site administrators attach a unique banner image that will appear at the top of every page in my theme. There is a 'banner' region in the theme that was intended to hold this image. I've added a banner image field to the Basic Page content type.  But now I can't figure out how to get that image to show up in the banner region and not in the flow of the rest of the page content (body).
I've tried a few things with views and blocks, but nothing works.  Please Help!
Comment: Just in case the above is unclear.... I want to set a unique banner on each page.  An 'about' banner for the About page. A 'Contact' banner for the 'Contact' page, etc.
Answer: This method is pretty similar to what Shoaid Nawaz has said above. For Drupal 7, you can use the Views module. Coupled with a custom theme region, you can create a block using the views module which will show an image for each node from a custom image field specified for the content type. You need to have a basic working knowledge of the Views module.
Here is how:

Create a custom theme region, name it something like "Banner Region"
In your content type, add an image field, name it something like "Banner image". If you need description, enable Alt tags for the image field. If you do not need slideshow, restrict the number of image to 1. For slideshow, you can use the views_slideshow module.
To create similar sized banner images, you can create a new image style.
Create a new View. Name it something like "Banner". Choose "block" display and not "page".
In the filter criteria, choose your content type.
Add a contextual filter for "Content: Nid" and save the view.
Now go to the your blocks administration page and add the newly created views block to your new banner region.

In short:

Banner image is a new image field in an existing content type.
Views module understands which image is attached with which node using the contextual filter.

Tip: You might want to disable this block on the frontpage if your frontpage is not a node.
Further tip: You might consider adding other content types to the filter criteria if you banners for multiple content types. Alternatively, you can create a block for each content type and block control visibility using "No results behaviour" in the views' settings.
Comment: This looks promising.  I'll give it a try and update how it turned out. Thanks.
Comment: Doing this, I realized I tried this early yesterday morning, but I couldn't figure out how to connect the individual content items to the page (Nid) it needs to display on. Also, in my Filter Criteria I have the following options from the Content type I created: field_banner_image:alt, field_banner_image:fid, field_banner_image:title.   I'm not sure which to pick or exactly what's happening by picking this.
Comment: @Ben I agree connecting the nodes to their respective images is the trick here. Try keeping the filter criteria simple. Add only Content: Published (Yes) and Content: Type (= Page). Then add the contextual filter: Content: Nid. The thing should not be more complex than this.
Comment: Have a look at this [screenshot](http://img59.imageshack.us/img59/4413/selection012.png). This is the view I had created. Note that the view preview won't show any result. You won't get any result until you put the block on a page.
Comment: this sort of worked.  it's showing the default image that I told the content type to use, and has a pager that maxes out at 26 pages for some reason.  I still don't see how it makes the connection that one particular banner should be shown on one particular page.
Comment: Did you configure your image field to accept only one value? In Views, make the pager to display all items. The connection between node and image is done through the contextual link. The view basically shows the image which is attached to the node presently being viewed. Since you have added an image field to a node, the images are treated as attachments of that node. Views uses this contextual filter to get the node id and searches for images that are attached to this node id. When you provide only one value, the view will find only one image and show it in the banner region.
Comment: So in your example is the image it's own content type or an added field of the page content type?  If it is it's own content type, then how does the "About Us" banner know to only show on the "About Us" page, and not the "Contact Us" page?
Comment: I have it limited to 1 (plus the default)
Comment: @Ben As I had specified in my original answer, it is an added field to an existing content type. So the images become attachments for nodes, but they do not themselves become a separate node. Thus, "About Us" page will add the contextual filter of Content:nid (which is the node id) to find the image attached to that node and display it on the About Us page.
Comment: I think I see what you mean now.  When you first said, "In your content type, add an image field..." my brain said, "Create a content type that has an image field."  I'll give this a try tomorrow and let you know how it turns out. Thanks.
Comment: Sure. I will suggest you to redo it from the beginning. Remember two basic things: banner image is a new image field in an existing content type. Views module understands which image is attached with which node using the contextual filter.
Comment: Success!! I had to remove the View, like you suggested, but after I did that and set it up correctly, it worked. At first it was showing every banner image on every page. I fixed that by setting the Contextual Filter > content: Nid to the option to "provide default value with type of Content ID from URL".
Comment: Glad to know it worked, @Ben. That is precisely what the contextual filter is for.
Comment: I know this Post is quite old, I had the same requirement for a drupal 8 project, here is some additional information:
-> when you set the Content: Node ID, select "Provide Default Value" and "Content ID from URL"
-> Make sure you really set the filter containing the Content Types that really have the Banner Image you want to display! Otherwise the View will break!
-> Create a Custom Block, that contains a Fallback Picture and add it to the no result section
Comment: @KaustavDasModak: i follow your instructions but my image is not shown on banner region.
Comment: For add the region in the template. i added this regions[banner_image]    = Banner Image to .info file and      the above code is page.tpl file
Answer: There is Header Image, a module but unfortunately not for Drupal 7. I do not think if you can port it yourself.
Here is another guide for alternate purpose.
Comment: I've actually seen that page.  It makes sense, but it's not really manageable on a site that has more than a few pages. There must be a "Drupal" way to get this done that doesn't require placing potentially hundreds of individual blocks in the right regions.
Comment: Yes Header Image is right choice in this regard, as I am using it but not in your case. :(
Comment: Try this module in your dev site and test it carefully. This is D7 port of Header Image. http://drupal.org/files/headerimage-7.x-.1.0-alpha.tar_.gz
Comment: Thanks for the suggestion, but I tried to install in drupal 7 and it would not take.

I'm shocked that there's not a way to do this without an additional module.  It's such a common web design practice that I can't see Drupal being so successful if you can't even add a banner image to a page without jumping through hoops and installing alpha modules.
Answer: I managed it in a different way in an experiment using Views and content type.
A Content type (Banner) with two additional (Content) fields.
1. Image field
2. Visibility Location (URL) field

Then I created a view with block display type.
Fields:
 - Image field (Imagecache output)

Filter:
 - Node type: Banner
 - Published: True

Contextual filter:
- Content: Visibility Location

I then edited the options under this contextual filer as:
1. Select "Provide default value"
2. then select type as "PHP code"

I then added PHP contextual filter code as under
if(drupal_is_front_page()){
  return '<front>';
}else{
  return drupal_lookup_path('alias',$_GET['q']);
}

TEST:
I put the views block in header region and created two nodes of banner types

For node 1 I selected Visibility Location as <front>
For node 2 I selected Visibility Location as contact-us

And it worked!
Comment: Thanks. I had to change the Field Type of Visibility Location to Text instead of URL.  Using URL as the Field Type forced the input to be a valid URL (e.g. http://whatever/)
Answer: Not sure if it's too late to answer this question but I think it will come in handy when upgrading from Drupal 7 to 8 or 9.
You could give this module a try:
Dynamic Banner
It has been around for a while (since 2010), and seems like the maintainer is committed to make it compatible with Drupal 8 and 9.

Add a unique Banner Image to each page


Infinite cardinals formal proof

Question: I need help in showing
$$2^a + 2^a = 2 · 2^ a$$
It sounds obvious but how can I formally prove it?
Comment: It's a special case of the identity $x+x=2\cdot x.$
Comment: If you want a "formal proof", you need to tell us what are the definitions you're using for cardinal arithmetic.
Answer: Let $A$ be a set of cardinality $a$, and let its power set be $\mathcal{P}(A)$; take also another set $Y$ which bijects with $\mathcal{P}(A)$ but is disjoint, and let $f: \mathcal{P}(A) \to Y$ be a bijection.
We wish to show that there is a bijection between the following two sets:

$\mathcal{P}(A) \sqcup Y$ (where $\sqcup$ notes that the union is disjoint), of cardinality $|\mathcal{P}(A)| + |Y| = 2^a + 2^a$
$2 \times \mathcal{P}(A)$ (the set of $2$-tuples such that the first element is $0$ or $1$ and the second is a subset of $A$), of cardinality $2 \times 2^a$.

There's an obvious injection from the second to the first: take $(0, x)$ (where $x \subseteq A$) and output $x$, while take $(1,x)$ and output $f(x)$ the isomorphic copy of $x$ in $Y$.
You can easily check that this is actually surjective too: it hits all of $\mathcal{P}(A) \sqcup Y$.

If you're worried about the ability to pick the set $Y$, we can define it as $$Y = \{ x \sqcup \{ \mathcal{P}(A) \}: x \in \mathcal{P}(A) \}$$
where the union inside the set-builder is a disjoint union since $\mathcal{P}(A)$ cannot lie in $\mathcal{P}(A)$.
Then $Y$ is disjoint from $\mathcal{P}(A)$ because no member of $\mathcal{P}(A)$ can contain $\mathcal{P}(A)$.

Infinite cardinals formal proof


How can I dynamically reference a control in vb.net

Question: I'm trying to select a control based on setting a variable equal to that control like so:
selectedBox = sender

For reference this is how I declare selectedBox:
Dim selectedBox As PictureBox

What I was hoping to do was something like this:
If selectedBox = picbox then
...

Where picbox is a picturebox passed to the function.
However this doesn't work due to:
Operator '=' is not defined for types 'PictureBox' and 'PictureBox'

So what can I do here?
Answer: You can use Is like so:
If selectedBox Is picbox Then


Grid increase row size for specific row and item

Question: im using a Grid to show 5 Items per row on my project.
When i click on an item, i wanna be able to show the item-detail by increaing the size of the html element.
Is there any trick in CSS where i cant say the Grid to grow an specific item and shrink the others in the row and also saying that i need for one row more space then the others.
Answer: Not really any trick to being able to do this, just hard work, or trial and error. Depends on exactly what you're looking to do.
If you don't mind about responsive behavior too much (ie, what happens when this page is shrunk to mobile size?) then I suppose you could implement this with scale css transforms on mouseover, or perhaps using calc to carefully set widths in CSS, or a combination of both.
If you're looking to use the CSS grid property you're fresh out of luck, it's not really designed to handle complex interactions like this. I'd build this from scratch with flexbox or manual positioning with JS.
Answer: Not the best approach but will solve your problem.
Margin 0 5rem; will give a margin left and right to the box that you hover.
.box:hover{
  transform: scale(1.3);
  margin: 0 5rem;
}

*,
*::before,
*::after {
  box-sizing: border-box;
}

body {
  min-height: 100vh;
  background-color: bisque;
}

.container{
  padding:1rem;
  display: flex;
  flex-direction: row;
  gap:1rem;
  padding:10rem
}

.box{
  height:15rem;
  background-color: grey;
  display: flex;
  flex:1;
  margin-top: 2rem;
  transition: 0.5s;

}

.box:hover{
  transform: scale(1.3);
  margin: 0 5rem;
}


Lightweight memory leak debugging on linux

Question: I looked for existing answers first and saw that Valgrind is everyone's favorite tool for memory leak debugging on linux. Unfortunately Valgrind does not seem to work for my purposes. I will try to explain why.
Constraints:

The leak reproduces only in customer's environment. Due to certain
legal restrictions we have to work with existing binary. No rebuilds.
In regular environment our application consumes ~10% CPU. Say, we can
tolerate up to 10x CPU usage increase. Valgrind with default memcheck
settings does much worse making our application unresponsive for long
periods of time.

What I need is an equivalent of Microsoft's UMDH: turn on stack tracing for each heap allocation, then at certain point of time dump all allocations grouped by stacks and ordered by allocation count in descending order. Our app ships on both Windows and Linux platforms, so I know that performance on Windows under UMDH is still tolerable.
Here are the tools/methods I considered

Valgrind's -memcheck and –massif tools They do much more than needed (like scanning whole process memory for every allocation
pointer), they are too slow, and they still don't do exactly what I
need (dump callstacks sorted by counts), so I will have to write some
scripts parsing the output
dmalloc library (dmalloc.com) requires new binary
LeakTracer (http://www.andreasen.org/LeakTracer/) Works only with C++
new/delete (I need malloc/free as well), does not have group-by-stack
and sort functionality
Implementing the tool myself as .so library using LD_PRELOAD
mechanism
(Overriding 'malloc' using the LD_PRELOAD mechanism)
That will take at least a week given my coding-for-Linux skills and it feels
like inventing a bicycle.

Did I miss anything? Are there any lightweight Valgrind options or existing LD_PRELOAD tool?
Comment: You know your code better than anyone. Can you get a process dump and look at the heap to find out what is slowly chewing memory off the cob ? Start with common structure allocations that are likely in the *customer's* environment.
Comment: I can get dumps, but there are too many allocations from normal execution flow in addition to the ones contributed by the leak. Some automatic tool is still required. In any case stacks would be much more informative than structures alone.
Comment: This appears fitting: https://github.com/jrfonseca/memtrail "A LD_PRELOAD based memory profiler and leak detector for Linux "
Answer: GNU libc has built-in malloc debugging:
http://www.gnu.org/software/libc/manual/html_node/Allocation-Debugging.html
Use LD_PRELOAD to call mtrace() from your own .so:
#include <mcheck.h>
static void prepare(void) __attribute__((constructor));
static void prepare(void)
{
    mtrace();
}

Compile it with:
gcc -shared -fPIC dbg.c -o dbg.so

Run it with:
export MALLOC_TRACE=out.txt
LD_PRELOAD=./dbg.so ./my-leaky-program

Later inspect the output file:
mtrace ./my-leaky-program out.txt

And you will get something like:
Memory not freed:
-----------------
           Address     Size     Caller
0x0000000001bda460     0x96  at /tmp/test/src/test.c:7

Of course, feel free to write your own malloc hooks that dump the entire stack (calling backtrace() if you think that's going to help).
Lines numbers and/or function names will be obtainable if you kept debug info for the binary somewhere (e.g. the binary has some debug info built in, or you did objcopy --only-keep-debug my-leaky-program my-leaky-program.debug).

Also, you could try Boehm's GC, it works as a leak detector too:
http://www.hpl.hp.com/personal/Hans_Boehm/gc/leak.html
Comment: Then I would keep an fixed-size hash table around; insert a record for every `malloc()`, delete it for every `free()`, and only output to the file if a collision happened. With the appropriate size it should be enough to discard short-lived allocations from appearing in the output file. Writing to the file can be done in a dedicated thread, with the help of a concurrent queue.
Comment: Thanks. This is a valid approach. But there are some problems though. Disk space: say, with 10^4 allocations per sec and 50 bytes per record we will have 5G file in about 3 hours. The leak becomes visible after several days. Performance: hopefully file writes are asynchronous, but I think they are still more expensive than storing stack trace along with allocation. I have to do some perf tests first. Coding: I still have to implement group-by-stack-trace and order-by-count functionality.
Comment: Sadly in many modern projects that use `xmalloc` and other `malloc` wrappers `mtrace` becomes useless as it will point to that generic wrapper rather than the function calling it. Luckily, there are other options described in the other answers that obviate that issue by means of stack unwinding etc. To put it short: `mtrace` is—alas!—obsolete for most practical purposes.
Comment: @undercat, it's enough if the project is in C++ where `operator new` is that generic wrapper.
Answer: I would like to advertise my just announced heaptrack utility, which should be just what you where looking for back then. You can find more information here: http://milianw.de/blog/heaptrack-a-heap-memory-profiler-for-linux
Compared to your heapwatch tool, the performance should be far better, as I use libunwind and later libbacktrace to delay the annotation of the backtrace with DWARF debug information.
I'd love to get more feedback on it, so try it out!
Comment: I have tried it, together with the companion analysis tool heaptrack_gui, for a memory tracing session of 15 minutes.
when opening the trace with my laptop, it crashed the machine OOM.
So i retried on another machine with 64gb(!) of ram. On this one it managed to run with 28gb of memory used. Unfortunately, after a bit of leaving it alone (although it kept at 100% cpu nevertheless), it almost froze the machine as well, which i managed to salvage via a remote shell i had open there so i could kill the tool.
Comment: @Pa_ please report bugs on https://bugs.kde.org/enter_bug.cgi?product=Heaptrack and ideally attach or upload the heaptrack data file, such that I can reproduce the analysis bug locally and fix it. Reporting bugs should not be done in a forum like SO.
Comment: Well, so feel free to forward it to kde.org.
I can't report since i don't know if this is a bug or it's by design, and so i merely reported my experience. Perhaps the author expects user to have 1TB of ram for using this tool
Comment: @Pa_ I am the author, and no I don't expect you to have so much memory. Please report bugs properly, not on a forum.
Answer: memleax should work for you.
It debugs memory leak of a running process by attaching it, without recompiling program or restarting target process. It's very convenient and suitable for production environment.
It TRAPs only for malloc/free() calls, so it should bring less performace impact than Vagrild.
It works on GNU/Linux-x86_64 and FreeBSD-amd64.
NOTE: I'm the author, any suggestion is welcomed
Comment: I enjoy being able to use this tool without any recompilation.  When interpreting the results though, it doesn't have any concept of "old" buffers, correct?  If I see `alloc=200295` and `free=200293`, those two missing free() calls could be right around the corner right?
Comment: Not exactly. `may-leak` is better. Assume your program alloc() 1 block first, and would free() it 3 second later. But you terminate memleax just after 1 second, before the free(). So this is not a leak, but just no time to free. In this case, `callc=1`, `free=0`, `may-leak=0`.
Comment: BTW, there is a bug in `memleax` to debugging multi-thread program. While I write a new tool [libleak](https://github.com/WuBingzheng/libleak), which is better and without recompliation too.
Answer: MemoryScape would meet your needs. This is the dynamic memory debugging tool that comes with the TotalView debugger.
http://www.roguewave.com/products/memoryscape.aspx
Comment: Yes, it looks like the tool does the job. I will play with the trial version and mark this as an answer if the tool really does by-stack grouping. The software is not free though; getting purchase approved is no faster/easier than writing my own code...
Comment: Oops... Trial version not available for automatic download (they evaluate the request for trial version)
Answer: @glagolig,
Yes, MemoryScape can group allocations by stack location.
Were you able to get the evaluation version? Assuming you used an email address that doesn't look like a bot you should have heard back from us pretty quickly. If not, or if you are having technical trouble with it give me a shout or reach out to our tech support team.
Chris Gottbrath
Principal Product Manager for TotalView at Rogue Wave Software
email: Firstname . Lastname (at) roguewave . com
Comment: Thanks. I will send you an e-mail.
Answer: Surprisingly, I was unable to find anything like Microsoft's UMDH in open-source domain or available for immediate download. (I also looked at Google Heap Leak Checker but it is more like Valgrind rather than to UMDH). So I ended up writing the tool myself using malloc instrumentation project as a reference point:
https://github.com/glagolig/heapwatch
The tool has number of limitations, but it worked just fine for my purposes.
Answer: There is a free, open source tool called chap that will do most of what you want.  It specifically will not give you stack traces, but it is an extremely light weight tool because it doesn't require any instrumentation at all.  All you need is to be able to grab a live core of the process in question, at a point at which you believe the process has already exhibited the bug (so you believe that it has leaked or is too large or whatever).
For details, see https://github.com/vmware/chap
Answer: You might also consider using Google's gperftools, which has a heap profiler that can be loaded via LD_PRELOAD. You can also link in its tcmalloc and leak checker into your binary, and enable them only when needed.
For details, see https://github.com/gperftools/gperftools


Show a unique first names from the patients table that only occurs once in the list

Question: Show unique first names from the patients table which only occurs once in the list.
For example, if two or more people are named 'John' in the first_name column then don't include their name in the output list. If only 1 person is named 'Leo' then include them in the output.
SELECT  first_name
FROM patients
HAVING COUNT(first_name) = 1;
ORDER BY first_name asc

Answer: You are almost there. Your query needs a group by clause, that defines groups of records that should be aggregated together. Here, obviously you want to group by first_name.
SELECT first_name
FROM patients
GROUP BY first_name
HAVING COUNT(*) = 1
ORDER BY first_name

Note that COUNT(*) is good enough here, as it counts how many records belong to each group; COUNT(x) is a slightly different thing, that counts how many non-null valuds of x exist.
Also note that asc is the default sort order, so it can be omitted.


How to get next auto increment id in SQL

Question: I have inserted an auto-incremented ID in SQL Server with this code:
[EmployeeID] AS ('EMP' + RIGHT('0000' + CONVERT([VARCHAR](5), [UserID]), (5))) + 1 PERSISTED,

And I want the next EmployeeID like if last inserted record is EMP0001, then I want to show EMP0002 when using a select query.
Comment: What's the purpose? You can't get the next id and store it somewhere and assume it'll be unused when you finally get around to inserting it into the database. If you want to use a database to store unique id's, don't try convoluted methods of generating them. Use an `IDENTITY`, insert a record to "reserve" it and let the database reserve it. Otherwise you have no guarantee the ID is unique when you finally put it in the database.
Comment: @Nick.McDermaid. Just want to display before saving in database
Comment: If this is a multi user system, then by the time you have displayed it, someone else has probably got the same number. For example if two people run your code, they get the same number, The first was to insert is OK. The next gets a PK error (or worse... simply inserts a duplicate)
Comment: You can use a `SEQUENCE` to ensure that two users won't get the same number.... _and_ you can just select from it, you don't have to insert. http://www.sqlservertutorial.net/sql-server-basics/sql-server-sequence/ The `EMP` part is simply formatting using whatever means.. a calculated column or you could do it in your app.
Answer: first put the id column as identity column
after that insert your data. no need to specify id columns it auto increments.
and put identity increment to your initial number and how much it should be incremented is given in identity seed.
check for identity columns in youtube for better understanding.
tq
Answer: You need to store max value of employee ID in to declared variable. From that you will separate EMP and Number.
After that you can increase number value by 1 and use REPLICATE() for generate preceding 0.
Please check below query for your answer.
DECLARE @EMPID VARCHAR(10)

SELECT
@EMPID = MAX(X.EmployeeID)
FROM
(
SELECT 'EMP0008' EmployeeID UNION ALL
SELECT 'EMP0011'
) X

SELECT 'EMP' + REPLICATE('0',4 - LEN(RIGHT(@EMPID,4) + 1)) + CONVERT(VARCHAR(10),(RIGHT(@EMPID,4) + 1)) AS EmployeeID

Demo


decompress split zip files (with zipsplit) in one shot

Question: I'm using the split feature of zip (zipsplit) on very large files (300GB).
file_parts.z01
file_parts.z02
file_parts.z03
file_parts.z04
file_parts.z05
file_parts.zip

Then to extract the content, the current solution is:
zip -s 0 file_parts.zip --out recombined.zip
unzip recombined.zip

However, it's very slow because it requires a lot of I/O to write the final zip file to disk.
How to recombine the split files and unzip in one shot, without writing the recombined split file on disk?
Thanks!
Answer: one can directly unzip the last file:
unzip file_parts.zip

7z can also unzip multi-part zip archives.
7z x file_parts.zip


How can I do the dynamic select in Drupal 7 forms?

Question: In the following code I call the function players() which returns array of values for option. This values were defined beforehand by hand. How can I load it dynamically from the database?
<code> $form['officers']['officer'] = array(
'#title' => t('Select the officer'),
'#type' => 'select',
'#description' => t('Please, select the officer'),
'#options' => players(),
'#multiple' => FALSE,
'#empty_value' => ' ',
'#empty_option' => '- None -',
</code>
);
For example in the "Text Field"  there is property #autocomplete which defines a path where Drupal's automatically included JavaScript will send HTTP requests using jQuery.
<code> $form['team_name'] = array(
'#title' => t('Name'),
'#type' => 'textfield',
'#description' => t('Please, insert your name'),
'#autocomplete_path' => 'autofillform/teamname' ,
</code>
);
And i created the module which handles it.
<code><?php
function autofillform_menu() {
$items['autofillform/teamname'] = array(
'title' => 'Example autocomplete',
'page callback' => 'autofillform_teamname',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
 );
 return $items;
 }
 function autofillform_teamname($string){
 $matches = array();
 $result = db_query("SELECT name FROM users where lower(name) like '".$string."%'  LIMIT 10");
 foreach ($result as $user) {
 $matches[$user->name] = check_plain($user->name);
  }
 print drupal_json_encode($matches);
 return;
 }
</code>
Are there any possibility to do the same with "Select" ?
Comment: Do you want to load them dinamicazlly with ajax or you want to load them from the db in php?
Comment: I want to do it in the same manner as I did for "Text field" I did it using php and then converted variables using drupal_json_encode($matches);
Comment: I edited the post. I added the module to show how i did it with TextField.
Answer: In any case take a look at the first answer of this question: i think it's what you are lloking for https://stackoverflow.com/questions/5158744/drupal-7-best-practice-for-a-dynamic-select-list-in-drupal-7


Emacs Lisp: Open a new frame, start IPython, run previous buffer

Question: I want to write an ELisp function to start a Python interpreter (IPython) in a new frame and then run the contents of the previous buffer in the IPython interpreter.  I am using Emacs 23.3.1, python-mode 6.0 and ipython.el.
Here's my function so far:
(defun python-run ()
  "Use to run Python programs."
  (interactive)
  (let (my-buffer-name buffer-name)
    (select-frame (make-frame))
    (set-frame-size (selected-frame) 90 60)
    (py-shell)
    (delete-other-windows)
    (switch-to-buffer my-buffer-name)
    (py-execute-buffer)))

The output is that:

IPython successfully starts via py-shell.
There is still two windows in the frame, not one like I want.
It doesn't successfully execute the buffer, output is:

In [1]: execfile(r'/var/folders/so/sox1TODiEE0hAb6AVusYq++++Tc/-Tmp-/python-26368Zoi.py') # PYTHON-> MODE
---------------------------------------------------------------------------
IOError
Traceback (most recent call last)
/Users/ben/ in ()
----> 1 execfile(r'/var/folders/so/sox1TODiEE0hAb6AVusYq++++Tc/-Tmp-/python-26368Zoi.py') # PYTHON-> MODE
IOError: [Errno 2] No such file or directory: '/var/folders/so/sox1TODiEE0hAb6AVusYq++++Tc/-Tmp-> /python-26368Zoi.py'
In [2]: ## working on region in file /var/folders/so/sox1TODiEE0hAb6AVusYq++++Tc/-Tmp-/python-> 26368fXv.py...
execfile(r'/var/folders/so/sox1TODiEE0hAb6AVusYq++++Tc/-Tmp-/python-26368fXv.py') # PYTHON-MODE
File "/var/folders/so/sox1TODiEE0hAb6AVusYq++++Tc/-Tmp-/python-26368fXv.py", line 1
   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    ^
SyntaxError: invalid syntax

Any thoughts on how to get either the single window or the buffer to be executed?  Thanks!
Answer: Not sure about that python output but in the elisp code you are not setting my-buffer-name to anything (it will be nil). It should be:
(let ((my-buffer-name (buffer-name))
   ....

Comment: Thanks for that.  It sort of works now.  The first time python-run is called, when it tries to execute py-execute-buffer it fails, but the next time it works.


High E String Buzzing Only When Picked Open

Question: I have an LTD H-1001 which I bought, used, about a month ago. Everything was close to perfect with it, until I tuned it back down from E standard to its usual Drop C tuning it's set up for. The guitar was set up for 12-54 gauge string, but I switched to a 10-52 set, but even after I did that, this problem only occurred after de-tuning from E standard, and it still persists after I placed a 14 gauge string in there, so I don't think it's the string gauge. After that, whenever I play the open high E string, and only when it's open, it buzzes unusually.
After some research and inspecting the guitar, I think the problem is that the nut slot for the string is slightly deeper than it should be, resulting in the open string almost touching the first fret.
Is there any way to raise that one specific nut slot without replacing the nut? I would like to avoid replacing the current nut with a new one, as it would mean that I would have to file the slots, and I don't have any experience with that sort of thing, nor do I have any repair shops close to me as far as I know. Any help is greatly appreciated, thanks!
Answer: Before doing anything you can test it by putting a thin piece of paper or something similar between the E string and the nut to temporarily raise it slightly. If this eliminates the buzz then you can be pretty sure the problem is the nut slot has worn down. The superglue suggestion sounds like it could work.
Comment: I've used the paper trick as a temporary fix, which became permanent over a few years. By the time the string has squashed the paper in the slot, it becomes pretty hard, and in my case(s) didn't damp or mute the string. +1, you beat me to it.
Comment: @Ken, Im glad this is working for you,  you've gotten a lot of useful info on the various answers and comments. I just wanted to also point out that the paper trick solves 2 issues simultaneously, it raises the string of course but it also narrows the slot. The width can also possibly be the cause of the buzz so when you get around to repairing it make sure you use a file with the correct width for the gauge string you plan on using.
Comment: It's situations like this that I ask - why don't all manufacturers use a *zero fret*? I have several guitars which are happy possessors, and this problem could never occur on them. And that apart, isn't a zero fret even better than a brass nut?
Comment: @Tim You're right, if you get the right thickness and seat it well it can actually work well and last a long time.
Comment: Thank you very much! This method is working for me right now, so as I suspected it is the nut slot that is the problem.
Comment: @Tim I'm also a fan of the zero fret but unfortunately you don't see them much.
Answer: You can use superglue to add material to the nut slot. Add a drip or two and wait for it to completely dry. I've also heard that you can mix baking soda with the superglue for extra hardness but I haven't tried that myself. It may need a little filing to get the right shape.
You might also try raising the action slightly at the bridge. This would move the string away from the fret.
Video
Comment: Thank you for your response! I will try this as soon as I get the chance to buy some super glue, haha!
Answer: Mainly, it's going to be string height and/or the angle at which the string vibrates.
If you change string gauges, you will most definitely get string buzz. That's strictly based on the fact that a heavier gauge string (or set of strings) adds more tension on the whole construction of the guitar. To a certain extent, the neck of the guitar is flexible. The same thing happens when you detune a string, as the neck will be "pulling" itself back, thus slightly reducing string height.
On electric and acoustic guitars the neck will almost always contain 1-2 truss rods. The way these work is that they internally tighten the neck so as to compensate (and almost match) the tensions with which the strings are pulling.
You need to slowly and slightly adjust the truss rod, retune the whole guitar, allow to sit for a bit of time, and test again. You need to allow the wood to settle before adjusting again. Your best bet is to only adjust by turning it no more than a quarter of a turn at a time. Keep in mind that the neck is supposed to have a slight bow.
Moving on, there are other factors which will contribute to fret buzz, too. On your particular type of guitar, the bridge has two height screws for each string. Technically, you want to adjust them so that the strings are level. Adjusting those two screws independently will also permit the string to vibrate at an angle, too. Keep in mind that strings don't only vibrate on a single axis.
The odds of having issues with the depth of the slot for the E string are rather low, I would say. Be aware of the fact that nut slots have different depths and widths, based on the string gauge. The slot for a low E will be wider than the one for the high E - and that's perfectly normal. More depth is needed so that the string doesn't simply fall off the nut when you're playing.
Of course, what I've mentioned here is just theory. I suggest, like many others have, to search for tutorials on how to properly adjust your type of guitar. By "type", I don't necessarily mean the specific model of guitar, but the type of truss rod configuration (I presume yours only has one, with adjustment access on the headstock, behind the little plastic triangle with "H-1001" written on it) and bridge type.
Whilst you're at it, I'd also recommend adjusting intonation, too. That involves adjusting string length in order for notes to be perfectly in tune regardless of the fret.
A few things you might want to know before proceeding:
- Adjusting your truss rod is somewhat dangerous. If you overtighten it, you can snap the neck.
- Adjusting the truss rod with the wrong tool is going to be bad, too. Make sure you're using the appropriate metric/imperial allen keys. The small difference between very similar metric/imperial key sizes will wear out the bolt, and you'll almost never going to be able to adjust it again.
- Make sure to not adjust the rod more than it can go. On certain guitars, it's hard to feel.
- Be prepared for this to take a full day if it's the first time you attempt it.
Good luck!
Comment: Thank you for your detailed response! In my instance, it was the nut slot that was the issue as inserting a piece of paper between the high e string and the nut fixed the issue temporarily, but I absolutely appreciate the detail in your answer, thank you again!
Comment: A pleasure, don't worry. It's hard to say as I'm not literally holding your guitar, but it's very possible to fix fret buzz by raising the string with something like a piece a paper. Physically, the result will be identical. If the nut is, indeed, broken, you might want to lift it with something like a piece of plastic film, as it will reduce friction. Friction points are very undesirable, as they'll get your strings out of tune quickly after bends.
Comment: Because the issue happened only after drop-tuning, I think this is the best answer, as the reduced string tension would cause the neck to unbow, bringing strings closer to the frets. Raising the string at the nut might fix the buzz, but isn't solving the underlying problem.
Answer: Like in the video BUT cover the nearby fretboard with tape first! You don't want glue on the fretboard!
Comment: @Ken and in a pinch, you can try this harmless hack: pull the string out of its saddle, place a small piece of paper over the saddle, and put back the string over the paper. Then somehow remove all the paper that remains outside, until the only paper remaining is the portion pinched between the string and the nut.That little paper may be just enough to lift the string and stop the buzzing. Of course it's not a permanent solution, but it's nice if it works, and one always learn something while tinkering with things... --- and I just realized that someone else already wrote the same thing! :)
Comment: Thank you very much for the video response! If I ever get some files I will certainly try this.
Comment: A luthier friend of mine inserts the superglue with the end of an old E string.
Answer: The nut is the problem, but it might not be the height of the slot but the shape of it.  If you look closely you should be able to see if the string is touching the fret during vibration.  If you are sure that it is not touching but you still hear something weird (more like a hizz than a buzz), it is gonna be the shape of the slot that is creating the trouble.
If the slot is not cut properly, it creates an imperfect point of contact with the string.  Most of the time it is due to a contact point not sitting on the edge of the nut that is closest to the fingerboard.  If the contact point sit just a little into the middle of the nut, the vibrating string might touch the nut and create that annoying hiss.
Comment: I agree with user9868. Thank you. That was my problem, the highest point of contact of the nut should be on the edge, otherwise string vibrates against nut sides. First, I checked if it was fret buzz between open string and first fret, then I realized... I took a simple cutter and pass it a few times with an angle of 30 to 45 degrees and back to tune. It worked great. Thank you very much
Answer: First off, I don't play guitar, I play electric bass.
As you mentioned, the string could be touching the fret. That is very likely. However, depending on the bridge that you have, the connector for the high E string could be wobbling, causing the buzzing sound. I'm guessing that because this only happens when the string is played open, that the string is rubbing against the first fret like you said. This can usually be fixed by adjusting the truss rod inside the neck, and it's probably not necessary to adjust the nut. Usually this is done by a professional, but giving your circumstances, the best you can do is to watch a video on ow to safely adjust the truss rod.
Comment: Thank you for your response! I do not believe it has anything to do with the truss rod as that would mean the other strings would be buzzing as well, but it is only the high e string, and I have also adjusted it before, but thank you for your detailed response!
Answer: Everyone says it is the nut. However, trust me it could also be a loose fret that is vibrating. And yes, they do vibrate at a particular frequency.


Problems with html and css design

Question: I got a problem with making a menu.
I can't figure out how to make it a drop down menu although I've basically tried everything under the sun!
This is a company project and I need to get a drop down menu going!
So to give you an example - here's the link to the website I am working on right now -
http://smartliving.comule.com/brands.html. Please exclude the "css" or "cssmenu" tags in the previous tags!
The HTML code is as follows - the navigation bar is here: .
<!DOCTYPE html>

<title>Smart-Living Bangladesh (BD)</title>

    <link rel="stylesheet" href="abs.css">
    <link rel="stylesheet" type="text/css" href="demos/css/search.css" />

    <link rel="stylesheet" type="text/css" href="demos/css/elastislide.css" />

    <link rel="stylesheet" type="text/css" href="demos/css/elastislide1.css" />
    <link rel="stylesheet" type="text/css" href="demos/css/custom.css" />

    <link rel="shortcut icon" href="demos/images/favicon.ico" type="image/x-icon">
    <link rel="apple-touch-icon" href="demos/images/apple-touch-icon.png">

    <link rel="stylesheet" href="demos/prettify/prettify.css" media="screen">

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css">

    <link rel="stylesheet" href="css/anythingslider.css">

    <link rel="stylesheet" href="css/theme-metallic.css" media="screen">

    <link rel="stylesheet" href="demos/css/pages.css">
    <link rel="stylesheet" href="demos/colorbox/colorbox.css">

    <meta http-equiv="content-type" content="text/html; charset=utf-8" />

    <meta name="description" content="" />

    <meta name="keywords" content="" />

    <meta name="author" content="" />

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

    <meta name="keywords" content="carousel, jquery, responsive, fluid, elastic, resize, thumbnail, slider" />

    <meta name="author" content="Codrops" />

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

    <meta name="keywords" content="carousel, jquery, responsive, fluid, elastic, resize, thumbnail, slider" />

    <meta name="author" content="Codrops" />

    <link rel="shortcut icon" href="../favicon.ico">

<title>SMART LIVING BANGLADESH (BD)</title>

            <form action="" id="search-form">
                <fieldset>
                    <input type="text" id="search" name="search" />
                    <input type="submit" id="search-submit" value="" />
                </fieldset>
            </form>

    Home
    About Us
    FAQ
    New Products
    Brands
    Gallery
    Shopping Cart
    News

    Wish List
    Contact

 © 2014 - Smart Living BD

Here's the PHP code for the page above - http://smartliving.comule.com/demos/css/pages.css
I have reproduced the code below. Please tell me how I can fix up the #nav tags and make a drop down menu for different brand names be displayed. I have tried with other codes and mixed it with different kinds of codes and ended up with mixed results.
body {
font-family: georgia,sans-serif;
font: normal 85%/1.1 "Lato", sans-serif;
color: white;
text-align: center

color:#333;
margin:0;
padding:0;
}

#wrapper {
width:960px;
/*background-color:#f1f1f1;*/
margin:0 auto;

}

#header {
width:960px;
height:135px;
margin:0 auto;

}

#nav {
width:960px;
height: 40px;

}
#nav span,
#nav a {
display:inline;
text-decoration:none;
background-color:#ffffff;
}

#nav a:hover {
background-color:#000000;
height:40px;
}

#featured {
width: 960px;
height: 301px;
margin: 0 auto;

}

#bodies {
width: 960px;
margin: 0 auto;
background-color: #f1f1f1;

}
#leftcolumn {
width:720px;
padding: 0;
margin: 0;
border:0;
float:left;

}
#rightcolumn {
width:240px;
padding: 0;
margin: 0;
border:0;
float:right;
}
#leftcolumn1 {
width:720px;
padding: 0;
margin: 0;
float:left;

}
#rightcolumn1 {
width:240px;
padding: 0;
margin: 0;
border:0;
float:right;

}

#leftsidebar {
width:200px;
padding: 0;
margin: 0;
border:0;
float:left;
}

#leftsidebar a {
text-decoration:none;
}
#leftsidebar ul, li{
list-style: none;
margin: 0;
padding: 0;
}
#leftsidebar li {
list-style:none;
}
#content {
width:560px;
position: relative;
float:center;
padding:10px;
}

#rightsidebar {
width:200px;
float:right;
}

#rightsidebar a {
text-decoration:none;
}

#rightsidebar li {
list-style:none;
}
#news-container{
    width: 230px;
    float: right;
    position: relative;
    margin: auto;
    border: 5px solid #333333;
}

#news-container ul li div
{
    border: 2px solid #aaaaaa;
    background: #ffffff;
}

#footer {
clear:both;
width:960px;
height:50px;

}

#footer p {
padding:5px;
}

/********************
  Overall Demo pages
 ********************/
body                   { font: 12px Georgia, Serif; background: #fff; color: #000; }
a, a img               { border: 0; text-decoration: none; }

#page-wrap, #demo2     { width: 100%; padding: 0 0px; margin: 0 auto 0px; position: relative; }

h1                     { font: bold 60px Helvetica, Sans-Serif; letter-spacing: -2px; margin: 10px 0; text-align: center; }
h2                     { font: bold 30px Helvetica, Sans-Serif; letter-spacing: -1px; margin: 0 0 10px 0; color: #000000; }
h2.title               { text-align: center; }
h3                     { font: bold 20px Georgia, Serif; margin: 0 0 10px 0; color: #003388; }
h5, .header            { font: bold 15px Georgia, Serif; text-align: center; }
pre, code              { font: 10px/1.8 Monaco, MonoSpace; margin: 0 0 15px 0; padding: 5px; background: #f5f5f5; block: inline; width: 100%; overflow-x: auto; }
blockquote             { margin-left: 30px; }

ul                     { margin: 0; padding-left: 35px; }
ul li                  { font: 15px Georgia, Serif; margin: 0 0 8px 0; }

#nav                   {
display: block;
width: 100%;
margin: 0px auto;
text-align: center;
line-height: 3em;
}
#nav a                 {
text-align: center;
background: black;
color: white;
border-radius: 5px;
-moz-border-radius: 0px;
-webkit-border-radius: 5px;
padding: 12px;
white-space: nowrap;
}
#nav a.issue           {
background: #FF8C00;
}
#nav a:hover,
#nav a.current {
background: #000; }
#nav .has-sub {
    z-index: 1;
}

#nav ul {
  list-style: none;
}
#nav > ul {
  float: left;
}
#nav > ul > li {
  float: left;
}
#nav > ul > li > a {
  color: #FFFFFF;
  font-size: 12px;
}
#nav > ul > li:hover:after {
  content: '';
  display: block;
  width: 0;
  height: 0;
  position: absolute;
  left: 50%;
  bottom: 0;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 10px solid #FF8C00;
  margin-left: -10px;
}
#nav > ul > li:first-child > a {
  border-radius: 5px 0 0 0;
  -moz-border-radius: 5px 0 0 0;
  -webkit-border-radius: 5px 0 0 0;
}
#nav > ul > li.active:after {
  content: '';
  display: block;
  width: 0;
  height: 0;
  position: absolute;
  left: 50%;
  bottom: 0;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 10px solid #FF8C00;
  margin-left: -10px;
}
#nav > ul > li.active > a {
  -moz-box-shadow: inset 0 0 2px rgba(0, 0, 0, 0.1);
  -webkit-box-shadow: inset 0 0 2px rgba(0, 0, 0, 0.1);
  box-shadow: inset 0 0 2px rgba(0, 0, 0, 0.1);
  background: -moz-linear-gradient(top, #FF8C00 0%, #ffeeff ef 100%);
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ececec), color-stop(100%, #FF8C00 ef));
  background: -webkit-linear-gradient(top, #FF8C00 0%, #ffeeff ef 100%);
  background: -o-linear-gradient(top, #FF8C00 0%, #ffeeff ef 100%);
  background: -ms-linear-gradient(top, #FF8C00 0%, #ffeeff ef 100%);
  background: linear-gradient(top, #FF8C00 0%, #ffeeff ef 100%);
}
#cssmenu > ul > li:hover > a {
  background: #FF8C00;
  background: -moz-linear-gradient(top, #FF8C00 0%, #ffeeff ef 100%);
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ececec), color-stop(100%, #FF8C00 ef));
  background: -webkit-linear-gradient(top, #FF8C00 0%, #ffeeff ef 100%);
  background: -o-linear-gradient(top, #FF8C00 0%, #ffeeff ef 100%);
  background: -ms-linear-gradient(top, #FF8C00 0%, #ffeeff ef 100%);
  background: linear-gradient(top, #FF8C00 0%, #FF8800 ef 100%);
  -moz-box-shadow: inset 0 0 2px rgba(0, 0, 0, 0.1);
  -webkit-box-shadow: inset 0 0 2px rgba(0, 0, 0, 0.1);
  box-shadow: inset 0 0 2px rgba(0, 0, 0, 0.1);
}
#nav .has-sub {
  z-index: 1;
}
#nav .has-sub:hover > ul {
  display: block;
}
#nav .has-sub ul {
  display: none;
  position: absolute;
  width: 200px;
  top: 100%;
  left: 0;
}
#nav .has-sub ul li {
  *margin-bottom: -1px;
}
#nav .has-sub ul li a {
  background: #FF8C00;
  border-bottom: 1px dotted #ffa333;
  filter: none;
  font-size: 11px;
  display: block;
  line-height: 120%;
  padding: 10px;
  color: #ffffff;
}
#nav .has-sub ul li:hover a {
  background: #cc7000;
}
#nav .has-sub .has-sub:hover > ul {
  display: block;
}
#cssmenu .has-sub .has-sub ul {
  display: none;
  position: absolute;
  left: 100%;
  top: 0;
}
#cssmenu .has-sub .has-sub ul li a {
  background: #cc7000;
  border-bottom: 1px dotted #ffa333;
}
#cssmenu .has-sub .has-sub ul li a:hover {
  background: #cc7000;
}

#nav .has-sub:hover > ul {
    display: block;
}
#nav .has-sub ul {
    display:none;
    position: relative;
    width: 200px;
    top: 100%;
    left: 0;
}
#nav .has-sub ul li{
    *margin-bottom: -1px;
}
#nav .has-sub ul li a {

    backgroun: #ff8c00;
    border-bottom: 1px dotted #ffa333;
    filter: none;
    font-size: 11px;
    display: block;
    line-height: 120%;
    padding: 10px;
    color: #ffffff;
}
#nav .has-sub ul li:hover a {
  background: #cc7000;
}
#nav .has-sub .has-sub:hover > ul {
  display: block;
}
#nav .has-sub .has-sub ul {
  display: none;
  position: absolute;
  left: 100%;
  top: 0;
}
#nav .has-sub .has-sub ul li a {
  background: #cc7000;
  border-bottom: 1px dotted #ffa333;
}
#nav .has-sub .has-sub ul li a:hover {
  background: #b36200;
}
.themeselector, .ani   { margin: 0 auto; text-align: center; }

#status                { color: #00a; font-weight: bold; }
.alert                 { color: #f00; font-weight: bold; }
.alert a, .attention   { color: #a00; }
.data                  { width: 100%; border: #555 0.5px solid; border-collapse: collapse; }
.data td, .data th     { border: #555 0.5px solid; padding: 0 5px; }
.data th               { background: #eee; }
.data .col             { width: 200px; }

/*****************
  Main demo page
 *****************/
#main #slider1         { width: 800px; height: 390px; list-style: none; }
#main #slider1 .panel5 ul { width: 200px; margin: 0 5px; }

/* For Specific Slides, these also apply to FX demo pages */
.textSlide             { padding: 10px 10px; }
.textSlide h3          { font: 20px Georgia, Serif; }
.textSlide h4          { text-transform: uppercase; font: 15px Georgia, Serif; margin: 10px 0; }
.textSlide ul          { list-style: disc; margin: 0; padding-left: 20px; }
.textSlide ul li       { display: list-item; }
.rightside             { float: right; margin: 0 0 2px 10px; }

.quoteSlide            { padding: 20px; }
.quoteSlide blockquote { font: italic 24px/1.5 Georgia, Serif; text-align: center; color: #444; margin: 0 0 10px 0; }
.quoteSlide p          { text-align: center; }

/***************************
  FX Demo Page
 ***************************/
/* Demo page accordions */
.accordion             { width: 100%; margin: 0 auto; }
.accordion .ui-widget-content a { color: #000000; }

/** Demo 1 **/
/* colorbox images to full size */
#demo2 #slider1        { width: 960px; height: 300px; list-style: none; }
.cboxPhoto             { width: 100%; height: 100%; margin: 0 !important; }
#cboxTitle             { color: #000 !important; }

/* Change metallic slider defaults to show thumbnails -
  using #demo2 (page wrapper) to increase this CSS priority */
#demo2 div.anythingControls { bottom: 15px; }
#demo2 div.anythingSlider-metallic .thumbNav a { background-image: url(); height: 10px; width: 30px; border: #000 1px solid; border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; }
#demo2 div.anythingSlider-metallic .thumbNav a span { visibility: visible; }

/* border around image to show current page */
#demo2 div.anythingSlider-metallic .thumbNav a:hover,
#demo2 div.anythingSlider-metallic .thumbNav a.cur { border-color: #fff; }
/* reposition the start/stop button */
#demo2 div.anythingSlider-metallic .start-stop { margin-top: 15px; }

/** Demo 2 **/
#demo2 #slider2        { width: 400px; height: 300px; list-style: none; }

/** Demo 3 **/
#demo2 #slider3        { width: 500px; height: 400px; list-style: none; }

/* position caption close button */
.caption-top .close,
.caption-right .close,
.caption-bottom .close,
.caption-left .close   { font-size: 80%; cursor: pointer; float: right; display: inline-block; }

/******************
  Expand demo page
 ******************/
#wrapper1              { width: 100%; height: 300px; margin: 0 auto; }
#wrapper2              { width: 50%; height: 300px; margin: 0 auto; }
#expand #slider1,
body#expand h2,        {margin-bottom:25px; }

/***************************
  Video Compatibility table
 ***************************/
.video-info            { width: 700px; margin: 0 auto; margin-top: 50px; font-size: 18px; }
.video-info h2         { text-align: center; }
.video-info ul,
.video-info li         { margin: 0; }
.video-info sup        { font-size: 12px; }
.video-info th.header  { width: 25px; }
.good, .bad, .prob     { color: #ddd; text-align: center; }
.good                  { background: #080; }
.bad                   { background: #800; }
.prob                  { background: #880; }
.group                 { border: #000 1px solid; }

/******************
  css3 demo page
 ******************/
.animations            { margin: 10px 10px 10px 5px; }
.ani                   { margin-top: 5px; }

/******************
  tooltips (Jatt)
 ******************/
.tooltip { cursor: pointer; }
#tooltip {
 min-width: 10px;
 color: #dddddd;
 background: #444;
 border: 1px solid #777;
 padding: 8px;
 display: none;
 opacity: 0.9;
 filter: alpha(opacity=90);
 text-align: left;
 border-radius: .5em;
 -moz-border-radius: .5em;
 -webkit-border-radius: .5em;
 z-index: 1000;
}
#tooltip .body {
 display: block;
 text-align: center;
}

Answer: It is quite simple if you know how to do it. What you need to do is have a
 then inside that
 another then in the styling what you need to do is when you hover over one of the
 elements it displays the
 inside it.
Here is an example:
http://jsfiddle.net/nvns3/
Code:
HTML:

Hello 1

Hello 1.1

Hello 2

CSS:
.menu li {
    list-style-type: none;
    float: left;
    margin: 0;
    position: relative;
    padding: 0;
}
.menu, .menu ul {
    display: inline-block;
}
.menu li > a {
    padding: 5px;
    padding-left: 10px;
    padding-right: 30px;
    white-space: nowrap;
}
.menu li > a:hover {
    background: blue;
     color: white;
}
.menu > li ul {
    position: absolute;
    display: none;
}
.dropdown > a:hover + ul {
    display: block;
    left: -40px;
    top: 26px;
}
.dropdown ul:hover {
    display: block;
    left: -40px;
    top: 26px;
}

Comment: i did that...it gives me lots of problems... can u just write a sample  code and place it inbetween the clauses...i'll see if it works or not!

Problems with html and css design


Formatar dados antes de salvar no banco

Question: Estou utilizando o Laravel para desenvolver um sistema, porém estou com um problema nos dados vindo de um formulário, preciso formatar uma dado no seguinte formato (#.##) para realizar determinados cálculos, o problema que o valor vem com o seguinte formato (###.#) fazendo o valor final sair errado, não sei como eu posso formatar esse dado no Controller ou antes de fazer o envio dele.
Segue o código do input
Peso (Kg) :
<input type="text" name="peso" class="form-control" v-model="peso"/>
Altura (m) :
<input type="text" name="altura" class="form-control" v-model="altura" v-mask="'#.##'"/>

<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" value="Enviar" class="btn btn-success pull-right"/>

Segue o código do Controller onde eu preciso validar os dados
public function store(ImcRequest $request)
{
    $imc = new Imc;
    $imc->peso = $request->peso;
    $imc->altura = $request->altura;
    $altura2 = ($imc->altura) * ($imc->altura);
    $imc->imccalculado = ($imc->peso / $altura2);

    if (($imc->imccalculado) < 16.00) {
        $imc->classificacao = 'Magreza severa';
    } elseif (($imc->imccalculado >= 16.00) && ($imc->imccalculado <= 16.99)) {
        $imc->classificacao = 'Magreza moderada';
    } elseif (($imc->imccalculado >= 17.00) && ($imc->imccalculado <= 18.40)) {
        $imc->classificacao = 'Magreza leve';
    } elseif (($imc->imccalculado >= 18.5) && ($imc->imccalculado <= 24.99)) {
        $imc->classificacao = 'Normal';
    } elseif (($imc->imccalculado >= 25.00) && ($imc->imccalculado <= 29.99)) {
        $imc->classificacao = 'Preobeso';
    } elseif (($imc->imccalculado >= 30.00) && ($imc->imccalculado <= 34.99)) {
        $imc->classificacao = 'Obesidade leve';
    } elseif (($imc->imccalculado >= 35.00) && ($imc->imccalculado <= 39.99)) {
        $imc->classificacao = 'Obesidade media';
    } elseif (($imc->imccalculado) >= 40.00) {
        $imc->classificacao = 'Obesidade morbida';
    }

    $imc->user_id = Auth::id();
    $imc->save();

    return redirect('/imcs');
}

Comment: De onde vem as informações? do banco de dados? você pode alterar a mascara no banco, não seria o caso?
Comment: As informações o usuário informa em um formulário, antes de salvar no banco eu realizo um calculo, pelo valor vim com o formato errado no formulário ele acaba salvando errado no banco.
Comment: Como está definido o migrations do `User` ? Em qualquer caso você pode adicionar ao model do `User` uma função assessora para obter o campo formatado da forma que pretende.
Comment: E como eu faria isso no model? Sou novo no Laravel.
Comment: Guilherme você está enviando isso com Ajax? pelo Angular ? e o formato seria na v-model Altura? tem como dizer como você está enviando e isso constar na sua pergunta!
Comment: Estou submetendo o formulário pelo método POST, o v-model foi um teste que fiz e não funcionou, estou usando vue para exibir os dados do usuário, mas isso é feito somente após o cálculo ser efetuado.
Answer: Tenta usar:
$imc->peso = number_format($request->peso, 2, '.');
$imc->altura = number_format($request->altura, 2, '.');

Outra opção de gambiarra:
$num = 100.4;
$num = str_replace('.', '', $num);
$num = str_replace(',', '', $num);
echo substr($num, 0, strlen($num)-2).".".substr($num, strlen($num)-2);

Acredito ser melhor tratar números de 3 dígitos com uma mensagem de erro ou mascara no formulário, mas esses são exemplos de gambiarras pra tratamento no controller. Uma dica, verifique como os dados chegam no controller antes, coloque um dd($request->campoX); no inicio do código da função pois o problema pode estar em algum componente carregado no JS da pagina também.

Formatar dados antes de salvar no banco


Como otimizar o tempo desse código?

Question: Criei o código abaixo para resolver o problema Cofre,  da OBI de 2017. Ele funciona, porém em 60% dos casos ele excede o tempo limite, como faço para otimizá-lo?
<code>#include <iostream>
#include <algorithm>
using namespace std;

int main(){
    int N, M, pAnt, pAtual, resp[10]={0};
    cin >> N >> M;
    int seq[N];
    for(int i=0;i<N;i++){
        cin >> seq[i];
    }
    cin >> pAnt;
    resp[seq[pAnt-1]]++;
    for(int i=1;i<M;i++){
        cin >> pAtual;
        if(pAnt<pAtual)
            for(int j=0;j<10;j++)
                resp[j]+=count(seq+pAnt, seq+pAtual, j);
        else
            for(int j=0;j<10;j++)
                resp[j]+=count(seq+pAtual-1, seq+pAnt-1, j);
        pAnt = pAtual;
    }
    cout << resp[0] << " " << resp[1] << " " << resp[2] << " " << resp[3] << " " << resp[4] << " ";
    cout << resp[5] << " " << resp[6] << " " << resp[7] << " " << resp[8] << " " << resp[9] << endl;
    return 0;
}
</code>
Comment: No lugar de para cada algarismo você contar quantas vezes ele ocorre no intervalo não seria mais prático varrer o intervalo uma única vez e incrementar cada ocorrência do algarismo?
Answer: Criar algoritmos é diferente de criar códigos, pois para se criar um algoritmo e bem otimizado, você deve ser um bom matemático e saber bem do funcionamento como um todo de computação.
Sobre a Complexidade de Tempo

Em ciência da computação, a complexidade de tempo de um algoritmo quantifica a porção de tempo tomada por um algoritmo para rodar em função do tamanho da entrada do problema. A complexidade de tempo de um algoritmo é comumente expressada usando a notação big O, que suprime constantes multiplicativas e outros termos de menor ordem. Quando expressada dessa forma, a complexidade de tempo é dito ser descrita assintoticamente, i.e., como o tamanho da entrada vai para o infinito. Por exemplo, se o tempo requisitado por um algoritmo em todas as entradas de tamanho n é no máximo 5n³ + 3n, a assíntota da complexidade de tempo é O(n³).

Sobre o Tempo de Processamento

Medir o tempo gasto por um algoritmo:

Não é uma boa opção
Depende do compilador
Pode preferir algumas construções ou otimizar melhor
Depende do hardware (GPU vs. CPU, desktop vs. smartphone)

Diferentes entradas podem ter custo diferente

Melhor caso
Pior caso
Caso médio

FONTE OFICIAL: WIKIPEDIA
NOTA:

Você pode ler mais sobre este assunto neste link e também para saber os melhores algoritmos criados em relação complexidade de tempo, acesse a fonte oficial acima.

Como otimizar o tempo desse código?


Dúvida com Update no Asp.NET MVC

Question: Desculpe pela pergunta, estou aprendendo Asp.NET com EF e estou tendo problemas ao realizar um Update específico.
Eu quero fazer um sistema em que haja transações em dinheiro entre contas. A parte estrutural está ok, mas o problema é o seguinte:
Quando eu realizo o primeiro update, o sistema faz a transferência normalmente, ou seja, ambas contas tem R$100,00, eu faço a transação de R$10,00, e uma conta fica com R$90,00 e outra com R$110,00.
Já na segunda transferência de mesmo valor, uma conta fica com R$80 e outra com R$100.
    [HttpPost]
    public ActionResult TransferCurrency(Usuario usuario, ViewModelTransfer viewModel)
    {
        if (usuario.Id == 0)
        {
            return HttpNotFound();
        }
        if (viewModel.ForId == null)
        {
            return HttpNotFound();
        }

        var usuarioTransaction = _context.Usuario.Single(c => c.NConta == viewModel.ForId);
        usuarioTransaction.Currency = usuario.Currency + viewModel.Transfer;

        var usuarioInDb = _context.Usuario.Single(m => m.Id == usuario.Id);
        usuarioInDb.Currency = usuario.Currency - viewModel.Transfer;

        _context.SaveChanges();

        return RedirectToAction("Index");
    }

Alguém sabe a solução?
Eu sei que é bem básico, mas não estou conseguindo desenvolver a lógica.
Comment: Dê uma olhada na atribuição, ai que está o problema! pegando valores errados
Answer: O problema aqui não é a primeira, segunda ou terceira transferência... A questão é que nas operações você está atribuindo para os seus _context.Usuario o valor de Currency do objeto Usuario recebido como parâmetro da sua action e adicionando ou substraindo a quantia de Transfer da ViewModel...
    var usuarioTransaction = _context.Usuario.Single(c => c.NConta == viewModel.ForId);
    usuarioTransaction.Currency += viewModel.Transfer;

    var usuarioInDb = _context.Usuario.Single(m => m.Id == usuario.Id);
    usuarioInDb.Currency -= viewModel.Transfer;

    _context.SaveChanges();

Dúvida com Update no Asp.NET MVC


How to add a delete and edit function into my HTML table which is filled with info from my MySQL database?

Question: I've made this simple PHP/HTML table which shows info in my database, now i want to add a delete and edit function using the SQL DELETE and EDIT functions.
How can i implent this so that every row has a delete button and edit button automaticly when its added to the DB?
Table

        CI nummer
        Aankoopdatum
        Serienummer
        Merk
        Model
        OS
        Eigenaar
        Locatie
        Bewerken
        Verwijderen

        <?php
        $conn = mysqli_connect("localhost", "root", "", "teradruk");

        if (mysqli_connect_errno()) {
            echo "Kan geen verbinding maken met de database!";
            exit();
        }

        $sqli = "SELECT * FROM `hardware`";

        if ($stmti = $conn->prepare($sqli)) {
            if (!$stmti->execute()) {
                echo "cant exec:
 " . $stmti->error;
                exit();
            } else {
                $stmti->bind_result($cinummer, $aankoopdatum, $serienummer, $merk, $model, $os, $eigenaar, $locatie, $applicatie);
                $stmti->store_result();

                while($stmti->fetch()) {
                    echo "

                        $cinummer
                        $aankoopdatum
                        $serienummer
                        $merk
                        $model
                        $os
                        $eigenaar
                        $locatie

";
                }

            }
        } else {
            echo "can't prepare:
 " . $stmti->error;
            exit();
        }
        ?>

Comment: add your while loop in last row ajax click function in pass hardware unique id and call ajax server side add sql delete query where unique id.
Comment: Don't really know how to do that, but I'll try, thx :)
Comment: The SQL edit function?
Comment: Yeah I know about the SQL function @Strawberry , only problem i i dont know how to make it work that every new row/existing row gets a edit + delete button.
Comment: Maybe you know about it, but I've never heard of it before
Comment: Im sorry I see it's called UPDATE not Edit
Answer: I just update the code. but I did not create a EDIT form in HTML and send values, I have write PHP codes

        CI nummer
        Aankoopdatum
        Serienummer
        Merk
        Model
        OS
        Eigenaar
        Locatie
        Bewerken
        Verwijderen
        Options

        <?php
        $conn = mysqli_connect("localhost", "root", "", "teradruk");

        if (mysqli_connect_errno()) {
            echo "Kan geen verbinding maken met de database!";
            exit();
        }

        if($_GET['action']=="delete")
        {
            $sql_delete = mysql_query("DELETE FROM hardware WHERE PRIMARY_KEY_OF_hardware_TABLE = ".$_GET['id']." ");
        }
        elseif($_GET['action']=="edit")
        {

            $sql_update = "UPDATE hardware SET cinummer = 'New Number' WHERE PRIMARY_KEY_OF_hardware_TABLE = ".$_GET['id']." ";
        }

        $sqli = "SELECT * FROM `hardware`";

        if ($stmti = $conn->prepare($sqli)) {
            if (!$stmti->execute()) {
                echo "cant exec:
 " . $stmti->error;
                exit();
            } else {
                $stmti->bind_result($cinummer, $aankoopdatum, $serienummer, $merk, $model, $os, $eigenaar, $locatie, $applicatie);
                $stmti->store_result();

                while($stmti->fetch()) {
                    echo "

                        $cinummer
                        $aankoopdatum
                        $serienummer
                        $merk
                        $model
                        $os
                        $eigenaar
                        $locatie
                        Delete | Edit

";
                }

            }
        } else {
            echo "can't prepare:
 " . $stmti->error;
            exit();
        }
        ?>

Thanks!
Comment: WOW! Thanks so much! Looks great! 1 think, im now getting this: http://prntscr.com/d45318 , how can i fix this?..
Comment: Hi, please replace this "PRIMARY_KEY_OF_hardware_TABLE" with your table auto increament primary id.
Comment: Still getting these 2 errors: http://prntscr.com/d45lv2 , when i click delete i get this: http://prntscr.com/d45m1q , sorry for the newbie questions by the way
Comment: I see the problem already, the action function is not regocnized. How do i make this work?


If $f:M\to N$ is a morphism of $A$-modules, counter-example to $M\cong \operatorname{ker}f\oplus \operatorname{im}f$

Question: If $f:V\to W$ is a linear transformation between (not necessarily finite-dimensional) vector spaces, then
$$V\cong \operatorname{ker}f\oplus \operatorname{im}f.$$
(This is the external direct sum, as usual in modern algebra.)
I absolutely don't expect a similar result to be true for $A$-modules. (We have conditions under which this holds, given by the splitting lemma.) But I couldn't find a counterexample.
So, what is a morphism of $A$-modules $f:M\to N$ such that $M$ is not isomorphic to $\operatorname{ker}f\oplus \operatorname{im}f$?
Answer: Look at the $\Bbb{Z}$-modules $\Bbb{Z}/2\Bbb{Z}$ and $\Bbb{Z}/4\Bbb{Z}$. Then $\phi:\Bbb{Z}/4\Bbb{Z}\to\Bbb{Z}/2\Bbb{Z}$ defined by $\phi(a)=a\mod 2$ is a $\Bbb{Z}$ module homomorphism but the direct sum of the kernel and image is not isomorphic to $\Bbb{Z}/4\Bbb{Z}$.
Answer: The simplest counter-example I can think of is
$$0\to 2\mathbb{Z} \to \mathbb{Z} \to \mathbb{Z}/2\mathbb{Z} \to 0.$$
$\mathbb{Z}$ is not isomorphic to $2\mathbb{Z} \oplus \mathbb{Z}/2\mathbb{Z}$, as $\mathbb{Z}$ does not have torsion.


Prove that $χ_τ (g_1, g_2) = χ_ρ(g_1)χ_ϕ(g_2)$.

Question: Let $G_1$ and $G_2$ be finite groups and let $G = G_1 ×G_2$. Suppose
$ρ: G_1 → GL_m(\Bbb C)$ and $ϕ: G_2 → GL_n(\Bbb C)$ are representations. Let $V =M_{mn}(\Bbb C)$ be the vector space of $m×n$-matrices over $\Bbb C$. Define $τ : G → GL(V )$
by $τ(g_1,g_2)(A) = ρ_{g_1}Aϕ_{g_2}^T$
 where $B^T$ is the transpose of a matrix $B$.

Show that $τ$ is a representation of $G$.
Prove that $χ_τ (g_1, g_2) = χ_ρ(g_1)χ_ϕ(g_2)$.
Show that if $ρ$ and $ϕ$ are irreducible, then $τ$ is irreducible.
Prove that every irreducible representation of $G_1×G_2$ can be obtained
in this way.

The solution of 1 is pretty clear.
I am facing problem from 2 onwards.
For a representation $\phi : G \to GL(V)$ where $V \cong \Bbb C^n$
$\chi _{\phi}(g)=Tr(\phi_g)=\sum_{i=1}^n<\phi_g(e_i),e_i>$ but what to do here I was writting in terms of $E_{ij}$ bit not getting satisfactory answer. Please help from 2 onwards.
Answer: You have the right idea: for 2, we note that the inner product over $M_{mn}$ is given by $\langle A,B \rangle = tr(AB^*)$, with $*$ denoting the conjugate transpose.  In other words, our inner product is simply the "dot product" of matrices.  Note also that $E_{ij} = e_ie_j^T$.  We then have
$$
\chi_\tau(g_1,g_2) = \sum_{i= 1}^m \sum_{j=1}^n \langle \tau(g_1,g_2)E_{ij}, E_{ij} \rangle =
\sum_{i= 1}^m \sum_{j=1}^n
\langle \rho_{g_1}e_ie_j^T\phi_{g_2}^T, e_ie_j^T \rangle = \\
\sum_{i= 1}^m \sum_{j=1}^n
\langle \rho_{g_1}e_i e_j^T\phi_{g_2}^T, e_ie_j^T \rangle = \\
\sum_{i= 1}^m \sum_{j=1}^n
Tr( \rho_{g_1}e_ie_j^T\phi_{g_2}^Te_je_i^T) = \\
\sum_{i= 1}^m \sum_{j=1}^n
Tr( e_i^T\rho_{g_1}e_ie_j^T\phi_{g_2}^Te_j) = \\
\sum_{i= 1}^m \sum_{j=1}^n
[e_i^T\rho_{g_1}e_i][e_j^T\phi_{g_2}^Te_j] = \\
\sum_{i= 1}^m \sum_{j=1}^n
\langle\rho_{g_1}e_i,e_i\rangle \langle \phi_{g_2} e_j,e_j\rangle = \\
\chi_\rho(g_1) \chi_{\phi}(g_2)
$$
For 3: I would try to prove by contrapositive.  That is: show that if $\tau$ is reducible but $\phi$ is irreducible, then $\rho$ is reducible.  Not sure about 4.
Comment: Would you explain the 4th to 5th line? How the trace breaks into two parts as trace is not in general multiplicative.
Comment: Matrix multiplication is associate, and the matrix whose trace we take in the 4th line is really $1\times 1$, which is to say a scalar.
Comment: Oh, I miscounted, that was 5 to 6. From 4 to 5: $Tr(AB)= Tr(BA)$, so the trace of a product is invariant under "cyclic permutations".
Comment: Alternatively, we can go straight from lines 3 to 5 if we note that both summands extract the $i,j$ entry of line 3's left-side of the inner product.
Comment: I am saying about $$Tr( e_i^T\rho_{g_1}e_ie_j^T\phi_{g_2}^Te_j) = \\
\sum_{i= 1}^m \sum_{j=1}^n
[e_i^T\rho_{g_1}e_i][e_j^T\phi_{g_2}^Te_j] $$ this line.
Comment: Well, then the first comment applies. The trace of a scalar is that scalar, and we're free to rebracket any product.
Comment: What is the scalar here? In  $$\sum_{i= 1}^m \sum_{j=1}^nTr( e_i^T\rho_{g_1}e_ie_j^T\phi_{g_2}^Te_j) = \\
\sum_{i= 1}^m \sum_{j=1}^n
[e_i^T\rho_{g_1}e_i][e_j^T\phi_{g_2}^Te_j] $$. Both $i,j$ are varying. I think you are trying to say $Tr(cA)=cTr(A)$ then what is $c$ scalar?
Comment: I'm saying that $e_i^T\rho_{g_1}e_ie_j^T\phi_{g_2}^Te_j$ is a $1 \times 1$ matrix (and thus equal to its trace).
Comment: yes yes. True. Thank you.


Will putting decals/stickers on my acoustic guitar affect the sound, and if so, how much?

Question: I can't seem to find a definitive answer to my  question.
I have a Yamaha F335 acoustic guitar and I want to put a sticker that says "Supreme" (here it is on Amazon).  But people have been telling me that it will affect the sound. It's just one sticker.
Will a sticker affect the sound?  If it does affect it, how much will the sound be affected?
Comment: Yes but not very much.
Comment: Might depend where you stick it...
Answer: One sticker on the guitar body will by any reasonable metric make diddly squat difference to the sound being made.  There's just no way such an imperceptible change in mass will affect the resonance, and it's not like a sticker is going to restrict vibration of the surface either.
I mean hell, most acoustic guitars have big plastic pickguards on them, and it's really just fine.
Use your sticker.  As a bonus, if anyone starts talking to you about how it might affect your tone, you now know who to kill first when the time comes.
Edit:
BONUS MURDER ROUND:
anyone who can't play in time but tells you they get the better tone if they use the right brand of batteries in their tube screamer
Jokes aside, sticker your guitar all you want, and most importantly, enjoy playing it :)
Answer: I don't think it will affect the overall sound. Something like the freshness of your strings will have a much bigger impact.
Answer: Yes.
But it depends on what is your guitar, what's the wood, where you place it, how thick is the sticker.
I'm assuming your Yamaha F335 is made of a plywood, then if you place your sticker on the back of your guitar, it'll be fine I guess. But if you place it on your fingerboard, it will affect the sound so much. But I know you'll place it somewhere on the top of the body. Where 1/4 of the sound will be affected.
How to minimize that is by understanding your bracing, because it is some kind of road where your sound goes and bounces. If you put the sticker near the bracing, you'll get some buzz (on the sound that comes out — I don't know how to call it, but) caused by vibrating sticker. Relax, it's not caused by the strings, it's just the sticker against the audio signal from the guitar (cause my friend once got that problem). If you put it far from the bracing, where the signal is bounce freely inside your guitar body, like the edge of your guitar, I think it'll be fine and don't really affect your sound so much.
If your sticker is kinda thick, the sound you'll get is kinda darker. But if it's not really thick, it wouldn't affect the sound so much.
Comment: The wood on a guitar is far less likely to vibrate where the bracing bars are, so this answer appears to me to be somewhat back to front. A properly stuck sticker shouldn't vibrate anyway.
Answer: One sticker on a Yamaha F335 will not have a perceptible effect on the sound of the guitar.  If you covered the entire soundboard (top) with stickers, you might notice an impact on the resonance of your tone.
Most of the sound from an acoustic guitar is produced by the vibration of the top - also known as the sound board.  Anything that reduces or dampens the vibration can have at least a slight effect on the sound.  But as another answer mentioned, a sticker is likely to have less impact on the sound than a pickguard would.  Having said that, if given an option on an acoustic guitar, I personally prefer one with no pickguard.
Stickers on the back of the guitar will have very little or no effect on the tone.  But then nobody will see the sticker when you are playing.
Something you may want to consider (besides impact on tone), is the potential for some damage to the finish should you ever remove the sticker.  Two things can happen.  First, the glue residue will be difficult to remove after the sticker has been affixed to your guitar for some time.  And the solvents you use to remove the glue residue, could also damage the finish.
Secondly, exposure to light over time will impact the color of the wood.  It will "age" so to speak due to exposure to light.  This is why if you remove a pickguard from an older guitar, you will see a ghost or shadow of the pickguard where the coloration of the wood will vary.  So it is likely that removal of a sticker after a year or more, could leave a ghost of the shape of the sticker from a variation in the coloration of the wood - unless you only take the guitar out of it's case occasionally to minimize exposure to light.
For these reasons, adding a sticker may slightly diminish the value of the guitar, if selling it in the future is a consideration.  If you plan to keep the guitar in your collection forever, and you like the sticker, and if it will enhance your enjoyment of your guitar, by all means stick it on.
PS:  I like stickers too - but I put them on my hardshell guitar cases where they can't possible effect the tone, and are easier to remove with no damage to the case.  That's an option for those who read this who want to compromise and have their stickers but with no negative impact on the tone or value of their guitar.


Variable selection in zero-inflation models

Question: I am trying to understand how to perform model comparison between different count models. In this example the author performs a zero-inflated poisson model testing the effect of number of people in a group (variable group), number of children in a group (variable child), and whether or not the group had a camper (variable 'camper`)
library(pscl)
library(dplyr)
zinb <- read.csv("https://stats.idre.ucla.edu/stat/data/fish.csv") %>% transform(camper = factor(camper))

They perform the analysis using the following syntax
summary(m1 <- zeroinfl(count ~ child + camper | persons, data = zinb))

And get the output
# Call:
# zeroinfl(formula = count ~ child + camper | persons, data = zinb)

# Pearson residuals:
#     Min      1Q  Median      3Q     Max
# -1.2369 -0.7540 -0.6080 -0.1921 24.0847

# Count model coefficients (poisson with log link):
#             Estimate Std. Error z value Pr(>|z|)
# (Intercept)  1.59789    0.08554  18.680   <2e-16 ***
# child       -1.04284    0.09999 -10.430   <2e-16 ***
# camper1      0.83402    0.09363   8.908   <2e-16 ***

# Zero-inflation model coefficients (binomial with logit link):
#             Estimate Std. Error z value Pr(>|z|)
# (Intercept)   1.2974     0.3739   3.470 0.000520 ***
# persons      -0.5643     0.1630  -3.463 0.000534 ***
# ---
# Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

# Number of iterations in BFGS optimization: 12
# Log-likelihood: -1032 on 5 Df

Question 1
What does the | persons section of the model specification do?
It obviously consigns the persons variable to the zero inflation portion of the output, presumably because they believe that variable contains (or is hiding) some of the information that contributes to the excess zeroes, namely that the reason why some people do not catch fish is because those people do not even try to fish.
The author then goes on to perform a standard poisson regression
summary(p1 <- glm(count ~ child + camper, family = poisson, data = zinb))

# Call:
#   glm(formula = count ~ child + camper, family = poisson, data = zinb)
#
# Deviance Residuals:
#   Min       1Q   Median       3Q      Max
# -3.7736  -2.2293  -1.2024  -0.3498  24.9492
#
# Coefficients:
#               Estimate Std. Error z value Pr(>|z|)
#   (Intercept)  0.91026    0.08119   11.21   <2e-16 ***
#   child       -1.23476    0.08029  -15.38   <2e-16 ***
#   camper1      1.05267    0.08871   11.87   <2e-16 ***
#   ---
#   Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#
# (Dispersion parameter for poisson family taken to be 1)
#
# Null deviance: 2958.4  on 249  degrees of freedom
# Residual deviance: 2380.1  on 247  degrees of freedom
# AIC: 2723.2
#
# Number of Fisher Scoring iterations: 6

Note the omission of the |persons term in this model. There is no explanation of why the persons variable was ommitted. This is especially confusing as they then go on to compare the standard poisson to the zero-inflated poisson using Vuong's non-nested test
vuong(p1, m1)

Question 2
How can we compare the two models when the standard poisson omits the |persons from the model specification?
Question 3
Should all zero-inflated models split the model this way, by identifying a variable that might contain/conceal/approximate the reason for the excess zeroes?
Question 4
In the above example the variable that might identify the reason for the excess zeros (how many people in the group actually tried to catch a fish) is not available. But if you do have that variable available should you include it in the model?
Answer: You've got a lot of questions here.
1. what does | persons do?
As you suggest, it sets the zero-inflation model to $\textrm{logit}(p_z) = \beta_{z0} + \beta_{z1} \cdot \textrm{persons}$.
The authors decided that the number of people in the group could affect whether the group didn't fish at all, but wouldn't affect the fishing success if the group did fish.
In the corresponding Poisson model, the zero-inflation term is completely missing (i.e. $p_z=0$, which would correspond to $\beta_{z0} \to -\infty$ (and $\beta_{z1}$ irrelevant).
2. How can we compare models?
I don't see the problem here. We have clear differences in model complexity (if we want to use AIC), or clear nesting (conditions under which the Poisson model is a special case of the ZIP model): note there is some debate about using Vuong tests for ZIP vs Poisson comparisons ...
3. should all Z-I models use separate covariates for the conditional vs zero-inflation components?
No, not necessarily.  In principle either component of the model could be anything from intercept-only to including all available covariates (this is the default in zeroinfl: e.g. zeroinfl(r ~ x + y + z, ...) assumes that all three covariates affect both parts of the model).  The choice should be based on (1) specifying an appropriately complex model for the data and (2) "subject-area considerations": using knowledge of what the parameters mean and which components they might sensibly affect.
4. should 'number of active fishers' be included in the model?
I'm not sure. If you know when the number of fishers is zero (in which case there are never any fish caught) vs. non-zero, then you might not want to use a ZIP at all.  On the other hand, it might be reasonable to include the number of fishers in the conditional mean model ($\textrm{log}(\textrm{fishers})$ as an offset or covariate)
Comment: see one of the answers [here](https://stats.stackexchange.com/questions/25415/using-offset-in-binomial-model-to-account-for-increased-numbers-of-patients)
Comment: Thank you @Ben Bolker. It's been a very illuminating morning for me. I am modelling number of counselling sessions attended by participants taking part in a clinical trial on several baseline predictors to see which best predict engagement in counselling during the trial. Of course the number of counselling sessions attended is highly conditional upon attendance, because you can't attend counselling sessions in a trial you are no longer enrolled in. Modelling this as a separate process to the actual desire to engage in counselling while enrolled in the trial makes a lot of sense to me.
Comment: what is an offset?