Prove the derivative of $f(x)=\left( \left| x \right| \right) ^{3}$ exist.

Question: i got a problem with this exercise.
I need to prove the derivative of this function: $f(x)=\left(  \left| x \right|  \right) ^{3}$ exist.
Well, i make via definition:$\lim _{h\rightarrow 0}{\frac { \left(  \left| x+h \right|  \right) ^{3
}- \left(  \left| x \right|  \right) ^{3}}{h}}$
I know this: $|x|^3=|x|^2|x|=x^2|x|$
Now, $\lim _{h\rightarrow 0}{\frac { \left(  \left| x+h \right|  \right) ^{3
}- \left(  \left| x \right|  \right) ^{3}}{h}}$ = $1/2\,{\frac { \left| x \right| x \left( 5\,\overline{x}+x \right) }{
\overline{x}}}$
But i think my answer is too bad, please help ):
Comment: What is $\bar{x}?$ The derivative outside $0$ exists because it's just $x^3$ or $-x^3$, and in zero it also exists because $\lim_{h\to 0} |h^3|/h=0$. By the way, it is more common to write $|x|^3$ or $|x^3|$ then $(|x|)^3$.
Comment: @PeterFranek is module
Answer: We know that $$|x|^3 =
\left\{
 \begin{array}{ll}
  x^3  & \mbox{if } x \geq 0 \\
  (-x)^3 & \mbox{if } x < 0
 \end{array}
\right.$$
so we know that our function is trivially differentiable everywhere except at $0$.
Let's prove, by definition, that our function is also differentiable at $0$.
$$\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}=\lim_{h \to 0}\frac{|h|^3}{h}=\lim_{h \to 0}h|h|=0.$$
If I skipped one too many steps, feel free to ask me to explain in the comments.
Comment: Can i abbreviate this always? $\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}=\lim_{h \to 0}\frac{|h|^3}{h}=\lim_{h \to 0}h|h|=0.$ @Matija Sreckovic
Comment: How do you mean abbreviate? The only step I think I skipped here is (this would go after the first equality sign)$ \lim_{h \to 0} \frac{f(h)-f(0)}{h}=\lim_{h \to 0} \frac{|h|^3-0}{h}$
Comment: @Bvss12 The key is $|h|^3=h^2|h|$.


Reverting blocks and other pseudo-exportables in an install hook

Question: We have a medium-sized Drupal 7 site whose configuration is almost entirely stored in code, in a single Features module.  In order to permit automated testing and a cleaner development workflow, I'd like to make it possible to install a new instance of the site from scratch without cloning the database.  To that end, I've created a simple install profile (based on the standard profile) which enables our themes and configuration module.  This mostly seems to work, but I've found that some feature components are not immediately reverted on the newly-installed site: specifically, blocks exported with fe_block_settings, user permissions, and variables.  All these are applied if I run drush fra -y from the command line after installing the new site, but I would like to do everything programmatically to make writing tests easier.
There is some discussion of the problem with blocks at https://www.drupal.org/node/1901116, but I've tried the fix given there (calling module_install in the hook_install implementation instead of listing a dependency in the .info file), without successs so far.  That page also doesn't address the issues I'm seeing with variables and user permissions.
Is it possible to successfully apply all of these exported feature components from an install hook, or do I need some other mechanism?
Answer: In short: the workaround is to call drupal_flush_all_caches() and drupal_static_reset() before reverting the module containing exported features again from an install task.
In detail: The main symptom observed was that blocks (exported as fe_block_settings components), were not correctly applied on the new site when they depended on a Views block display defined in the same features module.  This remained true even after adding an additional call to features_revert_module() in an installation task.  (There were also problems at one point with variables and permissions, but these were cleared up more easily by the addition of the call to features_revert_module()).
The problem with settings for views blocks is that Views caches all views loaded from the database in a static variable, making any views loaded or enabled for the first time during a single request or drush command invisible to later calls to views_block_info().  One possible (tested) workaround is the following:
views_get_all_views(TRUE);
drupal_flush_all_caches();
features_revert_module('xyz');

Supplying TRUE for the $reset parameter to views_get_all_views() forces the module to discard its static cache and re-compute the list of blocks from scratch.  This allows the revert of block settings to go through correctly.
Because I suspect this will not be the only problem caused by invalid static variable caches, I am trying the more drastic approach of resetting all static variables and clearing all caches before reverting the module:
drupal_static_reset();
drupal_flush_all_caches();
features_revert_module('xyz');

(Resetting all static variables does produce a few extra PHP warnings, which hopefully are spurious.)
The above lines are run as an installation task, and are combined with the approach described in https://www.drupal.org/node/1901116: i.e., remove the module with exported blocks from the dependencies[] list, and enable it manually in hook_install() after enabling themes for the site.  The complete implementation in the profile .install file then looks more like this, where the installation profile is named foo, the features module is named xyz and the site theme quux:
/**
 * Implements hook_install().
 */
function foo_install() {

  // ... other setup code here ...

  // Enable themes
  theme_enable(array('seven', 'quux'));
  variable_set('admin_theme', 'seven');
  variable_set('node_admin_theme', '1');
  variable_set('theme_default', 'quux');

  // Enable module containing features-exported block settings
  module_enable(array('xyz'));
}

/**
 * Implements hook_install_tasks().
 */
function foo_install_tasks(&$install_state) {
  $tasks = array(
    'foo_revert_xyz' => array(
      'display_name' => st('Apply all settings in "xyz" module'),
      'type' => 'normal',
    ),
  );
  return $tasks;
}

function foo_revert_xyz() {
  drupal_flush_all_caches();
  drupal_static_reset();
  features_revert_module('xyz');
}

Tracking this down was a real headache, so I hope the solution is useful to someone else.
Answer: Here is approach that I am using to automate creation of the Drupal site from scratch:

Create new installation profile and add all required modules and features as dependencies to the profile .info file
Run drush site-install {{ profile }} -y to install site
Run drush features-revert-all -y to revert all features
Run drush cache-clear all to clear all caches

I've noticed that if simply install feature as a module, then not all feature components are reverted, that is why step #3 is required.
If you install feature by running module_install then you should run features_revert afterwards http://drupalcontrib.org/api/drupal/contributions%21features%21features.module/function/features_revert/7
Comment: Thanks for your answer, which confirms that others have seen the same problem.  Indeed, if I follow these three steps with `drush`, there are no issues.  However, I'd like to be able to rely on these settings from automated SimpleTests, for which manually running `drush` is not possible.  I will see if it works to call `features_revert` from the setup method of the test case class.
Comment: Does it work for you with `feature-revert()`?
Comment: I haven't had the time to find out if it works in a SimpleTest yet.  I do know that calling `features_revert` or `features_revert_module` from `hook_install` or from an install task doesn't seem to work.  I know that API functions which depend on the database schema are advertised not to work during `hook_install`, so I wonder if the problems are related to that.
Comment: It does work to call `features_revert()` from an installation task, but you have to reset static variables and clear caches first to make some settings (notably blocks) be applied consistently.  Please have a look at my answer.


drupal ahah not working

Question: I'm trying to make a ahah form. the problem is the ahah is ignored. when i check the classes on the submit button, it doesn't have the 'ahah-processed' class. The really interesting thing is that ahah is working perfectly on my site, and even on a nearly identical form I created. this is how i'm creating the ahah submit button:
$form['ri_email_submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#weight' => 1,
        '#submit' => array('ri_email_form_submit'),//none JS version
        '#ahah' => array(
          'event' => 'click',
          'path' => 'ri_email/ajax',
          'wrapper' => 'email-friend-wrap',
          'method' => 'replace',
          'effect' => 'fade',
          'progress' => array(
            'type' => 'bar',
            'message' => t('Loading...')
          )
        )
        );

