Background some quando meus itens do menu estão na horizontal

Question: Tenho o seguinte código HTML:

Home

About

Services

Portfolio

Blog

Contato

E o seguinte CSS:
#topo {
    background-color: #1a1e27;
    color:#FFFFFF;
    width:950px;
}
#topo li {
    display:inline;
    float: left;
    margin-left: 5px;
}

Quando deixo esse código inteiro, ele perde o background #1a1e27 mas deixa meu menu na horizontal. Quando tiro todo o #topo li {}, ele atribui a cor do background.
O que estou fazendo errado?
Comment: @Bacco Na realidade, o problema pode ser reproduzido somente com o código original postado: http://jsfiddle.net/tZe4L/
Comment: @Rod agora acertei as 2 cores, veja se é isso.
Answer: Percebi alguns problemas: Como você usou display: inline, o float não é necessário,
e como existe um , a cor branca do
 não está fazendo efeito.
Este css soluciona os dois problemas:
#topo {
   background-color: #1a1e27;
   width:950px;
}
#topo li {
   display:inline;
   margin-left: 5px;
}
#topo a {
   color:#FFFFFF;
}

Comment: Boa, isso também funciona. Demo: http://jsfiddle.net/tZe4L/2/
Comment: @mgibsonbr agora que eu percebi o float :)
Comment: é, aquela hora eu estava rascunhando no fiddle que o @mgibsonbr postou, e foi ai que eu percebi o float sobrando :)
Comment: obrigado Bacco, então float, só funciona em elementos em bloco
Comment: @Rod Não, float funciona em qualquer elemento, e elementos flutuados são tratados como blocos.
Answer: Quando você flutua os elementos dentro de um container, ele se comporta como se estivesse vazio – portanto sem dimensões, e sem background. A solução é colocar overflow: hidden no container para "limpar" os floats. Repare também que float: left anula o seu display: inline. O CSS pode então ficar assim:
#topo {
    background-color: #1a1e27;
    color:#FFFFFF;
    width:950px;
    overflow: hidden;
}
#topo li {
    float: left;
    margin-left: 5px;
}

http://jsfiddle.net/tZe4L/1/
Ou, como sugeriu o Bacco, você pode colocar seus
 inline, sem flutuá-los.


Search & Amend User Details

Question: I wonder whether someone can help me please.
I'm trying to put together a form and PHP script (below) which allows an administrator to search and update member details via the email address, populating a second email address, forename and surname fields with the retrieved information ready for them to be amended.
<?php
mysql_connect ("hostname","username","password") or die (mysql_error());
mysql_select_db ("databasename");
if ($_POST['search'])
{
    $searchemailaddress = $_POST['searchemailaddress'];
    $sql = mysql_query("select * from userdetails where emailaddress like '$searchemailaddress'");
    while ($row = mysql_fetch_array($sql))
    {
        $emailaddress = $_POST['emailaddress'];
        $forename = $row['forename'];
        $surname = $row['surname'];
    }
elseif ($_POST[['update'])
{
    $userid = $_POST['userid'];
    $emailaddress = $_POST['emailaddress'];
    $forename = $_POST['forename'];
    $surname = $_POST['surname'];
    //replace TestTable with the name of your table
    $sql = ("UPDATE `userdetails` SET `emailaddress` = '$emailaddress', `forename` = '$forename',`surname` = '$surname' WHERE `userdetails`.`userid` = '$userid' LIMIT 1");
}
}
}
?>

I'm receiving the following error:
Parse error: syntax error, unexpected T_ELSEIF in /homepages/2/d333603417/htdocs/development/searchandamend.php on line 13
with line 13 being this line in my script. elseif ($_POST[['update'])
Could someone perhaps take a look at this please and let me know where I'm going wrong.
Many thanks
Comment: The `if` opens a scope which should be closed with `}` before `elseif`.
Answer: The line
$surname = $row['surname'];}

should have another } afterwards. The one you have only closes the while loop. You also may want to consider using some indentation - that really helps seeing errors like this one.
Also, the error basically says it all - the else if appears unexpectedly there, so the PHP processor expects something else (in this case a closing brace).
Comment: Hi, many thanks for this, this resolved the error I was receiving. Unfortunatly though I'm now having an issue with saving the amended changes. I'll have to have a look at this separately. Kind regards
Answer: As was mentioned in a comment to your answer your closing } are improperly placed and it appears you have too many of them.
if
{
    // stuff here
}
elseif
{
    // other stuff here
}

As was also mentioned in a previous answer if you properly format your code, similar to how it appears in the edited question, you will have a much easier time finding errors like this.

I also feel obliged to point you to the PHP documentation on choosing the correct MySQL API as the extension you are using is outdated and is not recommended for new project use.

Search & Amend User Details


Showing that $|N \cap Z(G)| > 1$ for normal subgroups of p-groups

