Undefined method 'role?' for User

Question: I have the following abilities model:
class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user, not logged in.

    if user.role? == :admin
      can :manage, :all
    else
      can :read, :all
      end
      if user.role == "default"
        can :create, Homescreen
        end
        can :destroy, Homescreen do |homescreen|
          homescreen.try(:user) == user
      end
  end
end

And I have the following users model:
class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  before_create :setup_default_role_for_new_users

  attr_accessible :email, :password, :password_confirmation, :remember_me
  has_many :homescreens

  ROLES =%w[admin default]
  private
  def setup_default_role_for_new_users
    if self.role.blank?
      self.role = "default"
    end
  end
end

When I run it on my local machine, it works fine.
However, when I deploy to heroku, I get the following error:
GET URL.herokuapp.com dyno=web.1 queue=0 wait=0ms service=158ms status=500 bytes=643
   app/models/ability.rb:7:in `initialize'
 NoMethodError (undefined method `role?' for #<User:0x00000003b56050>):

 cache: [GET /] miss

 Started GET "/" for my-ipaddress at 2012-03-19 16:14:38 +0000

 NoMethodError (undefined method `role?' for #<User:0x00000003df5d88>):
   app/models/ability.rb:7:in `initialize'

 cache: [GET /] miss

What am I doing wrong?
Comment: Have you migrated your database?
Comment: show us `user.rb` model, i you model actually have this method or is users table have boolean field role?
Comment: @NeilMiddleton Yes, multiple times including creating a new heroku app and trying again.
Comment: is ability working on development? check User model in heroku console for role field persistance. Also try this syntax for `ability.rb` `user.role.eql?("admin")` and `user.role.eql? "default"`
Comment: @MikhailNikalyukin It works in development.
Answer: I restarted heroku with the following command:
heroku restart && heroku ps:restart
It then worked fine.
Comment: just for future - try this first, but doesn't work for everyone

Undefined method 'role?' for User


Drupal Commerce Kickstart 2 Adding Attrubutes to SPECIFIC Products

Question: I have a product type and I sell a number of different items within that category, where most of them have the same 3 options (color, type, voltage).  However, I have a couple of products of this type that don't conform to the same option set in that they have an one additional option for the customer to select.
The way I see it, I have two workarounds here, and neither of them seem like it's the "right" way to do it.  Either I create a separate product/ variation type with all of the existing options, plus the additional option, or I add the additional option to ALL of my variations, even the ones that don't come with that option and just leave it blank for those products.  Neither of these solutions are ideal in that it separates these products from others of their "type" or it creates the possibility for options to become available to the end user that are not possible.
Perhaps this is just me coming from an ubercart background, but I feel that I should be able to create an option that is specific to an individual product.  I've scoured the internet and I'm not finding a way to do this, nor am I finding anyone else asking this question and getting an answer.  What am I missing here?
Answer: I think you can use Conditional Fields module which can help you in showing and hiding fields based on any other field value.
You can also watch these tutorials in case you need to understand Drupal Commerce in detail.
Comment: My point, is various sku's are going to be differentiated by different attribute sets, even within the same product category.  Lets keep the example simple with the often used "shirt" store.  One model of shirt comes in red, blue, green, and orange, and is sized S, M, L, XL.  Another model of shirt comes in white, grey, and black, and is sized 2, 4, 6, 8, 10.  Those are both "shirt" types, yet their attributes are completely different and never between shall they meet.  Am I supposed to have a completely different content type for every product to make it it's own type?  That can't be right.
Comment: I don't think that Conditional Fields is an effective solution in this case.  In fact, I think it's counter intuitive to the underlying problem here because it's adding more code to the rest of the product type instead of just being able to add an attribute to "this" specific product variation ad hoc.The fact of the matter is that in the attempt to make Drupal Commerce as flexible and as generalized as possible, it removes so much of the meat of the node- level content in lieu of the abstract entities that there's nothing left to hook into.
Comment: I don't think you need different contentype/producttype. If I have understood correctly you use SKU to distinguish products. To generate unique SKU to different attribtues you can check out this modules:
https://www.drupal.org/project/commerce_autosku

If SKU field settings allow you, you can use tokens to generate SKU as you want.
Comment: The problem is being able to add attributes to a specific product, and not to a product type.  For example, I have a product that has a set of attributes (two choices/ skus) that no other product I carry has.  It seems redundant and unnecessary to create an entire product/ variation type that is specific to 1 product set and it will never be used again.


echo image from converting text-to-image

Question: I found this code for converting text-to-image and I wanted to echo the result
<?php
// Set the content-type
header('Content-type: image/png');

// Create the image
$im = imagecreatetruecolor(400, 30);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);

// The text to draw
$text = 'Testing...';
// Replace path by your own font path
$font = 'arial.ttf';

// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);

// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>

for example I saved that code to image.php, I can echo that image by
echo"";

but I don't want to do that way, because if I did, I cant assign variable text.
Is there any other way to print the image from that code?
Comment: What do you mean with "I cant assign variable text."? You can always use $_GET-Parameters in the URLs.
Answer: in your image.php
replace
 $text = 'Testing...';

with
 $text=$_GET["text"];

and your code to print
echo"";

Hope this is what you want?
EDIT:
<form action="image.php" method="post">
<textarea name="text"></textarea>
<input type="Submit" value="Submit">
</form>

in your image.php file instead of
$text=$_GET["text"];

use
$text=$_POST["text"];

Comment: I have a long text to pass. Like a 600 word article type. Is it ok to pass that way?
Comment: why would you convert an article to an image for a web site?
Comment: It is OK to pass long GET variables. Though maybe you could consider storing all the text in a database then calling image.php?id=1 (where the ID then hits a lookup table through mySQL to get the text).
Comment: For headers that use special fonts.
Comment: @IvorySantos, If this solution helped you please mark this solution as accepted so that people will know that your problem has been solved.


Efficiently extract edges with biggest weight for each node igraph