I checked the menu path, it's correct.
UPDATE: this is the menu callback:
function ri_email_ajax() {
    return drupal_json(array('status' => TRUE, 'data' => '
Your email has been sent.
'));   }

by the way, i discovered that it didn't work when i invoked drupal_get_form() from page.tpl.php, but it does work from node.tpl.php
there is something missing with the javascript that is supposed to handle the ahah
Comment: I second your request Chapabu.
Answer: Can you post the callback function generating the page at 'ri_email/ajax'?
It should look something like this:
<?php
  function awesome_ahah_callback() {
    $thing_to_process = $_POST['thingfromform']
    /* do stuff, including generating some kind of $processed_data variable */

    drupal_json(array(
      'status' => TRUE,
      'data' => $processed_data,
    ));
    exit();
  }
?>

If you aren't generating the thing you want to send back through AHAH with drupal_json and then calling exit() then I don't think it will work.

drupal ahah not working


Drupal Backup and Migrate Error

Question: I'm looking to use Backup and Migrate modules to port over my website. However, even when I go and install a fresh install, update all the modules and activate them accordingly, and finally restore my database, I come out with a white page with the error below. I've done some searching around online here and elsewhere looking for a solution to the following error, and while I've found similar things none have been able to help me resolve this error:
<code>Fatal error: require_once(): Failed opening required '/var/www/html/profiles/acquia/modules/ctools/plugins/export_ui/ctools_export_ui.class.php' (include_path='.:/usr/share/pear:/usr/share/php') in /var/www/html/includes/bootstrap.inc on line 3168
</code>
From what I've read thus far, I am getting that this is basically telling me the something doesn't exist and needs to be added into the PHP. That's where things have begun to get foggy as I continue to push through.
Thanks in advance!
Answer: The issue was while I had imported all of the past module information, I was missing the profile files.

Drupal Backup and Migrate Error


Erro no CSS dos plugins do WordPress

Question: Estou com o seguinte problema, meu tema no WordPress não reconhece o CSS dos plugins instalados nas páginas internas, na home funciona normalmente, mas nas outras páginas, nenhum plugin que eu instalo reconhece o CSS.
Alguém pode em ajudar?
Comment: Tens `` no teu ficheiro `header.php` ?
Comment: Nossa era isso mesmo, estava faltando. Obrigado já resolveu meu problema Zuul. Abs!
Answer: Provávelmente o teu problema será a falta da função wp_head() no teu ficheiro header.php ou index.php cuja mesma é geralmente utilizada com gancho para carregar estilos, scripts e meta tags:
<?php
 ...
    /* Aplicar sempre a função wp_head() imediatamente antes da tag de fecho
     * no teu tema, ou vai-se quebrar muitos plugins, que geralmente usam este gancho
     * para adicionar elementos na , tais como estilos, scripts e meta tags.
     */
    wp_head();
 ?>

Nota:
Em algums casos, o problema reside também na ausência da função wp_footer() no ficheiro footer.php ou index.php cuja mesma pode estar a servir de gancho para referênciar ficheiros de JavaScript:
...
<?php
   /* Aplicar sempre a função wp_footer() imediatamente antes da tag de fecho
    * no teu tema, ou vai-se quebrar muitos plugins, que geralmente usam
    * este gancho para adicionar ficheiros de JavaScript.
    */
    wp_footer();
?>

Erro no CSS dos plugins do WordPress


Transform javascript array with objects with lodash

Question: I'm wondering what the best way would be to transform my javascript array with objects. I have tried making a fancy chain with lodash but I can't figure it out.
I need to format the data this way because of the way the backend works.
// from:
var something = [
  {
    name: 'foo',
    stuff: [
      {
        id: 1
      },
      {
        id: 2
      },
      {
        id: 3
      }
    ]
  },
  {
    name: 'bar',
    stuff: []
  },
  {
    name: 'baz',
    stuff: [
      {
        id: 7
      },
      {
        id: 8
      }
    ]
  }
];

// to:
var transformed = [
  {
    name: 'foo',
    included: {
      included: [1, 2, 3]
    }
  },
  {
    name: 'bar',
    included: {
      included: []
    }
  },
  {
    name: 'baz',
    included: {
      included: [7, 8]
    }
  }
];

Comment: You really need to have added the code you've tried.
Answer: You can do this quite concisely with two map calls (the array built in or lodash's map), one nested to handle the "included" array within each object:
const transformed = something.map(it => {
  return {
    name: it.name,
    included: {
      included: it.stuff.map(thing => thing.id)
    }
  };
});

Answer: No need for lodash, just use the Array.prototype.map function:
// Sorry no fancy ES6 => here :S
var res = something.map(function(item) {
  item.included = {included : item.stuff.map(function(i) {return i.id})}
  delete(item.stuff)
  return item
})

Per @ssube's comment:
var res = something.map(function(item) {
  return {
    included : {included : item.stuff.map(function(i) {return i.id})},
    name: item.name
  }
})

See this fiddle
Comment: This is going to mutate the original objects, which `map` should not do ([see this output](https://jsfiddle.net/esavpwjw/1/)). Rather than modifying and returning `item`, you probably want to return a new object with the right properties.


Discord py how to make administrators command?

Question: How do I create commands that are only available to administrators in discord py?
async def 청소(ctx, amout:int):
    await ctx.channel.purge(limit=amout)
    print('한 유저가 청소를 했습니다.')

Comment: Does this answer your question? [Discord bot check if user is admin](https://stackoverflow.com/questions/51240878/discord-bot-check-if-user-is-admin)
Answer: Use @commands.has_permissions(). commands.errors.MissingPermissions is called when someone doesn't have permissions to run a command. To make an error message pop up, use the on_command_error event like this:
@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.errors.MissingPermissions):
        await ctx.send('You are missing permissions to run this command!')

Anyways, the final code is:
@commands.has_permissions(administrator=True)
@bot.command()
async def 청소(ctx, amount:int):
    await ctx.channel.purge(limit=amount)
    print('한 유저가 청소를 했습니다.')

Answer: This should help:
@client.command()
async def clear(ctx, amount = 100):  #100 will be the default amount purged
    if ctx.author.guild_permissions.administrator:
        await ctx.channel.purge(limit = amount + 1)
        await ctx.send(f'**{amount}** message(s) deleted.')
    else:
        await ctx.send('Sorry, You are not an administrator.')


Else statement not readjusting height and width of img after If statement adjusts the img

Question: When the user scrolls more than 50px down the viewport, my if statement adjusts a bunch of elements in the header. Once the user scrolls back to less than 50px, it readjusts back to normal with an else statement. Currently, everything functions fine besides my img height and width within the else statement. For some reason, the code doesn't bounce back to 60px in height after shifting to 30px in the if/else statement. Please let me know what you think is wrong with the else statement. I assume is has something to do with catching images specifically.
HTML

CSS
// When the user scrolls down 50px from the top of the page, resize the header
    $(document).ready(function () {
      window.onscroll = function() {
        dynamicHeaderOnScroll()
      };

      function dynamicHeaderOnScroll() {
        if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
          document.getElementById("header-wrapper").style.maxWidth = "100%";
          document.getElementById("header").style.paddingTop = "10px";
          document.getElementById("header").style.paddingBottom = "0.4em";
          // Reposition "close hamburger menu" icon
          document.getElementById("closebtn").style.margin = "-43px 0 0 0";
          document.getElementById("header-logo-img-illustration").style.height = "30px";
          document.getElementById("header-logo-img-illustration").style.width = "30px";
        } else {
          document.getElementById("header-wrapper").style.maxWidth = "900px";
          document.getElementById("header").style.paddingTop = "55px";
          document.getElementById("header").style.paddingBottom = "0.25em";
          document.getElementById("header-homepage").style.paddingBottom = "1em";
          // Reposition "close hamburger menu" icon
          document.getElementById("closebtn").style.margin = "0";
          document.getElementById("header-logo-img-illustration").style.height = "60px"; // ISSUE HERE
          document.getElementById("header-logo-img-illustration").style.width = "60px"; // ISSUE HERE
        };
      };

Large image in header on page load:
https://i.stack.imgur.com/QJxYm.png
Img shrunk when scrolled down:
https://i.stack.imgur.com/UGywm.png
Img remains shrunk when scrolled back up and is supposed to go back to default like the first image:
https://i.stack.imgur.com/dDMHo.png
Comment: Welcome to Stack Overflow. When you inspect the element, what do you see the width & height set to? Are there any other Class styles that might be cascading to this element? Please provide a Minimal, Reproducible Example: https://stackoverflow.com/help/minimal-reproducible-example
Answer: Check your devtools console! - If your code crashes before resizing the image, it - well - won't resize the image.

You can see here that the code crashes due to the following error:
Uncaught TypeError: Cannot read properties of null (reading 'style')
    at dynamicHeaderOnScroll (main.js:144)
    at window.onscroll (main.js:130)

...which happens in this line:
document.getElementById("header-homepage").style.paddingBottom = "1em";

So, it complains about not being able to read properties, in particular style, from the value null. From that follows that document.getElementById("header-homepage") must have returned null so that you essentially did null.style.paddingBottom, hence the error. And why is that so? Because there is no element with ID header-homepage on your page.

Side note: It would make a lot more sense to have those styles in CSS depending on a class.
For example, you can use a class is-scrolled on the  tag - and all your JS code would need to do then is document.body.classList.add('is-scrolled') (and remove, of course).
You would then define the rules in your stylesheet such as this:
body.is-scrolled #closebtn {
  margin: -43px 0 0 0;
}

Comment: Wow, thank you! Does this mean that when called in JS, IDs will create errors if not found and classes will not?
Comment: I tried just calling the class name with getElementsByClassName() but this never functions. I haven't figured out why so I just used IDs, not knowing I could run into errors if they aren't used on all pages. Do you have insight into how to use getElementsByClassName()?
Comment: @Neg any selection of a element that does not exist will return `null`, Class or ID. Using Classes with your elements allows you to assign styling without a lot of extra code. Instead of having 3 or 4 lines of code each to add or remove styles, just add or remove a Class name and the browser will render it.


Limit problem help

Question: I have never encounter "proof" questions before in my career, but this question in textbook troubled me and I have totally no clue where to start.
Prove that the limit
$$\lim_{x\rightarrow0} \frac{1-\sqrt{1-x^2}}{x^2} = \frac{1}{2}$$
Answer: $$\begin{align}
\lim_{x\rightarrow0} \frac{1-\sqrt{1-x^2}}{x^2}
=& \lim_{x\rightarrow0} \frac{1-\sqrt{1-x^2}}{x^2}\cdot\frac{1+\sqrt{1-x^2}}{1+\sqrt{1-x^2}}\\
=& \lim_{x\rightarrow0} \frac{1^2-\left(1-x^2\right)}{x^2\left(1+\sqrt{1-x^2}\right)}\\
=& \lim_{x\rightarrow0} \frac{x^2}{x^2\left(1+\sqrt{1-x^2}\right)}\\
=& \lim_{x\rightarrow0} \frac{1}{1+\sqrt{1-x^2}}\\
=& \frac{1}{1+\sqrt{1-0^2}}\\
=& \frac{1}{2}
\end{align}$$
Answer: Hint Multiply by the conjugate of the numerator.
Answer: L'Hôpital's rule to the rescue:
$$\lim_{x\rightarrow0} \frac{1-\sqrt{1-x^2}}{x^2} =\lim_{x\rightarrow0} \frac{d/dx(1-\sqrt{1-x^2})}{d/dx(x^2)} = \frac{1}{2\sqrt{1-x^2}}$$
Let $x:=0$
$$\frac{1}{2\sqrt{1-0^2}}=\frac{1}{2}$$

Limit problem help


Probability that at least one suit is missing in a player's hand

Question: Here's an interesting problem from Henk Tijms's Understanding Probability.

What is the probability that in a player's hand of 13 cards at least
  one suit will be missing?

My approach is applying the inclusion-exclusion rule:
$$
P(\text{one suit missing})=\binom{4}{1}\left(\frac14\right)^{13}-\binom{4}{2}\left(\frac12\right)^{13}+\binom{4}{3}\left(\frac34\right)^{13}\simeq 0.0943
$$
where the first term on the rhs counts the probability that the player's hand consists of 13 cards of the same suit, the second term counts the probability that the hand contains cards from at most two suits, and the third term is the probability that the player's hand consists of at most three suits.
However, the book gives the result $0.051$, so something is wrong in my solution.
Comment: Your calculation gives the probability if the cards are dealt *with replacement*, which is not how cards are normally dealt.
Answer: Let $A_i = \{ \text { Suit } i \text{ is missing  } \} $. By inclusion-exclusion we have: $$P (A_1 \cup A_2 \cup A_3 \cup A_4) =  \frac {\binom41 \cdot \binom {39}{13}}{\binom {52}{13}} - \frac {\binom42 \cdot \binom {26}{13}}{\binom{52}{13}} + \frac {\binom43 \cdot 1}{\binom {52}{13}} = 0.051 $$
Comment: I see, so the problem is that I cannot count the number of hands missing $i$ suits with $\left(\frac{4-i}{4}\right)^{13}$? What is wrong in this way of thinking?
Comment: Note that if one suit is missing. Then, we cannot deal with the 13 cards of that suit. We then have to choose 13 cards from the 39 cards remaining. There are then $\binom {39}{13} $ ways to select.
Comment: Note if two suits are missing, we follow the same reasoning.
Comment: Now I understand. So the formula $\left(\frac{4-i}{4}\right)^{13}$ does not count the fact that as the drawing of cards proceeds, the probability of getting a card of a given suit differs from $1/4$. This is why the geometric distribution is used instead.


Qual o termo correto, palavra chave ou palavra reservada?

Question: Na programação temos certas "palavras especiais" que fazem coisas específicas.
Essas palavras são popularmente chamadas de palavras-chave ou palavras reservadas.
Qual o termo correto para essas palavras?
Exemplos: if, double, while, this, interface, entre outras.
Answer: Ambos estão corretos porque elas querem dizer coisas diferentes para a mesma coisa, ou seja, palavra reservada significa que aquela palavra não pode ser usada para identificadores no seu código, a linguagem proíbe isto porque ela possivelmente tem uso para elas. Já a palavra-chave é aquela que indica que faz algo especial no código. As palavras costumam ser as mesmas, mas tem exceções.
Podem existir palavras reservadas que não são usadas efetivamente pela linguagem e por isso não podem ser consideradas palavra-chave (ex.: goto do Java). Existem palavras-chave que são contextuais, por isso em certos contextos elas não são reservadas (ex.: where ou value do C#).
Existem linguagens que permitem que todas as palavras-chave possam ser usadas livremente, portanto não possuem palavras reservadas, já que o udo em identificador consegue ser feito de forma não ambígua.
Coloquei no GitHub para referência futura.


What family of functions could that be?

Question: I would like to find an analytical expression for a family of function that would look like the curves in the plot.
Essentially ranging from the identity function up to sqrt kind of curve.
What matters is that it must be concave and display some kind of saturation and also being able to parametrize the curvature.
I already had a look at functions like $f(x) = aX^b$ but for high values, you can not get  the identity, also functions like $f(x) = a(a-b)e^{(-cX)}$, but there is no parameter to impact the curvature.

EDIT:
Related question initially asked on stackoverflow:
https://stackoverflow.com/questions/65580685/fitting-power-exponential-curve-that-goes-through-a-specific-point
Comment: Can you please edit your post to indicate that you cross-posted it at [StackOverflow](https://stackoverflow.com/q/65580685/452096)?
Comment: What is the equivalent of that function in a 3 dimensional space? So with two variables x1 and x2
Comment: Three dimensions looks like it would be a good new question. (Probably better posted at Math.SE.) Here, the boundary conditions are $(0,0)$ and $(100,3)$; in three dimensions, the boundary conditions would need to be specified anew.
Answer: Take a look at scaled versions of the cumulative distribution function of the beta distribution. Specifically, scale your $x$ by $\frac{1}{100}$, feed this into a beta CDF (which takes values between $0$ and $1$ and outputs values between $0$ and $1$), and multiply the result by $3$. This function will take a value of $0$ for $x=0$ and of $3$ for $x=100$.
The beta has two positive parameters. For concavity, you want to constrain the first parameter to be $\leq 1$ and the second to be $\geq 1$. Setting both equal to $1$ will give you the diagonal line (the black line below). Parameterizing both parameters as $\frac{1}{t}$ and $t$ for $t\geq 1$ will give you a symmetric curve, and if the parameters diverge from this relationship, you get asymmetric ones.

R code:
<code>xx <- seq(0,100,by=.1)
plot(xx,3*pbeta(xx/100,1,1),type="l",xlab="",ylab="",las=1)
lines(xx,3*pbeta(xx/100,0.5,1),col=2)
lines(xx,3*pbeta(xx/100,1,2),col=3)
lines(xx,3*pbeta(xx/100,0.5,2),col=4)
lines(xx,3*pbeta(xx/100,0.25,4),col=5)
legend("bottomright",lwd=1,col=1:5,
    legend=c("(1,1)","(0.5,1)","(1,2)","(0.5,2)","(0.25,4)"))
</code>

What family of functions could that be?


Overwrite custom node view fail

Question: I've created a function that have custom content type and all went well, but the problem is now I'm unable to overwrite the node view page:
Here are my functions:
function xxx_theme($existing, $type, $theme, $path) {
  return array(
    'xxx_print' => array(
      //'variables' => array('node' => NULL),
      'function' => 'theme_xxx_print',
    ),
  );
}

function theme_xxx_print($node) {
  return '
test
';
}

Comment: Did you cleared the cache
Comment: yes, I did nothing happened, the current node view is presented by panel
Answer: If you are using panels node view template for your node view then your template file and node theme declarations would be overruled by panels.
If you want to verify, disable the panel node view. Make sure to flush your caches then visit a node you have and your theme override/addition will be there.
Comment: upon checking, my node was not using panels, I still can not overwrite the theme using my current functions
Comment: Can you provide more details on the content type, related template files, related template.php functions and related panels config(if there is). Have you tried also just creating a plain drupal site and tested your code? I believe your code works so it may be something overriding it in your project.

Overwrite custom node view fail


How to automatically setup SSH key pass on first ansible command run for each new server?

Question: Today I started learning ansible and first thing I came across while trying to run the command ping on remote server was
192.168.1.100 | UNREACHABLE! => {
    "changed": false,
    "msg": "(u'192.168.1.100', <paramiko.rsakey.RSAKey object at 0x103c8d250>, <paramiko.rsakey.RSAKey object at 0x103c62f50>)",
    "unreachable": true
}

so I manually setup the SSH key, I think I faced this as no writeup or Tutorial by any devops explains the step why they don't need it or if they have manually set it up before the writing a tutorial or a video.
So I think it would be great if we can automate this step too..
Answer: If ssh keys haven't been set up you can always prompt for an ssh password
-k, --ask-pass      ask for connection password

Comment: Well, that isn't my question
Answer: Not sure what types of servers these are, but nearly all Ansible tutorials cover the fact that Ansible uses SSH and you need SSH access to use it.
Depending on how you are provisioning the server in the first place you may be able to inject an ssh key on first boot, but if you are starting with password-only login you can use the --ask-pass flag when running Playbooks. You could then have your first play use the authorized_key module to set up your key on the server.
Answer: I use these commands for setting up keys on CentOS 6.8 under the root account:
cat ~/.ssh/id_rsa.pub | ssh ${user}@${1} -o StrictHostKeyChecking=no 'mkdir .ssh > /dev/null 2>&1; restorecon -R /root/; cat >> .ssh/authorized_keys'
ansible $1 -u $user -i etc/ansible/${hosts} -m raw -a "yum -y install python-simplejson"
ansible $1 -u $user -i etc/ansible/${hosts} -m yum -a "name=libselinux-python state=latest"

${1} is the first parameter passed to the script and should be the machine name.
I set ${user} elsewhere, but you could make it a parameter also.
${hosts} is my hosts file, and it has a default, but can be overridden with a parameter.
The restorecon command is to appease selinux. I just hardcoded it to run against the /root/ directory, and I can't remember exactly why. If you run this to setup a non-root user, I think that command is nonsense.
I think those installs, python-simplejson and libselinux-python are needed.
This will spam the authorized_keys files with duplicate entries if you run it repeatedly. There are probably better ways, but this is my quick and dirty run once script.
I made some slight variations in the script for CentOS 7 and Ubuntu.


How to alter the CartBlock build result?

Question: I'd like to alter the cart block links (replace Cart link by a checkout link).
CartBlock.php is a BlockBase but neither hook_block_build_alter nor hook_block_view_alter is called :-(
(same result with a specific block hook like hook_block_view_BASE_BLOCK_ID_alter or hook_block_build_BASE_BLOCK_ID_alter with id "commerce_cart" )
https://api.drupal.org/api/drupal/core!modules!block!block.api.php/funct...
https://api.drupal.org/api/drupal/core%21modules%21block%21block.api.php...
Do I have to use a views hook ? which one ? and how to access to the block render array to change the links at the bottom of the cart block ?
Thanks
Answer: I'm not sure that it is the best way to do it but I successed using hook
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook_preprocess_HOOK/8.2.x
<code>YOUR_MODULE_preprocess_block(&$variables)
</code>
==> to identify the block :
<code>$variables["elements"]["#configuration"]["id"] == "commerce_cart"
</code>
==> to change the links with customs :
<code>$variables['content']['#links']=$custom_links;
</code>


Questions that started new mathematics

Question: Most mathematical theories (Exceptions are unknown to me) were created by answering one or more open ended non-trivial questions. For example, The Brachiostome problem lead to the calculus of variations, Three pendulum problem leaded to chaos theory (somewhat physical) etc.
What are the questions that spawned most of the mathematics of 16~21st century mathematics ?
Comment: I am mainly asking this question to 1. Promote creativity over rote memorization 2. To promote quasi-original thinking 3. To find a general pattern/analogies/invariance (or other; whatsover) between these questions.
Comment: Complex numbers - simply wanting to have two independent real variables as elements of a field such that $pr =q$ has  a unique solution for any given $p$ and $q$. Leading to the algebra of algebras.
Answer: The Seven Bridges of Königsberg laid the foundations of graph theory, despite Euler originally perceiving the problem as nothing more than a puzzle.
A general solution to the degree five (quintic) equation led to Galois Theory and the Abel–Ruffini theorem.
The problem of area under a curve led to the creation of calculus. Isaac Newton and Gotfried Leibniz are usually credited with this feat, but early Greek thinkers such as Archimedes also though about area in a similar sense.
Answer: One of the big questions in algebra (around 1800) was whether a general quintic polynomial had a solution in terms of radicals. This led Galois to investigate and create what would later be named after him (Galois Theory), and finally Abel's impossibility theorem.
Comment: This is also generally acknowledged as being the foundation of group theory.
Answer:
The attempts to prove Euclid's fifth postulate led to the idea that alternatives to the fifth postulate could be consistent. Hence, the development of the non-Euclidean geometries.
Georg Cantor investigated the idea that there are different sizes of infinity. Hence, the development of set theory.
A consequence of Cantor's work was the attempt by Russell and Whitehead to axiomatize arithmetic (and thus all of mathematics). But Godel's Incompleteness Theorem crushed those attempts.
Answer: Newton developed calculus, the generalized binomial theorem, and general power series primarily to solve problems in mechanics, especially regarding orbits with an inverse-square gravity. It has been said that while others asked what keeps the moon up, Newton asked what keeps it down, that is, why it doesn't fly off at a tangent to its orbit.
Georg Cantor  developed set theory after studying "exceptional sets"  in the question of characterizing the set of points  at which a function's Fourier series may fail to converge to the function.
Paul Cohen invented Forcing to prove the consistency (in ZFC) of the negation of the Continuum Hypothesis, and the consistency (in ZF) of the negation of the Axion of Choice. His method led to an explosion of new  results. As Kunen wrote, "Infinitary Combinatorics is the branch of mathematics that was called Set Theory before there were independence proofs."

Questions that started new mathematics


Is it possible to create a link or button that will launch the link in incognito / private mode?

Question: I suspect this is not possible without an extension, but thought it was worth asking.
The scenario: You're providing support/services to users who use a device with a  browsing history that may be covertly monitored by a family member. This can put the user in danger.
Is there a way to provide an option to launch links to those services (clearly labelled and explained) into an incognito window so they won't appear in that user's history?

Obviously they can manually do it themselves, but that requires knowledge and forethought
They can clear their cache, but that can raise unwanted attention too.

Fingers crossed.
Answer: It is not possible on a webpage but it is with an extension as there are many privacy concerns if a webpage can open tabs in incognito / private mode
Comment: Thanks @Jeffrey. I suspected that would be the case.


Input and label in center of screen

Question: I creating signup form. I ran into a problem. how to make input wider without fixed width like width: 420px. And input and label place in the center. I want something like this: image. But now I have this: image.
My html code:

Create an account

     <form className="form">

            Your Name
            <input
            name="username"
            type="text"
            className="input"
            value={input.username}
            onChange={onInputChange}
            onBlur={validateInput}
           />

            Your Email
            <input
              name="email"
              type="email"
              className="input"
              value={input.email}
              onChange={onInputChange}
              onBlur={validateInput}
            />

            Password
            <input
              name="password"
              type="password"
              className="input"
              value={input.password}
              onChange={onInputChange}
              onBlur={validateInput}
            />

            Repeat your password
            <input
              name="confirmPassword"
              type="password"
              className="input"
              value={input.confirmPassword}
              onChange={onInputChange}
              onBlur={validateInput}
            />

            <input className="form-check-input" type="checkbox" value="" />

                I agree all statements in
                Terms of service

            <button className="btn">Create account</button>

            Have already an account
            Login here

    </form>

My css code:
.container {
padding: 16px;
width: 80%;
margin: 5% auto 0 auto;
}

.title {
text-align: center;
font-size: 2.5rem;
color: #0d6efd;
}

.input-label {
color: #6c757d;
}

.form-outline {
margin-bottom: 1.5rem;
flex: 1 1 auto;
}

.input {
padding: 0.45rem;
margin: 0.3rem 0 1.3rem 0;
font-size: 1.25rem;
border-radius: 0.5rem;
display: block;
color: #212529;
line-height: 1.5;
border: 1px solid #ced4da;
transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.input:focus {
color: #212529;
border-color: #86b7fe;
outline: 0;
box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}

.form-check {
margin-bottom: 3rem;
justify-content: center;
display: flex;
}

.form-check-label {
padding-left: 0.5rem;
font-size: 1.1rem;
}

.form-check-input {
border-radius: 0.25rem;
border: 1px solid #a9a9a9;
width: 1.3em;
height: 1.3em;
}

.form-check-input:focus {
border-color: #86b7fe;
outline: 0;
box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}

.terms {
color: #0d6efd;
text-decoration: underline;
padding-left: 0.2rem;
}

.terms:hover {
color: #0a58ca;
}

.button {
margin-bottom: 1.5rem;
justify-content: center;
display: flex;
}

.btn[disabled] {
opacity: .65;
cursor: not-allowed;
}

.btn {
cursor: pointer;
color: #fff;
background-color: #0d6efd;
border: none;
text-decoration: none;
padding: 0.5rem 1rem;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
border-radius: 0.375rem;
}

.have-account {
text-align: center;
font-size: 1.1rem;
}

.login-here {
color: #0d6efd;
font-weight: bold;
text-decoration: underline;
padding-left: 0.2rem;
}

.login-here:hover {
color: #0a58ca;
}

Edited:
Also I tried this:
.input-label {
color: #6c757d;
}

.form-outline {
margin-bottom: 1.5rem;
flex: 1 1 auto;
justify-content: center;
align-items: center;
display: flex;
flex-direction: column;
}

but my label hit in the middle of the screen. image For label float: left not working. So I'm need to place label on the left side, and input make wider.
Answer: Just remove align-items
.form-outline {
margin-bottom: 1.5rem;
flex: 1 1 auto;
justify-content: center;
display: flex;
flex-direction: column;
}

Note : Set a break point for media as well as wider screens.
Edits: Please use this corrected css ,

.form {
  max-width: 500px;
  margin: 0 auto;
}

.container {
  padding: 16px;
  width: 80%;
  margin: 5% auto 0 auto;
  }

  .title {
  text-align: center;
  font-size: 2.5rem;
  color: #0d6efd;
  }

  .input-label {
  color: #6c757d;
  }

  .form-outline {
  margin-bottom: 1.5rem;
  flex: 1 1 auto;
  }

  .input {
  padding: 0.45rem;
  margin: 0.3rem 0 1.3rem 0;
  font-size: 1.25rem;
  border-radius: 0.5rem;
  display: block;
  color: #212529;
  line-height: 1.5;
  border: 1px solid #ced4da;
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
  width:100%;
  }

  .input:focus {
  color: #212529;
  border-color: #86b7fe;
  outline: 0;
  box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
  }

  .form-check {
  margin-bottom: 3rem;
  justify-content: center;
  display: flex;
  }

  .form-check-label {
  padding-left: 0.5rem;
  font-size: 1.1rem;
  }

  .form-check-input {
  border-radius: 0.25rem;
  border: 1px solid #a9a9a9;
  width: 1.3em;
  height: 1.3em;
  }

  .form-check-input:focus {
  border-color: #86b7fe;
  outline: 0;
  box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
  }

  .terms {
  color: #0d6efd;
  text-decoration: underline;
  padding-left: 0.2rem;
  }

  .terms:hover {
  color: #0a58ca;
  }

  .button {
  margin-bottom: 1.5rem;
  justify-content: center;
  display: flex;
  }

  .btn[disabled] {
  opacity: .65;
  cursor: not-allowed;
  }

  .btn {
  cursor: pointer;
  color: #fff;
  background-color: #0d6efd;
  border: none;
  text-decoration: none;
  padding: 0.5rem 1rem;
  font-size: 1rem;
  font-weight: 400;
  line-height: 1.5;
  border-radius: 0.375rem;
  }

  .have-account {
  text-align: center;
  font-size: 1.1rem;
  }

  .login-here {
  color: #0d6efd;
  font-weight: bold;
  text-decoration: underline;
  padding-left: 0.2rem;
  }

  .login-here:hover {
  color: #0a58ca;
  }

Comment: If i set break point like this: `@media (min-width: 1281px) {  .input { width:30%; } }` input displayed on left side like on second image of my post. Also if I remove `align-items` input displayed full width of container, it's 80%
Comment: I have Corrected CSS in my answer, that should work for your expectation.

Input and label in center of screen


Is it legal to use two rackets in Table Tennis?

Question: I've looked on Google, the official rules for Table Tennis, and on this website
but found nothing telling me whether it's illegal to use two rackets to play
table tennis. I understand there are rules which states there must be a "free hand" during the serve, but during ongoing play it is legal to use two hands to use a single racket or switch hands with the racket during an ongoing point.
Lastly in the rules they always say racket rather than racket(s), but it would seem somewhat unnecessary if they had said racket(s) seeing as no one actually uses more than one racket and it's too niche.
Answer: Rules of TT:

2.5.2 The ball is in play  from the last moment at which it is  stationary on the palm of the free hand before being intentionally
  projected in service until the rally is decided as a let or a point.
  2.5.5 The racket hand is the hand carrying the racket.
  2.5.6 The free hand is the hand not carrying the racket; the free arm is the arm of the free hand.
  2.6.1 Service shall start with the ball resting freely on the open palm of the server's stationary free hand.

The rules clearly establish a free hand and a racket hand.
Further

9.3 For the same reason he cannot make a good return by throwing his  racket at the ball, because the racket does not "strike" the ball if
  it  is not held in the racket hand at the moment of impact. However, a
  player may transfer his racket from one hand to the other during play
  and strike the ball with the racket held alternately in either hand,
  because the hand holding the racket is automatically the "racket
  hand".

Therefore it is assumed that it is illegal to use two racquets as you are allowed to switch between hands.


Where are the Jira Application properties stored

Question: I am installing Jira using Ansible to avoid the web browser installation process. I am trying to automate the below part of the wizard:

So I wonder were are these properties stored:

Are those stored on Database tables (which tables are those) ?
Are those values stored on key=value properties files under jira_install_directory?
Is this stored in other place?

I am trying to automate those properties and configuration using Ansible and avoid the web browser process.
Answer: The values are stored in the database table propertystring
The ID's may change. You can find their ID's from the propertyentry table
In my case (JIRA 7.12.3)
  ID
======
10206 Application Title
10211 Base URL
10212 Mode


storing files on mongodb

Question: I am developing an app where user will upload multiple images along with some other data like name address etc.
I am using MEAN stack for development, So I have some questions regarding this:
How should I store image data in my db, like what information should I save in my db ?
I have read that we can use GridFS by mongodb. But my images would be of max 5MB in size. So what should I use simple fs by node or gridfs by mongodb ?
What is the need of storing file data on amazon s3, can't I just save base64 string into my database ?
Answer: This is not a problem at all if the database is dedicated to storing the images. If you have other data in it, you might have to consider memory usage of loading the images and its impact on other operations

storing files on mongodb


How to lock file in Xcode8?

Question:
See, I want to lock my code, How do this?
Comment: try this http://stackoverflow.com/questions/5843033/lock-file-in-xcode-4
Answer: It's same with Xcode 7 or early.
* Select your file and find the Full Path in Xcode, then open it in Finder.

Get Info and checked the Locked.

Last, check the file in Xcode.
Comment: Thank you, pictures could guide me through the operation, my English is so bad!
Answer: To lock file is possible with the Finder, it is much more troublesome when you need to lock multiple files. The long way now involves right clicking the file in the Project Navigator and selecting Show In Finder. Using Get Info (Cmd-I) will allow you to select Locked. When you do this, the lock symbol will appear in the top-right corner of the source editor, which you can click to Unlock the file.

How to lock file in Xcode8?


Erro Deploy Heroku - Java

Question: Estou iniciando um projeto de uma aplicação em Java, e estou realizando a configuração dos ambientes antes de começar a implementação. Porém, quando fui criar o app no Heroku e realizar o Deploy através do repositório do projeto no meu GIT, esse erro aparece:

Pelo que eu entendi, não encontrou meu arquivo pom.xml no meu projeto, mas ele foi criado:

Estou procurando algumas soluções, mas não encontrei nada por enquanto.
Comment: Poderia colocar, por favor, a estrutura toda de diretório do seu projeto no servidor? De qualquer maneira vou enviar uma solução para alguns casos que já vi.
Answer: Em alguns casos, o problema é que o diretório git é um diretório externo e a pasta do projeto (com código propriamente e que contém o pom.xml) está dentro desse mesmo diretório git "raiz".
Exemplo:
- diretorioGit
  |___diretorioDoProjeto
           |____codigo...
           |____pom.xml

Isso é um dos tipos de problema que já vi acontecer. Mas pra confirmar se é o seu caso, precisamos ver a estrutura de diretório do seu projeto, conforme solicitei no comentário na pergunta.
A solução para esse caso poderia ser mover o diretório .git e o arquivo .gitignore para o diretorio diretorioDoProjeto.

Erro Deploy Heroku - Java


jqgrid search popup allows all filters to be removed!

Question: I'm trying out very simple search popup on the JqGrid. Please see the code below. There are few issues:

The popup comes up with AND/OR and [+] controls at the very top. See screenshot below: (from FF 4)
You can click on [-] button to remove the very first (and only) filter row. It shouldn't be allowed. First filter row should never be allowed to be removed.
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<title>JQGRID Test</title>
<link rel="stylesheet" type="text/css" media="screen" href="http://trirand.com/blog/jqgrid/themes/redmond/jquery-ui-1.8.1.custom.css"/>
<link rel="stylesheet" type="text/css" media="screen" href="http://trirand.com/blog/jqgrid/themes/ui.jqgrid.css"/>

Answer: I suggest to overwrite the internal reDraw method used by filtering (see my another answer for more description). To do this you should include in the searchOptions which you use the beforeShowSearch  event handler with the following implementation:
beforeShowSearch: function($form) {
    var searchDialog = $form[0],
        oldrReDraw = searchDialog.reDraw, // save the original reDraw method
        doWhatWeNeed = function() {
            $('input.delete-rule:first',searchDialog).unbind('click');

            // set fucus in the last input field
            setTimeout(function() {
               // set fucus in the last input field
               $('input[type="text"]:last',searchDialog).focus();
            }, 50);
        }
    searchDialog.reDraw = function() {
        oldrReDraw.call(searchDialog);    // call the original reDraw method
        doWhatWeNeed();
    }
    doWhatWeNeed();
}

You can see the corresponding demo here.


Receber um inteiro e uma string e armazenar em 2 vetores em C?

Question: Estou aprendendo C e estou travado em um exercício que pede para armazenar os dados da seguinte forma.
Nota do Aluno e Nome do Aluno na mesma linha, e depois com um índice escolhido determinar a situação do aluno, a parte de manipular o índice e verificar a nota dele eu sei fazer, mas estou com problemas em como seria fazer esse tipo de problema usando vetores em C que receber um inteiro e uma string que passa para  2 vetores.
Exemplo dos dados:
8.0 Ed Rex
9.0 Marcos Vice
1.0 Alan Pequenuxo

Esse seria o meu codigo
include stdio.h
include stdlib.h
include string.h

int main()
{
    int n,i;
    int nota[99];
    char aluno[20][30];
    scanf("%d",&n);

    for (i=0 ;i < n; i++){
        scanf("%d %s",&nota[i], &aluno[i]);
    }

    return 0;
}

Comment: E que problema está tendo?
Comment: aparece esse erro quando tento compilar.

nomes.c: In function 'main':
nomes.c:12:10: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'char (*)[30]' [-Wformat=]
    scanf("%d %s",&nota[i], &aluno[i]);
          ^
Comment: Troque:    &aluno[i] por aluno[i] no scanf (tire o &).
Comment: valeu amigo, nem acredito que era só por causa disso.
mas se eu quisesse que ele guardasse o nome com sobrenome, o que eu poderia fazer?
Answer: Acho que o modo mais correto de resolver o seu problema é agregar o que é comum em uma estrutura. Assim, a nota e o nome pertencem à estrutura Aluno. Portanto, o seu programa ficaria do seguinte modo:
#include <stdio.h>

typedef struct Aluno
{
    float nota;
    char nome[100];
} Aluno;

int main()
{
    int n = 0, i = 0;
    Aluno aluno[30];
    scanf("%d",&n);

    for (i = 0; i < n; i++){
        scanf("%f %100[0-9a-zA-Z ]",&aluno[i].nota, aluno[i].nome);
    }

    for (i = 0; i < n; i++) {
        printf("%f %s\n", aluno[i].nota, aluno[i].nome);
    }

    return 0;
}

Note no scanf uma diretiva estranha: %100[0-9a-zA-Z ]. Ela se parece com um regex e permite que vc formate exatamente o que quer como entrada para o campo aluno[i].nome. Em outra palavras, vai aceitar uma quantidade máxima de 100 caracteres, onde eles podem ser de 0-9, a-z, A-Z e/ou espaço em branco.
Se quiser usar caracteres acentuados, pode substituí-la também por: %100[^\n]. Ou seja, lê qualquer coisa até o final da linha
Comment: A única coisa que desgostei foi usar uma `struct` para o cenário em que o AP está aprendendo ainda o básico. De toda sorte +1
Comment: estou aprendendo mesmo, mas essa parte do struct pode me ajudar para problemas futuros que necessitem desse raciocínio.obrigado pela ajuda tambem


Euler Circuits, a proof not utilising induction.

Question: I am currently doing a course in graph theory at University, and I have an exam coming up in a week or so. While studying I did a past exam for the course i am doing, in this past exam our lecturer asked  the question
"Is it true that if every vertex in a multigraph G has even degree then G admits an Euler tour? If it is true provide a proof, if it is false provide a counter example."
Looking back at my notes, this is true, and I know how to prove it by induction. It seems like induction is the traditional way to prove this proposition. However in in the past exam our lecturer provided only 5 or 6 lines to answer the question. Is there an easier way of proving this proposition, or is this proposition even true?
Answer: The graph may be disconnected with non-trivial components and hence the statement is false.
Comment: Oh yeag, I didn't notice that. Thank you


Zip all files returned from "grep-ril" command

Question: I'm using grep -ril to be able to see all files that contain a certain string:
[user@machine]$ grep -ril "test string"
file1.log
file2.log
file3.log
file4.log
...

I then would like to zip all of the files that have been returned by that command. Is this possible?
I've tried things such as grep -ril myPattern | zip files.zip and grep -ril myPattern | zip > files.zip but nothing has worked so far.
Is there a workaround to this?
Thank you.
Answer: Use the zip command line switch  -@ to have zip take the list of input files from standard input instead of from the command line. For example,
grep -ril "test string" | zip name-of-new-zip-file -@

Answer: You can try the command on this way:
zip zipfile.zip `grep -ril "test string"`

Comment: This suffers from the usual "any file with a space or starting with a dash" issue that makes it non generic, non stable and a generally bad habit to have as it can cause security issues in some cases.
Comment: @Ginnungagap, IMHO same for the answer of Bob
Comment: It probably suffers from newlines in filenames but it doesn't suffer from a file called `-o` (for example) being interpreted as a command line switch by `zip` nor does it suffer from `filename with space` (again, for example) being interpreted as 3 separate files. And as a general rule, it's better to pipe than to expand on the command line since it's unlikely to change the behavior of the invoked program.
Comment: Actually, looking for an document illustrating this, I stumbled upon [this](https://insinuator.net/2014/12/revisiting-an-old-friend-shell-globbing/) which explains the issue and actually lists `zip` as a security issue with this kind of invocation.


Como editar um campo booleano em uma lista no Asp.Net MVC

Question: Galera, estou desenvolvendo uma aplicação que gerencia Cursos, e estou com o seguinte problema. Na minha tela do Administrador eu preciso dos campos Nome do Curso, Nome do Aluno e o campo Aprovado que é um campo booleano. Essa tela é onde o Administrador diz qual aluno está aprovado no curso em que se inscreveu. Só que na minha View só aparece os campos Nome do Curso e o campo Aprovado e não aparece o Nome do Aluno, conforme imagem abaixo.

O outro problema é que esse meu campo Aprovado quando eu marco o checkbox ele não tá salvando como true no Banco de Dados, está sempre ficando false.
Action Aprovacao do controller Curso
public ActionResult Aprovacao()
    {
        return View(db.Cursos.ToList());
    }

Minha View Aprovacao
@model IEnumerable<MeuProjeto.Models.Curso>

@{
    Layout = "/Views/Shared/_Layout.cshtml";
}

Aprovação

            Curso

            Aluno

            Aprovado?

    @foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.Nome_Curso)

                @Html.DisplayFor(modelItem => item.AlunoCursos)

                @*@Html.DisplayFor(modelItem => item.Aprovado)*@
                <input type="checkbox" id="Aprovado" name="Aprovado" value="Aprovado"/>

    }

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")

}

Answer: Pelo que pude entender, não há algo que dispare uma Action para o Controller, então sua View precisa de algumas modificações:
1. Identificar a CheckBox corretamente
@foreach (var item in Model)
{

            @Html.DisplayFor(modelItem => item.Nome_Curso)

            @Html.DisplayFor(modelItem => item.AlunoCursos)

            @Html.CheckBox("Aprovado_" + item.Nome_Curso, new { @class = "Aprovado", id = item.Id })

}

2. Adicionar Script que dispare a Action
Isto pode ser feito por Ajax:
$(".Aprovado").click(function() {
    $.ajax({
        url: '@Url.Action("Aprovacao", "Curso")',
        type: "POST",
        data: { id = $(this).attr('id') },
        success: function (data) {
            alert("Aprovação feita com sucesso!");
        }
   });
});

3. Crie uma Action Aprovar em AlunoCursosController
[HttpPost]
public ActionResult Aprovar(int id)
{
    var alunoCurso = db.AlunoCursos.FirstOrDefault(ac => ac.AlunoCursoId == id);
    alunoCurso.Aprovado = !alunoCurso.Aprovado;
    db.Entry(alunoCurso).State = EntityState.Modified;
    db.SaveChanges();
}

Sobre a coluna Aluno
Na hora de selecionar AlunoCursos, tente o seguinte:
public ActionResult Aprovacao()
{
    return View(db.AlunoCursos.Include(ac => ac.Aluno).ToList());
}

Para exibir:
@Html.DisplayFor(modelItem => item.AlunoCursos.Aluno.Nome)

Comment: Ei @Cigano esse código aqui `var alunoCursos = contexto.AlunoCursos.Include(ac => ac.Aluno).ToList();` vai no meu `controller` né?
Comment: @Novato Isso. Só enviar pra *View* `alunoCursos`.
Comment: Meu campo **Aprovado** ainda não está salvando @Cigano, quando eu atualizo a página o `checkbox` volta vazio, e no banco também não está salvando como `true`.
Comment: @Novato Já colocou um breakpoint na *Action* que o Ajax chama?
Comment: Não, vou fazer isso agora @Cigano
Comment: Acho que o problema é aqui `[HttpPost]
        public ActionResult Aprovar(int id)
        {
            var alunoCursos = db.AlunoCursos.Include(ac => ac.Aluno).ToList();

            return View(alunoCursos);
        }`. Pode me dar uma luz nessa parte aqui **// Selecione aqui o AlunoCurso e mude o Aprovado.**. Não fiz...
Comment: A seleção de `alunoCursos` não vai em `Aprovar`. Veja minha edição. Dentro de `Aprovar` vai a seleção de apenas um `alunoCurso` e lá você edita o booleano.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/25093/discussion-between-novato-and-cigano-morrison-mendez).
Comment: Me dá só um exemplo @Cigano de como eu faria essa seleção de uma `alunoCurso` dentro do `Aprovar` e editar meu campo `booleano`, porque aqui não consegui.
Comment: @Novato Editei a resposta.
Comment: aqui nesse trecho `alunoCurso.Aprovado = !alunoCurso.Aprovado;` deu erro de **NullReferenceException**.
Comment: @Novato Significa que `alunoCurso` é `null`, e que não achou o registro pelo `id` passado. Você está realizando *debug* do código que está escrevendo?
Comment: Sim @Cigano, quando debugo aqui nesse trecho `var alunoCurso = db.AlunoCursos.FirstOrDefault(ac => ac.AlunoCursoId == id);` ele apresenta um `id = 5`


Change of default directory path for rest_mozprofile from geckodriver

Question: Geckodriver creates rust_mozprofile directory in '/tmp' directory.
There is a way to modify the path from '/tmp' to '/home' or some other location.
Could you please point me in right direction on how to do that.
Currently I am using

Selenium - 3.3.0
Firefox - 52.2.0
Geckodriver - 13
Comment: I found this link - https://github.com/mozilla/geckodriver#firefox-capabilities. But still can't able to fix it.
Comment: hey did you figure it out yet? I have the same question
Comment: I didn't get any solution but the problem which I had was memory issues. So I wrote a cron job to clean up whatever it is older.
Answer: A solution is to use driver.quit() instead of driver.close()
As explained here
Another solution is to add a custom profile
fp = webdriver.FirefoxProfile('specify location to profile .default')
driver = webdriver.Firefox(firefox_profile=fp)


Terms in tree view - wrong order?

Question: I wanted to list the terms that a node has in a tree view. I've gotten that far that the list, sorted by the parent, is done, but the terms is in wrong order. Some terms becomes childterms to the wrong parent.
How do I fix that?
function my_module_cmp($a, $b) {

$a = (array) $a;

$b = (array) $b;

return strcmp($a['name'], $b['name']);

}
// A block with the current nodes linked categories in a tree view

function myfunction_category_block_contents($delta) {

// get nid from URL

$nid = arg(1);

$node = node_load($nid);

// get the terms using that nid

$terms = taxonomy_node_get_terms($node);

usort($terms, "hr_torget_cmp");

// create the head

$html = '
Kategorier
';

$html .= '
';

$i = 0;

foreach ($terms as $term){

    // the tid

    $tid = $term->tid;

    // the name

    $name = $term->name;

// DEBUG    $html .= $tid.'
';

    // get terms

    $parents = taxonomy_get_tree(10,$tid,NULL);

    // if the term is a parent
    if ($parents) {
        $html .= '
'.$name.'
';
    }
    // if it isnt
    else {
        $html .= '
';
        $html .= '
'.$name.'
';
        $html .= '
';
    }

$i++;

}

$html .= '
';

$html .= '';

return $html;

}

Comment: It's an old question but, maybe you still care: are the parents totally alien (out-of-branch) or is the tree simply reversed (compared to what you expect)?
Comment: I still have the issue. They are the correct ones, they just show up in an alphabetical order, and I want them to me listed like
Parent1
 -child1
 -child2
Parent2
 -child3
 -child4
Comment: Does it help when you remove the usort statement?
Comment: Then all of the childre gets listes first, and then the parents last, at the bottom.
Answer: If I only get your goal correctly, I would suggest: for each node - get attached terms - for each term - get taxonomy_get_parents_all - reverse the array to have parent-to-child chain - form a list into a tree
Forming a tree could be yet another function with logic allowing to merge terms that share branches.

Terms in tree view - wrong order?


How to install jupyter notebook without Anaconda?In windows 7

Question: I am making a react- native application.I am using firebase for authentication.I ran this npm install firebase it was installed successfully and I was added in package.json file too but when I write this import * as firebase from 'firebase'.It gives me this : can't resolve firebase.Firebase version : latest v9.Please help me.
Comment: cant find any relevance in the question title and description
Answer: Go to the Path where Jupyter Notebook is installed.
Mostly it should be in
C:\Users\welcome\AppData\Local\Programs\Python\Python39\Scripts

From there run jupyter-notebook.exe file. It will be opened in browser.
Note : For my case it is welcome , for your case it can be your username.
C:\Users\atharva\AppData\Local\Programs\Python\Python39\Scripts

Basically you have to choose your path where python is installed.
This Answer is taken from How to install jupyter notebook without anaconda
Answer: it looks like you need to set the respective required PATH as a system variable and/or environment variable.
Comment: I appreciate your efforts towards learning python. however, if you want to take it to the next level you may consider some blogs eg. [link] (https://cppsecrets.com/users/7927971001051161051071111161041051219710855484864103109971051084699111109/Python-K-means-Music-Genre-Classification.php ) and you may also consider joining AWS coding events: bug buster [link]( https://aws.amazon.com/bugbust/ )
Answer:
While installing python make sure to check these points.
a. pip setting

b. add to Environment variable

Make sure these python variables is present in Environment Variables settings.

Open command-prompt and type: "pip install jupyter" and it looks like this..

After jupyter installation done. Type in command prompt: "jupyter notebook"
after few seconds jupyter server start and show this info in command prompt and open notebook in you browser as this..
Answer: Try reinstalling python. While installation, remember to  click "add python to path" option.
Open Command Prompt (cmd) and type:
python -m pip install -upgrade pip
#or, for python 2 users
python3 -m pip install -upgrade pip

After upgrading pip, write this -
python -m pip install jupyter

To open Jupyter notebook, write jupyter notebook in the cmd
Then, the Jupyter Notebook is opened in the browser
for more info - installing jupyter without anaconda
Comment: Thanks bruh!I have added it to path already


Correspondence theorem for rings.

Question: Could someone provide a reference that includes a full and honest proof of the Correspondence Theorem for rings?

Let $A$ be a multiplicative ring with identity and $I$ an ideal of $A$. There is a one-to-one correspondence between the ideals of $A$ that contain $I$ and the ideals of the quotient ring $A/I$.
Comment: Where can I find a "dishonest" proof of that? (to help understand what you mean)
Comment: Well, I mean a proof that does not refer to other results elsewhere, but rather starts from the start and ends at the end.
Comment: If you already know what the correspondence is, it shouldn't be terribly difficult to prove it is bijective (and even preserves lattice operations).
Comment: @Maxim_Koelt Usually this theorem appears almost immediately after the definition of rings and ideals, and so it does not refer to anything more exotic. Possibly the correspondence theorem for abelian groups is invoked to speed things up, but that hardly seems like a problem. What algebra books have you already checked and rejected?
Answer: My reference is this post.  Note that it is not necessary for $A$ to have an identity.

Let $\mathscr{C}$ and $\mathscr{D}$ denote, respectively, the collection of ideals of $A$ containing $I$, and the collection of ideals of $A/I$.
Define: $f:\mathscr{C}\to\mathscr{D}$ by $f(J) = \{a + I \mid a\in J\}\subset A/I$.
Define $g:\mathscr{D}\to\mathscr{C}$ by $g(\mathcal{J}) = \{a\mid a+I \in \mathcal{J}\} \subset A$.
(I omit the proofs that these give ideals, but these follow trivially from the definitions.)
If $\mathcal{J}\in\mathscr{C}$, then $(f\circ g)(\mathcal{J}) = \{a+I \mid a\in g(\mathcal{J})\} = \{a+I \mid a+I\in\mathcal{J}\} = \mathcal{J}$
.
If $J\in\mathscr{C}$, then $(g\circ f)(J) = \{a\mid a+I \in f(J)\} = \{a \mid a+I=b+I\text{ for some } b\in J\}$ $= \{a \mid a\in b+I\text{ for some } b\in J\}$.
This last set clearly contains $J$.  But $a\in b+I \implies (a-b)\in I\subset J \implies a=b+J\implies a\in J$.  So $(g\circ f)(J) = J$, and we have shown that $f$ and $g$ establish a bijection.

It probably doesn't get proved like this very often, because it's a lot shorter if we're allowed to use a few definitions.  It is, however, the same proof.
If $f:A\to B$ is a surjective ring homomorphism, and $J$ is an ideal of $A$ containing $\ker f$, then $f(J)$ is an ideal of $B$, because $Bf(J) \subset f(AJ) \subset f(J)$.
If $J'$ is an ideal of $S$, then $f^{-1} (J')$ is an ideal of $R$.
We have $f(f^{-1}(J')) = J'$ trivially, and $f^{-1} (f(J)) = J + \ker{f} = J$.
Comment: @Hawk  $B = f(A)$ by surjectivity, so $Bf(J) = f(A)f(J) \subset f(AJ)$, since $f$ is a homomorphism. (actually, we have equality here for unital rings, but we don't really need this)  Then we use $AJ\subset J$, since $J$ is an ideal.  I don't see how we can "jump" the first step.
Comment: Can you explain the first inclusion $Bf(J) \subset f(AJ)$? Why can't we just jump straight to $Bf(J) \subset f(J)$
Comment: Why I can't just assume that $\{a \mid a + I \in f(J)\} = \{a \mid a \in J\} = J$?
Comment: @LucasGiraldiA.Coimbra The question isn't why you can't, but why you think you can.  Certainly the second equality is clear (it's almost an axiom of set theory), but how can you "assume" the first without proving it?  Surely you need to know something about the relationship between $I$ and $J$, not to mention $f$!
Answer: Consider rings $R, R'$ (commutative, with unity) and a ring homomorphism $R \overset{\varphi}{\to} R'$.
For any ideal $J$ of subring $\varphi(R)$, clearly $\color{green}{\varphi(\varphi ^{-1} (J)) = J}$.
Also, for any ideal $I$ of $R$,  $\varphi ^{-1} (\varphi(I))$ $= \lbrace t \in R : \varphi(t) = \varphi(i) \text{ for some } i \in I \rbrace$ $ = \lbrace t \in R : t - i \in \ker(\varphi) \text{ for some } i \in I \rbrace$ $ = I + \ker(\varphi) $.
That is, for any ideal $I$ of $R$, $\color{green}{\varphi ^{-1} (\varphi (I)) = I + \ker(\varphi)}$.
But ideal $I + \ker(\varphi) = I$ if and only if $I \supseteq \ker(\varphi)$. This suggests :
Th: Let $R \overset{\varphi}{\to} R'$ be a ring homomorphism. There is a bijection
$$\lbrace \text{ideals of } R \text{ containing } \ker(\varphi)\rbrace \leftrightarrow \lbrace \text{ideals of } \varphi(R) \rbrace, $$
where $I$ in LHS is mapped to $\varphi(I)$.
Pf: Call LHS $\mathbf{A}$ and RHS $\mathbf{B}$. Define $\mathbf{A} \overset{f}{\to} \mathbf{B}$ by $I \mapsto \varphi(I)$, and $\mathbf{B} \overset{g}{\to} \mathbf{A}$ by $J \mapsto \varphi ^{-1}(J)$.

These are well-defined : $I \in \mathbf{A}$ implies $\varphi(I) \in \mathbf{B}$, and $J \in \mathbf{B}$ implies $\varphi ^{-1}(J) \in \mathbf{A}.$

For any $J \in \mathbf{B}$, $(f \circ g)(J)$ $= \varphi(\varphi ^{-1}(J))$ $=J$, so $f \circ g = \text{id} _{\mathbf{B}}$.
Similarly for any $I \in \mathbf{A}$, $(g \circ f)(I)$ $= \varphi ^{-1} (\varphi(I))$ $= I + \ker(\varphi)$ $=I$, so $g \circ f = \text{id} _{\mathbf{A}}$ too.
Comment: Doesn't $\phi$ need to be surjective?
Comment: No because it can always be viewed as a surjective ring homomorphism ${ R \overset{\varphi}{\to} \varphi(R) }$
Comment: @gen Note that $f\circ g=\mbox{id}_B$, which implies surjectivity of $f$. On the other hand, $g\circ f=\mbox{id}_A$, which implies injectivity of $f$. (In general, existence of a left inverse is equivalent to injectivity and existence of a right inverse is equivalent to surjectivity). Note that $f$ is actually $\varphi$. So, you get bijectivity of $\varphi$.

Correspondence theorem for rings.


For independent RVs $X_1,X_2,X_3$, does $X_1+X_2\stackrel{d}{=}X_1+X_3$ imply $X_2\stackrel{d}{=}X_3$?

Question: Let $X_1,X_2$, and $X_3$ be independent random variables such that $X_1+X_2$ and $X_1+X_3$ have the same distribution.  Does it follow that $X_2$ and $X_3$ have the same distribution?
Can this be answered without referring to characteristic functions?
Due to independence, the PGF of $U=X_1+X_2$ is given by $P_U(t)=P_{X_1}(t)P_{X_2}(t)$ and the same for $V=X_1+X_3$ is given by $P_V(t)=P_{X_1}(t)P_{X_3}(t)$
So we have $P_U(t)=P_V(t)\qquad$ (assuming convergence of the PGF's for some $t$)
$\Rightarrow P_{X_1}(t)P_{X_2}(t)=P_{X_1}(t)P_{X_3}(t)$
Now can I conclude from here that $P_{X_2}(t)=P_{X_3}(t)$? Moreover, I am restricting the random variables to be non-negative integer valued if I proceed like this.
Comment: Related post on math.se:https://math.stackexchange.com/questions/433478/if-xy-has-the-same-distribution-as-x-is-y-almost-surely-zero.
Answer: OK, for this answer I will assume the independent random variables have moment generating functions (mgf) existing in some open interval containing zero.  To dispel one possible doubt, mgf's can never be zero, since they are given by expectation of an exponential function $\DeclareMathOperator{\E}{\mathbb{E}} M_X(t) = \E e^{t X}$. Exponential functions are everywhere positive so that expectation can never be zero (or negative).
So, the assumption is that $X_1 +X_2$ have the same distribution as $X_1+X_3$. Write the mgf's as $M_i(t)=M_{X_i}(t)$. It follows that
$$
   M_1(t) M_2(t) = M_1(t) M_3(t)
$$ for all $t$ (where all three are defined, which will be some open interval containing zero). Since these functions can never be zero, we can divide on both sides by $M_1(t)$, obtaining $M_2(t)=M_3(t)$. We can conclude that $X_2$ and $X_3$ have the same distribution. For a nice review of properties of mgf's, see Existence of the moment generating function and variance
Now, what to do if mgf's do not exist? Replace the mgf's in the proof with characteristic functions. That becomes somewhat more involved, since that involves complex numbers, and my proof above that mgf's can never take the value zero do not work in that case.  But we can save the argument in that case in the following way: a characteristic function is always (uniformly) continuous, on the entire space, see https://en.wikipedia.org/wiki/Characteristic_function_(probability_theory)  .  Since it always take the value 1 at the argument zero, we can find an open interval containing zero where none of the three characteristic functions have zeros, so the cancellation works as above (this argument also works for moment generating functions).
Comment: Yes I wanted to see it explicitly mentioned whether they have the same distribution or not. One more thing is that if I use pgf, then the RVs are assumed to be discrete. What about when they are continuous? I suppose using mgf nullifies this issue.
Comment: For pgf versus mgf see https://stats.stackexchange.com/questions/297711/what-is-the-difference-between-moment-generating-function-and-probability-genera/297713#297713
Comment: I am probably missing something, but tollowing Polya's theorem (see https://en.wikipedia.org/wiki/Characteristic_function_(probability_theory)#Criteria_for_characteristic_functions) it seems to be possible to build two characteristic functions with the same values in a neighborhood of 0. Therefore if $M_1$ vanishes where $M_2$ and $M_3$ are not identical any more, the equation holds...
Answer: In general, no.
The proof given by @kjetil b halvorsen is fine, as long as the moment generating function exists.
However, there are counter examples when it does not. First, we need to recall a theorem by Polya. (More details can be found in the article Remarks on characterisic functions by G. Polya)
If φ is a real-valued, even, continuous function which satisfies the conditions

$\varphi(0) = 1$
$\varphi$ is convex for $ t<0$,
$\varphi(\infty) = 0 $,

then φ(t) is the characteristic function of an absolutely continuous symmetric distribution.
Now from this theorem, the two functions below are characteristic functions of some random variables, call them $X_1$ and $X_2$.

Now call $X$ the random variable whose characteristic function is
$ x \rightarrow (1-|x|)^+$ (again, using Polya's theorem).
Now, $\phi_{X_1}\phi_{X}=\phi_{X_2}\phi_{X}$ everywhere, so that $X_1+X\stackrel{d}=X_2+X$ but $X_1$ and $X_2$ have different distributions.
Comment: Very helpful, thanks. I was looking for a counterexample when I posted the question.


Stop Present Push Notification while App is Inactive or in Background

Question: I want to stop notification to present when user has been logged out from my App.
I have tried below.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
    print("\n>>willPresent notification")

    if sharedManager.instance.isLoggedIn {
        completionHandler([.alert, .badge, .sound])
    }else{
         completionHandler([])
    }
}

This is working perfect when app is active.
But the problem is when the app is in background or inactive, This code is not work.
I checked for background mode, at that time the willPresent notification  and didReceiveRemoteNotification methods are not get called.
Which is the appropriate method get called while receiving push notification in background or Inactive Mode??
Comment: but in settings->notification here not any option for this
just available UISWitch dude which used to on/off the facility
Comment: @NazmulHasan - can you explain little bit more...not getting exactly so
Answer: There is no direct way to handle this condition.
You can ask your API developer to handle this at server side,

When user clicks on logout button, call API to logout and set the status, isLoggedIn to false
For every API, that will send the push notification to user, at server it first check for the user's logged in status and can send the notification accordingly.
On, Login again set isLoggedIn to true in db at server and then it will start receiving the notifications again.

Hope it helps.
Comment: Thanx Bhavin, we did exact same. but the problem is in some case we are redirecting the user on login screen with out calling LOGOUT_API and we need to do that thing. Hence this situation is occurs.
Comment: Can you please elaborate that special case where you are redirecting the user to login screen
Comment: The case is when user tries 3 wrong attempt, we redirect to login.
but now, I got the answer,
we can set status "logged_Out" on third wrong API attempt.
Comment: thanxx to your last question... it helps to came me on the idea. thanx bro.@Bhavin Kansagra


Can I use PHP to add to an RSS feed?

Question: I've created an iPhone application that reads rss items from a feed. I understand this feed can be updated manually simply by adding  tags and adding sufficient info to the RSS file, but I want to do this using an interface. First thing that comes to mind, PHP. I could create an interface with a button that PHP can take the value of a few textboxes when submitted and create the item for me...
I can't seem to find any documentation online for this sort of thing however. Does this mean I'm doing something wrong?
Thanks
Answer: Yes, you can. However, then again, it won't be fun.
RSS is a subset format of XML, with specific rules. This, in practice, means that you can go two ways about it:

If you are familiar with DOMDocument and its use to parse XML/HTML, I strongly recommend you go down this route. It will allow you to fine-tune your RSS output
If, on the other hand, you are new to XML parsing and re-encoding overall, you are better off using a library or two to do it.

In terms of libraries, when in a pinch, I personally tend to use the universal RSS feed generator. Relatively simple to use, handles RSS and ATOM.
If you ARE familiar with DOMDocument, here are the things to look out for:

Before importing your RSS file, you will need to declare the namespaces. This is as easy as adding setAttributeNS() with the right definitions and imports
You will also need to care about the incoming format. Once you've got the hang of how DOMDocument works with XML, it is a trivial matter to add nodes. From there, once you're done, just call DOMDocument->saveXML() to get your new XML file. Voila, done.
Comment: Great thanks. Looks like the universal RSS feed generator will be the best option for me!

Can I use PHP to add to an RSS feed?


Permissions to see all users products, not just the orders on UberCart

Question: I am trying to figure out what permission in ubercart to set that would allow a user to see just the products they put in.  It show them orders but not a list of their own items. Any help?
Answer: The permission manage products must be turned off. The permission for to create a product, edit and delete own product must be turned on.


drush updb fails with "the 'media_delete_action' plugin does not exist" after 8.4.6 > 8.5.1 update

Question: We have recently updated a Drupal 8.4.6 installation via composer to Drupal 8.5.1. After the composer update I ran
drush updb

as usual. However, the command fails at one point with the following error message:
Failed: Drupal\Component\Plugin\Exception\PluginNotFoundException: The "media_delete_action" plugin does not     [error]
exist. in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 52 of
…\htdocs\casali\web\core\lib\Drupal\Component\Plugin\Discovery\DiscoveryTrait.php).

After that, every drush updb wants to do the following updates, since they are never completed:
system module :
  Change plugin IDs of actions.
  Clear caches due to schema changes in core.entity.schema.yml.

views module :
  Update dependencies for moved bulk field plugin.
  Add additional settings to the entity link field and convert node_path usage  to entity_link.
  Add placeholder settings to string or numeric filters.
  Fix cache max age for table displays.
  Include views data table provider in views dependencies.

I am not quite sure what to do here. As far as I have researched, media_delete_action is part of the media_entity module. However, that module is already part of the core in Drupal 8.4.x (https://www.drupal.org/project/media_entity).
If I run
drush en media_entity

it tells me
media_entity was not found.                                                                                [warning]
The following projects provide some or all of the extensions not found:                                                    [ok]
media_entity
Would you like to download them? (y/n):

But I don't think I should have to do that, since it's already part of the core?
Comment: I don't think its called media_entity anymore
Comment: True, it's only called `media`. But that module is already enabled anyway.
Comment: Did you follow the upgrade path mentioned on the project page?
Comment: The upgrade path is only applicable for projects that have been started prior to Drupal 8.4. I am not upgrading from `media_entity` to `media`. The installation always only was on Drupal 8.4 and it always only used `media`.
Comment: I've asked because media_entity_actions is part of the upgraded media in 8.4 which includes the missing plugin https://cgit.drupalcode.org/media_entity_actions/tree/src/Plugin/Action/DeleteMedia.php
Answer: This is how we were able to solve this problem:
Temporarily install drupal/media_entity_actions:
composer require drupal/media_entity_actions:^1.0
drush en media_entity_actions

Run the database update:
drush updb

This time it will work:
system module :
  Change plugin IDs of actions.
  Clear caches due to schema changes in core.entity.schema.yml.

views module :
  Update dependencies for moved bulk field plugin.
  Add additional settings to the entity link field and convert node_path usage  to entity_link.
  Add placeholder settings to string or numeric filters.
  Fix cache max age for table displays.
  Include views data table provider in views dependencies.

Do you wish to run all pending updates? (y/n): y
Post updating system                                                                                [ok]
Post updating system                                                                                [ok]
Post updating views                                                                                [ok]
Post updating views                                                                                [ok]
Post updating views                                                                                [ok]
Post updating views                                                                                [ok]
Post updating views                                                                                [ok]
Post updating views                                                                                [ok]
Post updating views                                                                                [ok]
Cache rebuild complete.                                                                                [ok]
Finished performing updates.                                                                                [ok]

Then the module can be uninstalled safely:
drush pm-uninstall media_entity_actions
composer remove drupal/media_entity_actions

Comment: In this situation, you *might* even need to download the tar.gz from drupal.org and extract it into modules/contrib (e.g. if you find the production server doesn't have sufficient memory or swap to run a composer require or update).


How can I remove all frequencies above a certain pitch with Audactiy?

Question: I'm trying to record an instrument using a piezo pickup, and while it's not capturing a lot of audio noise, it's capturing a lot of high frequency noise that my instrument shouldn't be making. The highest note my instrument can make is an A5 (880 Hz), yet it's capturing frequencies in the 2000-8000 Hz range.
How do I use Audacity to filter out all frequencies above a specific pitch?
I'm not talking about removing noise in general. When I'm not playing a note on the instrument, there's already virtually no background noise, so the "Noise Reduction" tool can't do anything.
This old question on the Audacity forum talks about it a little, but the filters they mention, like the Equalizer, have long since been removed in the current 2.4.2 version.
Comment: "it's capturing a lot of high frequency noise that my instrument shouldn't be making." BZZZT! Wrong. See Laurence's answer. Those frequencies are the essence of your instrument's sound. If you filter them away, nobody will be able to tell what instrument it is. Is there something wrong with the sound you're recording? Or is the prolem the way the spectrum _looks_? If it looks like the spectrum of a single sine wave, then it will sound like a single sine wave.
Answer: You can use the Spectral edit multi tool.
But be aware that the nominal frequency of a note only defines its pitch.   All musical sounds contain overtones, at higher frequencies than the basic pitch, and it's these which largely determine the timbre of the sound. Filter out everything above 880Hz and it's not going to sound like that instrument any more!
Answer: You need an equaliser.  Not any specific equaliser plugin, but any equaliser available in whatever application you choose to use.  It may be a plugin, it may be built into the application.
If you genuinely only want to keep frequencies below some cutoff, then you want a low-pass filter.  You'll find them in the list of EQ options, or you might find a separate plugin for it.
From reading your question though, this is not what you want to do.  As piiperi's comment says, these higher frequencies are what make your guitar sound like a guitar.  With just the fundamental frequency it would sound like a pure sine wave, because that's what it'd be.  (A tuning fork is the closest physical equivalent of this.)
It may be that you've got stuff on there which you don't want though.  If you've used a piezo pickup, they have a midrange "quack" to their sound which changes the tone.  If you've used a microphone and you've not done a good job with positioning and/or playing, you may be picking up fretting noise, finger squeaks, poor picking/fingerpicking technique, clothing rustling, etc..  These are things you mostly don't want - although sometimes you do, because on most acoustic guitar playing you'll hear some of these things, so be wary about aiming for a completely clean, sterile result.  But assuming you do want to remove them...
It's time for more EQ.  You can use a multiband graphic EQ, traditionally with 31 faders for bands of frequency, or you can use a parametric EQ where you set a frequency yourself.  Since you're a beginner, I'd suggest a graphic EQ is going to be easier for you.
You want to start with everything zeroed (at midpoint).  Work out roughly where your troublesome frequencies are.  Then one fader at a time, push that frequency up (at least halfway, to maximum if you can stand it) and run your recording.  The result will sound strange, but you're not listening for sound quality, you're listening to see if this is a frequency band which is adding a ton of crap.  If it is, then boosting that band will make the noise really jump out at you.  If it is, push that band down to maybe -6dB, and then move on to the next one.
The idea is to have as few frequencies removed as possible.  That leaves the tone of your guitar substantially intact, whilst doing a precision strike on the bits you don't want.  Initially you're going to be far too heavy-handed, and the result with loads of bands removed is going to sound dull and muffled.  No matter - go back and try again.
Doing good EQ is a skill, and it takes practise.  A good live sound engineer can dial this in by ear on the mixing desk within seconds, because they know what they're listening for.  It could take you half an hour to get something you like.  No worries, you'll get there.
But any engineer can also tell you that the best way to get a good sound is to start with a good sound!  Your guitar technique is part of that, of course - but after that, you need to record it well.  This SoundOnSound article is a very good place to start for techniques on recording guitars.  There are many ways to skin that particular cat, and it would certainly benefit you to do some experimentation with that.  (And one thing to avoid - never, absolutely never, point the mic straight at the soundhole!)
In general, I would thoroughly recommend you going to the SoundOnSound site and looking through their archives.  They've got a lot of articles about how to do recording and how to "massage" recordings with EQ and other FX.  You'll learn a lot by going through their articles and then trying out some of those ideas for yourself.
Comment: It has been 15+ years since I've done live sound, and I was never great at it, but I loved getting a space set up - reading this really takes me back to that "there it is!" feeling, thank you for a great answer.
Comment: @BriansaysReinstateMonica Thanks!  It's been a few years for me too - spending every other weekend with my son after a divorce is not compatible with gigging.  Back in the day though, I was running sound for local gigs where I'd have 3 or 4 bands on, and not a whole lot of time to soundcheck.  Or for small festivals, where at best you get to line-check.  I didn't do any huge events because this was never my day job, but it was a lot of fun and I was reasonably competent back then.
Comment: I disagree that a graphic EQ is a better choice for beginners. As you've explained, optimal use of EQ requires first _finding_ the critical frequencies, and that's much easier by sweeping through a single band-boost. Especially software graphic EQs are a huge pain to set up since you can just tweak multiple faders with one grab. Beginners using graphic EQs tend to set up ridiculously nonlinear curves that don't really accomplish anything useful. Only for seasoned engineers can (physical-fader) graphic EQs be quicker to set up, because they already _know_ pretty much what curve they want.
Comment: @leftaroundabout I don't disagree that a parametric is easier for people who know what they're doing.  I don't think it's easier for a beginner though.  And the point of this is that it *isn't* a curve - you're trying to notch out the nasties, not put a gentle curve across it.  Depending on how accurate the OP's information is, of course.  Without hearing it ourselves, we can't judge what's needed.  Hence my point about recording - often the best answer is to re-record and start with something that doesn't have these problems.
Comment: @leftaroundabout ... But you're right that it's an option.  The point really is for the OP to start learning how to use EQ effectively, and that's a wider problem than just "I've got noise on my recording".
Answer: It sounds like what you want is spectral selection and editing.

Spectral Selection is used to make selections that include a frequency range as well as a time range on tracks in Spectrogram view. Spectral Selection is used with special spectral editing effects to make changes to the frequency content of the selected audio.
Among other purposes, spectral selection and editing can be used for cleaning up unwanted sound, enhancing certain resonances, changing the quality of a voice or removing mouth sounds from voice work.

There above-linked reference page includes a detailed example of removing a specific pitch.
Answer: Turns out my Audacity installation was screwed up. The low pass filter is what I wanted by it wasn't showing up, probably because I carried over an older configuration file from a previous version.
So I did sudo apt purge audacity*; sudo apt install audacity and then all the regular filters were back.
With low pass removing all the junk high frequencies, it sounds much better. Thanks everyone.


How to make a button tkinter

Question: Just trying to learn here. How would I compare if a person selected "Sign in" from the selection? Currently it sleeps even though I selected "Sign in"
from tkinter import *
from tkinter import ttk
import sys
from time import sleep

def selectMode():
    if w == vlist[1]:
        sys.exit()
    else:
        sleep(10)

root = Tk()
root.geometry("1200x600")

label_1 = Label(root, text="Hello, world")
label_1.pack()

frame = Frame(root)
frame.pack()

vlist = ["Create an Account", "Sign In", "Forgot Username or Password"]

Combo = ttk.Combobox(frame, values = vlist, width="50")
Combo.set("Pick an Option")
Combo.pack(padx = 5, pady = 150)

    w = Button (root, command=selectMode)
    w.pack(padx = 5, pady =5)

root.mainloop()

Comment: `w` is a tk.Button object and `vlist` if full of strings so `w` will never equal `vlist[1]` so `selectMode` will always sleep
Comment: you should check value selected in `Combo`, not in `Button`  - `if Combo.get() == vlist[1]:`
Comment: maybe first use `print()` to see what you have in variables. It is called `"print debuging"` and it helps to see what code is doing.
Answer: You have to check value selected in Combo, not Button
if Combo.get() == vlist[1]:

Full working code with other changes.
You can use root.destroy() to close window - and then you can run other code (ie. other window) after root.mainloop()
import time
import tkinter as tk   # PEP8: `import *` is not preferred
from tkinter import ttk

# --- functions ---   # PEP8: `lower_case_names` for functions

def select_mode():
    if combo.get() == vlist[1]:
        root.destroy()  # close window
    else:
        time.sleep(10)

# --- main ---   # PEP8: `lower_case_names` for functions

vlist = ["Create an Account", "Sign In", "Forgot Username or Password"]

# ---

# --- main ---

vlist = ["Create an Account", "Sign In", "Forgot Username or Password"]

# ---

root = tk.Tk()

label = tk.Label(root, text="Hello World!")
label.pack(padx=15, pady=15)

combo = ttk.Combobox(root, values=vlist, width="50")  # PEP8: inside `()` use `=` without spaces
combo.set("Pick an Option")
combo.pack(padx=15, pady=15)  # PEP8: inside `()` use `=` without spaces

w = tk.Button(root, text='OK', command=select_mode)
w.pack(padx=15, pady=15)  # PEP8: inside `()` use `=` without spaces

root.mainloop()

print('after closing window')  # here you can run another window (with with another mainloop)

PEP 8 -- Style Guide for Python Code

How to make a button tkinter


Continuous deployment to Azure from TFS 2012 Update 2

Question: I am not using TFS Service (Preview/Online). I am running TFS 2012 Update 2 on-site and trying to deploy an Azure Service that contains a web and worker role. I'm also using Azure SDK 2.0.
I have tried endlessly to get the deployment working with the "AzureContinuousDeployment.11" template. However, from all my effort and from what I read on the web, it seems this template only applies when using TFS Service (Online/Preview) and not for on-premise TFS.
I have now ventured down the path as suggested by  http://blogs.msdn.com/b/tomholl/archive/2011/12/06/automated-build-and-deployment-with-windows-azure-sdk-1-6.aspx and http://www.justaprogrammer.net/2012/10/18/continuous-integration-with-windows-azure-sdk-1-7-powershell-and-tfs-build-too/ article. I just started the process, so have nothing working yet. However, when looking at all the steps required to do, I can't help and pause for a moment and think "Is there a better way?". We are on TFS 2012 Update 2, TFS Preview has been out for, there must be an easier way to do this.
What are the suggested steps/processes required to do a continuous push of Azure solution out to the cloud as part of TFS?
Any suggestions?
Answer: The problem is that Azure SDK 2.0 is not yet roled out on TFS Online Build, see also: http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/3932152-install-windows-azure-2-0-0-0-sdk-on-the-https-t.
Answer: Here are two fixes that TFS support gave me to get this working on my TFS on premise controller.
This only happens with Azure cloud services and only with an on premise build machine.
You will need to update the template and add quotes around the publishdir parameter value in the "Set project to build CSPack" activity in the workflow and check the template back in.
String.Format("/t:{0}:Publish /p:PublishDir=""{1}/app.publish/"" {2}", ccprojName, outputDirectory, MSBuildArguments)
To fix the assembly loading error, you need to copy
"C:\Program Files\Microsoft SDKs\Windows Azure.NET SDK\2012-06\bin\Microsoft.WindowsAzure.StorageClient.dll"
To
C:\Program Files\Microsoft Team Foundation Server 12.0\Tools
On the build machine and restart the service.
Let me know if that doesn't work for you.


What is this formula?

Question: i have been asked to plot a graph of the residuals from the following formula:
<code>|y(hat)/y|-1
</code>
they said that it was MAPE but i have the formula for MAPE as:
<code>|100*(y-y(hat))/y|
</code>
Is my formula for MAPE wrong or is the formula i was given not the formula for MAPE? If it isn't then what is it?
Answer: I think your first expression should be $|\frac{\bar y}{y}-1|$, because negative values are meaningless in terms of error.
Note that $|\frac{\bar y}{y}-1|=|\frac{y-\bar y}{y}|$.
So the difference between the two formula above is only $\cdot 100$. It is common practice to use the short form, which provides the real information, "$\cdot100$" is only there to call it percentage. When plotting, it doesn't matter which form you use, multiplying each value by a constant will not change shape and the essence of the plot.
Comment: thankyou i will definitly note that down! thankyou very much :)
Answer: Your first formula will yield a negative "MAPE" if $\hat{y}<y$, which can easily happen, but which will be hard to explain to users. Your second formula is indeed the most commonly accepted definition of the MAPE. Unfortunately, there is no universal agreement on what a "Mean Absolute Percentage Error" is, see here.

What is this formula?