Question: I have a finite $p$-group $G$ and a normal subgroup $N$ which is not the trivial subgroup. I am asked to show that $|N \cap Z(G)| > 1$.
There has been a similar question on MSE here:
How to show that $H \cap Z(G) \neq \{e\}$ when $H$ is a normal subgroup of $G$ with $\lvert H\rvert>1$
Unfortunately, I cannot comment on other user's questions yet, so I made my own question.
I know that the trick is to use conjugation but I can't follow the logic. Can someone elaborate? Especially on the last part of the top answer.
Answer: First, $G$ acts on itself by conjugation $g\cdot x=gxg^{-1}$, and under this action, the orbit $G\cdot x$ is precisely the conjugacy class of $x$ in $G$, by definition essentially. The orbit-stabilizer theorem says
$$
|G\cdot x|=\frac{|G|}{|\operatorname{Stab}(x)|}
$$
This implies $|\operatorname{Stab}(x)|=\frac{|G|}{|G\cdot x|}$, which means $|G\cdot x|$ divides $|G|$, hence $|G\cdot x|$ is a power of $p$, or possibly $1$.
Since $N$ is normal, it is a union of the conjugacy classes of the elements it contains, and these classes partition $N$. Since $e\in N$, the conjugacy class $C_G(e)=\{e\}\subseteq N$. Since $N$ is nontrivial, it has to contain other conjugacy classes. If all these other classes are not singletons, and since these classes partition $N$, then $|N|=1+\sum\text{powers of }p$, so that
$$
1=|N|-\sum\text{ powers of }p
$$
which implies $p\mid 1$, since $p\mid |N|$ and each term which is a power of $p$, a contradiction. (When I say powers of $p$ here, I'm not counting $p^0=1$, since I assumed all the other conjugacy classes are not singletons.) So $N$ must contain some other conjugacy class which is a singleton, say some nonidentity $x\in N$ such that $C_G(x)=\{x\}$. This means $gxg^{-1}=x$ for all $g\in G$, or $gx=xg$ for all $g\in G$, or $x\in Z(G)$, and you conclude.
Comment: Thanks, I think this clears it up. I try to write it down myself and come back in case I encounter any difficulties.
Answer:
Each $a \in G$ belongs to a conjugacy class, and in a given conjugacy class each element is a conjugate of every other element. G is partitioned into separate conjugacy classes (this is because "$a$ is conjugate to $b$" is an equivalence relation on G).
The orbit-stabilizer theorem shows that the size of each conjugacy class is a power of $p$. Why? Because given $g \in X$ in a conjugacy class $X$, let $Z_g$ be the subgroup of elements fixing $g$ by conjugation (i.e. they commute with $g$). There's a natural bijection between cosets of $Z_g$ and members of $X$. Since $G$ is a $p$-group, the order of $Z_g$ and therefore the index of $Z_g$, which is $|X|$, must be powers of $p$.
If $a \in Z(G)$, the conjugacy class of $a$ is just $\{a\}$, of order $p^0 = 1$. Otherwise the size of the conjugacy class of $a$ is a multiple of $p$.
$N$ is normal, so if $a \in N$, $a$ cannot get out of $N$ by conjugation. It follows that if $N$ includes some element of some conjugacy class, it includes the entire class. In other words, $N$ is a union of some conjugacy classes.
$N$ already includes one conjugacy class of size $1$: that of $e$. If it didn't have any other elements of $Z(G)$ in it, all other conjugacy classes in $N$ would be of size that divides $p$. But then the total sum of all these orders of conjugacy classes in $N$ would be $1$ modulo $p$. This cannot be, as the order of $N$ must divide $|G|$.
Comment: Thanks, Avva! I am going to write it down for myself now and see if I run into trouble.
Answer: The same question was asked and closed here, where the OP asks for a proof using the upper central series of $G$.

Define $i$ as the smallest integer such that $Z_i\cap N\neq\lbrace e\rbrace$, and consider $g\in (Z_i\cap N)\setminus\lbrace e\rbrace$. Since $Z_0=\lbrace e\rbrace$ and for $n$ large enough $Z_n=G$, $i$ is well defined and $\geq 1$. Then for any $h\in G$,
$$g\underbrace{hg^{-1}h^{-1}}_{\in N}\in Z_{i-1}\cap N$$
i.e. $\forall h\in G, ghg^{-1}h^{-1}=e$ i.e. $g\in Z(G)$. Hence $N\cap Z(G)\neq\lbrace e\rbrace$
Comment: This is because, by definition of $i$, $Z_{i-1}\cap N=\lbrace e\rbrace$.
Comment: How did you infer that last line?


How can I quickly re-save all users on my site?

Question: Very similar to this question except I need to save users, not nodes.
Use case: I added a field (single boolean) to a feature so that the field is added to user profiles.  I then pushed the feature to my staging server.  However, existing user accounts do not have the default field value for this field assigned.  Re-saving each account fixes the problem, but there are 1000 users.
How can I quickly re-save all users on my site?
Comment: Users are entities too, you can use exactly the same logic from the other question (VBO with PHP, or a manual update) and just replace `node_save()` with `user_save()`
Comment: How about forcing it through...`$items = field_get_items('user', $entity, 'field_name'); if (empty($items)) { $entity->field_name[LANGUAGE_NONE][0]['value'] = 1; } user_save($entity);` That should do the trick
Comment: @Clive @rooby Thanks for the tips here.  I just tried `user_save($entity)`; this causes the user to be saved (I confirmed by adding a rule that shows a message on the site).  However, no value is assigned to the new field, even if I run the save action multiple times.  If I do it manually, though, from the People page, the default value is set.
Answer: You can use the "Execute arbitrary PHP script" bulk operation in VBO and when you run it enter:
user_save($entity);

You could also run this PHP (you can do so by enabling the devel module and going to devel/php on your site):
set_time_limit(0);
$uids = db_query('SELECT uid FROM {users} WHERE uid != 0')->fetchCol();
$users = user_load_multiple($uids);
foreach ($users as $user) {
  user_save($user);
}

If you don't have many users you shouldn't need the time limit line.
Also, Clive mentions that field_attach_update is faster. To use that replace the user_save line with field_attach_update('user', $user)
Comment: My mistake, there is a "Save content" one for nodes but no equivalent user one. I have removed that part of my answer.
Comment: Thanks, I put a note about field_attach_update().
I also added an even nicer solution using VBO execute PHP code (thanks Bojan)
Comment: The PHP code via Devel worked great. I had to add 'WHERE uid > 0' to avoid an integrity constraint error in the logs.
Comment: What is the VBO save action for users?  I looked for it but I couldn't find it.
Comment: @Patrick is there not a generic save action for entities? (I haven't checked I just assumed there would be)
Comment: @Clive No, there is *Modify entity values* but nothing with the word "save" in it...
Comment: In that case I'd go with the manual query; but I'd alter it slightly to avoid changing the user properties (i.e. use `field_attach_update()` instead of `user_save()`)
Comment: The first option seems a lot easier...is the `$user` object definitely available in the arbitrary PHP execution?
Comment: Oops, that was a typo, thanks for picking that up.
Answer: rooby's answer is probably the easiest/quickest method but just to offer a code solution that can be used with VBO...
You can define your own action to save the user like this:
function MYMODULE_rules_action_info() {
  return array(
   'MYMODULE_update_user_account' => array(
     'label' => t('Save a user account'),
     'parameter' => array(
       'account' => array(
         'type' => 'user',
         'label' => t('User'),
       ),
     ),
     'group' => t('MODULENAME'),
   ),
 );
}

function MYMODULE_update_user_account($account) {
  user_save($account);
}

Once you've clerared the caches you should see your new action appear under VBO/rules and anywhere else actions are used.
Edit: It seems this might re-inventing the wheel somewhat if VBO will already let you do it natively, but it's a nice simple example of a rules action so I'll leave it here in case anyone needs it. Plus it removes the need for eval() to be used which is never a bad thing.
Comment: Seeing as this is now the leading answer, if anyone actually does end up doing it this way, please submit it back as a patch. The rightful module is the user module because the node module provides the save content action, however there might be more chance of it being committed to the views_bulk_operations module. - Maybe a drupal 8 user module patch that might have a chance at back port to 7.


Accessible Instruments While Away From Home

Question: I am a musician spending a few months away my home.  I fear that I may lose a good chunk of skill if I am unable to practice my instrument during this time.  It is completely unfeasible for me to buy an instrument while I'm away for both space and cost reasons (I play piano).  Does anyone know of any sort of group/club/system (generically) that revolves around communal instruments?  Perhaps something like a group where you pay some nominal fee every month for access to instruments.  I won't specify where I am as I'd like to keep this answer as generic as possible.
Answer: A person who plays the piano has difficulties in practicing. Like you questioned skill can go down without practice. Piano is a larger piece of musical instrument that is not portable easily. A key board is a solution. In this instance the cost is a deciding factor for him.
Taking all these considerations there can only be one solution. Are you in a location where there are clubs or hotels that have a piano. You could volunteer  to play a few pieces everyday to entertain the club members or the guests. As a starter offer it free. Ask Them if they would approve a hour or two earlier than the regular time to help you to be in your best performance. This should help you with your skill and practice.
One other idea is to volunteer to teach children music in a school where there is a piano or keyboard after school hours.
You could also think of a home where there is a piano and children or adults need piano lessons. This way you could help them and in turn help your self with maintaining your skills and practice sessions.
I hope you are in a country or a city where clubs, homes, hotels and schools are nearby.
Comment: +1 Great ideas. @Tanaki: You could perhaps also find a local church hosting a piano, where you might talk yourself to piano access and practice time.
Comment: Offering to play at other places is an excellent idea, thank you.  I'd say this is a pretty populated area, hah.
Answer: Taking a keyboard (from £20 second hand in U.K.) is an obvious answer, but probably not viable to you as a pianist - the action will not do the job, although the black and white bits are in the right place !  I got over the same problem in a different way. Learn another instrument. I take a flute or clarinet away when there is little luggage room. They can be played without upsetting anyone. Your musical knowledge will be enhanced by applying it to a different means of making sounds.This will not necessarily help you as a piano player, but as a musician it will be good.  You could (to add to existing answer) also source music shops, and find quiet times there. Talking to the guys in the shops will probably reveal other options.
Comment: That's a clever way to go about it.  I really am hoping to keep my piano repertoire though; I love the music shop idea.


Understanding VR ecology

Question: I have background in android and have developed few apps of my own. Now I want to explore VR app development for android. Going through forums etc., first thing I understand is that I need to have basic infrastructure like unity 3d sdk, cardboard sdk, cardboard device etc. I am not able to understand roles these individual components play in overall bigger picture.
Like, why do I need unity 3d sdk if I have android sdk and cardboard sdk, and android studio as dev environment?
Then, if I plan to develop for something like Oculus then what all sdks and devices are needed, and which programming language I can work with?
Comment: Wrong place for this question
Comment: @GerardoZinno at least tell OP a "right place" for this question
Comment: @dabadaba all I know is that stack overflow is for code-related question and this question is not about code. All I could say is look on other StackExchange communities.
Comment: @GerardoZinno that's a better comment than harshly shutting OP off ;)
Comment: In its current state, I'm not sure whether there are any Stack Exchange sites where this question would not be closed for one reason or another. Try to sift through the documentation for the answers first - oftentimes there'll be some sort of start-up guide that you can reference. Downloading a test project helps too, as it shows you all the pieces in place to get the technologies interacting. If, after this research and experimentation you run into an unsolvable problem, you can formulate that into a question here or perhaps http://gamedev.stackexchange.com/, depending on its specifics.
Comment: Thanks all for inputs. Yeah, I need to do lots of research it seems, which I have already started.Hope I would be able to do fine.
Answer: Your options depend on which device you'll target:

Game engines like Unity: You need Unity and some plug ins and of course the device you will target too:

Google Cardboard / Daydream
Samsung Gear VR

From scratch application: Your language is java and you need to download the sdk for your target device:

Google Cardboard / Daydream SDK
Samsung Gear VR, Oculus Mobile SDK

Regards
Answer: I think there is a lot of promise in web-based VR. Of course, the app will not be as high fidelity as a native application built in Unity or Java but you get the benefit of being able to target many platforms out of the box. ReactVR is a cool project coming out of facebook that is making it easier and more performant to build VR apps with web technologies.
Here is a cool starter-kit that can help you get started if you are interested: https://github.com/scaphold-io/react-vr-graphql
P.S. GraphQL is a great tool for enriching your VR apps with data no matter if you're building it with React, Unity, or Java.
Answer: You can check out A-Frame (https://aframe.io), a web framework for building VR experiences. It's been out over a year and has a strong community and ecosystem. With web-based VR, you get cross-platform support across Rift, Vive, Cardboard, Daydream, GearVR out of the box. With A-Frame, you get all of the boilerplate with a single line of HTML. You just have to grab a VR-enabled browser.
A-Frame's architecture is similar to Unity's, entity-component, but A-Frame makes it declarative and similar to web development. With effort, the fidelity can rival native (https://blog.mozvr.com/a-painter/).

Understanding VR ecology


Exit the screen in WPF C #

Question: I need a hint as to how to get the user out of the screen in the WPF window. I made a window that does not fit on the screen and needs to be scrolled so that more data can be added, but I have no idea how to do it. Or maybe I can add a slider to see a further label?
Comment: You should show us what you've already tried, show code examples and any error message you're having.
Answer: You should use scroll-viewer control. see this How to add scroll viewer. Hope it helps.
In XAML
<ScrollViewer VerticalScrollBarVisibility="Auto">
    Put other xaml content here..
</ScrollViewer>

or you can show Scrollbar in Grid
<Grid  ScrollViewer.CanContentScroll="True"
       ScrollViewer.HorizontalScrollBarVisibility="Auto">
   ...
</Grid>

Or in Program
ScrollViewer sv = new ScrollViewer();
sv.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
myGrid.Children.Add(sv);

Exit the screen in WPF C #


What is the musical form of Kamasi Washington's "Truth"?

Question: I'm pretty new to music theory, so I have been analyzing songs I enjoy for practice. I thought I was getting decent at it, but the length and complexity of this song has been giving me some trouble.
Kamasi Washington - "Truth"
Comment: Welcome to Music practice & theory StackExchange. Do you have a link to a recording and/or a score?
Comment: @Karlo Fixed. Added the link into the post
Answer: This piece can be analyzed on a two different levels: the small-scale repeating form and the large-scale structure of the whole 13 and a half minute recording.
The small-scale structure is really simple. It is a two-chord vamp consisting of four measures of Gmaj7 followed by four measures of F#-7. That's it. It's just those two chords over and over.
The large-scale structure is only slightly more complicated. The piece is kind of an overture for his Harmony of Difference EP. Kamasi is taking melodic elements from the other five compositions on the album and layering on top of one another.
Analyzing these melodic elements is the fun part, so I won't spoil it for you, but if you want to get serious about it, I recommend looking at those first five tunes on the album so that you can identify the various elements that he's working with.


"drush up" fails with "pm-updatestatus failed."

Question: When I execute drush up, it returns the following error message.

The command could not be executed successfully (returned: The
  filename, directory name, or volume label syntax is incorrect, code:
  1)   pm-updatestatus failed.

drush pm-updatestatus runs without errors.
Similarly, "C:\\Users\\user1\\AppData\\Roaming\\Composer\\vendor\\drush\\drush\\drush"
    --backend=2 --verbose --debug --root="C:\\website\\drupal7"
    --uri=http://default  pm-updatestatus 2>&1, which I extracted from the debug output of drush -d up (see below) also successfully runs.
What could I try?
The debug output is the following.

Calling hook drush_pm_updatecode_validate [11.27 sec, 17.04 MB]
  Returned from hook drush_pm_updatecode_validate [11.27 sec, 17.04 MB]
  Calling hook drush_pm_updatecode [11.27 sec, 17.05 MB]
  Cache MISS cid: 8.1.2-alias-path--59067c616e8e4f3b7078e0502d77bf35
  [11.27 sec, 17.06 MB]   Backend invoke:
  "C:\Users\user1\AppData\Roaming\Composer\vendor\drush\drush\drush"
  --backend=2 --verbose --debug --root="C:\website\drupal7" --uri=http://default  pm-updatestatus 2>&1 [11.61 sec, 17.09 MB]   "C:\Users\user1\AppData\Roaming\Composer\vendor\drush\drush\drush"
  --backend=2 --verbose --debug --root="C:\website\drupal7" --uri=http://default  pm-updatestatus 2>&1 [11.61 sec, 17.09 MB]   The command could not be executed successfully (returned: The filename,
  directory name, or volume label syntax is incorrect., code: 1) [11.79
  sec, 17.09 MB]   pm-updatestatus failed. [11.79 sec, 17.08 MB]

I am using Drush 8.1.2, Drupal 7.50 running on Windows 7, PHP 5.6.23, and Apache 2.4.23.
Answer: I was able to fix the problem by editing the file /path/to/drush/includes/exec.inc and changing line 331 from
return _drush_escapeshellarg_windows($arg, $raw);

to
return _drush_escapeshellarg_windows($arg, TRUE);

as described by peterromero here https://github.com/drush-ops/drush/issues/2152
Answer: My issue went away when I unlinked my email@example.com and linked firstname.lastname@example.com that MAMP is using. Then I run source ~/.bash_profile (didn't need to reload Terminal).Restarted apache.
Answer: In my case I was getting a Drupal error
Error: Call to undefined function Drush\UpdateService\simplexml_load_file() in                 Drush\UpdateService\Project::getInstance() (line 74 of phar:///usr/local/bin/drush/vendor/composer/../../lib/

which indicated that the php-xml extension was not installed.
sudo aptitude install php7.2-xml

fixed the problem.


MySQL crashing at service start. Hit a bug? DB corruption?

Question: I've a web server that's offline at this moment because MySQL fails to start with an exception. I can't find the root cause of the problem, but I'm afraid of database corruption crashing the MySQL service.
Here are the /var/log/mysql/mysqld.err output:
==> /var/log/mysql/mysqld.err <==
2015-02-11 23:45:11 25171 [Warning] No argument was provided to --log-bin, and --log-bin-index was not used; so replication may break when this MySQL server acts as a master and has his hostname changed!! Please use '--log-bin=mysqld-bin' to avoid this problem.
2015-02-11 23:45:11 25171 [Note] InnoDB: Using atomics to ref count buffer pool pages
2015-02-11 23:45:11 25171 [Note] InnoDB: The InnoDB memory heap is disabled
2015-02-11 23:45:11 25171 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2015-02-11 23:45:11 25171 [Note] InnoDB: Memory barrier is not used
2015-02-11 23:45:11 25171 [Note] InnoDB: Compressed tables use zlib 1.2.8
2015-02-11 23:45:11 25171 [Note] InnoDB: Using Linux native AIO
2015-02-11 23:45:11 25171 [Note] InnoDB: Using CPU crc32 instructions
2015-02-11 23:45:11 25171 [Note] InnoDB: Initializing buffer pool, size = 128.0M
2015-02-11 23:45:11 25171 [Note] InnoDB: Completed initialization of buffer pool
2015-02-11 23:45:11 25171 [Note] InnoDB: Highest supported file format is Barracuda.
2015-02-11 23:45:11 25171 [Note] InnoDB: The log sequence numbers 43953950155 and 43953950155 in ibdata files do not match the log sequence number 43955508491 in the ib_logfiles!
2015-02-11 23:45:11 25171 [Note] InnoDB: Database was not shutdown normally!
2015-02-11 23:45:11 25171 [Note] InnoDB: Starting crash recovery.
2015-02-11 23:45:11 25171 [Note] InnoDB: Reading tablespace information from the .ibd files...
2015-02-11 23:45:11 25171 [Note] InnoDB: Restoring possible half-written data pages
2015-02-11 23:45:11 25171 [Note] InnoDB: from the doublewrite buffer...
InnoDB: Last MySQL binlog file position 0 107020, file name ./mysqld-bin.000052
01:45:11 UTC - mysqld got signal 11 ;
This could be because you hit a bug. It is also possible that this binary
or one of the libraries it was linked against is corrupt, improperly built,
or misconfigured. This error can also be caused by malfunctioning hardware.
We will try our best to scrape up some info that will hopefully help
diagnose the problem, but since we have already crashed,
something is definitely wrong and this may fail.

key_buffer_size=16777216
read_buffer_size=262144
max_used_connections=0
max_threads=151
thread_count=0
connection_count=0
It is possible that mysqld could use up to
key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 134417 K  bytes of memory
Hope that's ok; if not, decrease some variables in the equation.

Thread pointer: 0x0
Attempting backtrace. You can use the following information to find out
where mysqld died. If you see no messages after this, something went
terribly wrong...
stack_bottom = 0 thread_stack 0x40000
/usr/sbin/mysqld(my_print_stacktrace+0x3c)[0x7f122fe0d18c]
/usr/sbin/mysqld(handle_fatal_signal+0x3c9)[0x7f122fc00c29]
/lib64/libpthread.so.0(+0x102b0)[0x7f122e4ef2b0]
/usr/sbin/mysqld(+0x792dd9)[0x7f122ff7bdd9]
/usr/sbin/mysqld(+0x799787)[0x7f122ff82787]
/usr/sbin/mysqld(+0x71a1bd)[0x7f122ff031bd]
/usr/sbin/mysqld(+0x66f175)[0x7f122fe58175]
/usr/sbin/mysqld(_Z24ha_initialize_handlertonP13st_plugin_int+0x41)[0x7f122fb65f41]
/usr/sbin/mysqld(+0x487c32)[0x7f122fc70c32]
/usr/sbin/mysqld(_Z11plugin_initPiPPci+0x5fc)[0x7f122fc7425c]
/usr/sbin/mysqld(_Z11mysqld_mainiPPc+0x7cb)[0x7f122fb5e7eb]
/lib64/libc.so.6(__libc_start_main+0xf5)[0x7f122db379f5]
/usr/sbin/mysqld(+0x36c3d8)[0x7f122fb553d8]
The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains
information that should help you find out what is causing the crash.

This crash happen on mysql-5.6.22.
Any idea of what's happening?
Comment: Your fastest way to resolution is to stand up a new database server and restore from a known-good backup. After doing that, you can spend time figuring out what happened here.
Answer: You have a (really badly) corrupt database, which is crashing mysql.
As a sidenote, this should only happed in rare cases like kernel freeze or power loss coupled with forcing innodb_flush_log_at_trx_commit to 2 or using a raid controller with write cache forced on but no backup battery.
If you have to recover the data, you can try starting mysql with innodb_force_recovery set to a non-zero value - first try to set it to 1, see if mysql starts, if so do a mysqldump of the database; if a value of 1 does not help, try with 2 and so on.
Further details are in the mysql documentation:
http://dev.mysql.com/doc/refman/5.6/en/forcing-innodb-recovery.html
Comment: I will take a look on the link. And yes. We had an extended power outage and the machine went down. The RAID is done by mdadm on Linux, so it's a software solution. Things are probably corrupted.


O código abaixo não está rodando. Somente quando eu retiro as variáveis Largura e Altura de dentro das funções

Question: Será que é possível alguém responder essa minha pergunta? Deve ser coisa simples, mas tá me quebrando a cabeça.
O código abaixo não está rodando. Somente quando eu retiro as variáveis Largura e Altura de dentro das funções

function mostrarAreaAlert() {
  var largura = prompt("Digite a largura");
  largura = parseFloat(largura);

  var altura = prompt("Digite a altura");
  altura = parseFloat(altura);

  var area = calcularArea(largura, altura);

  alert('A area total é: ' + area);
}

function mostrarAreaOutput() {
  var largura = prompt("Digite a largura");
  largura = parseFloat(largura);

  var altura = prompt("Digite a altura");
  altura = parseFloat(altura);

  var area = calcularArea(largura, altura);

  document.querySelector('#output').innerHTML = 'A area total é: ' + area;
}

function calcularArea(l, a) {
  return l * a;
}

  <button onclick="mostrarAreaAlert(largura, altura)">Mostrar Área em Alert</button>

  <button onclick="mostrarAreaOutput(largura, altura)">Mostrar Área no Output</button>

Answer: Olá. Pelo que eu entendi, não é necessário passar as duas variáveis dentro das funções pois logo elas serão inicializadas quando forem respondidas as perguntas. Dei uma modificada no seu código para ele fique mais reaproveitável. Espero ter ajudado.
<button onclick="mostrarAreaAlert()">Mostrar Área em Alert</button>
<button onclick="mostrarAreaOutput()">Mostrar Área no Output</button>

Comment: Perfeito Fernando, esta sua resposta foi muito útil também. Nosso amigo @Asleep deu um comentário acima, onde respondeu justamente a dúvida que eu tinha, do porque meu código não rodar. Ele informou que era só retirar largura e altura de dentro do onclickmouse dos buttons, e realmente resolveu. De toda forma, muito obrigado pelo tempo que você dedicou em responder minha dúvida, pois foi tanto útil quanto a outra, aprendi outra forma de realizar com seu comentário. Muito obrigado.
Answer: solução 1
var area = largura * altura

Depois metes o valor a ser apresentado onde queres.

solução 2
O que fizeste nesta função a seguir funcionava se fosse largura e altura, não tens nada iniciado com l e a.
function calcularArea(l, a){
        return l * a;
    }

Entendes?
Comment: @LucasRodrigues, se não compreendeu a resposta porque a marcou como aceita encerrando sua questão? [Como e por que aceitar uma resposta?](https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta)
Comment: Muito obrigado pela disposição em me atender, mas eu ainda não entendi. Você poderia adequar meu código conforme explicado acima? Com base nisso, entenderia o que devo fazer para que o prompt acione apenas ao clicar nos buttons. Entende? Muito obrigado desde já.
Comment: Para resolver o teu problema, de acordo com o teu codigo, basta alterares o seguinte nele: Nos buttons, quando chamas pelo mostrarareaalert(  ), não precisas da largura e altura lá dentro, deixa os ( ) vazios nos dois e diz-me se funcionou só assim.
Comment: @AugustoVasques
Desculpe, ainda estou aprendendo a mexer aqui. Foi falha minha, obrigado pela orientação.
Comment: @Asleep, perfeito. Funcionou de acordo com sua sugestão. Muito obrigado meu amigo!!!!!


Determining Cause of System Reboot

Question: I have a Fedora 13 virtual machine running on top of VMWare's Hypervisor. Around 6am, it mysteriously rebooted, screwing up some long-running data import processes I was running. I've been checking, but I'm having a hard time finding out why it rebooted. What's the best approach to find out the cause of a reboot?
The machine is in a locked server rack, so it's unlikely someone manually rebooted the hardware. I'm the only one with SSH access to the machine, so it's unlikely someone rebooted the VM remotely. And there are other VMs running on Hypervisor that weren't rebooted, so it's unlikely to be caused by a power failure or reboot of the entire hardware.
Running who -b tells me when the reboot occurred:
~$ who -b
system boot  2011-12-22 06:02

Running crontab -l shows no cron jobs that would trigger a reboot.
Reviewing the historical resource usage graphs in Hypervisor's vSphere client shows that the machine had at most 5% CPU usage for several hours before the reboot, so it wasn't under any unusual load.
Unfortunately, checking /var/log/messages around the time of the reboot only shows:
Dec 22 03:50:01 myserver pcscd: winscard.c:309:SCardConnect() Reader E-Gate 0 0 Not Found
Dec 22 03:50:01 myserver pcscd: winscard.c:309:SCardConnect() Reader E-Gate 0 0 Not Found
Dec 22 03:50:01 myserver pcscd: winscard.c:309:SCardConnect() Reader E-Gate 0 0 Not Found
Dec 22 03:50:01 myserver pcscd: winscard.c:309:SCardConnect() Reader E-Gate 0 0 Not Found
Dec 22 06:02:38 myserver kernel: imklog 4.4.2, log source = /proc/kmsg started.
Dec 22 06:02:38 myserver rsyslogd: [origin software="rsyslogd" swVersion="4.4.2" x-pid="1138" x-info="http://www.rsyslog.com"] (re)start
Dec 22 06:02:38 myserver kernel: Initializing cgroup subsys cpuset
Dec 22 06:02:38 myserver kernel: Initializing cgroup subsys cpu
Dec 22 06:02:38 myserver kernel: Linux version 188.8.131.52-56.fc13.x86_64 (firstname.lastname@example.com) (gcc version 4.4.4 20100630 (Red Hat 4.4.4-10) (GCC) ) #1 SMP Wed Sep 15 03:36:55 UTC 2010
Dec 22 06:02:38 myserver kernel: Command line: ro root=/dev/mapper/VolGroup-lv_root rd_LVM_LV=VolGroup/lv_root rd_LVM_LV=VolGroup/lv_swap rd_NO_LUKS rd_NO_MD rd_NO_DM LANG=en_US.UTF-8 SYSFONT=latarcyrheb-sun16 KEYTABLE=us rhgb quiet
Dec 22 06:02:38 myserver kernel: BIOS-provided physical RAM map:

So basically, nothing happened for about 2 hours, and then the machine suddenly rebooted.
Does this mean the kernel crashed? How would I confirm this? Are there any other logs I should be looking at?
Comment: And what tell the vmWare logs? Maybe a cpu or disk io threshold caused the vmWare manager to cycle the vm?
Comment: It's very difficult to tell why the machine rebooted; there can be several reasons; e.g. does your Fedora Box or your Hypervisor have a watchdog function? Could you have exhausted RAM causing an internal exception; Your APIC emulation may be interfering... can't know without more info.
Comment: @rene, How would I access VMWare logs on Hypervisor? I can only currently connect via vSphere, a crappy Windows GUI, and I can't find any logging info aside from a list of events since the last reboot. I don't know how to SSH into Hypervisor itself (if that's even possible), and finding docs on Hypervisor/VMWare is a nightmare.
Comment: If SSH is enabled on your VM Hypervisor (is it ESX?) then you can actually SSH into the hypervisor itself.
Comment: Any indications of hard or soft reboot? Does the system whine about unclean shutdowns when booting up?
Comment: @Ahmed, Yes, the console says "VMWare ESXi 1.4.0". I just found the option to enable "Remote Support (SSH)". Thanks.
Comment: @Tim, Not as far as I can tell in /var/log/messages.
Comment: In the VM's information area in vCenter there is a "Tasks & Events" tab.  This should contain information about the shutdown if it was the hypervisor that did it.  Most of the time I have seen this sort of thing happen it has been DRS that was the cause.
Answer: If there were a kernel issue and you have kernel dumps setup than there should be a dump file somewhere. Of couse, you this needed to be setup before the crash! You're probably aware by now that ESX/i is structurally similar to Linux so log files will be in roughly the same locations. A good overview is here,
http://www.vmwarewolf.com/which-esx-log-file/
There are also various different methods of parsing/viewing ESX/i log files.
http://www.simonlong.co.uk/blog/2010/06/03/vmware-esxi-4-log-files/

Determining Cause of System Reboot


Restart app to a certain activity?

Question: I need to restart my app to a certain activity...is it possible?
When I restart it I don't want to start the first activity of application. How can I do this?
EDIT : I need to free memory of the app when I restart the app.
Answer: In the onCreate method of the activity that is first launched you need to check if you want to go to another activity or not and then
where restarted is some condition that check if your app was running before , you can use shared preferences to store some bool value
if(restarted){

        Intent startActivity = new Intent();
        startActivity.setClass(this,OTHER_ACTIVITY.class);
        startActivity(startActivity);
        finish();
}else{
   //just normal flow
}

Comment: This is basically a pattern for 'resuming' an Activity. Whenever you start a new activity, the classname is put into a SharedPreference value. Then when the user re-launches the app at a later date, your first 'starter' activity starts the last known activity.
Comment: this mean that it frees the memory of app?
Comment: The memory it is not 'freezed', the app is started again but with different flow. If you want some variables to be saved in memory permanently use shared preferences
Comment: For me is important to free the memory...for this I want to restart the app
Comment: all your instance variables will be freed! of course this will happen if you allocate them in activity A and than close this activity A
Answer: You have to start the Activity you wish straight from the initial Activity's onCreate(). As this is only applicable when the app restarts, you have to save a SharedPreference to flag the fact your app has already started once.
There won't be any flickering as Activity is designed in a way it is not displayed if another Activity is started during its onCreate().

Restart app to a certain activity?


Translating contact forms

Question: Is there a way to fully translate the contact message forms in Drupal 8? In the content language screen, the contact message bundle is marked as translation is not supported.
Edit: To clarify, I would like to translate the fields of the form. As some answers note, the fields can be translated via the regular field translation, but I am running into an issue whereby translations are replaced by the English version when the cache is cleared. By going to /admin/config/regional/content-language and saving the form, the translations are back.
(Note that the default language on the site is not English.)
Comment: Do you want to translate the labels? Those are fields, so you can do that using config translation for the configurable fields and interface translation for the default ones (subject, message, ..)
Answer: I think, content in contact messages is the user input. Then you cannot translate this, because it is not saved to the database. The form itself is config translation, similar to the field definitions in content types.
Answer: Leaving a full answer here for post-release Drupal searchers.
The message "translation is not supported" refers to the content of the fields. The content in this case is not stored, ergo, cannot be translated - unlike, for example any node title or image description.
To translate content like field contents, the required modules are languages & content translation. In your case, you want to actually translate the field titles. This is classed as configuration translation which requires the module of the same name, and that in turn depends on interface translation. So basically, you'll have all of the core modules enabled to perform this task (as obviously you will be translating content as well, right?)
When you have enabled the required modules, you will need to download the .po translation file from .drupal.org and import them in the area User interface translation > Import. Also you can check for updates to your module interface translations under Reports > Available translation updates.
Translating a contact form's fields then is done automatically (if the language file provided for that). Translating the contact form's configurable items is a matter of visiting Structure > Contact forms and selecting translate on the edit/context menu of the form required, whereby you can translate the auto-reply etc.

Translating contact forms


What happend if flat and sharp in one line before any of them neutralized?

Question: its back normal or following the new rule?
for example E-flat hits sharp rule became E and E-flat hits flat rule became D
or back to E-Flat?
Comment: It says to play an E natural and then an E flat. that's what you play.
Comment: Are you talking about inside the red box? There is no sharp there. It goes to E natural and then back to E flat.
Comment: no problem. But if you can find an example of what your original question was it would be good to have on the site.
Comment: but in front of e flat there is sharp? so its not affected? i must follow new rule?
Comment: i think if there is sharp you must keep playing sharp before second sign
Comment: oh sorry my fault, yes that is natural
Comment: i will update the question soon :)
Answer: I think you have mistaken the natural sign for the sharp sign.
The natural sign destroys sharps and flats. This is why a new flat is added after the natural sign, to make it flat again.
There are no sharps here. This is a sharp: #
The key signature shows you all the flats in this piece : B, E, A
If you want an E natural you have to write the natural sign but it only will affect all the E's in that measure. In the next measure if you want an E natural again you will have to write the natural sign again.
I hope that helps.
Answer: In the red box there is an E nat then an Eb. What it says is what gets played, regardless of key Sig. The sign directly before a note is the definitive. Note that after the Eb is re-established (re, since as stated in the key signature), the next E in the same bar also is played Eb.
Here there are two more, both Eb.


How to show error message below the Input fields

Question: In my custom portlet, I want to show error message below the input fields,currently it showing above the input fields. I am using LR6.1.10EE ga1. I have done an analysis on this, under the server \ROOT\html\js\aui\aui-form-validator\aui-form-validator.js file handling the validation.
The javascript method _defErrorFieldFn defines the position where the error message is displayed by calling field.placeBefore(stackContainer); // or field.placeAfter(stackContainer);. By default _defErrorFieldFn calls field.placeBefore(stackContainer);.
Can anyone help me to override this in a custom portlet or find another solution? I don't want to change the core AlloyUI.
Comment: I think it is a CSS change, rather than JavaScript. Have you considered modifying your CSS to position error message below?
Answer: As far as I can tell from the aui-form-validator source*, there does not seem to be a simple way to change the position of the error message via the API. I also tried overriding _defErrorFieldFn() and changing placeBefore() to placeAfter(), but that did not work.
However, I did find a workaround which seems relatively elegant. _defErrorFieldFn() calls printStackError(), which can be overridden to call field.placeAfter(container) before calling through to the original printStackError() like so:
formValidator.printStackErrorDefault = formValidator.printStackError;

formValidator.printStackError = function(field, container, errors) {
    field.placeAfter(container)
    formValidator.printStackErrorDefault(field, container, errors);
};

Here's a runnable example which shows this working:

AUI().use('aui-form-validator', function (A) {
    formValidator = new A.FormValidator({
        boundingBox: '#myForm'
    });

    formValidator.printStackErrorBefore = formValidator.printStackError;

    formValidator.printStackError = function(field, container, errors) {
        field.placeAfter(container)
  formValidator.printStackErrorBefore(field, container, errors);
 };
});

<link href="http://cdn.alloyui.com/1.5.1/aui-skin-classic/css/aui-skin-classic-all-min.css" rel="stylesheet">
<form id="myForm">

    Name:
    <input class="aui-field-required" type="text" name="name" />

    Email:
    <input class="aui-field-required aui-field-email" type="text" name="email" />

    Age:
    <input class="aui-field-required aui-field-digits" type="text" name="age" />

    <input class="aui-button-input" type="submit" value="Submit" />
    <input class="aui-button-input" type="reset" value="Reset" />

</form>

*Liferay 6.1 uses the AlloyUI 1.5 aui-form-validator


RegEx for capturing beginning of file names whilst redacting both file type and a specific set of characters

Question: I have the following regex string:
(.*?)(?=(\(\d+\))).*(\.png|\.jpg)

which correctly matches the following strings and stores something something something in group 1, (123) in group 2 and .extension in group 3
something something something (123).png
something something something (123).jpg

However, when I try to match the next strings I can't figure out how to get the middle part to be optional so that the following are valid matches:
something something something.png
something something something.jpg

I need the first group to store:
something something something

The second group to store:
(123)

where this can be any number of any length
and the third group to store:
.extension

where this can be either .jpg or .png
UPDATE
The data comes in as a single string which is scraped from the internet such as:
Name (Scientific Name) Blah Blah (ID NUMBER).ext
Name (Scientific Name) Blah Blah.ext

Name Blah Blah (ID NUMBER).ext
Name Blah Blah.ext

Name (Scientific Name) (ID NUMBER).ext
Name (Scientific Name).ext

Name (ID NUMBER).ext
Name.ext

Name (ID NUMBER)
Name

EXAMPLES
Dave (Fancy Dave) found at home (1234).png
Dave (Fancy Dave) found at pub.png

Dave found at work (1234).png
Dave found at bus stop.png

Dave (Fancy Dave) (1234).gif
Dave (Fancy Dave).jpg

Dave (1234).ext
Dave.ext

Dave (1234)
Dave

I need to have just the:
Name (Scientific Name) Blah Blah
Name (Scientific Name)
Name Blah Blah
Name

Answer: I'm guessing that you might be designing an expression similar to:
(?i)^(.*?)\s*\(\d+\)?|(.*?)(?:\.ext)?$

DEMO
Test
import re

regex = r"(?i)^(.*?)\s*\(\d+\)?|(.*?)(?:\.ext)?$"

test_str = """

Name (Scientific Name) Blah Blah (123).ext
Name (Scientific Name) Blah Blah.ext
Name Blah Blah (123).ext
Name Blah Blah.ext
Name (Scientific Name) (123).ext
Name (Scientific Name).ext
Name (123).ext
Name.ext
Dave (1234)
Dave

"""
matches = re.findall(regex, test_str, re.M)

data=[];

for each_exts in matches:
    for each in each_exts:
        if each!='':
            data.append(each)

print(data)

Output
['Name (Scientific Name) Blah Blah', 'Name (Scientific Name) Blah Blah', 'Name Blah Blah', 'Name Blah Blah', 'Name (Scientific Name)', 'Name (Scientific Name)', 'Name', 'Name', 'Dave', 'Dave']

The expression is explained on the top right panel of regex101.com, if you wish to explore/simplify/modify it, and in this link, you can watch how it would match against some sample inputs, if you like.
RegEx Circuit
jex.im visualizes regular expressions:
Comment: Perfect! I added \s* inbetween the([^(]*?) and (\(\d+\)) to skip any whitespace after the name and the (123) or .ext
Comment: theres a small issue if the file name is: something (something).png as this would be valid as it contains (string) - something (something) something.png would be valid and so would something (something) (123).png and something (something) something (123).png
Comment: that seems closer to what I am after, do you know if there is anyway that both the (numbers) and .ext groups will be either consistent or that there is a way to get just the something's back from the groups and ignore the (123) and .ext? e.g. if its a (something) treat it as if there are no parenthesis?
Comment: Sorry and the last two cases of Dave (1234) and Dave? Other than that its exactly what I need :)
Comment: as in one sample works that is Dave (1234) but the only case that doesn't would be Dave on its own
Comment: Dave without the .ext so ext would have to be optional?
Answer: try
(.*?)((\(\d+\))?).*(\.png|\.jpg)

It makes the (d+) group optional.


Orthogonal basis with respect to an inner product

Question: Traditionally an orthogonal basis or orthonormal basis is a basis such that all the basis vectors are unit vectors and orthogonal to each other, i.e. the dot product is $0$ or
$$u\cdot v=0$$
for any two basis vectors $u$ and $v$. What if we find a basis where the inner product of any two vectors is 0 with respect to some $A$, i.e.
$$\langle u,v\rangle_A=0$$
Is there a special name for this kind of basis or is it also just called an orthogonal basis?
Furthermore, is there a geometric interpretation for this kind of basis? If we consider the dot product, each pair of basis vectors is at right angles to each other. How does this appear geometrically if we have some general matrix $A$?
Answer: I am assuming that $\langle u,v\rangle_A=u^TAv$ for some symmetric matrix $A$ such that $(u,v)\mapsto\langle u,v\rangle_A=u^TAv$ is an inner product. Then, yes, it is called an orthonormal basis (not just orthogonal, since you are requiring that the vectors are unit vectors).
If we work with that inner product, then we will have a concept of angles, which is distinct from the usual one. But, yes, distinct vectors will be at right angles for that way of measuring angles.
Comment: Intuitively I understand that there will be some concept of a right angle relative to our symmetric matrix $A$ but I was curious as to whether there is some other intuitive visualization of this fact.
Answer:
Traditionally an orthogonal basis or orthonormal basis is a basis such that all the basis vectors are unit vectors and orthogonal to each other, i.e. the dot product is 0 or u⋅v=0 for any two basis vectors u and v.

That's simply NOT true.  Most vector spaces (such as the space of functions continuous on [a, b] do not have a "dot product" defined but rather a general "inner product" (for the space of functions continuous on [a, b] the inner product of f and g is $\int_a^b f(x)g(x)dx$)


Verificar se o valor da coluna é "Base"

Question: Necessitava de verificar se na tabela mytable, na coluna mycolumn, o valor é 'meuvalor'.
O meu controller:
public function GetValue()
    {
            $this->config->set_item('language', $this->session->errorMessagesLang);
            $this->load->library('parser');
            $name= $this->admin_model->getmycolumn();
            if($name['mycolumn'] == 'meuvalor'){
                //fazer o que eu quero
            }
            echo $result;}

O meu model:
public function getmycolumn()
    {
        $this->db->select('mycolumn');
        $this->db->from('mytable');
        $result = $this->db->get()->result();
        return $result;
    }

O meu problema é o ifstatement, este não está a conseguir resolver o meu código, ou seja nao verifica, penso ter a ver com isto:
$name['mycolumn'] == 'meuvalor'

não me parece ser a sintaxe certa.
Todo o tipo de ajuda é bem-vinda!
PS: Só quero deixar claro que consigo ir buscar o valor à tabela, só quero verificar se tem dentro dele o valor que eu quero.
Answer: Faz assim:
$name['mytable'][0]->mycolumn == 'meuvalor'

Comment: Já resolvi, vou pôr aqui a resposta para pessoas futuras que tiverem este problema, ou parecido. Mas muito obrigado à mesma!
Answer: No meu model, vou buscar todos os dados e colunas da minha tabela, retorno isso, após isso, o controlador guarda os dados na variavel $name, e para fazer referência à minha coluna basta referenciar isso após a variavel pondo (conforme necessário) $name['mycolumn']. Ou seja a minha sintaxe estava correta, porém o erro era no model, que me enviava os valores em string, desta forma são enviados no tipo array e não dá qualquer erro, pelo menos da forma que eu estou a utilizar!
O meu controlador:
public function GetValue()
    {
            $this->config->set_item('language', $this->session->errorMessagesLang);
            $this->load->library('parser');
            $name = $this->admin_model->getmycolumn();
            if($name['mycolumn'] == 'meuvalor'){
                    //$result = Fazer oq que eu quero
                    //echo $result;
            }
            elseif($name['mycolumn'] == 'meuvalor2'){
                //$result = Fazer oq que eu quero
                //echo $result;
            }
    }

O meu model:
 public function getmycolumn() {
    $query = $this->db->query("SELECT * FROM mytable;");
    $row = $query->row_array();
    return $row;
}

Verificar se o valor da coluna é "Base"


How should we deal with "what are the causes of economic phenomenon X" questions?

Question: We are getting a fair amount of questions of the type "what are the reasons for X", or "what are the impacts of X on Y" e.g.

The reasons why rouble is collapsing
What is the impact of fracking on oil prices?

Based on down-votes and  comments, whether these questions are amenable to Economics.SE seems to be controversial.

How should we deal with these questions? Are they acceptable?
Under which conditions?
What would be some guidelines for OP who would want to ask this kind of questions and get good answers?
Answer: In my view such questions:
a) Can very easily come out as "too broad" (so guidelines to the OP)
b) In reality they are usually really complex, since they are actual real-world economic phenomena
and so
c) It would take a professional economist a whole paper (at least), and not just an on-screen post, to reach a conclusion.
So I consider them as the hardest challenge to our experts -to be able to formulate a condensed answer, providing some directions and tentative conclusions based on theory and on some relevant real-world info/experience, while keeping visible the parameters of the specific real-world issue that their answer has to leave out. This is applied economics (not econometrics).
So, given that many people here (including myself) would want to see a fair amount of activity coming from experts, I say they should prove that they are worthy of this positive bias in favor of them.
To conclude, some guidance to the OP  when needed to make the question as focused as possible, and keep the questions in, in order to see our experts deliver -or not see them.
Comment: I think we should be very aggressive about down-voting poor answers. It should be this way in general, but especially on answers to questions like these. I expect they'll attract a lot of non-expert answers.
Comment: @jmbejara I think you are right. _Exactly_ because they would be real-world cases, many people may _think_ that their half-baked, usually "practical" knowledge will permit them to provide a useful answer. And it will be exactly the opposite: More often than not Economics are not "intuitive", as the term goes.
Comment: So is this a fair summary of the policy: 1) these questions are okay, but the asker should make them as specific as possible , 2) answers should be either summaries of existing published research, or an experts' overview of the relevant factors, controversies and complexity. Any answers like "Well it's obviously X" will be downvoted/deleted. Is that about right?
Comment: @user568458 "Well it is obviously X" will most likely be turned into a comment. I would add a 3), which would be most interesting : a well organized argument (not necessarily long), by somebody who obviously is not an "expert", but knows how to process information and how to think, and has spent some time thinking and carefully writing his answer. Although really, this has not many chances of appearing: real world economic phenomena are deviously complex, since past, present, future, strategy, survival, position, intermingle tightly.
Comment: Okay, I phrased that badly, by "Well obviously X" I meant "Well obviously X because...[paragraph or two of conjecture/ideology/anecdote]". Would [this answer be an example of 3](http://economics.stackexchange.com/a/1811/1580)? I upvoted it because it acknowledged the construction crash, which is something I've seen in several expert analyses, but on second thoughts, maybe it's too conjecture-y? Maybe a better response would be "Interesting, but citations needed"? As a keen non-expert I want to be sure any contributions I make are positive!
Comment: @user568458 The first two paragraphs are rather the half-baked economic thinking I mentioned in an earlier comments (so they appear -the OP may now much more about these factors but I am talking about the way he _presented_ them). But the last two are good arguments and to the point , that are not strictly economic but bring into the picture issues like culture, ethics, and even climate. I am a Greek and I can tell you, he is dead to the point on these two points.
Answer: Given that the "dismal science" is mostly about influence of factors X,Y,Z on phenomena A, B, C, X, ZZZZ exclusion of such questions kind of seems unwarranted.
Answer: I agree with Alecos that there's a place for them, as long as they're consistent with the level we're aiming for; and that it's crucial to give guidance to posters to ask tightly focused questions, and to show at least some research effort.
It's also up to voters to signal when questions are poor. Both of those questions are very poor, and I am disappointed to see that they both currently have positive net scores. That doesn't preclude them getting good answers. But the key there is that bad questions such as these should be downvoted, and probably put on hold as "too broad", or "unclear what you are asking" until they're edited into better shape. (as a side note, it is unconstructive to add comments asking downvoters to explain - please don't do it; such comments are, in the words of the mighty Shog9, "noise at best, and potentially harmful at worst")
Good answers should be upvoted on their merits, regardless of whether they're on good or bad questions; by the same token, bad questions should be downvoted on their merits, regardless of whether they've got excellent answers.


