How I can insert some help text on the ckeditor media embed "Create embed" tab?

Question: How I can insert some help text on the ckeditor media embed "Create embed" tab? Oddly, I can't even find those words together in code. I have a user confused about its use, so I want to specify that this is for video URLs only. She is trying to "embed" an image that she already has on the site, but she gets an error message "input did not match any media types." If I do a form alter of "entity_embed_dialog" then the message displays on all tabs of media embed dialog window.
I have several contrib modules on the site. Any of these may/may not affect this process:
embed, entity, entity_browser, entity_embed, lightning_media, video_embed_field
Comment: Can you put twitter or other embeds in that field too?
Comment: From a comment you left on the answer, I take the [Entity Browser](https://www.drupal.org/project/entity_browser) module has been installed. Are there other contributed modules installed on that site?
Answer: Drupal is actually rendering the media create form for that bundle of 'embed', so that is why your alter affecting all the tabs.
What you want to do is actually edit the 'embed' media type field settings.

Open up /admin/structure/media and select your 'embed' media type.
Select the "Manage Fields" tab.
Edit the video embed field and add some help/description text.

You can also go to "Manage form display" and see the form configuration if there are settings there you would like to adjust.
Comment: This sounded good, but it didn't display anything other than the entry textarea. I did a search for "Enter a URL..." and it's in the lightning_media module, `src/Plugin/EntityBrowser/Widget/EmbedCode.php` file.
Comment: Ah yeah, core Drupal widget will render the form, whereas this module has some custom functionality. I think you are on the right track with the form alter, but that widget form is the one you want to alter.
Comment: @shelane were you able to sort out your issue with the widget form alter?
Comment: Not exactly, but close. I found that the right hook I need is `hook_form_entity_browser_form_alter` and that at least allows me to add some text to the form. I was trying with xdebug to fin the form element and maybe replace its placeholder value, but it wasn't showing the form element event though the breakpoint fired.


Unzip .zip File without Writing to Disc from Response c#

Question: Let me preface by stating that I' somewhat new to dealing with zipping/unzipping/reading/reading files. That being said, I'm doing a PoC that will retrieve data via api and write the responses to a database. The response is a zip file and inside this zip is the json data I will be reading and writing to the database.
I'm having some trouble unzipping and reading the information. Please find the code below:
HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage
            {
                Method = HttpMethod.Get,
                RequestUri = new Uri(baseUrl),
                Headers =
                {
                    { "X-API-TOKEN", apiKey },
                },

            };

            using (var response = await client.SendAsync(request))
            {
                response.EnsureSuccessStatusCode();
                var body = await response.Content.ReadAsStringAsync();
               // here is where I am stuck - not sure how I would unzip and read the contents
            }

Thanks
Comment: Is the HTTP GZIP or are you trying to unzip an attachment?
Comment: @jdweng it is a .zip
Comment: It is a MIME attachment which is in the body of the HTMP (https://learn.microsoft.com/en-us/previous-versions/office/developer/exchange-server-2010/aa563375(v=exchg.140)?force_isolation=true) .  The attachment is a new line that starts with two dashes.  So you need to extract the attachment.  If you do not want to write to disk you need to unzip into a memory stream.
Answer: Assuming you actually have a .zip file, you don't need a MemoryStream, you just need to pass the existing stream to ZipArchive
static HttpClient client = new HttpClient();  // always keep static client

async Task GetZip()
{
    using var request = new HttpRequestMessage(HttpMethod.Get, new Uri(baseUrl))
    {
        Headers = {
            { "X-API-TOKEN", apiKey },
        },
    };
    using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

    response.EnsureSuccessStatusCode();
    using var stream = await response.Content.ReadAsStreamAsync();
    await ProcessZip(stream);
}

async Task ProcessZip(Stream zipStream)
{
    using var zip = new ZipArchive(zipStream, ZipArchiveMode.Read);
    foreach (var file in zip.Entries)
    {
        using var entryStream = file.Open();
        await ....; // do stuff here
    }
}

Comment: Not sure what you mean. `entryStream` is a `Stream` and has no `BaseStream` property. Perhaps you meant `StreamReader.BaseStream`, not sure how that's relevant? And why would you expect it to have a `BaseStream`?
Comment: `entryStream` is showing `null` for BaseStream. Would you know why?
Comment: sorry yeah I got a little confused here. It was not relevant. I was able to use your code and tweak a bit to get the json object from the zip file, so I'll be marking this as the solution. Thank you again.
Answer: You can convert body to a byte array and then unzip it using MemoryStream.
    byte[] bytes = Encoding.ASCII.GetBytes(body);
    using (var mso = new MemoryStream(bytes)) {
        using (var gs = new GZipStream(msi, CompressionMode.Decompress)) {
            CopyTo(gs, mso);
        }

        return Encoding.UTF8.GetString(mso.ToArray());
    }

Comment: @duls we initially have the `body` `String` which is converted into a `byte[]` called `bytes`. This array is used to create a `MemoryStream` object that we refer to as `mso`. `gs` is a `GZipStream`. `CopyTo` is a method where we pass our `gs` and `mso`. So, we initially have an array derived from a String, but at the stage when we call `CopyTo`, we already have stream objects.
Comment: It's a `.zip` file, not a gzipped file.
Comment: is `CopyTo` for an array?


EHcache does not work in spring

Question: I am now applying EHcache to my web application by means of SpringModules EHcache support.
However, it does not work. No exception thrown though.
ehcache.xml:
<ehcache>
  <diskStore path="c:\\myapp\\cache"/>
  <defaultCache
      maxElementsInMemory="500"
      eternal="true"
      overflowToDisk="false"
      memoryStoreEvictionPolicy="LFU" />
  <cache name="WorldExpoCache"
      maxElementsInMemory="500"
      eternal="true"
      overflowToDisk="false"
      memoryStoreEvictionPolicy="LFU" />
</ehcache>

Excerpt of my applicationContext.xml:

    <ehcache:config configLocation="classpath:ehcache.xml"/>

<ehcache:proxy id="WorExpoDAO" refId="worldExpoDAO">
       <ehcache:caching methodName="grabcategory" cacheName="WorldExpoCache"/>
    </ehcache:proxy>

    <bean id="worldExpoDAO" class="com.cn.dao.WorldExpoDAOImpl">
        <property name="sessionFactory">
            <ref local="mySessionFactory" />
        </property>
    </bean>

Certainly, I have a method called "grabcategory" sitting in my DAO class.
However, when this method fired up second time, related data was still retrieved from underlying database rather than from cache.
P.S.: I did include all required jars into my application
Why was that? Can anybody tell me where I did wrong?
Any suggestions will be highly appreciated.
Answer: Spring Modules is no longer maintained, and does not work properly with the current versions of Spring and EhCache.
Unfortunately, the caching functionality provided by Spring Modules doesn't really have a replacement, you'll have to roll your own.
Answer: In fact the caching functionality of Spring Modules does have a replacement. EhCache Annotations for Spring has emerged, and is in fact a lot easier to use.
http://code.google.com/p/ehcache-spring-annotations/
Answer: The @Cachable annotation was introduced in the Spring 3.1 release. It can be configured to use Ehcache as backend.

EHcache does not work in spring


Crystal Reports - Unable to connect on PC's other than my own and another developer

Question: I built a report in Visual Studio 2010 using Crystal Reports for .net framework 4.0
All operator machines have the runtime CR13 for .net framework 4.0 installed on their machines.
When this report is run in the application through the report viewer, I can view and interact with it.  The other programmer on this project can also do this.  If we log off our machines and log onto our machine under another user's network credentials, reports work just fine.
However, if we use another operators PC and pull up the report, they are prompted to provide credentials.  This should not happen due to integrated security and the server field is also blank and grayed out.
Ive been fighting with this for hours and I am out of ideas.  It works on the dev machines but not on operator machines and they have crystal reports 13 for .net framework 4.0 runtime installed, the same one used to build these reports.
Anybody have any ideas, i'll try anything at this point...
So far I've tried:

Logging in as others on my machine, everyone works on my machine
Giving users full permissions on the database, no luck
Manually creating a connection in the code to set to my crystal report viewer to try to force this to work, no luck there
Comment: Are your operators on a separate network/domain from yourselves?  Do they need to do a 'double hop' authentication? Have you logged on as yourself on your user's machine?
Comment: We are all on the same network, I cannot access these reports as myself on their machines
Answer: I'd guess that the problem the connection string of the report. Is set to integrated authority? Try setting up a Report Only type user with select rights to the appropriate tables, and setting the connection string to use that login explicitly.
Edit - Are you connecting to an Oracle database? Make sure your drivers are up today, I've had huge headaches from that in the past.
Comment: SQL Server 2005. The report has setup all of that already I don't need to specify my own connection string
Answer: I had to create ODBC connections rather than using OLEDB.  Problem was solved 100%, although I don't think my network admins liked having these added to all the machines in the department.


SPF google mail + MY IP

Question: So this TEXT record response hardfail
XX.XX.XX.XX => my mail server
v=spf1 ip4:XX.XX.XX.XX include:aspmx.googlemail.com ~all

Question is how to create valid SPF record for sending e-mail

for my server IP
and using google mail servers, i thin problem is witch -all ~all
Comment: FWIW, [Google suggest](http://support.google.com/a/bin/answer.py?hl=en&answer=178723) that you should `include:_spf.google.com`
Comment: The ending `~all` is used while you are testing your SPF records but don't want them to actually *do* anything yet.  The ending `-all` is for once they are correct and you want people to reject email that claims to be from you but isn't.
Answer: I used to work for a company that had Google as their main email provider and this is an example of the SPF record.
v=spf1 a mx ip4:X.X.X.X ip4:Y.Y.Y.Y include:_spf.google.com include:blackberryservers.domain.com -all

So we could definite additional static IPs that we want to relay through us as well as the Google servers. We also did a lot of Blackberry email so we had a dig command set up to pull the SPF servers for the Blackberry servers. From here we put them in a separate spf record and then included it on the main SPF record. If you don't trust the _spf.google.com you can create a similar dig script to show all of the IPs and then cron it and diff the results on an hourly or daily basis.
Below is a small part of that code. I haven't used this in a while but I believe the output should still be the same.
PREVIOUS=/home/user/google_ips
NEW=`dig txt _spf.google.com | grep _spf | grep -ve ";" | awk -F\" '{print $2}' | tr ' ' '\n' | sort`
if [ "$PREVIOUS" != "$NEW" ]; then
echo $NEW | nail -r firstname.lastname@example.com
fi

Comment: Google search S*CK, 3 hours and only wrong information  --  THX , that solve my problem
Comment: OK now its working i had receive 4 new email that should be delivery day ego :)
Comment: Very glad to hear it!

SPF google mail + MY IP


Como resgatar partes especificas de um txt?

Question: Estou tento recuperar dados específicos de um txt, por exemplo do seguinte:
    Cod: 275          Nome: xxxxxxxxxxxxxxxx                            Funcao: xxxxxxxxxxxxxxxxxxxx                Dep.IR:  0 |
Admissão: 27/08/2012  Situação:Ativo                                                     Ocorrencia: 1 Salario:   1.630,00 |
+----------------------------------------------------------------------------------------------------------------------------+
    1 Salário                              30,00     1.630,00 |   11 INSS Sobre Salário                   9,00       187,84 |
5 D.S.R. Sobre Horas Extras                         16,91 |                                                             |
|   17 Horas Extras 50%                      5,00        55,57 |
|  152 DSR Adicional Noturno                             58,63 |                                                             |
| 1047 Adicional Noturno 25%               104,00       192,64 |
| 1403 Indenização Horas Itinere            18,00       133,36 |
+----------------------------------------------------------------------------------------------------------------------------+
| Base INSS Empresa:             2.087,11 Base INSS Func.:            2.087,11 Base INSS Func 13o Sal:                 0,00
| Base FGTS 13o:                     0,00 Base F.G.T.S.:              2.087,11 F.G.T.S.:                             166,97
| Base IRRF:                     2.087,11 Deducoes:                     187,84
Proventos:                     2.087,11 Descontos:                    187,84 Liquido:                            1.899,27  |
+----------------------------------------------------------------------------------------------------------------------------+

+----------------------------------------------------------------------------------------------------------------------------+
| Cod: 752          Nome:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx             Funcao: xxxxxxxxxxxxxxxxxxx                 Dep.IR:  1 |
| Admissão: 04/09/2017  Situação:Ativo                                                     Ocorrencia: 1 Salario:   1.470,00 |
+----------------------------------------------------------------------------------------------------------------------------+
|    1 Salário                               6,00       294,00 |   11 INSS Sobre Salário                   9,00        26,00 |
|    5 D.S.R. Sobre Horas Extras                         13,03 |   39 Faltas (Dias)                        1,00        49,00 |
|   17 Horas Extras 50%                      1,30        13,03 |   45 INSS Sobre Férias                               169,18 |
|  270 Férias No Mês                        24,00     1.409,84 |   53 Liquido de Férias                             1.710,61 |
|  271 1/3 de Férias no Mês                             469,95 | 1055 Faltas (DSR)                         1,00        49,00 |
| 1403 Indenização Horas Itinere            10,00        66,82 |                                                             |
+----------------------------------------------------------------------------------------------------------------------------+
| Base INSS Empresa:             2.168,67 Base INSS Func.:            2.168,67 Base INSS Func 13o Sal:                 0,00  |
| Base FGTS 13o:                     0,00 Base F.G.T.S.:              2.168,67 F.G.T.S.:                             173,49  |
| Base IRRF:                       288,88 Deducoes:                     215,59                                               |
| Proventos:                     2.266,67 Descontos:                  2.003,79 Liquido:                              262,88  |
+----------------------------------------------------------------------------------------------------------------------------+
| Proventos:                     1.298,40 Descontos:                    103,87 Liquido:                            1.194,53  |
+----------------------------------------------------------------------------------------------------------------------------+

A parte de extrair os dados, por exemplo o Cod, Nome, salario e os demais estou conseguindo fazer, lendo linha por linha e usando index, porém não sei se é a maneira ideal ou  pythonica de se fazer.
Segue meu código até então:
folha = open("xxxxx.txt")

linhas = folha.readlines()
list_func = []
#nome = linhas[linhas.find("nome:")+len("nome:"): linhas.find("Funcao:")+len("Funcao:")]
for i in range(0, len(linhas)):
        linha = linhas[i]
        try:
                cod  = linha[ linha.index("Cod:")+len("Cod:"): linha.index("Nome")]
                nome = linha[linha.index("Nome:")+len("Nome:"): linha.index("Funcao")]
                funcao = linha[linha.index("Funcao:")+len("Funcao:"): linha.index("Dep.IR")]
        except:
                funcionario = { 'Cod' : cod, 'Nome' : nome}
                print("Nome: " + funcionario['Nome'] + "Código: " + funcionario['Cod'])

Minha dúvida é de como que eu posso separar os funcionário por funcionario e jogar em um array, porque eu sei que os dados do funcionario começam em 'Cod'
e terminam em 'Liquido', como eu posso fazer essa verificação? Gostaria de uma dica
Answer: Dá para verificar se a linha contém o campo a adicionar à lista.
folha = open("xxxxx.txt")

linhas = folha.readlines()
list_func = []

for i in range(0, len(linhas)):
    linha = linhas[i]
    if "Cod:" in linha and "Nome:" in linha:
        cod  = linha[linha.index("Cod:")+len("Cod:"): linha.index("Nome:")].strip()
        nome = linha[linha.index("Nome:")+len("Nome:"): linha.index("Funcao:")].strip()
        list_func.append({"Cod": cod, "Nome:": nome})

print(list_func)

Comment: Nossa, é mais simples do que estava imaginando, Muito obrigado amigo.


Nested AJAX call in React redux

Question: So I'm working on some demoware and I have two AJAX calls, the first is just a last modified date, to let me know whether to fetch data from the second. This works, but I feel like there's a smarter way to do this for real applications, and I'm just a UI monkey trying to come up in the world, any advice is much appreciated.
<code>    componentDidMount() {
      this.getJson();
      setInterval(this.getJson.bind(this), 1000);
    }

    getJson() {
      const el = this;
      const isModified = (date) => {
        let mod = false;
        if (this.state.lastModified == date) {
          console.log('no change');
        } else {
          mod = true;
          console.log({
            'previously modified': this.state.lastModified,
            'newly modified': date
          });
          el.setState({lastModified: date});
        }
        return mod;
      }

      this.serverRequest = $.ajax({
        url: 'URL_LAST_MODIFIED',
        success: function(result) {
          const lastModified = $.parseJSON(result).LastModifiedDateTime;
          if (isModified(lastModified)) {
            $.ajax({
              url: 'URL_DATA',
              success: function(result2) {
                const result2Obj = $.parseJSON(result2);
                el.setState({data: result2Obj});
              },
              error: function(xhr, status, err) {
                alert(err.toString());
              }
            })
          }
        },
        error: function(xhr, status, err) {
        }
      });
    }
</code>
Answer: I think it is realted to this:
https://github.com/reactjs/redux/issues/1676
The idea is create a action for the first ajax call... and on success dispatch another action to execute the second call.

Nested AJAX call in React redux


Maximum of three variables function

Question: Let $a,b,c\in[0,1]$ and such that $a\leq b\leq c$. Find the maximum of
$$
f(a,b,c)=c(\sqrt{a}+\sqrt{b})-(a+b)\sqrt{c}
$$
This is a problem in the contest for talented students. I have tried but it is extremely difficult.
Attempt Observe that $f(a,b,c)\leq \sqrt{a}+\sqrt{b}-a-b$. Indeed, the latter inequality is equivalent to
$$
(1-\sqrt{c})((\sqrt{a}+\sqrt{b})(1-\sqrt{c}-a-b))\geq 0.
$$
Answer: Set $x = \sqrt a, y = \sqrt b, z = \sqrt c$. Then $0 \le x \le y \le z \le 1$, and
$$
 f(a, b, c) = z^2(x+y) - (x^2 + y^2) z
 = z x (z-x) + z y (z - y) \, .
$$
Applying the inequality of arithmetic and geometric means we get that
$$
 f(a, b, c) \le z \left( \frac{x + (z-x)}{2}\right)^2 + z \left( \frac{y + (z-y)}{2}\right)^2 = \frac{z^3 }{2} \le \frac 12.
$$
Equality holds for $(x, y, z) = (\frac 12, \frac 12, 1)$, that is for
$(a, b, c) = (\frac 14, \frac 14, 1)$.
Answer: $$\frac{\partial^2 f}{\partial c^2}=\frac{a+b}{4\sqrt{c^3}}>0.$$
Thus, $f$ is a convex function of $c$ and $$\max{f}=\max\{f(a,b,1),f(a,b,b)\}.$$
Now, by AM-GM: $$f(a,b,1)=\sqrt{a}+\sqrt{b}-a-b=\sqrt{a}(1-\sqrt{a})+\sqrt{b}(1-\sqrt{b})\leq$$
$$\leq\left(\frac{\sqrt{a}+1-\sqrt{a}}{2}\right)^2+\left(\frac{\sqrt{b}+1-\sqrt{b}}{2}\right)^2=\frac{1}{2},$$
where the equality occurs for $a=b=\frac{1}{4}.$
Also, $$f(a,b,b)=\sqrt{ba}(\sqrt{b}-\sqrt{a})\leq\sqrt{b}\left(\frac{\sqrt{a}+\sqrt{b}-\sqrt{a}}{2}\right)^2=\frac{1}{4}b\sqrt{b}<\frac{1}{2},$$
which says that $\frac{1}{2}$ is a maximal value.

Maximum of three variables function


Reading data from Google firestore with Python, daily reads count increases too fast

Question: I have a program reading data from a Google firestore database.
The database contains data for different users, and each instance of the program is supposed to read data only for a specified user.
The data is organized in this way:
UsersInfo (Collection)
|________User01 (document)
|________User02 (document)
...
|________UserN (document)

where each of the User documents contains an identifying ID.
The first time the program runs, it initializes the database and it looks for the right document containint the user info this way:
cred = credentials.Certificate(fcredentials_file.json)
firebase_admin.initialize_app(cred)
db = firestore.client()

docs = db.collection(u'UsersInfo').stream()
user_found = False
current_user_document = ''
## find the right document, based on user_ID
try:
    for doc in docs:
        if doc.to_dict()['Userid'] == user_ID:
            current_user_document = doc.id
            user_found = True
            print(f"User found in document {current_user_document}")
            break
except:
    print("Impossible to find user in firestore!!!")

At this point, the correct document for the required user has been located.
This info is passed to other processes in the system, which routinely check this document to retrieve some info, something like:
doc_ref = db.collection(u'UserInfo').document(UserXX)
return doc_ref.get().to_dict()['some_field']

I was expecting that:

during the initialization, the program checks all the UserXX documents in the collection (it's about 50 of them) -> 50 reads;
everytime the other processes check the identified User document, it counts as another read.

However, the amount of reported reads is skyrocketing...I ran the system a couple of times today, each time it performed the initialization and the other components checked the User document 4 or 5 times...but now the Usage reports 11K reads!
Am I doing something wrong, or did I misunderstand what even counts as a read?
Comment: Look into queries.
Answer: This one line alone immediately costs one read for every document in the collection:
docs = db.collection(u'UsersInfo').stream()

It doesn't matter what you do next - all of the documents are now read and available in memory.
If you are looking for only documents in the collection whose Userid field contains a specific value, you should query the collection using a filter on that field.
docs = db.collection(u'UsersInfo').where(u'Userid', u'==', user_ID).stream()


Problem extending BookNavigationBlock

Question: i have a Problem extending a BookNavigationBlock Plugin. When I extend BlockBase it works, but when trying to extend BookNavigationBlock, it fails when placing the block, without any error messages. What am I missing here? (The Code is inside modules/ifg_book_navigation/src/Plugin/Block/IfgBookNavigationBlock.php)
namespace Drupal\ifg_book_navigation\Plugin\Block;

use Drupal\book\Plugin\Block;
/**
 * Provides a fully expanded 'Book navigation' block.
 *
 * @Block(
 *   id = "ifg_book_navigation",
 *   admin_label = @Translation("Expanded Book navigation"),
 *   category = @Translation("Menus")
 * )
 */
class IfgBookNavigationBlock extends BookNavigationBlock {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return array(
      '#markup' => $this->t('Hello, World!'),
    );
  }
}

Thanx!
UPDATE:
I could trace the Problem to the Plugin Factory.
In the getPluginClass method of DefaultFactory it is checked if the class exists:
if (!class_exists($class)) {
  throw new PluginException(sprintf('Plugin (%s) instance class "%s" does not exist.', $plugin_id, $class));
}

The value of $class is Drupal\ifg_book_navigation\Plugin\Block\IfgBookNavigationBlock which seems to be correct. However class_exists() itself seems to fail, not even returning false. This could have something to do with autoloading, as by default class_exists() tries this by default ...
UPDATE: It seems like the behaviour is the same for other existing blocks, just tested UserLoginBlock
Comment: _it fails when trying to Place the blog_ I suppose you meant block?
Comment: exactly – edited
Comment: For what it's worth I have encountered exactly the same problem with a class that extends ContactBlock which in turn extends BlockBase. The problem occurs when placing the block in the block admin UI. I also see the failure at the call to class_exists - i.e. no return value. The parameter to class_exists looks ok. As a second test I modified a working block class that derived directly from BlockBase and instead derived it from ContactBlock. The error then occurred. It seems that deriving from a class that derives from BlockBase seems to cause the class to not autoload.
Answer: The actual class has to be included in the use statement.
use Drupal\book\Plugin\Block\BookNavigationBlock;

Problem extending BookNavigationBlock


Validar delete no controller, retornar html helper

Question: Tenho meu cadastro, que foi feito usando Scallfold do visual studio
Na minha view:
   @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

            <input type="submit" value="Delete" class="btn btn-danger" /> |

    }

E no meu controller:
public ActionResult DeleteConfirmed(string id)
{
    Cliente cliente = db.Clientes.Find(id);
    db.Clientes.Remove(cliente);
    db.SaveChanges();
    return RedirectToAction("Index");
}

Como eu valido a exclusão se já existe registro com esse cliente? Como retorno para View usando html helper?
Answer: Coloque na View:
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

        <input type="submit" value="Delete" class="btn btn-danger" /> |

}