Question: I have a weighted undirected simple graph.
The number of nodes is around the tens of thousands and so does the number of edges (it's a sparse graph / matrix).
For each node, I want to find the maximum edge weight ("max score") and store it in a data frame along with the nodes who share that edge. The data frame will have three columns: node_name - str, max_score - float [0-1], max_score_nodes - List[str]
My current solution is provided below, but it's not elegant, there are multiple list comprehensions (one of them is nested) inside a for loop, checking for nodes without edges etc. and I feel there's a smarter way of doing this.
import string
import igraph as ig
import numpy as np
import pandas as pd

nodes = list(string.ascii_letters[0:6].upper())
edges = [("A", "F"), ("A", "C"), ("F", "D"), ("D", "C"), ("D", "E")]
weights = [0.6, 0.4, 0.3, 0.9, 0.9]

w_graph = ig.Graph(directed=False)
w_graph.add_vertices(nodes)
w_graph.add_edges(edges, {"weight": weights})

records = {}
for node in nodes:
    local_edges = np.array(w_graph.vs.find(node).all_edges())
    if local_edges.size == 0:
        records.update({node: {"max_score": 0, "max_score_nodes": np.nan}})
        continue
    local_weights = [local_edge["weight"] for local_edge in local_edges]

    max_score = np.max(local_weights)
    max_score_ind = np.where(local_weights == max_score)[0]
    max_score_edges = local_edges[max_score_ind]

    vertex_tuples = [edge.vertex_tuple for edge in max_score_edges]
    max_score_nodes = [
        [vertex["name"] for vertex in vertex_tuple if vertex["name"] != node][0] for
        vertex_tuple in vertex_tuples]

    records.update({node: {"max_score": max_score, "max_score_nodes": max_score_nodes}})

output = pd.DataFrame.from_dict(records, orient="index")
output_with_node_name = output.rename_axis("node_name").reset_index()
print(output_with_node_name)

Answer: You can build your graph like this:
import igraph as ig
from igraph import Graph

g = Graph.Formula('A, B, C, D, E, F, A-F, A-C, F-D-C, D-E')
g.es['weight'] = [0.6, 0.4, 0.3, 0.9, 0.9]

Get the index of the highest weight edge for each vertex:
strongest_edges = [max(edges, key=g.es['weight'].__getitem__) for edges in g.get_inclist()]

Get the endpoints of each of these edges:
[g.es[eid].tuple for eid in strongest_edges]

Comment: I appreciate your answer and it taught me new igraph methods so + 1 but currently it doesn't work on my example since your graph is missing node B which has no edges. Also in the final output instead of a list tuples with two node ids, I would like to have a list of dicts with the max_weight and a single node name (as seen in output_with_node_name) so the last list comprehension needs modification
Answer: I discovered SciPy's csr matrix which efficiently handles sparse matrix in a compressed row format.
There's an igraph method which returns the graph's adjacency matrix as a CSR matrix.
From here we can utilize vectorized operations on rows, so the whole nested for loop is now reduced into 4 lines:
scores_matrix = w_graph.get_adjacency_sparse(attribute="weight")

node_names = w_graph.vs["name"]
max_scores = scores_matrix.max(axis=0).toarray()[0]
max_score_nodes = w_graph.vs[scores_matrix.argmax(axis=0).tolist()[0]]["name"]
max_score_nodes = np.where(max_scores == 0, np.nan, max_score_nodes)

output = pd.DataFrame({"node_name": node_names,
                       "max_score": max_scores,
                       "max_score_nodes": max_score_nodes})
print(output)

The problem is that argmax will return only a single index, if you want to have all node_names with max_score you can loop like this:
from scipy.sparse import find

max_score_nodes = []
for node_index in w_graph.vs.indices:
    max_score = max_scores[node_index]
    if max_score == 0:
        max_score_nodes.append(np.nan)
        continue

    max_score_node_ind = find(scores_matrix.getrow(node_index) == max_score)[1]
    max_score_node_names = w_graph.vs[max_score_node_ind.tolist()]["name"]
    max_score_nodes.append(max_score_node_names)

output["max_score_nodes"] = max_score_nodes
print(output)


Why Can't Panels Select My Organic Groups?

Question: I'm trying to create panels that are visible or show up on pages specific to certain groups. I'm using Organic Groups 7.x-2.7 on Drupal 7.34. So, our company's technicians would only see panels specific to them and the same for office staff. I'm having an issue integrating Panels with Organic Groups. When setting the "Selection Rules", "Visibility" or any other value for a panel to the group of the User who is viewing, the option to select the group is there and selectable BUT it only shows up as an empty string and the panel doesn't abide by this rule. I'm pulling my hair out and eating it in a mad attempt at proving to the gods of drupal code that I am worthy of a solution.
Update (3/20/15)
I changed my Organic Groups installation to version 1.5. This seems to work. I'll try each version incrementally until I reach the first one that breaks and just place it here. I still have no idea why this is occurring, though.
Comment: Have you tried the 'other groups' section?
Comment: Doesn't work. In fact, the autocomplete doesn't even respond. Just the little circle turning around.
Answer: The way I accomplished this was with Views Contextual Filters and the Views Content Panes module, displaying only content belonging to the particular groups I wanted to see the content.  This approach, however, requires the content being viewed to have a field instance of the group ID that it belongs to (and, incidentally, a field instance for "other" groups the content will be visible in).  Note, in order for the two contextual filters to work properly here (i.e. for the content pane to be visible in two or more groups) I had to install the "Views Contextual Filters OR" module (I can't link twice because no rep).
I couldn't comment because I don't have enough rep, but this approach worked for me, but it might not work in your specific use case.  It should be noted that if nothing matches the filter, the pane is omitted from display entirely (which is what you are ostensibly trying to accomplish).  So many ways to skin a cat with Drupal.


Why do my xcode builds always go to the iPad simulator instead of the iPhone simulator?

Question: I just installed the latest SDK from Apple so I can start learning iPhone / iPad app development. However, I'm having a stupid issue: all my builds get run in the iPad simulator instead of the iPhone simulator, and I have no idea how to change it.
Answer: On your build selector dropdown, (where you select device or simulator), there's now a new option that lets you choose the "Active Executible." Choose "iPhone Simulator."
alt text http://img.skitch.com/20100227-qyadm4ktn3abr3j44upkufjieh.jpg
Comment: I don't have this option, only iPad simulator is listed.
Comment: change the active sdk to 3.1.2
Answer: For now, the iPhone Simulator 3.2 SDK is iPad-only. Test using the iPhone Simulator 3.1.2 SDK
edit: as of the upcoming 4.2 SDK, the iPhone and iPad versions of iOS have been unified under a single SDK.
Comment: Was just about to ask the same question (thought it was a configuration problem) and saw this answer. I'd been digging through the target and executable settings for days trying to find this. Didn't expect something so simple.


Drupal commerce - same product with different formats that determine price and get added to line item titles

Question: I have a taxonomy term select list where the administrator can add one or more formats to a product entity. The term itself has a price coefficient field that should be used to determine the price of the product in that format. On the product display page there should be a 'add to cart' button for every format of that product. The title of the product in the cart/order views should display the format and the price should be according to what was calculated using the product base price and the format coefficient.
Any generic ideas how I could implement this with the Drupal Commerce module or good alternatives that accomplish the same thing? It could be assumed that every product display has only one product entity associated with it if this makes things easier.
Answer: Googletorp's suggestion seemed like it won't give me quite the result I needed so I tried to do the whole thing with my own add-to-cart form, line item/order creation and so on, but ended up with a lot of issues and work that made me go back and try the suggested approach. Got exactly what I needed much easier in the end. Posting the entire solution here to save possible trouble for others.
First I added a format field (that referenced the same taxonomy terms as the one attached to the product) for the used line item. Set it up so it would be included in the Add to Cart forms. After that I added the pricing rule via the GUI:

Events - Calculating the sell price of a product.
Conditions - Entity has field (line item format field).
Actions - Multiply the unit price by some amount (amount specified in the terms coefficient field).

To modify line item titles to show the selected format I found help here: http://digibits.org/blog/drupal-commerce-dynamic-line-item-titles. The code:
function mymodule_commerce_line_item_type_info_alter(&$line_items) {
  $line_items['product']['callbacks']['title'] = 'mymodule_line_item_title';
}

function mymodule_line_item_title($line_item) {
  $term = taxonomy_term_load($line_item->field_line_item_format[LANGUAGE_NONE][0]['tid']);

  return t('!product (!title)', array(
    '!product' => commerce_product_line_item_title($line_item),
    '!title' => $term->name,
  ));
}

Now I needed to restrict the format selection for customers depending of what the administrator has chosen for the product and display them all as add-to-cart buttons not a select list. This was doable via hook_form_alter():
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // Alter add to cart forms.
  if (strpos($form_id, 'commerce_cart_add_to_cart_form_') === 0) {
    // If the product is available for sale.
    if ($form['submit']['#value'] == t('Add to cart')) {
      // The form should only be for a single product so we can get the id from the product_id field.
      $product_id = $form['product_id']['#value'];
      $product = commerce_product_load($product_id);
      // The original submit button isn't needed.
      unset($form['submit']);

      $i = 1;
      // Create a submit button and additional markup for every given format.
      foreach ($product->field_format_types[LANGUAGE_NONE] as $format) {
        // #name will be used to determine the selected product format instead of the select list value.
        $form['submit_'.$i] = array(
          '#type' => 'submit',
          '#value' => t('Add to cart'),
          '#name' => $format['tid'],
        );
        $i++;
      }

      // This form submit handler needs to be called before any others.
      array_unshift($form['#submit'], 'mymodule_add_to_cart_form_submit');
    }
  }
}

function mymodule_add_to_cart_form_submit($form, &$form_state) {
  //drupal_set_message('
'.var_export($form_state['triggering_element'], TRUE).'
');

  // Get the clicked submit button name.
  $name = $form_state['triggering_element']['#name'];
  // Use the clicked submit button name to set the correct product format.
  $form_state['values']['line_item_fields']['field_line_item_format'][LANGUAGE_NONE][0]['tid'] = $name;
}

In the end I hid the select list via css and that was it.
Answer: The product reference field handles the add to cart functionality with the ability to select product etc. out of the box.
For the custom pricing, you should be able to handle that by setting up a custom rule that alters the price based on the term selected. It might require a few tricks to make all the variables available, but with the heavy integration Commerce has with Rules, and the special calculate sell price event, this shouldn't be possible to setup via the GUI.


Qual o RegExp para validar matrículas de Portugal

Question: Queria saber qual é a Expressão Regular que valida matrículas de Portugal.
Considerando que em Portugal há este tipo de matrículas

AA-00-00
00-00-AA
00-AA-00
AA-00-AA

qual o código de RegExp que tenho de usar para validar num formulário apenas matrículas desse tipo?
<input id="matrícula" type="text">

Comment: @Maniero porque motivo fechou o tópico?
Comment: Porque não respondemos perguntas que dão um enunciado e fica esperando que façam o código para si. As perguntas devem ser só conceitual ou então ter um problema específico. Isto é o que se chama enunciado, ou faça pra mim. Não faz sentido fechar quando uma pessoa pergunta e manter aberto quando a pessoa pergunta e responde.
Comment: @Maniero certo, mas excusava de dar um ponto negativo. Eu fiz a pergunta e respondi pois achava que esta questão era relevante e queria partilhar as conclusões a que cheguei.
Comment: Eu não dei negativo, só fechei.
Answer: De acordo com a wikipédia

Inicialmente a sequência utilizada era a AA-00-00. Em 1992 passou-se para a 00-00-AA e, em 2005, para a 00-AA-00 que está actualmente em vigor. Quando esta chegar ao fim, está prevista a introdução da sequência AA-00-AA.

Ou seja, consideramos os quatro formatos válidos

AA-00-00
00-00-AA
00-AA-00
AA-00-AA

Basta apenas agora considerar a expressão regular seguinte que considera exatamente estes 4 casos válidos, com um hífen comum (-) a separar os dígitos
/^(([A-Z]{2}-\d{2}-(\d{2}|[A-Z]{2}))|(\d{2}-(\d{2}-[A-Z]{2}|[A-Z]{2}-\d{2})))$/

Tem aqui um exemplo que pode usar

$("#matricula").css('outline','none').on('input', function(e){
  e.preventDefault()

  var expr = /^(([A-Z]{2}-\d{2}-(\d{2}|[A-Z]{2}))|(\d{2}-(\d{2}-[A-Z]{2}|[A-Z]{2}-\d{2})))$/

  if (!expr.test($(this).val())){
    $(this).css('border', '2px solid red')
  } else {
    $(this).css('border', '2px solid green')
  }
})

Insira a matrícula, usando o hífen comum (-) entre os dígitos:

<input id="matricula" type="text">
Comment: Sugiro colocar o `^` no início, caso contrário a regex aceitará valores como "AAA-00-AA". Além disso, dá pra simplificar um pouco: `\d` equivale a `[0-9]` e dá pra agrupar alguns casos (se começa com letras, sempre tem 2 números depois e no final 2 números ou letras, ou seja, `[A-Z]{2}-\d{2}-(\d|[A-Z]){2})`). E se começa com números, o restante é 2 números e 2 letras **ou** 2 letras e 2 números (ou seja, `\d{2}-(\d{2}-[A-Z]{2}|[A-Z]{2}-\d{2})`). Então a regex ficaria `^(([A-Z]{2}-\d{2}-(\d|[A-Z]){2})|(\d{2}-(\d{2}-[A-Z]{2}|[A-Z]{2}-\d{2})))$` - [veja](https://regex101.com/r/0eqtXE/2/)
Comment: Correção, no primeiro caso (começa com letras), seria `[A-Z]{2}-\d{2}-(\d{2}|[A-Z]{2})` (a versão do comentário anterior aceitava um número e uma letra no final, agora aceita somente 2 números ou 2 letras). Então a regex fica `^(([A-Z]{2}-\d{2}-(\d{2}|[A-Z]{2}))|(\d{2}-(\d{2}-[A-Z]{2}|[A-Z]{2}-\d{2})))$` - [veja](https://regex101.com/r/0eqtXE/3/). Outro detalhe é que se vc usa as barras, não precisa chamar o construtor de `RegExp`, ou seja, pode ser apenas `var expr = /^(([A-Z]{2}.../`
Comment: @hkotsubo bem visto, editei em conformidade tal como sugeriu


Broadcast através de uma rota no Express

Question: Tenho um endpoint em uma aplicação node que quando chamada deve disparar um broadcast para os usuários conectados na aplicação node.
Ou seja, assim que o usuário entrasse no sistema ele se conectaria através do socket.io e ficaria aguardando até que um agente externo chamasse essa rota para ai sim ser disparado a mensagem para quem estivesse conectado. Isso é possível ? Não sei se fui claro o bastante. Estou usando para isso express e socket.io.
Answer: Sem dúvida, é possível sim. Veja um exemplo:
No servidor, app.js
var _   = require('lodash');
var app = require('express').createServer();
var io  = require('socket.io')(app);

app.listen(80);

var sockets = {};

app.get('/', function(req, res) {
  res.sendfile(__dirname + '/index.html');
});

app.post('/oi', function(req, res) {
  enviaParaTodos(req.body);
});

io.on('connection', guardaConexao);

function guardaConexao(socket) {
  socket.on('error', console.log);
  socket.on('disconnect', function() {
    delete sockets[socket.id];
  });
  sockets[socket.id] = socket;
}

function enviaParaTodos(dados) {
  _.forOwn(sockets, function (socket, id) {
    socket.emit('oi', dados);
  });
}

No cliente, index.html


I have the problem when I run the project in android studio in my phone

Question: enter image description here
Before I updated my phone, the apps were working, but now they are not, My phone type is Redmi 9 and this is the last version 184.108.40.206 Stable MIUI 13
Answer: I looks like you have set you phone to only charge over the usb connection, and not allow file transfer. You should be able to reset all allowances and blocks under development settings. You should also make sure that the cable is a data cable and not just a charging cable. To check if you set your connection to only charge, you should be able to pull down from the top twice to see your notificaitons, and in the bottom there should be a "charging via cable" notification or something along those lines, click that and set it to file transfer
Answer: To run an app correctly on your device, you must follow these steps:
1- Allow developer mode.
2- Connect a cable.
3- Allow data transfer, not just charging.
4- Verify if your device is recognized (run "flutter doctor" and you will see the name of your device).
Finally, run the app on your device.


what variable can i use to identify a specific pages

Question: i need to load a diff stylesheet depending upon which page the user is on.
when using:
     themename_preprocess_page(){kpr(&$variables;)}
i thought i'd see a pageId or pageTitle in which i could use for a conditional statement but i'm not seeing those variables. am i overlooking something? what can i use to uniquely identify a page so i can the use drupal_add_css()?
i guess i could do at the node level? but the stylesheet i need to load is really a page level thing.
can someone advise on the best way to do? big thanks in advance
Comment: i think maybe my theme was somehow not outputting a page title variable, i see that now when switching page to Bartik.
Answer: You may have trouble adding CSS with drupal_add_css in hook_preprocess_page because the $styles variable has already been built.
Better to add CSS in hook_preprocess_html or hook_page_build
Note, you should be able to target specific pages in CSS by using body classes.
e.g:
body.page-node-type-article #content{
  background-color:pink;
}

But yes, to check the path, you can use
$arg = arg($index); // system path component
$path = current_path(); // full base system path ($_GET['q']);
$alias = $_SERVER['REQUEST_URI']; // full alias only

Answer: You can use arg to identify specific page.
It returns a component of the current Drupal path.
When viewing a page at the path "admin/structure/types", for example, arg(0) returns "admin", arg(1) returns "structure", and arg(2) returns "types".
For more info go through the documentation.
Comment: thanks i will try. for some reason it seems that 'page title' is not part $variables in my custom theme. not sure why?
Comment: if i do echo arg(1) it outputs an integer
Comment: No, It will return menu callback's second part.
Answer: I'm using:
if ( preg_match('(^comment/reply/[0-9]*)', current_path())  === 1 ) {}
if ( preg_match('(^node/[0-9]*$)', current_path())  === 1 ) {}
if ( current_path() == 'search' ) {}

Using themename_preprocess_html, I think works fine. But I'm not sure if you need this exactly.
However, is an alternative.
Answer: hook_init() is best function to make changes at page level. You can use arg() function to get arguments of current page. Even you can also use menu_get_object() to get all possible values on rendered page.
Comment: hook_init() gets called for every non-cached request that Drupal handles, which isn't always an HTML page.  There are better options for pages, like `hook_page_build()`.


How to work out Effect Size for a MANOVA using G*Power

Question: I'm using G*Power to work out how many participants I need. I'll be using a MANOVA, I have two independent variables (Male and Female) and they will be answering 13 different questionnaires so 13 dependent variables.
I put this data into G*Power and its telling me I only need 14 participants but I think that is too small?
Answer: If you choose as test family F tests and as statistical test MANOVA: Global effects. You can choose as Type of power analyis A priori: Compute required sample size - given alpha, power, and effects size. Depending on the Effect size, alpha and power you would like to achieve you obtain the required sample size (with 2 for the number of groups, and 13 for the response variables). Of course the effect size, etc. are up to you to decide and should be based, among other things, on theory!
Comment: Hi all. Just asked a similar question (http://stats.stackexchange.com/q/263308/64052) about a MANCOVA and would appreciate your help.
Comment: Remember that the 438 means at least 219 (half) in each of the two groups.
Answer: G*Power defines a medium-sized effect with the same value of f-squared (.0625) used for a medium effect in univariate ANOVA.  However, Cohen suggested different benchmarks for MANOVA, with a medium-sized effect having an f-squared of .15. See Steyn, H. S., Jr. & Ellis, S. M.  (2009).  Estimating an effect size in one-way multivariate analysis of variance (MANOVA).  Multivariate Behavioral Research, 44(1), 106-129.


$_post retorna vazio, tentei de tudo, pessoal. Por gentileza, me ajuda

Question: Eu tenho esse problema e não consigo resolver, o form está correto mas quando o usuário clica no botão salvar, o arquivo salvar.php é acionado normalmente, mas perde o conteúdo do $_POST....Me ajudem!
arquivo index.php
<!DOCTYPE html>

            <form action="salvar.php" method="post">

                        Id
                        <input type="text" class="form-control" name="id" value="">

                        Código
                        <input type="text" class="form-control" name="codigo" value="">

                        Descrição
                        <input type="text" class="form-control" name="descricao" value="">

            </form>

            <button type="submit" onclick="salvar()">Salvar</button>
            <button type="button" onclick="fechar()">Cancelar</button>

No arquivo salvar.php eu leio a variavel $_post e o valor é vazio, como mostro no arquivo em anexo.
arquivo salvar.php
<!DOCTYPE html>

        <?php
            var_dump($_POST);
        ?>

Resultado:
C:\wamp\www\salvar.php:5:
array (size=0)
  empty
Eu não consigo resolver e já perdi o domingo inteiro.
Não troquei de versão de nada, nenhuma atualização.
Boa semana a todos e obrigado por dispensar seu tempo.
Comment: Vc quer usar Ajax pra isso?
Answer: O window.location.href apenas redireciona a página, não envia o fomulário. O ideal seria colocar o botão dentro do form, mas se quer chamar uma função pra isso, pode submeter o formulário com o método submit():
function salvar() {
   document.forms[0].submit();
}

Pode remover o type="submit" do botão porque não faz diferença se está usando o evento onclick:
<button onclick="salvar()">Salvar</button>

Comment: Muito Bom. Obrigado. Poucas pessoas querem ajudar os iniciantes como eu, poucos tem paciência com perguntas simples, mas para nós é uma resposta como a sua é de grande valia.Resolvido!
Answer: Do jeito que está fazendo é como se estivesse redirecionando para o salvar.php, o ideal seria usar o ajax para recuperar esses dados, ou usando o jquery ou qualquer outro cliente http, como o axios por exemplo.
Tente fazer algo assim, não esquecendo de chamar o jquery.
<!DOCTYPE html>

                <form action="salvar.php" id="form_exemplo">

                            Id
                            <input type="text" class="form-control" name="id" value="">

                            Código
                            <input type="text" class="form-control" name="codigo" value="">

                            Descrição
                            <input type="text" class="form-control" name="descricao" value="">

                </form>

                <button id="btn_salvar">Salvar</button>
                <button type="button">Cancelar</button>

Comment: Resolvido! Juntei as duas respostas e resolvei meu problema por aqui. Muito Obrigado viu Alexandre. Um dia vou ser a pessoa que responde aos iniciantes se Deus quiser. Obrigado e boa semana!
Comment: Pq o ideal seria usar Ajax? Não entendi.


Why merge statement inserts all the data into the target table each time it runs?

Question: I have these two table with same schema and records on different server and databases.
If the record in source table gets added or modified then it should be reflected in the target table as well but for some weird reasons it inserts all the rows in the target table each time.
I just want it to insert if new row gets added in the source or modified in the source.
Code:
MERGE INTO dbo.CountrySourceType AS target
USING (
                SELECT Id = Id * (- 1)
                    , Name
                    , (
                        SELECT Id
                        FROM country c
                        WHERE ISNULL(c.Name, '') = (
                                SELECT ISNULL(cs.Name, '') Name
                                FROM [192.xxx.x.xxx].WebPortal.dbo.Country cs
                                WHERE cs.Id = cst.CountryId
                                )
                            AND ISNULL(c.ContinentName, '') = (
                                SELECT ISNULL(cs.ContinentName, '') ContinentName
                                FROM [192.xxx.x.xxx].WebPortal.dbo.Country cs
                                WHERE cs.Id = cst.CountryId
                        )
                ) CountryId
                FROM [192.xxx.x.xxx].WebPortal.dbo.CountrySourceType cst
                WHERE CountryId = cst.CountryId
                ) AS source
                ON source.Id = target.Id
            WHEN NOT MATCHED BY target
                THEN
                    INSERT (
                        [Name],
                        [CountryId]
                        )
                    VALUES (
                         source.Name
                        ,source.CountryId

                        );

I tried it using the merge and narrowed down using the where clause but still it doesn't.
Comment: Seems like the merge's condition `ON source.Id = target.Id` isn't met, so it inserts new rows. Since you're not inserting any of the the source's `Id` values into the target table the target is probably using an identity column and the source and target have different values. This is made worse when you multiply the source's `Id` by `-1`.
Comment: @AlwaysLearning thanks a to. How do I get around this? like matching the Ids?
Comment: You need to provide sample data and desired results in order for us to understand what you are trying to accomplish.
Comment: In `FROM [192.xxx.x.xxx].WebPortal.dbo.CountrySourceType cst WHERE CountryId = cst.CountryId` which two (or is it one) `CountryId` values do you think it is comparing? Do you just want to check that `cst.CountryId` is not `NULL`?
Answer: Try to avoid MERGE. Generally, you may have performances issues (among the other issues). You can simply add the source in a temporary table and just perform the update and insert by yourself.
DROP TABLE IF EXISTS #temp_table;

SELECT Id = Id * (- 1)
      , Name
      , (
        SELECT Id
        FROM country c
        WHERE ISNULL(c.Name, '') = (
                SELECT ISNULL(cs.Name, '') Name
                FROM [192.xxx.x.xxx].WebPortal.dbo.Country cs
                WHERE cs.Id = cst.CountryId
                )
            AND ISNULL(c.ContinentName, '') = (
                SELECT ISNULL(cs.ContinentName, '') ContinentName
                FROM [192.xxx.x.xxx].WebPortal.dbo.Country cs
                WHERE cs.Id = cst.CountryId
                )
        ) CountryId

INTO #temp_table

FROM [192.xxx.x.xxx].WebPortal.dbo.CountrySourceType cst
WHERE CountryId = cst.CountryId

UPDATE dbo.CountrySourceType
SET name = B.name
   ,County_id = B.CountryId
FROM dbo.CountrySourceType  A
INNER JOIN #temp_table B
    ON A.[Id] = B.[Id];

INSERT INTO dbo.CountrySourceType ([Name],[CountryId])
SELECT A.name, A.CountryId
FROM #temp_table A
LEFT JOIN dbo.CountrySourceType B
    ON A.[Id] = B.[Id]
WHERE B.[Id] IS NULL;

INSERT INTO dbo.CountrySourceType ([Name],[CountryId])
SELECT A.name, A.CountryId
FROM #temp_table A
LEFT JOIN dbo.CountrySourceType B
    ON A.[Name] = B.[Name]
    AND A.[CountryId] = B.[CountryId]
WHERE B.[Id] IS NULL;

Comment: @tester sry, I have made a typo.  I have edited the initial solution, too.


Covariance of an exchangeable random vector

Question: I am trying to solve the next exercise but I don´t know how to start.
Let $X\in\mathbb{R}^n$ be a random vector which is exchangeable in the sense that $X$ has the same distribution as $(X_{\pi(i)})_{i=1}^n$ for any fixed permutation $\pi$ of $\{1,2,...,n\}$.
a) Show that the covariance matrix of $X$ equals $$\Sigma=\alpha I_n+\beta 1_n 1_n^T$$ for certain real numbers $\alpha,\beta$ where $1_n:=(1)_{i=1}^n$.
Actually, I don't understand how to start, I have the next things:
The covariance is given by
$$Cov(X,X)=\begin{bmatrix}{Var(X_1)}&{Cov(X_1,X_2)}&{\ldots Cov(X_1,X_n)}\\{Cov(X_2,X_1)}&{Var(X_2)}&{\ldots Cov(X_2,X_n)}\\{\vdots}&{\vdots}&{\vdots}\\{cov(X_n,X_1)}&{Cov(X_n,X_2)}&{Var(X_n)}\end{bmatrix}$$ Here I suppose that because the vector $X$ can be interchangeable  $Cov(X_1,X_2)=Cov(X_i,X_k)$ for any pair of value $i,k$, also I think that $Var(X_1)=Var(X_2)=...Var(X_n)$, however I don´t know how to prove that I am only supposing that because of the statement of the exercise, I ddon´t know how to proceed in a formal way.
Then I need to answer the next questions:
b) Under which conditions on $\alpha$ and $\beta$ is $\Sigma$ non singular? Show that, under these conditions, the inverse of $\Sigma$ is also of the type:
$$\Sigma^{-1}=\tilde\alpha I_n+\tilde\beta 1_n 1_n^T$$ for some $\tilde \alpha ,\tilde\beta$
Comment: Intuitively: $\mbox{Cov}(X_i,X_j)=\mbox{Covariance}(X_1,X_2)$ from exchangeability.
Comment: Hint: let $\alpha=\operatorname{Var}(X_1) - \operatorname{Cov}(X_1,X_2)$ and $\beta=\operatorname{Cov}(X_1,X_2)$. Everything else is straightforward algebra, so just do the calculations.
Answer: From exchangeability of $X=(X_1, \dotsc,X_n)$ it follows that all the $X_i$ has the same marginal distributions, so in particular, the same variance (assuming existence). So the diagonal of the covariance matrix must be constant.
Likewise, from exchangeability all pairwise joint distributios $(X_i,X_j), i\not=j$ must be equal, so the off-diagonal elements must all be equal.


Vue js v-autocomplete does not update dynamically changed items correctly

Question: I'm trying to integrate a v-autocomplete select form with dynamically loaded items in my Vue component based on text input. The data for the items is obtained from a http get and is tested to be correct. At first, the items appear to be fine, but once I further specify my input I start getting zero items within the component although the received data contains more than zero entries. I've been stuck at this for the last few hours, so help will be appreciated! :-)
Below I've listed the relevant parts of the code and two images which illustrate the issue. Above the text input field I have printed out the first match of the inputs, which at the second photo are missing. I think there is something wrong with the v-autocomplete component but can't figure out what.