Naked domain not working on VirtualHost for EC2

Question: I am using AWS EC2 and I am redirecting example.com domain to a directory in EC2 with the following virtual host:
NameVirtualHost *:80

<VirtualHost *:80>
ServerName www.example.com
ServerAlias example.com *.example.com
<IfModule mod_rewrite.c>
    RewriteEngine on
    # WITH 'www.'
    RewriteCond %{HTTP_HOST} !^www.(.*) [nocase]
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}$1 [redirect=permanent,nocase,last]
  </IfModule>
DocumentRoot /var/www/html/Example
</VirtualHost>

Now it when I go to www.example.com it is working correctly. However, using the naked domain http://example.com I get the following error:
Failed to load resource: the server responded with a status of 404 (Not Found)
GET http://peep.ie/ net::ERR_NAME_NOT_RESOLVED

This is the DNS configuration:
A   *.example.com.  xxx.yyy.zzz.ttt 3600    Manual   Active  Yes

Answer: *.example.com covers all subdomains of example.com, but not example.com itself. You need a second DNS record.


Contar dados da coluna e resetar após troca do cpf

Question: Tenho as seguintes colunas na tabela eventos (nome_hosp,cpf_hosp,parametro_evento, data).
O que preciso fazer é, aonde o valor da coluna parametro_evento = 1, realize uma contagem de linhas separando por CPF, ou seja, por pessoas.
Por exemplo:

Caso tenha 03 dados com o CPF(numero ficticio) igual a 1

Ele me imprimirá: CPF:1 total: 3

Caso tenha 03 dados com CPF=1 e 02 dados com CPF=2

Ele me imprimirá: CPF: 1 total:3 CPF: 2 total: 1
Imagem da tabela

O que vem me retornando:

O que eu gostaria que retornasse seria, no lugar de "Joao" o BPM seria apenas 1, por que de acordo com o banco de dados ele só tem uma ocorrência com o parâmetro 1 e não 3.
Código:
$result_transacoes = "SELECT * FROM  eventos WHERE (timestamp_evento BETWEEN '$de' AND '$ate') GROUP BY cpf_hospede";
$resultado_trasacoes = mysqli_query($conecta, $result_transacoes);
$cont_bpm=0;
while($row_transacoes = mysqli_fetch_assoc($resultado_trasacoes)){
    if($row_transacoes['parametro_evento'] == '1') {
        $result = mysqli_query($conecta,"SELECT count(*) as total from eventos GROUP BY cpf_hospede");
        $data = mysqli_fetch_assoc($result);
        $num_bpms= $data['total'];
    }
}

Eu acreditava que, caso fizesse um group by isso resolveria meu problema, porém não.
Comment: Em seu primeiro SELECT você não informou a função de agregação. Em seu segundo SELECT você a função de agregação e a cláusula GROUP BY mas não lista o campo pelo qual está fazendo a agregação. Dessa forma não tenho ideia de como você une as informações dos dois SELECT.
Comment: Poderia explicar melhor? Eu fiz o GROUP BY no 1° e 2° select
Answer: Pelo que entendi o seu problema é mais na questão de montar o SQL.
Criei um exemplo aqui, onde você pode testar a solução
Exemplo
Vamos imaginar a seguinte estrutura da sua tabela
create table eventos(
  id integer,
  nome varchar(50),
  cpf varchar(50),
  parametro integer);