Controller:
public ActionResult DeleteConfirmed(string id)
{
    Cliente cliente = db.Clientes.Include(c => c.Registros).SingleOrDefault(c => c.Id == id);
    if (cliente.Registros.Count > 0) {
        ModelState.AddModelError("", "Cliente possui registros pendentes.");
        return View("Delete", cliente)
    }

    db.Clientes.Remove(cliente);
    db.SaveChanges();
    return RedirectToAction("Index");
}

Comment: Não aparece a mensagem de erro na view...
Comment: @Rod Você colocou o `@Html.ValidationSummary(true)`?
Comment: Acho que te falei bobagem. O `@Html.ValidationSummary(true)` tem que ser dentro do `Html.BeginForm`.
Comment: Exatamente dessa forma, não aparece a msg na View, tentei até com ValidationMessage("Erro") também não aparece
Comment: @Rod Revi algumas coisas e o `RedirectToAction` não considera o resultado da validação. Atualizei minha resposta.


Good places to start for Calculus?

Question: I am a student, and due to my school's decision to not teach Calculus in high school (They said we'd learn it in college, but that's a year and a half away for me), I have to learn it myself. I am trying to get a summer internship as a Bioinformatics intern, and I would like to have prior knowledge (I was told I'd need an understanding of calculus to get the internship.)
I have heard of MIT's OpenCourseWare, which I had taken a look at, but I was wondering if there were any other resources (Preferably free of charge, I don't have much money to spend)
Is there any good online (Preferably free) way to learn Calculus?
Comment: [Pauls' online notes](http://tutorial.math.lamar.edu/Classes/CalcI/CalcI.aspx) should be a decent one.
Comment: (Patrick JMT)[http://patrickjmt.com/] is also a good one. His videos are a little faster paced than Khan's, which I personally think is a good thing.
Comment: This isn't a way to learn calculus, but rather to test your conceptual understanding of the material. [This website](http://www.dougshaw.com/findtheerror/) offers a bunch of fake proofs of ridiculous claims ($\sin x > 0$ for all $x$, $0 = 1$, etc.) using calculus, and you have to try to find what the error is. I've found it to be fun and useful for developing logical careful thinking in mathematics at a lower level.
Answer: Have you looked at the Khan Academy?
There are tutorials for just about every topic in Calculus, particularly if you're just beginning to learn Calculus.

Topics covered in the first two or three semesters of college calculus. Everything from limits to derivatives to integrals to vector calculus. Should understand the topics in the pre-calculus playlist first (the limit videos are in both playlists)

MIT OpenCourseWare (Link to Calculus: single-variable, with lecture videos) can give you a nice outline of what topics to master, and how to progress through these topics, and includes video lectures, as well as handouts you can download.
Another great resource is Paul's Notes, which is presented as a progressive tutorial.
Answer: Try this site, it's interesting math doctor bob.
Answer: MIT OpenCourseWare is useful. Also, check out Paul's Online Notes:
http://tutorial.math.lamar.edu/Classes/CalcI/CalcI.aspx
Answer: www.openculture.com/freeonlinecourses
www.coursera.org/courses
Coursera comes with problem sets, the lectures are paced, and you can discuss things with your classmates on the associated forums.
Answer: Go online and order a calculus book from an older edition. My advice, take Stewart Calculus. The current edition is the 7th, thus expensive, even used. Purchase the 6th edition that can be had for a nickel and a dime and you got yourself an excellent resource.
Along with the websites listed by my colleagues, you can get quite far.

Good places to start for Calculus?


Javascript program that shows a message after inputting age, but function doesn't work

Question: I'm trying to make a fairly easy site/program that receives a number from an input, and after submitting using a button, shows the user a message based on their input. I feel as though it should be fairly easy, but I'm having a lot of errors, such as: Cannot set property 'innerHTML' of null. And as I tried fixing these errors (adding return false? to onsubmit on form, changing variables and syntax, etc.) I feel as if I am more stuck. I'm not sure how to make it work.
(Ignore the lastInn function, as it is something I did myself just to test if I could do it.)
Here is the html code:

<form onsubmit="return false" action="">
    <input type="number" name="inputAld" id="inputAld">

    <button type="submit" id="trykkAld" disabled="disabled" onsubmit="visAlder();">trykk på meg</button>

</form>

And here is the javscript file:
var vis, trykk;

function lastInn() {
var but;
but = document.querySelector("#trykkAld");
but.disabled = false;
}

trykk = document.getElementById("trykkAld");
vis = document.getElementById("visHer");

document.getElementById("visHer").innerHTML ="";

function visAlder() {
  var ald;
  ald = document.getElementById("inputAld").value;

  if (ald > 10) {
    vis.innerHTML = "Du er et ungt barn";
  }
  else if (ald < 10 && ald > 18) {
    vis.innerHTML = "Du er en tenåring";
  }
  else if (ald <= 18 && ald > 30) {
    vis.innerHTML = "Du er en ung voksen";
  }
  else if (ald <= 30 && ald > 60) {
    vis.innerHTML = "Du er voksen";
  }
  else if (ald <= 60 && ald < 70){
    vis.innerHTML = "Du begynner å dra på åra"
  }
  else if (ald <= 70) {
    vis.innerHTML = "Du er nok gammel";
  }
  else {
    vis.innerHTML = "Hva faen er du for noe?";
}

}
Edit: I fixed the operators in my document.
Answer: Your code looks logically wrong.
  else if (ald < 10 && ald > 18) {
    vis.innerHTML = "Du er en tenåring";
  }
  else if (ald <= 18 && ald > 30) {
    vis.innerHTML = "Du er en ung voksen";
  }
  else if (ald <= 30 && ald > 60) {
    vis.innerHTML = "Du er voksen";
  }

Won't all these return false?
Also try wrapping your code in a document ready.
Comment: I'm currently in the process of learning Javascript for the nth time, so operators are still kind of unclear to me, but i think i fixed them now(reversed the < and >). But what will wrapping the code in document ready do? And where do i begin the wrapping?
Comment: look here http://learn.jquery.com/using-jquery-core/document-ready/
You would want to do ```vis = document.getElementById("visHer");``` inside the ready
Comment: if the document is not rendered yet, attempting to get the element may result in null
Answer: I got the code to work. There is a missing brace at the end of the visAlder() function.
I think there is an issue with using the onsubmit in your form tag as well as in your button tag - these are probably conflicting with each other. Change your button type to type="button", change the onsubmit in your button tag to onclick and that should do it. Oh, and also remove the disabled attribute from your button tag.


trying to do a 360 degree rotation of a object

Question: My swift code is attempting to do a 360 degree rotation on a image view named box. The code does rotate however because I am doing a 360 degree rotation with code  self.box.transform = self.box.transform.rotated(by: CGFloat.pi * 2). Pi *2 is a 360 degree rotation so I think somehow its possibly confusing the compile. Like the rotation has already occured. The code should take one lap around the circle.
<code>import UIKit

class ViewController: UIViewController {
    var box = UIImageView()
    var box1 = UIImageView()

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        view.setNeedsLayout()
        view.layoutIfNeeded()

        self.box.setAnchorPoint(anchorPoint: CGPoint(x: 0.5, y: 1))
        Rotate()
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        box.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(box)
        box.backgroundColor = .systemPink
        box1.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(box1)
        box1.backgroundColor = .purple

        NSLayoutConstraint.activate([
            box.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.25),
            box.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.25),
            box.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            box.bottomAnchor.constraint(equalTo: view.centerYAnchor),

            box1.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.05),
            box1.widthAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.05),
            box1.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            box1.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
        // Do any additional setup after loading the view.
    }

    func Rotate(){

        let   rotation = UIViewPropertyAnimator(duration: 5, curve: .linear, animations: {

            self.box.transform = self.box.transform.rotated(by: CGFloat.pi * 2)

        })
        rotation.startAnimation()

    }

}