{{locations[0]? locations[0].name : null}}

<v-autocomplete
    item-value="osm_id"
    v-model="selectedLocationIndex"
    item-text="name"
    label="Location*"
    :items="locations"
    :search-input.sync="locationInput"
    placeholder="Start typing..."
    required
>
    <template slot="item" slot-scope="data">
         {{ data.item.name }}
    </template>
</v-autocomplete>

This is the rest of the code:
watch: {
    locationInput: function(newVal, oldVal) {
        this.locations = [];
        if (newVal !== null && newVal !== '') {
            this.getLocations(newVal).then((result) => {
                const hits = result.data.hits;
                hits.map(hit => {
                    this.locations.push(hit)
                })
            }).catch((err) => {
                console.log('we have obtained an error', err)
            });
        }
    }
}

And here are the two images:
Here it works -> https://i.stack.imgur.com/YyEIB.jpg
Here it doesn't -> https://i.stack.imgur.com/Rewmj.jpg
Comment: Turns out adding the "no-filter" property solves it :-)
Comment: Yes it helped setting the "no-filter"! maybe you should set that as the correct answer :-)
Comment: Can you reproduce it with codesandbox or codepen?
Comment: @AdamOrlov I included the codesandbox in the description
Answer: Add the no-filter property.

{{locations[0]? locations[0].name : null}}