Com os seguintes registros
 insert into eventos values (1, 'Joao', '123', 1);
 insert into eventos values (2, 'Joao', '123', 1);
 insert into eventos values (3, 'Joao', '123', 1);
 insert into eventos values (3, 'Joao', '123', 0);
 insert into eventos values (4, 'Maria', '321', 1);
 insert into eventos values (5, 'Maria', '321', 1);
 insert into eventos values (6, 'Matheus', '222', 1);

Agora para trazermos os dados que deseja, podemos fazer tudo em um único SQL, da seguinte forma
select nome
      ,cpf
      ,count(if(parametro = 1, 1, null)) as TOTAL
  from eventos
 group by cpf

Dessa forma você conseguiria ter o resultado que deseja com um único SQL, basta adequar a sua programação PHP agora.
Explicação
count(if(parametro = 1, 1, null)) as TOTAL essa parte, irá contar todos os registros que tiverem o parametro igual a 1, ignorando o que for diferente de 1 setando null para que a função não contabilize o mesmo.
EDITADO
Não possuo muito conhecimento com PHP e o que sei é voltado com utilização de PDO, mas esse exemplo pode te dar uma luz de como aplicar para o seu caso:
$result_transacoes   = "SELECT nome_hospede, cpf_hospede, count(if(parametro_evento = 1, 1, null)) as bpm FROM eventos WHERE (timestamp_evento BETWEEN '$de' AND '$ate') GROUP BY cpf_hospede";
$resultado_trasacoes = mysqli_query($conecta, $result_transacoes);

