How to add a Custom Serializer to alter the Output of REST EXPORT

Question: To the Response/Output of REST EXPORT of a view, I want to add one extra row.
So I created a Custom Serializer in my module.
The path of the file is:
My_Module/src/Plugin/views/style/HindiCustomSerializer.php

Here I extended the Serializer Class from core/modules/rest/src/Plugin/views/style/Serializer.php
And I am trying to override the render() method in my custom serializer like this. I am copying the render() method from original Serializer and adding one extra line from my side.
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\rest\Plugin\views\style\Serializer;

/**
 * The style plugin for serialized output formats.
 *
 * Add and extra row to the output.
 *
 * @ingroup views_style_plugins
 *
 * @ViewsStyle(
 *   id = "hindi_custom_serializer",
 *   title = @Translation("Hindi Custom Serializer"),
 *   help = @Translation("Serializes views row data using the Serializer component."),
 *   display_types = {"data"}
 * )
 */
class HindiCustomSerializer extends Serializer implements CacheableDependencyInterface{

  public function render() {
    $rows = [];
    // If the Data Entity row plugin is used, this will be an array of entities
    // which will pass through Serializer to one of the registered Normalizers,
    // which will transform it to arrays/scalars. If the Data field row plugin
    // is used, $rows will not contain objects and will pass directly to the
    // Encoder.
    foreach ($this->view->result as $row_index => $row) {
      $this->view->row_index = $row_index;
      $rows[] = $this->view->rowPlugin->render($row);
    }

    $rows[] = "JUST ADDING AN EXTRA ROW!!";
    unset($this->view->row_index);
    // Get the content type configured in the display or fallback to the
    // default.
    if ((empty($this->view->live_preview))) {
      $content_type = $this->displayHandler->getContentType();
    }
    else {
      $content_type = !empty($this->options['formats']) ? reset($this->options['formats']) : 'json';
    }
    return $this->serializer->serialize($rows, $content_type, ['views_style_plugin' => $this]);
  }

}

The option to choose the custom serializer MyCustomSerializer should be visible in Format section of view settings.

But its not displaying. Is there any step I am missing? Do I need to add some extra information regarding the serializer in .info file or any such steps needed ?
PS: If I add this line directly to the original Serializer code, I see the extra row coming in the response.
$rows[] = "JUST ADDING AN EXTRA ROW!!";

But of course that's not the correct way.
Comment: For what I'm seeing in your question droves me  that you forgot to add the proper @ViewStyle annotation check the `\Drupal\rest\Plugin\views\style\Serializer` annotation
Comment: What are the possible issues ?
Comment: Sorry I wrote to fast and stroke the Enter key without adding my actual comment :). Also don't forget to clear caches
Comment: thanks for comment. I added the annotations and updated the question. Still not getting it displayed.
Comment: You put it in the wrong place. I've updated your question with the annotation placed properly on the class not the method. Please test it that way and more information if the problem persist since this is a common solution and should work in almost all cases.
Comment: Another thing your plugin path... never use caps on your module's names. Could you add your plugin namespace? Also check that your module is being installed and is invoked properly for instance: implement hook_views_post_render and check is loaded.
Comment: After adding namespace and annotations in the correct place, its working. Thank you very much. Please add answer so that I can mark it as accepted.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/103674/discussion-between-sandesh-yadav-and-d70rr3s).
Answer: The plugin was missing the proper annotation (added now in the question). Views plugins use Annotation Discovery.
Adding something like the following solved the problem:
/**
 * My custom serializer
 *
 * @ViewsStyle(
 *   id = "hindi_custom_serializer",
 *   title = @Translation("Hindi Custom Serializer"),
 *   help = @Translation("Serializes views row data using the Serializer component."),
 *   display_types = {"data"}
 * )
 */
class HindiCustomSerializer extends Serializer {
  ....
}

Also worth noting that you don't need to include the implements CacheableDependencyInterface since is already declared by the \Drupal\rest\Plugin\views\style\Serializer plugin which you are extending from.


Erro código PHP

Question: Boa noite! Desculpe, sei que deveria procurar aprender o PHP para sanar minhas dúvidas, mas creio que para resolver a duvida que tenho levaria muito tempo que nao tenho agora.
Estou descriptografando um código PHP e ele apresentou um erro na hora de executar.
Estou fazendo pelo Wamp e Usando um Virtual Host na máquina(Wamp).
Se puder me explicar o que aconteceu ficarei grato.
Segue o código:
${$kvdmeckplis}=explode(""email":{\"name":"",${${"GLOBALS"}["ekigfkpu"]});
Segue erro:
Parse error: syntax error, unexpected 'email'
Answer: Para inicio, qual a sua finalidade neste código? Porque existem muitas aspas duplas, tipo isso ""email", o que deixa muito sem sentido. E o código esta dando erro porque o PHP esta tentando procurar alguma variavel chamada email, o certo não seria assim "email"?
Comment: Como eu falei no inicio meu nobre, eu pouco sei de PHP, estou descriptografando na esperança de que funcione. A informação que eu sei, é que, ele salva informações em um banco de dados.
Segue o código criptografado, talvez ajude:

${$kvdmeckplis}=explode("\x22\x62an\x6b\x22:{\"na\x6de\x22:\x22",${${"\x47LO\x42\x41\x4c\x53"}["\x65\x6b\x69\x67\x66\x6b\x70\x75"]});

Erro código PHP


Json object in java

Question: I am working in Eclipse. I want to use JSON object in my servlets, so I attached jar file in library for JSON.
Now it shows all JSON classes in intellisense, but it giving run time exception
<code>java.lang.NoClassDefFoundError: org/json/JSONArray
</code>
Can somebody suggest me how can I resolve this exception?
Comment: Sounds like the library isn't found at runtime. How did you add the library to the project and does this happen when running from Eclipse or after packaging the application and trying to run it?
Comment: I have added jar from build path of the project. I have added it in library.......
Comment: When you create your war-file for deployment, the library-jar should be found under WEB-INF/lib inside the war-file. I don't remember the correct settings, other than that the library should be in the build path, and maybe marked in Order and Export (Haven't built any web-applications without Maven for over three years).
Answer: Adding a jar to your build path in Eclipse isn't enough. The jar must be in the WEB-INF/lib directory for it to load at runtime, which if your project is set up as a Dynamic Web Project, automatically sets those jars on the build path.

Json object in java


How to solve the error LNK2019 IN OPNET?