extension UIView{
    func setAnchorPoint(anchorPoint: CGPoint) {

        var newPoint = CGPoint(x: self.bounds.size.width * anchorPoint.x, y: self.bounds.size.height * anchorPoint.y)
        var oldPoint = CGPoint(x: self.bounds.size.width * self.layer.anchorPoint.x, y: self.bounds.size.height * self.layer.anchorPoint.y)

        newPoint = newPoint.applying(self.transform)
        oldPoint = oldPoint.applying(self.transform)

        var position : CGPoint = self.layer.position

        position.x -= oldPoint.x
        position.x += newPoint.x;

        position.y -= oldPoint.y;
        position.y += newPoint.y;

        self.layer.position = position;
        self.layer.anchorPoint = anchorPoint;
    }
}
</code>
Answer: For transformations, Core Animation calculates the shortest path to achieve the rotation. For a 360 degree rotation, the shortest path is to do nothing. There is a workaround here that explains how to perform essentially the same animation.
Comment: You need to provide the answer here, not the link to a possible answer.


Javadoc creation with maven

Question: We have created a new artifact to generate javadoc. We have 40 artifacts defined as dependencies. Task is to create javadoc.jar and html pages for the 40 dependency artifacts.
Whats the best approach to achieve this in maven?
Answer: This is very unusual. Javadoc works on sources, not compiled classes, whereas maven dependencies reference classes, not sources.
So to make this work you'll have to do all of this:

since this is a dedicated javadoc artifact, it won't have a main JAR artifact, so you'll probably want to set the packaging to POM
make sure all your referenced artifacts have attached sources
add <classifier>sources</classifier> to all your dependencies
unpack all dependencies to a common root folder using dependency:unpack-dependencies
run javadoc on that folder
create a jar using the maven-assembly-plugin
attach that jar to the build using the buildhelper plugin

On re-reading the question: I'm assuming that you want to create combined docs of all dependencies. If not, you'll need 40 separate executions each of the javadoc, assembly and buildhelper plugins. Good luck with that.
Answer: A slightly more automated approach than the answer above:
So to make this work you'll have to do all of this:

since this is a dedicated javadoc artifact, it won't have a main JAR artifact, so you'll probably want to set the packaging to POM
make sure all your referenced artifacts have attached sources
add <classifier>sources</classifier> to all your dependencies
unpack all dependencies to a common root folder using dependency:unpack-dependencies
Change your sources directory to where you unpacked all the dependencies
Use the source plugin to manage all the Javadoc generation and deployment