$total_bpm=0;
while($row_transacoes = mysqli_fetch_assoc($resultado_trasacoes)){
    $nome= $row_transacoes['nome_hospede'];
    $cpf= $row_transacoes['cpf_hospede'];
    $num_bpms= $row_transacoes['bpm'];

    $total_bpm+=$num_bpms;
}

Cada volta que o loop der, as variáveis serão implementadas com o valor referente a linha atual da sua query. A variável $total_bpm será acrescida com o valor de BPM de cada linha para assim te retornar o total de BPMs referente a todos os registros retornados.
Comment: @JoãoVitor verifique a seção **EDITADO** da minha resposta, coloquei um complemento que pode te ajudar.
Comment: Matheus, no caso, o valor do parâmetro varia de 1-6, o código seria o mesmo? está me retornando o seguinte erro.:Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, bool given in C:\xampp\htdocs\swc\testapdf.php on line 49
Linha 48`$result = mysqli_query($conecta,"select nome_hospede,cpf_hospede,count(if(parametro = 1, 1, null)) as total from eventos group by cpf_hospede");
        `Linha 49:`$data = mysqli_fetch_assoc($result);`


How to get rid of voice crossing in Harmony?

Question: I am currently working on Harmony 9 in the new Royal Conservatory of Music Celebrate Theory curriculum, and I keep getting overlaps for SATB voicing (voice crossing)  when I try to harmonize a melody. How do you avoid them? I keep on doing it and I am so frustrated that I can't do it right.
Comment: 'Overlaps'?   Sorry, I don't understand.  Can you try another descriptiopn please?
Comment: Which (book?) is RCM?  What is contained in Harmony 9?  Is this a question about 4-part chorale writing, and if so, are you possibly referring to crossed voices or parallelisms?
Comment: Royal College of Music, U.K. or Royal Conservatory of Music, Canada? Harmony 9? haven't a clue...
Comment: Are overlaps voice crossings? Unisons between voices? Incorrect doublings? Maybe even parallels?
Comment: Yes they are voice crossing. I study using the new Royal Concervatory of Music book. Harmony 9 refers to Basic Harmony I guess.
Answer: Try giving the voices some space. Use wider voicings, with the bass tending  towards the lower end of its range and soprano tending towards the upper end of its range.
When you do find voices crossing, go back a few beats or measures and look for alternative voicings which won't result in overlap.
Answer: Well, if you don't want voice-crossing, don't write voice-crossing.  Difficult to give detailed advice without seeing the exercise you're working on. Sometimes this can mean tolerating static inner voices with lots of repeated notes instead of interesting melodic lines.  But I'm afraid that's the way with 'harmony exercise' style writing.  In the real musical world you probably won't be writing hymn tune style for SATB choir all that much and you'll be able to explore the possibilities of counterpoint between contrasting sounds rather than aiming for a homogeneous sound.
Comment: From what I recall of my Royal Conservatory of Music Harmony lessons, voice leading can get pretty strict--"we provide you the notes you must start with", "all leading tones must rise one semitone", "the seventh degree of a dominant seventh must fall to the third of the key", etc. Thus, voice crossing is harder to avoid than you'd think.
Comment: Yes, it's 'Bach chorale' rules. But I can't really picture how dom 7th and leading note voice leading would cause problems with voice crossing?
Comment: OK, maybe not precisely dominant 7th and leading tone. But say the soprano voice is pre-defined as D-G (falling), and you've already written a B in the alto voice at the D...leading tone voice leading dictates a voice crossing here already, and you pretty much have to take that path if the G is the last note.
Comment: Is this a real example?   Soprano voice wouldn't normally go as low as G below Middle C.  But if that's the melody, you aren't really at liberty to obscure it.   Of course, if the soprano is an octave higher, there's no problem.
Comment: I was assuming the G above Middle C and the D above that.
Comment: So what's the problem?  Unless the alto was on the B ABOVE middle C.  That would have been bad planning.
Comment: That's correct--the B is also above Middle C. There's some bad planning involved in someone's part, but the rules dictate that you write yourself into a corner surprisingly often.


Is the maximum entropy distribution consistent with given marginal distributions the product distribution of the marginals?

Question: There are generally many joint distributions $P(X_1 = x_1, X_2 = x_2, ..., X_n = x_n)$ consistent with a known set marginal distributions $f_i(x_i) = P(X_i = x_i)$.
Of these joint distributions, is the product formed by taking the product of the marginals $\prod_i f_i(x_i)$ the one with the highest entropy?
I certainly believe this is true, but would really like to see a proof.
I'm most interested in the case where all variables are discrete, but would also be interested in commentary about entropy relative to product measures in the continuous case.
Answer: One way is to use the properties of the Kullback-Leibler divergence.
Let $\mathfrak{P}$ be the family of distributions with the given margins, and let $Q$ be the product distribution (and obviously $Q \in \mathfrak{P}$).
Now, for any $P \in \mathfrak{P}$, the cross entropy is:
$H(P,Q) = E_P [\log q(X)] = E_P \left[ \log \prod_i q_i(X) \right] = \sum_i E_P [\log q_i(X)] = \sum_i H(P_i,Q_i)$
that is, the sum of the cross entropy of the margins. Since the margins are all fixed, this term itself must be fixed.
Now we can write the KL divergence as:
$D_{KL}(P \| Q) = H(P,Q) - H(P)$
and hence:
$\operatorname*{arg\,min}_{P \in \mathfrak{P}} \ D_{KL}(P \| Q) = \operatorname*{arg\,max}_{P \in \mathfrak{P}} \ H(P) $
that is, the distribution $P$ which maximises the entropy is the one which minimises the KL divergence with $Q$, which by the properties of the KL divergence, we know is $Q$ itself.


null equivalent in python for defining global variable

Question: I am looking for an example to create a global variable in Python , just like in java you can do something like
 String my_global_string = null
 for .... {
     reassign value of my_global_string
}
use the my_global_string value