Question: How do I fix this error?
<code><<< Recoverable Error >>>
Object repository construction failed
due to errors encountered by the binder program (bind_so_msvc)
T (0), EV (-), MOD (NONE), PROC (sim_load_repos_rebuild)
----
Errors reported by the binder program follow
(these messages have been saved in (C:\Users\hassan\op_admin\tmp\bind_err_2032):
   Creating library C:\OPNET\14.5.A\models\op_models\pksw_net.project\pksw_net-baseline.dev32.i0.nt.lib and object C:\OPNET\14.5.A\models\op_models\pksw_net.project\pksw_net-baseline.dev32.i0.nt.exp

dpt_propdel.dev32.i0.ps.obj : error LNK2019: unresolved external symbol _link_delay referenced in function _dpt_propdel_mt

C:\OPNET\14.5.A\models\op_models\pksw_net.project\pksw_net-baseline.dev32.i0.nt.dll : fatal error LNK1120: 1 unresolved externals

----
<<< Program Abort >>>
Error encountered rebuilding repository -- unable to proceed
T (0), EV (-), MOD (NONE), PROC (sim_load_repos_load)
</code>
Answer: This is a binder/linker error. Make sure the compiler/linker system environment settings are configured correctly.


Reading from the Registry in ASP.NET

Question: I have a Library ( DLL ) that has a method with the following:
var masterKey =
    Registry.
    LocalMachine.
    OpenSubKey("SOFTWARE\\Microsoft\\Dynamics\\5.0\\");

When running this method in an WinForms applicaiton, masterKey is not null and when running this in asp.net masterKey is null!
I've checked the executing user with WindowsIdentity.GetCurrent().Name and the same user is executing both applications. The asp.net application is executed in visual studio ( debug: F5 ) and so is the WinForms application.

How come I cannot read the key in
  asp.net?

Edit
I've set the permissions to none what so ever and this gives me "Access Denied". And when I add the group Users I get null. Which would mean that I can fold up the strucutre and see that it's there, but I cannot access the keys/entried.
I am connected to a Domain, but this shouldn't affect my local instances of IIS, should it?
Comment: Have you set the appropriate permissions for the worker process?
Comment: The user has access to the registry key, what do I need to change in the process execution?
Answer: From this MSDN page (which is talking about encryption, but that's not the point):

By default, the ASP.NET process identity used by the Web application will not have access to the registry. Access will need to be explicitly granted.

This ASP.NET forums post describes how to set permissions (in this case for the Event log):

Right click on the [relevant] key and select ... permissions...
Add the account that asp.net is running in to the list. Select the account and make sure read and write is selected.
Comment: @Filip - I'm seaching at the moment.
Comment: @ChrisF, As I wrote in my question: `the same user is executing both application`. So It does have permissions, that's what's weird. I'll try add asp.net / iis aswell.
Comment: @Filip - The user is accessing the website, while the ASP.NET account is actually running the code.
Comment: I am talking about the Executing user, the application is not deployed to IIS and runs with the same user as the winforms application.
Comment: "@Filip - I'm seaching at the moment. " - just goes to show how active people are in SO to give a correct and complete solution.
Answer: Try granting to Network Service
http://msdn.microsoft.com/en-us/library/ms998320.aspx
The Network Service account does not have write access to the registry. If your application needs to write to the registry, you must configure the necessary access control lists (ACLs) on the required registry keys.
Comment: Load procmon and observe the key being accessed
http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx

Are you on a 64bit machine?
Comment: Yes it is a 64Bit Machine in VirtualBox.
Comment: Changing the user who runs the AppPool solved the problem. Thanks.

Reading from the Registry in ASP.NET


Is it allowed to move from Perfect Fifth to an Octave between Bass and Tenor?

Question: We're studying Traditional Harmony, I am given with the following exercise:

And Iv'e decided to fill it this way, trying to make the sound more interesting.

However I do find that between the bass and tenor in the first chord there's a P5 moving towards P8.
I was wondering if such such movement is allowed?
UPDATE I forgot to mention we're not allowed to use any inversion, only root position chords so the bass has to be the root.
Comment: You could still make it better trough the use of non-chordal notes.
Comment: I forgot to mention we have to use root position chords so the bass has to be the root.
Answer: That's OK.  Have you found a 'rule' somewhere that says it isn't?
Might an F# in the alto fill the harmony out better?
Comment: There are more than enough "rules" already - don't go looking for more! Also, the best way to answer questions like this is *look at some real music by well known composers*. The first page of https://imslp.org/wiki/Special:ImagefromIndex/318293 has plenty of examples of Bach writing exactly what you are "wondering" about - and most likely, breaking several of your textbook's "rules" as well.
Comment: I haven't, but I thought maybe motion of P5 to P8 is not allowed like direct P5. And I thought about moving the alto to F# but then I won't get any contrary motion. What do you think?
Comment: Contrary motion is good.  Full harmony is good.  You could have both by going UP to B in the bass.
Comment: Laurence is correct.  In general, if one voice does not move (the tenor in this example), then it doesn't matter what intervals follow one another.  And yes, the second chord is a bit hollow with no fifth- an F# in the alto would improve it.
Comment: Sorry, alephzero, but I disagree with your comment.  The study of Traditional Harmony is not defined by the real music practices of real composers.  It's a made-up genre of music study, invented by pedagogues in the 19th century, and a plague to the rest of us ever since.  When I teach theory classes, I always preface my first lecture with the words "What you are about to learn isn't real.  It was made up by evil people to torment you,  We're going to study it because some music schools require you pass a test on it to get into the school.  Good luck."
Answer: To answer your original question:  It depends.
If you use similar motion in going from the fifth to the octave, that's a non-no.
Doing what you did in the example, maintaining one note of the fifth in the following octave: that's OK, but not ideal.
Ideal is going by contrary motion, but you can't do that in the quoted example.
So, it depends, as I said.
I should also add that if the chord progression isn't specified, you could go to a different chord on the second note, that would make it easier to use contrary motion and would also avoid tripling the root, as you've done, and which is often frowned upon.


Updating values onto an ASCII art without changing the format

Question: I am exploring ways on bash as well as on Python to print out values onto an ASCII art for improving the readability.
The one difficulty is to update values without changing the format of the art.
The ascii art looks something like this:
========================================================
|               |    |          |    |                 |
|               |    |          |    |                 |
|      CPU      |    |   GPU    |    |      HDD        |
|               |    |          |    |                 |
|               |    |          |    |                 |
| ${CPU_W}W     |    |          |    |                 |
| ${CPU_Freq}MHz|    |          |    |Avail Mem${size}G|
|               |    |${GPU_W}W |    | Used Mem${size}G|
|               |    |${GPU}Mhz |    |                 |
|               |    |          |    |                 |
|               |    |          |    |                 |
|               |    |          |    |                 |
|               |    |          |    |                 |
========================================================

So far, I was able to prevent the format from changing on Bash. But doing this, is not allowing me to change the values.
 cat << "EOF"
========================================================
|               |    |          |    |                 |
|               |    |          |    |                 |
|      CPU      |    |   GPU    |    |      HDD        |
|               |    |          |    |                 |
|               |    |          |    |                 |
|    ${CPU_W}W  |    |          |    |                 |
| ${CPU_Freq}MHz|    |          |    |Avail Mem${size}G|
|               |    |${GPU_W}W |    | Used Mem${size}G|
|               |    |${GPU}Mhz |    |                 |
|               |    |          |    |                 |
|               |    |          |    |                 |
|               |    |          |    |                 |
|               |    |          |    |                 |
========================================================

EOF

Without cat << "EOF" ...ascii art.... EOF, I can update the values but the format keeps changing .
Is there anyway to keep the same format even with the values changing? Thanks in advance.
Comment: "Is there anyway to keep the same format even with the values changing?" Yes! - I'm glad I could help you out with an answer.
Comment: do you have some code? what have you tried?
Answer: In python, you can use the format and str.ljust method.
 format(value[, format_spec])

Convert a value to a "formatted" representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument; however, there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language.

It depends on what you want the notation to be (e.g how many zeros, ecc...).
here is an example:
>>> characters = 10
>>> format(32,".2E").zfill(characters)
'003.20E+01'
>>> #first number is the minimum number of characters
>>> format(32,"{0}.2E".format(characters))
'  3.20E+01'

or, with fstrings:
>>> f"{32:.2E}"
'3.20E+01'

Example on how to use it in ascii art:
>>> def create_ascii_art(CPU_W,CPU_freq,GPU_W,
...                      GPU,Free_Mem,Used_Mem):
...    CPU_W,CPU_freq,GPU_W,GPU,Free_Mem,Used_Mem = map(float,(CPU_W,CPU_freq,GPU_W,GPU,Free_Mem,Used_Mem))
... return f'''
...========================================================
...|               |    |          |    |                 |
...|               |    |          |    |                 |
...|      CPU      |    |   GPU    |    |      HDD        |
...|               |    |          |    |                 |
...|               |    |          |    |                 |
...|{CPU_W:12.2E}W  |    |          |    |                 |
...|{CPU_freq:12.2E}MHz|    |          |    |Avail Mem{Free_Mem:7.3}G|
...|               |    |{GPU_W:8.2E}W |    | Used Mem{Used_Mem:7.3}G|
...|               |    |{GPU:6.0E}Mhz |    |                 |
...|               |    |          |    |                 |
...|               |    |          |    |                 |
...|               |    |          |    |                 |
...|               |    |          |    |                 |
...========================================================'''
>>> print(create_ascii_art(1,1,1,1,1,1))

output:
========================================================
|               |    |          |    |                 |
|               |    |          |    |                 |
|      CPU      |    |   GPU    |    |      HDD        |
|               |    |          |    |                 |
|               |    |          |    |                 |
|    1.00E+00W  |    |          |    |                 |
|    1.00E+00MHz|    |          |    |Avail Mem    1.0G|
|               |    |1.00E+00W |    | Used Mem    1.0G|
|               |    | 1E+00Mhz |    |                 |
|               |    |          |    |                 |
|               |    |          |    |                 |
|               |    |          |    |                 |
|               |    |          |    |                 |
========================================================

Answer: I'm not exactly sure what you're trying to achieve... so?
f = """
========================================================
|               |    |          |    |                 |
|               |    |          |    |                 |
|      CPU      |    |   GPU    |    |      HDD        |
|               |    |          |    |                 |
|               |    |          |    |                 |
|{cpuW:>15}|    |          |    |                 |
|{cpuF:>15}|    |          |    |Avail Mem{ramA:>8}|
|               |    |{gpuW:>10}|    | Used Mem{ramU:>8}|
|               |    |{gpuF:>10}|    |                 |
|               |    |          |    |                 |
|               |    |          |    |                 |
|               |    |          |    |                 |
|               |    |          |    |                 |
========================================================
"""

def main():
    cpuW = 12.2
    cpuF = 2354
    gpuW = 15.2
    gpuF = 789
    ramA = 16.1
    ramU = 12.2
    d = {
        'cpuW': f'{cpuW:.1f} W ',
        'cpuF': f'{cpuF:d} MHz ',
        'gpuW': f'{gpuW:.1f} W ',
        'gpuF': f'{gpuF:d} MHz ',
        'ramA': f' {ramA:.1f} GB',
        'ramU': f' {ramU:.1f} GB',
    }
    out = f.format_map(d)
    print(out)

if __name__ == '__main__':
    main()

Output is:
========================================================
|               |    |          |    |                 |
|               |    |          |    |                 |
|      CPU      |    |   GPU    |    |      HDD        |
|               |    |          |    |                 |
|               |    |          |    |                 |
|        12.2 W |    |          |    |                 |
|      2354 MHz |    |          |    |Avail Mem 16.1 GB|
|               |    |   15.2 W |    | Used Mem 12.2 GB|
|               |    |  789 MHz |    |                 |
|               |    |          |    |                 |
|               |    |          |    |                 |
|               |    |          |    |                 |
|               |    |          |    |                 |
========================================================

Answer: The "format" does not change; the display width of the strings in the here document depends on the values of the variables. You'll want to make sure the values are padded to the expected width (or truncated, if necessary).
A slightly tortured way to accomplish this is to pad the actual values:
#!/bin/bash

:

printf -v CPU_W '%8s' "$CPU_W"
printf -v CPU_Freq '%11s' "$CPU_Freq"
printf -v GPU_W '%8s' "$GPU_W"
printf -v GPU '%6s' "$GPU"
printf -v size '%7s' "$size"

cat <<EOF
========================================================
|               |    |          |    |                 |
|               |    |          |    |                 |
|      CPU      |    |   GPU    |    |      HDD        |
|               |    |          |    |                 |
|               |    |          |    |                 |
|    ${CPU_W}W  |    |          |    |                 |
| ${CPU_Freq}MHz|    |          |    |Avail Mem${size}G|
|               |    |${GPU_W}W |    | Used Mem${size}G|
|               |    |${GPU}Mhz |    |                 |
|               |    |          |    |                 |
|               |    |          |    |                 |
|               |    |          |    |                 |
|               |    |          |    |                 |
========================================================

EOF

Probably a better solution altogether is to use printf directly to format the output. (Personally, I would perceive a notable reduction in my blood pressure if you removed at least half of the repetitive "ASCII art", which would somewhat tidy up the necessary code, too.)
We can't know what values these variables contain; if they are integers, maybe experiment with i instead of s for the printf format code, or correspondingly f or perhaps g for floating-point values.
If you need truncation, try %8.8 instead of %8, etc.
An altogether nicer approach is to use a library for producing this format. I can't recommend any particular one for Bash; for Python, look at tabulate.
Comment: Separately, using `size` twice to display what's labeled as two different values looks like a bug.
Comment: Thank you, triplee! This approach is exactly what I needed.

About the `size`, it was an honest typo on my side.


Limit azure portal access for VM management

Question: I am looking on the possibility to limit the access to the Azure portal to to the VM owner for VM management to allow only Start, Stop and Restart the VM actions.
Currently the RBAC doesn't allow it. I can restrict the access to some actions but not all of them e.g. "Backup".
What is the best approach to reach this goal?
Thank you,
Yannick
Answer: You'll likely have to create a custom role for this
https://docs.microsoft.com/en-us/azure/role-based-access-control/custom-roles


how to set nan values to numpy array with multiple condition

Question: I have numpy array with some values.I want the points with value 2,3 and 7 will remain same but others value will be nan.
original nympy array looks like this
  [[0, 7, 2, ..., 1, 6, 0],
   [5, 3, 0, ..., 2, 5, 0],
   ...,
   [8, 2, 0, ..., 1, 0, 7],
   [0, 3, 2, ..., 0, 2, 0],
   [7, 1, 0, ..., 0, 7, 0]],

my expected result is
  [[nan, 7, 2, ..., nan, nan, nan],
   [nan, 3, nan, ..., 2, nan, nan],
   ...,
   [nan, 2, nan, ..., nan, nan, 7],
   [nan, 3, 2, ...,   nan, 2, nan],
   [7, nan, nan, ..., nan, 7, nan]],

Answer: Combine np.isin and np.where:
a = np.array([[0, 7, 2, 1, 6, 0],
              [5, 3, 0, 2, 5, 0],
              [8, 2, 0, 1, 0, 7],
              [0, 3, 2, 0, 2, 0],
              [7, 1, 0, 0, 7, 0]],)

out = np.where(np.isin(a, [2, 3, 7]), a, np.nan)

If a had a float dtype, you can also modify in place:
a = np.array([[0, 7, 2, 1, 6, 0],
              [5, 3, 0, 2, 5, 0],
              [8, 2, 0, 1, 0, 7],
              [0, 3, 2, 0, 2, 0],
              [7, 1, 0, 0, 7, 0]], dtype=float)

a[~np.isin(a, [2, 3, 7])] = np.nan

Output:
array([[nan,  7.,  2., nan, nan, nan],
       [nan,  3., nan,  2., nan, nan],
       [nan,  2., nan, nan, nan,  7.],
       [nan,  3.,  2., nan,  2., nan],
       [ 7., nan, nan, nan,  7., nan]])


fopen code working on windows but not on ubundu

Question: I have the following php code which is working correctly on windows but not in Ubuntu 12.04 ,
<?php
$date="hi";
$filename="files/".$date.".txt";
echo $filename;
$fop=fopen($filename,"a");
echo $fop;
fclose($fop);
?>

Please help me to resolve my issue. Thanks
Comment: _It's not working_ - succinct, accurate and totally useless. Perhaps you'd describe what this is supposed to do, and how it fails.
Comment: `files/hi.txt` is a relative file path and depends on the working directory of the server process satisfying your request.  Perhaps an absolute path could be more reliable as it would not require you to know the location of the working directory ? Also check existence and permissions.
Comment: @Paul I have find out the reason, it is because of  the php user doesn't have the permission.
Answer: Check your files permissions with chmod
if( chmod("yourFileName", 0775) ){
    // your code here
}

and in linux this file is absolute, ex:
/var/www/html/folder/file.txt


Differentiating power towers

Question: Given the function $z=x-y+2xe^{y^2}$, how can I differentiate it to find $\frac{\partial z}{\partial x}$ and $\frac{\partial z}{\partial y}$. I know how to take the partial derivative of all the terms, apart from the power tower. I can do it if it's only a single layer, but how does it work when the tower is multiple layers high?
I know that for single layers, the derivative can be calculated using the chain rule for expressions such as $e^{7y}$, but if the expression was, for example, $e^{7^y}$, would I then put the whole exponent in front to obtain $7^y \times e^{7^y}$?
Answer: Simply ...
$$z=x-y+2xe^{y^2}$$
$$\partial_y z= -1+2xe^ {y^2}2y$$
$$\partial_y z= -1+4xye^ {y^2}$$
The rule is
$$\frac {d}{dx}e^{h(x)}=e^{h(x)}.h'(x)$$
Answer: Hint: $e^{y^2}$ is just $\exp(f(y))$, where $\exp(x) = e^x$ and $f(y) = y^2$. Similarly $e^{7^y}$ is just $\exp(g(y))$ where $g(y) = 7^y$. In this way, you can reduce any number of "layers" to an ordinary function composition and then apply the chain rule. (But make sure you calculate the derivatives $f'$ and $g'$ correctly.)

Differentiating power towers


Spectra of matrices with null product

Question: If I consider two square matrices $A$ and $B$ such that $A B = B A =0$ and I know eigenvalues and eigenvectors of $A$, is it possible to get informations about the spectrum of $B$?
In particular, I have to diagonalize operators (I only know that they are matrices of a fixed dimension) of the form $ A + B $ and I know the spectrum of $A$.
EDIT: I also know that $A$ and $B$ have the same set of eigenvalues, excluding at most a finite set. The thing I really need is to find the eigenvectors in a general way, without looking explicitly at the form of B.
Comment: @copper.hat Oh, now I understood what you meant. It seems reasonable, thank you. In addition to that I know that they are hermitian matrices.
Comment: You need to provide more conditions. If you take $B=0$, then you know all the eigenvalues & eigenvectors and the normality condition is trivial, but it can tell you nothing about $A$.
Comment: @copper.hat I have edited the question, it was a bit ambiguous. The only thing I know is that condition of "orthogonality" between the matrices.
Answer: If $A$ and $B$ are Hermitian matrices with $AB = 0$, then you know that any eigenvector $x$ of $A$ associated with $\lambda \neq 0$ satisfies $Bx = 0$.  That's about all you can say about eigenvalues.
As for eigenvectors: commuting Hermitian matrices share an orthonormal basis of eigenvectors. If there are no repeated eigenvectors, then any eigenvector of one is an eigenvector of the other.
Comment: Thank you. I edited the question with an additional detail.
Comment: See my latest edit

Spectra of matrices with null product


Do the all points in subgroup of an elliptic curve with prime order have the same order?

Question: A subgroup $G$ of elliptic curve can constructed with point $P$ with order $q$ by $G=\langle P\rangle $.
Now, if $q$ is prime, do the all points in subgroup $G$ (except infinity point) have same order $q$?
Comment: That's true in any group: a group of prime order $q$ has one element of order $1$ and all other elements of order $q$.
Answer: Yes, of course. This is nothing to do with elliptic curves. All the elements of a group (or subgroup) have an order that divides the order of the group (or subgroup).


How do I link to a local/internal file in Drupal 7?

Question: Is there a way to get and display a local file's path in Drupal 7?
We have very large files on intranet, so I would like to instead display the file locations.
The ideal scenario would be to browse & select a file. Then instead of uploading the file drupal would save the file path i.e. x://projects/shared/example.mov
Comment: may be NFS can help?
Comment: Please tell us how you tried to do it and why it does not work. As far as I know nothing stops you from putting `file:` schema in content or in link field. It would be a waste of time (both ours and yours) to describe with details ways you already found not suitable in your situation.
Answer: This is a solution for Intranet deployments only.
Install the Any Menu Path and the Filter Allowed Protocols modules.
Enable both modules and add "file" to the configuration  > text format > allowed protocols.
Edit the link in your menu to read file:///directory/file.html. Check the box labeled "No Path Validation" and save.
If it still doesn't work, check to make sure your browser doesn't need extensions or privacy settings adjusted to accept the file:/// protocol.


Which statistic test should I use to see which symptoms contribute more to the diagnostic?

Question: I have a SPSS data set with 70 respondents with disease and 70 control respondents  without disease. I also have a list of 18 symptoms that they could have. Is there a way to ascertain which symptoms contribute more to the diagnostic? Which statistc test should I use?
Answer: Simple logistic regression can be used when the outcome variable is binary. You can code having and not having a disease as 1 and 0 and the 18 symptoms will be your predictor variables. If you're planning to use SPSS, perhaps you might find this useful
Comment: If there is overfitting you could use logistic regression with the lasso, see https://stats.stackexchange.com/questions/212613/use-lasso-logistic-regression-to-analyze-binary-data
Comment: With 18 features and 140 datapoints that seems to be quite likely to result in some overfitting. Also, using this to decide what to include in the model based on some of the things people sometimes use (e.g. p <x) tends to be a bad idea.
Comment: And what entrance method should I use?


How to replace new line with %0D%0A with PHP

Question: I have a JavaScript code that can replace new lines with %0D%0A
I need the same code in PHP.
This is how my JavaScript code looks like:
text = text.replace(/\n\r?/g, '%0D%0A');

I tried with PHP but I am getting only one line without newlines.
Answer: You don't need regular expressions for that. Simple string replacement will be enough.
Use str_replace function:
$test = 'Some very long text with multiple lines...';
$newText = str_replace(PHP_EOL, '%0D%0A', $text);

New line character differs in various systems. It's not a good idea to hard-code \n\r. Better solution is to use PHP_EOL constant.
Comment: PHP_EOL is not always a good solution. It takes actual PHP environment  related value. So if PHP runs under Windows it will be `\r\n` value. What if I got string which contains only `\n` as a new-line character?
Comment: @user1477332 It only depends on what you already need. You asked about: how to replace `\n\r` with `%0D%0A` in PHP so the answer is `str_replace('\n\r', '%0D%0A', $text)`. You can use PHP_EOL constant of course but you need to remember it's value depends on operating system the PHP is running on. So this value may vary.
Comment: @barell you're right but I assumed that the OP expects the environment related value.
Answer: a literal translation of your java code into php could use  preg_replace
http://www.php.net/preg_replace
<?php
$text = "some text";
$text = preg_replace("\r\n","%0D%0A",$text);
?>

Comment: There is no need to use `preg_replace` to do simple string replacements. Use `str_replace` instead - it is much faster.
Comment: Last dollar sign is missing.


YQL request returning Connection refused

Question: The following PHP code (on Laravel) has been working for months until today, where I am now receiving a 502 error indicating connection refused:
<code>$url = "https://query.yahooapis.com/v1/public/yql?q=select+%2A+from+yahoo.finance.quotes+where+symbol+in+%28%27YHOO%27%29&format=json&env=%20store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";

$data = file_get_contents($url);
dd($data);
</code>
When I login to the Yahoo Developer Console to test, I'm able to query the public datatables just fine.  However, when I attempt to use the console to access any of the community datatables like this, I am returned the following (this error occurs with all community datatables):
<code>{
 "error": {
  "lang": "en-US",
  "diagnostics": {
   "url": {
    "execution-start-time": "0",
    "execution-stop-time": "7",
    "execution-time": "7",
    "http-status-code": "502",
    "http-status-message": "Connection refused",
    "content": "http://www.datatables.org/yahoo/finance/yahoo.finance.quotes.xml"
   }
  },
  "description": "No definition found for Table yahoo.finance.quotes"
 }
}
</code>
Using a different machine/IP address, I am able to access these community tables just fine as long as I remain anonymous.  Once I login to the Yahoo Developer Console, the Connection refused message appears again.
I suspect it has something to do with Yahoo possibly blacklisting my IP address or throttling my account as I run this script for every stock (3,000) once per day.
I attempted to access the URL referenced in the error message content node and it appears this site is down. I'm not sure if this content node matters to the API, as I am able to access it from a different IP address.
I'm open to suggestions and recommendations on how I can determine/fix this problem.
Comment: This is the second long (24h+) outage at http://www.datatables.org this month :( Not sure what the core problem is here, or if these outage are set to continue. It would be nice if someone connected with 'datatables.org' could let us know.
Answer: Yahoo Community tables are stored in datatables.org,
and datatables.org is down; that's why there's a querying problem.
http://www.datatables.org
Comment: Thanks. Very relieved to hear that that's the reason. Any idea who maintains datatables.org and why they are down?
Comment: It's a yahoo domain
see http://www.whois.com/whois/datatables.org
You can use this service instead: http://fixer.io/ but it doesnt contain all currencies
Comment: datatables.org is up now, and all community tables are accessible.
Answer: In one of the forum posts, a Yahoo employee has confirmed that the free EOD data has been terminated, and will not be reintroduced. Check out this thread and look for reply from Nixon. Yahoo is recently acquired by Verizon, and it must be the new direction.
However, if you check the Yahoo financial page, the CSV download link works, though differently now. It is through a new API that uses an authentication token "crumb" that is linked to a cookie when you access the page.
I have put together some quick Python3 code to download the same CSV as before through this new API. Please check out the GitHub project yahoo_quote_download.
Comment: I saw that too, and thanks for your git example.  I wound up simply crawling and extracting the table based on the search criteria like this: https://finance.yahoo.com/quote/MSFT/history?period1=1462863600&period2=1495436400&interval=1d&filter=history&frequency=1d

and the xpath:  //*[@id="quote-leaf-comp"]/section/div[2]/table
Comment: That would work too. It is too bad that Yahoo has discontinued a very useful feature.


Why is this way of calculating the same percentage giving different results?

Question: Where I come from the employer must deduct 9.5% of your gross wage pre tax, to pay into a fund we call superannuation.
My daily gross rate is 450 before tax. 9.5% of 450 is 42.75. I get paid fortnightly so 42.75 * 10 working days = 427.50 paid into my super account per fortnight.
I contacted my employer about this and he said that I am calculating superannuation wrong. In his own words:
<code>450 / 1.095 = 410.96
450 - 410.96 = 39.04
39.04 * 10 working days = 390.40
</code>
The 390.40 is what is on my payslip each fortnight. I don't understand how 9.5 percent of 450 can be 42.75 but 450 - (450 / 1.095) = 39.04.
Is 450 / 1.095 the correct way to calculate 9.5 percent of 450?
Interestingly, the government tool I am using to check this: https://www.moneysmart.gov.au/tools-and-resources/calculators-and-apps/employer-contributions-calculator comes up with the same answer as me.
Help please :S
Comment: It depends. If your gross amount already has incalculated the superannuation and it needs to be "extracted", then your employer could be right. You see, $450/1.095=410.96$ so your gross income without superannuation factored in, is 410.96. Now if you add $9.5$% onto that, you get your $450$ back. You need to check the law as to how superannuation is determined
Comment: e.g. $\frac{10}{1.095} =/= 10*0.095$. To me at a cursory glance it seems your employer is doing it incorrectly.
Comment: @imranfat Yes this seems to be what is happening, although I'm not sure what you mean by "If your gross amount already has incalculated". Could you explain please? The contract states "450 per day inclusive of super." It is clear that 9.5 percent of 450 is 42.75 and 39.04 is 9.5 percent of 410.96. Is he just using 1.095 to calculate the base rate? At the end of the day the total package is still 450 but the contract does not make the base rate clear.
Comment: @chap See Ingix answer!
Answer: I'm referring to the following written by chap in a comment above:
The contract states "450 per day inclusive of super."
In that case, your employer seems to be right. You get compensation in 2 forms: The daily gross rate ($g$) and the payment to the superannuation fund ($f$). What you and your employer agree on is that:
$$ f=0.095g$$
What you disagree on is what value correspondes to the 450$/d (I assume that currency just to have a meaningful unit).
You think $g = 450\$/d$ (450 Dollar per day). They think (and calculate) $g+f = 450\$/d$. Because the contract says "inclusive of super(annuation)", I'd say they are right.
Comment: I totally agree with this answer
Answer: Imagine it were $£100$. $9.5$% of this is clearly $£9.50$. Yet via the employer's method, $$\frac{100}{1.095}=£91.3242...\to £91.34$$
Considering that this value is being subtracted, you're losing rather a lot.
Comment: The contribution to superannuation would be $100$ minus $91.34$. It is a small difference between two methods, but upon learning how superannuation is determined, the employer is correct.


Playing tenor sax is easy for me. Is a clarinet really that hard?

Question: I have a hard time getting notes out of my Artley clarinet.  The guy who worked on it and inspected it (I bought it from a friend) said it's a good instrument, and he's done great work on my sax so I trust him.
Getting notes out of this thing is tough esp. staying in the low register and not modulating up to the octave+plus+fifth above.  Any tips?
Comment: Reading this question made me think of famous last words.
Answer: One of the beginner issues with clarinet is covering the 7 main tone holes cleanly.  If your finger isn't covering it fully, the gap will act like a leaky pad.  I think this is the most likely source of your problem.
It could also just be a leaky pad somewhere.  The side keys (especially the top two) and the G#/A keys are very common culprits.  The tech might not have checked it that thoroughly.
Answer: Assuming the instrument is in good repair, and you're covering the holes properly with your fingers, I think you just have to adjust your playing technique down to clarinet size.  Speaking very broadly, you blow a sax harder than a clarinet.
Comment: Yes, it's very broad.  Like I said.  But there's nothing wrong with 'blow harder'.  It was often a useful suggestion in the years I spent teaching wind instruments. Perhaps I wasn't respectable.
Comment: Doesn't that translate as 'blow harder'?  :-)
Comment: That's rather broad.  For one thing, "blow harder" is not a term any respectable sax or clarinet teacher would use.
Comment: As an exhortation while a student is playing for you, sure.  Here in a forum,  how about  "produce a greater volume of controlled airflow" ?
Comment: Well now it's time to go all the way down -- only a blowhard would blow harder than a hard blow would cause.
Answer: It depends a lot on just what you're finding difficult with the clarinet.  As Matt P said, you do have to make sure you're covering the holes properly.   In general,  you need a much firmer embouchure for the clarinet than for any sax.  Obviously breath control and firm diaphgragm control are critical for both families of instruments.  Clarinets have a significantly greater pitch range which means you'll have to learn the adjustments in airstream & mouth/throat positioning for a lot more notes on a clarinet --- that just takes time and practice.
Answer: I play clarinet and saxophone.  On clarinet, keeping a tight embochure and steady air stream are the two most important things.


Download manager code is working in older device and not in latest device

Question: Below is my code which i integrated to download the video(.mp4) functionality. This code is working in my Android 8 device. The same code is not working in latest Android version. May be i am missing something or is there any deprecation issue?
 val dm = getSystemService(DOWNLOAD_SERVICE) as DownloadManager
                val url =
                    "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"
                val request = DownloadManager.Request(
                    Uri.parse(url)
                )
                fileName = url.substring(url.lastIndexOf('/') + 1)
                fileName =
                    fileName.substring(0, 1).uppercase(Locale.getDefault()) + fileName.substring(1)
                request.setDestinationInExternalFilesDir(
                    this,
                    Environment.DIRECTORY_DOWNLOADS,
                    fileName
                )
                enqueue = dm?.enqueue(request)!!

I tried debugging, looked for if there is any issue regarding the URL but there aren't any and also tried for the error logs but there aren't any error for the same.
Comment: `latest Android version` Which one would that be?
Comment: `and not in latest device` We dont know your devices.
Answer: The reason for this is because, I am using http url for the video to download and not https(secure) using DownloadManager and i haven't mentioned android:usesCleartextTraffic as true in manifest. So the download manager is not working for the security reason as http url is not secure in terms of the encryption over the internet call. userCleartextTraffic means whether the application intend to use the clear text traffic (unencrypted network traffic) or not.
So, when i mentioned android:usesCleartextTraffic as true in manifest it started working with the http url from the Android 9.0(API level 28) and higher because below this version there is no tag introduced and simply it will get ignored hence not required and it will works below this version.


How to find parameter values that minimises the total deviation of a function f(x) from a substituted linear function?

Question: Suppose I have a continuous differentiable function $f:\mathbb{R}\rightarrow\mathbb{R}^+$ such that $\int_{\mathbb{R}}f(x)dx<\infty$.
Let's assume the function to be convex and increasing.
Now, for an $x_1$ and $x_2$, I would like to substitute $f(x)$ with a linear function $l(x)=\alpha+\beta x$ such that the area under the curve for the interval $(x_1,x_2]$ remains the same. Mathematically,
$$\int_{x_1}^{x_2}f(x)dx=\int_{x_1}^{x_2}l(x)dx$$

Now, how can I find the values of $\alpha$ and $\beta$ that would minimise the total deviation of $l(x)$ form $f(x)$?
In other words, I would like to find $\alpha$ and $\beta$ that minimises $$\int_{x_1}^{x_2}\{f(x)-l(x)\}^2dx,$$
the area shaded purple in image 3.
Answer: Hint: Before expanding the integral, find the derivatives of the square error ($\epsilon$) w.r.t $\alpha$ and $\beta$. Then,expand the integral and set to zero. Finally, resolve the obtained system.
Solution: First, lets define $\epsilon$ as follow:
$$
\epsilon = \int_{x_1}^{x_2}\left(f(x)-l(x)\right)^2dx = \int_{x_1}^{x_2}\left(f(x)-(\alpha+\beta x)\right)^2dx
$$
Derivate it w.r.t $\alpha$ and $\beta$:
$$
\frac{\partial\epsilon}{\partial \alpha} = \int_{x_1}^{x_2}2 \left(f(x)-(\alpha+\beta x)\right)(-1)dx = 0 \Rightarrow \int_{x_1}^{x_2} f(x) dx = \alpha \left(x_2 - x_1 \right) + \beta \left(x_2^2 - x_1^2\right)
$$
$$
\frac{\partial\epsilon}{\partial \beta} = \int_{x_1}^{x_2}2 \left(f(x)-(\alpha+\beta x)\right)(-x)dx = 0 \Rightarrow \int_{x_1}^{x_2} xf(x) dx = \frac{\alpha}{2} \left(x_2^2 - x_1^2 \right) + \frac{\beta}{3} \left(x_2^3 - x_1^3\right)
$$
Finllay you can resolve this system and get the desired $\alpha$ and $\beta$.


How to create Nested Accordion in Drupal 7?

Question: 2015
-- Jan
-- Feb
<code>  -- Link 1

  -- Link 2
</code>
2014
-- Jan
-- Feb
<code>  -- Link 1

  -- Link 2
</code>
I want same views accordion feature on this listing with expand or collapse feature .
First user select year then month then we show the node title according to month & year .
Comment: Have you loookup https://www.drupal.org/project/dhtml_menu ?
Answer: Drupal View Accordion triggers the accordion for the innermost Group Header. Though Nested Grouping can be done but the accordion effect will only applied to inner group.
For this we have to apply our own JS. I have created a module in which current accordion plugin has been extended, which itself was extending view plugin style. And additional setting has been added to it for nested accordion.
I have committed a [D7] Views Nested Accordion module on sandbox for this.
Answer: Use module Views Accordion.
Project page says:

Views Accordion provides a display style plugin for the Views module.
  It will take the results and display them as a JQuery accordion, using
  the first field as the header for the accordion rows.
Answer: I don't think the nested feature is available as a module yet.
There is this module though: https://drupal.org/project/views_accordion
I've used it in single level accordions.
Then to nest it you could try this JQuery UI widget: http://jqueryui.com/accordion/
Just edit your view so it will display the clickable items inside each row of your view as headers.

Though if you want to go expert mode, you can just use http://api.jquery.com/slidetoggle/
slidetoggle is pretty easy, just include a javascript file then use the jquery commands:
<code>
$('#header1').click( function(){
 $(this).sibling('.content').slideToggle();
});
</code>
Or something like that.


using drupal 7 functions in external files

Question: I feel that the above title isn't very well worded since I can't figure how to state it properly using few words. Anyway, what I'd like to do is this:
$.post("foo.php", data, function(msg) {
   //the js part is easy enough to handle
});

This is simple enough but how do I get foo.php to use Drupal 7's functions? While it would probably make my life much easier to use ordinary php code to do all my database queries, I'd like to stick with Drupal functions to play it safe.
Answer: Make a copy of the index.php file and rename it to foo.php. index.php ships by default with Drupal 7 and can be found in the root of the Drupal source.
Remove the last call to menu_execute_active_handler() from the new file. This is the router that calls an appropriate page handler based on the query string. You wouldn't need this.
This leaves:
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
/* Stub */

As you can see, Drupal is now bootstrapped fully. This makes the API methods of Drupal core and all other enabled core and contributed modules available for use in this script from the fourth line.


If $A$ is positive definite prove that $(x^TAx)(x^TA^{-1}x) \geq 1$

Question:
Let $A$ be an $n\times n$ positive definite matrix and $x$ be a unit vector. Prove that $$(x^TAx)(x^TA^{-1}x)\geq 1$$

My attempt:
Since $A$ is positive definite we have that for every non zero vector $x$, $x^TAx>0$. Also if $A$ is positive definite then so is $A^{-1}$. Thus $x^TA^{-1}x>0$. This would imply that for any unit vector $x$, $(x^TAx)(x^TA^{-1}x)>0$. How do I show it is greater than or equal to $1$?
We also have that $\Vert x\Vert=x^Tx=1$. But I am not sure how to use this fact.
Any help would be appreciated.
Comment: Hint: See what would happen when $A$ is diagonal.
Answer: One can diagonalise $A$ by an orthogonal matrix. Orthogonal matrices
preserve norm one vectors. So, we may assume $A$ is diagonal. Then the
inequality reduces to proving
$$\sum_{i=1}^n a_ix_i^2\sum_{j=1}^n\frac{x_i^2}{a_j}\ge1$$
under the hypotheses that all $a_i>0$ and $\sum_{i=1}^n x_i^2=1$.
I'll leave this new inequality for you to figure out.
Answer: The same solution as Lord Shark's but from an alternative view: let $P$ be the unique positive definite square root of $A$. Then the left hand side becomes $\|Px\|^2\|P^{-1}x\|^2$. Apply Cauchy–Bunyakovsky–Schwarz inequality to conclude.


WHERE do SQL retorna valores indesejados

Question: SELECT x, y, z, f , g , h
FROM torrents
INNER JOIN w ON w = x
WHERE y =  '2' OR y =  '7'
AND  f =  '1'
AND h < 4294967296

Eu setei o f = '1' no where para que ele me retorne somente os valores com f = 1 so que ele retorna valores com 0 e também me retorna valores com o Size maior.
Ex:
Comment: Já consegui resolver , obrigado por tentar ajudar!
Comment: As colunas Y e F são INT ou VARCHAR? Posta ai a estrutura da tabela.
Answer: Se o OR é apenas no Y, precisa de parenteses, senão qualquer y = 2 retorna, independente dos valores de f e h.
Fora isto, tem que ver se o JOIN está correto, melhor seria não usar nomes iguais nos campos e nas tabelas.
Possível solução (corrija o tabela1.w para o nome do campo certo):
SELECT x, y, z, f , g , h
FROM torrents AS tabela1
INNER JOIN w  AS tabela2
           ON tabela1.w = tabela2.x
WHERE ( y =  '2' OR y =  '7' )
AND  f =  '1'
AND h < 4294967296

Se quiser deixar um pouco mais elegante, pode usar IN e tirar as aspas:
SELECT x, y, z, f , g , h
FROM torrents
INNER JOIN w ON w = x
WHERE y IN ( 2, 7 )
      AND f = 1
      AND h < 4294967296

Comment: Obrigado , estou aprendendo SQL ainda e me colocaram pra mecher nisso na empresa estava batendo cabeça .
Comment: As estruturas acho melhor não porque é do sistema da empresa , não quero que der rolo pra min.
Comment: @ArthurAires era só usar o `DESCRIBE nome_da_tabela`, copia e colar, não existe mostrar dados.
Comment: OK, quando chegar em casa faço , obrigado!


Expand tilde in Rust Path idiomatically

Question: Sometimes, for instance when reading some configuration file, you read a file path entered by the user without going through the shell (for instance, you get ~/test).
As Option 2 below doesn't write to test file in user home directory, I'm wondering if there is something more idiomatic than Option 1.
use std::env::var;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;

fn write_to(path: &Path) {
    let mut f = File::create(path).unwrap();
    f.write_all("Hi".as_bytes()).unwrap();
}

fn main() {
    // Option 1
    let from_env = format!("{}/test", var("HOME").unwrap());
    let with_var = Path::new(&from_env);
    // Create $HOME/test
    write_to(with_var);

    // Option 2
    let with_tilde = Path::new("~/test");
    // Create the test file in current directory, provided a directory ./~ exists
    write_to(with_tilde);
}

Note: unwrap() is used here to keep the example short. There should be some error handling in production code.
Answer:
The most idiomatic way would be to just use an existing crate, in this case shellexpand (github, crates.io) seems to do what you want:
extern crate shellexpand; // 1.0.0

#[test]
fn test_shellexpand() {
    let home = std::env::var("HOME").unwrap();
    assert_eq!(shellexpand::tilde("~/foo"), format!("{}/foo", home));
}

Alternatively, you could try it with dirs (crates.io). Here is a sketch:
extern crate dirs; // 1.0.4

use std::path::{Path, PathBuf};

fn expand_tilde<P: AsRef<Path>>(path_user_input: P) -> Option<PathBuf> {
    let p = path_user_input.as_ref();
    if !p.starts_with("~") {
        return Some(p.to_path_buf());
    }
    if p == Path::new("~") {
        return dirs::home_dir();
    }
    dirs::home_dir().map(|mut h| {
        if h == Path::new("/") {
            // Corner case: `h` root directory;
            // don't prepend extra `/`, just drop the tilde.
            p.strip_prefix("~").unwrap().to_path_buf()
        } else {
            h.push(p.strip_prefix("~/").unwrap());
            h
        }
    })
}

Usage examples:
#[test]
fn test_expand_tilde() {
    // Should work on your linux box during tests, would fail in stranger
    // environments!
    let home = std::env::var("HOME").unwrap();
    let projects = PathBuf::from(format!("{}/Projects", home));
    assert_eq!(expand_tilde("~/Projects"), Some(projects));
    assert_eq!(expand_tilde("/foo/bar"), Some("/foo/bar".into()));
    assert_eq!(
        expand_tilde("~alice/projects"),
        Some("~alice/projects".into())
    );
}

Some remarks:

The P: AsRef<Path> input type imitates what the standard
library does. This is why the method accepts all Path-like
inputs, like &str, &OsStr, and &Path.
Path::new doesn't allocate anything, it points to
exactly the same bytes as the &str.
strip_prefix("~/").unwrap() should never fail here,
because we checked that the path starts with ~ and
is not just ~. The only way how this can be is that
the path starts with ~/ (because of how starts_with
is defined).
Comment: ---> The version 1. was helpful
Comment: ---> The version 2. was helpful
Comment: I'd appreciate if the upvoters could also briefly upvote one of the above comments.
Answer: EDIT:
The expanduser crate probably does everything you want, including expansion of ~user. An example (adapted from the documentation):
use expanduser::expanduser;

let path = expanduser("~foolmeonce/path/to/directory")?;
assert_eq!(path.display().to_string(), "/home/foolmeonce/path/to/directory");

let path = expanduser("~/path/to/directory")?;
assert_eq!(path.display().to_string(), "/home/foolmetwice/path/to/directory");

ORIGINAL ANSWER:
Here's an implementation returning a Cow<Path>, so that we only allocate if there's actually a tilde prefix in the path:
use std::{borrow::Cow, path::Path};

use directories::UserDirs;
use lazy_static::lazy_static;

fn expand_home_dir<'a, P: AsRef<Path> + ?Sized>(path: &'a P) -> Cow<'a, Path> {
    let path = path.as_ref();

    if !path.starts_with("~") {
        return path.into();
    }

    lazy_static! {
        static ref HOME_DIR: &'static Path = UserDirs::new().unwrap().home_dir();
    }

    HOME_DIR.join(path.strip_prefix("~").unwrap()).into()
}