Javadoc creation with maven


inheritance of set class attribute in python

Question: I'm trying to create basic abstract class with mechanism for saving of set of all created instances.
class Basic(object):
    __metaclass__ = ABCMeta
    allInstances = set()

    def __init__(self, name):
        self.allInstances.add(self)

    def __del__(self):
        self.allInstances.remove(self)

The problem is that set allInstances saves instances of all child classes. Should I add this lines for every child class separately or there is way to create sets for every child class in basic class?
Comment: If you want to have a separate class attribute for each sub-class, that should be part of the metaclass (which can inherit from `ABCMeta`).
Comment: I like Marty Alchin's [plugin pattern](http://martyalchin.com/2008/jan/10/simple-plugin-framework/) for things like this.
Comment: Interesting thing, when I add integer class variable into my class `Basic`(the same way as `allInstances` - it creates separately for every child class. How it can be explained?
Comment: Note that `__del__` isn't guaranteed to always be called. This is especially true in python<3.4. Basically any cycle of objects with that method will be deallocated without calling it.
Answer: thnx jonrsharpe, after reading Your comment, some docs and articles, MyMeta class:
from abc import ABCMeta

class MyMeta(ABCMeta):
    def __init__(cls, name, bases, dct):
        super(MyMeta, cls).__init__(name, bases, dct)
        cls.allInstances = set()

parent class
from MyMeta import MyMeta

class Basic(object):
    __metaclass__ = MyMeta

    def __init__(self):
        self.allInstances.add(self)

    def __del__(self):
        self.allInstances.remove(self)

Another way
from abc import ABCMeta, abstractmethod

class Basic(object):
    __metaclass__ = ABCMeta

    allInstances = None

    def __init__(self):
        if self.__class__.allInstances is None:
            self.__class__.allInstances = set()
        self.__class__.allInstances.add(self)

    def __del__(self):
        self.__class__.allInstances.remove(self)


How do I set up PayPal parallel payments in Drupal 7 Commerce Express Checkout module?

Question: After an exhaustive online search, I can't find an answer to my problem: where do I place the code snippets PayPal provides to implement PayPal parallel payments in Drupal 7's Express Checkout module? I went to this site to find the code snippets to paste into my site's code, but unfortunately, I can't figure out what file to paste the code snippets into in the Express Checkout module. I've read all of the instructions on PayPal, and being a relative beginner at Drupal (and a total beginner at PayPal), I can't figure out what to do next.
I am trying to allow users of my website to buy downloadable files provided by other users. When they do so, I want to take a small commission for posting their materials on my site. I understand that chained payments is also an option people use for this type of scenario, but considering my inexperience with PayPal, I think that parallel payments is the better of the two options.
In case it matters, I'm working in PayPal's sandbox mode. I've downloaded the paypalplatform.php file and I think I'm supposed to upload this to the main Express Checkout folder (but I'm not sure?), and I understand how to get my sandbox API credentials from PayPal, but I'm pretty much clueless from that point on.
The two specific snippets I'm having trouble with are these:
1.) The one in step 3a, where the instructions say "Insert this code snippet into the section of your code that initiates the preapproval flow on your website." What code initiates the preapproval flow?  Is it contained in a file in the Express Checkout folder somewhere? In which file is it located, and specifically, where in the code should I paste the snippet provided by PayPal?
2.) The snippet provided in step 4c, where the instructions say "Insert this code snippet into the section of your code that initiates a PARALLEL PAYMENT on your website." Again, where is this code located?  Is it in a file in the Express Checkout folder? In which file is it located, and specifically, where in the code should I paste the snippet?
Any help anyone can give me would be much appreciated. Thank you.
Answer: The short answer is that there isn't just a place to "paste the snippet." That integration wizard is hopelessly simplistic. Support for a new payment method within Drupal Commerce would require more than simply adding code to a page, because presumably you'll want some sort of local record of any payment action taking place. For that to happen, you have to work with the Drupal / Drupal Commerce APIs as well.
In Drupal Commerce, these integrations are handled through payment method modules. We have documentation for writing them in the developer guide on DrupalCommerce.org. Additionally, if you're PayPal Express Checkout, you should switch to using the 2.x branch of the main PayPal project, http://drupal.org/project/commerce_paypal, as it has a complete implementation of the Express Checkout payment method and has been verified by PayPal.
Comment: Thanks for the quick response, Ryan! I'll take another look at the developer guide and switch back to using the main PayPal project. I'll let you know if I run into any issues.
Comment: thanks for this  sorry for my english  well i want  PayPal parallel payments  in dynamic way  i use token on receiver filed   but its not working  (token is from store entity filed ie paypal id ) well give me suggestion for that


Finding critical points of a function that is bounded by a condition

Question: I got stuck trying to solve a critical points calculation problem of the following function :
f(x,y)=3x−y
Thing is, I calculated the partial derivatives and came up with no results for any critical points.
The function is bounded by the following term:
x^2+2y^2=38
which I immediately assumed was the equation of an ellipse, and tried to bound the 'x' and the 'y' in the original function by the ellipse's 'a' and 'b' values.
I think I got utterly lost in the process of solving this problem, help would be much appreciated
Comment: Did you try Lagrange Multiplier method?
Comment: This problem was given in a Calculus university course, we haven't learned about that method yet
Answer: $f(x,y) = 3x-y$
Given constraint is $x = \sqrt{38 - 2y^2}$
$f(x,y) = 3\sqrt{38 - 2y^2} - y$
Now at critical points, $ \, \, \frac{-6y}{\sqrt{38-2y^2}} - 1 = 0$ (taking derivative and equating to zero)
So $y = \pm1$ and now you can find values of $x$ from the constraint and complete the solution.


JavaFX MediaPlayer "Error: 80de0001 in CallbackToJava..."

