How i can add a new line in my code here?

Question: HI guys go to THE TEXT THAT FOLLOWS I WANT IT IN NEW LINE and help how to separate that text in 2 lines
 $form['kkkkkk'] = array(
          '#type'          => 'textfield',
          '#title'         => t('blablabla'),
          '#default_value' => variable_get('kkkkkkkk', ''),
          '#description'   => t('sdakgbflabfgdsbf "THE TEXT THAT FOLLOWS I WANT IT IN NEW LINE" fdghhtrjgvfnbhsgf.'),
          '#required'      => TRUE,
          '#size'          => 10,
          '#required'      => TRUE,
        );

Answer: There are two options (simplified code example):

$description = t('Foo.
Bar.'); (recommended)
$description = t('Foo.') . '
' . t('Bar.');

The
 tag causes a line break in HTML. Both options give the same result technically. The difference is in what translators can do with it.
Option 1 treats the sentence as a unity and gives translators more flexibility. For instance, if the French translation needs to change the word order ('Barre.
Fou.'), that's possible. However the French translator would also have the possibility to leave out the line break completely.
Option 2 is more rigid. A translator could never control which part comes before the line break and which part comes after. The translator may not even know that the sentences "Foo." and "Bar." will be combined into a single page element, because they show up as separate strings in the translation interface.
Comment: Option 2 shouldn't be used - placeholders should always be used instead if you need to intersperse vars into a translated string, never concatenated according to Drupal best practices. See http://drupal.stackexchange.com/questions/96622/how-to-use-t-function-for-a-text-with-anchor-links for more info and links to official docs
Comment: Clive, I would rather say that option 2 is usually not the correct solution. There are some situations where it makes sense. You can even find this pattern in Drupal core, for instance in [_filter_html_tips](https://api.drupal.org/api/drupal/modules!filter!filter.module/function/_filter_html_tips/7).
Comment: Not to argue, but I think the reasoning in the best practice document means there _can't_ be any exceptions, and that its use in any core code is actually a bug...I shall report it and we'll see what the outcome is, will update when I get a response :)
Comment: OK, thanks for reporting it, I'm curious to see what the response is. For the record, I found the core examples by doing a regex search for `t\('.*'\) . '<.*>' . t\('.*'\)` on a Drupal 7 site. Anyway I'll update the answer to indicate that option 1 is recommended.
Comment: By the way, @Clive, I think the best practices at https://www.drupal.org/node/322774 describe a slightly different use case than this question. That page is only about links. As we all know the `` tag needs to wrap text, while this question is merely about inserting a tag between two strings.
Comment: I read it as "Dynamic or static links **and** HTML in translatable strings" (emphasis mine). I see what you're saying though, could be ambiguous
Comment: I am using t() to populate the body of a mail that I am sending, Using the first option of adding  doesn't seem to work. Is there any other way to add a line break?
Comment: @Bej By default Drupal sends plain text emails. You cannot simply turn plain text email into HTML mail by adding some tags in the body. To send HTML mail you need additional modules such as [Mime Mail](https://www.drupal.org/project/mimemail).


How to implement 3D / tilt mode in mapview?

Question: If you check the Google Maps application for Android, there are 3 modes available to display the listview. One of the modes available in Google Maps is the tilt mode wherein the map is displayed in 3D. The map also rotates when the user changes his direction.
How can I achieve this functionality?
Comment: Perhaps, with perspective projection/mapping, like in 3d shooting games?
Answer: If you're referring to an Android MapView allowing you to do that, you currently do not have those capabilities available via the SDK.
Comment: Yes, I'm referring to MapView. Is there any way to achieve that if it's not available at Google's API by default?
Answer: You should use accelerometer/gyroscope to achieve that.
please check out Sensor Manager and its examples!


Random variables and permutations

Question: I'm trying find the number of ordered triples of non-negative integers $a, b, c$ whose sum $a + b + c$ is a given positive integer $n$. I've related it to the concept of distinguishable balls in distinguishable boxes, but can't seem to see what's missing.
Comment: Which part of this question is not a duplicate of [this previous one](http://math.stackexchange.com/q/372331/)?
Answer: We can reframe the problem to see that this is precisely the problem of distributing $n$ apples to 3 people (apples indistinguishable, people distinguishable), ensuring that each person gets at least one apple. We can then reframe THIS problem by distributing one apple to each person, and then considering the number of distributions of $n-3$ apples to 3 people.
If this is sufficient, great! If not, keep reading.
To solve the problem of distributing $n-3$ apples to 3 people, note this is the same as the problem of placing 2 dividers between $n-3$ apples, where two adjacent dividers means that no apples were distributed to that person. This is the same as taking $n-3 + 2$ objects and choosing 2 to be dividers (The remaining $n-3$ will be apples). Hence, our answer is ${n-3 + 2 \choose 2}$.

Random variables and permutations


OSG: Camera flight with AnimationPathManipulator

Question: I'm trying to apply an osg::AnimationPath to the camera of my osgViewer::Viewer instance by using an osgGA::AnimationPathManipulator. My problem is that the AnimationPathManipulator only applies the change of rotation and no change of position to the camera. So it only rotates but doesn't translate.
I am using OpenSceneGraph Library 3.0.1.
For a better insight, this is my current code:
<code>void CameraFlyTest::animateCamera(osgViewer::Viewer* viewer) {

  osg::AnimationPath* path = new osg::AnimationPath();
  path->setLoopMode(osg::AnimationPath::SWING);

  osg::AnimationPath::ControlPoint cp1;
  cp1.setPosition(osg::Vec3d(-200,-450,60));
  cp1.setRotation(osg::Quat(M_PI_2, osg::Vec3(1,0,0)));

  osg::AnimationPath::ControlPoint cp2;
  cp2.setPosition(osg::Vec3d(2000,-500,60));
  cp2.setRotation(osg::Quat(M_PI_4, osg::Vec3(1,0,0)));

  path->insert(1.0f,cp1);
  path->insert(3.0f,cp2);

  osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(path);
  viewer->setCameraManipulator(apm);
}
</code>
Answer: The problem was that another active camera manipulator has also updated the position of the camera. The osgGA::AnimationPathManipulator itself works as it should.


Select2 apresentar valor do optgroup e option concatenado

Question: Estou criando um campo de seleção onde o usuário pode escolher entre vários estados, mas preciso que mostre quando selecionado tanto o valor do optgroup quanto do option, tem como?
Lembrando que estou usando a library select2
segue o html de base
<select name="estados[]" id="estados" multiple  style="width:300px">
    <optgroup label="Suldeste">
        <option value="SP">São Paulo</option>
        <option value="RJ">Rio de Janeiro</option>
        <option value="MG">Minas Gerais</option>
        <option value="ES">Espírito Santo</option>
    </optgroup>
    <optgroup label="Sul">
        <option value="PR">Paraná</option>
        <option value="SC">Santa Catarina</option>
        <option value="RS">Rio Grande do Sul</option>
    </optgroup>
    <optgroup label="Nordeste">
        <option value="AL">Alagoas</option>
        <option value="BA">Bahia</option>
        <option value="CE">Ceará</option>
        <option value="MA">Maranhão</option>
        <option value="PB">Paraíba</option>
        <option value="PE">Pernambuco</option>
        <option value="PI">Piauí</option>
        <option value="RN">Rio Grande do Norte</option>
        <option value="SE">Sergipe</option>
    </optgroup>
    <optgroup label="Centro-Oeste">
        <option value="DF">Distrito Federal</option>
        <option value="GO">Goiás</option>
        <option value="MT">Mato Grosso</option>
        <option value="MS">Mato Grosso do Sul</option>
    </optgroup>
    <optgroup label="Norte">
        <option value="AM">Amazonas</option>
        <option value="AC">Acre</option>
        <option value="RR">Roraima</option>
        <option value="RO">Rondônia</option>
        <option value="AP">Amapá</option>
        <option value="PA">Pará</option>
        <option value="TO">Tocantins</option>
    </optgroup>
</select>

e a chamado do js para o select2 funcionar
$("#estados").select2();

segue um exemplo no jsfiddle
perceba que quando se escolhe um estado ele mostra o nome do estado, mas precisaria que mostrasse tanto a região quanto o estado, por exemplo, Suldeste - São Paulo.
Answer: Aqui nessa resposta do So-Inglês trata seu problema,especificamente nesse jsfiddle que achei ser o melhor, porém só funciona com seleção simples.
Com ajuda do próprio Autor da Pergunta no jsFiddle e com essa pergunta no So-Inglês adaptamos o código para funcionar para multiple select;
Adicione:
function format(item) {

      var el = item.element;
    var og = $(el).closest('optgroup').attr('label');
    return og+'-'+item.text;
}

$("#estados").select2({
    formatSelection: format,
    escapeMarkup: function(m) { return m; }
});

Comment: @MarceloDiniz Tinha feito até pergunta no So-Inglês. Olha ai.
http://stackoverflow.com/questions/35361197/optgroup-value-multiple-select-with-selected2/35369650#35369650
Comment: Opa, dei uma olhada e com certeza já me da uma ajuda, mas tem alguma coisa estranha que acontece quando seleciono uma primeira opção, aparece como undefined o valor do label do optgroup, tem alguma ideia? da uma olhada nesse http://jsfiddle.net/pb8b7f2b/1/ atualizado
Comment: @MarceloDiniz tem que ser multipla seleção?
Comment: Nesse caso sim, pode ser que o usuário final escolher uma opção ou mais.
Comment: E se perceber, se escolher uma segunda opção ou até mais outras opções ele retorna sempre o primeiro label do optgroup
Comment: @MarceloDiniz entendi, esse código não funciona correta com multipla seleção.
Comment: da uma olhada nesse aqui http://jsfiddle.net/pb8b7f2b/3/ dai atualize sua resposta para eu marcar como válido, afinal foi com sua ajuda
Comment: @MarceloDiniz Ficou top. Se quiser editar pode ficar avontade. Tava tentando com um amigo no almoço, mais tava foda resolver. Bom que pude ajudar.


DNS through Cisco VPN

Question: We have a Cisco ASA providing a VPN gateway for users. Currently when users VPN'n from outside the network they can access file servers from their IP addresses but the shares do not response via share name.
I have checked the DNS settings on the ASA and it is distributing the correct internal DNS server addresses to the VPN client.
I am beginning to think it is something to do with the internal DNS servers not accepting queries from different subnets? Does anyone know this to be a problem? DNS servers are both WinServer2008R2.
Thanks
Answer: You should make sure that 53\udp and 53\tcp to your DNS servers are  allowed to the VPN clients by the ASA VPN policy. You should also make sure that the DHCP server for your VPN subnet(s) are giving these DNS servers to the clients.
Comment: Check by doing an `nslookup` of an internal FQDN from an affected client.  If you don't get a response, it's most likely a firewall issue.

DNS through Cisco VPN


adicionar select field dinamicamente (projeto laravel)

Question: Eu to criando um formulário de um repositório e tenho vários campos como esse de modality. O que eu não sei fazer é criar uma função para que quando uma pessoa clicar no botão + ao lado do select, ele crie na tela outro campo select de modality exatamente igual ao primeiro (no caso, o da imagem) e que eu possa fazer meu loop pra alimentá-lo com os dados do banco.
Eu sou uma porta pra mexer com front end (creio que seja isso)
Answer: Use a função .clone() do JQuery, crie um select com as opções padrões sem id e oculto para servir como base, então quando clicar no add ele copia este select e exibe na tela, já para popular com dados do banco é a mesma função só coloque ela dentro de um loop para receber os dados.
JS
jQuery('select[name="default"]').hide();
jQuery('#addSelect').on('click', function() {
    var novoSelect = jQuery('select[name="default"]').clone();
    novoSelect.attr('name', 'select1')
    novoSelect.show();
    jQuery('body').append(novoSelect);
});

Html
<select name="default">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
</select>
<button id="addSelect">add</button>


Entity access controler not called from custom route

Question: I define a custom entity named "Politician", where I set the class PoliticianAccessControl as an access handler. This is working fine for the canonical url of the entity set in the following way:
entity.politician.canonical:
  path: '/politician/{politician}'
  defaults:
    _controller: '\Drupal\pw_basic\Controller\EntityViewController\PoliticianViewController::view'
    _title_callback: '\Drupal\pw_basic\Controller\EntityViewController\PoliticianViewController::title'
  requirements:
    _entity_access: 'politician.view'

See the entity access requirement? Here the method PoliticianAccessControl->checkAccess() ist called, everything works just fine.
But when I try the same with another custom route the PoliticianAccessControl class gets not called and I always get an access denied message:
entity.politician.about_me:
  path: '/politician/{politician}/about-me'
  defaults:
    _controller: '\Drupal\pw_basic\Controller\PoliticianFrontend\AboutMe::build'
    _title_callback: '\Drupal\pw_basic\Controller\PoliticianFrontend\AboutMe::title'
  requirements:
    _entity_access: 'politician.view'

What do I forget?
Comment: When I have a look at the controller AboutMe::build() where I expect the parameter $politician to be an Politician entity I see that no loaded entity arrives here but just the id, which is part of the route. Why does this happen here? The {politician} parameter is written in the same way as the entity type id.
Answer: I guess you need to do a route parameter upcasting:
entity.politician.about_me:
  path: '/politician/{politician}/about-me'
  defaults:
    _controller: '\Drupal\pw_basic\Controller\PoliticianFrontend\AboutMe::build'
    _title_callback: '\Drupal\pw_basic\Controller\PoliticianFrontend\AboutMe::title'
  requirements:
    _entity_access: 'politician.view'
  options:
    parameters:
      politician:
        type: entity:politician

Answer: You need to give the router a nudge towards what $politician is supposed to be for the automatic up-casting to kick in. There are two ways to do that:

Type-hint the variable in the controller method:
function build(Politician $politician) {

See EntityResolverManager::setParametersFromReflection for details
Explicitly set the parameter type in the route config (which is pretty much what the first method does for you)
options:
  parameters:
    politician:
      type: 'entity:politician'


Bijection between power sets of sets implies bijection between sets?

Question: Is it true that if $X$ and $Y$ are sets and there is a bijection between $\mathcal{P}(X)$ and $\mathcal{P}(Y)$ then there is a bijection from $X$ to $Y$ ?. I believe this should be obvious, but I can't see why this is so. A proof or a counter example would be highly appreciated.
Thanks.
Comment: Nice question. It was in my mind some time ago but I did not post it for some reason
Comment: [When 2^a = 2^b implies a=b (a,b cardinals)](http://mathoverflow.net/questions/17152/when-2a-2b-implies-ab-a-b-cardinals) at Mathoverflow. Knowing about [Easton's theorem](http://en.wikipedia.org/wiki/Easton%27s_theorem) definitely helps.
Comment: And now I recalled also seeing this question here at MSE: [Does $2^X \cong 2^Y$ imply $X \cong Y$ without assuming the axiom of choice?](http://math.stackexchange.com/questions/74477/does-2x-cong-2y-imply-x-cong-y-without-assuming-the-axiom-of-choice). Maybe this could be considered a duplicate?
Comment: Yes you are right Martin. This could be concidered as a duplicate. I didn't find that thread when I searched to see if this question has been asked before, I guess I used the wrong keywords. For this I apologize.
Comment: See also [here](http://math.stackexchange.com/a/420484/462).
Answer: This cannot be proved from the axioms of $\sf ZFC$ (and so certainly not from naive set theory) but it cannot be refuted either.
That is to say, assuming that the axioms of set theory (read: $\sf ZFC$) are consistent there are models of set theory in which $2^X\sim 2^Y\implies X\sim Y$, and there are other models in which there are $X\nsim Y$ such that $2^X\sim 2^Y$.
For example if $\sf GCH$ holds then the statement is true, because the power set is "as small as possible", but it is consistent that there is an uncountable set of real numbers whose power set is equipotent with the real numbers themselves, i.e. $X$ such that $\Bbb N<X$ but $2^X\sim 2^\Bbb N$.
The statement is weaker than $\sf GCH$, and in a related (but unrelated) post on MathOverflow I called it "Injective Continuum Function", ICF. I have seen mentioning that this was called by Tarski "Weak Power Hypothesis", WPH.
Comment: @julien: I agree. One of the greatest difficulties is to understand how sets can have such different properties from one model to another. But let's put on the logical goggles and ask, can we prove from the axioms of fields that $\sqrt32$ exists? Can we prove it is unique? No, there are three fields, one in which there is no cube roots, one where there is just one, and another with three. But that doesn't surprise anyone, does it now? :-)
Comment: Argh, I meant $\sqrt[3]2$, not $\sqrt32$...
Comment: How puzzling for non set-theoricists...+1. At least for me.
Comment: I took it as a little extra challenge made on purpose...
Comment: @AsafKaragila I was trying to prove it for the OP's conjecture for the last 30 minutes until I saw your answer +1
Comment: Nice point. I'll keep that example in mind, thanks.


Is it always a bad practice to catch System.Exception?

Question: Please consider the following piece of code, which throws three different exceptions (namely, System.Configuration.ConfigurationErrorsException, System.FormatException and System.OverflowException):
int SomeInt = Convert.ToInt32(ConfigurationManager.AppSettings["SomeIntValue"]);

The exceptions are different, and so in practice I should have three different catch blocks  to handle each particular exception. However, in this particular case, all exceptions are handled the same way: a log is written to, say, EventViewer, and a message informing of a configuration error is displayed... In this particular cause, is it too bad to use
try
{
    int SomeInt = ConfigurationManager.AppSettings["SomeIntValue"];
}
catch (Exception ThisException)
{
    /* Log and display error message. */
}

or should I, instead, use the three catch blocks and repeat the code within each of them?
Comment: I wouldn't even catch any exception in this case. This would guarantee that the problem shows up immediately. Otherwise one is guessing around for the reason why this value is wrong and finds the problem only by scrolling through the log files.
Answer: See C# Exception Handling Fall Through for a discussion around this problem.
In short, if you catch the general Exception you should check if it is one of the expected types and if not rethrow it.
Update(and a bit out of scope)
Also there are a few times I think it's valid to do a catch all. This is very rare but sometimes in webservices or if you do something on the background thread in asp.net as and exception there will restart the whole application and people might lose their session if you have taken a dependency on that.
Answer: It is bad practice to catch System.Exception . . . or better yet, it is bad practice to handle System.Exception anywhere but the top level of your application. What you should to is:

Catch System.Exception
Test the exception for the types you plan to handle identically
Rethrow if it's not one of those.

Example code:
catch (Exception ex)
{
    if (ex is FormatException || ex is OverflowException || ex is ConfigurationErrorsException) {
        CommonHandler();
    }
    else {
        throw;
    }
}

Comment: Since C#6 it is ``catch (Exception ex) when (ex is FormatException || ex is ...)``. And don't use ``throw ex;``, always use ``throw;`` to keep the old exception 1:1.
Comment: And it passes Code Analysis rule 1031 "Do not catch general exception types", if only you throw the rest of exception types forward.
Answer: I don't think it's bad practice. If your desired functionality is "whenever this code throws an exception, then take these actions" then I think catching System.Exception is perfectly appropriate.
The fact that you're wrapping a very specific framework function instead of a large block of custom code helps in my opinion as well.
Comment: I disagree. That should not be your desired functionality. If something malicious is going on, then your code will just blissfully ignore it since it catches all exceptions as opposed to just the ones that it expects and knows how to handle. Saving yourself a minute of typing introduces security issues in your code and potentially masks bugs that you yourself have introduced.
Comment: @iheanyi: Do not use a catch-all at your upmost level but use System.AppDomain.UncatchedExceptionHandler.
Comment: I agree with @iheanyi. This is a bad practice. Exception handling is about *handling* exceptions. You should only catch the ones you know how to handle. Leave the others to bubble up. Keep in mind though, it's always a good idea to have a global exception handler that will catch all uncaught exceptions. This mechanism should at least log the error, but also have some intelligence to determine how to respond to the more serious exceptions. For example, what do you do if you get an IOException because your disk has run out of space? What if you were just swallowing that exception higher up?
Comment: I'm with @mikesigs on this. At the top level of your application, having a global catchall exception handler is appropriate. At this point, you still can't handle the exception and the appropriate response is either to log then "restart" your app or log then "terminate" your app.
Answer: What is really needed, but the .net exception hierarchy doesn't provide, is a clean way of distinguishing exceptions which mean "The requested operation didn't happen, but the system state is essentially fine except to the extent implied by the operation not having happened" from those which mean "The CPU is on fire, and even trying to save the current user's work would likely as not make things worse."  There are a lot of contexts in which one really should endeavor to catch all exceptions of the first type, while ideally not catching those of the second.  While there a few gradations beyond the two above, generally when catching exceptions one doesn't really care about the distinction between an InvalidArgumentException or an InvalidOperationException; what one cares about is whether the overall system state is valid or corrupted.
As it is, if one is making a call to e.g. a file-import plug-in and it throws an exception, I'm not really sure one can do except try to catch and rethrow really bad exceptions, while having all other exceptions put up a "This file could not be opened" dialog box.  Hopefully the state of the system at that point is essentially as it would be had the user not tried to open the file, but without some standardized way of indicating exception severity, I don't think there's any way to be sure.
Incidentally, if I had my druthers, there would be a class ExceptionBase, from which all exceptions would derive; most exceptions would derive from Exception (which would in turn derive from ExceptionBase) but things like ThreadAbortException, StackOverflowException, OutOfMemoryException, etc. would be derived from CriticalException.  That way one could catch most 'unexpected' exceptions without accidentally stifling the really bad ones.
Answer: It is not necessarily bad practice, the bad practice usually occurs when you do silly things in the catch block. Catching the base exception class is a good safety measure assuming you need to do something when the error occurs. The case for catching a specific exception class is best manifest when that specific class gives you information you can act on, catching SqlException for example can help you look at certain properties specific to that class and let you act on the problem.
Often times people will catch an exception and do something silly like create a new exception or even worse, swallow the exception details.
An often missed pattern is that you can catch, act an rethrow.
catch(Exception ex)
{
 //do something
 throw;
}

thus preserving the exception details.
Comment: I agree with you that in general that behaviour is deeply irksome. However, sometimes it is warranted. For example, when catching an exception at a "trust boundary" this is the right thing to do. An attacker outside the trust boundary could be attempting to determine secret implementation details of your system by feeding it bad data and examining the detailed error information that comes back. In that scenario, getting rid of all the detailed information and replacing it with "something failed, we'll log the results" is desirable.
Comment: Personally, I don't think it is silly to catch an exception and create a new one. What if, in the example I gave, I wanted to replace all the three exceptions thrown with a more generic `System.Configuration.ConfigurationErrorsException` with `ThisException` as an inner exception?
Comment: Clarification - I often see people catch an exception, create a new exception with the message 'error happened' and then not even provide the original exception as the inner to their new exception. Those are the boneheads of which I speak.
Comment: Oh... Ok then! Now I understand!
Comment: I would think it was bad practice in general to propagate details that come from a raw exception up into the user space. Well written, a program should log such information but hide it from anyone not trusted. If you are talking about something outside of web scope, something local machine and you are worried about details being sniffed I think the battle is already lost because without physical security there is no security IMHO.
Answer: In this particular case, it is entirely possible to use different catch blocks, as you do have different actions you can take depending on what exception you get.
For the first two you can set a reasonable default silently as to not annoy the user needlessly, then hope the problem fixes itself when you save your file, and for the latter exception you can ask the user if he wants to continue with the loading process (in which case you set a reasonable default), since the configuration file is obviously corrupted.
In general, the thinking is this: Do I need to take different actions in regards to different kinds of exceptions being thrown? More often than not, the answer is no, so a blank catch(Exception ex){ /* log... */ } (or even no catch at all if the exception is invariably fatal) is enough.
Edit: Blank as in blank check, not empty block :)


Validação Unique PUT and POST UNIQUE em REQUEST Laravel

Question: Estou com Um problema na hora de validar o campo unique.
Meu problema antes era q se fosse atualizar o valor ele não editava, porque acusava q o valor era unique, resolvi ele, porém agora ele não valida o campo unique, mas atualiza kkk
Esse é meu Request - Já tentei esses 3 métodos e eles só deixam atualizar o campo! Não valida se o valor é único antes de enviar pro banco!
public function rules()
{
    return[/*'nome'=>'bail|required|min:3|max:250|',Rule::unique('service')->ignore($this->service),*/

        'nome'=> 'bail|required|min:3|max:250|unique:service,nome,'.$this->id.',id',

        /*'nome' => 'bail|required|min:3|max:250',Rule::unique('service','nome')->ignore($this->service),*/
        'observacao'=> 'required'
    ];
}

Agora meu Controller
public function create()
{
    $action = route('admin.service.store');
    return view('admin.cadastro.service',compact('action'));
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\RedirectResponse
 */
public function store(ServiceRequest $request)
{
    Service::create($request->all());
    return  redirect()->route('admin.gerencial.index')->with('success_message', 'Cadastrado com Sucesso');
}

Já tentei de várias formas e não consigo fazer! Preciso de ajuda!
Answer: Consegui resolver meu problema! Como imaginei qdo estava rodando a validação em rules no campo UNIQUE ele só faz uma tarefa ou ignora ou atribui! Nesse caso ele estava só ignorando o ID quando estava atualizando e não validava o unique no create.
Rule::unique('service')->ignore($this->service)

Agora pra corrigir tive que fazer essa validação dentro de RULES no Request
$regras=[
        'campos do banco'          => 'bail|required|min:3|max:150',
        'endereco'      => 'required|min:3|max:200',
        'cities_id'     => 'required',
        'states_id'     => 'required'
    ];

    if ($this->method() === "POST"){
        $regras['coluna UNIQUE']= [
            'required',Rule::unique('client')
        ];
    }
    else{
        $regras['coluna UNIQUE']= [
        'required',Rule::unique('table')->ignore($this->route)
    ];
}
    return $regras;


Why are these two songs nearly identical for 20 whole seconds? Could there be a theoretical explanation?

Question: Disclaimer: this question is not about copyright. I am trying to understand why the voice melodies of the two songs are so similar. I thought the chord progression could be classical, and that there could be a theoretical explanation for the melody.
Some time ago I noticed that the second opening theme of the anime "Your lie in April" has a part of roughly 20 seconds that is nearly identical to another part of the famous japanese opening of Dragon ball GT ("Dan dan kokorohitareteku..."). The chords are essentially the same, and the voice notes are almost the same. Here are two links to Youtube videos that point to the correct minute (from those spots, the relevant part lasts roughly 20 seconds):
Your lie in April (2nd opening theme) 0:45 - 1:04
Dragon ball GT (opening theme) 0:25 - 0:47
The chord progression (transposed in D major (?)) is:

G A F#m Bm(7) Em F#m Bm D(7)

(with a variant that starts with Em instead of G in the second song; I am not sure about the 7's, hence the parentheses). This pattern is repeated two times in "Dragon ball GT" and almost two times in "Your lie in April". I guess there is no need of saying, but the second song is half tone above the first one.
I am reasonably sure the first just copied from the second (because of the melody, not just the chord progression), but I also thought that there could be a small chance that this is not the case. In particular, I have two questions to ask:

Is the chord progression something recurrent/classical, that maybe both songs took from somewhere else? (For this, someone pointed me to this famous progression, although this explains only the first 4 chords).
Given the chord progression, do you think the notes the voice can/should follow are in a sense "forced by", or a natural consequence of the underlying chords? Or instead do you think there is enough freedom in the voice melody to conclude that one took inspiration from the other beyond any reasonable doubt?

Explanation to the second question: the voice melody in the first song follows the chords quite strictly; I tried to sing the same lyrics with different notes that still match the notes of the underlying chords, but I did not find any natural alternative without unpleasant jumps between the notes. Also, basically the melody is simply descending for most of the time. This makes me think that maybe the melodies matching in the two songs could be not that strange after all.
I have a basic understanding of how notes and chords work, but I am not a musician, and for both questions I think it is needed some experience and knowledge. Also, I am new to this site and I hope the question suits the site (as you can see, mine is a theoretical interest, even though motivated by anime openings :) ).
Comment: Both offending melodies are abusing descending sequences. Is this enough of a hint?
Comment: https://en.wikipedia.org/wiki/Royal_road_progression
Comment: @Dekkadeci thank you X) that is true. What leaves me puzzled is also the transitions between the notes of the main line and, among the other similarities, that "walk up" (how who wrote the first answer said) to the tonic and back towards the end, 1:02 of the first link. The descending melody alone is definitely not what bothers me, it's the sum of all the pieces
Comment: @Valorum thank you. I know that, and I had already put the link in my question. What I still don't completely understand is the last four chords  of the progression. By "understand" I mean, how classical/recurrent this pattern with all these eight chords in that way. Of course it looks like quite a natural, reasonable way of resolving the progression to the tonic, I just cannot recall other songs with this specific 8 chord progression. But maybe this goes a little too off topic
Answer: For most people, musicians included, it's actually really difficult to intuit how "similar" two melodies are by ear; by "difficult", I mean that usually listeners will be surprised upon a second listen or a closer examination/analysis. Often times, certain things that to your brain sounded "similar" might have differing notes or rhythms. That's why generally if I want to compare how similar two songs are, I'll go to the trouble of actually transcribing the relevant parts of the music. If that's not possible, find some good sheet music for them.
The question as it stands is pretty subjective; I don't think there's much to do except speculate on whether or not one song was inspired by another. I'll answer in the more general case. I am not a lawyer, but I do usually like to point out certain things about what "similarity" means from a musical property standpoint:
First of all, from a legal perspective, chord progressions aren't part of the creative identity of a piece of music. The fact that two songs have the same chord progression isn't really evidence that one song is copying another, but it does set them in the same environment and can sometimes influence melodies to be written with more apparent similarities. According to how courts have historically interpreted the relevant laws, a song is only its lyrics and melody. (That doesn't mean they've been terribly consistent on that stance in recent times, but it's a good starting perspective.)
Second of all, when you isolate the patterns in music that you consider to be similar, it's also worth considering where that musical concept came from originally. If the portion of the melody you think is similar is actually a very common idiom in early blues or rock music, it's actually a lot more likely that the two songs drew influence from their common body of stylistically-related music. Mariah Carey has almost certainly sang some riffs that Christina Aguilera has sung identically. Are they copying each other? No, they're probably both emulating the vocal style that they prefer. You could call this unoriginal, but remember that no one person or record label owns or invented a genre... for good reason.
Third of all, even if you can't really draw a connection between the similarity and a historical musical idiom, consider how unique the pattern itself is. Prince's "Raspberry Beret" has a chorus melody that contains the same notes as Joe Dassin's "Les Champs-Élysées" - and oh là là, they even rhyme with each other and both use French words. Clear plagiarism? In reality, when you get right down to it, this melodic idea is a simple 3-2-1 scale degree walkdown in a major key with one of the most basic variations on it possible. Is it fair to say that either artist created that musical idea for the other to steal? Heck, Three Blind Mice was written in 1609 by Thomas Ravencroft, so is it fair to credit him as a songwriter? And Ravencroft surely is not the originator of the melodic idea 3-2-1, a musical concept as old as melody itself. The point I'm trying to make here is that one should avoid focusing too hard on very basic musical elements to find similarity. There are some things too old and too fundamental to be owned.

One more time, just to be clear: I have no legal expertise on intellectual property law and you should not trust the internet for such advice, but I understand musical history and theory enough to be able to interpret meanings in similarities most of the time. These are my opinions, not facts.
Comment: I did actually give a listen to both of those excerpts, and the first speculatory thing I'd point out is that the chord progressions being identical means absolutely nothing to me. Another comment mentions how ubiquitous the IV-V-ii-vi progression is in western-influenced contemporary Japanese music - I have a hard time thinking of a song in that style that *doesn't* feature an instance of this progression!
Comment: As for the melodies, yes, they have very similar notes. But if we look at the melodies analytically, we could notice they both emphasize the 3rd of the chord below them on the strong beats. Is that not a very common melodic pattern? I'd even go so far as to say this style of music *prefers* to emphasize the chordal 3rd, 5th, and 7th rather than the root - I have no data for that though, just seems correct from my experience. Also, they're def not *exactly* the same (the turnarounds halfway especially), which also hints weakly that they could have been conceived independently.
Comment: 2) in spite of all the defense I've provided for the two songs being independent, it's absolutely possible that one heard the other and used its ideas to guide their own. Both are from culturally relevant media, at least in my social circles, so yeah, definitely possible. Barring an interview clip or copyright lawsuit, I doubt we'll ever know for certain. @LorenzoPompili
Comment: "both emphasize the 3rd of the chord below them on the strong beats." That is admittedly something I did not notice :) "the chord progressions being identical means absolutely nothing to me" yep, that alone of course does not mean much. "The real question is how much variability is there in melodies that have the same chord progression" yes :) you essentially rephrased my question better than me. "that walk up to the high tonic on the second repetition […] Smells a little funny" indeed, that sounds a little too random XD. Thank you for these comments! You gave me some more elements
Comment: Forst of all, thank you for the extensive and very nice answer! I have played instruments, but not professionally, so it could be that I cannot judge how similar two songs are. I also understand that the question is subjective. Despite this, this case looks quite remarkable to me: six measures, five of which having the same melody in terms of notes (although maybe different rythm), of which a sequence repeating only three times…
Comment: …Moreover, of course it is difficult to prove or exclude plagiarism, and influences among musicians are often legit. But what I am interested in is looking for theoretical reasons (if any) why the two authors could have come up with chords + melody independently, considering that those are 20 seconds of music, and the melody does not look so simple to replicate two times just by pure chance, it is a little more complex than just a sequence that is repeated all the time. So, basically this turns into a theoretical question, although a little subjective.
Comment: I think the part that stood out to me as being the most similar is that walk up to the high tonic on the second repetition - that seemed pretty distinct to me. But then again, it makes sense that a songwriter might want to add a stronger climax to the melody the second time around... and look how we land on that chordal 3rd again? Smells a little funny but I think it's also possible for two songwriters to have made a similar writing choice here.
Comment: Some counterarguments, though: 1) you could easily make the same claims I'm making for any two songs if you squint your eyes hard enough. "See how they both used notes from within the parent key? That's such a fundamental concept, no one can own that idea - obviously there's nothing new under the sun". The real question is how much variability is there in melodies that have the same chord progression? Interesting experiment: have a bunch of songwriters get the same chord progression and then compare how similar their melodies are to each other!
Comment: @user45266 - "Interesting experiment: have a bunch of songwriters get the same chord progression and then compare how similar their melodies are to each other!" - Honestly, all those 12-bar blues and rhythm changes pieces I've heard have sounded pretty **dissimilar** to me melody-wise.
Answer: As a composer, I have sometimes felt that some parts of the music I compose sounds similar in flavour to something I have heard before, but often I am unable to even figure out what that was. The point is that it is undeniable that previously encountered music indeed influences a composer's musical output, but it's often also unconscious, so it's not so easy to tell whether it was intentionally plagiarized or not.
Others have already pointed out that this kind of melodic contour is quite common, and there are a limited number of chord progressions that go well with it, so... It's not unusual for multiple people to come up with similar chord progressions..
I think one point that should be emphasized is that typically the melody comes first, and the chords follow naturally, so I don't agree with the implicit assumption in your question (2) that the issue is about what melodies fit the chord progression, since it should be the other way around!
Comment: That is a very nice remark. It was not immediate for me to think in that way; from my very limited experience as a singer in a band, I ofted simply had a chord progression and tried to find a nice vocal line that matches the music. Thank you!
Comment: @LorenzoPompili: You're welcome! You can upvote if my answer is helpful. =)
Comment: In quite a lot of music, the harmony comes first (e.g. solos). Part of me speculates that for both offending pieces, it's actually the *lyrics* that came first, though.
Comment: @Dekkadeci: I know that. But I think you know my point; for *songs with lyrics* the lyrics comes first, and the melody has to respect the accents and intonation of the lyrics, so the melody comes before the chords.


OnClick Event not Captured

Question: I am currently developing a module in Drupal. I made a button that show a dialog box whenever it's clicked.
<code>function myid_init() {
  drupal_add_js(drupal_get_path("module", "myid") . "/js/jquery-1.11.2.min.js");

  drupal_add_js(drupal_get_path("module", "myid") . "/js/myid.js");
}

function myid_menu() {
  $items = array();

  $items['admin/settings/myid'] = array(
    'title' => 'myid Settings',
    'description' => 'Configuration options for the myid module',
    'page callback' => 'myid_admin_settings',
    'access callback ' => 'user_access',
    'access arguments' => array('administer site configuration'),
  );

  return $items;
}

function myid_admin_settings() {
   return drupal_get_form('myid_settings_form');
}

function myid_settings_form() {
  $form = array();

  $form['myid_registrar_button'] = array(
    '#type' => 'button',
    '#value' => '...',
    '#attributes' => array(
      'id' => 'myid_registrar_button',
    ),
  );

  return $form;
}
</code>
The JavaScript code is the following
<code>$(function(){
  $('#myid_registrar_button').on('click', function(e) {
    e.preventDefault();
    alert("Eww");
  });
});
</code>
Whenever I click a button, it refreshes and it doesn't show anything.
It seems the event is not captured. The console doesn't show errors.
What am I missing?
Comment: Go through following https://www.drupal.org/node/756722
Comment: Try after adding your js code inside `document.ready`.
Answer: You shouldn't be adding JQuery like that.  It's automatically included in core, so you don't need to include it yourself.  To stay up with the latest JQuery version, install the jQuery Update module.
For your JS file, this should work:
<code>(function ($) {
    Drupal.behaviors.myid.registrar_button = {
        attach: function (context, settings) {
            $('#myid_registrar_button').on('click', function(e) {
                e.preventDefault();
                alert("Eww");
            });
        }
    };
})(jQuery);
</code>
Comment: You don't want to do that.  Drupal.behaviors holds all the code to run on page load.  You can change it to Drupal.behaviors.myid_registrar_button, but make sure it's under Drupal.behaviors.

OnClick Event not Captured


Changing Drush path

Question: I previously had Drush working on my VPS, but for some reason since a server update Drush can no longer be located.
If I do 'which drush' the output is '/root/.composer/vendor/bin/drush'
which matches what is in my .bash_profile:
PATH="$HOME/.composer/vendor/bin:$PATH"

My drush installation is actually at /opt/drush-8.x/vendor/drush/drush
This may seem like an obvious answer, but when I tried editing .bash_profile to what made sense to me, something got broken (couldn't use any commands) and my hosts had to restore my old .bash_profile for me. I may just have made a typo then, but wanted someone to confirm exactly what my .bash_profile should say before I try again!
Answer: This is really a Bash / shell question - how to modify the path or set an alias. Anyway, replace
PATH="$HOME/.composer/vendor/bin:$PATH"

with
PATH="/opt/drush-8.x/vendor/drush/drush:$HOME/.composer/vendor/bin:$PATH"

assuming you may have other stuff in $HOME/.composer/vendor/bin that you stil want to use.
If you want to be 110% sure that you don't break something, try it in Bash before modifying .bash_profile - just copy and paste the line inside Bash.
Comment: Thank you - that's worked for the path, I'm now getting other errors - but's a separate question!

Changing Drush path


How to reuse subresource data for referenced inputs in React-admin?

Question: In react-admin documentation the use of ReferenceArrayInput is for this kind of data structure:
{
  id: 1,
  groups: [1, 2, 3]
}

And then:
<ReferenceArrayInput source="groups" reference="groups" allowEmpty>
    <SelectArrayInput optionText="name"/>
</ReferenceArrayInput>

Using a custom json data provider, it will be make this request:
https://example.com/api/groups/?ids=[1,2,3]
or if the API doesn't support WHERE IN, it will be do individual calls for each id:
https://example.com/api/groups/1
https://example.com/api/groups/2
https://example.com/api/groups/3

But if I have the following data structure:
{
  id: 1,
  name: "Pepito Perez",
  groups: [
    { id: 1, name: "HR"},
    { id: 2, name: "IT"},
    { id: 3, name: "FINANCE"}
  ]
}

I have the name field already, so I don't want make additional requests.
When I go to the edit view react-admin performs almost 70 requests unnecessary.
How can I avoid that? there's a way to reuse the data?
Also is tricky use ReferenceArrayInput component with an array of objects, I have to add a nonsense format prop to make it works: format={v => (v ? v.map(i => (i.id ? i.id : i)) : [])}
Guess it's related to the first problem.
Thanks in advance!
Answer: If the choices is not meant to be fetched, ReferenceInput is not what you want. You need only a SelectInput with programmatic setted choices. You can achieve that with FormDataConsumer:
        <FormDataConsumer>
            {({ formData, ...rest }) =>
                 <SelectArrayInput
                     source="selectedGroups"
                     optionText="name"
                     choices={formData.groups}
                     {...rest}
                 />
            }
        </FormDataConsumer>

Note a different source, probably setting as groups, equal to choices "source", after first selected group, would result in a re-render, letting choices values equal to the single selected group.
That's almost exactly the use case of FormDataConsumer in documentation:
https://marmelab.com/react-admin/Inputs.html#linking-two-inputs


Error printing the length of the longest word?

Question: I am writing a function that is supposed to print out the 3 largest words of a text file. Once those 3 words are printed out, I am supposed to create a function that will say how many characters are in those words. The three largest words are 13 characters, but for some reason my program is saying that they are 11 characters.
Here is my program:
def main():
    real_longest = ['']
    filename = input("What is the filename?")
    with open(filename) as f:
        linenum = 1
        for line in f:
            words = line.split()
            longest = ''
            for word in words:
                if len(longest) < len(word):
                    longest = word
            print("Line", linenum, "has", longest, "as the longest word.")
            if len(longest) > len(real_longest[0]):
                real_longest = [longest]
            elif len(longest) == len(real_longest[0]):
                real_longest.append(longest)
            linenum += 1
            print(longest)
    with open(filename) as f:
        for word in real_longest:
            print("This word is one of the largest:", word)
            print(len(longest))

main()

Here is what it returns:
What is the filename?test.txt
Line 1 has Working as the longest word.
Working
Line 2 has possibilities as the longest word.
possibilities
Line 3 has scrambled as the longest word.
scrambled
Line 4 has letters. as the longest word.
letters.
Line 5 has  as the longest word.

Line 6 has difficulties as the longest word.
difficulties
Line 7 has permutations. as the longest word.
permutations.
Line 8 has signature as the longest word.
signature
Line 9 has permutations. as the longest word.
permutations.
Line 10 has unscrambled as the longest word.
unscrambled
This word is one of the largest: possibilities
11
This word is one of the largest: permutations.
11
This word is one of the largest: permutations.
11

Answer: That is because you are not printing the length of the word, instead you are printing the length of longest variable, which points to the longest word in the last line (not the real longest word from the file) , In the particular example - 'unscrambled' , and hence the 11 length.
You should print the length of the word. Example -
with open(filename) as f:
    for word in real_longest:
        print("This word is one of the largest:", word)
        print(len(word))       # <---------- changed here from `len(longest)` .

Comment: Such a simple mistake! Thank you for clarifying, this works!


For which values of $a, b$ does the system of equations not have any solutions?

Question: I am trying to solve the following problem:

For which values of $a$ and $b$ does the linear system represented by the augmented matrix not have any solution?
$$ \left[\begin{array}{ccc|c}
      1&-2&3&-4\\
      2&1&1&2\\
      1&a&2&-b
     \end{array} \right] $$

Truthfully, I don't know where to start. Thus, any help is welcomed. Thank you very much!
EDIT: I tried to solve the problem on my own using Gaussian elimination, but I am not sure that the solution is the right one, or is that the right way to go.
EDIT2: OK, here is how I tried to solve it using Gaussian elimination:
multiplication of the third row with -1, and adding with the first row, the I got
$$ \left[
    \begin{array}{ccc|c}
      1&-2&3&-4\\
      2&1&1&2\\
      0&2a&-2&2b
    \end{array}
\right] $$
Dividing the third row with 2:
$$ \left[
    \begin{array}{ccc|c}
      1&-2&3&-4\\
      2&1&1&2\\
      0&a&-1&b
    \end{array}
\right] $$
Now my problem is, that I have two variables in one equation. I have no idea how to go next.
Comment: You should add your work to the problem statement so we can help you figure out if it right or, if not, where you went wrong.
Comment: Yes it's a right way or if you know the Cramer's formula then it's the second right way.
Answer: After a bit of Gaussian elimination, we arrive at
$$\begin{bmatrix}1 & 0 & 1 & 0 \\
0 & 1 & -1 & 2\\
0 & 0 & a+1 & -b - 2a\\
\end{bmatrix}$$
Now, when $a = - 1$ and $-b-2a \neq 0 \iff b\neq 2$, there will be no solution to the system of equations. Why not?
Comment: A system will be  inconsistent (no solution) if a row is all zero *except* for the rightmost entry, which is nonzero. It represents the "equation" $0x + 0y+0z = c$ where $c\neq 0$. (Hence no solution). If the entire row is zero, then the system has infinitely many solutions.
Comment: why is b not equal 6. One more question: Can I multiply two rowes? Thank you very much!!!
Answer: By row reduction the system becomes (if I didnt make a mistake (highly likely))
$$\begin{pmatrix}
1&0&1&0\\
0&1&-1&2\\
0&0&a+1&-b-2a\\
\end{pmatrix}$$
In order for the rank to be less than $3$ we need that $a+1=0$, so $a=-1$ for no solution we then need $-b-2a \neq 0$ so $b\neq 2$
Comment: the last row must be $0 \ 0\  0 \ x$ where $x$ is non zero since $x=-b-2a$ and $a=-1$ we get $b\neq 2$
Comment: Thanks for the help. Can you please explain to me why is the b not equal to 2. How did you get this. Thanks


Can intersection of two different maximal ideals of Euclidean ring contain prime element?

Question: Can intersection of two different maximal ideals of Euclidean ring contain prime element?
We define $I$ maximal ideal of ring $R$, if there is no such ideal $I' \neq R$, that $I \subset I' \subset R$.
Comment: Please clarify if  your definition of Euclidean *ring* requires that the ring is a *domain*.
Comment: We define ring $R$ Euclidean, if it corresponds to the following properties.
Comment: You didn't list any "following properties". The property I asked about is "integral domain", i.e is a Euclidean ring an integral domain *by your definition*?
Comment: We define ring $R$ Euclidean, if it corresponds to the following properties. 1) For all $a, b\in R$ if $ab=0$ then $a=0$ or $b=0$. 2) For each non-zero element we define numeral characteristic — norm $N: R\backslash{0}\rightarrow\mathbb{Z}, N(r)\geq 0$. 3) For all $a, b\in R\exists q, r: a=qb+r$ and either $r=0$, or $N(r)<N(b)$. 4) For all $a, b\in R, a\neq 0, b\neq 0$ it is true that $N(ab)\geq max(N(a), N(b))$.
Answer: Let $p$ be a prime element in the ring.
Then $(p)$ is maximal as if $(p)\subset (m)$, then $m\mid p$ which implies that either $m$ is a unit (in which case $(m) = (1)$) or $(m) = (p)$, either case, we see that $(p)$ is the largest pricipal proper-ideal in the ring.
Now, Euclidean rings are PIDs, so, $(p)$ is maximal.