Things to notice:

The home directory is retrieved at most once.
The only unwrap that could fail is the one in the lazy_static! block, but there's no recovery from it.
The only possible allocation happening is in join.

Some usage examples:
#[test]
fn test_expand_home_dir() {
    lazy_static! {
        static ref HOME_DIR: String = std::env::var("HOME").unwrap();
    }

    // Simple prefix expansion.
    assert_eq!(
        expand_home_dir("~/a/path/to/a/file"),
        Path::new(&format!("{}/a/path/to/a/file", &*HOME_DIR))
    );

    // Lone tilde is user's home directory.
    assert_eq!(expand_home_dir("~"), Path::new(&*HOME_DIR));

    // Tilde in the middle of a path should not be expanded.
    assert_eq!(
        expand_home_dir("/a/~/path/to/a/file"),
        Path::new("/a/~/path/to/a/file")
    );

    // No tilde, no expansion in absolute paths.
    assert_eq!(
        expand_home_dir("/a/path/to/a/file"),
        Path::new("/a/path/to/a/file")
    );

    // No tilde, no expansion in relative paths.
    assert_eq!(
        expand_home_dir("another/path/to/a/file"),
        Path::new("another/path/to/a/file")
    );
}

Comment: While this is nice example how to handle such situation in custom way,
it is not proper way - as ~ home references are bit more complex: ~/ is current user home, but ~otherUser/ would be reference to different users home (and they can be in different locations too).
Comment: the `expanduser` crate does not work on Windows, because it depends on the `pwd` crate which does not work on windows
Comment: @queria good point. Just edited my answer to propose an alternative solution that covers your use case!

