JPQL JPA - Criar uma lista agrupada por data com o somatório e o lucro de todos os itens vendidos naquele dia

Question: A consulta SQL abaixo esta retornando um resultado errado para o campo valorEntrega.
SELECT
DATE(p.dt_pedido) AS  barChartLabels,
COUNT( DISTINCT p.id) AS qtdPedido,
SUM((item.quantidade * item.preco) * p.taxa_compra) AS percentualCompra,
SUM(item.quantidade * item.preco) AS valoresTotal,
SUM(p.taxa_bairro) AS valorEntregaAS valorEntrega

FROM pedido p, item_pedido item
where (p.id = item.pedido_id)
GROUP BY DATE(p.dt_pedido)

Ao invés dele simplesmente realizar a somatória do valor do Pedido.taxa_Bairro, ele esta multiplicando este pedido.taxa_Bairro pela quantidade de itens de cada pedido e depois somando estes resultados. Como fazer para que ele somente realize a somatória e não a multiplicação? Abaixo o diagrama:

A idéia é que após a correção do SQL eu consiga converter-la para JPQL. Grato
Comment: Estive observando que mesmo apesar de não estar escrito na query, ela esta pegando o valor da taxaBairro do Pedido e multiplicando pela quantidade de itens que tem neste pedido, e o correto é não ocorrer esta multiplicação. Esta multiplicação não pode ocorrer, como fazer isso?
Comment: Tente não colocar imagens de códigos, ao invés disso cole o código no corpo da pergunta mesmo, como no caso do JSON e do código SQL, fica mais fácil para quem for ler sua pergunta e tentar responde-la. No caso das imagens de tela tudo bem.
Comment: Você está usando MySQL? Por que está usando `DISTINCT` para retornar a data do pedido e o count do id? Não seria necessário para a data, se você já está agrupando por ela, e para o id também é desncessário, porque o id deveria ser único. Qual o retorno de `SUM(p.taxa_bairro)` se colocar só ele no `SELECT`?
Comment: Eu sugiro que você dê uma lida nesse artigo da ajuda do site: [Como criar um exemplo Mínimo, Completo e Verificável](https://pt.stackoverflow.com/help/mcve). No seu caso, creio que só bastava postar a sua consulta SQL, porque é lá que está o problema e é lá que você quer ajuda. Quando você posta um texto muito grande assim, muito cheio de detalhes, pode ser que menos pessoas leiam ele por completo, então, se não for necessário, o melhor é tentar colocar o menos possível, o suficiente para identificar o problema.
Comment: Obrigado @PedroGaspar, vou editar a pergunta observando o artigo que vc colocou.
Comment: @PedroGaspar, se eu deixo somente SUM(p.taxa_Bairro) e retiro todos os demais campos do SQL, além de retirar a ligação com a outra tabela ele realiza o calculo corretamente, porém se insiro a ligação com a tabela filha, seja desta forma ou join, ele volta a multiplicar pelas linhas dos itens antes de somar.
Comment: Mas a ligação com a outra tabela está no `WHERE` e não na lista de campos selecionados!
Comment: @PedroGaspar, o que esta acontecendo é que por causa da ligação ele esta repetindo o pedido.taxa_Bairro pelo mesmo numero da quantidade de itens e depois somando. É como se antes do SUM ele replicasse a linha 14 (numero de itens) vezes. (Estou utilizando MySQL)
Comment: Sugiro que acrescente no texto da pergunta detalhes sobre as colunas das tabelas. Por exemplo, o que contém `p.taxa_compra`?
Answer: Depois de conversar com o autor através dos comentários, percebi que o problema acontecia porque ao fazer uma consulta com full join (Retrieving Records from Multiple Tables | MySQL SQL Syntax and Use | InformIT), o número de registros percorridos era o número de registros da tabela item_pedido (14 registros).
No exemplo dele o retorno da tabela pedido, para pedidos feitos na data 01/11/2018, trazia 2 registros:
+-----+---------------------+-------------+-------------+
| id  |      dt_pedido      | taxa_bairro | taxa_compra |
+-----+---------------------+-------------+-------------+
| 227 | 2018-11-01 03:26:19 |        1.00 |        0.10 |
| 228 | 2018-11-01 03:39:09 |        1.00 |        0.10 |
+-----+---------------------+-------------+-------------+

E o retorno da tabela item_pedido, para os itens relacionados àqueles 2 pedidos, trazia 14 registros:
+-----------+-------+------------+
| pedido_id | preco | quantidade |
+-----------+-------+------------+
|       227 | 35.00 |       1.00 |
|       227 | 25.21 |       1.00 |
|       227 | 16.10 |       1.00 |
|       227 | 23.10 |       3.00 |
|       227 |  2.00 |       2.00 |
|       227 |  6.00 |       2.00 |
|       227 |  1.00 |       2.00 |
|       227 | 33.55 |       2.00 |
|       227 | 21.22 |       1.00 |
+-----------+-------+------------+
|       228 | 20.12 |       2.00 |
|       228 | 11.10 |       2.00 |
|       228 | 21.22 |       2.00 |
|       228 | 13.22 |       1.00 |
|       228 | 25.21 |       3.00 |
+-----------+-------+------------+

Então, após o full join das duas tabelas:
FROM pedido p, item_pedido item
WHERE p.id = item.pedido_id

O retorno seria uma junção dos dois resultados, ou seja, 14 registros:
+-------+---------------------+-------------+-------------+-----------+-------+------------+
|  id   |      dt_pedido      | taxa_bairro | taxa_compra | pedido_id | preco | quantidade |
+-------+---------------------+-------------+-------------+-----------+-------+------------+
| 227   | 2018-11-01 03:26:19 |        1.00 |        0.10 |       227 | 35.00 |       1.00 |
| 227   | 2018-11-01 03:26:19 |        1.00 |        0.10 |       227 | 25.21 |       1.00 |
| 227   | 2018-11-01 03:26:19 |        1.00 |        0.10 |       227 | 16.10 |       1.00 |
| 227   | 2018-11-01 03:26:19 |        1.00 |        0.10 |       227 | 23.10 |       3.00 |
| 227   | 2018-11-01 03:26:19 |        1.00 |        0.10 |       227 |  2.00 |       2.00 |
| 227   | 2018-11-01 03:26:19 |        1.00 |        0.10 |       227 |  6.00 |       2.00 |
| 227   | 2018-11-01 03:26:19 |        1.00 |        0.10 |       227 |  1.00 |       2.00 |
| 227   | 2018-11-01 03:26:19 |        1.00 |        0.10 |       227 | 33.55 |       2.00 |
| 227   | 2018-11-01 03:26:19 |        1.00 |        0.10 |       227 | 21.22 |       1.00 |
+-------+---------------------+-------------+-------------+-----------+-------+------------+
| 228   | 2018-11-01 03:39:09 |        1.00 |        0.10 |       228 | 20.12 |       2.00 |
| 228   | 2018-11-01 03:39:09 |        1.00 |        0.10 |       228 | 11.10 |       2.00 |
| 228   | 2018-11-01 03:39:09 |        1.00 |        0.10 |       228 | 21.22 |       2.00 |
| 228   | 2018-11-01 03:39:09 |        1.00 |        0.10 |       228 | 13.22 |       1.00 |
| 228   | 2018-11-01 03:39:09 |        1.00 |        0.10 |       228 | 25.21 |       3.00 |
+-------+---------------------+-------------+-------------+-----------+-------+------------+

Por isso o retorno do campo SUM(p.taxa_bairro) era '14.00', ao invés do valor '2.00' esperado pelo autor.
Para resolver isso, pode-se colocar a somatória dos valores dos itens do pedido em uma subquery, dessa forma:
SELECT
  DATE(p.dt_pedido) AS barChartLabels,
  COUNT(p.id) AS qtdPedido,
  SUM(itens.valorTotalPedido * p.taxa_compra) AS percentualCompra,
  itens.valorTotalPedido AS valoresTotal,
  (SUM(itens.valorTotalPedido * p.taxa_compra) + SUM(p.taxa_bairro)) AS valorEntrega
FROM pedido AS p
   INNER JOIN
     (SELECT pedido_id, SUM(quantidade * preco) AS valorTotalPedido
      FROM item_pedido
      GROUP BY pedido_id
     ) AS itens
   ON itens.pedido_id = p.id
GROUP BY DATE(p.dt_pedido)

Confira o resultado no SQL Fiddle.
Comment: Ola Pedro, o problema que relatei realmente é este, descrito por vc. Porém o código esta dando um erro "Error Code: 1054. Unknown column 'p.id' in 'where clause" , já tentei alterando o alias 'p' para o nome da tabela, porém o erro continua. Estou utilizando o MySQL.
Comment: @JoséLuizGonzagaNeto, alterei para `FROM pedido p INNER JOIN (SELECT  ...`, veja se agora funciona.
Comment: Não Pedro, continua a mesma falha, também estou tentando por aqui. Sua linha de raciocínio esta perfeita, só tenho que identificar o que na sintaxe devo adequar.
Comment: Fiz uma nova edição na resposta, veja se agora ficou OK.
Comment: @JoséLuizGonzagaNeto, agora está funcionando, coloquei inclusive um link para o SQL Fiddle, dê uma olhada e diga se ficou OK aí para você também.
Comment: Pedro, estudando seu código consegui fazer rodar, segue o código atualizado para vc colocar na resposta.  select
DATE(pedido.dt_pedido ) AS barChartLabels ,
COUNT(pedido.id) AS qtdPedido,
SUM(itens.total * pedido.taxa_compra) as percentualCompra,
SUM(pedido.taxa_bairro) AS valorEntrega,
SUM(itens.total) as custoProdutos
from pedido
inner join
( select pedido_id as pedido_id, SUM(item.quantidade * item.preco) as total
  from item_pedido item group by item.pedido_id ) as itens on itens.pedido_id = pedido.id
group by  DATE(pedido.dt_pedido )
Comment: Obrigado o apoio.


Share named scope in Rails 4

Question: I'm attempting to share a named scope between two models via a module. It is not working for me. I keep getting an undefined error. I'm trying with an empty 'your_scope' scope:
config/initializers/boxshare_init.rb
require 'assets/named_scopes/m.rb'

lib/assets/named_scopes/m.rb
module M
  def self.included(base)
    base.class_eval do
      scope :your_scope, lambda {}
    end
  end
end

app/models/folder.rb
class Folder < ActiveRecord::Base
    include M

    acts_as_tree

    belongs_to :user
    has_many :assets, dependent: :destroy
end

rails console:
$ rails c
Loading development environment (Rails 4.1.1) irb: warn: can't alias
context from irb_context.
2.0.0-p0 :001 > Folder.last.your_scope
Folder Load (0.1ms)  SELECT  "folders".* FROM "folders"   ORDER BY "folders"."id" DESC LIMIT 1
NoMethodError: undefined method `your_scope' for <Folder:0x007fd781a1daf0>

Where am I going wrong?
Comment: You should use Concerns

http://stackoverflow.com/questions/14541823/how-to-use-concerns-in-rails-4
Answer: The ActiveRecord's method .last returns an instance of your model, not an AR::Relation that you can chain scopes on it.
Try this:
Folder.last.class
# => Folder
Folder.your_scope.class
# => ActiveRecord::Relation

Use your_scope like this:
Folder.your_scope.last

Share named scope in Rails 4


How do I extract definitions from a html file?

Question: I'm trying to practice with regular expressions by extracting function definitions from Python's standard library built-in functions page. What I do have so far is that the definitions are generally printed between

 and

. When I try
import re
fname = open('functions.html').read()
deflst = re.findall(r'

([\D3]+)

', fhand)

it doesn't actually stop at

. This is probably something very silly that I'm missing here, but I've been really having a hard time trying to figure this one out.
Answer: Regular expressions are evaluated left to right, in a sense. So in your regular expression,
r'

([\D3]+)

'

the regex engine will first look for a

, then it will look at each of the following characters in turn, checking each for whether it's a nondigit or 3, and if so, add it to the match. It turns out that all the characters in

 are in the class "nondigit or 3", so all of them get added to the portion matched by [\D3]+, and the engine dutifully keeps going. It will only stop when it finds a character that is  a digit other than 3, and then go on and "notice" the rest of the regex (the

).
To fix this, you can use the reluctant quantifier like so:
r'

([\D3]+?)

'

(note the added ?) which means the regex engine should be conservative in how much it adds to the match. Instead of trying to "gobble" as many characters as possible, it will now try to match the [\D3]+? to just one character and then go on and see if the rest of the regex matches, and if not it will try to match [\D3]+? with just two characters, and so on.
Basically, [\D3]+ matches the longest possible string of [\D3]'s that it can while still letting the full regex match, whereas [\D3]+? matches the shortest possible string of [\D3]'s that it can while still letting the full regex match.

Of course one shouldn't really be using regular expressions to parse HTML in "the real world", but if you just want to practice regular expressions, this is probably as good a text sample as any.
Comment: Ah thank you so much for the explanation! Very helpful!
Answer: By default all quantifiers are greedy which means they want to match as many characters as possible. You can use ? after quantifier to make it lazy which matches as few characters as possible. \d+? matches at least one digit, but as few as possible.
Try r'

([\D3]+?)

'


will be any problem with my website if I empty all the cache tables from Database?

Question: I'm trying to move my website from localhost to a server. the size of DB is too big and from what I saw the cache tables have big size. is there any problem (for my localhost version of site) if I empty all of them? (specially cache_form)
besides that when I was trying to import the DB into server the server reported an error when it was inserting cache_views table; it is very important for me to empty this table to avoid insertion error in the future.
thanks
Comment: I would recommend to either use the `drush`, or clear the cache from the `/admin/config/development/performance` page. However if do you some reason you are not able to clear the cache from this place than only you should go for manually clearing the cache tables
Comment: @AnkitAgrawal clearing the cache from `/performance` does not empty above mentioned tables. besides that I'm going to clear the cache table because of moving the website
Answer: As per the drupal community doc for clearing the cache you can manually TRUNCATE the tables (empty, not remove) starting with cache_ and there shouldn't be any problem doing so as on visiting any page the cache is rebuilt.
However I would recommend to either use the drush, or clear the cache from the /admin/config/development/performance page.
If you want to clear the cache from code than you may try the following:
// clear cache
drupal_flush_all_caches();

Also its always safe to keep the Backup of database before making any manual operation on database.
Comment: That page on DO is not 100% accurate.  `{cache_form}` isn't a true cache table.  Totally clearing it may cause problems for any in progress forms.
Comment: even though `clear cache` code didn't clear those tables (it is really surprising!) but from what you and Nigel said, it should be safe. thanks
Comment: @Mohammad It may be not emptying the tables as the cache gets rebuilt, so you can manually TRUNCATE the tables (empty, not remove) starting with cache_ and there shouldn't be any problem doing.
Comment: I did this and successfully imported DB to server, thanks
Comment: @MPD Yeah right, Thanks for mentioning this point :)
Comment: I'm opening a discussion on the D.O docs to correct this oversight.


Salvar tempo do cronômetro ao reiniciar página

Question: Estou fazendo um cronômetro regressivo em JavaScript que após 3 dias ele reinicia a contagem, porém gostaria de saber como posso fazer para a contagem não reiniciar ao recarregar a página.
let time = new Date();
let finalDate = new Date();
finalDate.setDate(time.getDate()+3);

setInterval(function() {
    time = new Date();
    finalDate = new Date();
    finalDate.setDate(time.getDate()+3);
    console.log('Funcionou')
}, 259200000)

let now, timeLeft, timeString;

let timer = setInterval(function() {
    now = Date.now();
    dateDiff = finalDate - now;
    timeLeft = new Date(dateDiff);

    timeString = timeLeft.toLocaleTimeString (
    'pt-BR',
        {
            hour12: false,
            minute: '2-digit',
            second: '2-digit',
            hour: '2-digit',
            day: '2-digit',
            timeZone: 'GMT'
        }
    )

    $('.timer .count-timer .days').text(timeString.split(':')[0].split(" ")[0]);
    $('.timer .count-timer .hours').text(timeString.split(':')[0].split(" ")[1]);
    $('.timer .count-timer .minutes').text(timeString.split(':')[1]);
    $('.timer .count-timer .seconds').text(timeString.split(':')[2]);
}, 1000)

Comment: Gostaria de salvar o finalDate
Comment: por favor, coloque mais detalhes. Qual é a variável que deseja salvar?
Comment: Tentou salvar o `finalDate` em um `localStorage`, por exemplo, e consultar ele toda vez que a página for recarregada? Fiquei confuso no uso do `setInterval`
Comment: Muito legal a sua pergunta! :-D Vou acompanhar aqui para ver o que a galera vai responder ;-) Faz mais de 100 anos que não mexo com web e estou meio enferrujado. Se você criar um cookie para armazenar a data e ler quando o usuário voltar a carregar a página não funciona?
Comment: Essa solução do localStorage eu até pensei em fazer, mas quando um novo usuário acessar a página o cronômetro será reiniciado novamente não ? Pq o localStorage não vai existir
Comment: @LuizFelipedaSilva aí vc vai precisar de um backend, pode usar o google firebase caso não queira fazer um do 0
Answer: Para salvar e ler a data localmente você pode usar o localStorage:
Salvando:
localStorage.setItem('data', finalDate.toString())
Lendo:
finalDate = new Date(localStorage.getItem('data'))
Caso localStorage.getItem('data') for null, você inicia finalDate normalmente.
Porém pelo que entendi, você quer salvar para todos usuários. Aí você irá precisar de um back-end para salvar e ler a data a partir do servidor. Você não precisa criar um back-end apenas para isso, você pode usar soluções gratuitas existentes como o Google Firebase.


Half notes with slashed stem

Question: How should I play the half bass notes with the slashed stem?
See please the attached image:
Answer: It's called measured tremolo, and is a shorthand for writing a series of eighth notes. It means that you are to play repeated eighth notes that fill the time of the half note. So, for example, in the first measure, you'd play four eighth notes of A, followed by four eighth notes of G♯.
Comment: To be precise,  the repetition rate is typically two notes per beat.  If this were in cut time (2/2), then you'd play two notes for each half note, not four.
Comment: Uncommon in a piano score.  Much more common in instrumental music, where repeated notes are a frequent feature of string parts in particular.
Comment: Thank you for the answer Caleb Hines. Finally, I think that the half note means that these notes are played as quarters. The piece of music is the Resurreccion del Angel by Astor Piazzolla a slow tango and I can clearly hear this quarters on the bass lines.
Comment: If there were two slashes through the stem of a half note, it would be 8th notes, and if there were three slashes through the stem of a half note, it would be 16th notes, etc.
Comment: See also: http://music.stackexchange.com/questions/20649/what-do-these-beamed-half-notes-mean
Answer: Just in case a total music nerd comes across this: a note stem with slash is the modern transcription of a "plica" in Modal (meaning: 12th/13th century School of Notre Dame) notation.
A plica is a single note with stems on both left and right side, both up or both down. The left stem has no meaning, but the right one indicates that the note is "plicated". This means that the note length (typically a longa, rendered as a quarter note) is split in two notes (therefore: eights), with the second a diatonic step up or down depending on the stem direction. In modern transcriptions, the stem of the second note receives a slash, to indicate that it was a plica in the original.
Example: https://imslp.org/wiki/Magnus_Liber_Organi_(Various) part 2, opening page, 3rd staff, 2nd note.
Comment: I'm afraid this answer is not too informative. Could you add an example of such notation, and an explanation how it should be realized?

Half notes with slashed stem


Where are 'DeviceContext' claims when using alternate browser in ADFS 4.0?

Question: I know this is probably not the best place to ask this question. But, after days of working on this, and having posted in the Microsoft Forum, I'm at my wits end.
We are utilizing a hybrid ADFS 4.0 (Server 2016) / Azure AD / Office 365 setup with device registration and SSO working.
We are attempting to enable multi-factor authentication with device based access policies. We don't want "recognized" devices seeing additional MFA prompts. We are evaluating the claims being returned by ADFS using the Microsoft Claims Xray.
We have successfully enabled MFA and configured ADFS to only prompt for MFA if a device is unrecognized. This works because devices that are recognized have additional properties in active directory (isRegisteredUser; isManaged; isKnown; trustType; etc) and we can take action on those properties. We've tested with IE, Firefox, Chrome, and Safari on an iPad. However, the "DeviceContext" claims only come through when the authentication is done from IE or Safari on the iPad.
For some reason, it appears no device authentication occurs when the request is made from Chrome or Firefox. Authentication works, we just can't see any of the devicecontext claims that allow us to make a decision based on if the device is registered or not. So, these browsers get an additional MFA prompt.
I simply cannot find any posts online matching my exact problem. There are a few threads that are similar, but turn out to be different issues, or end up at a dead end. I'm hoping someone has this similar setup and knows why Chrome and Firefox would not perform the additional device based authentication, but safari on an iPad would. All the devices have valid certificates to perform the authentication.
I don't get any errors to go on in any event logs. The browser simply doesn't make a device authentication request, and no devicecontext claims are issued. It's possible this isn't supported, but I can't find any information indicating one way or another.
Comment: @JevgenijMartynenko Check out my answer. All the studying over weeks came around full circle, so that the problem is a simple inability to access the Local Computer certificate store when using Chrome or Firefox in Windows 10.
Comment: We are facing the same problem: Device Authentication in ADFS only works with IE. Hope you can share any insight with me, or any ideas we could verify something. For now I did traffic inspection with Fiddler, and from what I understand other browsers are not even trying to authenticate the device. Strange that the same device auth works with Office 365 services in Chrome, for example. It's just not working with ADFS
Comment: @JevgenijMartynenko Thanks for the comment. Can you clarify how it "works with Office 365 services?" I need something to go on here. Thanks.
Comment: I ment, device auth works in non-IE browsers for office.com but does not work with ADFS server. So I guess it is the ADFS server which is the fault. I have two ideas I did not have time to test yet:
1. Use Fiddler to compare headers and cookies between IE and Chrome/Edge
2. Try to use Azure for SSO/Federation and avoid using ADFS alltogether. Still need more time to test both
Comment: @JevgenijMartynenko Thanks. This is what I discovered as well. I've pretty much answered this question now and can post some details soon. Non IE / Edge browsers do not pass the device context claims to ADFS nor Office 365. Microsoft created a plugin for Chrome that solves this, if you have Win 10 v1703 or newer. But, the plugin only works with MFA handled by Office 365, not ADFS. Device authentication is different, and works on mobile devices that have "user" scoped certificates, but that is not how MFA is done with Windows, which uses a PRT.
Answer: Device Context claims are necessary for ADFS / Azure AD to determine if a device is recognized, managed, compliant, etc. Without them, scenarios that rely on MFA and SSO are broken, if bypassing MFA relies on "recognizing" a known device. The device context claims are generated when device authentication is performed alongside user authentication in ADFS.
I found that in Windows 7, a Workplace Joined machine is per user based and receives a device authentication certificate that is stored in the "Current User" certificate store. During authentication, device authentication is successfully performed using the certificate even in Chrome.
In Windows 10, I found that Azure AD device registration is per machine, and the machine receives a device authentication certificate that is stored in the "Local Machine" certificate store. During authentication, IE and Edge successfully use this certificate to complete device authentication. Chrome will not touch any certificates in the "Local Machine" certificate store. If using Chrome the device is not recognized, MFA fails, and the user is prompted for a secondary form of authentication.
This appears to be a known issue with alternative browsers without a suitable answer. Without device authentication occurring, a device can not be recognized for the purposes of bypassing MFA with conditional access policies.
Microsoft has provided a plug-in for Google Chrome, that allows it to perform device authentication when using MFA. However, there are a couple caveats to be aware of:

The plug-in only works for Chrome and only works with Windows 10 Creators Updates (1703) or newer.
The plugin only works for Azure AD conditional access policies.
ADFS device based conditional access policies will not work.
Relying party trusts in ADFS other than Office 365 will not be able to utilize the plugin due to the previous limitation.

Long story short, Windows 7 device authentication seems to work fine and recognized devices will support device based conditional access policies if you use Chrome. Windows 10 devices using Chrome have limited ability to support device based conditional access policies. Mobile devices receive a user based certificate when enrolled in to MDM, therefore they also seem to support bypassing MFA when the device is managed.
I believe the main problem here is that the developers of Chrome have deliberately prevented it from accessing the "Local Computer" certificate store for authentication purposes. This can be verified with Process Monitor, and from looking at available certificates in the certificate settings in Chrome.
I am sorry to say this, but Mozilla has continued their headstrong approach that causes their browser to be very difficult to utilize in enterprise, and the developers have made Firefox not able to access any Windows certificate stores. So, unless you deliberately import a certificate in to Firefox, device based conditional access doesn't work at all on any OS.
Comment: Thanks for sharing. Wierd thing though, for us device auth in ADFS only works in IE. Edge on Azure AD registered devices and any browser on compliant devices enrolled in Intune both behave the same way as Chrome :( Could you confirm Edge/Intune mobile devices can auth to ADFS and bypass manual MFA requirement?


How to get searched item value in search form?

Question: How do I get the value of searched item value, if I searched for "cat" in a search box then it also displays on a search page?
Comment: How do you want to use it?
Comment: Just need to display it like in a variable
Answer: You can catch your entity in the preprocess and put data into drupal_static. After that you can display it where you want.
Answer: This way sometimes works, in a hook_alter function:
<code>if ($form_id == 'search_form'){
  // gives you the value
  $save_value = $form['basic']['keys']["#default_value"];
}
</code>
But this way seems to work even better:
<code>\Drupal::request()->query->get('keys')
</code>
There should technically also be a way of making a custom module, add a custom submit handler to the search form, and getting the value in there, but I couldn't get it working that way.
Comment: Oh, I forgot to mention the second part. To display on your search results page, override the search-results twig template and use the variable from the .theme file.
Answer: Though I am seriously late to the party, you can also grab the query thusly if you use the Search API module. After you created a View associated to your search index, you can use:
<code>/**
 * Implements hook_preprocess_views_view()
 * @param $variables
 */
function YOUR_THEME_NAME_preprocess_views_view(&$variables) {
  if ($variables['view']->id() == 'search') {
        $variables['search_keywords'] = \Drupal::request()->query->get('search_api_fulltext');
  }
}
</code>
In this case, my view is named "search" and the query key I am looking for (after the ?) is "search_api_fulltext" (id of my input search field).
$variables['search_keywords'] will now contain the keywords after the "=", for instance from /search?search_api_fulltext=searched+term


Cannot create SharePoint list item through Graph API which includes people picker value

Question: I am trying to create a SharePoint list item via the Graph API which includes a people picker field as well as several others. I am using an HTTP POST request to pass a JSON payload to the correct endpoint located at https://graph.microsoft.com/v1.0/sites/{my_site_id}/lists/{my_list_id}/items. The list item has a "Tested By" field which is the people picker.
The creation completes just fine, so long as I leave this "Tested By" field blank, but for my use case, this field needs to be populated for audit compliance. Under the hood, if you GET an existing list item, the field shows up with the title "Tested_x0020_By," which exists as:
"Tested_x0020_By": [{
            "LookupId": 123,
            "LookupValue": "John Doe",
            "Email": "email@example.com"
        }]

But when you try to POST a JSON payload which includes this field using a patch document which matches this exact format, it blows up with an HTTP 400 "Invalid Request." No further information to be had other than "Invalid Request" to say why it is, in fact, invalid. I've tried passing the full three items as well as only the LookupId.
How am I supposed to create a list item which includes data for this field?
HTTP POST request to https://graph.microsoft.com/v1.0/sites/{my_site_id}/lists/{my_list_id}/items with a JSON payload including the field listed above.  Expected to receive an HTTP 2XX response with the typical information from Microsoft Graph showing item creation.  Did receive an HTTP 400 "Invalid Request" with no further amplifying info about what, in fact, was invalid.  Request will complete successfully when not including the "Tested_x0020_By" field in the JSON payload.
Answer: I think there is a workaround for this
Add LookupId to the name of the people picker column and specifies only lookup ids in the array
POST https://graph.microsoft.com/v1.0/sites/{site_id}/lists/{list_id}/items
{
    "fields": {
        "email@example.com": "Collection(Edm.Int32)",
        "Tested_x0020_ByLookupId": [123]
    }
}

You need to specify the type of the field to make sure OData understands it by adding "email@example.com": "Collection(Edm.Int32)"


What is the name of the table where view modes are stored?

Question: We have 10 view modes that we created. When we run drush @env cex sync in our local we are able to export the config files related to these view modes such as core.entity_view_mode.node.related.yml (where related is the view mode).
Is there a database table where these View modes are stored? If so, what is the name of it?
We are not using Display Suite or Panels, just the out of the box View Modes from Core. We do not plan to add those modules.
Goal:

Find out what view modes are being used programmatically.
Delete all view modes that are not being used.

Definition of not being used:

Article content type has 3 custom view modes: listing, minimum, related
Basic Page content type has an Entity reference to Article pages where the Article view mode = listing under Basic Page Default View Mode.
Custom view modes listing and minimum are not being used. However, if we consider all content types (e.g. 10 more content types) then it will be a pain to have to go through one by one.
Comment: you say in definition - #2 "Article view mode = listing", then on #3 "listing and minimum are not being used.", can you review this please?
Comment: it seems like you know which view modes are not in use, so why don't you just delete them in the admin interface (/admin/structure/display-modes/view)?
Comment: @CesarMoore I have updated the questions goal and definition. We are looking for a programmatic way to figure out what is being used and what is not. Hopefully it is clear now.
Answer: View modes are stored in the configuration entity entity_view_mode which you can load like any other entity:
$view_mode = \Drupal::entityTypeManager()
  ->getStorage('entity_view_mode')
  ->load('node.teaser');

To load all view modes for the entity type node:
$view_modes = \Drupal::entityTypeManager()
  ->getStorage('entity_view_mode')
  ->loadByProperties(['targetEntityType' => 'node']);

View modes don't store much data other than a label for the view mode name.
How a view mode is displayed for a specific content type is stored in a different entity:
$display = \Drupal::entityTypeManager()
  ->getStorage('entity_view_display')
  ->load('node.article.teaser');

The usage depends on how you define what being used means. If you mean with not used that it is not configured in a content type, which you can query in the config entities mentioned before, this doesn't mean necessarily, that the view mode is not used anywhere. If you configure an entity to be displayed in a view mode, for example in a View or a entity reference field, and this view mode is not configured in the content type, then it fallbacks to the default view mode.
Comment: Just updated the question with definition of `not being used`
Comment: If this is only for the usage between referenced content types you could load all displays like in the last code example and check the field formatter settings of all reference fields. But this would be only one of many places where view modes can be used.
Answer: The configuration is stored in the config table
mysql> describe config;
+------------+--------------+------+-----+---------+-------+
| Field      | Type         | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| collection | varchar(255) | NO   | PRI |         |       |
| name       | varchar(255) | NO   | PRI |         |       |
| data       | longblob     | YES  |     | NULL    |       |
+------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

This is an example query from the umami demo profile:
    mysql> select name from config where name like 'core.entity_view_display.node.article.%';
+-------------------------------------------------------+
| name                                                  |
+-------------------------------------------------------+
| core.entity_view_display.node.article.card            |
| core.entity_view_display.node.article.card_common     |
| core.entity_view_display.node.article.card_common_alt |
| core.entity_view_display.node.article.default         |
| core.entity_view_display.node.article.full            |
| core.entity_view_display.node.article.rss             |
| core.entity_view_display.node.article.teaser          |
+-------------------------------------------------------+
7 rows in set (0.00 sec)

Comment: This is an answer to the original question: "What is the name of the table where view modes are stored?" ... "Is there a database table where these View modes are stored? If so, what is the name of it?"


Shortcut for "Convert java code ( not file) to Kotlin

Question: In Android studio, When you copy java code to Kotlin file, you see a dialog

I need help to know if I select "Don't show dialog" how can i re-enabled it. I can't find settings in studio unfortunately :(
Answer: command shift A (Mac) or ctrl shift A in Windows and Linux to invoke find action dialogue.
Type convert pasted java code

If it is off, press enter.
Answer: @aristotll's answer gives you what you want!
If you want to convert an existing file:
- Menu: Code > Convert Java File to Kotlin File
- Win: Ctrl+Alt+Shift+K
- Mac: ⌘+⌥+Shift+K


How to perform join operation for following table?

Question: I am a beginner programmer. Here are my table structures:

I want to retrieve content and type field from 'post' table where userdId following the 'following' field. I am trying this SQL Join for retrive post of followers.
SELECT userId,following, userId,postId,content,file,type
FROM follow, post
WHERE userId = '5a37589e4ff8b'

Comment: Please read [Under what circumstances may I add "urgent" or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions.
Answer: You should use the JOIN syntax
SELECT f.userId, f.following, p.postId, p.content, p.file, p.type
    FROM follow f
    JOIN post p ON p.userId = f.userId
    WHERE f.userId = '5a37589e4ff8b'

Comment: should i replace f with follow and p with post ?
Comment: When you use `follow f` it's called an alias, it means that you can use it to prefix field names without having to use the full name.  So `f` becomes a shorthand for `follow`
Comment: thank you very much . one more thing can i tag you again if i get any trouble regarding this query ?
Comment: Just leave another message and I will try and help.  Not always around, but will always get back eventually.
Comment: thanks . Actually This query not gives me desired results .. i want to retrieve post of users which posted by followed users .
Comment: Do you mean `JOIN post p ON p.userId = f.following`?


What's is wrong with this dagger2 simple example?

Question: 1 - Scope:
@Scope
@Retention(RetentionPolicy.CLASS)
public @interface PerInstance {}

2 - AppContextModule:
@Module
public class AppContextModule {

Application application;

public AppContextModule(Application application){
    this.application = application;
}

@Provides
public Application application(){
    return this.application;
}

@Provides
public Context context(){
    return this.application;
}

@Provides
public LocationManager locationManager(Context context){
    return (LocationManager)      context.getSystemService(context.LOCATION_SERVICE);
}

}

3 - MeuPrimeiroModule:
@Module
public class MeuPrimeiroModule {

@Provides
@PerInstance
public String nome() {
    return new String("Gorick");
}

}

4 - MeuSegundoModule:
@Module(includes = MeuPrimeiroModule.class)
public class MeuSegundoModule {

@Provides
@Singleton
public String nomeCompleto(MeuPrimeiroModule meuPrimeiroModule) {
    return new String(meuPrimeiroModule + " Silva");
}

}

5 - MeuPrimeiroComponent:
@PerInstance
@Component(modules={MeuPrimeiroModule.class})
public interface MeuPrimeiroComponent {
void inject(MainActivity mainActivity);
}

6 - MeuSegundoComponent:
@Singleton
@Component(modules={MeuSegundoComponent.class})
public interface MeuSegundoComponent extends MeuPrimeiroComponent {

void inject(MainActivity mainActivity);
}

7 - AppContextComponent:
public interface AppContextComponent {

Application app(); //provision method
Context applicationContext(); //provision method
LocationManager locationManager(); //provision method
}

8 - ApplicationComponent:
@Singleton
@Component(modules={AppContextModule.class})
public interface ApplicationComponent extends AppContextComponent {
void inject(MainActivity mainActivity);
}

9 - MainActivity:
public class MainActivity extends AppCompatActivity {

@Inject
MeuPrimeiroComponent meuPrimeiroComponent;

@Inject
MeuSegundoComponent meuSegundoComponent;

TextView nome, nomeCompleto;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    nome = (TextView) findViewById(R.id.nome);
    nomeCompleto = (TextView) findViewById(R.id.nomeCompleto);

    setNome(nome, nomeCompleto);
}

public void setNome(TextView nome, TextView nomeCompleto){
    nome.setText(meuPrimeiroComponent.toString());
    nomeCompleto.setText(meuSegundoComponent.toString());
}

}

Build:
Error:(16, 10) error: gorick.dagger2.Dagger2.Component.MeuPrimeiroComponent cannot be provided without an @Provides- or @Produces-annotated method.
gorick.dagger2.Dagger2.Component.MeuPrimeiroComponent is injected at
gorick.dagger2.MainActivity.meuPrimeiroComponent
gorick.dagger2.MainActivity is injected at
gorick.dagger2.Dagger2.Component.ApplicationComponent.inject(mainActivity)

PS: If i use meuPrimeiroComponent.nome(), android studio doesn't find the nome() method.
Comment: From where your injecting `MainActivity` ?
Comment: From MeuPrimeiroComponent.
Answer: You cannot inject values in component instead you need to inject in object whose constructor contains values which is returns by the providers
For more info Ref this Example
You need build Component like this on onCreate():
DaggerMeuPrimeiroComponent.builder()
                // list of modules that are part of this component need to be created here too
                .appContextModule(new AppContextModule(getApplicationContext())) // This also corresponds to the name of your module: %component_name%Module
                .build().inject(this);

Comment: I didn't understand very well your answer.
Comment: I have edited my answer and provided you the example


Show that $x^{2}-6y^{2}=523$ has infinitely many integral solutions

Question: I want to show that $x^2-6y^2=523$  has infinitely many solutions. For the special case $x^2-dy^2=1$, I know what I need to do. I can get the result by using continued fractions. Also, in the kinds of $x^2-dy^2=m$ for some examples, I can say that there is no solution using modulo prime $p$. But in general, I'm not sure how to find the solution set for $ax^{2}+by^{2}+c=0$ where $a,b,c\in \mathbf{Z}$.
I would appreciate if you can help me with this question or direct it to a resource that can help.
Comment: The general question you ask at the end turns out to be quite a difficult problem in general. In the most general case whether a prime $p$ may be written as $ax^2 + by^2 = p$ boils down to asking about the splitting behaviour of a prime $p$ in the Hilbert Class Field of $\mathbb{Q}(\sqrt{D})$ where $D$ is the discriminant of $ax^2 + by^2$.
Answer: You can use a twist on Pell's equation in this case. The fundamental Pell solution for $D=6$ is $(x,y)=(5,2).$ So all positive solutions to $$a^2-6b^2=1$$ are given by $$a_k+b_k \sqrt{6}=(5+2\sqrt{6})^k$$ for $k\in \mathbb{Z}_{+}.$ Here's the fun part: since $(x,y)=(23,1)$ is a solution to $$x^2-6y^2 = 523$$ (found by trying out smaller values of $x$ or $y$ and seeing if the other variable turns out to be an integer), a solution is given by $$x_k + y_k\sqrt{6}=(23+\sqrt{6})(a_k+b_k \sqrt{6})$$ for each positive integer $k.$ It is easy to prove that these are all solutions because if $a^2-6b^2=1$ then
$$(23+\sqrt{6})(a+b\sqrt{6}) = (23a+6b)+(23b+a)\sqrt{6}$$
and
\begin{align*}
(23a+6b)^2-6(23b+a)^2 &= 23^2 (a^2-6b^2) - 6(a^2-6b^2)\\
&= 23^2-6\\
&=523.
\end{align*}
This does not necessarily find all solutions, but you do get infinitely many since they are monotonically increasing in some sense. You can read what Keith Conrad has written about finding all solutions.
Comment: I understood the idea very well. I will read the paper you said to see more details. Thank you for clarifying.
Comment: @TuğbaYesin  here Favst displays the process beginning with $(23,1).$ You get every solution if you do the same process beginning with $(23,-1).$  The reason that just two beginning "seed" points suffice is that 523 is prime. I recommend Weissman,       https://bookstore.ams.org/mbk-105/
Answer: $(23, 1)$ is a solution.
If $(x, y)$ is a solution, then $(5x + 12y, 2x + 5y)$ is also a solution.
Comment: Then I would suppose that the preferred method is to leave a comment inquiring that instead of writing an answer.
Comment: it's better if you show your analysis ( some key details ) that leads to the answer.
Comment: @DeepSea I would like to, but without any context I'm not sure whether the OP is supposed to know the ring $\Bbb Z[\sqrt 6]$ or any of the algebraic number theory backgrounds.
Comment: @TuğbaYesin The first question is easier to answer: simply multiply $x + y\sqrt 6$ by $5 + 2\sqrt 6$. The second question (i.e. finding the first solution) is more complicated. In this simple case, just try every value of $y$, starting from $0$.
Comment: Thank you for the answer, but actually I am curious about the process that continues after finding a solution. Also, finding the first solution isn't always that easy, right?


How to feature-ize multiple vocabularies applied to multiple content types?

Question: Each of my content types is being exported into its own feature. I now need to export several vocabularies that are associated with the content.
Some of the vocabularies are applied to multiple content types. What is my best option for exporting those? Can I export a stand-alone feature that contains all the vocabularies that apply to multiple content types? Or should I associate them all with the most common content type? Or do I have to include each vocabulary in each feature individually?
Answer: An important thing to keep in mind is that things start getting messy when multiple features try to export the same thing. For example, have multiple features that export the same Taxonomy vocabulary. When this happens, best case scenario is that you have to update all the features every time you make a change to the vocabulary. Worst case is, well, worse than that. I've heard some horror stories, but never tried it personally; I do my best to keep proper separation.
In your case, I suggest separating the content types and vocabularies into separate Features. For the vocabularies, you can either put them all in one feature or split them up into separate features, whichever you prefer. I tend to keep all the vocabularies in a single feature, which I think makes sense for your situation as well. For the content type Features, you can now list as a dependency the Features module defining the vocabulary used by that content type.


Determining the order of quantified statement after negation

Question: I'm confused about determining the order in which the quantified symbols should appear and where it's appropriate to place such that when negating the original statement. For example my Professor gave the example $$\mbox{Original Statement: }\exists a\in Z \ni \forall b\in Z , (a+b) = 0 \\ \mbox{Negation: } \exists b\in Z\ni \forall a\in Z, (a+b)\neq 0$$
However, if you just negate the original statement you obtain the order: $$\forall a\in Z, \exists b\in Z \ni (a+b)\neq 0$$
Where I just moved the $\ni$ to where it seemed appropriate.
Comment: The negation you attribute to the professor is incorrect.
Comment: The universal quantifiers are not commutative.
Comment: @Craig first of all, with quantifiers you can no longer use  truth-tables, as there are infnitely many possible domains to consider. But more importantly, the order of quantifiers matters if they are of a different type. Consider: $\forall x \exists y x<y$, means that for every number there is a greater number (true), but $\exists y \forall x x <y$ means that there is a number greater than all numbers (false).
Comment: You are correct and your professor was not.
Comment: Yikes... Well at least it makes sense now.
Comment: @Bram28 Could you elaborate on why the professor is incorrect? I understand it doesn't follow the order in which we are negating original but it has essentially the same statement (only variable names changed) and the negation of the conclusion, therefore if thinking in terms of a truth table I think it should always have the opposite value of the original statement.
Answer: You are correct, and your professor is not.
And yes, the order of quantifiers matters if they are of a different type.
Consider: $\forall x \exists y x<y$, means that for every number there is a greater number (true), but $\exists y \forall x x <y$ means that there is a number greater than all numbers (false).


Java deserialization speed

Question: I am writing a Java application that among other things needs to read a dictionary text file (each line is one word) and store it in a HashSet. Each time I start the application this same file is being read all over again (6 Megabytes unicode file).
That seemed expensive, so I decided to serialize resulting  HashSet and store it to a binary file. I expected my application to run faster after this. Instead it got slower: from ~2,5 seconds before to ~5 seconds after serialization.
Is this expected result? I thought that in similar cases serialization should increase speed.
Comment: How large is the resulting file after serialization? That may also give a hint about the speed.
Comment: About the same. text file is 6.536.068 and serialized binary is 6.879.332
Comment: 2 1/2 seconds is not a whole bunch of time, you might want to preprocess your file to eliminate white space, you could also try zipping it up and benchmarking to see if that increases the speed.
Answer: It's not a question of one serialization mechanism or another, it's a question of the data structure you are serializing.
You have one very efficient, natural representation of these words: a simple list, in the text file. That's fast to read.
You have created a data structure to store them which is different: a hash table. It takes more memory to represent a hash table. However the benefit is that it's very fast to look for a word, compared to a simple list.
But that tradeoff means serialization gets slower as well, since the naive serialization of a hash table will serialize more data and be larger, and therefore slower.
I think you should stick with the simple reading of the text file.
Comment: That seems logical. Except serialized binary file didn't get much larger than original text file 6.536.068 to 6.879.332.
Comment: While it wasn't *longer*, it was *more complex*. That's what is slowing down.
Comment: OK, thanks. I'll take the advice and stick with simple reading.
Answer: @Sean's answer is correct.  Java serialization/deserialization has significant performance overheads.   If you need to make the dictionary loading faster (or ...), consider the following approaches:

Using the java.nio.* classes to read the file may speed things up.
If the application doesn't necessarily need the dictionary to be loaded instantly on startup, consider using a separate thread to do the dictionary loading asynchronously.  The dictionary loading is no faster, but (for example) the application's GUI starts faster anyway.
Comment: Using the separate thread will work for me. Thanks for the idea.

Java deserialization speed


Backprojection from projection matrix using MATLAB

Question: I've a 256x256 projection matrix. each row is a projection taken with equal angles. i need to generate the original image with backprojection using matlab and I am not really familiar with matlab. Can you suggest me any code samples or alghorithms? I've found some similar codes i couldn't generate the original image using them.
Answer: This should be relatively simple with the iradon command, if you have the Image Processing Toolbox. If you don't, it will be a bit tougher because you need to roll your own version of that. Apparently you can't use this, but for what it's worth I get an image if I use:
I = iradon(Pteta',linspace(0,179,size(Pteta,1));

So, how can you do this yourself? I'll try to help you along the way without giving you the answer - this is homework after all!
First, think about your 0-degree projection. Imagine the axis you're projecting on has units 1,256. Now imagine back projection of these coordinates across your image, it would look something like this:

Similarly, think a 90-degree projection would look like this:

Cool, we can get these matrices by using [X, Y] = meshgrid(1:256);, but what about off-axis projections? Just think of the distance along some angled line, like converting polar/Cartesian coordinates:
theta = 45 % projection angle in degrees
t = X*cosd(theta) + Y*sind(theta);

And it works!

There is a problem, though! Notice the values go up over 350 now? Also it's sort of off-center. The coordinates now exceed the length of our projections because the diagonal of a square is longer than the side. I'll leave it to you to figure out how to resolve this, but figure the final image will be smaller than the initial projections, and you may need to use different units (-127 to 128 instead of 1 to 256).
Now you can just index your projections for those angles to backproject the actual values across the image. Here we have a second problem, though, because the values are not integers! We could just round them, this is called nearest-neighbor interpolation, but it doesn't give the best results.
proj = Pteta(angle,:);
% add projection filtering here
t = X*cosd(theta) + Y*sind(theta);
% do some rounding/interpolating to make t all integers
imagesc(proj(t));

For our off-center version, that gives us this image, or something similar:

Now you just need to do this for every angle, and add them all up.
Comment: although i am not allowed to use iradon command, i tried it gave me some random image. I need to get an image of a real thing like a car or a tree.
and angles span [0,pi]
here is the matrix if that helps: http://www.mediafire.com/?rn6j2h7rbkje3oe
Comment: It sounds like this is homework for you, so I've added that tag. Do you understand how backprojection works in general (i.e. on paper)?
Comment: OK, I just opened your projection matrix - is this fan-beam data?
Comment: yes it is my homework, actually just a part of my homework. i need to get filtered backprojection and convolution backprojection but i think i could do them if i knew how backprojection works on matlab. And i understand how backprojection works but this is first time i am using matlab.
edit: yes it is like fan-beam data.
Comment: sorry for the confusion but it is not fan-beam. i dont know how to describe it english but it is like the one here:
http://www.clear.rice.edu/elec431/projects96/DSP/bpanalysis.html
Comment: thank you very much for the detailed answer. this was exactly what i was looking for. i would really love to buy you a beer right now :)


Restrict delete operation on a node referenced by another node

Question: I am using References module to make a node reference in my course content type that reference to school content type (a course belong to one school and a school have many courses).
Now what I want is if I'm going to delete a school, the delete operation will not be completed if the school referenced by any courses.
I've read hook_node_delete() and hook_delete(), written them in my custom module, tried to dpm($node) but no use!
function mymodule_delete($node) {
    dpm($node);
}
function mymodule_node_delete($node) {
    dpm($node);
}

The school node still be deleted!
According to hook_node_info() , I create:
function mymodule_node_info() {
  return array(
     'school' => array(
      'name' => t('School'),
      'base' => 'school',
      'description' => t('A short description'),
    )
  );
}

base: (required) The base name for implementations of
  node-type-specific hooks that respond to this node type. Base is
  usually the name of the module or 'node_content', but not always

And then in my mymodule.module:
function school_delete($node) {
    dpm($node);
}

The code still not working!
Comment: please post the code that is not working
Comment: Hi @Geoff , I use two hook functions above to dpm the $node, but nothing printed, school node always be deleted!
Comment: I used your code and it worked fine for me. I assume you are using as an Admin, if not make sure the permissions for the user role allows access to Devel information. What theme are you using when access the delete page?
Answer: I believe you are invoking the hook incorrectly - according to the API page for hook_delete():

This is a node-type-specific hook, which is invoked only for the node
  type being affected

Further disccussed on the Node API Hooks Page:

Node-type-specific hooks: When defining a node type, hook_node_info()
  returns a 'base' component. Node-type-specific hooks are named
  base_hookname() instead of mymodule_hookname() (in a module called
  'mymodule' for example). Only the node type's corresponding
  implementation is invoked. For example, poll_node_info() in
  poll.module defines the base for the 'poll' node type as 'poll'. So
  when a poll node is created, hook_insert() is invoked on poll_insert()
  only. Hooks that are node-type-specific are noted below.
Comment: Hmm.. I assume the node type is created without any problems?
Comment: And did you clear the cache?
Comment: Oh yes, the node type is created without problems and cached is cleared!
Answer: If you are familiar with Rules (if you are not check here) you can use this selection :
add an integer field to school content type (this field is going to count courses which are referenced to a school)
on node creation event , check if it is a course type , if it is before saving that read the school reference value , then go and increase the school course count .
on node deletion , check if it is a course , then before deletion read the field school and decrease its course count value ,
and finally we are going to use some code :
//Implement hook_delete
function ModuleName_delete($node) {
   if($node->type == "school") //if your type machine readable name is school
   {
       if($node->course_count[LANGUAGE_NONE][0]['value'] < 0) //check field name ...
       {
           node_delete($node->nid);
       }
   }
}


Bootstrap doesn't work in my Rails app with mongodb

Question: I have a simple Rails app with mongodb as my database.
I just want to add bootstrap to it and previously I didn't have any problems with this, but this time I have.
Gemfile
source 'https://rubygems.org'
gem 'rails', '4.2.6'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
gem 'bootstrap-sass'
gem 'sprockets-rails'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
gem 'mongoid'

So, I've added bootstrap-sass
Here I include it in my application.js
//= require jquery
//= require bootstrap-sprockets
//= require jquery_ujs
//= require turbolinks
//= require_tree .

And here in application.scss
/*
 *= require_self
 *= require_tree .
*/
@import "bootstrap-sprockets";
@import "bootstrap";

development.rb
Mongoid.load!("config/mongoid.yml", :development)

mongoid.yml
development:
  clients:
    default:
      database: app
      hosts:
        - localhost:27017
      options:

  options:
test:
  clients:
    default:
      database: app_test
      hosts:
        - localhost:27017
      options:
        read:
          mode: :primary
        max_pool_size: 1

It doesn't work. Moreover, when a try to write something like

test

  <%= yield %>

in my application.html.erb  doesn't display on the page.
Comment: What is output? Some error, blank screen?
Comment: The standart output like Started GET controller etc. But no changes in the interface and no errors.
Comment: In what environment do you run your app (`development` vs. `production`), did you try to run `rake assets:precompile RAILS_ENV=production`? Does that work without errors? Are there errors in your log file?
Comment: I run rake assets:precompile RAILS_ENV=development and got (rake aborted!
Mongoid::Errors::NoEnvironment:
message:
  Could not load the configuration since no environment was defined.
summary:
  Mongoid attempted to find the appropriate environment but no Rails.env, Sinatra::Base.environment, RACK_ENV, or MONGOID_ENV could be found.)
Answer: The problem was that in my controller I wrote
class BotsController < ActionController::Base

Now changed to
class BotsController < ApplicationController

and it works.


Any tips for sealing swimming goggles.masks and keeping water out?

Question: I am having major problem with my goggles. I have 6 pairs of competitive and training grade goggles. If I use the tight low profile goggles when I swim (one hour everyday) I feel pressure above my eyes (very unpleasant when done everyday) and I have to loosen the goggles => Water gets in when swimming rigorously that long and If i use the swimming masks when doing butterfly and breaststroke water gets in when swimming at a very rigorous pace.
Any tips to sealing the goggles better? any sort of coating or material I can use to seal them better?
Answer: I would advise a less obvious answer: no gasket/seal at all!
I (and almost all members of our swimming team) was using the well known Swedish goggles. They come unassembled, so you have to assemble them by yourself but can then adapt them perfectly: single or double rubber strip around the head (I used two, one quite high on the head and another one quite low, but you may prefer something different), size and length of nose piece, which will help both cups to stay in contact with your skin when the length is correctly adapted.
Despite what most people think, they are not less comfortable than other goggles but really have to be well assembled to your face's dimensions. So, lots of trial and error but you'll end up with a tailor-made goggle. Bring everything you need to adapt them directly at the pool, so you can modify nose piece length, try for 50 meters and adapt again if needed.
I didn't check recently but I think some (most?) of the current competitive swimmers still use this kind of goggles and they swim quite vigorously!
You can even be fashionable and use two cups of different color should you want it!
And best of all, being just two plastic cups, a strap and a piece of string, they are quite cheap!
Answer: When I used to compete a lot, the solution (given the technology back then was not advanced, so goggles were not as streamlined and the gaskets weren't as good as they are today) was to overtighten them. Yes, it's uncomfortable, but it works.
Nowadays, most goggles should seal themselves incredibly well, so no matter what stroke you are swimmiing, or how hard you are swimming you should not get leaks.
If you are getting leaks, the things to look at:

style: are you choosing goggles that are the right fit for you? Everyone's face is a different shape, so shop around. I have a wide bridge of my nose, so I need to pick up goggles which accommodate this - they are easily available.
tension: are you tightening them up enough, and ensuring that you have not only a tight strap, but also suction behind the goggles
dive: you could be losing a bit of the seal on your dive. Have a look at my answer on this question to see how wearing two caps can help with this
Answer: I don't know about a product to for sealing the goggles, but I switched to using a different brand of goggle a while back and I haven't had any leakage problems since. I use Aquasphere Kayenne. The seal is really good and the eye piece/strap connector has a little button you can press to adjust the tension slightly without having to adjust the fit and seal. You can see it on this picture - http://www.amazon.co.uk/dp/B0025KURO2/?tag=hydra0b-21&hvadid=9556669869&ref=asc_df_B0025KURO2 (I know it's an Amazon picture and I'm not promoting them or suggesting you buy them, but there's a handy zoom function so that you can see exactly what I mean!)
They're not suitable for everyone - they're rather bulky so may be a bit big for competitive swimming. But I swim long distance, indoor and outdoor, and they work really well for me. And I've tried many different styles before these ones.
Comment: Do you find the Aquaspheres start to leak after a few months? I find them great when new, but need to replace them every three or four months when the seal starts to go. I clean them with hand soap every time I use them, but I don't keep the hard case. Any thoughts?


Calculate the sum for 3 CCK fields with Rules in Drupal 7

Question: I have 4 stock fields (Stock 1, Stock 2, Stock 3 and TOTAL STOCK) and I want to set up a rule to calculate ["+"] the sum of Stock 1, Stock 2 and Stock 3 fields, and automatically appear in TOTAL STOCK field.
example -> http://ucreateawebsite.com/DRUPAL/dalexgrup/pt
What event, conditions and actions Should I use?
Thank you.
Answer: I found the answer:
For Event I used:

After updating an existing commerce product

For Conditions I used:

Entity has field

Parameter: Entity: [commerce-product], Field: field_stock1

Entity has field

Parameter: Entity: [commerce-product], Field: field_stock2

Entity has field

Parameter: Entity: [commerce-product], Field: field_stock3

Entity has field

Parameter: Entity: [commerce-product], Field: field_totalstock

For Actions I used:

Calculate a value

Parameter: Input value 1: [commerce-product:field-stock1], Input value 2: [commerce-product:field-stock2]; Provides variables: Calculation result for Stock1  and Stock2 (stock1_plus_stock2_result)

Calculate a value

Parameter: Input value 1: [stock1-plus-stock2-result], Input value 2: [commerce-product:field-stock3]; Provides variables: Calculation result for stock1-plus-stock2-result and Stock3 (stock1_plus_stock2_result_plus_stock3)

Set a data value

Parameter: Data: [commerce-product:field-totalstock], Value: [stock1_plus_stock2_result_plus_stock3]

You can see what I wrote on http://ucreateawebsite.com/DRUPAL/dalexgrup/pt.
Answer: You can try playing with:
Event: on updating content
Conditions: entity has field (to have it available in actions) for stock1, stock2 and stock3
Actions: set data value
Comment: ok I tried, but no success.


how to exclude image while saving Rss Feed In dataBase and need to show full Feed Description in page

Question: while i am saving RssFeed in Database all Fields are saving like link,Id etc but coming to Description it saving only smalldescription  until image Src coming and stopping there onwards.i just want to Ignore image and need to save full Description and show in my page.i am showing Rss Feed in Repeater control i will post my code here thanks in advance
aspx :
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="RSSFeed.aspx.cs" Inherits="RSSFeed" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">

        <%--  <asp:Label ID="lblBlogOutput" runat="server"></asp:Label>
        <asp:Label ID="Label1" runat="server"></asp:Label>
        <asp:Label ID="Label2" runat="server"></asp:Label>--%>
        <asp:Repeater ID="Repeater1" runat="server">
            <ItemTemplate>

                    <asp:HyperLink ID="TitleHyperLink" runat="server" Text='<%#Eval("Title") %>' NavigateUrl='<%#Eval("Link") %>'></asp:HyperLink>

                        <asp:Label ID="DescriptionLabel" runat="server" Text='<%#Eval("Description") %>'></asp:Label>
                          <%--
<asp:HyperLink ID="MoreHyperLink" runat="server">See More...</asp:HyperLink>
--%>

                    <asp:Label ID="PublishedLabel" runat="server" Text='<%#Eval("Published") %>'></asp:Label>
                        <%--<asp:Label ID="Label1" runat="server" Text='<%#Eval("SmallDescription") %>'></asp:Label>--%>
                          <%--<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/NewsFeedinfo.aspx?RssId={0}">See More...</asp:HyperLink>--%>
                        <asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl='<%# "NewsFeedinfo.aspx?RssId=" + Eval("RssID") %>' >See More...</asp:HyperLink>

            </ItemTemplate>
        </asp:Repeater>

</asp:Content>

aspx.cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data;

public partial class RSSFeed : System.Web.UI.Page
{
    RssDC rssDC = new RssDC();
    RssBAL rssBAL = new RssBAL();

    protected void Page_Load(object sender, EventArgs e)
    {

        BlogFeeds("http://rss.cnn.com/rss/edition_americas.rss", 3);
        BlogFeeds("http://feeds.bbci.co.uk/news/rss.xml?edition=int#", 3);
        BlogFeeds("http://feeds.reuters.com/reuters/Election2012", 3);

        fillRssFeeds();

    }

    private void fillRssFeeds()
    {
        DataSet ds = new DataSet();
        ds = rssBAL.GetRssFeeds(rssDC);

        Repeater1.DataSource = ds;
        Repeater1.DataBind();
    }
    protected void BlogFeeds(string url, int count)
    {

        try
        {

            RssDC rssDC = new RssDC();
            XmlDocument xmldoc = new XmlDocument();
            XmlNodeList items = default(XmlNodeList);
            xmldoc.Load(url);
            items = xmldoc.SelectNodes("/rss/channel/item");
            int i = 0;
            // use XPath to get only items

            foreach (XmlNode item1 in items)
            {
                int currentIterationIndex = 0;
                foreach (XmlNode node1 in item1.ChildNodes)
                {
                    if (currentIterationIndex == count - 1)
                    {
                        continue;
                    }

                    if (node1.Name == "title")
                    {
                        rssDC.Title = node1.InnerText;
                    }
                    else if (node1.Name == "link")
                    {
                        rssDC.Link = node1.InnerText;
                    }
                    else if (node1.Name == "guid")
                    {
                        rssDC.RSS_ID = node1.InnerText;
                    }
                    else if (node1.Name == "description")
                    {
                        rssDC.Description = node1.InnerText;
                    }
                    else if (node1.Name == "pubDate")
                    {
                        rssDC.DatePublished = node1.InnerText;

                    }
                    currentIterationIndex += 1;

                }
                rssDC = RssBAL.AddRssFeed(rssDC);
                i++;

                if (i == 3)
                    break;

            }

        }
        catch (Exception eax)
        {
            //return;
        }

        //return rssFeedList;
        //Repeater1.DataSource = rssFeedList;
        //Repeater1.DataBind();
    }
}

Answer: Remove the asp:Label and use <%# Eval("Description") %> without it.


UITableview , dynamically section & rows

Question: want create a uitableview dynamically with 2 rows in one section
i write this code but i have problem the repeats  only 2 first rows in all sections
now i have this  row 0,1 -> section 0 , row 0,1 -> section 1 , row 0,1 -> section 2
want read all rows after for example   row 0,1 -> section 0 , row 2,3 -> section 1 , row 4,5 -> section 2 -> row 6,7
         items = [[NSMutableArray alloc] init];
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    { return items.count/2; }

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    { return 2; }

 - (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    UILabel *label = nil;

    cell = [tv dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"Cell"] autorelease];
        label = [[UILabel alloc] initWithFrame:CGRectZero];
        [label setLineBreakMode:UILineBreakModeWordWrap];
        [label setMinimumFontSize:FONT_SIZE];
        [label setNumberOfLines:0];
        [label setFont:[UIFont systemFontOfSize:FONT_SIZE]];

        [label setTag:1];

        label.textColor = [UIColor darkGrayColor];

        [label setAlpha:0.8];

        cell.backgroundColor = [UIColor whiteColor];

        [[cell contentView] addSubview:label];

    }
    NSString *text = [items objectAtIndex:[indexPath row]];

    CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);

    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];

    if (!label)
        label = (UILabel*)[cell viewWithTag:1];

    [label setText:text];
    [label setFrame:CGRectMake(CELL_CONTENT_MARGIN-5, CELL_CONTENT_MARGIN+30, CELL_CONTENT_WIDTH - ((CELL_CONTENT_MARGIN * 2)+6), MAX(size.height, 44.0f))];

    label.backgroundColor = [UIColor clearColor];

     cell.selectionStyle = UITableViewCellSelectionStyleNone;

    for (UIView *theSubview in [cell.contentView subviews])
    {
        if([theSubview isKindOfClass:[UIImageView class]])
        {
            [theSubview removeFromSuperview];
        }
    }

    UIImageView *imv = [[UIImageView alloc]initWithFrame:CGRectMake(128,5, 32, 32)];
    imv.image=[UIImage imageNamed:@"0England.png"];
    [cell.contentView addSubview:imv];
    [imv release];

     if (indexPath.row % 2==0) {

        UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(-7 ,10, 8, 18)];
        img.image=[UIImage imageNamed:@"...."];

        [cell.contentView addSubview:img];
        [img release];

    }
    else {  }

     return cell;
}

Comment: Can you please post your cellForRowAtIndexPath function?  The problem would probably be in your mapping of indexPath -> items[index].
Comment: Why are you posting this same question (which you did 20 minutes ago) under another user name?
Comment: @shadow, each sections has rows starting from 0. It doesn't work like section 0 has row starting from zero, section one rows starting at 1. If its that what you want.
Comment: i update this questions
Comment: i want creat one section for 2 rows

one even row and one odd row in one section
Answer: You have a problem in your mapping of indexPaths to the rows of your data structure (in this case, your items array).  Each section will be numbered from 0 to ceil(n/2) (which, by the way, should be the number of sections, not simply n/2) where n is the number of elements in items.
Each row inside the section will have an indexPath.row of 0 or 1.
Therefore, in order to map from indexPaths back to your items array, you have to do something like this in your cellForRowAtIndexPath function:

NSString *text = [items objectAtIndex:([indexPath section]*2 + [indexPath row])];

Comment: Yes, I think I get what you're trying to do.  That's what the code I presented here would do.
Comment: doesn't any change

i think the problem is for  //tableView numberOfRowsInSection
Comment: Why would it be there?  You said that you're getting the same two rows repeated in each section, correct?  the `numberOfRowsInSection` method just tells the table view how MANY rows there are in a section, not WHICH ONES go there.  If you have tried this code and it doesn't work, please update your question with more specifics on the behavior you're seeing.
Comment: no  dosent repeat !! i want unique rows in section

now i have row 0,1 -> section 0 , row 0,1 -> section 1

--------
i want this row 0,1 -> section 0 , row 2,3 -> section 1 , row 4,5 -> section 2


How can I store information on after I press a button?

Question: I have a problem that I don't know how can I add the information to a new page when I click a button. For example I have an add-to-cart button and when I press it I want to store some information. How can I do it? I want to be able to add some information on a click of a button but I don't know how to do it. For example the add to cart button is not working and I want to be able to click it and store information, How?

.products .box-container {
  display: flex;
  flex-wrap: wrap;
  gap: 1.5rem;
}

.products .box-container .box {
  flex: 1 1 30rem;
  box-shadow: 0 .5rem 1.5rem rgba(0, 0, 0, .1);
  border-radius: .5rem;
  border: .1rem solid rgba(0, 0, 0, .1);
  position: relative;
}

.products .box-container .box .discount {
  position: absolute;
  top: 1rem;
  left: 1rem;
  padding: .7rem 1rem;
  font-size: 2rem;
  color: var(--pink);
  background: rgba(255, 51, 153, .05);
  z-index: 1;
  border-radius: .5rem;
}

.products .box-container .box .image {
  position: relative;
  text-align: center;
  padding-top: 2rem;
  overflow: hidden;
}

.products .box-container .box .image img {
  height: 25rem;
}

.products .box-container .box:hover .image img {
  transform: scale(1.1);
}

.products .box-container .box .image .icons {
  position: absolute;
  bottom: -7rem;
  left: 0;
  right: 0;
  display: flex;
}

.products .box-container .box:hover .image .icons {
  bottom: 0;
}

.products .box-container .box .image .icons a {
  height: 5rem;
  line-height: 5rem;
  font-size: 2rem;
  width: 50%;
  background: var(--pink);
  color: #fff;
}

.products .box-container .box .image .icons .cart-btn {
  border-left: .1rem solid #fff7;
  border-right: .1rem solid #fff7;
  width: 100%;
}

.products .box-container .box .image .icons a:hover {
  background: #333;
}

.products .box-container .box .content {
  padding: 2rem;
  text-align: center;
}

.products .box-container .box .content h3 {
  font-size: 2.5rem;
  color: #333;
}

.products .box-container .box .content .price {
  font-size: 2.5rem;
  color: var(--pink);
  font-weight: bolder;
  padding-top: 1rem;
}

.products .box-container .box .content .price span {
  font-size: 1.5rem;
  color: #999;
  font-weight: lighter;
  text-decoration: line-through;
}

  -18%

      add to cart

Costop Pro Spray

 26.90€ 31.74€

Thanks to anyone who can help!
Comment: A database can hold data for you. You can put them in a database to and on the next page can request the data from the database. Second option is to use a JSON and Javascript.
Answer: if you want to save info about order, then you need use DOM. For example you can save info in local storage. For it - write script inside eventListener

const box = document.querySelector('.box')
add.eventListener('submit', () => {
  // here your logic
})

  -18%

      add to cart

Costop Pro Spray

 26.90€ 31.74€

  <button type='submit'>Add to basket</button>

Comment: Sorry but can you examplify the js code as well? I don't know how to do it, I'm new to this sorry :)
Answer: you just need to replace anchor link with button and use js to update your cart price dynamically

.products .box-container{
    display: flex;
    flex-wrap: wrap;
    gap:1.5rem;
}

.products .box-container .box{
    flex:1 1 30rem;
    box-shadow: 0 .5rem 1.5rem rgba(0,0,0,.1);
    border-radius: .5rem;
    border:.1rem solid rgba(0,0,0,.1);
    position: relative;
}

.products .box-container .box .discount{
    position: absolute;
    top:1rem; left:1rem;
    padding:.7rem 1rem;
    font-size: 2rem;
    color:var(--pink);
    background:rgba(255, 51, 153,.05);
    z-index: 1;
    border-radius: .5rem;
}

.products .box-container .box .image{
    position: relative;
    text-align: center;
    padding-top: 2rem;
    overflow:hidden;
}

.products .box-container .box .image img{
    height:25rem;
}

.products .box-container .box:hover .image img{
    transform: scale(1.1);
}

.products .box-container .box .image .icons{
    position: absolute;
    bottom:-7rem; left:0; right:0;
    display: flex;
}

.products .box-container .box:hover .image .icons{
    bottom:0;
}

.products .box-container .box .image .icons a{
    height: 5rem;
    line-height: 5rem;
    font-size: 2rem;
    width:50%;
    background:var(--pink);
    color:#fff;
}

.products .box-container .box .image .icons .cart-btn{
    border-left: .1rem solid #fff7;
    border-right: .1rem solid #fff7;
    width:100%;
}

.products .box-container .box .image .icons a:hover{
    background:#333;
}

.products .box-container .box .content{
    padding:2rem;
    text-align: center;
}

.products .box-container .box .content h3{
    font-size: 2.5rem;
    color:#333;
}

.products .box-container .box .content .price{
    font-size: 2.5rem;
    color:var(--pink);
    font-weight: bolder;
    padding-top: 1rem;
}

.products .box-container .box .content .price span{
    font-size: 1.5rem;
    color:#999;
    font-weight: lighter;
    text-decoration: line-through;
}

            -18%

                    <button class="cart-btn" onclick="updateCart(10,12)">add to cart</button>

Costop Pro Spray

 0€ 0€

Comment: For example I have 9 items to make this "add to cart" how can I do it then?
Comment: just pass separate values from each calling button , and will increase price.

    add to cart
add to cart
add to cart


How to scrape data with filters from the website when the URL doesn't change?

Question: I've scraped data from this list in R, however it doesn't include the website filters (List = Oxford 3000 and CEFR level = A1) that I had applied, and there aren't variables as far as I can see which I can use to filter the data in R.
Is there some other way I can get just the data I want? The URL doesn't appear to change with filtering.
Here is my code:
url <- "https://www.oxfordlearnersdictionaries.com/wordlists/oxford3000-5000"

url %>%
  map(. %>%
    read_html() %>%
      html_nodes(".belong-to , .pos , a") %>%
      html_text()
  ) %>%
  unlist() -> ox3ka1

Answer: To select only the words with filter a1 we can do the following,
df = 'https://www.oxfordlearnersdictionaries.com/wordlists/oxford3000-5000' %>% read_html() %>% html_nodes('.top-g') %>% html_nodes( "li[data-ox5000 = 'a1']") %>% html_text()

head(df)
[1] "   a   indefinite articlea1      " "   about   adverba1      "         "   about   prepositiona1      "    "   above   adverba1      "
[5] "   above   prepositiona1      "    "   across   adverba1      "

Further reference,
How do I use html_nodes to select nodes with "attribute = x" in R?


Filter result by using global php value in views

Question: I am appending city code and city value in global php field in views
Now I want to filter the result based on this field value.
For example if a record having city code:NY and city:New York If i search NY-New York then it should filter the results.
Any help plz..
Comment: did you tried grouping fields of code and city in views?
Comment: Yes displaying..lets simple..I want add filter for global php field in views?
Comment: I'm not sure if I understood you correctly. But try creating a view with grouped fields as "Code" and "City", then simply bind with token filter and output the result as replacements pattern. Tell me if that works.
Answer: Long story short, using views filters change the SQL query, by adding a where clause in the SQL query. The limitation by this is that information needs to be in the database. Since the global PHP field doesn't exist in the database, it's not possible to use views filter on such a value.
You could write some code in a custom module, where you implement the logic and removes all unwanted records, but this wont perform well.
Generally you should avoid the global PHP fields if at all possible.


User role wise permission for controller function in laravel

Question: I am working with laravel5.4. I need to create role wise permission for every method.
Here I have created one middleware (roles) as below :
CheckRole.php
public function handle($request, Closure $next)
{
    $role = array_slice(func_get_args(), 2);
    if ( ! User::find(auth()->id())->hasAnyRole($role))
    {
        return response("Insufficient permission",401);
        session()->flash('message',"You have no permission to access");
        return redirect('/');
    }
    return $next($request);
}

I have one controller as CompanyController :
CoompanyController.php
public function __construct()
{
    $this->middleware(function (Request $request, $next)
    {
        $this->user = \Auth::User();
        //print_r($this->user);exit;
        if($this->user['userrole_id'] == 1)
        {
            $this->middleware('roles:superadmin');
        }
        else if ($this->user['userrole_id'] == 3)
        {
            $this->middleware('roles:supportperson',['only' => ['index']]);
        }
        return $next($request);
    });
}

Here, if login user is superadmin than he can access all the function of controller. And If login user is supportperson than he can access only index method.
So how can I set permission to function for different rolewise using same middleware?
Comment: IMHO laravel ships with a fully configurable Authorisation system. There is no need for a custom middleware. See here: https://laravel.com/docs/5.4/authorization
Comment: @dparoli I am new  in laravel so i don't know how to use it. So i user middleware.
Comment: first rule is don't reinvent the wheel, laravel codebase is a large beast to fight, read the docs before any customization.
Comment: @dparoli Ok. thanks
Answer: use https://github.com/Zizaco/entrust
Entrust is a succinct and flexible way to add Role-based Permissions to Laravel 5.


Cannot start services on CentOS 7

Question: Suddenly, I cannot start services on my VPS(CentOS 7). For example,
service httpd start
Redirecting to /bin/systemctl start  httpd.service
Authorization not available. Check if polkit service is running or see debug message for more information.
Failed to start httpd.service: Connection timed out
See system logs and 'systemctl status httpd.service' for details.

This is probably because the domain name I used as the host name has expired. I do not know the logic behind the service command. I start httpd, why does it invoke polkit service? The polkit service is also dead and cannot be started. The "service polkit status -l" command shows a message:
Lost the name org.freedesktop.PolcyKit1 - exiting

How to solve the problem?
Comment: what does `systemctl start httpd` return?
Answer: You need to use sudo
[user@localhost ~]$ sudo systemctl start httpd

or login as root
[root@localhost ~]# systemctl start httpd

in order to start and stop services.
Comment: I am also having this problem, however I still get the same error message even when as root. Do you have any suggestions?
Comment: @rnoodle Click the Ask Question button.

Cannot start services on CentOS 7


Hardly-used Ubuntu 12.04 server shows high CPU / Disc I/O every 8 hours

Question: I have a basic cloud-based server that is only used here and there for testing. Since I installed New Relic (yesterday) it has reported high Disc I/O and high CPU problems (>90%) every 8 hours for a total of 25 minutes (approx.) each time.
New Relic seems to show these issues:
(a) very high CPU issue with "find (root)"
(b) high usage of dev/xvda1

My server provider doesn't know what the issue is as they see nothing at their end.

My logs show zero usage - no visitors at the time.
There are no issues with PHP/Apache on that server (according to New Relic).
Some security tests show the server isn't compromised.

What does all this mean? Is there anything I need to do at my end?
Comment: cron job running every 8 hours?
Answer:
(a) very high CPU issue with "find (root)"

This is likely the update scripts rebuilding the locate database, or some other script scanning through your disk for whatever reason. If you type ps auxwwf when the problem is happening, then you can see the process tree; look for the 'find' process which is causing the issue and then see what's running it (probably something like 'updatedb').
Answer: Dan is (was) most likely correct. I used this post and another to solve my problem,
I have a VMWare Linux Mint 17.1 that has a similar issue. A few minutes after it is started 90-100% of the CPU is consumed for 15 or so minutes--it has a rather large shared directory that has a lot of genetic data in it.
I used top to get the find process id (12788). Since it was consuming all CPU power, it was the first line on top. One difference here is that the offending process was owned by "nobody".
Then I ran ps -auxwwf and found this tree--notice the find command on the last line.
root      1334  0.0  0.0  12780   960 ?        Ss   07:15   0:00 anacron -s
root     12676  0.0  0.0   4440   652 ?        S    07:20   0:00  \_ /bin/sh -c run-parts --report /etc/cron.daily
root     12677  0.0  0.0   4332   648 ?        S    07:20   0:00      \_ run-parts --report /etc/cron.daily
root     12749  0.0  0.0   4440   652 ?        S    07:20   0:00          \_ /bin/sh /etc/cron.daily/locate
root     12754  0.0  0.0   4440   744 ?        SN   07:20   0:00              \_ /bin/sh /usr/bin/updatedb.findutils
root     12762  0.0  0.0   4440   336 ?        SN   07:20   0:00                  \_ /bin/sh /usr/bin/updatedb.findutils
root     12788  0.0  0.0  86152  2384 ?        SN   07:20   0:00                  |   \_ su nobody -s /bin/sh -c /usr/bin/find / -ignore_readdir_race      \( -fstype NFS -o -fstype nfs -o -fstype nfs4 -o -fstype afs -o -fstype binfmt_misc -o -fstype proc -o -fstype smbfs -o -fstype autofs -o -fstype iso9660 -o -fstype ncpfs -o -fstype coda -o -fstype devpts -o -fstype ftpfs -o -fstype devfs -o -fstype mfs -o -fstype shfs -o -fstype sysfs -o -fstype cifs -o -fstype lustre_lite -o -fstype tmpfs -o -fstype usbfs -o -fstype udf -o -fstype ocfs2 -o      -type d -regex '\(^/tmp$\)\|\(^/usr/tmp$\)\|\(^/var/tmp$\)\|\(^/afs$\)\|\(^/amd$\)\|\(^/alex$\)\|\(^/var/spool$\)\|\(^/sfs$\)\|\(^/media$\)\|\(^/var/lib/schroot/mount$\)' \) -prune -o -print0

I do not have rpm installed, so I used the Synaptic Package Manager GUI and searched for "updatedb" in package and name. The only package installed with updatedb was "locate". I then removed the locate package.
Another good answer with command line tools is on Unix Stack Exchange about disabling locate/updatedb


De-conflicting data strategies when associating two tables

Question: I have some tables that look like this:
+------------+------------+------------+----------------+----------+
| Locations  |  HotelsA   |  HotelsB   | HotelsB-People |  People  |
+------------+------------+------------+----------------+----------+
| LocationID | HotelAID   | HotelBID   | PersonID       | PersonID |
| Address    | HotelAName | HotelBName | HotelBID       | Name     |
|            | LocationID |            |                |          |
+------------+------------+------------+----------------+----------+

Currently, if I want to know what the address is of the hotel someone is staying at there is no way to make that association without manually looking through the names of HotelsA for something that looks similar enough to the name of HotelsB.
I would like to remove HotelBName and replace it with a foreign key to HotelAID (in this example it would actually make more sense to change HotelsB-People to HotelsAPeople, but there are additional columns that I have omitted for simplicity that prevent that solution from being viable in my particular case). The end result would look like this:
+------------+------------+-------------+----------------+----------+
| Locations  |  HotelsA   |   HotelsB   | HotelsB-People |  People  |
+------------+------------+-------------+----------------+----------+
| LocationID | HotelAID   | HotelBID    | PersonID       | PersonID |
| Address    | HotelAName | FK_HotelAID | HotelBID       | Name     |
|            | LocationID |             |                |          |
+------------+------------+-------------+----------------+----------+

HotelAName and HotelBName are likely very similar, but inconsistently so. You could have "Springfield Marriott" in one and "Marriott, Springfield" in the other, but there's no consistency (no guarantee anything is spelled correctly either).
Are there any strategies for how this could be done as well as considerations for how to make the applications that utilize this data continue to work during the time it takes to fix all of the data?
Thank you.
Answer: I would just add the FK_HotelAID column to the HotelsB table.  Assigning the correct id to that column will largely be a manual process, although you could try joining HotelAName to HotelBName to at least cover the ids for names that have a perfect match.  Your applications should continue to work while you do this.  After you've assigned all the ids inHotelsB you can define the foreign key and then delete the HotelBName column.  Of course, any references that the applications make to HotelBName will need to be modified.


A generic UIPickerView+UITextField function in Swift

Question: I am trying to make a function called
`createSpinner(params: Dictionary<String, AnyObject>) -> UITextField`

which will take parameters like height, width and return a UITextField in which there will be a UIPickerView attached. Also, I am trying to find a way to integrate even the controllers in it.
Till now I have created the UITextfield in the function and also added a dropdown button to the right of the UITextField. Then I have initialized a UIPickerView in the function and added it to the inputView of the UITextField instance.
Now the problem I am facing is, when the user touches the dropdown, I want to call a function using addTarget to bring up the UIPickerView instance. Where should I implement the action: of addTarget and what should the target in addTarget be?
Answer: You have two options to link those actions. The first is to hook up to the UITextFieldDelegate where you can use textFieldDidStartEditing or you can fake the UITextField by creating a UIButton where you can hook up to various UIControlEvents.
Comment: What if I want to use my function to create 2 input spinners in the same view?
Comment: Subclass the UITextField and add those spinners as subviews?


how to remove junk characters in file the data looks like this

Question: [15;1Runts/Jumbos        [16;1Errors Rx/Tx        [17;1Total Rx Pkts       [18;1      Tx Pkts       [19;1      Rx MBs        [20;1      Tx MBs        [21;1ARP/ICMP Pkts       [23;1Pattern Type        [24;1Tx Count/% Rate     [25;1PktSize/Tx Burst    [26;1Src/Dest Port
Answer: You could do this with regex replacement.
<code>import re
string = '[15;1Runts/Jumbos [16;1Errors Rx/Tx [17;1Total Rx Pkts [18;1 Tx Pkts [19;1 Rx MBs [20;1 Tx MBs [21;1ARP/ICMP Pkts [23;1Pattern Type [24;1Tx Count/% Rate [25;1PktSize/Tx Burst [26;1Src/Dest Port'
print(re.sub('\[\d{1,2}\;\d','',string))
>>> 'Runts/Jumbos Errors Rx/Tx Total Rx Pkts  Tx Pkts  Rx MBs  Tx MBs ARP/ICMP Pkts Pattern Type Tx Count/% Rate PktSize/Tx Burst Src/Dest Port'
</code>


Vector calculus "identities"

Question: Do these "identities" even make sense? $F$ is a 3D vector field. For the second equation, the LHS is a vector but the RHS is a scalar.
$$\nabla\cdot\Delta F=\Delta(\nabla\cdot F),\,\nabla\times\Delta F=\Delta(\nabla\times F)$$
Comment: Notice that, since $F$ is a vector field, $\Delta$ must be the [vector Laplacial](https://en.wikipedia.org/wiki/Laplace_operator#Vector_Laplacian) both on the LHS and on the RHS.
Answer: The first equation means $\partial_i(\partial_j\partial_j F_i)=\partial_j\partial_j(\partial_i F_i)$. The second means $\epsilon_{ijk}\partial_j(\partial_l\partial_l F_k)=\partial_l\partial_l(\epsilon_{ijk}\partial_j F_k)$.
Comment: @user770687 You should actually consider *thrice*-differentiable $f,\,g,\,h$, but the error in your reasoning is that you need the [vector Laplacian](https://en.wikipedia.org/wiki/Laplace_operator#Vector_Laplacian), as Gae. S. already noted.
Comment: With repeated indices summation convention
Comment: sorry, but I must be misunderstanding something. For the second equation, suppose $F = < f,g,h>$ where $f(x,y,z), g(x,y,z), h(x,y,z)$ are twice differentiable scalar functions, then the curl of the Laplacian of $F$ is a 3-by-1 vector $< \Delta F_y - \Delta F_z, \Delta F_z - \Delta F_x, \Delta F_y - \Delta F_z>$ whereas the Laplacian of the curl of $F$ is $(h_y - g_z)_{xx} + (f_z - h_y)_{yy} + (g_x - f_y)_{zz}$ . The LHS is a vector and the RHS is a scalar, no?
Comment: Thank you, I see that now.

Vector calculus "identities"


NoSql document structure

Question: I have a database of 3 tables:
Brands (think MacDonalds) -> shops -> sales
Each shop has many sales and each brand has many shops. If I want to query how many sales McDonalds has in order to build a report how do I structure my brands document? Do I keep a sales field in the brands document which gets updated whenever each shop makes a sale or I keep a sale field in the shops document and then I loop through all the shops to create a SUM of sales for each brand.
First approach will probably behave better on reads while the second on writes. My database will have more reads than writes (at least at start) so I'm interested to find out what's the standard way of doing this in MongoDB especially.
Coming from a relational DB I would probably have Shops -> BrandShops -> Shop -> Sales etc but I'm just trying out Mongo. Thanks.
Comment: Is `sales` just a number (per brand)? Or a document for every sale made? Is `shops`:`brand` many-to-many ?
Comment: Yes `sales` is a counter of how many sales a brand has. Each shop should also have `sales` field if the admin digs deeper. `brand`:`shops` is one to many.
Answer: When you have a one-to-many relation in MongoDB, it is usually preferable to embed the data in the owning object instead of representing the relation with database references. The reason is that MongoDB doesn't support joins - when you need data from two different collections, you need to query both collections separately.
When you have a many-to-many relationship, you should use arrays of references instead of embedding, because otherwise you would have to update all the objects which embed an object which changed.
But note that there is a 16MB limit per document in MongoDB. When the object with embedded objects could get close to this limit, you should still use references (either in form of an array in the owning object, or a field in the owned object).
References in MongoDB can be either object IDs, DBRef's (which many drivers can resolve automatically or semi-automatically) or a custom unique identifier like a name or an ID number. The latter has the advantage that you can show the user a meaningful overview list of the related documents without querying them all. Needless to say, that this field should have an unique index in the referenced collection. You can also combine the reference with some essential data points of the referenced object to be able to present a more meaningful preview to the user.

NoSql document structure