Entrar em página usando o ID do banco em ASP.NET

Question: Preciso fazer uma página que possa ser acessada no seguinte formato:
www.exemplo.com/id/123qwe
Esse 123qwe é o ID de uma linha da base de dados, onde pegarei todos os dados pra preencher a página.
Até agora consegui fazer www.exemplo.com/id/id.aspx?id=123qwe usando:
<%=Request.QueryString["id"] %>

Como faço para utilizar www.exemplo.com/id/123qwe em vez de www.exemplo.com/id/id.aspx?id=123qwe?
Comment: você está usando webForms ou MVC?
Answer: Você pode usar ASP.NET MVC, que implementa isso automaticamente para você. A rota padrão de um projeto MVC (já criada de início) é a seguinte:
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { action = "Index", id = UrlParameter.Optional }
);

O que significa que você teria uma URL do tipo Home/Index/123qwe funcionando por default. Aí bastaria ler esse ID no seu controler e usá-lo:
public ActionResult Index(string id)

Comment: Estou usando um projeto ASP.Net Webforms com DevExpress.

Essa rota eu configuro onde?
Comment: Não tem como @GutoSchiavon isso é ASP.NET MVC e não WebForms. tem que converter sua aplicação para usar isso.
Comment: @GutoSchiavon você poderia até configurar rotas no seu Web Forms, mas acredite, não vale a pena pelo esforço. Recomendo fortemente a adoção do padrão MVC, junto a outros frameworks  nativos que te ajudarão bastante em suas tarefas (especialmente o Entity Framework, de início, atrelado ao MVC).
Comment: Seu projeto ainda está no início? Se sim, vale o esforço em adaptar ao MVC!
Comment: Sim @TiagoCésarOliveira, meu projeto está no inicio. Vou tentar a adaptação para o MVC. Obrigado pela ajuda.
Comment: @GutoSchiavon disponha! Se estiver usando o Visual Studio 2012 ou 2013, já use a versão 5 do MVC...
Comment: @TiagoCésarOliveira ainda estou na versão 2010, visto que é a versão usada pela empresa onde estagio.
Comment: Nesse caso acho que vc tem acesso ao MVC 4 que também é uma boa
Answer: Se você estiver usando ASP.NET WebForms teria de criar um HttpHandler ou usar o RouteCollection. No caso do ASP.NET MVC basta adicionar uma rota.
ASP.NET WebForms - Forma 1 (qualquer versão)
Criando a rota:
public class EmployeeHandlerFactory : IHttpHandlerFactory
{
   ...

   public IHttpHandler GetHandler(HttpContext context,
     string requestType, string url, string pathTranslated)
   {
      // determine the employee's name
      string empName =
        Path.GetFileNameWithoutExtension(
        context.Request.PhysicalPath);

      // Add the Employee object to the Items property
      context.Items.Add("Employee Info",
        EmployeeFactory.GetEmployeeByName(empName));

      // Get the DisplayEmployee.aspx HTTP handler
      return PageParser.GetCompiledPageInstance(url,
        context.Server.MapPath("DisplayEmployee.aspx"), context);
   }
}

Criando a página
public class DisplayEmployee : System.Web.UI.Page
{
   // three Label Web controls in HTML portion of page
   protected System.Web.UI.WebControls.Label lblName;
   protected System.Web.UI.WebControls.Label lblSSN;
   protected System.Web.UI.WebControls.Label lblBio;

   private void Page_Load(object sender, System.EventArgs e)
   {
      // load Employee information from context
      Employee emp = (Employee) Context.Items["Employee Info"];

      if (emp != null)
      {
         // Assign the Employee properties to the Label controls
         lblName.Text = emp.Name;
         lblSSN.Text = emp.SSN;
         lblBio.Text = emp.Biography;
      }
   }

Atualizando o web.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <httpHandlers>

      <add verb="*" path="*.info"
         type="skmHttpHandlers.EmployeeHandlerFactory,
         skmHttpHandlers" />
    </httpHandlers>
  </system.web>
</configuration>}

Efeito final:

ASP.NET WebForms - Forma 2 (Apenas ASP.NET 3.5+)
No arquivo Global.asax inclua:
protected void Application_Start(object sender, EventArgs e)
{
    RegisterRoutes(RouteTable.Routes);
}

public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapPageRoute("",
        "Category/{action}/{categoryName}",
        "~/categoriespage.aspx");
}

ASP.NET MVC
Adicione a rota diretamente na classe de sua aplicação:
public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );

    }

    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
    }
}

Comment: Excelente resposta, @AlexandreMarcondes.
Comment: Obrigado @TiagoCésarOliveira. Quero traduzir as variáveis do código, mas estou corrido com algumas coisas aqui. Em breve devo fazer isso.
Comment: @AlexandreMarcondes, como faço para editar isso para o meu projeto? Ainda não compreendi esse Category, action, etc. No meu projeto, usando WebForms (3.5+), como ficaria? Preciso acessar exemplo.com/id/123qwe (que seria exemplo.com/id/index.php?id=123qwe) e depois pegar o id '123qwe' no código.

Tentei: routes.MapPageRoute("",
                    "id/{id}",
                    "~/index.aspx"); e não foi.
Comment: @GutoSchiavon que erro deu nesse exemplo que você tentou? Ou simplesmente não funciona sem dar erro?
Comment: Ao tentar acessar http://localhost:56619/id/123qwe, ele diz reporta "Não é possível encontrar o recurso".
Comment: Mas @GutoSchiavon, tem um registro com esse id no banco?
Comment: Sim, tem sim. O erro não de não ter registro  e sim de não encontrar a página.
Comment: Você usou qual técnica?
Comment: Consegui agora: | routes.MapPageRoute("identificao", "id/{id}", "~/id.aspx", false, new RouteValueDictionary { { "id", "1" } }); |. Agora como faço pra recuperar esse ID no meu Select, dentro do SQL Data Source?
Comment: Edita sua pergunta coloca uma barra separando e coloca o código que você usou, por favor. Adiciona isso na pergunta que vai ajudar muito as pessoas e ajudar a entender em que ponto você está. Não esquece de falar como está fazendo a conexão com banco de dados: entity framework, ado, etc.
Answer: .Net 4.0 em diante já é possível usar as rotas do MVC em projeto webforms, eu mesmo uso.
No Global.asax você deve registrar as rotas.
routes.MapPageRoute("SalesRoute",
      "SalesReport/{locale}/{year}",
      "~/sales.aspx");

E para acessar o valor na página aspx você usa o seguinte código:
Page.RouteData.Values["locale"]
Page.RouteData.Values["year"]

Comment: No caso, aplicando ao meu projeto, como ficaria? ainda não consegui entender mto bem a sintaxe das rotaas.
Comment: Adiciona o código que registra a rota para sua página aspx, lá no arquivo Global.asax, no método Start.  RouteTable.Routes.MapPageRoute("SalesRoute" ...
Comment: @GutoSchiavon Veja aquin na minha resposta como fazer: http://pt.stackoverflow.com/a/7087/280


Python parameter behavior

Question: My understanding of function parameters in Python is that they are like empty objects until function call and that's it. eg.
def square(x): #where x is an empty var defined here.
    return x*x #for the scope of this function

So how does this work, where "NamedTuple" is a callback function I assume? Does "NamedTuple" return value gets used as the parameter to class Car()?
>>> from typing import NamedTuple

>>> class Car(NamedTuple):
...     color: str
...     mileage: float
...     automatic: bool

>>> car1 = Car("red", 3812.4, True)

>>> # Instances have a nice repr:
>>> car1
Car(color='red', mileage=3812.4, automatic=True)

Comment: `class Foo(something)` isn't a function (it's a class definition) and `something` isn't a parameter (it's an inheritance list). I'm voting to close as a misunderstanding/unhelpful to future visitors; see [the docs](https://docs.python.org/3/tutorial/classes.html#inheritance).
Comment: I suggest you read more about classes and inheritence. There is no function call here.
Comment: Coming from javascript? In Python, "class" is a core part of the language rather than syntatic sugar.
Comment: @PaulBecotte Yes I'am! Thank you took me a while to figure that out.
Answer: class Car(NamedTuple): is a class declaration, not a function call. NamedTuple is a class that Car is derived from.
Answer: No, NamedTuple is not a function, but a class. This is called inheritance (or subclassing), more about it here.

Python parameter behavior


lilypond:: tacet

Question: In German music-notation, we know the term "tacet" in order to say the musician not to play his chords for a while. How can that be typeset with lilypond? It's similar to "N.C.", but in most common books the text "tacet" is printed.
Comment: "Tacet' is used internationally.
Answer: It depends on how you want the tacet to be printed. A simple
R1*20 ^ \markup{Tacet}

will print the word 'Tacet' above the staff:

Combine it with \compressFullBarRests for a short version:
Comment: Ah, I'm using it in regular mode.
Comment: Thanks for your fast reply. I've tried:

the definition
CMString  = { -\markup { \whiteout { \hspace #-2 "Tacet" } } }
CMStringX = #(append (sequential-music-to-chord-exceptions CMString #t)
           ignatzekExceptions)

and use:

   \set   chordNameExceptions = #CMStringX c
   \unset chordNameExceptions

but my "a" is always overlined. Any idea?
Comment: Trying ^ }markup{tacet} in chordmode results in errors

lilypond:: tacet


Improved Markov inequality when I have higher moments?

Question: If I have all the first $n$ moments of a discrete random variable $Z$ defined on the non-negative integers $$\mathbb{E}(Z),\mathbb{E}(Z^2),\dots,\mathbb{E}(Z^n)$$ but desire $P(Z \geq 1)$, Markov's inequality can bound this from above with $\mathbb{E}(Z)$.
Can I do better using the remaining $(n-1)$ moments at my disposal? Are there better bounds on $P(Z \geq 1)$ which are more precise when more moments are incorporated?
Comment: Depends on the distribution. For example if $P(Z=0)=0$ then $Z \geq 1$ a.s. so $EZ\leq EZ^{2}\leq EZ^{3}...$  in which case the best bound is given by $P(Z\geq 1) \leq EZ$.
Comment: $P(Z\geq 1)=P(Z^k\geq 1)\leq EZ^k$. In this way you can use all the first $n$ moments.
Comment: This gives new bounds, but I think the idea is to use the $\inf_{k \geq 0}\mathbb{E}Z^{k}$, which gives something equivalent to the Chernoff bound. The bounds are not necessarily any better, often being optimal for $k=1$.
Answer: One can use the factorial moment bound
$$P(Z \geq 1) = 1 - \sum_{i \geq 0} \frac{(-1)^i}{i!}\mathbb{E}\left[\left( Z\right)_i\right]$$
where $\left( Z\right)_i = Z(Z-1)\dots(Z-i+1)$ is the descending factorial.
Comment: One thing, can this work with approximate moments?


Slow ssh login - Activation of org.freedesktop.login1 timed out

Question: On one of my servers I've noticed really delay on SSH logins.
Connecting using the ssh -vvv options the delay occurs at debug1: Entering interactive session.
extract of connection:
debug1: Authentication succeeded (publickey).
Authenticated to IP_REDACTED ([IP_REDACTED]:22).
debug1: channel 0: new [client-session]
debug3: ssh_session2_open: channel_new: 0
debug2: channel 0: send open
debug1: Requesting firstname.lastname@example.com
debug1: Entering interactive session.
debug2: callback start
debug2: fd 3 setting TCP_NODELAY
debug3: packet_set_tos: set IP_TOS 0x10
debug2: client_session2_setup: id 0
debug2: channel 0: request pty-req confirm 1

using the method outlined here I generated strace output and noticed the line 14:09:53.676004 ppoll([{fd=5, events=POLLIN}], 1, {24, 999645000}, NULL, 8) = 1 ([{fd=5, revents=POLLIN}], left {0, 0}) <25.020764> which takes 25 seconds.
extract of strace output:
14:09:53.675567 clock_gettime(CLOCK_MONOTONIC, {4662549, 999741404}) = 0 <0.000024>
14:09:53.675651 recvmsg(5, {msg_name(0)=NULL, msg_iov(1)=[{"l\4\1\1\n\0\0\0\2\0\0\0\215\0\0\0\1\1o\0\25\0\0\0", 24}], msg_controll
en=0, msg_flags=MSG_CMSG_CLOEXEC}, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) = 24 <0.000024>
14:09:53.675744 recvmsg(5, {msg_name(0)=NULL, msg_iov(1)=[{"/org/freedesktop/DBus\0\0\0\2\1s\0\24\0\0\0"..., 146}], msg_controllen
=0, msg_flags=MSG_CMSG_CLOEXEC}, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) = 146 <0.000025>
14:09:53.675842 recvmsg(5, 0x7ffe0ff1dfa0, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) = -1 EAGAIN (Resource temporarily unavailab
le) <0.000023>
14:09:53.675925 clock_gettime(CLOCK_MONOTONIC, {4662550, 96075}) = 0 <0.000024>
14:09:53.676004 ppoll([{fd=5, events=POLLIN}], 1, {24, 999645000}, NULL, 8) = 1 ([{fd=5, revents=POLLIN}], left {0, 0}) <25.020764>
14:10:18.696865 recvmsg(5, {msg_name(0)=NULL, msg_iov(1)=[{"l\3\1\0013\0\0\0\3\0\0\0m\0\0\0\6\1s\0\5\0\0\0", 24}], msg_controllen=0,     msg_flags=MSG_CMSG_CLOEXEC}, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) = 24 <0.000017>
14:10:18.696944 recvmsg(5, {msg_name(0)=NULL, msg_iov(1)=[{":1.10\0\0\0\4\1s\0#\0\0\0org.freedesktop."..., 155}], msg_controllen=0, msg_flags=MSG_CMSG_CLOEXEC}, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) = 155 <0.000018>

I have noticed an entry in the auth logs at the relevant time:
Jul 21 14:10:18 click sshd[8165]: pam_systemd(sshd:session): Failed to create session: Activation of org.freedesktop.login1 timed out

Not knowing enough about this what is it trying to poll for and why is it now taking 25seconds on this particular server.
The journalctl -u systemd-logind command shows
Jul 20 11:33:06 click systemd-logind[19415]: Failed to abandon session scope: Transport endpoint is not connected
Jul 21 05:04:54 myhost systemd[1]: Started Login Service.
Jul 21 12:15:30 myhost systemd[1]: Started Login Service.
Jul 21 12:17:04 myhost systemd[1]: Started Login Service.
Jul 21 12:49:55 myhost systemd[1]: Started Login Service.
Jul 21 13:57:05 myhost systemd[1]: Started Login Service.
Jul 21 13:58:49 myhost systemd[1]: Started Login Service.
Jul 21 14:01:55 myhost systemd[1]: Started Login Service.
Jul 21 14:08:32 myhost systemd[1]: Started Login Service.
Jul 21 14:09:53 myhost systemd[1]: Started Login Service.
Jul 21 14:19:08 myhost systemd[1]: Started Login Service.
Jul 21 14:21:26 myhost systemd[1]: Started Login Service.
Jul 21 14:22:37 myhost systemd[1]: Started Login Service.
Jul 21 14:25:20 myhost systemd[1]: Started Login Service.
Jul 21 14:30:27 myhost systemd[1]: Started Login Service.
Jul 21 15:02:56 myhost systemd[1]: Started Login Service.

Issuing the command systemctl restart systemd-logind.service fixes it (for now probably).
What is the Activation of org.freedesktop.login1 it mentions?  Is there a way I can prevent having to restart logind in future?  I expect over time I will have this issue with the rest of the servers I manage.
Just noticed this starting to happen on another server.
$ sudo service systemd-logind status

● systemd-logind.service - Login Service
   Loaded: loaded (/lib/systemd/system/systemd-logind.service; static)
   Active: active (running) since Tue 2015-06-16 14:10:57 BST; 1 months 12 days ago
     Docs: man:systemd-logind.service(8)
           man:logind.conf(5)
           http://www.freedesktop.org/wiki/Software/systemd/logind
           http://www.freedesktop.org/wiki/Software/systemd/multiseat
 Main PID: 1701 (systemd-logind)
   Status: "Processing requests..."
   CGroup: /system.slice/systemd-logind.service
           └─1701 /lib/systemd/systemd-logind

Jul 28 13:16:21 myhost systemd[1]: Started Login Service.
Jul 28 13:16:47 myhost systemd[1]: Started Login Service.
Jul 28 16:09:23 myhost systemd[1]: Started Login Service.
Jul 28 16:09:49 myhost systemd[1]: Started Login Service.
Jul 28 16:10:15 myhost systemd[1]: Started Login Service.
Jul 28 16:10:41 myhost systemd[1]: Started Login Service.
Jul 28 22:50:19 myhost systemd[1]: Started Login Service.
Jul 29 05:00:15 myhost systemd[1]: Started Login Service.
Jul 29 11:00:20 myhost systemd[1]: Started Login Service.
Jul 29 11:09:56 myhost systemd[1]: Started Login Service.

EDIT - expanded journalctl output.
EDIT2 - added systemd-logind status as suggested in comments when noticed this starting on another server.
UPDATE - This is starting to happen to the rest of my Jessie servers.  Am I the only one experiencing this?  There must be some fix other than restarting systemd-logind, has anyone any thoughts?
There is a Debian bug report on this 770135.
Comment: It would be useful to see the output of `systemcts status systemd-logind` before restart to see what was wrong with it (exited, failed, whatever). `ppoll` is just a mediator who is waiting for response from systemd so you can't blame it.
Comment: there is no `systemcts` command
Comment: sorry. `systemctl` of course
Comment: I thought that was what you meant but wanted to be sure.  Is that not the same output as is available from the command `journalctl -u systemd-logind`
Comment: it should show the log, but also status of service itself.
Comment: True, didnt run status but expanded `journalctl` output on question from what was left in my terminal.
Comment: @Jakuje Added status out put from other server started to notice slowdown on
Comment: I still have the same Issue, on Ubuntu 16.04.
Comment: See also https://unix.stackexchange.com/q/239489/9454
Comment: FYI, I had this issue with LXC containers in Proxmox and the solution was to enable nesting for the container. [link](https://forum.proxmox.com/threads/lxc-container-upgrade-to-bullseye-slow-login-and-apparmor-errors.93064/)
Answer: This happens when dbus is restarted, but systemd-logind is not restarted. Just do the following:
systemctl restart systemd-logind

The solution is from here:
https://major.io/2015/07/27/very-slow-ssh-logins-on-fedora-22/
Comment: Already stated in question, bug report still unresolved, but thanks for reinstating it.
Comment: Note: this can also give a "login loop" in the regular lightdm greeter; same solution applies.
Answer: Using:
systemctl restart systemd-logind

solves the problem only temporarily.
One workaround is to remove all the .scope files from a cron job, as stated here.
* 2,14 * * * root /bin/rm -f /run/systemd/system/*.scope

The related systemd bug report is here : Leak of scope units slowing down "systemctl list-unit-files" and delaying logins .
It seems that it's in fact a dbus bug : unix fd in-flight counting broken which is solved in dbus version 1.11.10
For a permanent fix of this bug, you just have to wait that this version of dbus appears in your distribution. For now, Debian Stretch is at dbus 1.10.18, Ubuntu 17.04 (Zesty) is at 1.10.10, CentOS 7 is at dbus 1.6.12.


What is the distribution of $\frac{s^2}{10x̅^2}$

Question: For $X_1, ...., X_{10}$, a random sample of size 10 with a normal population with mean 0 and variance $σ^2$ . Let x̅ be the sample mean and $s^2$ be the sample variance. How would one find the distribution of:
$\frac{s^2}{10x̅^2}$
I'm really struggling to figure this one out. (The answer is $F_{9,1}$)
Comment: What is $F_{9,1}$?
Comment: F distribution with degrees of freedom 9 and 1
Answer: Cochran's theorem (see also this answer) implies that
$$\sum_{i=1}^{10} (X_i - \bar{x})^2/ \sigma^2 \sim \chi^2_9$$
and $$10 \bar{x}^2 / \sigma^2 \sim \chi^2_1$$
and that the two are independent.
Thus $$\frac{\left(\sum_{i=1}^{10} (X_i - \bar{x})^2/ \sigma^2\right) / 9}{(10\bar{x}^2 / \sigma^2) / 1} = \frac{s^2}{10 \bar{x}^2}$$
follows the $F_{9,1}$ distribution.


Elmah log entry does not include Server Variables

Question: I Log my errors in Elmah using ErrorLog.GetDefault because I want to use the ErrorId. However when I do this the Server Variables are not included in the log entry. Could anyone explain why and if possible, how to fix this?
public void LogExceptionToElmah(Exception exception)
{
    //Includes Server Variables
    ErrorSignal.FromContext(HttpContext.Current).Raise(exception);

    //Does not include Server Variables
    var elmahId = Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Error(exception));
}

Answer: I was able to solve this by including HttpContext.Current into the Elmah Error.
var elmahId = ErrorLog.GetDefault(HttpContext.Current).Log(new Error(exception, HttpContext.Current));

I still wonder why the ErrorLog.GetDefault requires a HttpContext as it doesn't seem to do anything with it.


Why is ZFS not doing anything with my disk's duff sector?

Question: I was under the impression that if an I/O error occurs during a read
from a ZFS pool, two things will happen:

The failure will be recorded in either the READ or CKSUM statistic of the relevant device, propagating upwards toward the pool level.

Redundant data will be used to reconstruct the requested block, return the requested block to the caller and if the duff drive is still functional rewrite the block to it, OR
An I/O error will be returned if redundant data is not available to correct for the read error.

It appears that one of the disks in my mirror setup has developed a
bad sector. That by itself is not alarming; such things happen, and
that's exactly why I have redundancy (a two-way mirror, to be exact).
Every time I scrub the pool or read through the files in a particular
directory (I haven't bothered yet to determine exactly which file is
at fault), the following pops up in dmesg, obviously with varying
timestamps:
Nov  1 09:54:26 yeono kernel: [302621.236549] ata6.00: exception Emask 0x0 SAct 0x9c10 SErr 0x0 action 0x0
Nov  1 09:54:26 yeono kernel: [302621.236557] ata6.00: irq_stat 0x40000008
Nov  1 09:54:26 yeono kernel: [302621.236566] ata6.00: failed command: READ FPDMA QUEUED
Nov  1 09:54:26 yeono kernel: [302621.236578] ata6.00: cmd 60/a8:78:18:5a:12/00:00:5c:01:00/40 tag 15 ncq 86016 in
Nov  1 09:54:26 yeono kernel: [302621.236580]          res 41/40:a8:18:5a:12/00:00:5c:01:00/00 Emask 0x409 (media error) <F>
Nov  1 09:54:26 yeono kernel: [302621.236585] ata6.00: status: { DRDY ERR }
Nov  1 09:54:26 yeono kernel: [302621.236589] ata6.00: error: { UNC }
Nov  1 09:54:26 yeono kernel: [302621.238214] ata6.00: configured for UDMA/133

This is a fairly up to date Debian Wheezy, kernel 3.2.0-4-amd64 #1 SMP
Debian 3.2.63-2 x86_64, ZoL 0.6.3. Package versions are current at
debian-zfs=7~wheezy, libzfs2=0.6.3-1~wheezy, zfs-dkms=0.6.3-1~wheezy,
zfs-initramfs=0.6.3-1~wheezy, zfsutils=0.6.3-1~wheezy,
zfsonlinux=3~wheezy, linux-image-amd64=3.2+46,
linux-image-3.2.0-4-amd64=3.2.63-2. The only package pinning that I
know of is for ZoL, for which I have (as provided by the zfsonlinux
package):
Package: *
Pin: release o=archive.zfsonlinux.org
Pin-Priority: 1001

Running hdparm -R on the drive reports that Write-Read-Verify is
turned on (this is a Seagate, so has that feature and I use it as an
extra safety net; the additional write latency is not a problem since
my interactive use pattern is very read-heavy):
/dev/disk/by-id/ata-ST4000NM0033-9ZM170_XXXXXXXX:
 write-read-verify =  2

Even given the clear indication that something is amiss, zpool status claims that there is no problem with the pool:
  pool: akita
 state: ONLINE
  scan: scrub repaired 0 in 8h16m with 0 errors on Sat Nov  1 10:46:03 2014
config:

        NAME                        STATE     READ WRITE CKSUM
        akita                       ONLINE       0     0     0
          mirror-0                  ONLINE       0     0     0
            wwn-0x5000c50065e8414a  ONLINE       0     0     0
            wwn-0x5000c500645b0fec  ONLINE       0     0     0

errors: No known data errors

This error has been showing up in the logs regularly for the last
several days now (since Oct 27) so I'm not terribly inclined to write
it off as merely a fluke. I run the disks with quite short SCTERC
timeouts; 1.5 seconds read (to recover quickly from read errors), 10
seconds write. I have confirmed that these values are active on the
drive in question.
smartd keeps pestering me (which in itself is a good thing!) about the
fact that the ATA error count is climbing:
The following warning/error was logged by the smartd daemon:

Device: /dev/disk/by-id/ata-ST4000NM0033-9ZM170_XXXXXXXX [SAT], ATA error count increased from 4 to 5

For details see host's SYSLOG.

Running smartctl --attributes on the drive in question yields the
following:
smartctl 5.41 2011-06-09 r3365 [x86_64-linux-3.2.0-4-amd64] (local build)
Copyright (C) 2002-11 by Bruce Allen, http://smartmontools.sourceforge.net

=== START OF READ SMART DATA SECTION ===
SMART Attributes Data Structure revision number: 10
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE
  1 Raw_Read_Error_Rate     0x000f   076   063   044    Pre-fail  Always       -       48910012
  3 Spin_Up_Time            0x0003   091   091   000    Pre-fail  Always       -       0
  4 Start_Stop_Count        0x0032   100   100   020    Old_age   Always       -       97
  5 Reallocated_Sector_Ct   0x0033   100   100   010    Pre-fail  Always       -       0
  7 Seek_Error_Rate         0x000f   092   060   030    Pre-fail  Always       -       1698336160
  9 Power_On_Hours          0x0032   089   089   000    Old_age   Always       -       9887
 10 Spin_Retry_Count        0x0013   100   100   097    Pre-fail  Always       -       0
 12 Power_Cycle_Count       0x0032   100   100   020    Old_age   Always       -       98
184 End-to-End_Error        0x0032   100   100   099    Old_age   Always       -       0
187 Reported_Uncorrect      0x0032   095   095   000    Old_age   Always       -       5
188 Command_Timeout         0x0032   100   099   000    Old_age   Always       -       10
189 High_Fly_Writes         0x003a   100   100   000    Old_age   Always       -       0
190 Airflow_Temperature_Cel 0x0022   058   052   045    Old_age   Always       -       42 (Min/Max 20/45)
191 G-Sense_Error_Rate      0x0032   100   100   000    Old_age   Always       -       0
192 Power-Off_Retract_Count 0x0032   100   100   000    Old_age   Always       -       61
193 Load_Cycle_Count        0x0032   100   100   000    Old_age   Always       -       492
194 Temperature_Celsius     0x0022   042   048   000    Old_age   Always       -       42 (0 11 0 0)
195 Hardware_ECC_Recovered  0x001a   052   008   000    Old_age   Always       -       48910012
197 Current_Pending_Sector  0x0012   100   100   000    Old_age   Always       -       0
198 Offline_Uncorrectable   0x0010   100   100   000    Old_age   Offline      -       0
199 UDMA_CRC_Error_Count    0x003e   200   200   000    Old_age   Always       -       0

Nothing glaringly out of the ordinary there. Note that this is an
enterprise drive, so five years warranty and rated for 24x7
operation (meaning it's meant to be reliable for over 40,000 hours of
operation, compared to the just under 10,000 hours under its belt so
far). Notice the number 5 in attribute 187 Reported_Uncorrect; that's
where the problem is. Also note the fairly low Start_Stop_Count and
Power_Cycle_Count values of under 100 each.
Not that I think it's relevant in this case, but yes, the system does
have ECC RAM.
Non-default properties of the root file system on the pool are:
NAME   PROPERTY              VALUE                  SOURCE
akita  type                  filesystem             -
akita  creation              Thu Sep 12 18:03 2013  -
akita  used                  3,14T                  -
akita  available             434G                   -
akita  referenced            136K                   -
akita  compressratio         1.04x                  -
akita  mounted               no                     -
akita  mountpoint            none                   local
akita  version               5                      -
akita  utf8only              off                    -
akita  normalization         none                   -
akita  casesensitivity       sensitive              -
akita  usedbysnapshots       0                      -
akita  usedbydataset         136K                   -
akita  usedbychildren        3,14T                  -
akita  usedbyrefreservation  0                      -
akita  sync                  standard               local
akita  refcompressratio      1.00x                  -
akita  written               0                      -
akita  logicalused           2,32T                  -
akita  logicalreferenced     15K                    -

and correspondingly for the pool itself:
NAME   PROPERTY               VALUE                  SOURCE
akita  size                   3,62T                  -
akita  capacity               62%                    -
akita  health                 ONLINE                 -
akita  dedupratio             1.00x                  -
akita  free                   1,36T                  -
akita  allocated              2,27T                  -
akita  readonly               off                    -
akita  ashift                 12                     local
akita  expandsize             0                      -
akita  feature@async_destroy  enabled                local
akita  feature@empty_bpobj    active                 local
akita  feature@lz4_compress   active                 local

These lists were obtained by running {zfs,zpool} get all akita | grep -v default.
Now for the questions:

Why isn't ZFS reporting anything about the read problem? It's
clearly recovering from it.
Why isn't ZFS automatically rewriting the duff sector that the
drive is clearly having trouble reading, in turn hopefully
triggering a relocation by the drive, given that sufficient
redundancy exists for automatic repair in the read request path?
Comment: Right. Did you also post to the ZFS group?
Comment: I don't have an answer for you, but I've seen similar behavior on FreeBSD. A failing drive which resulted in decreased performance and lots of errors printed to the console, but which failed to increment any zpool-level error counters. I have not yet found an explanation, but it may at least be worth considering that this is not a Linux-specific phenomenon.
Comment: I dunno. Maybe you're not hitting the affected files. Or perhaps none of the files are affected at this point.
Comment: @ewwhite During a *scrub,* running which has *repeatedly* triggered the error showing up in the system log? (The error also showed up when I burned a set of files to DVD, which was what originally had me looking into this.) There is also a ton of snapshots on the pool going quite a way back.
Comment: Upvoted because I'm not sure why you're encountering this with ZFS - It could be interesting to see if this is a bug... However from a sysadmin's perspective, spinning disks are consumables. I have disks that are DOA, die within a few weeks, die after a year... and some fail at 5 years. If you suspect severe problems, replace the drive.
Comment: @ewwhite I'm pretty sure this is a single bad sector (or a very small number of consecutive bad sectors) which isn't very alarming in my book. What I want to understand is *why ZFS isn't reporting this* as a problem or rewriting the data, even though the disk fairly clearly does have trouble reading it currently. If ZFS were to simply use the redundancy which is available to rewrite the sector, the sector would likely be remapped by the drive and all would be well for the time being.
Comment: @ewwhite discuss@zfsonlinux, yes.
Comment: I don't have any answers for you, but +1 for a well researched and written question!
Answer: I suspect the ATA driver is retrying the read operation a couple of times when it receives an error before passing the error back to the filesystem driver.
What this means is by the time the ZFS filesystem driver gets the result of the read the data is all there, and correct, but it likely took a bit longer than normal to happen. There is of course no error counter for higher-than-average latency, so nothing logged.
The fact that the SMART value for Reported_Uncorrect is not 0 makes me suspect that the cause of the failure is the disk itself, as opposed to say the SATA cable or SATA controller being flakey.
If this is the case, most likely the disk will eventually die more and start failing to read even after however many retries the block device driver is attempting. As such my advice would be to replace the disk.
Trigging a long SMART test would likely fail on the affected blocks, if you wanted to make the error go away rewriting those blocks (with dd for example) should cause the disk to swap out those sectors, but in my experience is once a drive starts to go it's better to just replace it and be done with it.
Answer: I had a bad SCSI disk with a ZFS raid on Solaris.  I was scanning the log files for information on error messages to gather proof the disk was bad and get Oracle to cover it on the hardware maintenance.  I ran grep for certain strings in error logs and these lines showing disk errors would be in my console screen.  When "Explorer" (the system log and reporting tool for Solaris) was run and sent to Oracle, they said there was no errors on the disks.  But I had them on my screen history.  I checked and it was indeed gone from the logs on disk.
Here is what was going on...  ZFS promises zero file system errors, not zero data errors.  When a serious corruption is encountered, it rolls back the transaction, doing whatever is required to make the file system integrity good.  As a result, file updates are lost when it rolls back to an earlier version of the file prior to the corruption, and therefore data loss may occur.  But your file system is error free.
Perhaps for simple errors, ZFS can rollback and rewrite the data in another attempt, but it seems in serious cases of bad disk behaviour, it can get into a catch-22 where data isn't being recovered and written.  If you need to gather evidence on disk errors, make them come on the screen and don't rely on proof which will reside on disk, where data is potentially being reset by ZFS transaction rollbacks.
Comment: Two things. One, I don't quite see how this answers the question; perhaps you can clarify? Two, this answer appears to be factually incorrect. [In the words](https://blogs.oracle.com/bonwick/entry/zfs_end_to_end_data) of [one of the original ZFS team leads](https://en.wikipedia.org/wiki/ZFS#History), "note that **ZFS end-to-end data integrity** doesn't require any special hardware" (my emphasis). If a system crash happens you can lose the currently-outstanding txg, and `zpool import -F` can be used if recent txgs are unusable, but claims of automatic txg rollbacks would IMO require citations.
Comment: The OP asked : "Why isn't ZFS reporting anything about the read problem".  I am answering that.  ZFS can't report to files on disk when it can't write to the disk.  ZFS cannot be perfect when hardware performance is not perfect.  All it can hope to achieve is protection against file system corruption.  "End to end data integrity" depends on what is meant by "data" and "integrity".  I believe it means "no corruption", not "all your data will be written/read perfectly under any conditions".  There is a way to test for the loss under /var, check /var/log files for missing hours/days.  I saw that.
Comment: (1) I am the OP. (2) As shown in the question, the vdev is a mirror configuration. (3) Claims are that once data on ZFS has made it to persistent storage, it will remain there and either be readable or the I/O operation will return a read error. (4) The OS clearly detected the I/O problem, and either the kernel itself or ZFS recovered from it (since the read operation succeeded), yet the I/O error was not recorded in the pool stats.
Comment: My ZFS was a mirror too.  But firmware errors can spew junk causing no disks to work properly.  Where are errors and pool stats written?  To bad media.  Look in the files in your /var/log area.  Look at files which are constantly written to, for whatever your server does.  If mail, look at maillog.  If web, look at access log.  Otherwise try messages.  If I am right, there will be time gaps (in my case, days missing) from the log files.  That is your proof that data is being lost.  Don't believe me.  Don't look for citations.  Look at your files, and that may confirm what is happening.


Install powerline fonts on centOS6.6

Question: I installed recently the patched fonts for Powerline users from the github repository on a centOS6.6 box.
As indicated in the docs I executed the script that ran ok and printed
[statquant@latitude fonts]$ ./install.sh
Copying fonts...
Resetting font cache, this may take a moment...
All Powerline fonts installed to /home/statquant/.local/share/fonts

And indeed:
[statquant@latitude fonts]$ tree /home/statquant/.local/share/fonts
/home/statquant/.local/share/fonts
├── Anonymice\ Powerline\ Bold\ Italic.ttf
├── Anonymice\ Powerline\ Bold.ttf
├── Anonymice\ Powerline\ Italic.ttf
├── Anonymice\ Powerline.ttf
...

But for some reason gvim is not picking up those fonts, as it the context menu Edit > select font... I have no trace on any *Powerline font.
Any help appreciated
Comment: add /home/statquant/.local/share/fonts to the font searching directory list. or just put those ttf files into /usr/share/fonts.
Comment: how do I add the path to the search list?
Comment: try /etc/fonts/fonts.conf
Comment: I have no root access
Comment: https://www.freedesktop.org/software/fontconfig/fontconfig-user.html
Comment: Your suggestion of looking in the file was good, write an answer to get the bounty
Answer: when adding fonts, one should put those fonts in the directory that fontconfig will scan. run fc-list to list available fonts.
the fontconfig user's guide
Comment: while you're at it I appears I have to change my terminal font from `~/.Xresources` I am using `terminal` (`xfce`), any idea what I need to put in this file to get a powerline font ?
Comment: Damn, so now I have it working on `gvim` but not vim, looks like it has to do with the terminal setup `terminal 0.4.7 xfce terminal emulator`
Comment: know little about xfce terminal,  in GNOME Terminal,  font can be modified by Editing Profile.
Comment: I think xfce terminal and gnome terminal are the same... almost. So there is a profile, `Edit>Preference>Appearance` but then the newly installed fonts are NOT in the list. Though I know it is there because when I open `gvim` I can see those fonts and can change them
Comment: run `fc-cache -f  -v` to update font cache, if still not work, restart terminal emulator.
Comment: you mean start a new terminal? or restart the desktop environment? It clearly did something as I see it printed "loaded 86 new fonts from my local dir", by they are still not in the terminal drop list choice menu
Comment: start a new terminal
Comment: This is crazy, `xfce` (the desktop) now sees the font, I can change all icon/window/... to use the new font... BUT when I start a terminal I cannot change the font within the terminal !! How sick is that ?
Comment: restart terminal emulator should work. So the last advice, logout then login.
Answer: I solved it,
Looking in cat /etc/fonts/fonts.conf I could see

<dir>/usr/share/fonts</dir>
<dir>/usr/share/X11/fonts/Type1</dir>
<dir>/usr/share/X11/fonts/TTF</dir>
<dir>/usr/local/share/fonts</dir>
<dir>~/.fonts</dir>

Then I created a symlink ln -s  ~/.local/share/fonts/ ~/.fonts

Install powerline fonts on centOS6.6


Deep neural networks versus tall neural networks

Question: I've been reading Chris Bishop's book, Neural Networks for Pattern Recognition recently.  It is quite dated relative to the state of the art, but it is the best book I've found on neural nets that actual relates things back to statistics, optimization, etc.
Reading it today, I crossed a passage that I've heard before, specifically:  a three layer network (2 hidden layers, or 3 layers of weights) with sigmoidal activation functions can approximate, to arbitrary accuracy, any smooth mapping.  He goes on further to say that given an adequate number of hidden units, dimensionality of input to output mapping is not limiting.  I believe also he describes a 3 layer network as a universal function approximator.
Also, I recently read a paper (https://arxiv.org/abs/1806.06850) showing  empirically that polynomial regression was able to perform as well or better than neural networks of depth similar to the degree of the polynomial, but, they only explored to the power of 3.
With all the interest in deep neural networks, I'm wondering why tall neural networks haven't also been of interest.  Obviously the name isn't as sexy, but it seems in general I could have a more shallow network that is simply taller and get to the same result.  The only thing that comes to mind for me is the gradients for each layer are much higher dimension, and maybe convergence would be a problem.
Or I'm missing something more deep.  I appreciate any thoughts on the topic.
Comment: So the "height" or "width" of a 3 layer network could approach the same capability of a deep network, but the number of nodes required by the "wide" network would become computationally intractable to achieve the same complexity of the comparative deep network.  Does that capture it?
Comment: Because complexity grows exponentially with depth, as opposed to polynomially with width. That paper's results are restricted to 3 layer networks, which is laughably low for any deep learning application. Contrast that with deep networks on images, which have *hundreds* of layers.
Answer: Whilst a 3 layer network can be assigned weights that can approximate any function, this function might not be easily learnable via backpropagation.
Whereas deep networks can learn effectively from back-propagation.
Just to show that it is in fact possible to pack a lot of the learning from a deep network into a shallow network, you can look at 'Do deep nets really need to be deep", https://arxiv.org/abs/1312.6184, by Ba and Caruna. In this paper, they show that a shallow network that cannot learn a good fit to the desired function from supervised training on the original task, can in fact learn this function by being trained from a deep 'teacher' network.


String advice for viola

Question: I want to put new strings on my viola, as the current ones are more than five years old. I think the current ones are D'Addario Helicore for C, G and D, and Jargar medium for A (I tried to lookup the silk colors). These are the strings the builder put on the instrument.
The instrument itself is for students, my technique is not great, and I play for my own pleasure only. So I'm looking for robust, responsive strings that are not too expensive. I'm quite happy with the Helicores, but the A string sounds a bit too bright for my liking. I don't know if that is because of the string or also because of the instrument, but I guess the builder had a reason for using a different A string.
If I replace the A string with a Helicore, will that make the A sound less bright or brighter? What other strings are there that might suit me?
(Added later, in response to comment by Bob Broadley) How does string type (polymer core, steel core, winding, ...) influence the sound and the responsiveness of the string? Are there any general rules of thumb concerning that?
Comment: Hey there. Shame about the close votes; our community is a bit quick to jump on off-topic questions sometimes. We don't do purchase recommendations here, BUT if you rephrase your question to ask about the TYPE of strings that would suit your requirements, this question will stay open. And be useful for future readers. +1 BTW.
Comment: @BobBroadley - the trouble with this type of question is that there is no good answer, even without the product recommendation part. If it's a dull instrument, it will probably need bright strings or vice versa. This really is one of those "the only way to find out is to try it" questions. Possibly helped by a visit to a store - play it at them, see what they say.
Comment: @Tetsujin that the answer to the question is perhaps not precisely what the asker is expecting isn't a reason to close the question.  In fact, your comment would make a fine answer to the question; why not post it as such?
Answer: There is no definitive answer to your question. Which brand of strings suits your instrument best is not something we can tell you. Different strings work differently on different instruments. More advanced players often go through periods of changing the brand of strings they use regularly because they are not 100% happy with the current sound.
The strings which I think sound great on my instrument may not sound great on your instrument in your opinion. As an amateur, your opinion of what sounds good is the most important opinion. My opinion is not worth that much. I'm not the one who is going to hear you play. That person is you.
The best advice anybody can give you here is to read the reviews (to be honest this is for placebo effect, you won't really be much wiser) and then buy a set of strings which suits your pocket. If you really like the sound then next time your strings need to be changed then stick with your original choice. If not then try something different.
Finally I don't think can make any judgement on the merits of 5 year-old strings. How a 5 year old string sounds to you now is no guide to how the same brand new string will sound.
Answer: For my instrument, a rather large 16.5 inch instrument, I use D'Addario Helicore Viola String Set, Long Scale, Medium Tension (found on Amazon).  I like the tone on all four strings, but I am an amateur, and it probably sounds better to me.
For my violin, for reference, I use Prim Strings (again on Amazon).  These strings are also available for viola, but they're expensive (when they're available).
The two sets of strings above are similar in tone, but I think that it really comes down to personal choice.  What tone you want determines whether you want gut, synthetic, steel-core, rope-core or another type of string.
In my opinion, older strings do not sound as good as a brand new set of strings, but that is only my opinion
Answer: Jargar A will probably be very marginally brighter than the Helicore A. The other answers gave the standard advice which is broadly correct - your instrument has too many things that could be different and will likely change the answer a bit, but ... There are a few resources which can help you make your decision. First, here is a research paper that examined this exact question. On page 43, it shows that Helicore open A is significantly brighter than the other Helicore strings (meaning you probably noticing something that is real), but on the same page, it shows that the Jargar A is also brighter than the other Jargars - but with a bit more high frequency response than the Helicore.
In the same paper, there was some discussion (on page 49) of responsiveness, but no real experimentation to back it up. Check out this site for a 2 dimensional plot of different violin strings which may also help.
As for how core material impacts the sounding of the string, the main rule is that gut strings sound great, but are touchy (break-in slowly, change pitch with humidity) and not as durable. The marketing folks want you to think synthetic core strings have all of the advantages of gut with none of the drawbacks, but both steel and synthetic core strings can have very different properties depending on the manufacturers' goals and how they interact with your viola.
A lot of experimentation is probably needed to get a really good answer, so just experiment on the one(s) you don't like. New strings every year or so (unless you start playing more) will be better than old ones unless you get a string that really isn't suited for your instrument.

String advice for viola


How to layout the theme within the regions?

Question: I'm very much beginner to the drupal and learning to themeing, and I'm confused how to make regions within the regions?
+----------------------------------------------------------+
| +--------------+                +---------------------+  |
| |              |                |                     |  |
| |    header1   |                |   header2           |  |
| |              |                |                     |  |
| +--------------+                +---------------------+  |
|                       header                             |
+----------------------------------------------------------+

page--front.tpl.php

    .....
   <?php print render($page['header1']); ?>

    .....
   <?php print render($page['header2']); ?>

<?php print render($page['header']); ?>

And I did the change in .info file like:
regions[header1]        = Logo Area
regions[header2]        = Search bar and Navigation

But it's not displaying as the picture describes better it:

Update:
The rendered html is like this:

But What I wanted to be like this:

Comment: What you did seems valid, and should only need a proper CSS to work. Strictly speaking it is not "region in region" but should display all right. Just don't expect Drupal to show it as nested regions, as this concept is unknown to Drupal.
Comment: Did you clear the theme cache after you made the changes ?
Comment: Which theme you are using ?
Comment: @Rupesh Zen theme
Comment: Yes clear the cache, but no avail....
Comment: The exact output you want is not possible, or at least hard, because Drupal does not support nesting regions. [Rupesh's answer](http://drupal.stackexchange.com/a/112161/16495) and CSS seems the way to go. Simply move all styles you would like on `div.region-header` to `header#header`.
Answer: You cannot make region within region. You can place block in a region.
Fix the width of block and float that. You have to use only css to achieve that.
Print wrapper like this

<?php if($page['header1'] || $page['header2']) :?>

    <?php if($page['header1'] ) :?>

        <?php print render($page['header1']); ?>

    <?php endif;?>
    <?php if($page['header2'] ) :?>

        <?php print render($page['header2']); ?>

    <?php endif;?>

<?php endif;?>

Comment: CSS questions are off topic here @Navin, we won't be able to help you with that
Comment: please answer in detail what should I do?
Comment: Sorry, I don't know another way to phrase it - you cannot put a region inside another region. You'll need to adjust your strategy to use blocks instead. Or add another concept to your theme (like Omega does with 'zones'), but that would be a lot of work. If you're desperate to have that exact markup I don't understand why you don't just manually wrap the output of the two regions in the markup you want, directly in page.tpl.php
Comment: @Clive No, I'm not talking about css, I know css very well, but the problem with the rendered markup....
Comment: Ok, but you still can't put a region inside a region... _blocks_ go in regions, so usually one would put their content in blocks, add them to a region, and use CSS to produce the desired layout. Anything beyond that and you'll need a custom region template file (a quick search on this site should show you how to do that, but if not just update the question). Bit there is no native support for putting a region inside another region
Comment: please check my edit...
Comment: Rupesh, consider adding that the CSS way would be to simply move all styles OP would like on `div.region-header` to `header#header` to your answer. It would make it easy to apply to data in question's last update
Comment: No not like that. I would advise outputting the wrapping markup manually, it's the only easy way to get the result you desire without you learning a lot more about Drupal theming works
Comment: @NavinRauniyar If one of the answers above fixes your issue, you should accept it (click the check mark next to the appropriate answer). That does two things. It lets everyone know your issue has been resolved, and it gives the person that helps you credit for the assist.
Answer: you cannot put region into region, but you can fake it

    .....
   <?php print render($page['header1']); ?>

    .....
   <?php print render($page['header2']); ?>

   <?php print render($page['header']); ?>

now you dont want that extra div with classes to appear in header region so you theme it and remove div. create region--header.tpl.php
and put this inside:
<?php if ($content): ?>
    <?php print $content; ?>
<?php endif; ?>

Comment: there is no region.header.tpl.php but pane.header.tpl.php should I create one...
Comment: yes. you need to create region--header.tpl.php
but not region.header.tpl.php
you can copy and rename modules/system/region.tpl.php but then you need to remove div wrapper from there


Elements of a space

Question: If A is a normed linear space and there exists an element x,y in A, then is it also true that x-y is also in A as well?
I am pretty sure this is true by definition, but I am not able to find any reference backing this, thereby leading myself to doubt the statement.
Comment: A is closed under addition and under multiplication with numbers. Hence, x-y = x + (-1)*y is an element of A.
Answer: Look at the definition for "normed linear space" in whatever text you're using. It will contain axioms saying:

there is an addition operation sending any $x$ and $y$ in $A$ to $x+y$, also in $A$; and
every element $x$ in $A$ has an additive inverse in $A$, which we denote $-x$, such that ...

or similar.
Therefore, if $x$ and $y$ are in $A$, we can define "$x-y$" to be shorthand notation for $x + (-y)$, which we know will be in $A$ from the above axioms.
(Note that if your axioms don't give an "additive inverse" explicitly, they will at least allow you to perform scalar multiplication. We can then interpret "$-x$" as shorthand for the scalar multiplication $(-1)x$ and do the same trick.)
Answer: In fact, every linear combination $ax+by$ will be an element of the space for scalars $a,b$ and vectors $x,y$.
Answer: This is true even for ordinary linear spaces, e.g. Vector spaces.
You can check out the axioms for vector space, it is closed under addition and the additive inverse exists, thus $x-y$ is in it.

Elements of a space


Windows 10: How to fix 'Service MongoDB server' (MongoDB) failed to start as service after installing MongoDB

Question: I tried to install MongoDB on my machine and after the installation is about to finish it is throwing an error stating "Service MongoDB server' (MongoDB) failed to star".

And while I try to run mongod.exe it's getting failed.
Please help me with this. Thank You
Comment: https://stackoverflow.com/questions/6478113/unable-to-start-mongodb-local-server?noredirect=1&lq=1, https://stackoverflow.com/questions/20796714/how-do-i-start-mongo-db-from-windows?rq=1 answers in this questions will be also relevant to your problem.
Answer: Have the same problem.

Install complete version to default folders will help, because it writes default path address for MongoDB Server service, check it by running Win+R
Answer: Try installing with Administrator.
Comment: Tried. Still same problem is persisting.
Comment: 1. Navigate to Group Policy Object Editor > Local Computer Policy.
2. In the console tree, navigate to Computer Configuration > Windows Settings > Security Settings > Local Policies >User Rights Assignment.
3. In the details pane, double-click Log on as a service.
4. Click Add User or Group and add the account to the list of accounts that have the Log on as a service right.


Installing SVN separately after Apache (Windows)

Question: My friends and I have recently began a final college project and we require the use of software version control system. I have used Subversion Tortoise and Silk when I was working as a web developer for a former employer and I thought it would be a good idea to use it.
Although I know how to install and run the client, I have no idea how to configure it to run as a server.
I am currently using an old Acer Aspire laptop running Windows XP as a web server. It already has (of course) Apache 2.2 and MySQL installed via XAMPP. How would I go to install TortoiseSVN so that it makes use of the web directory I made for Apache?
Should I start everything over considering I am using XAMPP or is there another way to do this? I do not mind formatting and perhaps migrating over to a Linux platform.
If I missed something or you need more details concerning my configuration, I'll edit this question.
Thank you in advance.
-Christopher
Answer: Tortoise SVN is just an SVN client. You still need an SVN server. Collabnet or VisualSVN are the two most common. Collabnet is very easy to set up for Apache (never used Visual SVN). Just install the binaries and edit your httpd.conf to include the path to the DAV SVN plugins. Or, Collabnet include Apache for you if you want to run it on a different port or IP address.
Once you've got it set up and your repo's created, you then need to make sure your web server has an up to date copy. There are two common ways of doing this:

Do an SVN checkout into your public HTML folder. This will mean that all your .svn folders are present though and can cause a security risk. For internal use it should be OK though. Maintenance is easy cos then you can just do an SVN Update
Do an SVN export from your local working copy (after doing an SVN Update, of course) into your web server's Public HTML folder. This means that no .svn folders are lurking on the server.
Comment: I'll give it a try and tell you how it goes. For now I'll just give you a +1 :)


Google Cloud Resolve VM host name to Google Cloud DNS host names

Question: I'm setting up an OpenShift cluster in Google Cloud and have a bunch of VM's spun up.  I also have a Google Cloud DNS zone where I have registered the hostnames of the VM's I've set up.  I want to be able to reference all the VM's by the hostnames I've configured in my Google Cloud DNS zone and not by the local names Google Cloud Platform gives them.  How do I go about doing that please?
I've tried editing resolv.conf (they are all Centos 7 Linux VMs) but that doesn't work and I understand that gets overwritten every DHCP lease renewal anyway.
To explain in more detail, I'll use 1 VM as an example.
I have a VM called 'nat-gateway'.  It's 'hostname -f' is nat-gateway.c.MyProjectName.internal and I can ping it using both nat-gateway and it's fqdn nat-gateway.c.MyProjectName.internal.  On my Cloud DNS zone, called cloud.abc.gcp I have created an A record for nat-gateway and I want to be able to ping it using nat-gateway.cloud.abc.gcp.  So for all my VMs I want to ping them by their corresponding cloud.abc.gcp hostnames.
Your help would be very much appreciated, thank you.
Answer: The short answer is yes. It is possible.
The long answer is that this is not the intended use of Cloud DNS. but here are the steps to make it behave almost like you want:

On your Cloud DNS create the A record pointing to the Internal IP of your nat-gateway (as an example: 10.128.0.3)
Side note, you can reserve an Internal IP address when creating a VM or promoting an in-use ephemeral internal IP address to a static address since the A record is pointing to its Internal IP.
Wait for the Cloud DNS propagate the A record and ping the nat-gateway.cloud.abc.gcp hostname.

Results:

If within the same VPC and the firewall allows ping, it will resolve the Cloud DNS hostname as the FQDN nat-gateway.c.MyProjectName.internal and it will ping normally.
If outside the VPC but connected to it using a VPN or VPC Peering (example: Project A VPC A is connected to Project B VPC B using a VPN tunnel and all firewalls and routes apply, one instance can reach another form the other network using the Cloud DNS hostname resolved as Internal IP address)
If the machine trying to ping is not connected to the VPC of your nat-gateway, it will resolve the hostname as the reserved IP address but not be able to reach it (expected behavior).

Finally, Cloud DNS will not resolve the FQDN nat-gateway.c.MyProjectName.internal directly, but to the IP associated to it and when used in the same VPC the IP will be resolved again by the internal DNS of the VPC as the FQDN nat-gateway.c.MyProjectName.internal.


Will other teams start breaching the cost cap if Red Bull are not punished for breaching it?

Question: We know that Red Bull has breached the F1 cost cap. The situation has become more and more tense between the top three teams (Red Bull, Ferrari, and Mercedes). The McLaren CEO has also spoken about this and said that the team need to be punished.
Now, let's say that the Red Bull team do not get punished for this breach, and only get reprimanded and keep their championship. Will this give the others teams, like Mercedes or Ferrari, the opportunity to find the loop-hole in order to breach the cost cap without getting punished? Let's say that in 2023, Ferrari wins the championship but breach the cost cap, they can say that their situation is the same as 2021 and of course, keep their title to themselves.
I think that this will become a big problem if the team do not get punished, because the other teams can manipulate this situation in order to find the loop-hole.
Answer: This was certainly what the other teams (and many commentators) believed would happen if Red Bull's sentence was too lenient - the cost cap would become meaningless and other teams would start breaching it too. The day before you posted this, Lewis Hamilton stated in an interview:

If they are relaxed with these rules, all the teams will just go over. Spending millions more and only having a slap on the wrist is not going to be great for the sport. They might as well not have a cost cap in the future.

There is precedent for this: in 1994, the FIA banned the use of launch control software, yet that year's title-winning Benetton B194 was found to have one installed. The FIA couldn't prove they'd actually used it, so Benetton got away with it, and over the following seasons, so many other teams installed launch control software that they "weren't using" that the FIA were forced to admit the ban was unenforceable and lifted it.
In the case of the cost cap, however, this hasn't happened. Despite the cost cap rules being made more stringent for 2022, and criticism from some that Red Bull's punishment was too lenient, the FIA have stated that no teams breached the cost cap that year.
The linked Sky Sports article suggests why: while some teams were unhappy with Red Bull's punishment, others were satisfied, and Mercedes' Toto Wolff noted that the "reputational damage" Red Bull suffered would be enough of a deterrent. In the case of Benetton, they weren't punished at all, and the incident was overshadowed by other controversies surrounding the team that year (namely, accusations of illegal fuel hoses, and Michael Schumacher's controversial title-deciding collision with Damon Hill), such that it didn't hurt Benetton's reputation all that much.


Wix Toolset - Variable Shared Across Projects/Solution

Question: I am trying to share a variable across 2 of my wix projects but I am having issues.
Basically I am trying to accomplish having the version number of my bootstrapper and MSI in one file and then this referenced by the two projects.
I have three projects

Install - This is a setup project that creates an .msi file
Bootstrapper - This is a Wix Bootstrapper project that references and runs the .msi file at runtime
Shared - This is a wixlib project that contains a single variable in a fragment that is the version number

The shared project contains a single file i have called GlobalVars.wxs and looks like this
<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Fragment>
    <?define VersionNo = "6.86.123"?>
    </Fragment>
</Wix>

The bootstrapper references this variable like this
<Bundle Name="ProgramName" Version="$(var.VersionNo)" Manufacturer="CompanyName" UpgradeCode="Guid" Compressed="no">

and the Install project references the variable like this - and has a reference to the .wxs from the shared project
  <Product Id="*" Name="Program Name" Language="2057" Version="$(var.VersionNo)" Manufacturer="CompanyName" UpgradeCode="guid">
    <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine"  InstallPrivileges="elevated"/>
    <?include GlobalVars.wxs ?>

Both projects have references setup to the wixlib project that contains the variable
When i attempt to build I am getting this error on both the install and bootstrapper project
Undefined preprocessor variable '$(var.VersionNo)'.

If the <?include?> tag resolved the issue I would expect the install project to build
Does anyone have any ideas as to what I might be doing wrong here?
To me it looks like the variable has not been defined by the time the build attempts to call it, but I am unsure as to show to change the order to ensure the variable is defined before anything else
Thanks for the help
Comment: I think you are mixing pre-processing and runtime.  is pre-processing, it does not create a variable.
Comment: You could use Windows Installer properties
Comment: You can also do `Version="!(bind.packageVersion.MSIPackage)"` where "MSIPackage" is the Id of the `` in your bundle. Your $(var.VersionNo) isn't getting picked up because you have nothing to bring in that `` from the wxs file. Generally you need a `` tag in your product to bring in a fragment from another wxs.
Comment: First thing: `` defines a pre-processor-variable to be used later on by referencing it via `$(var.VersionNo)`. Second: Just referencing a wix project doesn't help, you have to include the file with the version via ``. One more note: Variables are not put into the generated MSI file, therefore you do not see them
Comment: I'd also be keen to see an answer to this. Copy+Pasting code, even Wix code, feels wrong to me
Comment: Ah that would make sense! How do I make a variable then? (sorry really simple question I know!)
Comment: Do you know if it is possible to define these in the WiX files rather than passing them in at run time?
Comment: Thanks Brian, please can you explain the reference thing? I thought If i added a project reference to the shared project in the install project, the install project would have access to all the fragments?
Comment: Thanks Stephen, I have added this tag to the main Product.wxs file . The project that contains the Product.wxs has a visual studio reference to the project that contains the .GlobalVars file as well, but unfortunately it still does not pick up the variable. I will update the question now as well
Comment: One comment states  does not create a variable, then another comment by @StephenReindl says it does.  Preprocess variables, Bind variables, Wix Variables, Windows Properties... this whole WiX thing seems needlessly overcomplicated with a lack of good documentation.
Comment: Well, you are free to find other tools that might fot to your needs. I use several tools to create installers, but whenever it reaches a higher level of complexity I automatically start over with WiX. The complexity does not com from Wix but of the environment the software works with.
Answer: I believe the answer to this question will help. I've used it and noticed that properties seem to be usable in my main wxs file.
To summarise, you need to set up a fake componentGroup in your library fragment, and use it in your installer. You do not need the include anymore, as long as the fake componentGroup from your fragment is referenced as a componentGroupRef in your main install, and your wixlib project is referenced in your installer project through VS (you said you'd already done this in your comments above).
Your library fragment might look something like this.
<Fragment id="fragment_id_may_not_be_needed">
    <?define VersionNo = "6.86.123"?>
    <ComponentGroup Id="c.define_version_num" />
</Fragment>

If the define for whatever reason doesn't work, try using a property instead. I'd be interested to know which works. Properties seem to work for me.
Then reference it in your main install like this:
<Feature Id="Main_installation" Title="Main installation" Level="1">

  <ComponentGroupRef Id="c.define_version_num" />
</feature>

Give it a whirl.


How to display the profile url in the comments?

Question: I have the module :
https://www.drupal.org/project/profile
https://www.drupal.org/project/twig_tweak
Here is the twig file of my comments :
{#
/**
 * @file
 * Default theme implementation for comments.
 *
 * Available variables:
 * - author: Comment author. Can be a link or plain text.
 * - content: The content-related items for the comment display. Use
 *   {{ content }} to print them all, or print a subset such as
 *   {{ content.field_example }}. Use the following code to temporarily suppress
 *   the printing of a given child element:
 *   @code
 *   {{ content|without('field_example') }}
 *   @endcode
 * - created: Formatted date and time for when the comment was created.
 *   Preprocess functions can reformat it by calling format_date() with the
 *   desired parameters on the 'comment.created' variable.
 * - changed: Formatted date and time for when the comment was last changed.
 *   Preprocess functions can reformat it by calling format_date() with the
 *   desired parameters on the 'comment.changed' variable.
 * - permalink: Comment permalink.
 * - submitted: Submission information created from author and created
 *   during template_preprocess_comment().
 * - user_picture: The comment author's profile picture.
 * - status: Comment status. Possible values are:
 *   unpublished, published, or preview.
 * - title: Comment title, linked to the comment.
 * - attributes: HTML attributes for the containing element.
 *   The attributes.class may contain one or more of the following classes:
 *   - comment: The current template type; for instance, 'theming hook'.
 *   - by-anonymous: Comment by an unregistered user.
 *   - by-{entity-type}-author: Comment by the author of the parent entity,
 *     eg. by-node-author.
 *   - preview: When previewing a new or edited comment.
 *   The following applies only to viewers who are registered users:
 *   - unpublished: An unpublished comment visible only to administrators.
 * - title_prefix: Additional output populated by modules, intended to be
 *   displayed in front of the main title tag that appears in the template.
 * - title_suffix: Additional output populated by modules, intended to be
 *   displayed after the main title tag that appears in the template.
 * - content_attributes: List of classes for the styling of the comment content.
 * - title_attributes: Same as attributes, except applied to the main title
 *   tag that appears in the template.
 * - threaded: A flag indicating whether the comments are threaded or not.
 *
 * These variables are provided to give context about the parent comment (if
 * any):
 * - comment_parent: Full parent comment entity (if any).
 * - parent_author: Equivalent to author for the parent comment.
 * - parent_created: Equivalent to created for the parent comment.
 * - parent_changed: Equivalent to changed for the parent comment.
 * - parent_title: Equivalent to title for the parent comment.
 * - parent_permalink: Equivalent to permalink for the parent comment.
 * - parent: A text string of parent comment submission information created from
 *   'parent_author' and 'parent_created' during template_preprocess_comment().
 *   This information is presented to help screen readers follow lengthy
 *   discussion threads. You can hide this from sighted users using the class
 *   visually-hidden.
 *
 * These two variables are provided for context:
 * - comment: Full comment object.
 * - entity: Entity the comments are attached to.
 *
 * @see template_preprocess_comment()
 *
 * @ingroup themeable
 */
#}

        {{ drupal_entity('user', comment.uid.target_id, 'comment_teaser_relation') }}
        {{ author }}

     {{ created }}
     {{ content.field_article_commentaire }}
     {{ content.links }}
     {{ content.flag_report_comment }}

I want to display instead of :
{{ ??? URL PROFILE USER ??? }}

The url of the profile (profil_personnel) of the author of the comment.
On the comment_teaser_relation view of the user account, there is a profile field personnel that I activated.
Here is the twig file of the user account :
{#
/**
 * @file
 * Default theme implementation to present all user data.
 *
 * This template is used when viewing a registered user's page,
 * e.g., example.com/user/123. 123 being the user's ID.
 *
 * Available variables:
 * - content: A list of content items. Use 'content' to print all content, or
 *   print a subset such as 'content.field_example'. Fields attached to a user
 *   such as 'user_picture' are available as 'content.user_picture'.
 * - attributes: HTML attributes for the container element.
 * - user: A Drupal User entity.
 *
 * @see template_preprocess_user()
 *
 * @ingroup themeable
 */
#}

    {{ content.profile_personnel }}
    {{ content.user_picture }}

If I enter the code {{ content.profile_personnel }} in the twig file of the user display, the profile is displayed.
How to display only the profile link ?
And how to display the profile link of the author of the comment, in the comments twig ?
Here is the twig of the profile if it can help :
{#
/**
 * @file
 *
 * Default theme implementation for profiles.
 *
 * Available variables:
 * - content: Items for the content of the profile.
 *   Use 'content' to print them all, or print a subset such as
 *   'content.title'. Use the following code to exclude the
 *   printing of a given child element:
 *   @code
 *   {{ content|without('title') }}
 *   @endcode
 * - attributes: HTML attributes for the wrapper.
 * - profile: The profile object.
 * - url: The profile URL, if available.
 *
 * @ingroup themeable
 */
#}

Comment: This might help: https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates -- if you know the id, you can generate a link in twig.
Comment: @Kevin Thank you, but I do not master at all twig
Comment: If you just want to link to the user profile page, you can do
`{{ 'View user profile'|t }}` - in your case I am guessing the user.id is instead `comment.uid.target_id`
Comment: @Kevin In fact I am talking about the profile (module profile). Who is linked to the user account. See the screenshot at the end of my question.
Comment: The core module?
Comment: @Kevin I believe this module has been installed with "Drupal Commerce". I tried this, but it does not work
  {{ drupal_entity('user', comment.uid.content.profile_personnel.target_id) }}
Answer: To link to this in the twig file, you can use the path function like so:
{{ 'View user profile'|t }}

I am guessing that comment.uid.content.profile_personnel.target_id returns the entity id of the profile. This will create a /profile/{id} href where {id} is the profile id.
I don't use twig tweak, but I assume it would be:
{{ drupal_entity('profile', comment.uid.content.profile_personnel.target_id) }}

But I think that would embed the profile, not link to it, which is why you want something like the path function.
Comment: I have an error message
 Symfony\Component\Routing\Exception\InvalidParameterException : Parameter "profile" for route "entity.profile.canonical" must match "[^/]++" ("" given) to generate a corresponding URL. dans Drupal\Core\Routing\UrlGenerator->doGenerate() (ligne 204 de /home/www.s1biose.com/public_html/web/core/lib/Drupal/Core/Routing/UrlGenerator.php).
Comment: That's because the variable is not producing an id value, I don't know what it would be based on your setup. You can test it by passing it the actual number just to see it work, then debug the variables to figure out the correct reference.
Comment: In the profile twig, there is {{url}} that displays the url of the profile. How to recover this in the comments ?
Comment: Those variables are only available in that file when it's rendered.
Comment: I can make the complete profile in the user twig with
 {{ content.profile_personnel }} so how to display the profile url in the user twig ?
Comment: I asked a new question about user view https://drupal.stackexchange.com/questions/260148/how-to-display-the-profile-url-in-the-user-view
Comment: You essentially just asked the same question again, and I gave you the answer above. To create links in a twig file, use the `path` function with the id of the entity you want to link to and its applicable canonical route.
Comment: I installed kint on drupal, what should I do to find the right path
Comment: I have the same concern, I want to get the profile id of the user who posted the content. I use `{{ user.displayname }}` but seems to be reading the admin profile only, not the others.
Comment: you got any idea how to deala with it? Would really appreciate your help, here's my thread.https://drupal.stackexchange.com/questions/266456/direct-photo-and-name-to-profile-page


How to build and send hex commands to TV

Question: I have an NEC PX-42VM5HA plasma tv that I am trying to control with the connected computer.  I have the data sheet that shows all the codes to control the tv and the protocol information.  I am unsure how to build the right data structure in python to send the HEX control codes.  Below is the Power Control Codes and the Communications Protocol.
Communication Protocol:
    Interface: RS-232C
    Communication: Asynchronous
    Baud Rate: 9600
    Data Length: 8bits
    Parity: Odd
    Stop Bit: 1bit
    Communication Code: Hex

Power Control Codes
    ON          9FH 80H 60H 4EH 00H CDH
    OFF         9FH 80H 60H 4FH 00H CEH

Here is the code I have so far:
import time
import serial

ser = serial.Serial(
    port='COM1',
    baudrate=9600,
    parity=serial.PARITY_ODD,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS
)

ser.close()
ser.open()
ser.isOpen()

ON=bytearray([0x9FH,0x80H,0x60H,0x4EH,0x00H,0xCDH])
OFF=bytearray([0x9FH,0x80H,0x60H,0x4FH,0x00H,0xCEH])

ser.write(OFF)
time.sleep(30)
ser.write(ON)
ser.close()

Comment: You need to drop those `H` characters, they are not valid in hexadecimal integer notation in python.
Answer: Write out the control codes as strings
ON = "\x9f\x80\x60\x4e\x00\xcd"
ser.write(ON)


Ajuda com LibGdx

Question: Quero saber como faço para criar um evento ao tocar em uma imagem usando a LibGdx...Estou tentando iniciar um jogo e adicionei uma imagem como botao de Play.
Answer: Você deve implementar um InputProcessor, e defini-la como recebedora dos eventos :
Gdx.input.setInputProcessor(instanciaInputProcessor);

Essa interface tem todos os tipos de eventos de input, no caso do touch, você vai precisar usar a câmera pra saber qual a posição relativa do toque(se vc usa só uma simples, com mesma dimensão da tela e sem escalar, não precisa), depois basta checar se essa posição está dentro dos limites da sprite. A wiki da libgdx mostra um exemplo completo :
public class SimplerTouchTest extends ApplicationAdapter implements InputProcessor {
public final static float SCALE = 32f;
public final static float INV_SCALE = 1.f/SCALE;
public final static float VP_WIDTH = 1280 * INV_SCALE;
public final static float VP_HEIGHT = 720 * INV_SCALE;

private OrthographicCamera camera;
private ExtendViewport viewport;
private ShapeRenderer shapes;

@Override public void create () {
    camera = new OrthographicCamera();
    viewport = new ExtendViewport(VP_WIDTH, VP_HEIGHT, camera);
    shapes = new ShapeRenderer();
    Gdx.input.setInputProcessor(this);
}

@Override public void render () {
    //Provavelmente você está usando sprite-batch
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    shapes.setProjectionMatrix(camera.combined);
    shapes.begin(ShapeRenderer.ShapeType.Filled);
    shapes.circle(tp.x, tp.y, 0.25f, 16);
    shapes.end();
}

@Override public void resize (int width, int height) {
    viewport.update(width, height, true);
}

@Override public void dispose () {
    shapes.dispose();
}
@Override public boolean touchDown (int screenX, int screenY, int pointer, int button) {
    //Aki vocÊ verifica se o screenX e sceenY estão dentro dos limites da sprite.
    if(screenX > posicaoX && screenX < posicaoX+largura && screenY > posicaoY && screenY < posicaoY+altura){
        //evento aki
    }
    return true;
}
//Abaixo tem mais vários eventos que você tem a obrigação de implementar (ja q e interface, mas use apenas quando quiser)
@Override public boolean mouseMoved (int screenX, int screenY) {
    return false;
}

@Override public boolean touchDragged (int screenX, int screenY, int pointer) {
    return true;
}

@Override public boolean touchUp (int screenX, int screenY, int pointer, int button) {
    return true;
}

@Override public boolean keyDown (int keycode) {
    return false;
}

@Override public boolean keyUp (int keycode) {
    return false;
}

@Override public boolean keyTyped (char character) {
    return false;
}

@Override public boolean scrolled (int amount) {
    return false;
}
}

Tem como simplificar tudo, mas esse modo é o mais seguro que eu conheço

Ajuda com LibGdx


How to sample N points between 0 and R if they are exponentially distributed?

Question: The density of my points x $\in$ [0,R] is exponential:
$\rho(x) \approx e^x$
How can I sample N points from there?
Thanks,
Answer: This is an important class of problems, with many different sorts of solutions.  We give a procedure that is general, but has important drawbacks.
A random variable $X$ with density function a constant times $e^x$ on $[0,R]$ and $0$ elsewhere is unlikely to come up in applications. In order for the integral over $[0,R]$ to be $1$, the density function of $X$ will be given by
$$f(x)=\frac{e^x}{e^R-1}$$
on $[0,R]$, and $0$ elsewhere. On the interval $[0,R]$, the cumulative distribution function $F(x)$ is given by
$$F(x)=\frac{e^x-1}{e^R-1}.$$
To simulate, we use independent uniforms $U$ on the interval $[0,1]$, and solve the equation
$$\frac{e^X-1}{e^R-1}=U.$$
We get
$$X=\ln(1+(e^R-1)U).$$


MIDI count in with Lilypond

Question: I tend to score in lilypond most of the classical piano pieces I practice. It forces me to examine the score in detail and it is also useful to audibly check against what I read/play.
Is it possible to set a count in with MIDI generated output? Ideally, nothing would appear in the score.
To date, I have just been using \midi { } after the \layout
Answer: Yes, you can make a count-in that you can hear in the midi file, but doesn't show up in the pdf score.  The trick is actually to make two score blocks (one with the count-in and one without).  Fortunately this is reasonably easy if you use variables.
Normally when using multiple instruments in a score you would want to wrap them both in double chevrons << >>, but this isn't appropriate here as you don't want them to be simultaneous, you want instruments to be sequential — so braces are required { }.
    \version "2.18.2"

    % Clave
    clave = {
        \new DrumStaff {
            \drummode {
                cl4 cl cl cl |
            }
        }
    }

    % Piano
    piano = {
        \new Staff {
             c'4 d' c' d' |
        }
    }

    %% PDF
    \score {
        \piano
        \layout { }
    }

    %% MIDI
    \score {
        {
            \clave
            \piano
        }
        \midi { }
    }

MIDI count in with Lilypond


What is the difference in notation for Ln(z) vs. ln(z)

Question: We are learning about the principal vs. non-principal values of the natural logarithm. There are 2 problems:

$\ln(-7)$
$\operatorname{Ln}(-7)$

I solved $\ln(-7)$ for:
$$=\ln|-7|+i\pi+2\pi k$$
Is the difference in notation for the other problem really just removing the $2\pi k$? Or maybe it would be better if I define the argument like $-\pi<\theta<\pi$?
Comment: Which branches are these, i.e., what are your definitions of $\ln$ and $\operatorname{Ln}$?
Comment: As a multivalue function, $\ln{z}$ has, as you mentioned has the periodic $2\pi k$.  the $Ln{z}$ is the principal branch.
Comment: There's no "canonical" choice for the branch cut of logarithm. I'd say that choosing a branch to take values in $(-\pi, \pi]$ is most common, but this is not universal, and not the right choice for all situations. For example, when using contour integration to evaluate certain real integrals involving the logarithm over $[0, \infty)$, choosing the branch with values in $[0, 2\pi)$ is easiest.
Comment: @Travis So there isn't a standard range then? Should I explicitly write that $-\pi<\theta<\pi$ ?
Comment: I see, I see. Ok. Good to know, that's all I was wondering. Thanks!!
Answer: It is a convention in complex analysis to denote the principle branch of a multivalued function by capitalizing the first letter.
In this case, $\operatorname{Ln}(z) = \operatorname{Ln}|z|+i \operatorname{Arg}(z)$
As for $\operatorname{Ln}$, $\operatorname{Arg}$ is the principle branch of the the argument function, taking values in $(-\pi, \pi]$.
Comment: Yes, that is correct.
Comment: yes it is....that is it
Comment: It is convention. If you are using it numerous times, and are afraid of ambiguities, you could define it yourself the first time it is used.
Comment: I guess my question was worded ambiguously. I simply want to know if the difference between the final answers for both problems is just writing the $2\pi k$ or not.
Comment: Oh wow....ok so I guess I have the concept right, I'm just wondering about the notation for the final answers. Do I assume that everyone knows that $Ln$ is defined in $(-\pi,\pi]$ or does that part also need to be written?
Comment: Assume that my professor is super formal....lol
Comment: Thanks @MathMajor that's basically what I was wondering.


Can we recover a compact smooth manifold from its ring of smooth functions?

Question: It is well-known that if $X$ is a reasonably nice topological space (compact Hausdorff, say) then we can recover $X$ from the ring $C(X)$ of continuous functions $X\to\mathbb R$; see this MSE question for a discussion and problem 26 in the first chapter of Atiyah MacDonald for the construction. Is the same true for a compact smooth manifold $M$ and its ring $C^\infty(M)$ of smooth functions? More specifically,

Let $M$ and $N$ be compact smooth manifolds. If $C^\infty(M)$ and $C^\infty(N)$ are isomorphic, then are $M$ and $N$ necessarily diffeomorphic?
Can we recover the topological space $M$ from $C^\infty(M)$? If so, can we also recover the smooth structure on $M$?
Comment: See Milnor-Stasheff, exercise 1C. 2(b) is slightly subtle and it's not yet completely obvious to me how to recover charts from the structure of the ring $C^\infty(M)$ alone.
Comment: [This question on MSE](http://math.stackexchange.com/questions/1577985/smooth-manifold-m-is-completely-determined-by-the-ring-f?rq=1) refers to that problem (for reference).
Comment: If I'm not wrong you can find the proofs in the paper Ordinary differential equations on vector bundles and chronological calculus (R. V. Gamrelidze; A. A. Agrachev; S. A. Vakhrameev). I'll try to write an answer later..
Answer: [I assume all "smooth manifolds" are Hausdorff and paracompact.]
Yes, you can recover $M$ as a smooth manifold from the ring $C^\infty(M)$.  Here's a quick sketch.
First, note that we can recover the set of connected components of $M$, since each connected component $N\subseteq M$ corresponds to a minimal nonzero idempotent in $C^\infty(M)$, and the ideal generated by such an idempotent is isomorphic as a rng to $C^\infty(N)$.  Thus we can recover each of the rings $C^\infty(N)$ from $C^\infty(M)$, so we may assume without loss of generality that $M$ is connected.
Now note that every ring-homomorphism $\varphi:C^\infty(M)\to\mathbb{R}$ is evaluation at a point of $M$, which lets us recover the set of points of $M$ from $C^\infty(M)$.  For details, see the answers to this question.
So we've recovered the set $M$, and we also know how to think of elements of $C^\infty(M)$ as functions $M\to\mathbb{R}$ (since we identify points of $M$ with their evaluation homomorphisms). We can now also recover the smooth structure: we know exactly which functions $M\to\mathbb{R}$ are smooth, so we also know exactly which functions $M\to\mathbb{R}^n$ are smooth.  Since every connected manifold $N$ embeds in $\mathbb{R}^n$ for some $n$, we also know exactly which functions $M\to N$ are smooth for any such $N$.  This means we have recovered the entire functor $\operatorname{Hom}(M,-)$ on the category of connected smooth manifolds.  By Yoneda, this is enough to recover $M$.
Comment: sorry for reviving, may you elaborate on how one use Yoneda to recover $M$? So I guess you have shown that $C^\infty(M)$ uniquely determines $Hom(M,-)$, so if $C^\infty(M) \cong C^\infty(N)$, then so are their Hom functors, hence by Yoneda's, $M \cong N$ in category of connected smooth manifolds?
Comment: Yes, that's correct.
Answer: I believe this is proven in Chapter 7 of Nestruev's Smooth Manifolds and Observables, but I haven't checked carefully. More precisely, the functor $M \to C^{\infty}(M)$ from smooth manifolds to the opposite of real commutative algebras is fully faithful, meaning that smooth maps $M \to N$ are precisely algebra maps $C^{\infty}(N) \to C^{\infty}(M)$.
Comment: You shouldn't even need the $\mathbb{R}$-algebra structure.  If $M$ is connected, the constant functions can be described as the unique maximal subfield of $C^\infty(M)$ (since every non-constant function takes a rational value, and hence some rational polynomial in it is non-invertible but not identically $0$).  If $M$ is disconnected, you can apply this to each component separately, since you can recognize the components are determining the idempotents in $C^\infty(M)$.
Comment: Alternatively, you can say there is only one ring-homomorphism $f:\mathbb{R}\to C^\infty(M)$, since such a homomorphism must be order preserving (you can prove this by thinking about square roots, though you have to be a bit careful how you state things since $\sqrt{x}$ is only smooth on $(0,\infty)$, not $[0,\infty)$).
Comment: Ah, that's very nice. So in fact the embedding into affine schemes is fully faithful.
Answer: I want to give full steps to this problem. The answer is that one can recover $M$ from $\mathscr{C}^{\infty}(M)$ for  arbitrary manifold  $M$ (assuming second countability and Hausdorff).

First step, recover the space. Let
$$\Sigma=\{\textrm{non-zero $\mathbb{R}$-algebra homomoprhoism $F:\mathscr{C}^{\infty}(M)\to \mathbb{R}$}\}$$
Actually, any $F\in \Sigma$ is a calculation, say $f\mapsto f(x)$ for some fixed $x$.

Proof. Pick a "step" smooth function $f_0: M\to \mathbb{R}$ such that for any $\lambda\in \mathbb{R}$, $f_0^{-1}(\lambda)$ is compact (with using the assumption of existence of countable partition of unity). Assume $F$ is not a calculation, then
$$\forall x\in M, \exists f_x\in\mathscr{C}^{\infty}(M),\quad  \textrm{such that}\quad f_x(x)\neq F(f_x)$$
replace $f_x$ by $f_x-F(f_x)$, one can assume that $f_x(x)\neq 0$ and $Ff_x=0$. Then
$$U_x=\{a\in M: f_x(a)\neq 0\}\ni x$$
gives a open cover of $f_0^{-1}(F(f_0))$, thus there exists finite subset $X_0$ such that $\{U_x: x\in X_0\}$ cover $f_0^{-1}(F(f_0))$, construct
$$g=(f_0-Ff_0)^2+\sum_{x\in X_0} f_x^2\qquad Fg=0$$
but for any $y\in M$, $g(y)>0$. $\square$

Second steo, recover the topology. Topologize $\Sigma$ with the weak topology such that for any $f\in \mathscr{C}^\infty(M)$, $F\mapsto F(f)$ is continuous. Then
$$\varphi: M\to \Sigma\qquad x\mapsto [f\mapsto f(x)]$$
is homoemorphism.

Proof. Firstly, the map is surjective by above. By Urysohn's Lemma of smooth version, the map is injective. To show the map is continuous, it suffices to show $[F\mapsto F(f)]\circ \varphi=f$ is continuous, which is trivial. To show the map is closed map, for any closed $A$, by Urysohn Lemma of smooth version, there exists an $f:M\to \mathbb{R}$ such that $f^{-1}(0)=A$. This shows $\varphi(A)=[F\mapsto F(f)]^{-1}(A)$ is closed. $\square$

Third step, recover its smooth structure 1. Now pick $p\in M=\Sigma$, One can defines a equivalent relation on $\mathscr{C}^{\infty}(M)$
$$f\sim g\iff f|_U=g|_U\textrm{ for some open neighborhood $U$ around $p$}$$
Then the corresponding quotient space is exactly the germ of $\mathscr{C}^{\infty}_p(M)$.

Proof. Let $(f,U)$ be a representation of some germ at $x$, then by times a bump function, one can show that there exists some $g$ defining all over $M$ such $g|_V=f|_V$ for some more small neighborhood of $x$. $\square$

Fourth step, recover its smooth structure 2. Now let
$$\mathfrak{m}_p=\{f\in \mathscr{C}^{\infty}_p(M): f(p)=0\}$$
One knows that $\mathfrak{m}_p/\mathfrak{m}_{p}^2$ is exactly the cotangent space at $p$. Let $x^1,\ldots,x^n \in \mathscr{C}^{\infty}(M)$, such that their image in $\mathfrak{m}_p/\mathfrak{m}_{p}^2$ forms a basis. It must form a local coordination for $x$.

Proof. That means $dx^1, \ldots, dx^n$ forms a basis of cotangent space at $x$. It must form a local coordination for $x$. It is a consequence of inverse maps theorem. $\square$
Once the local coordination is recovered, the proof is complete.
Answer: As Eric Wofsey points out, because $M$ as a topological space is the space of homomorphisms $C^\infty(M) \to \Bbb R$, appropriately topologized, we know precisely what the elements of $C^\infty(M)$ are as functions on $M$. So we can recover the space $C^\infty(M)_p$ of germs at $p$, and hence we can recover the dimension of $M$ as the dimension of the space of derivations. Now we can pick a set of $n$ functions $M \to \Bbb R$ such that these functions induce an isomorphism $T_pM \to T_p \Bbb R^n$; restricting the functions to an appropriate subset of $M$, these are charts. So we can explicitly construct the charts from $C^\infty(M)$.
A deeply fancy way of explaining what's going on (even though you can do the above in all dimensions, and smoothing theory proper only in dimension $n \geq 5$) is smoothing theory. Smoothing theory equips a topological manifold $M$ with a "tangent microbundle", and if you can lift this microbundle structure to an honest vector bundle, this lift provides your manifold with a smooth structure. The point of the above is that, through $C^\infty(M)$ alone, we can construct the tangent bundle $TM$, and hence invoke smoothing theory.
Comment: It's not true that $M$ is the maximal spectrum of $C^\infty(M)$ if $M$ is not compact; it's just the $\mathbb{R}$-points.  (If $M$ is not compact, there are maximal ideals which contain all functions with compact support.)
Comment: @EricW Thanks for the correction. The rest of the answer should still hold with the appropriate modifications.
Answer: What I'll describe next comes from the paper

Ordinary differential equations on vector bundles and chronological calculus (R. V. Gamrelidze, A. A. Agrachev and S. A. Vakhrameev).

In the following $M$ must be second countable (it doesn't have to be compact). For a point $p\in M$ consider the map $\mathsf{ev}_p: C^\infty(M)\longrightarrow \mathbb R$ given by:
$$\mathsf{ev}_p(f):=f(p).$$
It is clearly an $\mathbb R$-algebra morphism.

Theorem 1. There exists a bijection:
$$M\longrightarrow \mathsf{Hom}_{\mathsf{Rng}}(C^\infty(M), \mathbb
 R)-\{0\},$$
which is given by:
$$p\longmapsto \mathsf{ev}_p.$$

The proof can be found in the forementioned paper. However, using this we can characterize easily the smooth functions on $M$.

Theorem 2. There exists a bijection:
$$C^\infty(M, N)\longrightarrow
 \mathsf{Hom}_{\mathsf{Alg}}(C^\infty(N), C^\infty(M))$$
which is given by:
$$f\longmapsto (f^*: C^\infty(N)\longrightarrow C^\infty(M),
 g\longmapsto g\circ f),$$
  which preserves composition.

It is easy to see this map is well defined (that is, $f^*$ is a homomorphism of $\mathbb R$-algebras). On the other hand, given $g\in \mathsf{Hom}_{\mathsf{Alg}}(C^\infty(N), C^\infty(M))$ define:
$$f(p):=q\quad (p\in M),$$
where $q\in N$ is the unique point such that:
$$\mathsf{ev}_p\circ g=\mathsf{ev}_q.$$
Such point $q$ exists by Theorem 1. applied to the nonzero ring homomorphism $$\mathsf{ev}_p\circ g:C^\infty(M)\longrightarrow \mathbb R.$$
The smoothness of $f$ follows from the following criterium:
$$f\in C^\infty(M, N)\Leftrightarrow h\circ f\in C^\infty(M)\ \forall h\in C^\infty(N).$$
In fact:
$$f^*(h)(p)=h(f(p))=h(q)=\mathsf{ev}_q(h)=\mathsf{ev}_p\circ g(h)=g(h)(p),$$ for every $h\in C^\infty(N)$ and for every $p\in M$, that is $$f\circ h=g(h)\in C^\infty(M)\ \forall h\in C^\infty(N),$$ and we are done. The above computation also shows that $f^*=g$.
Now using the above you can show easily $f$ is a diffeomorphism if and only if $f^*$ is an isomorphism of algebras.
I believe the above constructions gives an equivalence (maybe an isomorphism) of categories between the category of second countable manifolds $\mathsf{Man}$ and the category $\mathsf{Alg}_{\mathbb R}$ of $\mathbb R$-algebras. Just check how the categories $\mathsf{Man}$ and $\mathsf{Alg}_{\mathbb R}$ are defined in order to this equivalence to hold.
Comment: This is definitely not an equivalence between $\mathsf{Man}$ and $\mathsf{Alg}_{\mathbb R}$: most $\mathbb{R}$-algebras are not isomorphic to $C^\infty(M)$ for any manifold $M$.  Also, it's contravariant.  What it does give is an equivalence between $\mathsf{Man}$ and a full subcategory of $\mathsf{Alg}_{\mathbb R}^{op}$.
Comment: @Bumblebee There is a nice discussion of this in Chapter 7 of Nestruev's Smooth Manifolds and Observables, mentioned in Qiaochu Yuan's answer. An $\mathbb{R}$-algebra $F$ is of the form $C^{\infty}(M)$ if and only if 1) it is geometric, meaning that if an element $f$ of $F$ is sent to zero by any $\mathbb{R}$-algebra map $F \to \mathbb{R}$ then it is already zero, 2) it is complete (the definition of which doesn't fit in this comment) and 3) it is locally isomorphic to $C^{\infty}(\mathbb{R}^n)$ for fixed $n$.
Comment: @EricWofsey: This is interesting. Do you know a good reference for this equivalance?
Comment: @Bumblebee: Not sure what you mean.  The equivalence is exactly what Theorem 2 of this answer says.
Comment: @EricWofsey: I was thinking about this full subcategory of $\mathsf{Alg}_{\mathbb R}.$ What are the properties of it? How can we identify it ? Explicitly, is there any way we can identify whether a given algebra is isomorphic to an algebra of smooth functions over a manifold?
Comment: @Bumblebee: I don't know anything about that off the top of my head.