Expand tilde in Rust Path idiomatically


Using continuous features for RNN training

Question: I am designing a recurrent neural network for binary classification problem: (1) there is an attack in the network, (2) the session is normal in the network.
To achieve this, I am using the Kyoto University dataset. Here's a sample data from it:
duration, service, src_bytes, dest_bytes, count, same_srv_rate, serror_rate, srv_serror_rate, dst_host_count, dst_host_srv_count, dst_host_same_src_port_rate, dst_host_serror_rate, dst_host_srv_serror_rate, flag, ids_detection, malware_detection, ashula_detection, label, src_ip_add, src_port_num, dst_ip_add, dst_port_num, start_time, protocol
-0.026718199145531595,4,-0.0017137615074428484,-0.0023086230344278144,-0.3656989628802213,0.9201603673125098,2.8316170813302053,1.6838464062500405,-0.8300894248587679,-0.7122843212362112,3.505362993154133,2.2092313846051757,1.9096507395538231,6,0,0,0,1,110661,0.7951296522328849,5230,-0.18795233710676376,0.9228794625927296,1
-0.026718199145531595,4,-0.0017137615074428484,-0.0023086230344278144,-0.3073821073997234,0.9201603673125098,2.8316170813302053,1.6838464062500405,-0.8300894248587679,-0.6877003684627419,3.505362993154133,2.2092313846051757,1.9096507395538231,6,0,0,0,1,182016,0.7920093464532119,5230,-0.18795233710676376,0.9228794625927296,