Question: I am making a media player which allows users to drag and drop media thumbnails onto a media player (using JavaFX MediaPlayer).
When I run it and try the drag/drop functionality, some of the time it works just as expected. However sometimes it produces a weird error.
The error in its fullness is:
Error:80de0001 in CallbackToJava(javaIDs.View.notifyDragDrop, grfKeyState, pt, pdwEffect)
COM Error:80de0001 Unknown Error 0x80DE0001
Error:80de0001  in :: DoDragDrop( pcd, IDropSourcePtr(new GlassDropSource(obj), getDROPEFFECT(supportedActions, &performedDropEffect)
COM Error:80de0001  Unknown error 0x80DE0001

The print-out in Eclipse looks like: (all double-spaced)

I really have no idea why this is happening - I'm clearly doing something wrong. The error doesn't point me to any line of code. I would suggest that the error is referring to a memory address? Are you able to help me, please?
The listeners/handlers which perform the Drag/Drop functionality are:
    root.setOnMouseEntered(new EventHandler<MouseEvent>(){
        @Override
        public void handle(MouseEvent arg0) {
            root.setStyle(highlightBackgroundStyle);
            parentScene.setCursor(Cursor.OPEN_HAND);
        }

    });

    root.setOnMouseExited(new EventHandler<MouseEvent>(){
        @Override
        public void handle(MouseEvent arg0) {
            root.setStyle(backgroundStyle);
            //parentScene.setCursor(Cursor.DEFAULT);
        }

    });

    root.setOnDragDetected(new EventHandler<MouseEvent>(){
        @Override
        public void handle(MouseEvent arg0) {
            parentScene.setCursor(Cursor.CLOSED_HAND);
            Dragboard db = parentScene.startDragAndDrop(TransferMode.COPY);

             ClipboardContent content = new ClipboardContent();
             content.putString(mediaFile.toURI().toString());
             db.setContent(content);
             arg0.consume();
        }

    });

    mediaPanel.getDropZoneA().setOnDragDropped(new EventHandler<DragEvent>(){

        @Override
        public void handle(DragEvent arg0) {
            mediaPanel.getMixerA().dragGraphicsOff();

            Dragboard db = arg0.getDragboard();
            if (db.hasString())
            {
                //System.out.println(db.getString());
                String mediaURI = db.getString();
                System.out.println(mediaURI);
                mediaPanel.getMixerA().getJfxMediaPlayer().loadAndPlayMediaA(new Media(mediaURI));
                mediaPanel.getMixerA().prepareMedia();

                arg0.setDropCompleted(true);
            }else{System.out.println("Drag error");arg0.setDropCompleted(false);}

            arg0.consume();
        }

    });

    mediaPanel.getDropZoneA().setOnDragExited(new EventHandler<DragEvent>(){

        @Override
        public void handle(DragEvent arg0) {
            mediaPanel.getMixerA().dragGraphicsOff();
            arg0.consume();
        }

    });

    mediaPanel.getDropZoneA().setOnDragOver(new EventHandler <DragEvent>() {
        public void handle(DragEvent arg0) {
            mediaPanel.getMixerA().dragGraphicsOn();

            if (arg0.getGestureSource() != mediaPanel.getDropZoneB() && arg0.getDragboard().hasString())
            {
                arg0.acceptTransferModes(TransferMode.COPY);
            }
            arg0.consume();
        }
    });

Update 1
I am wondering whether this is caused by the way I 'change' the media for the MediaPlayer. I do the following:
public void loadAndPlayMediaA(Media playableMedia)
{
    if((player != null))
    {
        player.stop();
    }
    media = playableMedia;
    player = new MediaPlayer(media);

    player.play();
}

I then immediately call:
public void prepareMedia()
{

    view.setMediaPlayer(jfxMediaPlayer.getMediaPlayer());
    view.setPreserveRatio(preserveRatio);
    view.setFitWidth(miniaturePlayerX);
    view.setFitHeight(miniaturePlayerY);
    playerSlider.setValue(0.0);

}

...The key line being player = new MediaPlayer(media);. I wonder whether occasionally I am hitting the split second where the MediaView is trying to get the next frame, but failing because the media has been re instantiated. (?)
What's the best way to load up a new video?
Answer: I don't know if you haven't found a solution yet...
I had the same problem and solved it by following code:
setOnDragDropped(new EventHandler<DragEvent>()
            {
                @Override
                public void handle(DragEvent event)
                {
                    System.out.println("onDragDropped");
                    event.setDropCompleted(true);
                }
            });

setOnDragExited(new EventHandler<DragEvent>()
            {
                @Override
                public void handle(DragEvent event)
                {
                    System.out.println("onDragExited");
                    Dragboard db = event.getDragboard();
                    ArrayList<Object> f = (ArrayList<Object>) db.getContent(DataFormat.FILES);
                    for(Object o:f)
                        System.out.println(o.getClass().getName() + ":" + o);
                    File file = (File) f.get(0);
                    newMedia(file.toURI());
                }
            });

setOnDragOver(new EventHandler<DragEvent>()
            {
                @Override
                public void handle(DragEvent event)
                {
                    System.out.println("onDragOver");
                    event.acceptTransferModes(TransferMode.ANY);
                }
            });

public void newMedia(URI uri)
{
    m = new Media(uri.toASCIIString());
    mp = new MediaPlayer(m);
    mV = new MediaView(mp);

    mp.setOnReady(new Runnable()
    {
        @Override
        public void run()
        {
            mp.play();
        }
    });
}

In the DragDropped handler I call setDropCompleted to call the DragExited handler. Then I get the File out of the Dragboard and create a new MediaPlayerInstance. And then, you aren't allowed to call play immideately, else nothing will happen. You need to call play in the OnReady Handler, or at least after the MediaPlayer's status has been changed to Ready.
The Error will still appear, but it should work now ;)


The Sub Gradient and the Proximal Operator of the of $ {L}_{2, 1} $ Norm (Mixed Norm)

Question: What would be the the Sub Gradient of
$$ f \left( X \right) = {\left\| A X \right\|}_{2, 1} $$
Where $ X \in \mathbb{R}^{m \times n} $, $ {A} \in \mathbb{R}^{k \times m} $ and $ {\left\| Y \right\|}_{2, 1} = \sum_{j} \sqrt{ \sum_{i} {Y}_{i,j}^{2} } $.
What would be the Prox of:
$$ \operatorname{Prox}_{\lambda {\left\| \cdot \right\|}_{2,1}} \left( Y \right) = \arg \min_{X} \frac{1}{2} {\left\| X - Y \right\|}_{F}^{2}  + \lambda {\left\| X \right\|}_{2, 1}, \; X, Y \in {\mathbb{R}}^{m \times n} $$
Can either be generalized for $ {\left\| \cdot \right\|}_{q, p} $?
Comment: $f$ is not differentiable. The $\ell_{2,1}$-norm is a separable sum, so it follows from the separable sum rule that evaluating the prox-operator of the $\ell_{2,1}$-norm reduces to evaluating the prox-operator of the 2-norm.
Comment: You're right. I was not accurate with this. Edited for the Sub Gradient. I meant something similar to https://math.stackexchange.com/questions/2035198.
Comment: There's a separable sum rule for subgradients and also a separable sum rule for prox-operators. Because the $\ell_{2,1}$-norm is a separable sum, we can use these separable sum rules to reduce these calculations to the corresponding calculations for the 2-norm.
Comment: This is what I thought about (Decompose $ X $ into its columns). I thought someone will come with more elegant and simple way.
Answer: In the following I will use MATLAB's notation using the <code>:</code> operator for selecting a column of a Matrix.
Sub Gradient of $ {L}_{2, 1} $ Mixed Norm
$$ f \left( X \right) = {\left\| A X \right\|}_{2, 1} = \sum_{i} {\left\| A {X}_{:, i} \right\|}_{2} $$
Now, for a vector $ x $ the gradient:
$$ \frac{\mathrm{d} {\left\| A x \right\|}_{2} }{\mathrm{d} x} = \frac{ {A}^{T} A x }{ {\left\| A x \right\|}_{2} } $$
Which implies:
$$\begin{align*}
\frac{\mathrm{d} {\left\| A X \right\|}_{2, 1} }{\mathrm{d} X} & = \frac{\mathrm{d} \sum_{i} {\left\| A {X}_{:, i} \right\|}_{2} }{\mathrm{d} X} && \text{} \\
& = \frac{\mathrm{d} \sum_{i} {\left\| A {X}_{:, i} \right\|}_{2} }{\mathrm{d} {X}_{:, i}} \boldsymbol{e}_{i}^{T} && \text{Where $ \boldsymbol{e}_{i} $ is the standard $ i $ -th basis vector} \\
& = \sum_{i} \frac{\mathrm{d} {\left\| A {X}_{:, i} \right\|}_{2} }{\mathrm{d} {X}_{:, i}} \boldsymbol{e}_{i}^{T} && \text{} \\
& = \sum_{i} \frac{ {A}^{T} A {X}_{:, i} }{ {\left\| A {X}_{:, i} \right\|}_{2} } \boldsymbol{e}_{i}^{T} && \text{} \\
& = {A}^{T} A X D
\end{align*}$$
Where
$$ D = \operatorname{diag} \left\{ {d}_{1}, {d}_{2}, \ldots, {d}_{n} \right\}, \; {d}_{i} = \begin{cases}
0 & \text{ if } {\left\| A {X}_{:, i} \right\|}_{2} = 0 \\
\frac{1}{{\left\| A {X}_{:, i} \right\|}_{2}} & \text{ if } {\left\| A {X}_{:, i} \right\|}_{2} \neq 0
\end{cases} $$
Remark
For a column of zero sin $ X $ the Sub Gradient of the $ {L}_{2} $ norm of that vector is any vector with $ {L}_{2} $ norm which less or equal to unit. In the case above it was chosen to be the zero vector which indeed has a norm less than 1.
Prox of $ {L}_{2, 1} $ Mixed Norm
The problem is given by:
$$ \arg \min_{X} \frac{1}{2} {\left\| X - Y \right\|}_{F}^{2} + \lambda {\left\| X \right\|}_{2, 1} $$
Where $ X, Y \in \mathbb{R}^{m \times n} $.
Again, this can be decomposed into working on each column of $ X $ separately:
$$\begin{aligned}
\arg \min_{X} \frac{1}{2} {\left\| X - Y \right\|}_{F}^{2} + \lambda {\left\| X \right\|}_{2, 1} & = \arg \min_{X} \sum_{i} \frac{1}{2} {\left\| {X}_{:, i} - {Y}_{:, i} \right\|}_{2}^{2} + \sum_{i} \lambda {\left\| {X}_{:, i} \right\|}_{2}^{2} && \text{} \\
& = \arg \min_{X} \left( \frac{1}{2} {\left\| {X}_{:, 1} - {Y}_{:, 1} \right\|}_{2}^{2} + \lambda {\left\| {X}_{:, 1} \right\|}_{2}^{2} \right) && \\
& + \left( \frac{1}{2} {\left\| {X}_{:, 2} - {Y}_{:, 2} \right\|}_{2}^{2} + \lambda {\left\| {X}_{:, 2} \right\|}_{2}^{2} \right) && \\
& + \cdots && \\
& + \left( \frac{1}{2} {\left\| {X}_{:, n} - {Y}_{:, n} \right\|}_{2}^{2} + \lambda {\left\| {X}_{:, n} \right\|}_{2}^{2} \right)
\end{aligned}$$
Each term in the brackets is independent Prox Function of $ {L}_{2} $ Norm.
Hence the solution is given by:
$$ \hat{X} = \arg \min_{X} \frac{1}{2} {\left\| X - Y \right\|}_{F}^{2} + \lambda {\left\| X \right\|}_{2, 1} $$
Where $ \hat{X}_{:, i} = {Y}_{:, i} \left( 1 - \frac{\lambda}{\max \left( {\left\| {Y}_{:, i} \right\|}_{2} , \lambda \right)} \right) $
MATLAB Code
I implemented a code to verify the results versus Numerical Derivative (Finite Differences) and CVX (Reference for the Prox).
The full code is in my StackExchange Mathematics Q3307741 GitHub Repository.
Answer: Let $x_j$ be the $j$th column of $X$. (So $\|X\|_{2,1} = \sum_{j=1}^n \| x_j \|_2$.) Then the separable sum rule for proximal operators tells us that $\text{prox}_{\lambda\| \cdot \|_{2,1}}(X)$ is the $m \times n$ matrix whose $j$th column is $\text{prox}_{\lambda\| \cdot \|_2}(x_j)$.


How to Get Sum of One Column Based On Other Table in Sql Server

Question: I have 2 table in my database (like this):
tblCustomers:

id    CustomerName
1     aaa
2     bbb
3     ccc
4     ddd
5     eee
6     fff

tblPurchases:

id    CustomerID    Price
1     1             300
2     2             100
3     3             500
4     1             150
5     4             50
6     3             250
7     6             700
8     2             30
9     1             310
10    4             25

Now I want with "Stored Procedures" take a new table that give me the sum of price for each customer. Exactly like under.
How can do that?
Procedures Result:

id    CustomerName    SumPrice
1     aaa             760
2     bbb             130
3     ccc             750
4     ddd             75
5     eee             0
6     fff             700

Answer: select c.id, c.customername, sum(isnull(p.price, 0)) as sumprice
  from tblcustomers c
  left join tblpurchases p
    on c.id = p.customerid
 group by c.id, c.customername

SQL Fiddle test: http://sqlfiddle.com/#!3/9b573/1/0
Note the need for an outer join because your desired result includes customers with no purchases.
Answer: You can use the below query to get the result
   select id,CustomerName,sum(price) as TotalPrice
    from
    (
    select tc.id,tc.CustomerName,tp.price
    from tblCustomers tc
    join
    tblPurchases tp on tc.id = tp.CustomerID
    ) tab
    group by id,CustomerName

Comment: Why the sub-query?  It doesn't appear to be needed at all.
Answer: Although the other answers here do work, they don't appear to be what I would consider standard practice, or optimal.
The simplest solution (standard, but not always optimal) requires no sub-query of any variety.
SELECT
  cust.id,
  cust.CustomerName,
  SUM(prch.price)   AS SumPrice
FROM
  tblCustomers   AS cust
INNER JOIN
  tblPurchases   AS prch
    ON  cust.id = prch.CustomerID
GROUP BY
  cust.id,
  cust.CustomerName

The only reason that this is not necessarily optimal is that it involves grouping by two fields, one of which is a string.  This involves creating 'counters' in memory that are identified by this composite of an id and string, which can be inefficient due to the fact that you only really need to use the id to uniquely identify the counter.  (The identifier is only one item and is a small (probably only 4 bytes), rather than multiple items one of which is long (potentially many many bytes)).
This means that you can do the following as a possible optimisation.  Though depending on your data this many be a premature optimsation, it has no performance down-side and is always good to know about...
SELECT
  cust.id,
  cust.CustomerName,
  prch.SumPrice
FROM
  tblCustomers   AS cust
INNER JOIN
  (
  SELECT
    CustomerID,
    SUM(price) AS SumPrice
  FROM
    tblPurchases
  GROUP BY
    CustomerID
  )              AS prch
    ON  cust.id = prch.CustomerID

This makes the in-memory aggregation as simple as possible, as so as quick as possible.

In both cases you should have the best possible efficiency in the query by ensuring that you have indexes on tblCustomer(id) and on tblPurchases(CustomerID),
Answer: DECLARE @tblcustomers table  (id int, customername varchar(10));

insert into @tblcustomers values (1, 'aaa');
insert into @tblcustomers values (2, 'bbb');
insert into @tblcustomers values (3, 'ccc');
insert into @tblcustomers values (4, 'ddd');
insert into @tblcustomers values (5, 'eee');
insert into @tblcustomers values (6, 'fff');

DECLARE @tblpurchases table  (id int, customerid int, price int);

insert into @tblpurchases values (1, 1, 300);
insert into @tblpurchases values (2, 2, 100);
insert into @tblpurchases values (3, 3, 500);
insert into @tblpurchases values (4, 1, 150);
insert into @tblpurchases values (5, 4, 50);
insert into @tblpurchases values (6, 3, 250);
insert into @tblpurchases values (7, 6, 700);
insert into @tblpurchases values (8, 2, 30);
insert into @tblpurchases values (9, 1, 310);
insert into @tblpurchases values (10, 4, 25);

WITH CTE  AS(
select c.id,c.customername from @tblcustomers c
)
Select c.id,c.customername,(Select SUM(ISNULL(P.price,0)) from @tblpurchases P
WHERE P.customerid = C.id) AS Price  from  CTE c


Play framework localisation is not working in production

Question: If I run my play framework application with "play run" the localisation is fine. But if I do a "play dist" then use the start command, then the original English messages appear.
I have found, that if I change the classpath order in the start script putting the jar containing my messages file to the first place, then the localisation is fine.
Is there any better way to do this?
It is the same, if I copy the conf/messages to conf/messages.hu and set application.langs="hu" in the application.conf.
And stays the same, if I change my browser settings, so this is in the request header: "Accept-Language:hu,en-US;q=0.8,en;q=0.6". Still English messages (only, if they are the built in keys. My custom keys are translated correctly).
Answer: We have figured it out.
There is a custom field constructor used. My assumption was, that it is using the implicit lang parameter, but this is not the case. The lang must be given to the elements.errors() as parameter, and the current lang setting is stored in the elements.lang attribute. This is stated in the documentation, but we missed it. So the implicit lang parameter should not be used in the field template, because it contains wrong value.
The solution was this: @elements.errors(elements.lang)
    @elements.input
    @elements.errors(elements.lang).mkString(", ")


How to find non-existing terms based on the list?

Question: I've few thousands terms in my vocabulary. I'd like to find out which one still are missing (without adding them) based on the list of term names.
I believe this can be achieved by some anti-join sql query, but any solution would be fine.
How this can be achieved?
Comment: maybe this can help you: https://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.module/function/taxonomy_get_term_by_name/7. If you get an empty array you know the term doesn't exist yet...
Answer: If the list is in text file (list.txt), this can be achieved by grep comparision.
First, extract the list of terms from the database by drush:
$ drush sqlq "SELECT name FROM taxonomy_term_data -- WHERE vid = 1" > my_list.txt

Then compare the two lists:
$ grep -Fxv -f my_list.txt list.txt

This will print all the term names which doesn't exist in my_list.txt file.
This solution is based on: Is there a tool to get the lines in one file that are not in another?.


Independence of Transformed Bivariate Normal

Question: Let $\alpha$ and $\beta$ be jointly distributed by the bivariate normal distribution.
Let A and B be jointly distributed by the standard bivariate normal distribution, where
$A=\frac{\alpha-\mu_\alpha}{\sigma_\alpha}$ and $B=\frac{\beta-\mu_\beta}{\sigma_\beta}$
Is is sufficient to show that A+B and A-B are independent, given  $\sigma_A=\sigma_B$, in order to establish that $\alpha+\beta$ and $\alpha-\beta$ are independent if $\sigma_\alpha=\sigma_\beta$?
My intuition is that it should be sufficient as the transformation from A to $\alpha$ and B to $\beta$ are independent of each other. However, I can't find any rigorous proof / theory about this.
Comment: Is this question [self-study](https://stats.stackexchange.com/tags/self-study/info)? In any case, [this answer](https://stats.stackexchange.com/a/261381) may help.
Answer: If $\alpha$ and $\beta$ are independent random variables, then $A$ and $B$ are also independent (standard normal) random variables regardless of the values of the variances of $\alpha$ and $\beta$, and $A+B$ and $A-B$ are independent random variables too since $A$ and $B$ are independent standard normal random variables.  But, as you correctly observe, if $\alpha$ and $\beta$ are independent normal random variables, we cannot simply assert that $\alpha+\beta$ and $\alpha-\beta$ are independent random variables because
$$\operatorname{cov}(\alpha+\beta, \alpha-\beta) = \sigma_\alpha^2 - \sigma_\beta^2 \neq 0 ~~ \text{unless}~~
\sigma_\alpha = \sigma_\beta.$$


Glassfish not seeing my handler-chain.xml

Question: When setting up my first handler chain I followed many guides, but only some of them were specific where to put the handler-chain.xml. The spec said in the class path.
So I tried to put them in the same dir as my webservice or even my root but I keep getting:
handler file handler-chain.xml not found.
I'm using GlassFish 3.1.2
Answer: After just copying and pasting my handler-chain.xml around I found that it worked if I put the file into web pages/WEB-INF/classes
Comment: I had the same problem with Glassfish 4.1, this solved it. Thanks !


Clarification about completeness of metric spaces

Question: This is probably a very silly question but it bothers me for some time.
We define a metric space $X$ to be complete if every Cauchy sequence in $X$ converges to some point in $X$.
But any metric space $X$ is closed in itself, so every convergent sequence in $X$ has its limit in $X$. From that I would say that when we check if $X$ is complete, it suffices to check that any Cauchy sequence in $X$ converges because if it converges, then it will converge in $X$.
However...

consider for example the space of continuous functions on $[0,1]$,
  $C([0,1],\mathbb R)$ with $\|\cdot\|_1$. Take $(f_n)_{n\geq1}$ given
  by
$$f_n(x)=\begin{cases}
0,&0\leq x\leq\frac12\\
n\left(x-\frac12\right),&\frac 12<x\leq \frac 12+\frac1n\\
1,&\frac12+\frac1n<x\leq 1\;.
\end{cases}$$
This is continuous for
  each $n\geq 1$ and so in $C([a,b],\mathbb R)$.  We can show that it is
  a Cauchy sequence and that it converges in the $\|\cdot\|_1$ norm to
  $f$ defined by $f(x)=1$ when $x\in(1/2,1]$ and $f(x)=0$ otherwise.

If my reasoning above were correct, then we would stop now and say that $C([0,1],\mathbb R)$ is complete, which of course it isn't because the $f$ we found above is not continuous.
I think that the problem  has to do with the universe we are in. Because if we consider $C[0,1]$ as just a subset of $R[0,1]$ (where this is the set of Riemann integrable functions on $[0,1]$), then of course it is not closed in $R[0,1]$. But we are not doing that, we are just referring to $C[0,1]$, or more generally to the metric space $X$ and assume that $X$ is the "universe."
So what am I missing here?
Comment: The space in your example is $C([0,1],\Bbb R)$, and in that space your sequence does *not* converge: there is no $f\in C([0,1],\Bbb R)$ such that $\langle f_n:n\in\Bbb Z^+\rangle\to f$.
Comment: I don't disagree on the facts, but I do disagree on the terminology. If you are working n the space $C([0,1],\Bbb R)$, the sequence does not converge: the indicator function of $\left(\frac12,1\right]$ in $[0,1]$ effectively does not exist. If you are working in $R[0,1]$, it does converge, but not to a point of $C([0,1],\Bbb R)$, thereby showing that $C([0,1],\Bbb R)$ is neither complete as a subspace of $R[0,1]$ nor closed in $R[0,1]$. (And of course there is a theorem that says that these two observations are equivalent.)
Comment: As I see it, it does converge; it's just that its limit is not in $C[0,1]$. I think I see what my issue is. If our universe is $X$, then $x_n$ (if it converges) can only converge in $X$. So, in my example, we either think that our universe is $C[0,1]$ and say that there is no $f$ such that $f_n\to f$, or we say that the our universe is $R[0,1]$ and then there is $f$ such that $f_n\to f$ but $f\notin C[0,1]$. But in the latter case, there is no problem because $C[0,1]$ is not closed in $R[0,1]$. Is this right?
Answer: Brian's comments are spot on. Let me add a little (too long for a comment): Properties like "Cauchy" or "convergent" depend on the metric space you're living in. It doesn't make sense to say that the sequence $(3, 3.1, 3.14, . . . )$ converges or doesn't converge - you have to say what metric space you're in. In $\mathbb{R}$ with the usual metric, this does converge; in $\mathbb{Q}$ with the usual metric, it doesn't. And the sequence isn't even Cauchy in $\mathbb{R}$ with the discrete metric $d(x, y)=1$!
Usually, of course, we just say things like "$S$ is Cauchy" - but this is a quirk of natural language. Technically, we should say what space we're living in, but we don't when it's clear from context.
There is, however, a useful sense in which Cauchy-ness is "more absolute" than convergence: namely, if $S$ is a sequence in a metric space $M$, and $N$ is a larger metric space, then $S$ is Cauchy in $M$ iff $S$ is Cauchy in $N$. This is not true for convergence. In particular, Cauchy-ness depends only on the distances between the points in the sequence itself; convergence depends on the "rest" of the space.
There is a precise sense in which every Cauchy sequence in a metric space $M$ is convergent "somewhere" - namely, in the completion of $M$! But this shift in the underlying space is important.
Comment: People often confuse convergent sequence with Cauchy sequence . A convergent sequence in a space S is a Cauchy sequence in S with a limit point in S. But a Cauchy sequence in S  may fail to have a limit point in S.


Make a t chart for $f(x) = -3^x$

Question: I am bit confused. I don't know if it is my calculations but when $f(x)=-3^x$, I get $f(-2)=\frac19$.
That can't be right. What am I doing wrong?
Answer: I'm guessing that this is $-3^{x}=(-1)\cdot3^{x}$ not $(-3)^{x}$. So $f(-2)=-(3^{-2})$.
Answer: First, note that $a^{-b} = \frac{1}{a^b}$ for all $a,b$.
Next, there is a difference between $-3^x$ and $(-3)^x$ that you should be aware of. I will illustrate the difference for $x=-2$:
$$-3^x = -(3^x) = -(3^{-2}) = -\frac{1}{3^2} = \frac{-1}{9}$$
$$(-3)^x = (-3)^{-2} = \frac{1}{(-3)^2} = \frac{1}{9}$$
Hopefully this clears up your confusion regarding what must be wrong. Maybe you've calculated as if there were parentheses when in fact there are none, or vice versa.
Answer: For $f(x)=-(3)^x \Rightarrow f(-2)=-(3)^{-2}=-\frac{1}{3^{2}}=-\frac{1}{9}$.
For $f(x)=(-3)^x \Rightarrow f(-2)=(-3)^{-2}=\frac{1}{(-3)^2}=\frac{1}{9}$
Answer: It depends on which operation do you apply first (exponentiation or negation). For exponentiation $\to$ negation, you will get $-\frac{1}{9}$, and for negation $\to$ exponentiation, you will get $\frac{1}{9}$.

Make a t chart for $f(x) = -3^x$


Why does dependency injection not work when im using esbuild for building my Angular 17 project?

Question: I want to migrate from "@angular-devkit/build-angular:browser" to "@angular-devkit/build-angular:browser" to speed up development. But the problem i get is that every time i start my application the following error gets logged in my console:
NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with runInInjectionContext.
As described in the Angular docs, i simply changed "@angular-devkit/build-angular:browser" to "@angular-devkit/build-angular:browser-esbuild" in my angular.json file. While no errors get logged in my vs code terminal, i keep seeing this error in the console in the browser. I expected this to work, since the docs said that this would be the only change i needed to make
Comment: Please add a minimal reproducible code example of the code where the error is thrown. Also, I assume you are migrating from  `@angular-devkit/build-angular:browser` to `@angular-devkit/build-angular:application`? In your question it always says "browser".
Comment: Im migrating to browser-esbuild, my bad.

The error seems to appear when im registering an effect like this in app.module:
`EffectsModule.forRoot([AuthEffects])`

The effect class looks like this:
`@Injectable()
export class AuthEffects {
  constructor(private actions$: Actions, private authService: AuthService) {}

  login$ = createEffect(() =>
    this.actions$.pipe(
      ofType(fetchUser),
      mergeMap(() =>
        this.authService.fetchUser().pipe(
          map((user) => setUser({ user })),
          catchError((error) => of())
        )
      )
    )
  );
}`
Answer: i assume that you run Inject() function outside the class.
so that can cause the error.
In practice the inject() calls are allowed in a constructor, a constructor parameter and a field initializer.
Here is the example
@Injectable({providedIn: 'root'})
export class Car {
  radio: Radio|undefined;

  // OK: field initializer
  spareTyre = inject(Tyre);

  constructor() {
    // OK: constructor body
    this.radio = inject(Radio);
  }
}

Or you can visit the angular documentation to fix the error
https://angular.io/errors/NG0203
And let me know
Comment: The error occurs because of an ngrx effect class, which annotated with @Injectable(). Which i then register with `EffectsModule.forRoot([AuthEffects])` in my app.module
Comment: is that solve the problem?? i hope so
in your comment above, i suggest you to use EMPTY instead of of() in cacthError stream.
catchError(() => EMPTY)
it's more Idiomatic and its about personal preference and code style.
Comment: It doesn't solve the problem, it seems to cause the problem.


Determining the distance of Poisson-distributed stars in $\mathbb{R}^3$.

Question: I want to solve the following exercise:

Suppose the distribution of the star in space is a
  Poisson-distribution, i.e. the probability that there are $n$ stars in
  a region $T\in\mathbb{R}^{3}$ is $e^{-\lambda}\frac{\lambda^{n}}{n!}$,
  where $\lambda$ is proportional to the volume of $T$. We choose
  randomly a point $x\in\mathbb{R}^{3}$. Let $X$ be the distance of $x$
  to the next star. Then calculate the probability distribution function
  of $X$, i.e. calculate $P\left(s\leq X\leq t\right)$.

My questions are:
1) Is this problem even well-defined ?
Saying that stars in some region
$T\in\mathbb{R}^{3}$ are Poisson-distributed (shortly: "P-distr.")
confuses me, since $T$ is not fixed, so actually I have for every
possible volume a different P-distr.. Thus, if the next star is for
example within distance $A$ of $x$ I can have many differently shaped
$T$'s with different volumes that contain $x$ at the " center"
(whatever that is) and that star, so I have different P-distributions
that measure my distance (Intuitively suppose I should take balls
around $x$, but this explanation is not rigorous).
Conclusion: Not having a "fixed unit" $T$ with which to
measure distance, makes this problem not well-defined?
2) What is the image of $X$ ? Heck, what is even our probability
space ?
Possible (but very unsure) explanation: Since we dealt only with discrete
(countable) probability models so far, I assume that we somehow have
to approximate $\mathbb{R}^{3}$ by $\mathbb{Q}^{3}$ or $\mathbb{Z}^{3}$
(which are still countable...) and take that as our probability model
$\Omega$ (I think that by symmetry we could assume $x$ to be the
origin) and take our $X:\mathbb{Q}^{3}\rightarrow\mathbb{R}$ as mapping
$\left(x,y,z\right)\mapsto\sqrt{x^{2}+y^{2}+z^{2}}$. This explanation
would at least coincide with the fact that this exercise asks only
for $P\left(s\leq X\leq t\right)$ instead of precisely $P\left(X=q\right)$
(although the wording " distribution" would rather mean the
latter, I think...), since if have approximated the exact location
of the star by a rational number, to make the theory work. But this
seems also sketchy to me, since I don't know how to approximate the
error (what should $s,t$ be ?)
(Or, a different line of thought; we accept only rational numbers
as distances; but what would $\Omega$ the be ?)
Comment: I believe this problem is discussed in Tuckwell's "[Elementary Applications of Probability Theory](http://www.amazon.com/Elementary-Applications-Probability-Edition-Statistical/dp/0412576201)", section 3.6.
Comment: You are probably expected to exploit the relationship between the Poisson distribution and the exponential distribution. It is usually expressed in terms of time. If the number of events in unit time is Poisson mean $\lambda$, then interarrival times are exponential mean $1/\lambda$. In our case, volume plays the role of time. So you can find an expression for the probability that asphere of certain volume about $x$ is empty, and turn this into information about distance.
Answer:
1) Yes. $\ \ $ 2) $\mathbb R_+$.