How to send message in rabbitmq on docker?

Question: Again, it supposed to be simple, but wasn't able to find any documentation about it
In my previous question I had a problems with running rabbitmq container in docker. It has been solved, but now another one appeared
Container was created with this line
docker run -d --hostname my-rabbit --name some-rabbit -p 15672:15672 rabbitmq:3-management

I was trying to create a simple console application to check how message sending is working (from base tutorial):
var factory = new ConnectionFactory()
{
  HostName = "localhost",
  Port = 15672
};

using (var connection = factory.CreateConnection())
{
  using (var channel = connection.CreateModel())
  {
    channel.QueueDeclare("Test", false, false, false, null);

    var mess = new RepMessage()
    {
       ConnectionString = "TestingString",
       QueueID = 5
    };

    var jsonified = JsonConvert.SerializeObject(mess);
    var messBody = Encoding.UTF8.GetBytes(jsonified);
    channel.BasicPublish("", "Test", null, messBody);

    Console.WriteLine(string.Format("Message with ConStr={0}, QueueID={1} has been send", mess.ConnectionString, mess.QueueID));
  }
}

And result is, its not working.
I am receiving exception None of the specified endpoints were reachable and inner exception as connection.start was never received, likely due to a network timeout
If I remove port, then my inner exception transforms in No connection could be made because the target machine actively refused it 127.0.0.1:5672
What am I missing, is is this example not supposed to work with docker?
Comment: Oh... tried... it worked out... jezz. Could you please at this as an answer?
Answer: Port 15672 is a port of rabbitmq management plugin web interface. When you are sending message to rabbit - you need to connect to different port (by default - 5672). So change your code to connect to that port and map it in docker via -p 5672:5672.
Answer: In your particular case docker command would look like this