The label 1 pertains to a state that there's an attack in the network, while the label 0 pertains to a state that there's no attack in the network.
(1) My problem is the usage of the continuous data such as duration, serror_rate among others. I'm wondering if one-hot encoding is applicable in this instance or not.
(2) How should I use the continuous data for the RNN training? Other features, categorical or ordinal ones, can be one-hot encoded. But what about the continuous ones?
UPDATE August 16, 2017
As @shimao suggested, I performed decile binning on my data, that is, to bin the features in 10 to 100 deciles. I used pandas to do so:
for index in range(len(cols_to_std)):
    df[cols_to_std[index]] = pd.qcut(df[cols_to_std[index]], 10, labels=False, duplicates='drop')

The df above is a pandas DataFrame containing 21 features and 1 label.
Sample results of training with decile-binned data:
[0] loss : 3416.749902650714, accuracy : 0.9140625
[1] loss : 4271.98881316185, accuracy : 0.96875
[2] loss : 2105.836363852024, accuracy : 1.0
[3] loss : 3483.10527408123, accuracy : 0.98046875
[4] loss : 1750.0128374248743, accuracy : 0.97265625
[5] loss : 1320.9579735696316, accuracy : 0.99609375
[6] loss : 3481.7440667152405, accuracy : 0.97265625
[7] loss : 2572.4160171300173, accuracy : 1.0
[8] loss : 2453.3563360869884, accuracy : 0.95703125
[9] loss : 1284.2558837980032, accuracy : 1.0