A possible choice of probability space $(\Omega,\mathcal F)$ is as follows:

each $\omega$ in $\Omega$ is a locally finite subset of $\mathbb R^3$,
$\mathcal F$ is the smallest sigma-algebra such that counting functions of Borel subsets are measurable.

In other words, one asks that $[N_B=k]$ is in $\mathcal F$, for every Borel subset $B$ of $\mathbb R^3$ and every integer $k$, where $N_B(\omega)=\#(\omega\cap B)$.
Then $X:(\Omega,\mathcal F)\to(\mathbb R_+,\mathcal B(\mathbb R_+))$ is a random variable since $[X\gt r]=[N_{B(r)}=0]$ where, for every real number $r\gt0$, $B(r)$ is the ball in $\mathbb R^3$ with radius $r$ and centre $x$.
And $\mathrm P(N_{B(r)}=0)$ is not difficult to compute since one knows the distribution of $N_{B(r)}$.
Answer: 1) Yes, it's well defined. You should see it if your are familiar with analogous Poisson  process in the real line. In that case, you have a point process with "intensity" $\alpha$, so that if you take a very small interval $dx$ the probability that an event occurs in that interval is $p = \alpha \; dx$, and the events ocurrences in different intervals are independent. Hence, letting $dx \to 0$ you get that the number of events in any interval of length $L$ (actually, in any measurable subset of $\mathbb{R}$) is a Poisson variable with expected value $\lambda = \alpha L$. The same happens here, in $\mathbb{R}^3$.
2) You must pick a point at random in $\mathbb{R}^3$ and measure the distance to the nearest event ("star"). $X$ takes values in $(0,+\infty)$, and it's not difficult to compute, considering that $P(X \ge x)$ is just the probability that a ball of radius $x$ has zero events.