What is the equivalent of null in python if the object is of type file
Comment: Does this answer your question? [Referring to the null object in Python](https://stackoverflow.com/questions/3289601/referring-to-the-null-object-in-python)
Comment: ...are you looking for `None`? Please remember to _search_ before asking a new question.
Comment: @alaniwi, I get where you're coming from, but this has still been covered already and users _are_ expected to search before asking. This is the kind of question that experienced users should expect to already be here.
Comment: In Python, `null` is `None`
Comment: Before everybody piles on with negative comments or downvotes, cut the OP a little slack here. They are coming to it from the point of view of a strongly typed language, and asking about the equivalent of `null` **for type `file`**. Well the answer is that there is no equivalent for type `file`. There doesn't need to be. A variable that could under certain circumstances point to a `file` object can instead point to `None` when applicable, even though it is a different type.
Answer: On a closer look, this question doesn't really appear to be about None, but about scope. Python doesn't have block scopes, so any definition you assign to my_global_string inside the loop can serve as the initial definition, so long as the loop itself is at the global scope.
There is no need to "preassign" a null value (None) to the name before entering the loop.
for x in some_iterable:
    my_global_string = "hi there"

print(my_global_string)

Should you need to define a global from some other scope, that's why the global statement exists.
# This function creates a variable named "my_global_string"
# in the global scope.
def define_a_string():
    global my_global_string
    my_global_string = "hi there"

for x in some_iterable:
    define_a_string()

print(my_global_string)


Number of $r$-colorings of a path graph with a specific color appearing $k$ times: A budgeted graph coloring

Question: How to count proper vertex colorings of a path graph with $n$ vertices using at most $r$ colors with the condition that a specific color is used exactly $k$ times?
When the condition is relaxed, the answer is $r(r-1)^{n-1}$.
When the condition is hold, but the coloring can be improper, the answer is $\binom{n}{k}(r-1)^{n-k}$. If it is additionally assumed that the specific color is not used for adjacent vertices, while the other colors can (kind of partially proper coloring), the answer is $\binom{n+1-k}{k}(r-1)^{n-k}$.
Is there a closed form solution to it? I find it challenging, while only a simple condition is imposed.
It is also related to budgeted graph coloring studied in this paper.
In general, is there any efficient algorithm that enumerates or counts proper $r$-colorings of a given simple graph where the number of times that each color appears is exactly given or lies in a given interval? In the above question, the specific color appears exactly $k$ times and there are no restrictions on the other colors.
Answer: The argument that gives $\binom{n+1-k}{k}(r-1)^{n-k}$ can be refined to count proper colorings. The idea is that deleting the $k$ vertices colored with the special color leaves, in most cases, $k+1$ paths with $n-k$ vertices total, and there are $(r-1)^{k+1}(r-2)^{n-2k-1}$ ways to color these paths.
We cannot simply say $\binom{n+1-k}{k}(r-1)^{k+1}(r-2)^{n-2k-1}$, because if the first and/or the last vertex gets the special color, then fewer components are left over. There are $\binom{n-k-1}{k-2}$ cases where both the first and last vertex get the special color, $2\binom{n-k-1}{k-1}$ cases where only one of them does, and $\binom{n-k-1}{k}$  cases where neither of them does. We can combine these into $$\binom{n-k-1}{k-2}(r-1)^{k-1}(r-2)^{n-2k+1} + 2 \binom{n-k-1}{k-1}(r-1)^k (r-2)^{n-2k} + \binom{n-k-1}{k} (r-1)^{k+1}(r-2)^{n-2k-1}$$ total $r$-colorings.
Comment: Thank you Misha, but a slight change is required. $r$ and $r-1$ should be replaced by $r-1$ and $r-2$, respectively as the specific color is one of the $r$ colors.
Comment: Hence, the answer is $$\binom{n-k-1}{k-2}(r-1)^{k-1}(r-2)^{n-2k+1} + 2 \binom{n-k-1}{k-1}(r-1)^k (r-2)^{n-2k} + \binom{n-k-1}{k} (r-1)^{k+1}(r-2)^{n-2k-1}$$
Comment: Thank you! I've corrected it.


Number of ways of getting valid change

Question: A movie theater charges $50$ Rupees for a ticket.
The cashier starts out with no change, and each change customer pays with a Rupees $50$ note or Rupees $100$ note (& gets change).
Clearly, the cashier will be in trouble if there are too many customers with $100$ rupees note.
It turns out that there are $2n$ customers, and cashier never had to turn them away, but after dealing with last customer, there were no $50$ rupees note left in cash register. Let $w_n$ denote the number of different ways this could have happened.
Find $w_n$.
Answer: HINT: As each customer comes to the cashier, write down a left parenthesis if he pays with a $50$ rupee note and a right parenthesis if he pays with a $100$ rupee note. At the end you will have a string of $2n$ parentheses.

Show that exactly $n$ of the customers paid with a $50$ rupee note, so that the string has $n$ left and $n$ right parentheses.
Show that as you read the string of parentheses from left to right, you have always seen at least as many left parentheses as right parentheses. For example, if $n=3$, you might see (()()) or ()()(), but you cannot see ())(() or )((()).

Now look at this article on Catalan numbers, especially the part on Dyck words in this section.
Comment: @Maggi: The article actually has a proof, though you have to modify it slightly. Look at [this proof](http://en.wikipedia.org/wiki/Catalan_number#Second_proof), but think of each $\to$ step as a `(` and each $\uparrow$ step as a `)`. The legitimate parenthesis strings correspond to the lattice paths that do not cross the diagonal.
Comment: Thanks , your post was indeed usefull including links :) i can show both points easily but i am having difficulties in calculations , how can we calculate possible sequences like you showed using parenthesis ?
It would be very useful @Brian M.Scott if you could directly tell the answer/explanation as tomorrow is itself my olympiad :)
Comment: So is the answer (2n)!/((n+1)!n! ? But how can we prove that ?
Comment: Thanks a lot Proffessor Brian M.Scott :D
I loved combinatorcs a lot but this sector was totally unexplored by me , your links and application of Catalan nos. has really given me more approaches and techniques ! Thanks a looooot :D
Comment: @Maggi: You're welcome!

Number of ways of getting valid change


ABC is an isosceles triangle with AB = AC = 3. There are k distinct points on BC, denoted by P1, P2, P3...Pk.

Question: ABC is an isosceles triangle with AB = AC = 3. There are k distinct points on BC, denoted by P1, P2, P3...Pk. Let Xi = (APi)^2 + (BPi x PiC) where i = 1, 2, 3...k. Find the value of k if X1 + X2 + X3 ... Xk = 1080.
So
$X_i=3^2=9$
$k \cdot 9=1080$
Is this correct?
Comment: Why do you think that?
Comment: Your post would be a lot easier to read if you also used proper formatting on the paragraph. Formatting tips [here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: This may be helpful: http://mathworld.wolfram.com/StewartsTheorem.html
Answer: Yes, it is because according to Stewart's theorem you have
$$X_i = AP_i^2 + BP_i\cdot P_iC=\frac{3^2P_iC+3^2BP_i}{BP_i+P_iC}=9.$$
Comment: Thanks you very much by correction of writing.
Answer: This is solvable because $P_iA^2+BP_i\cdot CP_i=AB^2=AC^2=9$ for every  $i.$
Let $AB=c,\;BC=a,\; CA=b.\;$ For brevity let $P_iB=x_i, \; P_iC=y_i, \; P_iA=z_i,\;$ and  $ \cos B=\cos C=D.$ By the cosine formula we have $$z_i^2=x_i^2+b^2-2x_ibD.$$ $$z_i^2=y_i^2+c^2-2y_icD.$$ Adding these and substituting $b=c=3$ we have $$2z_i^2=x_i^2+y_i^2+18-6(x_i+y_i)D.$$ Adding $2x_iy_i$ and noting that $x_i+y_i=BC=a,$ we have $$2(x_iy_i+z_i^2)=2x_iy_i+x_i^2+y_i^2-6(x_i+y_i)D=(x_i+y_i)^2+18-6(x_i+y_i)D=$$ $$=a^2+18-6aD.$$ By the cosine formula we have $$9=c^2=a^2+b^2-2ab \cos C=a^2+9-6aD,$$ $$\text {So } a^2-6aD=0.$$ $$\text {Therefore }\; 2(x_iy_i+z_i^2)=a^2-6aD+18=18.$$ $$\text {So } x_iy_i+z_i^2=9.$$ $$\text {Finally, }\; 1080=\sum_{i=1}^k(x_iy_i+z^2)=\sum_{i=1}^k9=9k.$$ $$\text {So } k=120.$$
Answer: Your hypothesis is that $X_i = 9 $ $ \forall i$ but $X_i = (AP_i)^2 + (BP_i)(P_iC)$. So the value of $X_i$ can't be considered as a constant.
For example if you take $B$ like $P_i$, so  $X_i = (AB)^2 + (BB)(BC) = (AB)^2 = 9$.
If you take the mid of $BC$, called $D$, like $P_i$, so  $X_i = (AD)^2 + (DB)(DC) = (AD)^2*(DB)^2 $ .
We can consider a triangle where $BC =4$. So $DB =2$ and  $AD= \sqrt5$ (because $BC^2 + DA^2 = AB^2$ by Pythagorus).
We have :
$X_i = (\sqrt5)^2*(2)^2 = 20$.
And if your $X_i$ are different you can't use your formula ...
Comment: It seems that  the Q was re-written after your A.
Comment: You made an error and replaced plus with times. In your example X = AD^2 + (DB) (DC)=AD^2 + (DB)^2. You wrote times. So X = 5 + 2^2 and not $5*2^2$ which *does* equal 9 and not 20.  Turns out all X_i are constant after all. And no, the question had not been changed since this answer.


Unknow database [...] when selecting the database (Ubuntu)

Question: I'm trying to work with MySQL on my laptop (Ubuntu)  and always that I have to export a .sql file to database, the console show me the same message: "unknow database Spotify (for example) when selecting the database".
The sql script is correct, and must work, but always show the same message; any solution?
<code>CREATE DATABASE Spotify;
USE Spotify ;

DROP TABLE IF EXISTS Spotify.Usuarios ;
CREATE TABLE IF NOT EXISTS Spotify.Usuarios
(
  iduser INT NULL ,
  user VARCHAR(10) NULL ,
  password VARCHAR(45) NULL ,
  reg VARCHAR(45) NULL
) ENGINE = InnoDB;
</code>
Comment: You show neither your script nor the way you execute it. Hard to help you without any information.
Answer: Finally, I solved it: there was a problem with Ubuntu packages, and the mysql's installation didn't finished correctly


Prove $\neg (p \land q) \vdash \neg p \lor \neg q$ by natural deduction

Question: I have tried solving this by negating $\neg p \lor \neg q$ to get to a pbc, but apparently you need to use a few lem's (law of excluded middle) to solve the problem. Where (and how) have I gone wrong in the following deduction?

$\neg(p \land q)$ .............................hyp

$\neg(\neg p \lor \neg q)$ .................hyp

$\neg p$ ........................hyp

¬p ∨ ¬q ....... vIL, $3$
$F$ ...................$\neg$E, $2$, $4$

$\neg q$ ........................hyp

$\neg p \lor \neg q$ .......$\lor$ER, $6$
$F$...................$\neg$E, $2$, $7$

$F$ .................................$\lor$E, $2$, $3-5$, $6-8$

$\neg p \lor \neg q$ .............................pbc $2-9$

Any help would be greatly appreciated!
Comment: Hello, next time please use MathJax to format your questions: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference If you want to see an example, I went through your question and edited it. So you can look at the code.
Answer: Fairly close.    Always keep an eye on the prize.   You want to be able to contradict the first premise, $\lnot(p\land q)$, so that requires deriving $p$ and $q$, then introducing a conjunction.
Thus the purpose of those subproof are to be proofs by contradiction too.
$$\def\bot{\mathcal F}\def\fitch#1#2{\quad\begin{array}{|l} #1\\\hline #2\end{array}}
\fitch{~~1.~\lnot(p\land q)}{\fitch{~~2.~\lnot(\lnot p\lor\lnot q)}{\\\fitch{~~3.~\lnot p}{~~4.~\lnot p\lor \lnot q\hspace{4ex}\lor\mathsf I, 3\\~~5.~\bot\hspace{9ex}\lnot\mathsf E,2,4}\\~~6.~p\hspace{13ex}\mathsf {PBC},3{-}5\\\\\fitch{~~7.~\lnot q}{~~8.~\lnot p\lor \lnot q\hspace{4ex}\lor\mathsf I, 7\\~~9.~\bot\hspace{9ex}\lnot\mathsf E,2,8}\\10.~q\hspace{13ex}\mathsf {PBC},7{-}9\\\\11.~p\land q\hspace{9ex}\land\mathsf I, 6,10\\12.~\bot\hspace{12ex}\lnot\mathsf E,1,11}\\13.~~\lnot p\lor\lnot q\hspace{9ex}\mathsf {PBC},2{-}12}$$

PS: The PBC steps contain the LEM, in the form of double negation elimination (DNE).
$$\begin{array}{|l}\fitch{~~3.~\lnot p}{~~4.~\lnot p\lor \lnot q\hspace{4ex}\lor\mathsf I, 3\\~~5.~\bot\hspace{9ex}\lnot\mathsf E,2,4}\\~~6.1.~~\lnot\lnot p\hspace{10ex}\neg\mathsf I, 3{-}5\\~~6.2.~p\hspace{13ex}\lnot\lnot\,\mathsf E,6.1\end{array}$$
Answer: The following proof is patterned on the one provided in section 19.6 of the forallx text as a proof of the first De Morgan rule.

Note the use of the law of the excluded middle (LEM) on line 10 which references the two cases for $P$ on lines 2-7 and $¬P$ on lines 8-9.  The links to the proof checker and the textbook are provided below.

Kevin Klement's JavaScript/PHP Fitch-style natural deduction proof editor and checker http://proofs.openlogicproject.org/
P. D. Magnus, Tim Button with additions by J. Robert Loftis remixed and revised by Aaron Thomas-Bolduc, Richard Zach, forallx Calgary Remix: An Introduction to Formal Logic, Fall 2019. http://forallx.openlogicproject.org/forallxyyc.pdf


CSS float and div block position

Question: I have this problem then I try to float div left,
each block contains same div class (member).
Block goes up if it is on the right hand side, but doesnt work on left.
Any thoughts?
.member {
    float: left;
    position: relative;
    width: 422px;
    margin: 0px 10px 10px 0px;
    height: auto;
}

image with example
Comment: Post your HTML, please. It depends on order of these blocks.
Comment: mg-web.co.uk/hosting/bugs/html_css/team.htm - I am getting really confused, there could be a problem?
Answer: I suppose you want two columns with blocks of different height.
Then you should one column float to left and the second to the right:
Like this:
.member {
    position: relative;
    width: 422px;
    margin: 0px 10px 10px 0px;
    height: auto;
}

.fl_left {
    float: left;
    clear: left;
}

.fl_right {
    float: right;
    clear: right;
}

HTML:

Comment: [link](http://mg-web.co.uk/hosting/bugs/html_css/team2.htm) - Yes but in this case block on the left dont go up, I dont need the spacing between the divs

CSS float and div block position


Opening a winform from an IronPython shell without blocking the shell or the form

Question: I'm starting a winform from an IronPython shell. My form is then calling a script which runs for some hours and writes output to the shell.
While the script is running, the GUI is blocked (I cannot hit any buttons or minimize it).
I tried these approaches:

When I open the form with ShowDialog(), the form stays in front. I cannot put the python shell in front and scroll the written comments. I have to close the form first, but this is not what I want.
When I open the form with Show(), I can put the python shell in front and I can scroll it, but when I close the python shell (before closing the winform), the winform stays open and is now blocked; I can only kill it using the Task Manager.

So, what I want is the situation like in case 2, but when I close my python shell, the winform should be automatically closed too.
After reading some other questions here I thought about starting the form with Show() but setting the Modal property to true, but when I try to do this from the shell it says the property is private. I created the form in Visual Studio, so is it maybe possible to set the Modal property there somewhere?
Answer: I think what you need to get your UI to process the windows events for the application by calling:
Application.DoEvents()

The reason why the Modal window is working for you is because it automatically behind the scenes loops and automatically process windows messages.
Here is a sample C# and IronPython code to simulate a long running script showing a Windows Form
var py = Python.CreateEngine();
var script = @"
import clr
clr.AddReference('System.Windows.Forms')
from System.Windows.Forms import *
from System.Threading import *
frm = Form()
frm.Show()
while True:
    Thread.Sleep(100)
    Application.DoEvents()
";
var source = py.CreateScriptSourceFromString(script);
var scope = py.CreateScope();
source.Execute(scope);

Notice the python code is just indefinately looping (Simulating your long running script)
It is important that your script has the opportunity to be able to call into DoEvents to update the UI. If this is NOT the case and your script will block for a long time on single calls, you might consider running the script itself in a seperate thread, this will allow you to leave the main thread available to process messages.
Just be careful when creating threads the Winforms doesn't like to be created or updated from a seperate thread, so make sure you are calling your UI update methods by synchronizing them to the main thread.
With the sample code above, when I close the console window, the Winform is also automatically destroyed by windows. So I am not seeing the problem you describe.


Calculating time difference between two dates

Question: I have data similar to the following:
`date1`     `date2`
2013-04-02  NULL
2013-03-26  NULL
2013-03-26  2013-03-06
2013-03-25  2013-03-05

I would like to find the difference in days. For example:
`date1`     `date2`    `difference`
2013-04-02  NULL        NULL
2013-03-26  NULL        NULL
2013-03-26  2013-03-27  1.0 # DAYS
2013-03-25  2013-03-28  3.0

How would I calculate this difference?
Comment: https://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_datediff
Comment: date2.Subtract(date1).TotalDays;
Answer: You can use a DATEDIFF function.
DATEDIFF(date1,date2)

The following SELECT statement:
SELECT DATEDIFF('2014-11-30','2014-11-29') AS DiffDate

Output will be.
DiffDate
1


Power in survival analysis

Question: I just read an article discussing the effect of radiotherapy duration on survival. They state the following:

It was expected that changing the treatment from 1 week to 3 weeks
  would improve survival by 15%. 144 deaths were needed to detect a
  hazard ratio of 1.61 between the two treatment arms, with a power of
  80% and a significance level of 5%.

Could someone elaborate on how this poweranalysis was done, specifically where does the number 1.61 come from?
Reference to the article:
Pubmed PMID: 26392096
Comment: Can you provide a full citation for the article?
Answer: The cited paper reported on a non-inferiority trial for 1 week versus 3 weeks of radiotherapy in elderly/frail patients with glioblastoma multiforme.
The confusion here might arise from the ambiguity in the phrase "improve survival by 15%." To me, that seems to represent a 15 percentage point improvement from a baseline of 6-month median (50%) survival.
For an exponential survival curve with $S(t)=\exp(-t/\beta)$, a median survival of 6 months means $\beta = 8.656$ months. If you multiply that value of $\beta$ by 1.61, getting a value of 13.94 months, the corresponding 6-month survival is $\exp(-6/13.94)=0.65$, or 65% 6-month survival. That's a 15 percentage point improvement in 6-month survival.
As the cited paper was in the Journal of Clinical Oncology, which typically has strong statistical review, the power analysis for the non-inferiority trial presumably followed guidelines like those  in this paper, although I haven't worked through the details myself.

Power in survival analysis


What does "dead money" mean when referred to in the NFL?

Question: I always hear this used especially during the off season when players are being signed to a new contract or cut. I still don't understand the significance and usage so what does "dead money" mean when referred to in the NFL?
Comment: It has been referred to a lot during sports shows, I have a better idea now of what their discussing
Comment: I've seen website displaying "dead money" as they represent the salary cap for each team as well
Answer: It's a consequence of signing bonuses and the salary cap maths. Due to the non-guaranteed nature of contracts, NFL contracts are split into two parts: an annual salary, payable if the player is on the roster that year, and a "signing bonus" which is paid up front. For example, a 5 year, $15 million contract could be broken up as a $2 million annual salary and a $5 million signing bonus. For cap purposes, the signing bonus is prorated over the length of the contract, so that $15 million contract would have an annual cap charge of $3 million as you might expect.
The complication comes if a team decides to cut a player - in that case, the annual salary comes off the books, but whatever hasn't already been accounted from the signing bonus counts against the cap in that year. For example, if the team decided to cut our $15M player just before the fourth year of his contract, the "cap charge" for that player would be $2M for the bits of the signing bonus that got prorated into years 4 and 5 of the contract. However, they get nothing for that $2M (because they've cut the player!) hence "dead money".
Comment: Whether it counts against the current depends on whether the player is current prior to June 1st, if it is after then the dead money accelerates into the following year not the current.
Answer: Dead Money means money that can't be spent because it was paid to a player who is no longer on the team.  It is the penalty  for teams paying players up front.  Simply put, The Jets sign Joe Player to a 5 year deal worth $15M during free agency before the 2014 season.  The contract is structured so that Joe will receive $2M in salary every year he is on the team and will receive a $5M signing bonus.  The 2014 NFL salary cap per team was $133M.  After the 2014  season Joe earned $7M ($5M to sign + $2M in salary).  Joe is slated to make his regular $2M salary in 2015, but before the regular season starts, the Jets trade Joe to another team or cut him.  No matter what does or doesn't happen to Joe, the Jets now have $4M in dead money in 2015. The $5M signing bonus received by Joe in essence was the Jets spending future salary cap money ($1M against the the Jets salary cap in 2014, $1M in 2015, $1M in 2016, $1M in 2017, and $1M in 2018). When Joe's contract is terminated or traded by the Jets, those 2015 - 2018 amounts on the Jets book are moved to 2015 resulting in $4M the Jets can't spend in 2015. The 2015 NFL salary cap per team was $143M and the Jets can only spend $139M because they have $4M in dead money they can't spend.


How can i rename my default wp-login.php to login?

Question: I would like to rename url of http://mysite/wp-login.php to http://mysite/login
and also http://mysite/wp-login.php?action=register to http://mysite/signup
I used following code in my .htaccess file but it does not work
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /robin_site/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^login$ http://mysite/wp-login.php [NC,L]
RewriteRule . /robin_site/index.php [L]
</IfModule>

# END WordPress

So is it possible or not if have then please help me ?
Comment: you can try this plugin https://wordpress.org/plugins/custom-login-url/?
Comment: What does "not work" mean? Isn't it redirecting? Do you get a "500 server error", a "404 not found", anything else?
Comment: Yes , error showing me like 'page isn't working'
Answer: Your question is still a bit vague, so this is just a guess.
First of all, the order of rules (and its associated conditions) is important, because they will be tried from top to bottom. Furthermore, conditions belong to the immediately following rule.
Since this is a Wordpress site, I think the following two rules, and conditions, belong together
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /robin_site/index.php [L]

The new rule looks good, but will never trigger, if put after the above rules. To have any effect, you must put it at the beginning. Also, there's no need to prefix with the scheme and host, unless you want to force http or redirect to a specific host
RewriteRule ^login$ /wp-login.php [NC,L]

So, all rules together, with the new one in front, gives
RewriteRule ^login$ /wp-login.php [NC,L]

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /robin_site/index.php [L]


How to track backups

Question: We're in the midst of re-organizing our backup solution.  We currently have several different tools and scripts running on various machines in our network which run backups autonomously.  In the end, all the backups are to be consolidated onto a single NAS which will be rotated weekly.
What we'd like is something that tracks all of the final backups on the NAS and lets us know when one of them failed to occur.  Before rotating the NAS', the invididual would first check some form of report to find out if all the "backup targets" have been updated.
Are there any existing solutions?  We're a small enterprise so it can't be very expensive (ideally free).
Answer: You should look into centralizing your backup process with a solution like Bacula or the myriad of non-free solutions. Other solutions might fit your environment better, but you haven't listed any details of what OS, the quantity of servers/data, or other specifics.
Links provided for ideas and do not represent an exhaustive list by any means.
Comment: I'm not looking for an all-in-one backup solution.  I want to keep it open to being a mixture of methods.   I'm just looking for a way to report on the final backup to the NAS.  We're mostly a Windows environment but I'll install linux on a box if I need to.
Comment: +1 for bacula. We backup several dozen servers with it, and it feeds its results into an EMC Networker (which then goes to tape). Works like a charm, with fully configurable notifications.
Comment: @Mr Grieves, without knowing what software you're currently using I have no way of knowing if it can be configured to report results or send notifications. I'm guessing that you're using a "solution" that's fairly duct-taped together and are simply hoping that everything works as intended. The reason most places ditch such methods are the very problems you are bringing up. Business mature, and their needs change; sounds like it's time for the Backup Methods to change with the business needs.
Comment: @Mr Grieves - if you're hard-set on using your homebrewed solution, one thing you could do pretty easily is to add logic to your scripts to email you the `stderr` output of each script. At least with that, you'll know pretty quickly when something goes awry.

How to track backups