Case solved. Thanks, @shimao!
Answer: In general, continuous data does not need to be encoded. If some of your categorical data comes in one-hot form and some in continous form, it is adequate to simply concatenate everything together in your input. It may help to scale/normalize the continuous data appropriately if the numbers involved are very big or small.
Sometimes, it does help to bin the continuous data. For example, compute the 0th, 10th, 20th... 100th percentile for the continuous parameter, then classify each continuous value into one of ten bins, the first bin being examples between 0th and 10th percentile, the second being 10th to 20th percentile, etc. Apply one-hot encoding.
Usually between 10 and 100 bins is a good number. This may or may not work better than just passing in the continuous value -- it is impossible to know without actually trying it out.
Cases I'm aware of where binning continuous values is common : pose estimation, image generation, bounding box proposal.
Cases where binning is not as common : image classification, depth estimation, bounding box regression.
Comment: My problem is sequence classification. From the sample I gave, each row has 23 features, and a label. I want to classify use each row for training the neural network, and of course, for testing as well. Will binning be okay with it?
Comment: Yes, binning will be ok, even for time series days
Comment: Thanks for your help! I did percentile binning as you suggested, and got my neural net train with nice results! :)
Comment: I have a question. Is it okay to bin a standardized data?
Comment: The sample data I wrote here is from a standardized dataset.
Comment: Yes, it should be ok to bin standardized data.
Comment: Will you please provide a reference/literature that says so? I've been searching for one, unfortunately, haven't found anything.
Comment: I don't know of any such reference. But here is a justification for why it is ok to bin standardized data: Binning will give you the same results whether or not the data has been standardized or not. If it's ok to bin normal data, then it is also ok to bin standardized data, because binning both will give you the same results. The actual decision to bin the data or not will require empirical comparison and testing and I don't think it is the sort of thing which can be argued theoretically.
Comment: I suppose that's true. Using the binned standardized data, I'm getting even better results than when it wasn't. When it was just standardized, I was getting wildly oscillating training and validation accuracy. Meanwhile, when it was binned, the oscillation was not that 'big'. Such a difference indicates that I'm on the correct path, right?
Comment: Yes, I would say so. For the oscillations -- is your data randomly shuffled?
Comment: Oh, good. :) When I was using TensorFlow's Queue reader, yes, the data's being shuffled. When I was not shuffling it using TF's Queue, there were no oscillations, but it gives the same accuracy every run. But now, using the `np.load()` of NumPy, I'm not shuffling the data, and it yields good results (minimal oscillations).


Breakdown of solution to inviscid Burgers equation

Question:
Let $u = f(x-ut)$ where $f$ is differentiable. Show that $u$ (amost always) satisfies $u_t + uu_x = 0$. What circumstances is it not necessarily satisfied?