docker run -d --hostname my-rabbit --name some-rabbit -p 15672:15672 -p 5672:5672 rabbitmq:3-management


Angular2 dynamic style

Question: What about dynamic styling.
Imagine you're deploying a unique plaftorm for multiple clients. (SAAS platform)
You deploy ONE webapp folder but these webapp must apply a different theme (color) for each client (exemple configuration : loading colors by domain name).
In angular 2, there is scss but the scss is a compiled language -> so you need to compile each time for each client to compile N webapps. It takes time and it's difficult to maintain.
So the only solution i see:
 - compile scss at runtime (via remote server call, fe:jsass, or js) when loading app and inject the generated css file in head section.
but i think it's an anti-pattern with the (s)css file for angular2 components.
Moreover the generated file will contains components style that will apply on entire page instead even if component is not initialized.
Have you got any framework or other solution ?
Comment: SCSS is only compiled once (When you build your app) into CSS file. Same goes for the Typescript files, compiled and minified into one JS file.
Comment: You should create a custom [RootRenderer](https://angular.io/docs/ts/latest/api/core/index/RootRenderer-class.html), that will handle compiling sass or use custom css files. To do that, you will need to create a new platform, that's a big task I never did. See how it works [in browser platform](https://github.com/angular/angular/blob/2.4.x/modules/%40angular/platform-browser/src/dom/dom_renderer.ts#L126). And there is  a [speach about custom renderers](https://www.youtube.com/watch?v=iE-wYf4AaiM) at ng-europe
Comment: great i will have a look at it.
Answer: You can achieve this creating a Service that return the colors of some structures that you want to change and inject it into the Components
Example inside the component html:

And do some logic to get the pattern for each user when App starts and insert into the ThemeService.
Full Example:
import { Component } from '@angular/core'

@Component ({
  selector: 'my-component',
  templateUrl: './my-component.component.html',
})
export class MyComponent {

    constructor( private themeService: ThemeService){}
}

@Injectable()
export class ThemeService {
    backgroundColor: string

    getNavbarBackgroundColor: string() {
        return this.backgroundColor;
    }

    someLogicToGetTheme() {
        //do stuff
    }

    ngOnInit() {
        this.someLogicToGetTheme()
    }
}

Comment: Yes but it's pity to have to specify colors in non styles files.
In the  Google Web Toolkit (GWT) world you can evaluate value in GSS file. Im' surprised that there is no equivalent.
Comment: Indeed it's pity, but I don't know another way to dinamically change the CSS in production on Angular
Comment: I am trying to achieve the same thing, this project has dynamic themes https://github.com/akveo/nebular/ but the sass code is rather complicated @cassiano

Angular2 dynamic style


Having trouble with Chinese Remainder Theorem

Question: I am having trouble with the Chinese Remainder Theorem.
For this question..the equation $5x\equiv 3 \pmod6$ I found there is exactly one incongruent solution modulo $6$. But then I found 3 solutions modulo $6$?
Similarly, in this system
$$\begin{cases}
x\equiv3 \pmod4\\
x\equiv5 \pmod3
\end{cases}$$
I am having trouble determining how many solutions there are? I think there is only one solution modulo $12$, but I am not so sure right now.
Comment: Of course it makes sense for $x$ to be congruent to $5$ (mod $3$). Equivalence modulo something is defined for any two integers on the left/right. There is no magic role played by the integers $0,1,2$ (mod $3$), other than convenience.
Comment: What were your three solutions? $5$ is invertible $\pmod 6$ with inverse $5$, so $x \equiv 3 \pmod 6$.
Comment: Yea I realized I make a mistake and theres only one solution. But what about the system of congruences?
Comment: Thats what was given. So would there be no solution?
Comment: The system has exactly one solution modulo 12, and that is precisely an illustration of the Chinese Remainder Theorem. What is it that you are not so sure about?
Comment: What is an "incongruent solution"?
Answer: In both cases there is exactly 1 solution.
Easiest way to solve the second system is:
$$
\begin{cases}
x \equiv 3 \pmod 4 \\
x \equiv 5 \pmod 3
\end{cases} \Rightarrow
\begin{cases}
x = 3 + 4k \\
3 + 4k \equiv 5 \pmod 3
\end{cases}\Rightarrow
\begin{cases}
x = 3 + 4k \\
k \equiv 2 \pmod 3
\end{cases}$$
$$ \Rightarrow\begin{cases}
x = 3 + 4k \\
k = 2 +3l
\end{cases} \Rightarrow
x = 3 + 4(2+3l) = 11 + 12l$$
So:
$$x \equiv -1 \pmod{12}$$
Answer: \begin{align}
   x \equiv 3 \pmod 4\\
   x \equiv 5 \pmod 3
\end{align}
For really small number such as this, you don't need a lot of high-powered math to get a feel for what the solution should look like
$x \equiv 3 \pmod 4
   \implies x \in
   \{\dots, 3, 7, \color{red}{11},
            15, 19, \color{red}{23},
            27, 31, \color{red}{35}, 39, \dots\}$
$x \equiv 5 \pmod 3
   \implies x \in
   \{\dots, 2, 8, \color{red}{11},
            14, 17, 20, \color{red}{23},
            26, 29, 32, \color{red}{35}, 38  \dots\}$
You can see that $x \in \{\dots, 11, 23, 35, \dots\}$
Which doesn't prove but strongly suggests that $x \equiv 11 \pmod{12}$


Change color of active navbar dropdown item in Bootstrap

Question: I am using Bootstrap 5.3 to create a navbar that uses green colors. However, active dropdown item in the dropdown menu is showing in Bootstrap's default blue - see screenshot. How do I change the blue color to green?
Menu screenshot

My custom CSS is as follows:
<code>.navbar-nav .nav-item.active .nav-link, .navbar-nav .nav-item:hover .nav-link, .nav-item.dropdown .dropdown-item:active {
    background-color: green;
    color: white;
}
</code>
Comment: Can you add the html code too?
Answer:
<code>.dropdown-item.active, .dropdown-item:active {
  background-color: green;
  color: white;
}
</code>


Do difference in octaves matter for the intervals?

Question: Should I account difference in octaves between different guitar strings, like between 5th (octave A2) string and 4th string (octave D3), when I'm looking for intervals (for example perfect 4th) ? I mean, technically from theory standpoint, because I understand that they sound a bit differently.
Also, for example If I play P4 of G which is G-C notes, and if I play notes in reverse order and C and G are in different octaves is that considered a different interval? I think not, but what confuses me is that being in different octaves the actual half-step distance between notes change (if G is in the next octave then the distance is 7 half-steps, or P5), while the definition of P4 says that half-step distance should be 5 half-steps.
So, the rule is that if notes of some interval are in the same octave then the order they are played doesn't matter, but if notes are in different octaves then the order may matter?
Comment: An eight and fiftheenth will never be the same interval. A third and a tenth too
Answer: Intervals make sense when counted from lower to upper note. Not the only way, but that works.
Thus, if the lower note is G, and upper the very next C going up, we have a P4. Using that same C, and going up to the very next G (an octave above the original), the interval is now a P5.
Be very careful with intervals, though - the number of semitones is literally half the story, the other half being what the notes are being called. For example G>B♯ (which will sound the same, and be the same number of semitones apart), is not P4, it's actually A3.
Comment: Thank you. As I understand now, it matters that notes are not in the same octave for the interval naming + the order matters as well. Does the meaning of the term "interval" change, when it's in the context of a chord structure ? In power chord D on 5th string (5th fret) it's said that A on 4th string is a P5 of our D. So, if I check using the same logic as you mention D3 + 7 half-steps = A3, but the actuall A on 4th string (7th fret) in this chord is A4 not A3, so the actual distance is +12 half-steps to our 7 made, which is in total 19 half-steps, how is this considered P5 ?
Comment: An octave is the 'space between two notes'. 12 semitones between two notes of the same name is an octave. 19 semitones won't produce a 'power chord' (aka 5). The interval you describe is P5 - the usual 'power chord'.
Comment: Thank you again, I've made a mistake when said "but the actuall A on 4th string (7th fret) in this chord is A4 not A3", it's A3 not A4, and the distance between D3 and A3 is exactly 7 semitones or P5.
Answer: Two important ideas:

Intervals are defined from the lower pitch to the higher pitch.
The numerical octave designation by itself does not affect the interval type.

Given the example of A2 to D3:

A2, being the lower pitch, is our starting point for naming the interval.
Counting up from A2, there are five semitones between it and D3 (A#2 B2 C3 C#3 D3).
Thus, the interval is a P4.
Even if we count from D3 down to A2, of course, it's still five semitones — P4.
However, if we invert the interval, DX to AX, the number of semitones from lower pitch to higher pitch is now 7, a P5.

Where the octave matters is in compound intervals, intervals in which the pitches are more than a diatonic octave apart. A2 to D4 and C3 to D4 are both compound intervals. A2 to D4 is a compound P4 or an P11; C3 to D4 is a compound M2 or a M9.
The guitar string(s) on which the notes are played doesn't matter in itself in determining the interval, only the actual pitches involved.


Laravel Broadcasting with Soketi listening to channel via Echo is not working

Question: I'm using Laravel Broadcasting with Soketi and I'm trying to listen to the jobs channel and JobFailedEvent. So here is my code.

class JobFailedEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     */
    public $jobName;
    public $errorMessage;
    public function __construct($jobName, $errorMessage)
    {
        $this->jobName = $jobName;
        $this->errorMessage = $errorMessage;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return array<int, \Illuminate\Broadcasting\Channel>
     */
    public function broadcastOn(): array
    {
        return [
            new Channel('jobs'),
        ];
    }
}

This is my bootstrap.js

import Echo from 'laravel-echo';

import Pusher from 'pusher-js';
window.Pusher = Pusher;

window.Echo = new Echo({
    broadcaster: "pusher",
    key: import.meta.env.VITE_PUSHER_APP_KEY,
    cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER ?? 'mt1',
    wsHost:
        import.meta.env.VITE_PUSHER_HOST ??
        `ws-${import.meta.env.VITE_PUSHER_APP_CLUSTER}.pusher.com`,
    wsPort: import.meta.env.VITE_PUSHER_PORT ?? 80,
    wssPort: import.meta.env.VITE_PUSHER_PORT ?? 443,
    forceTLS: (import.meta.env.VITE_PUSHER_SCHEME ?? "https") === "https",
    enabledTransports: ["ws", "wss"],
});

and lastly the Vue component where I'm trying to listen to

const echo = ref();

echo.value = new Echo({
    broadcaster: "pusher",
    key: import.meta.env.VITE_PUSHER_APP_KEY,
    cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER ?? 'mt1',
    wsHost:
        import.meta.env.VITE_PUSHER_HOST ??
        `ws-${import.meta.env.VITE_PUSHER_APP_CLUSTER}.pusher.com`,
    wsPort: import.meta.env.VITE_PUSHER_PORT ?? 80,
    wssPort: import.meta.env.VITE_PUSHER_PORT ?? 443,
    forceTLS: (import.meta.env.VITE_PUSHER_SCHEME ?? "https") === "https",
    enabledTransports: ["ws", "wss"],
});

echo.value.channel('jobs').listen('JobFailedEvent', (e) => {
    console.log('Job failed:', e);

});

Apparently even after the event is done, the listen in Vue component is never called even if I received the payload
Answer: Listen for event 'App\Events\JobFailedEvent':
echo.value.channel('jobs').listen('App\\Events\\JobFailedEvent', (e) => { console.log('Job failed:', e); });


2 way bindings Set firing multiple times when set from another property setter (MAUI)

Question: 2 Way Binding Issue:
I'm (until recently) a driver developer poking my nose into the world of app development; I will readily admit that my understanding of the proper patterns is extremely limited. My problem today relates to two way bindings. Specifically I have bindings that work perfectly (one-way) with labels but when I change them to Editors I see some wildly incomprehensible behavior. In short my app may scan a barcode, use a regex to break it out into 8 different fields and sets those fields. This part works. However once one of those is a 2 way binding (i.e. with an editor or entry) instead of a label the OnPropertyChanged event for that property fires 4 or 5 extra times with values being passed into the Set function that are clearly part of the whole scan but pieced together in an incomprehensible way.  For instance I may assign BoxNo = 14, then the UI does a get on that property but then we start setting it over and over until I see a value like "2031523969.0 LB 14" which are all piece of the full scan but not necessarily sequential.
The first way I tried to do this is to replace "<Label ..." in my xaml with "<Editor". This is when I first saw the error. I then backed off until I had only one property as an editor, and the rest as labels.
The second thing I tried was to manually specify "Two Way" in the binding ala
<Editor x:Name="LotNo"
                       Text="{Binding LotNo, Mode=TwoWay}"
                       BackgroundColor="Chartreuse"
                       Grid.Row="3"
                       Grid.Column="0"/>

The third thing I tried was using "Entry" instead of "Editor" but the problem was identical. I did this both explicitly setting the mode and implicitly setting the mode.
The fourth thing I did was try different properties (i.e. Lot Number instead of Box Number ) with the Entry, while leaving the others as labels, it makes no difference which property is used, all are susceptible to this.
After this I figured it's not a UI problem and started looking in my Barcode object. When ScannedText gets set it had been setting all the other public properties which each raise an OnPropertyChanged event. I tried setting all the private properties in the ScannedText.Set and then calling all the OnPropertyChanged events at the end but that made no difference.
Finally I added checks to my set function to skip raising the OnProperty changed if the property value isn't actually changing
Architecture: I have a MauiProgram.cs which passes scanned data from the datawedge to my helpermodel.ScannedText property. I set a break point at the OnReceive event and I only ever receive data from the scanner once per scan.
Here is the code from my Barcode related to the scanned text
public sealed class Barcode : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public event Action OnChange;

        private static Barcode _instance;
        public static Barcode GetInstance()
        {
            if (_instance == null)
            {
                _instance = new Barcode();
            }
            return _instance;
        }

        private string scannedText = "Scan a Bag";
        private string partNo = "";
        private string lotNo = "";
        private string boxNo = "";
        private string netWeight = "";// 0.0m; //includes unit i.e. "lb"
        private string tareWeight = ""; //0.0m;//includes unit i.e. "lb"
        private string grossWeight = ""; //0.0m;//includes unit i.e. "lb"
        private string mfgDateTime = "";
        private DateTime scanTime ;

        public void OnPropertyChanged(string name = "") =>
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

        public string PartNo
        {
            get => partNo;
            set {
                if (partNo != value)
                {
                    partNo = value;
                    OnPropertyChanged(nameof(PartNo));
                }
            }
        }
        public string LotNo
        {
            get => lotNo;
            set
            {
                if (lotNo != value)
                {
                    lotNo = value;
                    OnPropertyChanged(nameof(LotNo));
                }
            }
        }
 // ...
 // 6 More properties that look functionally identical to PartNo
 // ...
public string ScannedText
        {
            //8608970AMUVGN3254  213908  1500  1
            //EVERYONE ELSE -- PN - LOT NUM - NET WEIGHT - BAG NUM
            get => scannedText;
            set
            {
                string pattern = @"(\w+\s+\w+)\s+(\d+)\s+([\d,\.]+\s+\w+)\s+([\d,\.]+\s+\w+)\s+([\d,\.]+\s+\w+)\s+([\d,\/]+\s[\d,\:]+\s\w+)\s+(\d+)\s+";
                Match match = Regex.Match(value, pattern);
                scannedText = value.TrimEnd();

                //if this is a proper label, then set all other fields.
                if (match.Success)
                {
                    //fill all the other fields. '
                    PartNo = match.Groups[1].Value;
                    LotNo = match.Groups[2].Value;
                    NetWeight = match.Groups[3].Value;
                    TareWeight = match.Groups[4].Value;
                    GrossWeight = match.Groups[5].Value;
                    MfgDateTime = match.Groups[6].Value;
                    BoxNo = match.Groups[7].Value;
                    ScanTime = DateTime.Now;
                }
                else
                {
                    PartNo = String.Empty;
                    LotNo = String.Empty;
                    NetWeight = String.Empty;
                    TareWeight = String.Empty;
                    GrossWeight = String.Empty;
                    MfgDateTime = String.Empty;
                    BoxNo = String.Empty;
                    ScanTime = DateTime.Now;
                }

                OnPropertyChanged(nameof(ScannedText));
            }
        }

        public void NotifyStateChanged() => OnChange?.Invoke();

        public Barcode()
        {

        }
}

Here is a snippet from Barcode.cs
My MainPage.xaml.cs is dirt simple
    Barcode barcode = Barcode.GetInstance();
    public MainPage()
    {
        InitializeComponent();

        this.BindingContext = barcode;
    }

Here is most of the XAML with a few repeating elements left out
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="ZebraDatawegeSampleMaui.MainPage"
             xmlns:model="clr-namespace:scannerwerWithIntent.model">

    <ScrollView>
        <VerticalStackLayout
            Spacing="5"
            Padding="30,0"
            VerticalOptions="Center">

            <Grid VerticalOptions="Fill"
                  HorizontalOptions="Fill"
                  >
                <Grid.RowDefinitions>
                    <RowDefinition Height="1*" />
                    <RowDefinition Height="1*" />
                    <RowDefinition Height="1*" />
                    <RowDefinition Height="1*" />
                    <RowDefinition Height="1*" />
                    <RowDefinition Height="1*" />
                    <RowDefinition Height="1*" />
                    <RowDefinition Height="1*" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="1*" />
                    <ColumnDefinition Width="50" />
                    <ColumnDefinition Width="1*" />
                </Grid.ColumnDefinitions>

                <Entry x:Name="BoxNum"
                       Text="{Binding BoxNo, Mode=TwoWay}"
                       BackgroundColor="Chartreuse"
                       HorizontalTextAlignment="End"
                       Grid.Row="3"
                       Grid.Column="2"/>

            </Grid>
            <Button Text="Use Bag!"
                    x:Name="Commit"
                    HorizontalOptions="Center"
                    VerticalOptions="Center"
                    Clicked="CommitClicked"
                    />
        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

Now just to add more of my thoughts. It's clear that a 2 way binding is complicated and could easily have an infinite loop when you set the code in text and raises a changed event -> the UI sees the event does a get, updates itself and sends a set command because it's changed but that's clearly not happening and is such a simplistic issue that the designers must have accounted for it.
To be clear the unexpected data is passing through the set parameter, the Change event is being raised, a get happens  and then it starts over with the set being called and I cannot figure out why it's being called or why the value is a substring of the value passed into the ScannedText set event.
Comment: Sorry I had a few days vacation. Thanks for your help.  Eventually I realized that the "issues" were only occurring on fields with focus.  In short my broadcast receiver was getting the barcode output and it was being written at the same time to that field.  I found a dirt simple solution in the DataWedge configuration that disables keystroke output and viola, no more issues. You're linked solution with the IsBusy would work if I discarded the secondary inputs but not if I queued them. I think I'd like to have a SetReadOnly method in the UI and trigger it with a MainThread.InvokeOnMainThread()
Comment: First, make sure you don't have two two-way bindings to the same property. Assuming you don't, sounds like a "re-entry" problem. Additional incoming data causes a second Set, before the first Set has propagated through everything it affects. Can you change your implementation, so that Set is done less often? Accumulate data for a second, then Set?
Comment: Steve, so far in my testing all incoming data has come in via the scanner. It's certainly viable to collect from the keyboard but that hasn't been happening. The onReceive function  of the scanner is only hitting once
Comment: The symptom suggests to me that scanner input is causing Set to get called multiple times, too quickly. Ensure that never happens, and the problem might go away.
Comment: I triple checked. All 9 bindings are unique but only 1 binding is currently 2 way because the others are on labels.
Comment: Unique isn't the point. I would use a high res stopwatch and record the ticks when Set is called. Save each value, compare to previous value. Are there ever two Setter calls close together in time?
Comment: Sorry, I missed the statement that you only see one call per scan. Maybe clone the string, to make sure isn't a buffer that is getting re-used?
Comment: Another idea. Comment out scanner's ability to set anything. On a timer, directly call Setter once a second, with string you store from a previous scan. Problem still happen? Goal is to determine whether it really is onpropertychanged going haywire, or something elsewhere.
Comment: That's a good thought. I'll give those a try.
Comment: `Application.Current.Dispatcher.Dispatch( () => ScannedText = . . . );`  This helps ensure setter is called at a safe time.
Comment: You appear to be correct. This is clearly an issue with the scanner as everything works as expected with a timer based set of the data. Thanks for pointing me in the right direction.
Comment: That doesn't necessarily mean it is an issue with scanner. Its possible that the scanner interrupt happens "at a bad time". Try my last comment. If that doesn't fix it, then [use BlockingCollection to queue incoming changes](https://stackoverflow.com/a/76284531/199364). Similar to `HandleOneTap` there, be sure to wrap `ScannedText = ...` in a Dispatch call. If still not fixed, then add to `// Consume the BlockingCollection` loop, `await Task.Delay(500);`, before `await HandleOneTap`. Tune the value as needed. Your situation is different than that Q&A the onpropertychanges take time.
Comment: I suspect that onpropertychanges is not thread safe. Goal is to ensure UI has fully updated after one sequence of setter / onpropertychanges, before next setter call is allowed to happen. Unfortunately, I'm not aware of any Maui event that will tell us that UI has finished processing all changes and updating the UI. Thus the hack of using a delay.
Answer: barcodeConfig.PutString("keystroke_output_enabled", "false");

fixed my issue. No more dual inputs.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


When recall methods Fragment not attached to a context Error. What context should i send and receive?

Question: At first my sendData method is working but when I call it from another activity it has 'not attached to a context.' error.
When I opened it looks work, but after i delete some data it wasn't work.
Here is my code.
DeleteDialog.java
public class DeleteDialog extends android.support.v4.app.DialogFragment {
private Context mContext;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.activity_delete_dialog, container, false);

    mContext=this.getContext();

...

ok_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(editText.getText().toString().equals("")){
                Toast.makeText(getContext(), "과목명을 입력해 주세요", Toast.LENGTH_SHORT).show();

            }else{

                dbHelper = new DBHelper(mContext);
                db = dbHelper.getWritableDatabase();
                dbHelper.deleteColum(editText.getText().toString());
                timeTableFragment.sendData(mContext);
                getDialog().dismiss();
            }

        }
    });