<v-autocomplete
    item-value="osm_id"
    no-filter
    v-model="selectedLocationIndex"
    item-text="name"
    label="Location*"
    :items="locations"
    :search-input.sync="locationInput"
    placeholder="Start typing..."
    required
>
    <template slot="item" slot-scope="data">
         {{ data.item.name }}
    </template>
</v-autocomplete>


How to make an array then accessing its elements as reference using C#?

Question: I am working on a project using C# windows forms.
I want to change a Label.Text by putting it in array then i want to access this labels by the array and change its text.
I tried to do this but it isn't working.
<code>int*[] Labels = new int*[30];
</code>
but this message appears:

pointers and fixed size buffers may only be used in unsafe context

So, any one can help?
I tried to make array of pointers then access it by reference but can't do it?
Comment: *"I want to change a Label.Text by putting it in array then i want to access this labels by the array and change its text."* your code example does not show you using the `Label.Text` anywhere. Perhaps you are wanting to do [Binding](https://msdn.microsoft.com/en-us/library/ef2xyb33(v=vs.110).aspx) so you can have the labels update automatically when some other variable updates.
Comment: OK, exactly this what i want thanks alot
Answer: In c# you are not allowed to work with pointers usually, but if you want to , you have to use unsafe block.
That is you have to put code that does pointer manipulations inside the unsafe block.
eg:unsafe{code....}
For more info : unsafe code
In visual studio you also have to go to the project settings and enable unsafe code.


shell method not giving right answer

Question: The soot produced by a garbage incinerator spreads out in a circular pattern. The depth, $H (r)$, in millimeters, of the soot deposited each month at a distance $r$ kilometers from the incinerator is given by $H (r) = 0.116 e^{-1.5 r}$.
I'm supposed to get the integral? I found that
integral from $0$ to $5$ is $2pi*r*0.116*e^{(-1.5*r)/1000000}$ km$^3$ …Unit and I have to include the units along with my answer which keep giving me wrong.
I have tried Km$^3$, m$^3$, mm$^3$ and it's all wrong
Can anyone help with it?
Comment: First, what question were you asked? The volume? The average depth? Second, this is not a shell method problem, it is integration in polar coordinates.
Comment: Write a definite integral (with independent variable r) giving the total volume of soot deposited within 5 kilometers of the incinerator each month.
volume. That's the question
Answer: Better keep $r$ in kilometers as in the problem statement--and therefore you must not put a conversion factor into the exponent of $e.$ The exponential should be $e^{-1.5r}$ with nothing else in the exponent.
To make units of height and width consistent so that you can measure the volume
in $\mbox{km}^3,$
you could observe that
$H(r) = 0.116 e^{-1.5 r}\, \mbox{mm} =  (0.116 \times 10^{-6}) e^{-1.5 r}\, \mbox{km}.$
If you would rather the answer be in $\mbox{mm}^3,$
you can make a substitution, $r =10^6 u,$ so that $r\, \mbox{km} = u\, \mbox{mm}.$
Just make sure to follow all the usual rules of substituting a variable in
a definite integral.

shell method not giving right answer


What does this notation mean p(x|y)?

Question: I was reading through a paper, when I encounter p(a|s). What does this mean? It was in context with log probability but I cant find this notation anywhere.
Comment: The probability of event $a$, given that event $b$ occurs. For example, when rolling a die, $P(X\text{ is even}\mid X\text{ is prime})=\frac13$
Comment: Specifically $P(A\mid B) = \frac{P(A\cap B)}{P(B)}$.  See [wiki](https://en.wikipedia.org/wiki/Conditional_probability).
Comment: Usually that notation is used for conditional probabilities.  It is the likelihood of event $a$ happening, given that we know $s$ about it.
Comment: @Miemels, feel free to answer your own question, now that you know the answer!
Comment: I will add that $p(x\mid y)$ is too often used as shortened for $p_{X\mid Y}(x\mid y)$, especially in engineering and physics texts. $~$ In such case it usually means conditional probability *mass* function, which equals $\mathsf P(X=x\mid Y=y)$.  $~$ ( Only occasionally is $p$ used to represent a probability *density* function. )
Answer: That is standard notation for conditional probability.
See here for example for further information.
Answer: The notation P(x|y) means P(x) given event y has occurred, this notation is used in conditional probability.
There are two cases if x and y are dependent or if x and y are independent.
Case 1) P(x|y) = P(x&y)/P(y)
Case 2) P(x|y) = P(x)
Comment: Indeed, the "second case" is just a simplification; because independence means that $\mathsf P(x \& y)=\mathsf P(x)\cdot\mathsf P(y)$ .
Comment: "There are two cases if x and y are dependent or if x and y are independent" Actually there is only one case, when P(x|y) = P(x&y)/P(y).
Answer: Like everyone else said, it's just notation for conditional probability. Here is the textbook that I used last semester in my probability class. Flip to page 141 and you can read all about the conditional probability, both in discrete and continuous cases.

What does this notation mean p(x|y)?


Geometric question

Question: solve:
I tried dropping the projections from I to the three sides, from here it's clear that the area of the triangle is $rs$ where $s$ is the semiperimeter and $r$ the inradius.
But by Heron's formula the area is just $80 \sqrt{12 383}$. We can then find:
$$r=20 \sqrt{\dfrac{203}{61}}.$$
Then I got stuck, I was trying to get the ratio of the similarity between MAN and BAC but I have been unable to do so.
Thanks for the help
Answer: Given that $P_A$ is the intersection between $AI$ and $BC$, then $\triangle AMN$ and $\triangle ABC$ are similar, and the ratio between the two perimeters is just $\frac{AI}{AP}$. Using Van Obel's theorem and the bisector theorem we have:
$$\frac{AI}{IP}=\frac{AP_C}{P_C B}+\frac{AP_B}{P_B C}=\frac{AB+AC}{BC},\tag{1}$$
where $P_B$ and $P_C$ are the feet of the angle bisector on $AC$ and $AB$. Now $(1)$ gives:
$$\frac{AI}{AP}=\frac{AB+AC}{AB+AC+BC}\tag{2}$$
hence the perimeter of $\triangle AMN$ is just $AB+AC = 272$.
We can achieve the same by proving that $\triangle MIB$ and $\triangle NIC$ are isosceles triangles.
Comment: An upvote would not be offensive ;)

Geometric question


Is a covering map on compact metric space, $k$ - to- $1$ at all points?