Cannot connect to Openstack Instance via horizon, but SSH works?

Question: I've got an OpenStack deployment running inside a VM for testing purposes. My setup is as follows: Host Ubuntu x64 with Virtualbox -> Guest Ubuntu x64 with OpenStack -> Ubuntu X64 Server Test Instances through Openstack.
I realize it is of no practical use, but as said, it is for testing purposes only. I successfully launched an instance, binding it to 184.108.40.206 and 172.16.1.1 (host is 172.16.0.1) and I can successfully ssh into it from either the host or the guest VM with ssh -i key.pem email@example.com (or 172.16.1.1). Unfortunately, the NoVNC via Horizon does not work (Starting VNC handshake -> Failed to connect).
The relevant lines from my nova.conf are the following:
--novnc_enabled=true
--novncproxy_base_url=http://172.16.0.1:6080/vnc_auto.html
--vncserver_proxyclient_address=172.16.0.1
--vncserver_listen=172.16.0.1

So I'm not sure what's going wrong. The keypair that matches the .pem file I ssh with is of course coupled with the instance, and the instance is Active and Running.
Any help would be greatly appreciated.
Edit: nova get-vnc-console [id] novnc correctly supplies me with a link to vnc into the vm, but it also fails to connect.
Edit 2: To clarify: I have an active, running instance that successfully launched through the OpenStack dashboard. I can ping the instance, I can ssh into it (using 'ssh -i key.pem ip), but I cannot access it through VNC (specifically novnc on the dashboard). Trying to access the VM through the URL nova supplies through get-vnc-console does not work either. What I wish to do is access this instance via VNC.
Comment: So is your question about VNC on openstack or VMz not being reachable.
Comment: Sorry if it was a little unclear: I added clarification as to what I meant. I wish to access the instance via VNC, but cannot as of right now.
Answer: I think your URL reference should be your public IP.

novncproxy_base_url=http://:6080/vnc_auto.html
xvpvncproxy_base_url=http://:6081/console

Try that.
Comment: Could you elaborate on that slightly? In my nova.conf above, I have: `--novncproxy_base_url=http://172.16.0.1:6080/vnc_auto.html`, with 172.16.0.1 being the VM's (= the system running Openstack services) public IP address as far as it is concerned. Am I missing something?
Answer: Put --vncserver_listen=0.0.0.0 instated of --vncserver_listen=172.16.0.1 in your configuration. Restart relevant services then try to access the instance via VNC.
It should work.
Answer: Try this on the compute node you want to access from NoVNC
iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 5900:5950 -j ACCEPT
iptables -D INPUT -j REJECT --reject-with icmp-host-prohibited

If this is the right solution save it
iptables-save

Hope you can find the solution.
Regards Gerardo


New to electric guitar, need help with amp settings

Question: I am new to electric guitar, though I've played acoustic.
I have the Zar E20R amplifier and I am struggling to get certain styles I want. I'm attempting to get a distorted rock sound.
Any tips?
Comment: I see your problem straight away - it only goes up to 10… Cue compulsory [Spinal Tap link](https://www.youtube.com/watch?v=KOO5S4vxi0o)
Comment: More seriously, what have you tried & where have you failed? Basically "rock" is anywhere from everything on 7 to everything on 10.
Answer: Hopefully you are not playing with all the EQ knobs on 0! Most active EQs act as a cut or boost depending on if they are high or low, and so you'll want to start them all on 5 for a flatter EQ response until you know you need something different.
For distorted rock sound, try turning on the overdrive channel, and turn the volume up to somewhere between 1-3, then play with the gain knob (push it high, 6-10 maybe). Keeping the volume low while increasing the gain should help you hear whereabouts the gain (distortion/clipping) behaves how you want it to. Then you can adjust the volume to suit how loud you want to be playing.
Frequently there's reverb in there as well, so after dialing in the distortion, try fiddling with the reverb knob and see how that affects the sound.
Frequently when I'm playing heavy rock/metal stuff, I cut the mids a bit and boost the bass a little bit.... and depending on the amp, possibly cut or boost the high frequency. After getting everything else dialed in, try lowering the mid to 4 or 3, move the bass up to 6 or more, and fiddle with the treble. Don't forget to also fiddle with the tone knob on the guitar if you have one; that controls how much of the high frequency signal from the guitar makes it to the amp.
I play on 6 different amps regularly, and I've got 17 guitars. I have built pedals and redesigned the guts of an amp or two. I can tell you that there's a lot of "moving parts" between an electric guitar and the amp it's plugged in to, so a lot of it boils down to the setup.
Some things to consider:
The pickups and electronics in the guitar are what shapes the analog signal that the amp gets, so it all starts there.
The amp itself might have some quirks or tendencies, so what works on another amp may not be quite right on your own.
Your best bet might be to try and find a nice middle ground on your amp, and see what happens when you play with one knob at a time, until you get a feel for how each knob affects the sound, with your setup.
Rock on!


$L: \text{Aff}\left ( \mathbb{R}^n ,\mathbb{R}^n \right ) \to M(n,\mathbb{R})$ is a map of rings?

Question: First of all, $\text{Aff}\left ( \mathbb{R}^n ,\mathbb{R}^n \right )$ is a set of affine maps $\mathbb{R}^n \to \mathbb{R}^n$. And, $M(n,\mathbb{R})$ is a set of all $n \times n$ matrices over $\mathbb{R}$.
Let $L_f$ be a linear map that corresponds to $f \in \text{Aff}\left ( \mathbb{R}^n ,\mathbb{R}^n \right )$, which is defined by $L_f(x)=f(x)-f(0)$.
I have to show that $L: \text{Aff}\left ( \mathbb{R}^n ,\mathbb{R}^n \right ) \to M(n,\mathbb{R})$ is a map of rings.
So far, I've checked $\text{Aff}\left ( \mathbb{R}^n ,\mathbb{R}^n \right )$ is a ring under addition and composition.
Also, it was easy to check that $L_{f_1+f_2}(x)=(L_{f_1}+L_{f_2})(x)$, and the identity preserving axiom.
However, I'm stuck showing for the other axiom.
i.e.: $L_{f_1 \circ f_2}(x)=(f_1(x)-f_1(0)) \circ (f_2(x)-f_2(0))=^?(f_1 \circ f_2)(x)-(f_1 \circ f_2 )(0)$
How to show this? Should I just change all $\circ$'s on the RHS to matrix multiplication?
Any help would be appreciated a lot!
Answer: Actually, your $L$ sends an affine map to a linear map, to get a matrix you need to choose a basis, in this situation there is the standard one in $\mathbb{R}^n$.
So
$L_{f_1 \circ f_2}(x)=(f_1 \circ f_2)(x)-(f_1 \circ f_2 )(0)=$
$=f_1( f_2(x))-f_1(f_2 (0)).$
By definition of affine map, this is exactly the linear map associated to $f_1$ evaluated on the vector $ f_2(x)-f_2(0)$, which is exactly
$(f_1(x)-f_1(0)) \circ (f_2(x)-f_2(0))$.
Finally, the matrix associated to the composition of linear maps is the product matrix so you get the claim.
If you prefer, you also choose an origin, again there is a standard one, then $f_i(x)=A_ix+b_i$ for some matrix $A_i$ and some vector $b_i$ and the result follows by explicit computations.


Abrir calendário a partir de um link

Question: Vi muitas formas diferentes de fazer isso, mas nenhuma funciona
Preciso colocar um link no meu site, onde quando clicar, abrir a agendar para a pessoa salvar na agenda dela
assim como o tel: mailto:, vi algumas coisas como calendar: calshow:, mas nenhuma funciona
Tentei criar ics e fazer download, porem no android não funciona se não tiver algum programa terceiro para fazer handle do ics
Alguem ja passou por isso? Alguma dica?
Answer:

(function() {
  if (window.addtocalendar)
    if (typeof window.addtocalendar.start == "function") return;
  if (window.ifaddtocalendar == undefined) {
    window.ifaddtocalendar = 1;
    var d = document,
      s = d.createElement('script'),
      g = 'getElementsByTagName';
    s.type = 'text/javascript';
    s.charset = 'UTF-8';
    s.async = true;
    s.src = ('https:' == window.location.protocol ? 'https' : 'http') + '://addtocalendar.com/atc/1.5/atc.min.js';
    var h = d[g]('body')[0];
    h.appendChild(s);
  }
})();
<link href="http://addtocalendar.com/atc/1.5/atc-style-blue.css" rel="stylesheet" />

  <var class="atc_event">
    <var class="atc_date_start">2016-05-04 12:00:00</var>
    <var class="atc_date_end">2016-05-04 18:00:00</var>
    <var class="atc_timezone">Europe/London</var>
    <var class="atc_title">Star Wars Day Party</var>
    <var class="atc_description">May the force be with you</var>
    <var class="atc_location">Tatooine</var>
    <var class="atc_organizer">Luke Skywalker</var>
    <var class="atc_organizer_email">email@example.com</var>
  </var>

jsFiddle: http://jsfiddle.net/AddToCalendar/Df86Z/
Livraria: http://addtocalendar.com/
Comment: A ideia é muito boa. Porem pelo que eu testei por aqui ele deu a opção para o usuário adicionar no calendário mais conveniente. Dai se o usuário nao sabe o que ele tem, ele nao sabe o que fazer. Outro problema é que se no celular ele nao usa google calendar, ele não funciona. O bom mesmo seria se ao abrir o .ics (por exemplo) ele perguntasse aquele famoso "abrir como", ou algo assim sabe? porem ics não funciona no android
Comment: Ao abrir o .ics ele vai perguntar qual o calendário, que quer mas mesmo assim é necessário que o utilizador execute o ficheiro.. Podes simplesmente ver qual o tipo de aparelho a aceder ao site e a partir daí reencaminhas para o calendário predefinido do mesmo. Resposta editada.
Comment: Se tentar abrir o ICS no android, verá que ele aparecerá: "cannot open file"
Answer: Parece que achei a minha propria resposta. Infelizmente não sei se posso responde-la, mas se nao puder, peço aos moderadores que corrijam e me instruam para que eu possa entender melhor
Bem, no iOS temos o webcal, como disse anteriormente. Montando links assim:
Agendar

O iOS abre direitinho o evento
Para resolver esse problema, no shouldOverrideUrlLoading do meu webview, eu verifico se a URL possui o webcal, e abro um novo intent para o calendário, assim eu baixo o ICS e monto um calendário. Sei que existem maneiras melhores de dar o parse no ICS, mas segue o código que utilizei
De qualquer forma, agora tenho o mesmo HTML funcionando para ambos os dispositivos
// Verifica se começa com o protocolo de calendario (webcal para manter padrão com ios)
        if(url.startsWith("webcal")) {

            if (android.os.Build.VERSION.SDK_INT > 9) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }
            try {
                // Cria o link para o ICS
                URL urla = new URL(url.replace("webcal", "http"));

                // Coloca em buffer todo o texto
                BufferedReader in = new BufferedReader(new InputStreamReader(urla.openStream()));
                String str;

                // Inicia o calendario e percorre linha à linha
                Calendar cal = Calendar.getInstance();
                Intent intent = new Intent(Intent.ACTION_EDIT);
                intent.setType("vnd.android.cursor.item/event");
                while ((str = in.readLine()) != null) {
                    /*
                        Verificar de não ter espaços entre o :
                        Não usar Z no final do datetime
                     */

                    // Verifica data de inicio
                    if(str.contains("DTSTART:")) {
                        // Cria o formato da data e da o parse
                        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
                        Date date = format.parse(str.replace("DTSTART:", ""));

                        // Adiciona o parametro
                        intent.putExtra(CalendarContract.Events.DTSTART, (date.getTime()));
                    }

                    // Verifica data de fim
                    else if(str.contains("DTEND:")) {
                        // Cria o formato da data e da o parse
                        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
                        Date date = format.parse(str.replace("DTEND:", ""));

                        // Adiciona o parametro
                        intent.putExtra(CalendarContract.Events.DTEND, (date.getTime()));
                    }

                    // Verifica o titulo
                    else if(str.contains("SUMMARY:")) {
                        intent.putExtra(CalendarContract.Events.TITLE, str.replace("SUMMARY:", ""));
                    }

                    // Verifica o organizador
                    else if(str.contains("ORGANIZER:")) {
                        intent.putExtra(CalendarContract.Events.ORGANIZER, str.replace("ORGANIZER:", ""));
                    }

                    // Verifica o local
                    else if(str.contains("LOCATION:")) {
                        intent.putExtra(CalendarContract.Events.EVENT_LOCATION, str.replace("LOCATION:", ""));
                    }

                    // Verifica o descrição
                    else if(str.contains("DESCRIPTION:")) {
                        intent.putExtra(CalendarContract.Events.DESCRIPTION, str.replace("DESCRIPTION:", ""));
                    }
                }

                // Fecha a conexão
                in.close();

                // Inicia o intent do calendário
                startActivity(intent);

            } catch (MalformedURLException e) {
                Log.d("Log", "Erro: " + e);
            } catch (IOException e) {
                Log.d("Log", "Erro: " + e);
            } catch (ParseException e) {
                Log.d("Log", "Erro: " + e);
            } catch (Exception e) {
                Log.d("Log", "Erro: " + e);
            }

            return true;
        }

Abrir calendário a partir de um link


how can I use jquery autocomplete in drupal 7

Question: I want to use jquery autocomplete jquery plugin, I test below code but nothing happend, I check, the file added correctly and there is not js error.
function imodbdev_form_alter(&$form,$form_state,$form_id){
  if($form_id='movie_node_form'){
      drupal_add_library('system', 'drupal.autocomplete');
      drupal_add_js(drupal_get_path('module', 'imodbdev') . '/js/jquery.livequery.js', array('scope' => 'footer'));
      drupal_add_js(drupal_get_path('module', 'imodbdev') . '/js/imodbdev.js', array('scope' => 'footer'));
  }

}

and  js/imodbdev.js file
(function($) {
    Drupal.behaviors.imodbdev = {
        attach: function(context) {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#edit-title" ).autocomplete({
source: availableTags
});
        }
    }
})(jQuery);