TimeTableFragment.java
public class TimeTableFragment extends Fragment {
private Context mContext;

public void sendData(Context context) { //get data and draw to layout
    dbHelper = new DBHelper(context);
    db = dbHelper.getWritableDatabase();
    dbHelper.onCreate(db);
    String date = "", start = "", end = "", title = "", color = "";

    ArrayList<SubjectItem> timetable_data;
    timetable_data = dbHelper.getDataTimetable(); //get data from sql
    SimpleDateFormat sf = new SimpleDateFormat("HHmm");

    int resID = 0;
    int mok;
    Date a, b;
    long diff, min;
    View view = getView();

    for (int i = 0; i < timetable_data.size(); i++) {  // draw to layout
        date = timetable_data.get(i).getSub_date();
        start = timetable_data.get(i).getSub_start();
        end = timetable_data.get(i).getSub_end();
        title = timetable_data.get(i).getSub_title();
        color = timetable_data.get(i).getSub_color();

        if (date.substring(0, 2).equals("Th")) {
            date = "h";
            Log.d("ㄹㄹ","목요일 : " +date);
        }
        date = date.toLowerCase().substring(0, 1);
        Log.d("ㄹㄹ","바깥의 데이터 : " +date);
        start = start.replace(":", "");
        end = end.replace(":", "");

        try {
            a = sf.parse(start);
            b = sf.parse(end);
            diff = b.getTime() - a.getTime();
            min = (diff / (1000 * 60));
            mok = (int) min / 30;

            Log.d(TAG,"title " +title + " start :  " + start +","+ a.getTime()+ " / end : " +  end+","+b.getTime() +   "   date : " + date);

            for (int k = 0; k < mok; k++) {

                if (mok != 1) {

                    if (end.substring(2, 4).equals("30")) {
                        end = Integer.toString(Integer.parseInt(end) - 30);
                        if (end.length() == 3) end = "0" + end;
                        Log.d(TAG, " 그리기 title :  " +title );
                        //Log.d(TAG , "콘텍스트 : " + getContext().getPackageName());
         Error ->       resID = getResources().getIdentifier(date + end, "id", getContext().getPackageName());
                        TextView textView = (TextView) view.findViewById(resID);
                        textView.setText(title);
                        paintTimetable(textView,color);

                    } else {
                        end = Integer.toString(Integer.parseInt(end) - 70);
                        if (end.length() == 3) end = "0" + end;
                        Log.d("Contxet " , "콘텍스트 : " + getContext().getPackageName());
                        resID = getResources().getIdentifier(date + end, "id", getContext().getPackageName());
                        TextView textView = (TextView) view.findViewById(resID);
                        textView.setText(title);
                        paintTimetable(textView,color);
                        Log.d(TAG, " 그리기 title :  "  +title);
                    }
                } else {
                    Log.d("Contxet " , "콘텍스트 : " + getContext().getPackageName());
                    resID = getResources().getIdentifier(date + start, "id", getContext().getPackageName());
                    TextView textView = (TextView) view.findViewById(resID);
                    textView.setText(title);
                    paintTimetable(textView,color);

                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    try {

        mContext=getContext();
    } catch (ClassCastException e) {
        Log.d(TAG, "Exception" + e.getMessage());
    }
}

DBHelper.java
public class DBHelper extends SQLiteOpenHelper {

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);

}

...

public void deleteColum(String name)
{
    String DELETE = "DELETE FROM " + TABLE_TIMETABLE + " WHERE " + KEY_TITLE + "='" + name + "'";

    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL(DELETE);
    Log.d("dd", "sql deleted  :  " + name);

}

And Error message :
Fragment TimeTableFragment{f4aa844} not attached to a context.

In DB Insert, Delete are perfectly works but after call sendData method in DeleteDialog occurred 'not attached to a context'.
What context should I send and receive?
Comment: Your `DeleteDialog` is already a `Fragment` that is attached - why are you using some different `TimeTableFragment` to send your data? Where do you add the `TimeTableFragment` to a `FragmentManager`?
Comment: @ianhanniballake Actually sendData should be renamed to drawData. In DeleteDialog, delete some column and redraw the data using TimeTableFragemnt sendData method. FragmentManger is in MainActivity it's consist of bottom navigation view.
Answer: All database tasks should be done in async (another thread). It might take a while and after job is done you should come back to main thread and check if the view still exist, this way you will avoid memory leaks and error that you mentioned.
Answer: Use getApplicationContext() for initializing your DBHelper. This will ensure proper context of your app and does create the error you are receiving.
Addtional Info:
Make your DBHelper as Singleton it will optimize your app resources.


Swift 3 mutating functions missing ('...inPlace' methods)

Question: In Swift 2.3, we can write something like this:
var rect = CGRect(...)
rect.offsetInPlace(dx: 15, dy: 0)

to move a rect 15pt to the right.
However in Swift 3, it seems like this function does no longer exist.
When inspecting the CGRect interface we can only see the non mutating variant offsetBy(dx:, dy:). This is also true in all the places we've usually used mutating functions (named ...inPlace). I have already searched the Swift evolution repo on GitHub, but couldn't find any notes about this.
Have the mutating variants been removed? Is the remaining function automatically mutating depending on whether or not the return value is used? IMHO, it would be a shame, if they have actually been removed, because they used to be very convenient when doing code based layout, etc.
Comment: It doesn't show as deprecated https://developer.apple.com/reference/coregraphics/cgrect/1455748-offsetinplace
Comment: in the meantime you can do as follow `extension CGRect {
    mutating func offsetInPlace(dx: CGFloat, dy: CGFloat) {
        self = offsetBy(dx: dx, dy: dy)
    }
}`
Comment: Yes I know I could go ahead and write extensions for things that are missing. But I'd rather avoid doing so for ALL the ..inPlace methods usually provided by the framework itself..
Comment: I just provided you a way of keeping your code as it was before. You can refactor your code if you want. https://developer.apple.com/reference/coregraphics/cgrect offsetInPlace is not listed there anymore
Answer: You can make one for compatibility.
extension CGRect {
    mutating func offsetInPlace(dx: CGFloat, dy: CGFloat) {
        self = self.offsetBy(dx: dx, dy: dy)
    }
}

Answer: It seems there is no offsetInPlace anymore. Please see the screen here is all available functions in Instance Methods
Comment: Did they remove this via oversight, or are there a load of mutating functions that are no longer existing? (I just converted my app to 3.0 and I used offsetInPlace a lot)
Comment: @solenoid Hi made more research about this and seems this function load to mutating. Please review this link https://developer.apple.com/library/content/releasenotes/General/iOS91APIDiffs/Swift/CoreGraphics.html


__getitem__ method receives int instead of slice obj

Question: When implementing the __getitem__ method in a custom class I expect the second argument to always be a slice obj.
However, when one execute obj[i] where i is an integer, obj.__getitem__(self,value) receives an int instead of a slice.
This can be tested doing
class MyClass:

    def __getitem__(self, sliceobj):
        print(type(sliceobj))

a = MyClass()

a[1:5]
a[2:]
a[::2]
a[0]

>> <class 'slice'>
>> <class 'slice'>
>> <class 'slice'>
>> <class 'int'>

This is causing me issues as my class has an internal list (defined in __init__) and I want to use the slice to iterate over it. The problem is that the output of list[slice] is not an iterable when slice is an int.
In other words:
class MyClass2:

    def __getitem__(self, sliceobj):

        a_list = [1,2,3,4]

        print(sliceobj)

        for val in a_list[sliceobj]:
            # do stuff
            pass

        print('it worked')

a = MyClass2()

a[1:3]
a[2:]
a[::2]
a[0]

works for the first 3 calls, but it doesn't for the last, as a_list[0] is not iterable.
Shouldn't a[0] be translated in a.__getitem__(slice(0,1)) (that would work) ?
Comment: If `a[x]` were translated to `a[x:x+1]`, how would you ever get the value actually stored at that position, rather than another list that contains the value?
Comment: Once upon a time (in Python 2), there were separate methods `__getitem__` and `__getslice__`. At some point (probably at or around the time new-style classes were created), the `slice` type was added so that both methods could be merged into a single `__getitem__` method. `__getslice__` was deprecated and formally removed in Python 3.
Comment: At the moment the only solution i found is to add `if isinstance(sliceobj, int): sliceobj= slice(sliceobj, sliceobj+1)` to the `__getitem__` method
Comment: @chepner you are right. That would make access to the value impossible. Didn't think about that (as in my case that is not required, but it obviously is in most other cases)
Comment: Note that the slicing syntax can also generate a *tuple* of `slice` objects: `a[1:3, 2:]` would desugar to `a.__getitem__((slice(1,3), slice(2,None))`. This was added specifically for NumPy, though no built-in type supports the resulting tuple.
Answer: As per the docs:

For sequence types, the accepted keys should be integers and slice objects

You can check if the key is a slice or not and create one:
class MyClass2:
    def __getitem__(self, key):

        a_list = [1,2,3,4]
        keys_to_iterate = key if isinstance(key, slice) else slice(key, key+1)
        print(key)

        for val in a_list[keys_to_iterate]:
            # do stuff
            pass

        print('it worked')

Running example: https://repl.it/repls/SmallDarkblueWifi


Facebook Graph API: Miscellaneous UserId

Question: When exploring the Facebook Graph API, at: https://developers.facebook.com/tools/explorer The default example is get my name & id (under the assumption the browsers logged to my Facebook account). All good and I get my correct Id (facebook.com/id redirect to my profile).
So here is the thing: Exploring network traffic via developer console, I noticed some ajax have user id as url param, and the id is totally different from the previous one:

Same length
Much more zeros

So I tried same thing: facebook.com/new_id and same result: Redirect to my correct profile page.
How is that each user have 2 different id's?
Answer: It's called app-scoped user ids, see https://developers.facebook.com/docs/apps/changelog#v2_0_graph_api


Net5.0 Razor Pages CRUD Delete Error, Can anyone help me with this?

Question: I keep getting this error when I try deleting an album:
An unhandled exception occurred while processing the request.
SqliteException: SQLite Error 19: 'FOREIGN KEY constraint failed'.
Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(int rc, sqlite3 db)
DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
This is the Delete.cshtml.cs Page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using ChinookApp.Models;

namespace ChinookApp.Pages_Albums
{
    public class DeleteModel : PageModel
    {
        private readonly ChinookAppContext _context;

        public DeleteModel(ChinookAppContext context)
        {
            _context = context;
        }

        [BindProperty]
        public Album Album { get; set; }

        public async Task<IActionResult> OnGetAsync(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            Album = await _context.albums.FirstOrDefaultAsync(m => m.AlbumId == id);

            if (Album == null)
            {
                return NotFound();
            }
            return Page();
        }

        public async Task<IActionResult> OnPostAsync(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            Album = await _context.albums.FindAsync(id);

            if (Album != null)
            {
                _context.albums.Remove(Album);
                await _context.SaveChangesAsync();
            }

            return RedirectToPage("./Index");
        }
    }
}

This is the Delete.cshtml Page:
@page
@model ChinookApp.Pages_Albums.DetailsModel

@{
    ViewData["Title"] = "Details";
}

Details

Album

            @Html.DisplayNameFor(model => model.Album.Title)

            @Html.DisplayFor(model => model.Album.Title)

Related Tracks

            @Html.DisplayNameFor(model => model.Track[0].TrackId)

            @Html.DisplayNameFor(model => model.Track[0].Name)

@foreach (var item in Model.Album.tracks) {

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

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

}

    Edit |
    Back to List

My Album Model:
using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;

namespace ChinookApp.Models
{
    public class Album
    {
        public int AlbumId { get; set; }
        public string Title { get; set; }
        public int ArtistId { get; set; }
        public ICollection<Track> tracks { get; set; }
        public ICollection<Artist> artists { get; set; }

        }
}

Comment: it seems like you have data that references the album you are trying to delete. You can handle this many ways. You can delete everything referencing it first. Or you can set the cascade behavior to update the referencing item to null album id. Those are probably the two most commonly used options.
Answer: Because your Album has two one-to-many associated attributes. When you delete Album, its associated attributes are not deleted, which leads to foreign key constraint problems, like
@Crowcoder said, you have two solutions.
One way you can change your code like below:
  Album = await _context.albums.Where(c=>c.Id==id).Include(c=>c.tracks).Include(c=>c.artists).SingleOrDefaultAsync();

The second way is use Fluent API OnDelete Method:
For the details you can see:
Doc : Cascade Delete.
Article:The Fluent API OnDelete Method.