Question: Let $X$,$Y$ be topological space, surjective map
$\varphi:X\rightarrow Y$ is called a covering map if there is an
open cover $\{U_{\alpha}\}$ of $Y$  such that for every $\alpha$,
$\varphi^{-1}(U_{\alpha})$ is a disjoint union of open sets in $X$,
each of which is mapped by $\varphi$ homeomorphically onto
$U_{\alpha}$.
Question. Let $X, Y$ be compact metric spaces,
Is there is $k$ such that $\varphi$ is $k$- to- $1$ at all points?
Comment: Well, it is definitely false if you don't assume some connectedness.
Comment: If you assume that X is pathconnected, then it is true. The compactness gives you the finiteness of the fibre.
Comment: @ShubhodipMondal Given that they're metric spaces, just connectedness is enough.
Comment: I think in any case, as far as this result is concerned, connectedness alone is enough?
Comment: @ShubhodipMondal If you mean connected+compact, as opposed to path-connected+compact, then yes. If you mean connected _without_ compactness then it seems to me yes, if you allow $k$ to be an infinite cardinal: It's still true that for every $k$ the set of $x$ with a fiber of cardinality $k$ is open, and since this holds for every $k$ it's also closed.
Comment: Is the metric space assumption necessary? We can cover $Y$ by $U_i$ 's such that $\varphi ^{-1} (U_i)$  is a disjoint union and then cover $X$ by $\varphi ^{-1} (U_i)$. Since $X$ is compact, this has to have a finite subcover. But that gives finiteness of the fibres.
Comment: I meant to say that cover $X$ by the various disjoint sets appearing in $\varphi ^{-1}( U_i)$ for all $i$.
Comment: I am asking this because you wrote "*Given that they're metric spaces*, just connectedness is enough"
Comment: @ShubhodipMondal (power failure) Seems right - I said "metric" just because I hadn't thought about the general case, didn't want to tell any lies. (Speaking of which I just noticed I've had $X$ and $Y$ switched throughout all this, in case that makes anything I said make more sense...)
Answer: Obviously not if $Y$ is not connected; you could have a covering of this part of $Y$ that simply has nothing to do with a covering of that part of $Y$.
Yes, if $Y$ is connected. First you have to show that the inverse image of each point is finite (hint: If $x_j\ne x_k$ for $j\ne k$, $\phi(x_j)=y$ for all $j$ and $x_j\to x$ then $\phi$ cannot be a covering map).
Now for every $k$ the set of points of $Y$ that have exactly $k$ inverse images is open. Since this set is open for every $k$ it follows that it is closed...
Answer: This is not true if $X$ is not connected. But is true if $X$ is connected since the function $g$ defined on $X$ such that $g(x)$ is the cardinal of the fiber of $x$ is continuous.
Comment: Well, I think you should mention that the "cardinal" is finite because of compactness.
Answer: If you assume everything is connected and compact then the fiber over any point $y\in Y$ is given as the orbit of the deck-group transformation which is discrete and hence finite.


Dúvida sobre a conexão LDAP + php

Question: estou criando uma classe para autenticação LDAP para integrar com apps intranet, como gerador de protocolo, etc.
1- Após efetuar o ldap_bind() e conectar o usuário, existe alguma persistência desta autenticação? Existe a necessidade de encerrá-la com ldap_close() quando o usuário sair ou deslogar?
Bônus: As vezes, mais de um usuário utiliza o mesmo computador, porém em logins diferentes, como poderia gerenciar estas autenticações para que elas ficassem armazenadas durante determinado período?
Answer: Tudo depende. Digo isso porque eu não sei como sua empresa usa o LDAP. Algumas empresas usam o LDAP só como árvore de diretórios onde mantém sua estrutura, colaboradores e alguns atributos de tal como nome, alguns grupos, etc... Usado preferencialmente para logins nas estações de trabalho.
Outras empresas no entanto usam mais profundamente o LDAP gerenciando boa parte de informações dos colaboradores, estruturas hierarquicas complexas da própria empresa, árvore de permissões para acesso a sistemas e áreas restritas da empresa, controle de acesso em catracas e por aí vai. Ou seja, no mercado por aí há usos e mais usos do LDAP.
Dito isso, acho que posso prosseguir com a resposta a sua pergunta.
Se você for só autenticar o usuário...
Se sua empresa apenas autentica usuários, então você só vai tentar fazer o bind no servidor usando usuário e senha de quem quer acessar a aplicação. Se o servidor LDAP recusar o bind, o usuário e senha estão errados e você informa o usuário sobre o falha na autenticação, fecha a conexão e um abraço.
Se você for autenticar e recuperar algumas propriedades do usuário...
Bom, se sua empresa guarda algumas informações do usuário no LDAP, como matrícula, líder (ou gerente), telefone... Você pode recuperar essas informações do LDAP e mostrar no seu sistema. Então aí você precisará saber um pouco sobre a sintaxe de busca de LDAP.
Com informações recuperadas do LDAP, você também pode integrar sua aplicação com outros sistemas (se possível) como RH, ERP e por aí vai.
Nessa caso, você faz o bind, recupera a informação, salva essa informação em sessão (ou persiste) e então você pode fechar a conexão com ldap.
Se você precisar recuperar permissões de acesso...
Nessa caso, depende do seu sistema. Se você precisará recuperar papel e permissão do LDAP para cada usuário que acessa sua aplicação e verifica se esse usuário pode ou não acessar determinada funcionalidade do seu sistema, você aqui, até poderia manter a conexão aberta com o LDAP e fecha-la após o usuário fazer o logout.
Aqui, suas consultas ap LDAP poderão ser mais frequentes, por isso voce poderia manter a conexão aberta se não quiser salvar as permissões do usuário na sessão.
Respondendo diretamente suas perguntas

Após efetuar o ldap_bind() e conectar o usuário, existe alguma
  persistência desta autenticação? Existe a necessidade de encerrá-la
  com ldap_close() quando o usuário sair ou deslogar?

Eu só trabalhei com o AD (active Directory) da Microsoft. E nesse caso eu não vi ele persistindo nada lá quando fazemos bind nele em nossas aplicações. Todo esse controle é feito internamente na minha aplicação. Para nós, o LDAP é apenas um flag de login com sucesso true ou false. E também recupero algumas coisas, nada mais que isso.
Mas acredito que seja uma boa prática encerrar a conexão, assim como existe o fechamento de conexão com banco de dados, como streamings...

As vezes, mais de um usuário utiliza o mesmo computador, porém em
  logins diferentes, como poderia gerenciar estas autenticações para que
  elas ficassem armazenadas durante determinado período?

Esse controle é sua aplicação que faz, não o LDAP. Ambos o usuários precisarão digitar usuário e senha na sua aplicação e sua aplicação gerencia o resto. Como disse na resposta acima, o LDAP apenas responderá true ou false para você em uma combinação login e senha. O resto, é por sua conta.
Comment: Ricardo, sanou completamente minhas dúvidas, vou recuperar algumas informações sim, como email, vou aplicar o ldap_read() com filtro, muito obrigado!

Dúvida sobre a conexão LDAP + php


Linux Firewall authentication based on MySQL?

Question: I have a linux server that many users connect to. I use Squid for http access but I need a software that can grant access control to different ports based on a MySQL database.
IPtables is great but I need something that will work with MySQL and grant control based on certain IF conditions.
Thanks
Comment: Have you thought about the performance issues of trying to do this?  Do you really want a mysql query run for every single packet?
Comment: Can you go into a bit more detail about what kind of authentication you are trying to implement?
Comment: It's a very simple one: IP authentication. I know IPtables allow you to set a range of allowed IP addresses. I need to do the same thing but based on a list of ip addresses in a database. In a sense, the authentication won't be done here. I just need an access control to do some Mysql query "query IP_list, if allow_IP exists, allow access; else Deny."
Comment: You are right. Is there any way to do a transparent SOCKS proxy?
Answer: iptables permits you to do special processing per packet, by assigning the packet to the QUEUE chain; each packet must then be processed by a userland program that will decide the fate of the packet (Accept, drop, et-cetera).  Writing such a handler is described here: http://imchris.org/projects/libipq.html.  Because this technique involves making a routing decision per-packet in userland; it may have some serious throughput implications.  If possible, you really should consider using ErikA's suggestion of just writing a script that manages rules as needed.
Answer: IPtables/netfilter is your only option. What you'll need is some custom script that manages netfilter rules according to information in your database.
I know of nothing that can do this out of the box. You'll likely need to roll this one yourself.
Comment: Thanks Erik. My question is how to make Iptables work with MySQL. Is there a plugin?
Comment: Not that I know of, and even if there were, it would likely require a large amount of customization to get it to fit your needs.


hook_preprocess_html in my module

Question: I am having a content type with fields select list, js, css, and body. In the select box it list a number of templates to apply on the current node. I have these custom templates in the templates folder of the active theme, in the format my-module-blank.tpl.php, my-module-custom1.tpl.php
And on select list I have blank and custom1 as options. In the hook_preprocess_node, using theme_hook_suggestions I have did the same,
  $variables['theme_hook_suggestions'][] = 'my_module_' . $field_template_list;

But it is not taking the template, In addition I need to use hook_preprocess_html
to include the custom css and js added to fields of content type to the header portion. I didn't find any proper documentation on it.
Please show me a better documentation so that I could implement.
Comment: Have you tried clearing cache?
Comment: @SumitMadan I wanted to know what is the purpose of html preprocess, would you mind providing a link to a good documentation on it.
Answer: hook_preprocess_page() is called before hook_preprocess_html(). hook_preprocess_html() would probably be the last one that's run in a page build.
If you want your CSS and JavaScript when displaying a node, you can add the files it in the preprocess function for the node template.
function THEME_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full') {
    $node =& $variables['node'];
    if ($node->type == 'something') {
      $path = drupal_get_path('theme', 'THEME');
      drupal_add_css($path . '/misc/jquery.fancybox-1.3.4.css');
      drupal_add_js($path . '/misc/jquery.mousewheel-3.0.4.pack.js', array('type' => 'file', 'scope' => 'header'));
      drupal_add_js($path . '/misc/jquery.fancybox-1.3.4.pack.js', array('type' => 'file', 'scope' => 'header'));
      drupal_add_js($path . '/misc/jquery.fancybox-calls.js', array('type' => 'file', 'scope' => 'header'));
    }
  }
}

You can add a custom template for any content type like:
node--[node-type].tpl.php

I would suggest you to use hook_preprocess_page at template.php for this:
function MYTHEME_preprocess_page(&$variables, $hook) {
    if (isset($variables['node'])) {
        if ($variables['node']->type == 'something') {
            $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->type;
        }
    }
}

Note: Don't forget to clear your cache after this :)

hook_preprocess_html in my module


Azure DevOps Pipeline - React Js application build was failing during build (npm run build)

Question: I was using vmImage: ubuntu-latest. Getting many errors during build (npm run build) such as:
ERROR in ./src/components/*********/testCard.scss
Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleNotFoundError: Module not found: Error: Can't resolve './green.png' in '/home/vsts/work/1/s/web/src/components/testCard'
Answer: All these run errors during build due to referred components are case sensitive when we use vmImage: ubuntu-latest.
To avoid those build errors, use vmImage: macOS-10.15 or latest macOs.
Comment: Case sensitive was exactly the problem, and I couldn't get it locally because I was running on a Windows machine.


Search input center header and button with Bootstrap 5

Question: I am trying to build a simple search page, but I am having a hard time getting the elements aligned properly.

I would like to have the company name centered over the search input and I would like to have the buttons centered under the search input with a little spacing between them.

Company Name

            <input class="form-control py-2 rounded-pill mr-1 pr-5" type="search" placeholder="Search for your organization" id="example-search-input">

                <button class="btn rounded-pill border-0 ms-n5" type="button">

                </button>

            Players

            Organizers

Any help would be appreciated
Answer: Try this :
I just replaced below code
align-content-center to text-center

 to

 and

Company Name

 to

Company Name

<!DOCTYPE html>

  <title>Bootstrap 5 Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://email@example.com/dist/css/bootstrap.min.css" rel="stylesheet">

Company Name

            <input class="form-control py-2 rounded-pill mr-1 pr-5" type="search" placeholder="Search for your organization" id="example-search-input">

                <button class="btn rounded-pill border-0 ms-n5" type="button">

                </button>

            Players

            Organizers


Why is the kernel of $\phi : G\mapsto S_m$ included in $B\le G$ where $\phi(g)=g:xB\mapsto gxB$?

Question: Let $G$ be a group with $B$ a subgroup of index $m$. There is a homomorphism that associates each element of $G$ to a permutation of the left cosets $xB\in G/B$, which is of cardinality $m$.
So these permutations live in $S_m$.
Why is the kernel of that homomorphism included in $B$?
$$\ker\phi=\{g\in G~:~gxB=xB \text{ for all } x\in G\}=\dotsb= \bigcap\limits_{g\in G}gBg^{-1}$$
I don't see why that is a subset of $B$...
Answer: Because take $g=e$ and you will get that $B$ is one of the groups in the intersection. Hence $B$ contains the intersection.


Why can't I successfully send the array via the POST method in Express?

Question: I'm new here and I'm learning Express, although I think I'm on the right track, I'm currently having some problems with the POST method. What happens to me now is the following:

When I send a POST request to an http file, I receive an empty object {}. Also, I have done tests through Thunder client but, I receive a 400 error or another http error,

Doesn't work Content-Type: application/json below path in method in http file,

GET method works fine,

This is the code I've been working with:

const express = require('express');
const { stories } = require('../data/books.js').infoBooks;

const routerStories = express.Router();
routerStories.use(express.json());

routerStories.post('/', (req, res) => {
    const newBook = req.body;
    stories.push(newBook);
    res.send(JSON.stringify(stories));
});

I've been trying to solve it for several days. And though, I've done quite a bit to research, I haven't been able to figure it out.
Please, I'd greatly appreciate your perspective and experience to be able to finish resolving this situation.
Answer: I see a few things wrong here with your code. Im going to assume you pasted the code as is so here is what you need to change.
1.) I don't think this line here is valid javascript or if it is its a bit strange. const { stories } = require('../data/books.js').infoBooks; if infoBooks is an object that contains stories just import the object
2.) you shouldn't need to set the router as json as the method exists on the router by default and will accept json as a valid response
3.) its possible you are not using a different route name and another route is using the same string literal.
You have not provided enough information so there could be another issue with how you are using the router itself but from what you have posted these are all the issues I have identified. hope it helps!
import {infoBooks} from "../data/books.js"
import express from "express";
const router = express.Router();