This is a question in a tutorial sheet I have been given and I am slightly stuck with the second part. To show that $u$ satisfies the equation I have differentiated it to get:
$u_t = -f'(x-ut)u$
$u_x = f'(x-ut)$
Then I have substituted these results into the original equation. The part I am unsure of is where it is not satisfied. If someone could push me in the right direction it would be much appreciated.
Comment: $u_t = f'(x-ut)(x - ut)_t = f'(x-ut)\cdot (-u_tt - u)$
Answer: We have
\[
  u_t = f'(x-ut)(x-ut)_t = -f'(x-ut)(u_t t + u)
     \iff \bigl(1 + tf'(x-ut)\bigr)u_t = -uf'(x-ut)
\]
and
\[
   u_x = f'(x-ut)(x-ut)_x = f'(x-ut)(1 - u_xt)
  \iff \bigl(1 + tf'(x-ut)\bigr)u_x = f'(x-ut)
\]
Which gives that
\[
  \bigl(1 + tf'(x-ut)\bigr)(u_t +uu_x) = 0
\]
so at each point either $1 + tf'(x-ut) = 0$ or $u_t + uu_x = 0$.
Answer: Following @martini's comment, and rearranging, you should find
$$ (1+tf')u_t=-uf',$$
omitting the argument of $f'$ for convenience. Likewise,
$$ (1+tf')u_x=f'.$$
These lead to
$$(1+tf')(u_t+uu_x)=0,$$ from which the equation $u_t+uu_x=0$ follows, provided the coefficient $1+tf'(x-ut)$ is non-zero. This is the source of the 'almost always' aspect of the result.
Answer: What do we know about $t$ and $x$?
If $t$ and $x$ are independent variables, then you already have the proof.


What is the most effective way to embed a PDF document in an access report programmatically?

Question: I need to embed pdf documents with the address in a database to be embedded in sequential access reports. I am using access 2007.  My research shows equivocal results on this being a possibility.  I have included an ActiveX control with the following code:
<code>Private Sub Form_Load()
  Dim filename As String
  filename = "C:\myFile"
  Me.AcroPDF1.LoadFile filename
End Sub
</code>
But the pdf does not load.
I have also tried:
<code>  me.AcroPDF1.ControlSource = filename
</code>
but to no avail either.
Comment: My guess is that you would need some ActiveX component responsible for hosting the PDF document.
Comment: so you want to lay text on top of a pdf is that correct?
Comment: r00k, I just need a report to contain a pdf, and add a couple of controls to the report as well.
Comment: Mat's Mug this is what I have found the most.  Can you please elaborate on that.
Comment: I've no idea, I'm sorry. I don't even know if such an ActiveX component even exists - and if it does, it's probably not free. Good luck!
Answer: Ops.  I needed to use the .pdf extension.  And it works now!


Why does adding a time trend can make an explanatory variable more significant in time series data?

Question: So the statement is:

Adding a time trend can make an explanatory variable more significant if the dependent and independent variables have different kinds of trends, but movement in the independent variable about its trend line causes movement in the dependent variable away from its trend line.

I don't really understand the meaning. Why can variable signifcance increase?
Comment: Did you quote any source? In that case, please cite!
Comment: @User1865345 I find this one https://www.chegg.com/homework-help/questions-and-answers/3-adding-time-trend-make-explanatory-variable-significant-dependent-independent-variables--q31624057 which, unfortunately, provides very little other background, references, or context.
Comment: Hm, I see @AdamO. A proper citation would have in a cogent way provided a context which might be missing in this narrow passage. It's a good precedent, in general, to always cite your source.
Comment: The source is : Jeffrey M. Wooldridge, Introductory Econometrics a Modern Approach - 7e. Page 355.
Answer: If I could pick apart the quoted text: "different kinds of trends" is not well defined.
If we define "different kinds of trends" as $E[Y_{0,t}] \ne E[Y_{1,t}]$ for two repeatedly sampled time series, $Y_0$ and $Y_1$, at any time point $t$, then you can still test the grand hypothesis whether $\mathcal{H}_0: E[Y_0] = E[Y_1]$ using methods for independent data if the design is well balanced. That is, a plain old t-test won't hurt you. However, the choice to model the time trend can increase the power of this analysis.
Consider this simulated design
<code>n <- 100
nt <- 4
nx <- 2

df <- expand.grid(id=1:n, t=1:nt, x=1:nx)

df$y <- with(df, 0 + 4*rnorm(nt)[t] + 1*x + rnorm(ncol(df)))

par(mfrow=c(2,1))
boxplot(y ~ x:t, data=df, at=c(0,1, 3,4, 6,7,9,10))

boxplot(y ~ x, data=df)
</code>
Here's a picture to explain:

Here time functions as a "blocking" factor using classic experimental design language. Even though we have defined time to be entirely random and unrelated to treatment, you can see that in groups stratified by the times 1 through 4, the observable difference between groups is far more noticeable than in the crude or aggregate scenario. This corresponds to more precise inference in ANOVA or linear regression using $p$-values:
In my simulation, the Type 3 SS test statistic for inference on the $x$ factor without adjustment for $t$ is 4 and after factor adjustment for time, it increases to 31.
Answer: The full quote is :

In some cases, adding a time trend can make a key explanatory variable more significant. This
can happen if the dependent and independent variables have different kinds of trends (say, one upward
and one downward), but movement in the independent variable about its trend line causes movement
in the dependent variable away from its trend line.

I did not fully follow. However I would like to share my incomplete understanding.
What is this conversation all about ? It is about spurious regression.
What is spurious regression ? It results from a kind of omitted variable bias where the time trend is the omitted variable.
Now, when we omit variables correlated with one of the explanatory variables the coefficient of the explanatory variable may be biased upwards or downwards. In simple examples the bias is upwards ie on including the time trend the explanatory variable becomes less significant. The author is trying to describe a case where the explanatory variable becomes more significant on adding a time trend. That is the key point.
I think, the author is trying to say that time affects the dependent and independent variable in opposite ways. One positive and one negative.
Further, the independent variable x moves about its trend. When it moves about its  trend it may cause the dependent variable y to move more or less about it's trend.
Let's us consider the case when y moves more about it's trend. I think this is what the author means when he says

movement in the independent variable about its trend line causes movement in the dependent variable away from its trend line.

Notice: in this case when x goes from below its  trend to above it's trend it will induce positive correlation between y and x.
So there is positive correlation between y and x (due to movement of x around it's trend) and then there is a negative correlation between y and x due to the time trend.
When I control for the time variable, x will have a +ve coefficient.
When I ignore the time variable, the common negative correlation due to the omitted variable bias will cause the coefficient of x to be less positive.
In other words: on adding a time trend the coefficient of the explanatory variable will become more significant.
PS: I am not 100% certain of this.


Como usar o servlet context listener para iniciar um servlet assim qua a aplicação for carregada?

Question: Tenho o seguinte servlet declarado no web.xml e gostaria que ele fosse inicializado antes de qualquer um dos outros servlets da aplicação:
<servlet>
    <servlet-name>ListarFilmesIndex</servlet-name>
    <servlet-class>br.com.corporacao.servlets.ListarFilmesIndex</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>ListarFilmesIndex</servlet-name>
    <url-pattern>/ListarFilmesIndex</url-pattern>
</servlet-mapping>
<listener>
    <listener-class>
        br.com.corporacao.servlets.InicializacaoServletContextListener
    </listener-class>
</listener>

Tentei implementar a classe que usa ServletContextListener:
package br.com.corporacao.servlets;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class InicializacaoServletContextListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent e) {

    }

    public void contextDestroyed(ServletContextEvent e) {

    }
}

Mas não consigo instanciar dentro do método contextInitialized o servlet ListarFilmesIndex que usa um DAO para carregar todos os filmes que estão cadastrados no banco de dados.
Quando tento instanciar a classe ListarFilmesIndex não sei o que fazer com o request e o response que são necessários para o servlet, e então quando executo a aplicação é lançada uma NullPointerException.
Já tentei de tudo e pesquisei mas não encontrei nada, apenas exemplos de filtros e de classes que não são servlets.
O que devo fazer?
Answer: Acho que você está bem próximo da solução, mas indo pelo caminho errado.
Primeiro, você fez certo em usar a tag <load-on-startup>. Isto faz com que o Servlet seja inicializado durante a inicialização da aplicação.
Porém, um context listener não serve para instanciar servlets. Ele apenas permite executar alguma ação exatamente depois da aplicação iniciar e antes de atender a qualquer requisição.
De qualquer forma, para inicializar valores em servlets, não é necessário um listener. Basta sobrescrever método init no seu servlet. Exemplo:
public class CatalogServlet extends HttpServlet {
    private BookDBAO bookDB;
    public void init() throws ServletException {
        bookDB = (BookDBAO)getServletContext().
            getAttribute("bookDB");
        if (bookDB == null) throw new
            UnavailableException("Couldn't get database.");
    }
}

Outro detalhe, é que você não precisa garantir que esse servlet seja inicializado antes dos outros. Isso porque nenhum servlet vai executar antes da inicialização completa da aplicação, que inclui inicializar e chamar o método init de todos os servlets com a tag <load-on-startup>.
Entretanto, se realmente a ordem importa, basta deixar os outros servlets sem a tag de inicialização ou colocar valores maiores que 1.


Combo box in datagrid not updating correctly

Question: I am binding a combobox selected index to an integer value (Mode) in my viewmodel.  It seems to work except when I try to change the value in the combobox it will not change the selected index/value.
Xaml:

<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
         <ComboBox
             ItemsSource="{Binding Source={StaticResource modeValues}}"
             SelectedIndex="{Binding Mode, Mode=TwoWay}"
          />
    </DataTemplate>
 </DataGridTemplateColumn.CellTemplate>

public int Mode
    {
        get { return _mode; }
        set
        {
            _mode = value;
            NotifyPropertyChanged("Mode");
        }
    }

Comment: When you say it will not change the "selected index/value" are you referring to the value in the ViewModel or something else? When you change the ComboBox selection the Mode property on the ViewModel is what will change. Are you expecting different behavior?
Comment: I mean the value in the combo box in the grid
Answer: Turns out I needed a Cell template and a CellEditingTemplate.
<DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding ModeText}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
                <DataGridTemplateColumn.CellEditingTemplate>
                    <DataTemplate>
                        <ComboBox
                            ItemsSource="{Binding Source={StaticResource modeValues}}"
                            SelectedIndex="{Binding Mode, Mode=TwoWay}"
                        />
                    </DataTemplate>
                </DataGridTemplateColumn.CellEditingTemplate>
            </DataGridTemplateColumn>


Writing the likelihood function for a linear combination of Normal and Laplacian random variables

Question: I am working on a probability problem to solidify my knowledge and running into some difficulty.
I have the following setup:

Let $W_{i}, W_{j}$ represent 2 i.i.d random variables, drawn from $N(0,1)$. $W_{i}$ and $W_{j}$ represent the individual skill of 2 chess players, $i$ and $j$ respectively.
Let $v$ ~ $Laplace(0, \frac{1}{2})$ represent some variability of game $g$ between player $i$ and $j$ (time of day, weather, current state of both players etc.).
Define $y = sign(W_{i} - W_{j} + v)$ to be the outcome of game $g$. $y = -1$ if player $i$ wins and $y = +1$ if player $j$ wins.

This is where I am stuck: how do I write out the likelihood $P(y | W)$? I know the difference of 2 independent normal variables $X_1$ ~ $N(\mu_1, \sigma_1)$ and $X_2$ ~ $N(\mu_2, \sigma_2)$ is $X_1 - X_2$ ~ $N(\mu_1 - \mu_2, \sqrt(\sigma_1^{2} + \sigma_2^{2}))$, but that's as far as I've gotten.
Additionally, I am trying to write the joint probability $P(y, W)$, but unsure how to.
Any pointers or ressources would be appreciated. Thanks!
Comment: You need to compute the density of $(X_1-X_2)+V$ which is a convolution of a Normal and a Laplace. The resulting distribution of $Y$ is immediate.
Answer: Let us discuss how to find $P(y|W)$, which is your first part of the question.
I imagine that when you write $P(y|W)$ you mean that $W = W_i - W_j$, which we should really call $W_1 - W_2$ since there are only two players. Let us say that $W$ (random variable) has a known value equal to $w$. We want to find the likelihood function of $y$ given that $W=w$. Since $y=\pm 1$, once we figure out where $y=+1$, then the complement is when it will be $-1$, so let us focus on the condition when $\text{sgn}(w+v) > 0$. This condition is satisfied when $v>-w$. Recall that $v\sim \text{Lap}(0,\tfrac{1}{2})$, so the probability that $v>-w$ is equal to $\int_{-w}^{\infty} e^{-2|x|} ~ dx $.
The value of that integral will depend on whether $w>0$ or $w<0$ (because of the presence of absolute values in the integral). If $w<0$ then that integral is equal to $\tfrac{1}{2}e^{2w}$. If $w>0$ then that integral is equal to $\int_{-w}^{\infty} = \int_{-w}^0 + \int_0^{\infty}$, which computes to be $(\tfrac{1}{2} - \tfrac{1}{2}e^{-2w}) + \tfrac{1}{2} = 1 - \tfrac{1}{2}e^{-2w}$.
We can summarize our answer, by saying that,
$$ P(y=+1|W=w) = \tfrac{1}{2}\left(1+\text{sgn}(w) - \text{sgn}(w)e^{-2|w|}\right)$$
Comment: @nicolas-bourkaki Many thanks for your answer, this helps quite a bit. Adding a few details for clarification: There are more than one game and more than 2 players, and I initially simplified. My goal is to find $W_{MLE} = argmax_{W} P(y | W)$ (by eventually using [MH](https://en.wikipedia.org/wiki/Metropolis–Hastings_algorithm)). Using your methodology, I derived $P(y = -1 | W = w) = \frac{1}{2} (1 - sgn(w) + sgn(w)e^{-2|w|})$
Comment: Would you know how I may go about the joint probability $P(y, W)$? Thank you.


Comments not showing up when set to open and assigned a region in manage display in drupal 7

Question: I just set my comments for my content type to "open" and assigned the comment field to show up in the full content manage display. But it doesnt show up when viewing in my full display node. I tried changing the theme and it still doesnt show up. How can I debug something like this?
Comment: Make sure your theme's [node.tpl.php](https://api.drupal.org/api/drupal/modules%21node%21node.tpl.php/7.x) has `print render($content['comments']);`
Comment: doesn't look like my node.tpl.php is loading. maybe because im using display suite.
Answer: My issue was that comments was "CLOSED" for the nodes I already created as the default setting initially was set as "CLOSED". Even thought I set the comment settings to OPEN on the content type, this doesn't affect previously created work.
Solution was to bulk update all the nodes types to open comments with the following sql:
<code>UPDATE node SET comment = 0 WHERE type LIKE "MY_NODE_TYPE_HERE";
</code>


Show by an example that a proper closed subset of $\mathbb{R}$ in the sandard (order) topology need not be compact.

Question:
In my mind, I can think of below example which seems to work.
If $(X,T) = \mathbb{R}$, and $A = (0,\infty)$, then as far as I know it comes in the standard (order) topology of $\mathbb{R}$, but what I dont know is whether it will be a proper closed subset of $\mathbb{R}$. If it works, then it will be perfect b/c for all positive integer $i$, if I let $P_i$ be the open interval $(0,i)$, then clearly $A \subset \cup$ $O_i$, where $i = 1$ to $\infty$,
however there doesnt exist $i_1, i_2,......, i_n$, such that $A \subset (0,i_1),(0,i_2),....,(0,i_n)$, therefore by the definition of compactness we can see that we dont have a finite sub-cover, so its not compact.
Kindly check my proof, let me know if there is anything wrong. Also, give it better style and notation if required.
Comment: $A$ is a proper subset, but it is not closed. However, $[0, \infty)$ is closed in the standard topology of $\Bbb{R}$.
Comment: @peek-a-boo it says standard (order) topology, can u show me how its closed in that on $\mathbb{R}$ ?
Comment: The complement of $[0, \infty)$ is $(-\infty, 0)$, which is an open interval (and hopefully you've proven that open intervals form a basis for the standard topology). Since the complement is open, it follows that the original set is closed (by definition).
Answer: The set $(0,\infty)$ is not closed. But $[0,\infty)$ will work. For instance, the sequence $1,2,3,\ldots$ has no convergent subsequence. Or you can say that $\{[0,n)\mid n\in\mathbb N\}$ is an open cover with no finite subcover.
Comment: $[0,n)$ is not an open set for any natural $n$.
Comment: I was thinking of this, however $[0,\infty)$ is not a closed proper subset, its a half open interval. Also, how will b the standard (order) topology if I choose that? Standard (order) topology is the topology generated by the sub-basis consisting of positive and negative open rays. Here, I can think of NOR = $(0, \infty)$ but I am not sure whether POR will be $(-\infty, 0)$ or not. Regarding the open and finite sub-cover I will have to check. I am working on that bt I got a doubt before that so thought of asking it.
Comment: @Martund It *is* an open subset of $[0,\infty)$.
Comment: @Math_Is_Fun I claim that $[0,\infty)$ is a proper subset of $\mathbb R$ and that it is a closed subset of $\mathbb R$. Do you disagree with any of these assertions?
Comment: But we are considering $\Bbb R$ as the universal set, not $[0,\infty)$. We are viewing $[0,\infty)$ also as a subset of $\Bbb R$.
Comment: @Martund Then consider $\{(-1,n)\mid n\in\mathbb N\}$ instead.
Comment: @JoséCarlosSantos No I dont, I got your idea now.
Comment: @JoséCarlosSantos u can consider  {(−n,n)|n∈N} this instead, this will work perfectly. I have checked it.
Answer: Noting that any bounded closed subset of $\mathbb{R}$ is compact, so we need to think of unbounded closed subsets like: $$[a,\infty), \mathbb{N}, \ldots$$
Answer: Let $A = [0, \infty)$, then its complement $A^c = (-\infty, 0)$ is an open interval, and hence $A^c$ is an open set. Thus, by definition, $A$ is a closed set.
To show it is not compact, consider the following open cover: $\{(-n,n)| \, \, n \in \Bbb{N}\}$. This open cover in fact covers all of $\Bbb{R}$, so in particular covers $A$. Clearly, there is no finite subcover. Hence, $A$ is not compact.
Comment: wat will be the sub-basis of $A$? I guess $(-\infty,0) \cup [0,\infty)$, still correct me if I am wrong
Comment: @Math_Is_Fun why do you need a subbasis?
Comment: just asking, I might have to show that while writing the proof. My prof loves 2 see all d details.
Answer: By Heine-Borel, a compact subset of $\Bbb R^n$ is closed and bounded.
So take any closed, unbounded set.


Postifx Dovecot lmtp, sieve not working

Question: My mail server has a problem. I want to install sieve, but the rules do not work.
As far as I found out, I think the handover at lmtp to dovecot does not work.
e-mails can be received and sent, but the rules do not work.
If I stop dovecot the mail is still stored in /var/vmail
Where is the mistake?
Debian 9.5
Postfix 3.1.8
Dovecot 2.2.27
Mail log when an email is received
Aug 30 22:46:09 vps582284 postfix/smtpd[28317]: connect from mx09lb.world4you.com[126.96.36.199]
Aug 30 22:46:09 vps582284 postfix/smtpd[28317]: 856843F6A9: client=mx09lb.world4you.com[220.127.116.11]
Aug 30 22:46:09 vps582284 postfix/cleanup[28323]: 856843F6A9: message-id=<email@example.com>
Aug 30 22:46:09 vps582284 postfix/qmgr[28309]: 856843F6A9: from=<email@example.com>, size=1923, nrcpt=1 (queue active)
Aug 30 22:46:09 vps582284 postfix/virtual[28324]: 856843F6A9: to=<email@example.com>, relay=virtual, delay=0.17, delays=0.15/0.01/0/0.01, dsn=2.0.0, status=sent (delivered to maildir)
Aug 30 22:46:09 vps582284 postfix/qmgr[28309]: 856843F6A9: removed
Aug 30 22:46:09 vps582284 postfix/smtpd[28317]: disconnect from mx09lb.world4you.com[220.127.116.11] ehlo=2 starttls=1 mail=1 rcpt=1 data=1 quit=1 commands=7

doveconf -n
# 2.2.27 (c0f36b0): /etc/dovecot/dovecot.conf
# Pigeonhole version 0.4.16 (fed8554)
doveconf: Warning: NOTE: You can get a new clean config file with: doveconf -n > dovecot-new.conf
doveconf: Warning: Obsolete setting in /etc/dovecot/dovecot.conf:150: listen=..:port has been replaced by service { inet_listener { port } }
doveconf: Warning: Obsolete setting in /etc/dovecot/dovecot.conf:150: protocol { listen } has been replaced by service { inet_listener { address } }
doveconf: Warning: NOTE: You can get a new clean config file with: doveconf -n > dovecot-new.conf
doveconf: Warning: Obsolete setting in /etc/dovecot/dovecot.conf:150: listen=..:port has been replaced by service { inet_listener { port } }
doveconf: Warning: Obsolete setting in /etc/dovecot/dovecot.conf:150: protocol { listen } has been replaced by service { inet_listener { address } }
# OS: Linux 4.9.0-7-amd64 x86_64 Debian 9.5
auth_mechanisms = plain login
disable_plaintext_auth = no
mail_debug = yes
mail_location = mbox:~/mail:INBOX=/var/mail/%u
managesieve_notify_capability = mailto
managesieve_sieve_capability = fileinto reject envelope encoded-character vacation subaddress comparator-i;ascii-numeric relational regex imap4flags copy include variables body enotify environment mailbox date index ihave duplicate mime foreverypart extracttext
namespace inbox {
  inbox = yes
  location =
  mailbox Archive {
    auto = subscribe
    special_use = \Archive
  }
  mailbox Drafts {
    auto = subscribe
    special_use = \Drafts
  }
  mailbox Junk {
    auto = subscribe
    special_use = \Junk
  }
  mailbox Sent {
    auto = subscribe
    special_use = \Sent
  }
  mailbox "Sent Messages" {
    special_use = \Sent
  }
  mailbox Trash {
    auto = subscribe
    special_use = \Trash
  }
  prefix =
  separator = /
}
passdb {
  args = /etc/dovecot/dovecot-sql.conf
  driver = sql
}
plugin {
  mail_debug = yes
  sieve = /var/vmail/%d/%n/sieve
  sieve_dir = /var/vmail/%d/%n/sieve-scripts
  sieve_storage = /var/vmail/%d/%n/sieve-scripts
}
protocols = imap lmtp sieve
service auth {
  unix_listener /var/spool/postfix/private/auth {
    group = postfix
    mode = 0660
    user = postfix
  }
}
service imap-login {
  inet_listener imaps {
    port = 993
    ssl = yes
  }
}
service lmtp {
  unix_listener lmtp {
    group = postfix
    mode = 0600
    user = postfix
  }
}
ssl = required
ssl_cert = </etc/letsencrypt/live/dest-domain.com/fullchain.pem
ssl_cipher_list = EDH+CAMELLIA:EDH+aRSA:EECDH+aRSA+AESGCM:EECDH+aRSA+SHA256:EECDH:+CAMELLIA128:+AES128:+SSLv3:!aNULL:!eNULL:!LOW:!3DES:!MD5:!EXP:!PSK:!DSS:!RC4:!SEED:!IDEA:!ECDSA:kEDH:CAMELLIA128-SHA:AES128-SHA
ssl_dh_parameters_length = 2048
ssl_key =  # hidden, use -P to show it
ssl_prefer_server_ciphers = yes
userdb {
  args = /etc/dovecot/dovecot-sql.conf
  driver = sql
}
protocol lmtp {
  mail_plugins = " sieve"
  postmaster_address = firstname.lastname@example.com
}

postconf -n
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
append_dot_mydomain = no
biff = no
compatibility_level = 2
inet_interfaces = all
inet_protocols = all
local_transport = virtual
mailbox_size_limit = 0
mydestination = $myhostname, localhost dest-domain.com
myhostname = mail.dest-domain.com
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
readme_directory = no
recipient_delimiter = +
relayhost =
smtp_tls_ciphers = high
smtp_tls_security_level = may
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
smtpd_recipient_restrictions = reject_non_fqdn_sender, reject_non_fqdn_recipient, reject_unknown_sender_domain, reject_unknown_recipient_domain, permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination, reject_rbl_client zen.spamhaus.org, reject_rbl_client ix.dnsbl.manitu.net, reject_unverified_recipient, permit
smtpd_relay_restrictions =
smtpd_sasl_auth_enable = yes
smtpd_sasl_path = private/auth
smtpd_sasl_type = dovecot
smtpd_tls_auth_only = yes
smtpd_tls_cert_file = /etc/letsencrypt/live/dest-domain.com/fullchain.pem
smtpd_tls_ciphers = high
smtpd_tls_dh1024_param_file = /etc/letsencrypt/live/dest-domain.com/dh.pem
smtpd_tls_key_file = /etc/letsencrypt/live/dest-domain.com/privkey.pem
smtpd_tls_security_level = may
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtpd_use_tls = yes
tls_high_cipherlist = EDH+CAMELLIA:EDH+aRSA:EECDH+aRSA+AESGCM:EECDH+aRSA+SHA256:EECDH:+CAMELLIA128:+AES128:+SSLv3:!aNULL:!eNULL:!LOW:!3DES:!MD5:!EXP:!PSK:!DSS:!RC4:!SEED:!IDEA:!ECDSA:kEDH:CAMELLIA128-SHA:AES128-SHA
virtual_alias_maps = proxy:mysql:/etc/postfix/sql/mysql_virtual_alias_maps.cf, proxy:mysql:/etc/postfix/sql/mysql_virtual_alias_domain_maps.cf, proxy:mysql:/etc/postfix/sql/mysql_virtual_alias_domain_catchall_maps.cf
virtual_gid_maps = static:5000
virtual_mailbox_base = /var/vmail
virtual_mailbox_maps = proxy:mysql:/etc/postfix/sql/mysql_virtual_mailbox_maps.cf, proxy:mysql:/etc/postfix/sql/mysql_virtual_alias_domain_mailbox_maps.cf
virtual_transport = lmtp:unix:private/dovecot-lmtp
virtual_uid_maps = static:5000
postconf: warning: /etc/postfix/main.cf: unused parameter: dovecot_destination_recipient_limit=1

thank you,
daniel
Comment: your dovecot lmtp service block is suspect with its permission and relative path. In your postfix main.cf you have `virtual_transport = lmtp:unix:private/dovecot-lmtp` which if your master.cf chroot's the process, translates to `/var/spool/postfix/private/dovecot-lmtp`. So your `unix_listener` in your dovecot  `service lmtp` block probably needs to be `unix_listener /var/spool/postfix/private/dovecot-lmtp`. And both dovecot and postfix need to be able to access the socket, but you have the permission set to `0600`.
Comment: Also, in your dovecot `protocol lmtp` block, I have never seen mail_plugins set as `" sieve`. I would expect to see `mail_plugins = sieve` but I don't know if this causes a problem or not.
Answer: Dovecot's sieve is invoked on local delivery performed by deliver utility bundled with dovecot. Your setup do not used the deliver and perform LDA by postfix that isn't related to the sieve. You have to change the postfix configuration the way described here: https://wiki.dovecot.org/LDA/Postfix

Postifx Dovecot lmtp, sieve not working


Let's get critical: May 2015 Site Self-Evaluation

Question: We all love Economics Stack Exchange, but there is a whole world of people out there who need answers to their questions and don't even know that this site exists. When they arrive from Google, what will their first impression be? Let's try to look at this site through the eyes of someone who's never seen it before, and see how we stack up against the rest of the 'Net.
The Site Self-Evaluation review queue is open and populated with 10 questions that were asked and answered in the last quarter.
Run a few Google searches to see how easy they are to find and compare the answers we have with the information available on other sites.
Rating the questions is only a part of the puzzle, though. Do you see a pattern of questions that should have been closed but are not? Questions or answers that could use an edit? Anything that's going really well? Post an answer below to share your thoughts and discuss these questions and the site's health with your fellow users!
Answer: Final Results

Why does Slutsky compensation "overcompensate" the consumer?

Net Score: 10 (Excellent: 10, Satisfactory: 5, Needs Improvement: 0)

What does a supply+demand curve look like for fare evasion?

Net Score: 8 (Excellent: 10, Satisfactory: 3, Needs Improvement: 2)

From Discrete to Continuous Time

Net Score: 6 (Excellent: 9, Satisfactory: 2, Needs Improvement: 3)

on economic growth and Second Welfare theorem

Net Score: 5 (Excellent: 6, Satisfactory: 8, Needs Improvement: 1)

Asymmetric vs incomplete information

Net Score: 4 (Excellent: 8, Satisfactory: 5, Needs Improvement: 4)

Is Marginal Rate of Substitution a multivariable function?

Net Score: 3 (Excellent: 7, Satisfactory: 7, Needs Improvement: 4)

Modelling Pay what you want

Net Score: 1 (Excellent: 4, Satisfactory: 6, Needs Improvement: 3)

https://economics.stackexchange.com/questions/5234/why-low-labour-productivity-in-finance-insurance-real-estate-and-business-ser

Net Score: -1 (Excellent: 3, Satisfactory: 6, Needs Improvement: 4)

How to work out average income based on square meter of property rented

Net Score: -2 (Excellent: 4, Satisfactory: 4, Needs Improvement: 6)

Why are labor, capital, and land traditionally denoted by the letters L, K, and T?

Net Score: -2 (Excellent: 3, Satisfactory: 5, Needs Improvement: 5)