I had install jquery update module and set jquery version to  1.8 .
where is the problem?
update
after sometimes I type in textfield to test , I saw TypeError: c.curCSS is not a function in firebug, I search this error in google and suggestion in upgrade jquery ui  to 1.9.3  but drupal not has version higher than 1.8.
Comment: Unrelated note: $form_state param should be &$form_state in the form alter function.
Comment: @rooby, not always !!! , we usually change the form, but if we need to change $form_sate pass it by ref. ;)
Comment: Always pass form_state by reference in drupal. That's best practice anyways.
Answer: Yes, jQuery UI is available in drupal core.
To include libraries like that you need to call the drupal_add_library() function to load the required js & css.
For exmaple:
drupal_add_library('system', 'drupal.autocomplete');

So where you are adding your javascript, add that first.
For example:
// Add the jQuery UI autocomplete library.
drupal_add_library('system', 'drupal.autocomplete');
// Load the custom js for this module.
drupal_add_js(drupal_get_path('module', 'MODULE_NAME') . '/js/SCRIPT_FILE.js');

The caps lock parts need to be changed to suit your module.
As for where you would put this, I can't say unless I know where you are putting your code. It could be in your theme or in a custom module.
If it is in your theme then the drupal_add_js() part would be drupal_add_js(drupal_get_path('theme', 'THEME_NAME') . '/js/SCRIPT_FILE.js');
I'm also assuming your scripts are in a js sub-directory.
You also need to make sure that any custom js you have is inside a drupal behavior (or $(document).ready() at the very least). Otherwise your javascript will run to early in the page load before the text field even is on the page, so it will do nothing.
It will be like this:
(function ($) {
  Drupal.behaviors.yourThemeAutocomplete = {
    attach: function (context, settings) {
      // Your code goes here.
    }
  };
})(jQuery);

For more info see https://drupal.org/node/756722#behaviors (the whole page is useful info)
Comment: my js file added correctly and exists and run ,let's test `drupal_add_library`
Comment: my js file and autocomplete.js file exist in script ( I check them in firebug) , but nothing happend when I type in '#edit-title' field . where is the problem?
Comment: Hard to say. If you have no errors in your firebug console, then does #edit-title actually exist on the page? - Oh actually, is that code you posted the entire js file you have written or is that code inside a drupal behavior or document ready?
Comment: I will update my question with code, tnx for your atention
Comment: In that case, if you don't have any js errors and #edit-title exists on the form I'm not sure off the top of my head.
Comment: yes, `edit-title` exists , after I type in text field , it return `TypeError: c.curCSS is not a function` error in firebug
Comment: Looks like https://drupal.org/node/1847900 might be of use to you. Seems they aren't going to fix it in favour of using the newer version of jQuery (via jquery_update still - need the dev version though) than 1.8 - Also if there's a chance you don't need it you could just remove jquery update and use the drupal core version.
Comment: tnx for your attention, I set jquery version to 1.7 and work.
Answer: Gleaned from above and a few different sources, this is what worked for me.

add jquery.autocomplete to your render array
add your data source to your render array
add your custom JS to your render array
code your custom JS
'#attached' => array(
  'library' => array(
    array('system', 'ui.autocomplete'), // 1. add JQUI autocomplete
  ),
  'js' => array(
    array(
      'data' => array(
        'MYMODULE_autocomplete_list' => $my_php_array, // 2. add data
      ),
      'type' => 'setting',
    ),
    drupal_get_path('module', 'MYMODULE') . '/js/autocomplete.js',
    // 3. add custom js
  ),
),

);

and in your MYMODULE/js/autocomplete.js as step 4:
(function ($) {
  Drupal.behaviors.myModuleAutocomplete = {
    attach: function (context, settings) {
      $("#ID-OF-INPUT-FIELD", context).autocomplete({
        source: Drupal.settings.MYMODULE_autocomplete_list
      });
    }
  };
})(jQuery);

Answer: It is because of jquery 1.8 used in drupal jquery, according to this issue  just need to set jquery to 1.7 and everything work correctly,