routerStories.post('/createNewBook', (req, res) => {
    const newBook = req.body;
    if(!newBook){
       res.status(400).json({message: "invalid arguments"})
       return
    }
    infoBooks.stories.push(newBook);
    //we don't need to set status here because by default the response will be 200
    res.json({infoBooks.stories});
    return
})

Comment: Hi JSON Derulo,
• I'm using "const { stories } = require('../data/books.js').infoBooks;" to tell it to express where is the body structure that I need to extract to run the POST request and where is the database. Also, without that, the GET method didn't work (well, whomever I learned this structure from, it worked perfectly).
• Within the database I have different genders and, in the same way, I have routers in the Routers file.
• Anyway, I'm going to try the code you give me. I'll be updating you with progress.
Thank you very much.

PDT. Quite a name: "JSON Derulo", Nice!
Comment: then you should be exporting it like this
```
export const infoBooks = {stories: []}
//or
export {
infoBooks
}
```
Comment: Hi @JSON Derulo, The test with the code you gave me had a negative result. This is the output the terminal shows me: " [nodemon] app crashed - waiting for file changes before starting... "


Knockout.js: conditionally bind title attribute of div

Question: I have a viewModel on my page that holds the data for an overview of current states of some devices. So far everything works great except for one issue: I need to set the title attribute of a div element depending on another value in my viewModel.
I know that you can basically set the title attribute like this (within the data-bind attribute of the div tag):
attr: { title: 'Some title' }

Using the statement above, "Some title" gets set as tooltip when hovering the div.
I can also set this:
attr: { title: ConnectState.Value() }

and it outputs the correct value (an integer value) of my current viewModel data, so the viewModel gets populated correctly.
Now I need to change this to something like that:
attr: {
  title: {
    'Text 1': ConnectState.Value() == 0,
    'Text 2': ConnectState.Value() == 1,
    'Text 3': ConnectState.Value() == 2,
    'Text 4': ConnectState.Value() == 3
  }
}

The example above will only give "[object Object]" as title (resp. as tooltip). How can I fix that?
Thanks a lot in advance!
Comment: Why don't you write `attr: { title: 'Text ' + (ConnectState.Value() + 1) }` Or your actual text is more complicated than your example?
Comment: Unfortunately, it is. The value of ConnectState is an enum that translates into "connected", "disconnected", "connecting" etc.
Answer: Define a ko.computed in your viewmodel.
self.ConnectTitle = ko.computed(function() {
   return 'Text ' + (self.ConnectState.Value() + 1).toString();
});

Then:-
attr: { title: ConnectTitle }

As your binding.  You can replace the contents of the computed's function with something that'll suit your needs, if your text was just a simple example.
Comment: Each of your rows is represented by an object, correct?  Post your Javascript view model and we'll take a look.
Comment: Thanks for your suggestion. The title attribute I need to set exists in a data-bound table row:  So I have to apply this ConnectTitle function to every item in my viewModels "Rows" collection, which is dynamically, depending on the page. I couldn't figure out how to achieve that.
Answer: You can use ternary operator, something like this:
attr: {
  title: ConnectState.Value() == 0 ? 'Text 1' :
         ConnectState.Value() == 1 ? 'Text 2' :
         ConnectState.Value() == 2 ? 'Text 3' :
         'Text 4'
}

Comment: That's elegant! Never used a ternary like this.


Erro ao passar props com objetos literais via v-bind="object"

Question: No Vue é descrito na documentação que se deseja passar todas as propriedades de um objeto via props é possível passar o mesmo da seguinte forma
# data do componente
post: {
  title: 'Título da post',
  content: '...'
}

# template

<blog-post v-bind="post"></blog-post>

Testei essa abordagem mas recebo um erro. Eis meu código:

const blogPost = {
    props: ['post'],
    template: '\

\

{{ title }}
\

{{ content }}
\

'
};

const app = new Vue({
  el: '#app',
  data: {
    post: {
      title: 'Minha jornada com Vue',
      content: '...'
    }
  },
  components: {
    'blog-post': blogPost
  }
});

  <blog-post v-bind="post"></blog-post>

# Erro

title is not defined

Answer: Ao dar o v-bind você deve apontar a prop que deseja atribuir, e na interpolação usar a prop como objeto...

const blogPost = {
    props: ['post'],
    template: '\

\

{{ post.title }}
\

{{ post.content }}
\

'
};

const app = new Vue({
  el: '#app',
  data: {
    post: {
      title: 'Minha jornada com Vue',
      content: '...'
    }
  },
  components: {
    'blog-post': blogPost
  }
});

  <blog-post v-bind:post="post"></blog-post>


Erro ao referenciar valor de um objeto em outro objeto javascript

Question: Tenho a seguinte variável com vários objetos dentro:

const dados = {
  estudouNaFaculdadeAno: {
    metricas: {
      ano: [],
      invalido: {
        num: 0,
        palavras: []
      }
    }
  },
  estudouNaFaculdadeCurso: {
    metricas: {
      curso: {
        ads: 0,
        grh: 0,
        gpi: 0
      },
      invalido: {
        num: dados.estudouNaFaculdadeAno.metricas.invalido.num,
        palavras: dados.estudouNaFaculdadeAno.metricas.invalido.palavras
      }
    }
  }
}

Ao executar um console.log(dados) eu recebo o seguinte código de erro:
Uncaught ReferenceError: Cannot access 'dados' before initialization at dados.js:550
Alguém poderia me ajudar a entender o pq disso? Como faço para ele referenciar sem ter esse problema?
PS.: esse arquivo dados.js contém somente a constante dados com os valores a serem lidos por outras funções que estão em outros arquivos .js
Answer: Você está referenciando o objeto dados dentro dele mesmo. Irá resultar no erro porque a variável dados ainda não foi inicializada. Ao tentar construir o objeto, o JavaScript irá tentar buscar o valor de dados.estudouNaFaculdadeAno.metricas.invalido.num, porém esse valor está dentro do próprio objeto que ainda está sendo construído, ou seja, ele ainda não foi inicializado.
Você pode usar um getter para retornar esses valores dentro do próprio objeto:
Em vez de:
invalido: {
   num: dados.estudouNaFaculdadeAno.metricas.invalido.num,
   palavras: dados.estudouNaFaculdadeAno.metricas.invalido.palavras
}

Use:
get invalido(){
  return {
     num: dados.estudouNaFaculdadeAno.metricas.invalido.num,
     palavras: dados.estudouNaFaculdadeAno.metricas.invalido.palavras
  }
}

Veja o resultado:

const dados = {
  estudouNaFaculdadeAno: {
    metricas: {
      ano: [],
      invalido: {
        num: 0,
        palavras: []
      }
    }
  },
  estudouNaFaculdadeCurso: {
    metricas: {
      curso: {
        ads: 0,
        grh: 0,
        gpi: 0
      },
      get invalido(){
        return {
           num: dados.estudouNaFaculdadeAno.metricas.invalido.num,
           palavras: dados.estudouNaFaculdadeAno.metricas.invalido.palavras
        }
      }
    }
  }
}

console.log(dados.estudouNaFaculdadeCurso.metricas.invalido);
Comment: Opa, você me deu uma luz e tanto @Sam ! Muito obrigado pela ajuda :)
Answer: Revise a estrutura que você está utilizando.
Há duas referências circulares no seu json:
num: dados.estudouNaFaculdadeAno.metricas.invalido.num,
palavras: dados.estudouNaFaculdadeAno.metricas.invalido.palavras
Insira valores JSON válidos, como por exemplo:
num: 1234,
palavras: "palavras jogadas ao vento!"
Então o valor para o caminho JSON dados.estudouNaFaculdadeAno.metricas.invalido.num será 1234.
Comment: Então, mas o q eu quero é justamente pegar um dado de outro objeto. Fazendo da forma q tu disse eu teria valores fixos no `num` e `palavras` do objeto `estudouNaFaculdadeCurso`


Storing a hexadecimal string without using arrays in C

Question: Our school gave us an assignment and in some part of that assignment we are supposed to take a hexadecimal input then convert it to binary. But the problem is that using arrays are not permitted. When using an array to store the hexadecimal string I can easily convert it to binary but is there anyway to store it without using arrays?
Comment: dynamic memory allocation?
Comment: When someone is telling me "take hexadecimal and convert to binary" I am getting really suspicious that actually nothing needs to be done here. So please, describe your problem in more detail.
Comment: what we need to do is get a hexadecimal input from the user and convert it to binary letter by letter then use that binary for a XOR operation. I am quite new to C so to do that operation I feel like I need to assign those binary numbers to a variable to use it in a future operation.
Comment: Is there a "binary" somewhere in the input or output? If not, this conversion step is most likely unnecessary. Computer can perform binary operations on *numbers* regardless of their representation to the user. What is your input? What is your required output?
Comment: our assignment says that we must take hexadecimal input from the user, conver it to binary, and use that binary for encryption with XOR logic(a key is selected prior to this operation). But xor operation provided in the C is also not permitted to use. So I need to do the conversion in order to pass it to the encryption.
Comment: No arrays yet required to convert data to a bit-stream? Hm. There must be some misunderstanding somewhere.
Comment: I need to access each letter or digit of the input one by one so don't I need to use an array for that? I'm sorry if I am not clear enough, I am way too new to C :)
Comment: This has nothing to do with C, most languages have the concept of arrays. An array is an indexed "collection" of equally typed elements. Any string is an array. -- Please show us some source code how you are supposed to do the encryption.
Comment: They didn't provide any source code but I can send you the assignment explanation.
Answer: Your task seems to be:

Convert input data entered as hexadecimal values to a stream of binary digits.

You can just read the input ne byte at a time and convert any hexadecimal character to the corresponding binary digits.
There are many different ways to approach this problem, here is an implementation with a switch statement.
#include <stdio.h>

int main() {
    int c;

    while ((c = getchar()) != EOF) {
        switch (c) {
          case '0': fputs("0000", stdout); break;
          case '1': fputs("0001", stdout); break;
          case '2': fputs("0010", stdout); break;
          case '3': fputs("0011", stdout); break;
          case '4': fputs("0100", stdout); break;
          case '5': fputs("0101", stdout); break;
          case '6': fputs("0110", stdout); break;
          case '7': fputs("0111", stdout); break;
          case '8': fputs("1000", stdout); break;
          case '9': fputs("1001", stdout); break;
          case 'A':
          case 'a': fputs("1010", stdout); break;
          case 'B':
          case 'b': fputs("1011", stdout); break;
          case 'C':
          case 'c': fputs("1100", stdout); break;
          case 'D':
          case 'd': fputs("1101", stdout); break;
          case 'E':
          case 'e': fputs("1110", stdout); break;
          case 'F':
          case 'f': fputs("1111", stdout); break;
          case '\n':
          case ' ': putchar(c); break;
          default:  break;
        }
    }
    return 0;
}

If you just need to read a value encoded as a hexadecimal string and store it into a variable, scanf() is a simple solution:
#include <stdio.h>

void print_binary(unsigned int x) {
    if (x > 1) {
        print_binary(x >> 1);
    }
    putchar('0' + (x & 1));
}

int main(void) {
    unsigned int value;

    if (scanf("%x", &value) == 1) {
        print_binary(value);
        putchar('\n');
    }
    return 0;
}

Comment: This is kind of what i needed but the only thing is, i actually need to store the printed binary value in a variable.
Comment: So you need to read a value encoded in hexadecimal, store it in binary into a variable? Do you need to print the value in binary or just store the value?
Comment: i just need to store the binary value
Comment: @STT: OK, no need to *convert it to binary.* then. You just want to convert to an integer. Numbers are indeed stored in memory as binary, but the conversion is independent of the internal representation. When you mention *convert it to binary.* many programmers will assume you want to output a binary representation.
Comment: thanks a lot. I can work my way through the second code. I understand the confusion. I will be more careful from now on :)


Checkboxes to select autogenerated methods, properties, etc

Question: In Eclipse, whenever I need to create something automatically (like delegate methods or similar), there is a checkbox beside each method thus making selection very precise and easy.
IntelliJ IDEA does not have such check boxes so we have to use CTRL or SHIFT button. Does such feature exist and how to turn it on? If not, where can we vote for it.
The main thing with IntelliJ IDEA (and the main reason people and myself like it) is the speed. In that respect, I was very surprised such way of selecting isn't the default one.
For better understanding of this issue, please look at the pic (IntelliJ IDE without check boxes).
Answer: Please vote for:

member chooser can be more keyboard friendly
Change the way to select fields to generate constructor/getters/setters...
Comment: The fastest way to get any feature implemented is to implement it yourself and attach a patch to the issue. This functionality in available in the Community edition of IDEA and you can grab the source code from git to add checkboxes and create patch.
Comment: How many votes you usually need to implement a certain feature?


Is coda the same thing as a cadence?

Question: So a coda is "the concluding passage of a piece or movement, typically forming an addition to the basic structure" (Oxford Languages). A cadence, according to Britannica, is the ending of a phrase.
I've seen some websites define a coda as a sort of "extended cadence", so are they basically the same thing then?
Comment: @OldBrixtonian - doesn't just about everything end in a cadence? Unless it fades out.
Comment: @user87626 Oh OK :)
Comment: Coda is Italian for "tail" btw - it's just the end after having repeated some sections of the piece ^^
Comment: You may be getting cadence conflated with cadenza. Similar in sound, but not the same. A cadenza is possibly closer to a coda.
Comment: Codas often end with a cadence. I don't think that makes them extended cadences though. Britannica's definition of cadence is OK as long as it says phrase and not phase.
Comment: @Tim - Well cadences and codas - and cadenzas, come to think of it - are more associated with music of the common practice period than with more recent 'classical' music.
Comment: @OldBrixtonian Britannica's definition was the ending of a phase, not a phrase
Comment: @user87626 I've never heard of a phase of music. What is it?
Comment: @OldBrixtonian sorry, i must have misread Britannica's definition. It definitely says "phrase"
Comment: @Tim "Cadenza" usually refers to the show-offy solo part near the end of a concerto movement.  It often ends in a cadence, and is followed by a coda.  Etymologically, they're the same word - "cadenza" is just Italian for "cadence", but in usage they differ slightly.
Comment: (Of course, in Schenkerian analysis, the whole piece is an "extended cadence"...)
Comment: Why do people keep downvoting my question? Can you guys please at least give feedback??
Answer:
I've seen some websites define a coda as a sort of "extended cadence"

Well, yes.  But very 'sort of'.   A cadence comes at the end of a musical phrase, a coda comes at the end of the whole piece.   And that's about as far as the 'sort of' goes.
Your question suggests that you're just looking at books (or websites :-), you've no actual experience of music that contains cadences and codas.   Here's a brief illustration.
Comment: Great illustration, you beat me to it. It could be nice to show also the notational meaning of "To Coda"  etc. which doesn't really care about what there is inside the coda, cadence or no cadence, it doesn't matter.
Comment: Yes, 'DS al Coda' often leads to something that isn't a Coda at all, in terms of musical form!
Comment: Really nice illustration. What software do you use, by the way?
Comment: @Aaron Sibelius
Answer: Think of a coda as being a part of a piece's formal structure while a cadence is more a part of the harmonic or melodic structure.
For example, take a basic song form — AABA — but now compose some additional material to form a sort of extended ending, or perhaps a musical commentary on the main body of the piece. The form is now AABA+coda. However, each of those sections of the piece could have its own cadence.
The key is Oxford's note that a coda is "an addition to the basic structure." Formally, with a coda, the piece could already have concluded, but the composer chose to add an extension or extra section "after the end", so to speak. Such additional material sometimes serves as an "extended cadence", prolonging what otherwise might be a quick ending.
A cadence typically refers to a smaller structure within the piece, forming moments of pause or separation between phrases or sections.
Answer: There can be lots of cadences in a piece, but only one coda. A coda may contain cadences, or it may contain none.
A cadence is a harmonic structure

the end of a phrase in which the melody or harmony creates a sense of
resolution.

https://en.wikipedia.org/wiki/Cadence
A coda is an ending part of a whole piece, and it can contain anything rhythmically, melodically and harmonically. Or even complete silence. In pop music it's an "outro".
https://en.wikipedia.org/wiki/Coda_(music)
The Wikipedia page says "Technically, it is an expanded cadence" ... Who writes this stuff. "Technically?" Maybe in old classical pieces, codas usually did something specific regarding harmony.
In music notation, a coda  is where you jump to finish off a song. "D.C. al Coda" means, repeat from the beginning, and when you reach the small coda sign, jump to the big coda sign.  https://en.wikipedia.org/wiki/Coda_(music)#In_music_notation
"See you at the Coda" is a musicians' saying. Saying "see you at the cadence" would be nonsensical, because there can be cadences all over.
There may be something in the coda section that you could call a cadence, or maybe not.
Codas are like what you get, when you press the Ending button on an arranger keyboard:

That particular coda i.e. ending seems to have lots of cadences programmed into it, but it wouldn't have to have any. It's just a break from the flow of the song, and it probably makes you get the idea that the song is going to end now. It's the opposite of an intro: an intro gets the song started and a coda gets it finished. One could say that a cadence, on the other hand, finishes off a harmonic phrase. But there are other dimensions to musical phrasing besides harmony, of course.
Comment: 'See you at the coda'  might mean 'Let's at least try to END together!'.   Or it might mean 'See you in the pub afterwards!'.   In which latter case the brass players might well manage to get one in at a cadence :-)
Comment: "Who writes Wikipedia?" (Do you really not know?) Anybody. So it doesn't say that "technically" bit any more, cuz I removed it.
Comment: @BrianChandler It was my way of reminding everybody that there is weird stuff there and you shouldn't take it at face value. It's actually fairly common thing to hear, that something "is technically" something, and when it comes to music, that's just rubbish. There's no "technical" anything involved. Whoever is saying that just cannot put that particular use of the word in perspective, or thinks that it is some kind of a universal rule. Or just never realized that there are multiple different uses for a word, among different groups of people, and that languages evolve
Comment: If I had actually been interested in finding who or what wrote that, I could have looked at the page edit history. But anyway, this "technically" thing has already been copied and distributed over many sites on the internet. A better explanation might say something about specific traditional or historical forms and practices in classical music. I'm not an expert on that, I cannot give those explanations, but I know the explanation is not something "technical".

Is coda the same thing as a cadence?


Score with snare on 3rd beat or on 2nd and 4th beats half speed

Question: I was making a 4/4 score for a bassist and it had 170 bpm with kick on first beat and snare on 3rd, he said he was used to having the snare on 2nd and 4th with half the bpm.  That was news to me, is there a best practice which to do? I'd rather do higher bpm and snare on 3rd, but also want to do way most people are used to. Thanks.
Comment: It's an instrumental world music song in rock/pop style with acoustic guitar and bass.
Answer: Yeah, in Rock the back beat is usually understood to be 2 and 4.
X: 1
L: 1/8
K: Cmaj
M: C
Q: 1/4=85
%% score (D1 D2)
V:D1 clef=perc
V:D2 clef=perc
% 1
[V:D1] ffff  ffff
[V:D2] F2 B2 F F B2

If it's on 3, this is called half-time feeling, which corresponds to the classical notion of alla breve
X: 1
L: 1/8
K: Cmaj
M: C|
Q: 1/2=85
%% score (D1 D2)
V:D1 clef=perc
V:D2 clef=perc
% 1
[V:D1] ffff ffff | ffff  ffff
[V:D2] F4   B4   | F2 F2 B4

...though if that's the groove in an entire piece, it's often common time with 16th on the Hi-Hat instead, so the back beat is again on 2 and 4.
X: 1
L: 1/16
K: Cmaj
M: C
Q: 1/4=85
%% score (D1 D2)
V:D1 clef=perc
V:D2 clef=perc
% 1
[V:D1] ffff ffff ffff  ffff
[V:D2] F4   B4   F2 F2 B4

Answer: The bass player is right (speaking as a drummer here).
As a conductor I'd also prefer to have the downstrokes of the baton land
on the bass on 1 and the snare on 2.
It's just the convention for modern pop/rock based music and the players of this style will focus on a strong bass on 1 and 3 and the drummer and rhythm guitar will bring out the 2 and 4.


WebView can't handle response when using a custom NSURLProtocol

Question: I'm using a custom NSURLProtocol in order to be able to save the username and password from a form that is loaded in a webView and automatically log the user in.
My issue is that I can get the data, but I can't complete the action to login the user as the webpage uses some JS to listen to the response and complete the form action.
Is there a way to do it?
Here's my current CustomURLProtocol class:
class CustomURLProtocol: NSURLProtocol {

    var connection: NSURLConnection!

    override class func canInitWithRequest(request: NSURLRequest) -> Bool {
        if NSURLProtocol.propertyForKey("customProtocolKey", inRequest: request) != nil {
            return false
        }
        return true
    }

    override class func canonicalRequestForRequest(request: NSURLRequest) -> NSURLRequest {
        return request
    }

    override func startLoading() {
        let newRequest = request.mutableCopy() as! NSMutableURLRequest
        NSURLProtocol.setProperty(true, forKey: "customProtocolKey", inRequest: newRequest)

        // Look for user credentials
        if request.URL?.description == "https://www.website.com/Account/Login" {
            if let data = request.HTTPBody {
                let dataString: String = NSString(data: data, encoding: NSASCIIStringEncoding) as! String
                // Code for reading user credentials goes here
            }
        }

        connection = NSURLConnection(request: newRequest, delegate: self)
    }

    override func stopLoading() {
        if connection != nil {
            connection.cancel()
        }
        connection = nil
    }

    func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
        client!.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: .NotAllowed)
    }

    func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
        client!.URLProtocol(self, didLoadData: data)
    }

    func connectionDidFinishLoading(connection: NSURLConnection!) {
        client!.URLProtocolDidFinishLoading(self)
    }

    func connection(connection: NSURLConnection!, didFailWithError error: NSError!) {
        client!.URLProtocol(self, didFailWithError: error)
    }
}

Is there something I'm missing or is wrong in my logic?
Thanks in advance
Answer: So if I understand correctly, you're intercepting the call just to preserve the credentials so you can log the user in automatically later? If you only care about the login request you could move the url check to canInitWithRequest, but that's a side issue.
Using a custom NSURLProtocol correctly shouldn't affect the response, so the web page should behave normally. I notice that you're using NSURLConnection, which is deprecated, so you might want to look at using NSURLSession but again that's a side issue.
Have you stepped through the code to see where it's failing? Are your connection delegate methods being called? Is "webViewDidFinishLoad" being called on the web view?
Or are you not talking about the initial form submission, but subsequent ones when you're trying to log in the user with the stored credentials?
Comment: First of all, I have also to support iOS 7, so that's why I'm using 'deprecated' methods.
Second, the request is made through AJAX and, for that reason, it does not go through my delegate. That's why I'm trying to use a custom `NSURLProtocol`.
Does that help?
Comment: NSURLSession was released in ios7.
Comment: Anyway, it does help a bit, but it's not clear to me which part is failing. are you saying that when you intercept the request, the response isn't returned? Or that the response is invalid so the web page doesn't react? If the former, can you see it hitting the right NSURLProtocol methods? If the latter, can you validate the response is correct?


How to integrate $\int_0^\infty \frac{(x^2+a)^n}{(x^2+b)^m} \>\text{d}x$?

Question: How to integrate this guy:
$$\int_0^\infty \frac{(x^2+a)^n}{(x^2+b)^m} \>\text{d}x,$$
where $a,b,n,m$ are positive integers, and $n<m.$
Thank you in advance. :)
Comment: I do not understand why my comment has been removed. That integral can, indeed, be computed through a binomial expansion and Euler's beta function.
Comment: you can also try to solve the recurrence equation $I_{m-1,n}=(b-a)I_{m,n}+I_{m,n+1}$
Comment: @tired that sounds interesting. how do you define the recurrence equation? could you show in details?
Answer: In a first step, we perform the substitution $y=x^2$. Then you integral reads
$$ I=\int_0^\infty \!dy \frac{(y+a)^n}{2\sqrt{y}(y+b)^m}.\tag{1}$$
It is easy to show, the this integral is given by
$$I = \oint_C\!dz \frac{(z+a)^n}{4i\sqrt{-z} (z+b)^m} ,\tag{2}$$
where $C$ is the keyhole contour; the branch cut of $\sqrt{z}$ is along the negative real axis.
The keyhole contour is chose such that the large semicircle ($for m \geq n+1/2$) and the small semicircle (around $z=0$) vanish. The remaining integral is along the real axis. Slightly below the real axis (along which you integrate to the left), we have that $1/\sqrt{-z} = -i/\sqrt{z}$. Slightly above the real axis (along which you integrate to the right), we have that $1/\sqrt{-z} = i/\sqrt{z}$. Together, these two contours give $2i/\sqrt{z}$. So in (2) you have to divide by an additional $2i$ with respect to (1).
The integral can thus be solved by the residue theorem. As the only pole is at $z=-b$, we obtain
$$I = 2\pi i \mathop{\rm Res}_{z=-b} \frac{(z+a)^n}{4i\sqrt{-z} (z+b)^m}.$$
As there is an $m$-th order pole at $z=-b$, the result reads
$$I =   \frac{\pi}{2}  \frac{1}{(m-1)!} \lim_{z \to -b} \frac{d^{m-1}}{dz^{m-1}}\left( \frac{(z+a)^n}{\sqrt{-z}} \right).$$
So now we need to evaluate the $m-1$-derivative. You can show by induction that
$$\frac{d^{m-1}}{dz^{m-1}}\left( \frac{(z+a)^n}{\sqrt{-z}}\right)= (m-1)!\sum_{k=0}^{m-1}\binom{n}{k} \frac{  (2 m - 3 - 2 k)!! (a+z)^{n-k}}{(m-1-k)! 2^{m-1-k} (-z)^{m-1/2-k}}.$$
Thus, we obtain the result
$$I= \frac{\pi}{2}\sum_{k=0}^{m-1}\binom{n}{k} \frac{  (2 m - 3 - 2 k)!! (a+z)^{n-k}}{(m-1-k)! 2^{m-1-k} (b)^{m-1/2-k}}$$
Comment: @AlanTuring: thanks. I added some lines explaining the factor $2i$. Also I have evaluated the final result explicitly.
Comment: I prefer to call the keyhole contour "Pacman" for fun.
Comment: That is very interesting. Can you tell me how you step from $\sqrt{y}$ to $2i\sqrt{-z}$ please? (+1 in the meantime).
Comment: Also, here is a possibly better image of the path: https://i.stack.imgur.com/UIBMS.png
Comment: Awesome! $~~~~~$
Comment: @Fabian Or have you found the final result?  ;)
Comment: Thank you very much. Your answer helps me remind what complex variables can do. To be honest,  I totally forgot this technique. Such a bad student! btw, thank you again.
Answer: Assuming $b>0$ and $k<m$
$$\int_{0}^{+\infty}\frac{x^{2k}}{(x^2+b)^m}\,dx = \frac{\Gamma\left(k+\frac{1}{2}\right)\,\Gamma\left(m-k-\frac{1}{2}\right)}{2b^{m-k}(m-1)!}\sqrt{b} $$
follows from Euler's Beta function, hence it is enough to apply a binomial expansion to solve the given integral.
Comment: @PakhapoomSarapat: because $$(x^2+a)^n=\sum_{k=0}^{n}\binom{n}{k}\color{red}{x^{2k}}a^{n-k}.$$
Comment: oh wooowwww!!! I love this approach!!!!!!!!!!! thank you so much :)
Comment: I sorry but may I ask you a question? I'm just wondering why the integrand can be reduced to \frac{x^{2k}}{(x^2+b)^m}.
Comment: Why the downvote?
Answer: Assuming that $m>n+1/2$ so that the integral converges and $m\in\mathbb N$ for simplicity, it's easy enough to apply a semicircle contour, and by Jordan's lemma one can see the circular part of the integral goes to $0$ as $R\to\infty$.  By symmetry, all that remains is twice the integral in interest, and by Cauchy's residue formula, we have
$$\oint_C\frac{(x^2+a)^n}{(x^2+b)^m}\ dx=2\pi i\frac1{(m-1)!}\lim_{x\to bi}\frac{d^{m-1}}{dx^{m-1}}\frac{(x^2+a)^n}{(x+bi)^m}$$
Which finally gives us
$$\int_0^\infty\frac{(x^2+a)^n}{(x^2+b)^m}\ dx=\pi i\frac1{(m-1)!}\lim_{x\to bi}\frac{d^{m-1}}{dx^{m-1}}\frac{(x^2+a)^n}{(x+bi)^m}$$
Comment: @nbubis I'm unsure how to tackle that request.  I mean, I can brute force evaluate the $n$th derivative with general leibnize rule and all that, but the result doesn't look good.  The best hope is to evaluate the Laurent series and then do the residue, but I can't see how to do so simply
Comment: This method is exactly as same as what I learned in complex variables course. Thank you very much for your help!
Comment: :D Your welcome!
Comment: I'm curious - can't you give an explicit expression instead of the limit?
Answer: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

With $\ds{\quad a, b, m, n \in \mathbb{N}_{> 0}\quad}$ and
  $\ds{\quad \color{#f00}{m > n + {1 \over 2}}}$,
  note that:
  $$
\int_{0}^{\infty}{\pars{x^{2} + a}^{n} \over \pars{x^{2} + b}^{m}}\,\dd x =
{1 \over b^{m - n - 1/2}}
\int_{0}^{\infty}{\pars{x^{2} + \mu}^{n} \over \pars{x^{2} + 1}^{m}}\,\dd x\,,
\qquad \mu \equiv {a \over b}
$$

\begin{align}
\int_{0}^{\infty}{\pars{x^{2} + a}^{n} \over \pars{x^{2} + b}^{m}}\,\dd x & =
{1 \over b^{m - n - 1/2}}
\int_{0}^{\infty}{\pars{x^{2} + \mu}^{n} \over \pars{x^{2} + 1}^{m}}\,\dd x
\,\,\,\stackrel{x^{2}\ \mapsto\ x}{=}\,\,\,
{1 \over 2b^{m - n - 1/2}}
\int_{0}^{\infty}{\pars{x + \mu}^{n} \over \pars{x + 1}^{m}}\,x^{-1/2}\,\dd x
\\[5mm] & \stackrel{x + 1\ \mapsto\ x}{=}\,\,\,
{1 \over 2b^{m - n - 1/2}}
\int_{1}^{\infty}x^{-m}\,\pars{x - 1}^{-1/2}\,\pars{x - 1 + \mu}^{n}\,\dd x
\\[5mm] & \stackrel{x\ \mapsto\ 1/x}{=}\,\,\,
{1 \over 2b^{m - n - 1/2}}
\int_{1}^{0}x^{m}\pars{{1 \over x} - 1}^{-1/2}\pars{{1 \over x} - 1 + \mu}^{n}
\,{\dd x \over -x^{2}}
\\[5mm] & \stackrel{x\ \mapsto\ 1/x}{=}\,\,\,
{1 \over 2b^{m - n - 1/2}}
\int_{0}^{1}x^{m - n - 3/2}\,\pars{1 - x}^{-1/2}\,
\bracks{1 - \pars{1 - \mu}x}^{\,n}\,\dd x\label{1}\tag{1}
\\[5mm] & =
{1 \over 2b^{m - n - 1/2}}\,
{{}_{2}\mrm{F}_{1}\pars{-n,m - n -1/2;m - n;1  - \mu} \over
\mrm{B}\pars{m - n - 1/2,1/2}}
\end{align}

${}_{2}\mrm{F}_{1}$ is the 'Euler type'
Hypergeometric Function and
  $\ds{\,\mrm{B}}$ is the Beta Function.

$$\bbx{\ds{%
\int_{0}^{\infty}{\pars{x^{2} + a}^{n} \over \pars{x^{2} + b}^{m}}\,\dd x =
{1 \over 2b^{m - n - 1/2}}\,
{{}_{2}\mrm{F}_{1}\pars{-n,m - n -1/2;m - n;\bracks{b - a}/a} \over
\mrm{B}\pars{m - n - 1/2,1/2}}}}
$$
As explained in the above link, the result requires
$\ds{\verts{1 - \mu} \leq 1\ \mbox{and/or}\ 1 \leq {b \over a} \leq 2}$.
Otherwise, we can modify the factor
$\ds{\bracks{1 - \pars{1 - \mu}}^{\,n}}$, in expression \eqref{1}, in a trivial way.
Comment: I saw all comments mention the condition that $m>n+1/2$. Could you tell me how necessary of this condition? Btw, thank you very much! :)
Comment: @PakhapoomSarapat Note that $\left(x^{2} + a\right)^{n}/\left(x^{2} + b\right)^{m} \sim x^{2n - 2m}\ \mbox{as}\ x \to \infty$. Also,
$\int x^{2n - 2m}\,\mathrm{d}x \propto x^{2n - 2m + 1}$. The integral converges whenever $2n - 2m + 1 \color{#f00}{< 0} \implies m > n + 1/2$.
Comment: oh gosh!!! I definitely cannot come up with this by myself. Thank you again :)
Comment: @PakhapoomSarapat You're welcome.


Möbius function on a finite poset (X, $\leq$)

Question: I'm having some difficulties with the following problem:

Give an example of a finite poset $(X, \leq)$ and elements $a,b \in$ X such that $\mu(a,b)=-4$ where $\mu$ is the Möbius function of $(X, \leq)$.

I think I know what a finite poset $(X, \leq)$ typically looks like, but how does this Möbius function come into play? My understanding of Möbius functions is mainly limited to recurrences and matrices, so I don't know how this generally changes things.
Comment: I suspect you are confusing Möbius functions with Möbius transformations. They are quite different.
Comment: The Moebius function does not *alter* a poset in any way. Your understanding of Moebius functions sounds very strange; you should probably read up a bit of some textbook, like Stanley's great *Enumerative Combinanorics*, volume 1.
Comment: @ThomasAndrews, that is immensely unlikely, given what is written in the post.
Comment: There's enough information in [this Wikipedia article](http://en.wikipedia.org/wiki/Incidence_algebra) for you at least to verify Mariano's example.
Answer: A simple example is the following:
Comment: What program / language did you use to create this Hasse diagram? It is very nice.