How do I add custom field to Python log format string?

Question: My current format string is:
formatter = logging.Formatter('%(asctime)s : %(message)s')

and I want to add a new field called app_name which will have a different value in each script that contains this formatter.
import logging
formatter = logging.Formatter('%(asctime)s %(app_name)s : %(message)s')
syslog.setFormatter(formatter)
logger.addHandler(syslog)

But I'm not sure how to pass that app_name value to the logger to interpolate into the format string. I can obviously get it to appear in the log message by passing it each time but this is messy.
I've tried:
logging.info('Log message', app_name='myapp')
logging.info('Log message', {'app_name', 'myapp'})
logging.info('Log message', 'myapp')

but none work.
Comment: Do you really want to pass this in to every `log` call? If so, look at [the docs](http://docs.python.org/3.3/library/logging.html#logrecord-objects) where it says "This functionality can be used to inject your own values into a LogRecord…" But this seems like a prime case for using `logger = logging.getLogger('myapp')` and having it baked into the `logger.info` call.
Comment: the python logging can already do that afaik. if you use a different `logger` object in each app, you can make each one use a different name by instantiating your `logger`s like so: `logger = logging.getLogger(myAppName)`. note that `__name__` is the python module name, so if each app is its own python module, that would work as well.
Answer: You could use a LoggerAdapter so you don't have to pass the extra info with every logging call:
import logging
extra = {'app_name':'Super App'}

logger = logging.getLogger(__name__)
syslog = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(app_name)s : %(message)s')
syslog.setFormatter(formatter)
logger.setLevel(logging.INFO)
logger.addHandler(syslog)

logger = logging.LoggerAdapter(logger, extra)
logger.info('The sky is so blue')

logs (something like)
2013-07-09 17:39:33,596 Super App : The sky is so blue

Filters can also be used to add contextual information.
import logging

class AppFilter(logging.Filter):
    def filter(self, record):
        record.app_name = 'Super App'
        return True

logger = logging.getLogger(__name__)
logger.addFilter(AppFilter())
syslog = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(app_name)s : %(message)s')
syslog.setFormatter(formatter)
logger.setLevel(logging.INFO)
logger.addHandler(syslog)

logger.info('The sky is so blue')

produces a similar log record.
Comment: How can we specify that in a `config.ini` file? I wish to add the current host name `socket.gethostname()`.
Comment: Can I just pass a string of Extra Info. Something like this:                                   "Error occurred for employee ID 1029382" Without creating any dictionary.
Comment: I have this sample not working for me.
```import uuid
    uniqueId = str(uuid.uuid4())
    extra  = {"u_id" : uniqueId}
RotatingHandler = RotatingFileHandler(LOG_FILENAME,encoding='utf-8',maxBytes=maxSize, backupCount=batchSize)

    logger.basicConfig(handlers=[RotatingHandler],level=logLevel.upper(),format='%(levelname)s %(u_id)s %(funcName)s  %(asctime)s %(message)s ',datefmt='%m/%d/%Y %I:%M:%S %p')
    logger = logger.LoggerAdapter(logger=logger, extra=extra)```
Comment: Is it possible to add a field "level" which is equal to "levelname"? See: [How can I rename "levelname" to "level" in Python log messages?](https://stackoverflow.com/q/52929290/562769)
Answer: Python3
As of Python3.2 you can now use LogRecordFactory
import logging

logging.basicConfig(format="%(custom_attribute)s - %(message)s")

old_factory = logging.getLogRecordFactory()

def record_factory(*args, **kwargs):
    record = old_factory(*args, **kwargs)
    record.custom_attribute = "my-attr"
    return record

logging.setLogRecordFactory(record_factory)

>>> logging.info("hello")
my-attr - hello

Of course, record_factory can be customized to be any callable and the value of custom_attribute could be updated if you keep a reference to the factory callable.
Why is that better than using Adapters / Filters?

You do not need to pass your logger around the application
It actually works with 3rd party libraries that use their own logger (by just calling logger = logging.getLogger(..)) would now have the same log format. (this is not the case with Filters / Adapters where you need to be using the same logger object)
You can stack/chain multiple factories
Comment: This is nowaday's python3 best answer
Comment: According to https://docs.python.org/3/howto/logging-cookbook.html:

This pattern allows different libraries to chain factories together, and as long as they don't overwrite each other's attributes or unintentionally overwrite the attributes provided as standard, there should be no surprises. However, it should be borne in mind that each link in the chain adds run-time overhead to all logging operations, and the technique should only be used when the use of a Filter does not provide the desired result.
Comment: @steve0hh one of the key desired results is the ability to log contextual information across different libraries/modules, which could only be achieved using this way.
In most circumstances, libraries should not be touching the logger configuration, it's the responsibility of the parent application.
Comment: Is any alternative for python 2.7?
Comment: Not with the same benefits, with 2.7 you'd have to go with Adapters or Filters.
Comment: Perfect, exactly what I was looking for. Especially since it affects all the 3rd party loggers.
Comment: Note that this applies to all the logs. With Filter(s) you can limit to which Handler(s) it gets applied.
Comment: The only one out of the answers here that has actually worked for me (Python 3.9.5)
Comment: what if a 3rd party logger, overrides the `makeRecord` method without caring about the `logRecordFactory` ?
Comment: Unfortunately it is not possible to combine this with `LoggerAdapter`, e.g. to supply a default value for custom attribute via the factory and then override it via `LoggerAdapter`
Comment: I like the pythonic _consistent_ naming of the `setLogRecordFactory` method - face-palm :\
Comment: Maybe I'm missing something here, why is this better than say setting a custom attribute in the Formatter (i.e. logging.Formatter(f'{custom_attribute} - %(asctime)s - %(name)s - %(levelname)s - %(message)s')) and setting this formatter on the root handler. Not criticising your solution, just trying to understand which is better to use and why :)
Answer: You need to pass the dict as a parameter to extra to do it that way.
logging.info('Log message', extra={'app_name': 'myapp'})

Proof:
>>> import logging
>>> logging.basicConfig(format="%(foo)s - %(message)s")
>>> logging.warning('test', extra={'foo': 'bar'})
bar - test

Also, as a note, if you try to log a message without passing the dict, then it will fail.
>>> logging.warning('test')
Traceback (most recent call last):
  File "/usr/lib/python2.7/logging/__init__.py", line 846, in emit
    msg = self.format(record)
  File "/usr/lib/python2.7/logging/__init__.py", line 723, in format
    return fmt.format(record)
  File "/usr/lib/python2.7/logging/__init__.py", line 467, in format
    s = self._fmt % record.__dict__
KeyError: 'foo'
Logged from file <stdin>, line 1

Comment: I like @mr2ert answer. You can give a default value to the extra field by extending the `logging.Formatter` class:

    class CustomFormatter(logging.Formatter):
        def format(self, record):
            if not hasattr(record, 'foo'):
                record.foo = 'default_foo'
            return super(CustomFormatter, self.format(record)

    h = loggin.StreamHandler()
    h.setFormatter(CustomFormatter('%(foo)s %(message)s')
    logger = logging.getLogger('bar')
    logger.addHandler(h)

    logger.error('hey!', extra={'foo': 'FOO'})

    logger.error('hey!')
Comment: Will this also work for `logging.info()`? It failed when I tried last. :/
Comment: This method is faster but you need to add the extra lines on each log message which is easy to forget and prone to errors. Replacing the super() calls is messier than the answer from unutbu.
Comment: @Prakhar Mohan Srivastava Yes It'll work fine for logging.info() as well. What error message are you getting ?
Comment: Can I just pass a string of Extra Info. Something like this:                                   "Error occurred for employee ID 1029382" Without creating any dictionary and passing the keys
Answer: Another way is to create a custom LoggerAdapter. This is particularly useful when you can't change the format OR if your format is shared with code that does not send the unique key (in your case app_name):
class LoggerAdapter(logging.LoggerAdapter):
    def __init__(self, logger, prefix):
        super(LoggerAdapter, self).__init__(logger, {})
        self.prefix = prefix

    def process(self, msg, kwargs):
        return '[%s] %s' % (self.prefix, msg), kwargs

And in your code, you would create and initialize your logger as usual:
    logger = logging.getLogger(__name__)
    # Add any custom handlers, formatters for this logger
    myHandler = logging.StreamHandler()
    myFormatter = logging.Formatter('%(asctime)s %(message)s')
    myHandler.setFormatter(myFormatter)
    logger.addHandler(myHandler)
    logger.setLevel(logging.INFO)

Finally, you would create the wrapper adapter to add a prefix as needed:
    logger = LoggerAdapter(logger, 'myapp')
    logger.info('The world bores you when you are cool.')

The output will look something like this:
2013-07-09 17:39:33,596 [myapp] The world bores you when you are cool.

Answer: I found this SO question after implementing it myself. Hope it helps someone. In the code below, I'm inducing an extra key called claim_id in the logger format. It will log the claim_id whenever there is a claim_id key present in the environment. In my use case, I needed to log this information for an AWS Lambda function.
import logging
import os

LOG_FORMAT = '%(asctime)s %(name)s %(levelname)s %(funcName)s %(lineno)s ClaimID: %(claim_id)s: %(message)s'

class AppLogger(logging.Logger):

    # Override all levels similarly - only info overriden here

    def info(self, msg, *args, **kwargs):
        return super(AppLogger, self).info(msg, extra={"claim_id": os.getenv("claim_id", "")})

def get_logger(name):
    """ This function sets log level and log format and then returns the instance of logger"""
    logging.setLoggerClass(AppLogger)
    logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
    logger = logging.getLogger(name)
    logger.setLevel(logging.INFO)
    return logger

LOGGER = get_logger(__name__)

LOGGER.info("Hey")
os.environ["claim_id"] = "12334"
LOGGER.info("Hey")

Gist: https://gist.github.com/ygivenx/306f2e4e1506f302504fb67abef50652
Answer: The accepted answer did not log the format in logfile, whereas the format was reflected in sys output.
Alternatively I used a simpler approach and worked as;

logging.basicConfig(filename="mylogfile.test",
                    filemode="w+",
                    format='%(asctime)s: ' +app_name+': %(message)s ',
                    level=logging.DEBUG)
Comment: simple and easy!
Answer: If you need a default extra mapping, and you want to customize it for ad-hoc log messages, this works in Python 2.7+ by creating a LoggerAdapter that merges a default extra dictionary with any extra from a given message.
import logging
import os
import sys

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s %(levelname)-8s Py%(python)-4s pid:%(pid)-5s %(message)s',
)
_logger = logging.getLogger("my-logger")
_logger.setLevel(logging.DEBUG)

class DefaultExtrasAdapter(logging.LoggerAdapter):
    def __init__(self, logger, extra):
        super(DefaultExtrasAdapter, self).__init__(logger, extra)

    def process(self, msg, kwargs):
        # Speed gain if no extras are present
        if "extra" in kwargs:
            copy = dict(self.extra).copy()
            copy.update(kwargs["extra"])
            kwargs["extra"] = copy
        else:
            kwargs["extra"] = self.extra
        return msg, kwargs

LOG = DefaultExtrasAdapter(_logger, {"python": sys.version_info[0], "pid": os.getpid()})

if __name__ == "__main__":
    LOG.info("<-- With defaults")
    LOG.info("<-- With my version", extra={"python": 3.10})
    LOG.info("<-- With my pid", extra={"pid": 0})
    LOG.info("<-- With both", extra={"python": 2.7, "pid": -1})

Results:
2021-08-05 18:58:27,308 INFO     Py2    pid:8435  <-- With defaults
2021-08-05 18:58:27,309 INFO     Py3.1  pid:8435  <-- With my version
2021-08-05 18:58:27,309 INFO     Py2    pid:0     <-- With my pid
2021-08-05 18:58:27,309 INFO     Py2.7  pid:-1    <-- With both

Answer: Using mr2ert's answer, I came up with this comfortable solution (Though I guess it's not recommended) - Override the built-in logging methods to accept the custom argument and create the extra dictionary inside the methods:
import logging

class CustomLogger(logging.Logger):

   def debug(self, msg, foo, *args, **kwargs):
       extra = {'foo': foo}

       if self.isEnabledFor(logging.DEBUG):
            self._log(logging.DEBUG, msg, args, extra=extra, **kwargs)

   *repeat for info, warning, etc*

logger = CustomLogger('CustomLogger', logging.DEBUG)
formatter = logging.Formatter('%(asctime)s [%(foo)s] %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)

logger.debug('test', 'bar')

Output:
2019-03-02 20:06:51,998 [bar] test

This is the built in function for reference:
def debug(self, msg, *args, **kwargs):
    """
    Log 'msg % args' with severity 'DEBUG'.

    To pass exception information, use the keyword argument exc_info with
    a true value, e.g.

    logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
    """
    if self.isEnabledFor(DEBUG):
        self._log(DEBUG, msg, args, **kwargs)

Answer: import logging;
class LogFilter(logging.Filter):
def __init__(self, code):
    self.code = code

def filter(self, record):
    record.app_code = self.code
    return True

logging.basicConfig(format='[%(asctime)s:%(levelname)s]::[%(module)s -> %(name)s] - APP_CODE:%(app_code)s - MSG:%(message)s');
class Logger:
def __init__(self, className):
    self.logger = logging.getLogger(className)
    self.logger.setLevel(logging.ERROR)

@staticmethod
def getLogger(className):
    return Logger(className)

def logMessage(self, level, code, msg):
    self.logger.addFilter(LogFilter(code))

    if level == 'WARN':
        self.logger.warning(msg)
    elif level == 'ERROR':
        self.logger.error(msg)
    else:
        self.logger.info(msg)

class Test:
    logger = Logger.getLogger('Test')
if __name__=='__main__':
    logger.logMessage('ERROR','123','This is an error')

Comment: This implementation will be very inefficient.


How write datatype in file with julia

Question: In julia, I would like write in a file a variable and his type in order to reuse it later. Like this:
var = Float64(15)
stream = open("foo.dat", "w")
write(stream, typeof(var))
write(stream, var)
close(stream)

stream = open("foo.dat", "r")
typevar = read(stream, DataType)
var = read(stream, typevar)
close(stream)

The third line doesn't work :
ERROR: LoadError: MethodError: `write` has no method matching write(::IOStream, ::Type{Float64})
Closest candidates are:
write(::IO, ::Any)

How can I do this? Thank you :)
Comment: Have you looked into the JLD package?  You can use that to store complete Julia objects, which will include their types.
Comment: Also, depending on what you want, that might not even be necessary.  For instance, if you just have an Array of say `Float64` objects, then you could just use `writedlm` to write it to a .txt file and then `readdlm` to read it back in.  `readdlm` will take an optional argument to specify the type when reading the data back in.
Comment: JLD is the correct solution. What error do you get?
Comment: Thank you Michael :) I look JLD and HDF5 packages. writedlm write text, but I would to write binary.
Comment: Well, I'm not certain of this, but I don't know of a way to write a file type to a canonical binary file - I suspect that there might not be a way, since file types differ across languages, but I could easily be wrong.  As a work-around, however, you could just write one extra number or character at the beginning of your file that represents a file type and then keep a dictionary that maps those on to file types.  A bit of a hack, but it would probably do the trick.
Comment: I could not run JDL. HDF5 works well, but I don't understand how it encodes the file.
Answer: Since there doesn't seem to be any strong requirements about the format of your file, using the JLD package is the best way, as many commenters have said above. It will automatically track the types of everything you store in it, and so you can read the values back directly.
You will have to install the package with Pkg.add("JLD") . Having done that, using it is simple:
julia> using JLD
INFO: Precompiling module JLD...
INFO: Recompiling stale cache file /Users/aviks/.julia/lib/v0.4/FileIO.ji for module FileIO.

julia> a=10
10

julia> b="A String"
"A String"

julia> c=[1,2]
2-element Array{Int64,1}:
 1
 2

julia> file = jldopen("/tmp/mydata.jld", "w")
Julia data file version 0.1.1: /tmp/mydata.jld

julia> write(file, "a", a)

julia> write(file, "b", b)

julia> write(file, "c", c)

julia> close(file)

Then, when you want to read the variables, in new REPL session
julia> using JLD

julia> d=load("/tmp/mydata.jld")
Dict{ByteString,Any} with 3 entries:
  "c" => [1,2]
  "b" => "A String"
  "a" => 10

julia> d["a"]
10

julia> d["b"]
"A String"

julia> d["c"]
2-element Array{Int64,1}:
 1
 2

More information about the JLD package is available at: https://github.com/JuliaIO/JLD.jl
Answer: My best way :
var = Float64(89)
typevar = string(typeof(var), "\n")

s = open("var.dat", "w")
write(s, typevar, var) # Float64\n@V@
close(s)

s = open("var.dat", "r")
typevar = chomp(readline(s)) # delete "\n"
var = read(s, eval(parse(typevar)))
close(s)

How write datatype in file with julia


How to say $\dim X=|X|$ without using mathematical symbols?

Question: I happen to be in a situation where I have to say $\dim X=|X|$ without using mathematical symbols. Here is the thing I am trying to say:

Let $X$ is a Banach space. $|X|$ denotes the cardinality of the space. If $\dim X=\infty$, then $\dim X=|X|$.

I try to say something like "The basis of an infinite-dimensional Banach space possesses the same cardinality as the entire space". This is a bit awkward.
Is there a better way of saying it?
Comment: How about, "Infinite-dimensional spaces have the same cardinality as their bases"?
Comment: What's the use case of making a mathematical point without using mathematical notation? If the audience knows what cardinality is, why avoid $|X|$ as a symbol?
Comment: @HennoBrandsma: Sometimes you want to avoid using mathemathical symbols, e.g. in an abstract. But for this sort of thing, I cannot really imagine...
Answer:
"Any [Hamel] basis of an infinite dimensional Banach space has the same cardinality as the space itself", or
"There is a bijection between any [Hamel] basis of an infinite dimensional Banach space, and the entire space. I might add, this bijection is certainly not a linear transformation."

Those require you to know what is a Hamel basis and a Banach space, of course. Which may or may not be "as terrible" as mathematical symbols.


How can we configure IIS for domain name mapping

Question: I would like to configure IIS server at(windows server 2003) for domain name mapping.
We have purchased domain name for one of our newly created website. I would like to know how can i configure IIS so that anybody from outside world can reach wensite by typing url.
say http://xyz.com/ it should redirect at my website home page.
I have made website in using asp.net and oracle.
Please help me? If there is some tutorial/ link please forward me.
This is my first experience of hosting.
Answer: You will need to configure your DNS settings for the domain you purchased so that the "A" record points to the IP address of your web server.
Then you need to configure a website on your IIS server and specify the host header which matches up to the domain name you purchased.
This tutorial should help: http://www.visualwin.com/host-header/


VSCode não interpreta tags do Ionic 6

Question: Olá! Tenho um workspace no VSCode com vários projetos incluindo alguns em Ionic em versões anteriores à versão 6, todas funcionando normalmente. Agora fui criar um novo projeto com as atualizações mais recentes do Angular 13.2.2 e Ionic 6.0.0 e as tags do Ionic não são mais reconhecidas no html dos componentes, apesar do projeto estar executando. O que devo fazer para tirar estes erros no Html, que dizem:
'ion-app' is not a known element:???
Obrigado pela ajuda!!!!
Answer: Pelo o que eu entendi você está se referindo a componentes criados por você, correto?
Por algum motivo que ate hoje nao entendo, ao criar um componente o ionic o faz sem o arquivo de module.ts, sendo necessario criar manualmente... digamos que seu componente se chame myHeader
Você terá na sua pasta os seguintes arquivos:

myheader.component.html

myheader.component.scss

myheader.component.spec.ts

myheader.component.ts

Crie o seguinte arquivo:
myheader.component.module.ts e adicione o seguinte código
<code>import { HeaderComponent } from './header.component';
import { IonicModule } from '@ionic/angular';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

@NgModule({
  declarations: [
    //Nome do seu componente
    MyHeaderComponent
  ],
  imports: [
    CommonModule,
    IonicModule
  ],
  exports: [
    //Nome do seu componente
    MyHeaderComponent
  ],
  providers: []
})

export class MyCustomHeader {}
</code>
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: Oi Maurício! Obrigado pela resposta! O componente fui eu mesmo que criei, mas ele já está com o módulo incluso e portanto com todas as configurações corretas. Se executar o projeto ele funciona normalmente o problema é que todas as tags  não estavam sendo reconhecidas dentro do arquivo html do componente, ficando com uma linha vermelha debaixo. Acabei resolvendo o problema quando atualizei o angular para a versão 14.0.0 o erro desapareceu. Acredito que seja alguma incompatibilidade de versões mesmo.

VSCode não interpreta tags do Ionic 6


Prove that if we add the edge $(u,v)$ to $T$, the resulting graph has exactly one cycle.

Question: Let $T$ be a tree with $u,v\in V (T)$, $u$ is not equal to $v$, and $(u,v)$ does not belong to $E(T)$. Prove that if we add the edge $(u,v)$ to $T$, the resulting graph has exactly one cycle.
Comment: What is your problem?
Comment: I can't prove it. I can see it on examples, but I do not know how to prove it.
Comment: What do you know about trees?
Answer: You can do this inductively on the number of leaves of the tree. Base case: two leaves, which is easy because a tree with two leaves is just a line, and adding a single edge to a line either turns the whole thing into a loop or it adds a single loop somewhere inside the line.

If $u$ and $v$ are both not leaves, then remove a leaf and you're done by induction.
If exactly one of $u$ and $v$ is a leaf, then there's another leaf which you can remove and be done by induction again.
Otherwise, both are leaves; either there is a third leaf (in which case done by induction when you remove it) or there's no third leaf (base case).

Note that the inductive step of removing a leaf can't possibly remove any cycles, because a leaf can't be part of a cycle.
Answer: Let n be the number of vertices, e be the number of edges and f be the number of faces. If T is a tree, then we have
$$n = e + 1$$
and since every tree can be represented as a planar graph, Euler's characteristic equation holds, that is,
$$n - e + f = 2$$
which gives f = 1, obviously. Let T ' be the new graph after adding one more edge to T and n', e', f ' be the number of vertices, edges and faces of T ' respectively, with
$$n' = n$$ $$ e' = e + 1$$
Now, without loss of generality, you can add this edge without breaking the planarity (since T has no cycles) so that Euler's characteristic equation still holds for T ':
$$n' - e' + f ' = 2$$
Since you have now n' = e', f ' must be 2. Therefore there is exactly one cycle in the new graph T ' (One face is inside of cycle and one face is outside of cycle).


How can I allow front end users to add their own custom fields?

Question: We have a new project that is going to allow users to add their own nodes of a content type e.g. 'cars'.
There are some existing fields that they need to complete e.g. 'colour' and 'year'. We also need to allow them to add their own custom fields, which only they can use. So one user will add 'mileage' whereas another might want to add 'number of seats'. How would I go about allowing hundreds of users to do this without bloating the content type?
We will be building it in Drupal 7.
Thanks for any help.
Answer: Use Field Collection module.
Install Field Collection module
Create a field collection field to a content type and set to unlimited.
Then create a fields with two text fields - "label" (for 'colour' and 'year') and "value" for that field collection
So when the node add form loads user will have two fields, Label and value with add more button there user can click and add another set of "label" and "value" pair.
Comment: Have a look at the [paragraphs](https://www.drupal.org/project/paragraphs) module too, you can achieve the same things. At least for Drupal 8 field collection is likely going to be replaced by paragraphs.
Comment: Yeah that does look like it will do the job - to some extent. I was thinking the user would be able to define fields of all of their nodes, not on a one by one basis. in other words, they define 'colour' once in their 'settings' and then add the colours for each car - not the label and the value. Gee I ask a lot.
Answer:
I was thinking the user would be able to define fields of all of their nodes, not on a one by one basis. in other words, they define 'colour' once in their 'settings' and then add the colours for each car - not the label and the value

I don't know any module that offers this out of the box, so you would need to write your own custom module. You could try to add a new paragraphs or field_collection field to the user's profile and let them define what custom attribute (e.g. "colour") they want to define (at least in D8 there's also the \Drupal\user\UserDataInterface that can be used to store personal user preferences). Then use a hook_form_alter or something similar to adjust the form when adding a new car and display the name of that specific attribute as a label to another paragraphs/field collection field (which then holds the actual data ,e.g. "red").


Erros no programa para determinar triangulo

Question: Quais erros estou cometendo?

Leia 3 valores de ponto flutuante A, B e C e ordene-os em ordem decrescente, de modo que o lado A representa o maior dos 3 lados. A seguir, determine o tipo de triângulo que estes três lados formam, com base nos seguintes casos, sempre escrevendo uma mensagem adequada:

se A ≥ B+C, apresente a mensagem: NAO FORMA TRIANGULO

se A2 = B2 + C2, apresente a mensagem: TRIANGULO RETANGULO
se A2 > B2 + C2, apresente a mensagem: TRIANGULO OBTUSANGULO
se A2 < B2 + C2, apresente a mensagem: TRIANGULO ACUTANGULO
se os três lados forem iguais, apresente a mensagem: TRIANGULO EQUILATERO
se apenas dois dos lados forem iguais, apresente a mensagem:
  TRIANGULO ISOSCELES

Código:
#include <iostream>
    using namespace std;
    int main(){

        double a=0, b=0, c=0, ValorUm=0, ValorDois=0, ValorTres=0, b2=0, a2=0, c2=0, bc=0, b2c2=0;

//aqui o usuário insere os valores...Usei as variaveis ValorUm...
//para depois inverter para a ordem "a" "b" "c" , os valores tem que
ficar  // em ordem decrecente, o valor maior tem que ser a ..por
 exemplo  //a== 10 , b == 5 , c == 3 do maior para o menor

    cin>>ValorUm>>ValorDois>>ValorTres;

 /*usei os if para inverter as posições, pelo oque testei   o problema
 nao esta nessa parte de trocar as posicoes*/

    if(ValorUm<ValorDois&&ValorDois<ValorTres)  {
        c=ValorUm;
        b=ValorDois;
        a=ValorTres;
        cout<<endl<<a<<endl<<b<<endl<<c<<endl;
    }if(ValorUm>ValorDois&&ValorDois>ValorTres){
        a=ValorUm;
        b=ValorDois;
        c=ValorTres;
        cout<<endl<<a<<endl<<b<<endl<<c<<endl;
    }if(ValorDois>ValorUm&&ValorTres<ValorDois&&ValorTres<ValorUm){
        a=ValorDois;
        b=ValorUm;
        c=ValorTres;
        cout<<endl<<a<<endl<<b<<endl<<c<<endl;
    }if(ValorUm>ValorDois&&ValorUm<ValorTres){
        a=ValorTres;
        b=ValorUm;
        c=ValorDois;
        cout<<endl<<a<<endl<<b<<endl<<c<<endl;
    }if(ValorUm>ValorDois&&ValorTres<ValorUm&&ValorDois<ValorTres){
        a=ValorUm;
        b=ValorTres;
        c=ValorDois;cout<<endl<<a<<endl<<b<<endl<<c<<endl;
    }
    bc=b+c;
    a2=a*a;
    b2=b*b;
    c2=c*c;
    b2c2=b2+c2;
    /*até onde sei é aqui , que está o problema o TRIANGULO OBTUSANGULO
    e o TRIANGULO ACUTANGULO está com diversos erros*/
//a2 a*a b2 c2...  b2c2 é b2+c2 e bc é b+c

        if (ValorUm>ValorDois+ValorTres || ValorUm==ValorDois+ValorTres){
          cout<<"NAO FORMA TRIANGULO"<<endl;

        }
        else
        if(a2==b2c2)
        {
          cout<<"TRIANGULO RETANGULO"<<endl;
        }
        if(a2>b2c2){
          cout<<"TRIANGULO OBTUSANGULO"<<endl;

        }
        if(a2 < b2c2){
            cout<<"TRIANGULO ACUTANGULO"<<endl;
     }
     if(a==c && a!=b){
         cout<<"TRIANGULO ISOSCELES"<<endl;
     }
     if(a==b && a!=c){
         cout<<"TRIANGULO ISOSCELES"<<endl;
     }
    if(a == b && a == c ){
        cout<<"TRIANGULO EQUILATERO"<<endl;
    }
    return 0;
    }

Comment: Seu código está muito poluído, poderia simplificar os if e else, mas isto não vem ao caso, executei seu código e me parece tudo ok, qual seria o erro exatamente?
Answer: Não fiz nenhuma melhoria no seu código, porém darei algumas dicas para melhorá-lo
O saída, indesejada, que você estava encontrado quando a entrada era:
ValorUm=10;
ValorDois=5;
ValorTres=3

Saída:
NAO FORMA TRIANGULO
TRIANGULO OBTUSANGULO

Acontecia pois faltava delimitar o primeiro else com chaves
#include <iostream>
using namespace std;
int main(){

        double a=0, b=0, c=0, ValorUm=0, ValorDois=0, ValorTres=0, b2=0, a2=0, c2=0, bc=0, b2c2=0;

//aqui o usuário insere os valores...Usei as variaveis ValorUm...
//para depois inverter para a ordem "a" "b" "c" , os valores tem que
//ficar   em ordem decrecente, o valor maior tem que ser a ..por
// exemplo  //a== 10 , b == 5 , c == 3 do maior para o menor

    cin>>ValorUm>>ValorDois>>ValorTres;

 /*usei os if para inverter as posições, pelo oque testei   o problema
 nao esta nessa parte de trocar as posicoes*/

    if(ValorUm<ValorDois&&ValorDois<ValorTres)  {
        c=ValorUm;
        b=ValorDois;
        a=ValorTres;
        cout<<endl<<a<<endl<<b<<endl<<c<<endl;
    }if(ValorUm>ValorDois&&ValorDois>ValorTres){
        a=ValorUm;
        b=ValorDois;
        c=ValorTres;
        cout<<endl<<a<<endl<<b<<endl<<c<<endl;
    }if(ValorDois>ValorUm&&ValorTres<ValorDois&&ValorTres<ValorUm){
        a=ValorDois;
        b=ValorUm;
        c=ValorTres;
        cout<<endl<<a<<endl<<b<<endl<<c<<endl;
    }if(ValorUm>ValorDois&&ValorUm<ValorTres){
        a=ValorTres;
        b=ValorUm;
        c=ValorDois;
        cout<<endl<<a<<endl<<b<<endl<<c<<endl;
    }if(ValorUm>ValorDois&&ValorTres<ValorUm&&ValorDois<ValorTres){
        a=ValorUm;
        b=ValorTres;
        c=ValorDois;cout<<endl<<a<<endl<<b<<endl<<c<<endl;
    }
    bc=b+c;
    a2=a*a;
    b2=b*b;
    c2=c*c;
    b2c2=b2+c2;
    /*até onde sei é aqui , que está o problema o TRIANGULO OBTUSANGULO
    e o TRIANGULO ACUTANGULO está com diversos erros*/
//a2 a*a b2 c2...  b2c2 é b2+c2 e bc é b+c

        if ((ValorUm>ValorDois+ValorTres) || (ValorUm==ValorDois+ValorTres)){
          cout<<"NAO FORMA TRIANGULO"<<endl;

        }
        else{ **// FALTAVA ESTÁ CHAVE AQUI**
        if(a2==b2c2)
        {
          cout<<"TRIANGULO RETANGULO"<<endl;
        }
        if(a2>b2c2){
          cout<<"TRIANGULO OBTUSANGULO"<<endl;

        }
        if(a2 < b2c2){
            cout<<"TRIANGULO ACUTANGULO"<<endl;
     }
     if(a==c && a!=b){
         cout<<"TRIANGULO ISOSCELES"<<endl;
     }
     if(a==b && a!=c){
         cout<<"TRIANGULO ISOSCELES"<<endl;
     }
    if(a == b && a == c ){
        cout<<"TRIANGULO EQUILATERO"<<endl;
    }
        }**// FALTAVA ESTÁ CHAVE AQUI**
    return 0;
    }

Sobre "TRIANGULO ACUTANGULO" é um pequeno erro de lógica, verifique as estruturas de condição if/else, pois há alguns if sem o seu respectivo else, por mais que não seja obrigatório cada if possuir seu else, é uma boa pratica faze-lo.
Lembre-se das boas práticas de programação do Deitel:

Indentar ambos os comandos do corpo de uma estrutura if/else;
Se existem vários níveis de indentação, cada nível deve ser
  indentado pelo mesmo espaço adicional

DICAS

Por que fazer tantas estruturas de condições if/else? Seu código é
pequeno, então por agora não terá problemas, mas e no futuro, e se
tiver que implementar um código com milhares de condicionais, fará
tantos if/else assim?

Opte fazer assim: ( Em C, pois não te darei o código pronto! :P)
if (a < b){ x = a; a = b; b = x; }
if (b < c){ x = b; b = c; c = x; }

Veja o quão mais limpo ficará seu código usando o Operador
ternário;
Ao nomear variáveis evite nomes tais como:  bc; a2; c2; b2c2; Dê nomes significativos as variáveis.

Para sanar mais dúvidas, leie esta resposta: Padrão de nomenclatura no código para o C#
Fonte:  Tipos de Triângulos SOLUÇÃO EM C
Tipos de Triângulos SOLUÇÃO EM PYTHON
Comment: Qual o erro lógico, não encontrei erro? bc=b+c;
a2=a*a;
b2=b*b;
c2=c*c;
b2c2=b2+c2;
Comment: Cometi um engano, a lógica está certa, o erro é na cascata de if/else, pois há if sem um else respectivo e por sua vez sem delimitação por chaves.
Comment: @cristovanlopes editei a resposta, veja se sanou suas dúvidas
Answer: #include <iostream>
using namespace std;
int main(){
    double a=0, b=0, c=0, x=0;
    cin>>a>>b>>c;
if (a < b){ x = a; a = b; b = x; }
if (b < c){ x = b; b = c; c = x; }
if (a = b + c) {cout<<"NAO FORMA TRIANGULO"<<endl;}
else
{
if(a*a==b*b+c*c){cout<<"TRIANGULO RETANGULO"<<endl;}
else
if(a*a>b*b+c*c){cout<<"TRIANGULO OBTUSANGULO"<<endl;}
if(a*a < b*b+c*c)
{
cout<<"TRIANGULO ACUTANGULO"<<endl;
}
if(a == b && b == c )
{
cout<<"TRIANGULO EQUILATERO"<<endl;
}
else
{
    if(a==b || b==c){cout<<"TRIANGULO ISOSCELES"<<endl;}
}

 }
}


Why Google Search Console API Only Returns 1,000 Landing pages?

Question: I'm trying to fetch all landing pages from Google Search console, this is working fine on sites with less that 1,000 landing pages but when I try it on larger accounts, it only ever returns 1,000 results.
The limit with the API is 5,000
Here is my query:
       {
         "startDate": str(start_date.strftime("%Y-%m-%d")),
         "endDate": str(end_date.strftime("%Y-%m-%d")),
         "dimensions": [
          "page"
         ],
         "dimensionFilterGroups": [{
             "filters": [
                 {
                 "dimension": "country",
                 "expression": "GBR"
                 },
                 {
                  "dimension": "device",
                  "expression": "desktop"
                  }],
         "rowLimit": 5000}]
        }

Can anyone see what I'm doing wrong, if anything?
API Reference: https://developers.google.com/webmaster-tools/v3/searchanalytics/query
Comment: How old is the data remember webmaster tools doesn't keep data forever if memory services its only three months old.
Comment: Last 90 days of data
Comment: I would check your code then sounds like its not applying the rowLimit property if your only seeing 1000 rows that's default.   try changing it to 1 or something to ensure that its picking it up.
Comment: It says integer value and it works when I set the dimensions to query
Comment: Try adding a "startRow": 0   Might be that the row limit is only recognized if they are both specified.
Comment: Yea I've tried that too
Answer: The dimensionFilterGroups property has a groupType property that you are missing.
The official documentation says:
{
  "startDate": string,
  "endDate": string,
  "dimensions": [
    string
  ],
  "searchType": string,
  "dimensionFilterGroups": [
    {
      "groupType": string,
      "filters": [
        {
          "dimension": string,
          "operator": string,
          "expression": string
        }
      ]
    }
  ],
  "aggregationType": string,
  "rowLimit": integer,
  "startRow": integer
}

Since you have no groupType perhaps it is giving results to a default query and thereby ignoring your rowLimit property.
Answer: I was also getting only 1000 records out of 4000 so I put this noow I am able to get all data.
pageSize:5000,

Comment: So how did you figure it out?
Comment: Just tried to change its default value (1000) to 5000 , and in my response i got my all rows which is around 4200


display contents in input

Question: I have anchor tag and input tag
Go to Example.com

and
<a href="example.com">Go to Example.com</a>

Now I need to display above text in input box
<input type="text" value="Go to Example.com">

But it's not working, How can I do this?
Comment: Do you want to see the link in the text box OR want to see it as Go to Example.com in the text box?
Comment: @enam: I need to see it as Go to Example.com in the text box
Comment: doesn't my answer solve the issue?
Answer: Change quotes to html entities:
"

<input type="text" value="Go to Example.com">

Comment: didn't get you, please explain
Comment: @I-M-JM: you have to replace `"` char to according html entity `"` within `value=""`.
Answer: <input type="text" value="Go to Example.com">

display contents in input


how to return a Rails query as a hash with the keys as the primary key id value

Question: I'm curious whether there is native way to return a query with the id value as the hash key returned. Something like:
Location.find([2,4,7]).as_hash

get back
{
  2:{name:"name 1", id: 2},
  4:{name:"name 4", id: 4},
  7:{name:"name 7", id: 7},

}

I'd like to just do a to_json and this would be convenient.
thx
Answer: I'd like to just do a to_json and this would be convenient.
Natively, There is a to_json method which can directly give you the output of query in json format.
Location.find([2,4,7]).to_json

However, the format is different from what you have specified. Check if it works for you.
to_xml, to_yaml methods are other methods which can similarly output xml and yaml data, respectively, from the activerecord queries.
Alternatively, you can do something like this
locations = Location.find([2,4,7])
locations_hash = {}
locations.each do |location|
    locations_hash[location.id] = location
end
locations_hash.to_json

Comment: thx, I currently do something like the latter. just seems kinda ugly esp since json api which is done by Rails core team members advocates something else.
Comment: Hmm, you can also do `json = {}.tap{ |h| Locations.each{ |l| h[l.id] = l}}.to_json` to do it all in one line, but that's not your concern, right?


What is the maximum length for clientUserId

Question: What is the maximum length for clientUserId?
https://docs.docusign.com/esign/restapi/Envelopes/EnvelopeRecipients/ does not say.
Answer: Maximum length of clientUserId is 100
You can specify a clientUserId greater than 100 but Docusign will only consider upto 100 characters and ignore the remaining part.


Combine multiple Monte-Carlo estimates

Question: I use a Monte Carlo simulation (say 100.000 runs) to estimate parameter in R. I have memory problems and my first thought is to run multiples times my estimation program (say 500 times) .
My question are: what is the distribution of an estimator ? how to get an estimator from multiple estimators ? (for the mean you can use a mean of means for example, does this hold in general ?). Is it possible to derive some kind of confidence interval from the runs ?
My questions are both general and specific to quantile and correlation estimation. For the quantile and correlation part thanks to assume a general distribution.
Comment: Your description is pretty vague but it seems that is is just a programming issue with efficient using of memory (i.e. not storing all the simulation output in RAM but taking only the important or aggregated values, saving things on disc rather that storing in memory, in most cases you can even stop a simulation and start again in the place you stopped)
Comment: Once I understand how to aggregate estimator for quantile and correlations I may be able to use inline calculation. Like after n simulation, a run r, and one estimator of the mean m I can use (n*m + r)/(n+1). For the moment the problem is I don't know how to aggregate quantile and correlation estimators (well in fact thinking about correlation, it look like a mean).
Answer: Only the mean of means allows for a strict recovery of multiple simulations with limited storage capacities. However, Monte Carlo being an approximation method, approximations are always available.
The theoretical basis of Monte Carlo estimation is the Law of Large Numbers. This means that the empirical cdf
$$\hat{F}_i(x)=\dfrac{1}{n}\sum_{i=1}^n \mathbb{I}_{x_i\le x}$$
is an unbiased estimator of the true cdf $F$. Unfortunately, you cannot store this empirical cdf $\hat{F}_i$ without storing the entire simulation sample of the $n$ $x_i$'s. However, if you replace $\hat{F}_i$ with an approximation based on the empirical percentiles
$$\hat{\hat{F}}_i(x)=\dfrac{1}{99}\sum_{i=1}^{99} \mathbb{I}_{\hat{c}_i\le x}$$where $\hat{c}_i$ is the $i$-th empirical percentile, given by
$$\hat{F}_i(\hat{c}_i)=\dfrac{i}{100}$$
you only need to store $99$ values. (If the percentile precision is not sufficient, you can move to the permile precision or beyond.) You can then repeat simulations without undue pressure on storage by averaging the $\hat{\hat{F}}_i$'s. From this average, you can derive a convergent estimator of the quantiles of interest.
As you noticed, since $\text{cor}(X,Y)$ can be consistently estimated as $$\dfrac{\frac{1}{n}\sum_{i=1}^n x_iy_i -\frac{1}{n}\sum_{i=1}^n x_i\,\frac{1}{n}\sum_{i=1}^n y_i}{\left\{\frac{1}{n}\sum_{i=1}^n x_i^2-\frac{1}{n^2}(\sum_{i=1}^n x_i)^2\right\}^{1/2}\left\{\frac{1}{n}\sum_{i=1}^n y_i^2-\frac{1}{n^2}(\sum_{i=1}^n y_i)^2\right\}^{1/2}}$$you can easily update the five quantities involved in this expression
$$\sum_{i=1}^n x_iy_i,\ \sum_{i=1}^n x_i,\ \sum_{i=1}^n y_i,\ \sum_{i=1}^n x_i^2,\ \sum_{i=1}^n y_i^2$$
without increase storage pressure.
Comment: Thanks that was the answer I was looking for. After working a bit more on my problem, I have concluded that I have other bottleneck. Basically i am simulating a "big" sum of variables that have a t-copula dependence structure and differents compound poisson marginals, so the main bottleneck is not the quantile of my final distribution but the whole cdf estimation of my numerous marginals...
If I understand correctly I can deal with my memory problems with averaging my estimators.

Combine multiple Monte-Carlo estimates


CoreGraphics Image resize

Question: This code is from Apple's WWDC 2011 Session 318 - iOS Performance in Depth and uses CoreGraphics to create thumbnails from server hosted images.
CGImageSourceRef src = CGImageSourceCreateWithURL(url);
NSDictionary *options = (CFDictionaryRef)[NSDictionary
dictionaryWithObject:[NSNumber numberWithInt:1024
forKey:(id)kCGImageSourceThumbnailMaxPixelSize];

CGImageRef thumbnail = CGImageSourceCreateThumbnailAtIndex(src,0,options);
UIImage *image = [UIImage imageWithCGImage:thumbnail];
CGImageRelease(thumbnail);
CGImageSourceRelease(src);

But it doesnt work and the docs don't really help. In the iOS docs CGImageSource CGImageSourceRef CGImageSourceCreateThumbnailAtIndex are available

in Mac OS X v10.4 or later

How can I get this to work?
EDIT
These are the compiler errors I'm getting:

Use of undeclared identifier 'CGImageSourceRef'
Use of undeclared identifier 'kCGImageSourceThumbnailMaxPixelSize'
Use of undeclared identifier 'src'
Implicit declaration of function 'CGImageSourceCreateThumbnailAtIndex' is invalid in C99
Implicit declaration of function 'CGImageSourceRelease' is invalid in C99
Implicit declaration of function 'CGImageSourceCreateWithURL' is invalid in C99
Comment: iOS docs are actually [here](http://developer.apple.com/library/ios/#documentation/GraphicsImaging/Reference/CGImageSource/Reference/reference.html) and availabilaty is declared `in iOS 4.0 and later`. Try to state the exact source of problem. Do you even get a valid `src`. P.S. it's not a good idea to discuss WWDC sessions outside apple.developer forum - since all of referenced functions are not under NDA i guess you're o.k. :)
Comment: Ah yep didnt see that iOS 4+ further down. Edited with errors. Also, this is from last years WWDC, which is fine no?
Comment: I guess it should be fine though i remember seing disclamer somewhere.
Answer: School boy mistake.
Didn't add #import <ImageIO/ImageIO.h>
Answer: Try image resize:
-(UIImage*) resizedImage:(UIImage *)inImage:(CGRect) thumbRect
{
    CGImageRef          imageRef = [inImage CGImage];
    CGImageAlphaInfo    alphaInfo = CGImageGetAlphaInfo(imageRef);

    // There's a wierdness with kCGImageAlphaNone and CGBitmapContextCreate
    // see Supported Pixel Formats in the Quartz 2D Programming Guide
    // Creating a Bitmap Graphics Context section
    // only RGB 8 bit images with alpha of kCGImageAlphaNoneSkipFirst, kCGImageAlphaNoneSkipLast, kCGImageAlphaPremultipliedFirst,
    // and kCGImageAlphaPremultipliedLast, with a few other oddball image kinds are supported
    // The images on input here are likely to be png or jpeg files
    if (alphaInfo == kCGImageAlphaNone)
        alphaInfo = kCGImageAlphaNoneSkipLast;

    // Build a bitmap context that's the size of the thumbRect
    CGContextRef bitmap = CGBitmapContextCreate(
                                                NULL,
                                                thumbRect.size.width,       // width
                                                thumbRect.size.height,      // height
                                                CGImageGetBitsPerComponent(imageRef),   // really needs to always be 8
                                                4 * thumbRect.size.width,   // rowbytes
                                                CGImageGetColorSpace(imageRef),
                                                alphaInfo
                                                );

    // Draw into the context, this scales the image
    CGContextDrawImage(bitmap, thumbRect, imageRef);

    // Get an image from the context and a UIImage
    CGImageRef  ref = CGBitmapContextCreateImage(bitmap);
    UIImage*    result = [UIImage imageWithCGImage:ref];

    CGContextRelease(bitmap);   // ok if NULL
    CGImageRelease(ref);

    return result;
}

i use it in my code for awhile but i can't remember it's source
try this also
resizing a UIImage without loading it entirely into memory?
Comment: http://stackoverflow.com/questions/5860215/resizing-a-uiimage-without-loading-it-entirely-into-memory  try this please
Comment: Thanks for this, but I specifically wanted to use the `CGImageSourceCreateThumbnailAtIndex` function

CoreGraphics Image resize


Is density estimation the same as parameter estimation?

Question: I was studying parameter estimation from Sheldon Ross' probability and statistics book. Here the task of parameter estimation is described as follows:

Is this task the same of density estimation in machine learning contexts?
Mathematics for Machine Learning book describes density estimation as follows:

My question arises from the fact that a probability density function is fully described by its parameters (e.g. a Gaussian or normal distribution is a density function which is fully described by its mean $\mu$ and its variance $\sigma^2$).
Answer: I understand this argument and can buy it as being technically true. However, the goal of language is to communicate ideas, and statistics has decided that "density estimation", for better or for worse, refers to doing density estimation with minimal assumptions about the density as to keep from being restricted to a particular parametric family.
Perhaps this means that the use of English words is not perfect. However, you are likely to elicit confusion (or at least strange looks) in statistics circles if you deviate from the established terminology.
Comment: I agree with this broadly. We can, I hope, all agree that what the problems have in common is indeed _estimation_, with a key flavour in both cases that results will vary if the data do -- or if you use a different method.  That said, I agree with the signal here, as density estimation is not in my reading usually regarded or reported as a parameter estimation problem. One reason is that there's not a fixed number of parameters. In some problems estimating the density at say 30 points could be enough in practice, in others 300 or 3000 points might or might not work well.
Comment: (Density estimation can be almost trivial with one variable, and almost impossible with several!)
Comment: So what's the key difference between the two?
Comment: @tail It's a matter of the "feel" for the terminology. You're right that estimating a parameter and going with a distribution with that parameter is one way to do density estimation, yet this tends not to be what the field means by "density estimation".
Answer: No, it's not the same. Density estimation is about estimating the distribution of the data. This can be achieved with a parametric model, for example, fitting a Gaussian mixture to the data. In such a case, to find the distribution means to estimate its parameters since the distribution is defined by its parameters. But there are also non-parametric approaches to density estimation, like Kernel density estimation, using histograms, etc where we are not estimating any parameters but rather finding the density itself.
Comment: So, we can say that density estimation methods exploit parameter estimation (or non-parametric methods) for estimating a suitable probability distribution for some given data?
Comment: @tail You _can_ say that, but I wouldn't usually do so, Estimating a suitable probability distribution implies that you are going to use that distribution henceforth. Often density estimation (which in turn usually means kernel density estimation) is a descriptive method that is directly informative about the data, so that graphs can be used to show what is going on. It can also be used to guide decisions e.g. on whether to work with data as they come or to apply some transformations. But there can be other uses.
Comment: A bit confusing, in my opinion.


What do the smaller notes in the Treble Clef indicate?

Question:
This is piano sheet music for "I Will Follow You Into The Dark" by Death Cab for Cutie. I've been trying to search for what these notes mean. Do I play them with the left hand? Not play them? Are they optional? I'm not sure.
Answer: This small pitch just means that it's an optional pitch to play. You definitely have to play the D, but you could also play D and F. (But you'll never play only F.) You can play this pitch with either the left or right hand.
The musical term is ossia, which is Italian for "alternatively." Oftentimes ossia parts are written on a different staff:

But in your case, since it's just a single note, they wrote it slightly smaller.
These smaller notes are not to be confused with the small pitches discussed in Small notes on the staff. The small notes there are grace notes, which are completely different.
Comment: @AndreAngelo It seems to me it's either D&F or just D. Note (no pun intended) that only the F is smaller
Comment: Just to make things clear since you said "alternatively," I can play the D **or** the F in the first measure? Or is it an option to play both?
Comment: @elliotsvensson: All the cue notes I've notivced would have small stems of their own, rather merely having small note heads sharing the stem with performed notes.
Comment: @AndreAngelo Very good question, and JAD is right on. I'll edit to make that more obvious.
Comment: ...and on orchestral sheet music, the small notes could mean "this is what you'll hear by another instrument"...


Adding a flag to Menu Content Link to display as a non-link

Question: I have been struggling/failing for the last day to try find a way that I can add a flag/marker to the Drupal menu links that I can examine within the menu TWIG template to modify the link such that it becomes plain text instead of a menu link.
I am not using any menu modules, standard Drupal Menu with CSS to provide the drop down functionality and styling.
What I need is to be able to output a menu item as shown in the screen shot, specifically the 'Sell your property' & 'Essential Services' items which are unlinked headers.

Initially I attempted to use the contributed module menu item extras
 (https://www.drupal.org/project/menu_item_extras) which works fine from a menu management plugin point of view but then they change the markup way too much and it actually breaks the drop down functionality, so I cannot use it.
I then tried a second module which seemed simpler, i.e. Menu link content fields (https://www.drupal.org/project/menu_link_content_fields).
This module has some strange behaviour in that it makes the menu links fieldable. I can add a new field but after adding a field, it does not appear under the Manage Fields tab, and in the twig template the new field is un-available in the menu item object (Examined through xDebug)
Also, trying to remove this invisible field at a later stage seems difficult.
Question: How can I easily add some sort of marker to a menu item link  to allow me to modify the template output for said link. Or is the re a module that will allow then insertion of HTML markup/plain text instead of a link (Megamenu doesnt seem to allow this)
Also, I cannot seem to find the hook which deals specifically with a sites menu, i.e. the hook that is executed for each menu link. Does one even exist?
I'd like to avoid a hack whereby I put in a unique string into the text of the link and then examine this in the menu twig templates to see if that string exists to know if I need to modify it.
Comment: You need to enable Twig Debugging first: https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates This will help you understand which files need to be overridden
Comment: I have got twig debugging installed and enabled. Templating is not my issue.
Comment: The attached duplicate answer sdolved part of the problem and allowed me to at least change styling based on the route:
Answer: The module Special menu items allows you this, even some control over the HTML output.
This is now in Drupal core (although Docs need some updating):

This features is in core for >=8.2.0. Create menu without link by entering route: <nolink>.

That is, you enter into Link:
route:<nolink>
and select:
Show as expanded
if you need it for drop-downs.


IP address blocked in Google App Engine firewall rules but still seeing it in logs

Question: I run a Google App Engine app that has a honeypot admin page to distract from the real admin login page. A while ago I started getting repeated emails saying that someone was trying to log in on the honeypot page. I blocked the IP in question, but then I started seeing it for a new IP.
I've since blocked that one as well in the firewall rules section of Google App Engine:

I've tested the IPs in firewall rules and they are getting denied. However I'm still receiving emails saying this IP is trying to log in to the honeypot admin. To do that, they have to be able to reach the page in the first place, then submit the form, which they shouldn't be able to do.
What else can I look at and do to resolve this?
Update:
I've just done some further testing by attempting to log in to the fake page myself, and it appears that all log in attempts are coming through as 172.17.0.6, so it must be an infrastructure related IP.
I am assuming that is why the IP is not blocked by the firewall. I've done a bit of a deep dive into the code for the honeypot site (which I'm not the author of), and it appears the IP address is obtained by ip_address=self.request.META.get('REMOTE_ADDR').
How might this be rectified?
Comment: Those are RFC1918 private IP addresses. You should look first at whether your own application is trying to connect to itself. That range is also the default private IP address range for Docker containers. Do you have a Docker container generating this traffic?
Comment: I saw that when looking up the IPs but as far as I can tell they are not coming from any site related infrastructure. The site does have a custom runtime via a Dockerfile. The main reason I doubt it is internal traffic is that the emails I get telling me someone is trying to log in from this IP show the usernames that are being entered (admin, for e.g.) and it seems like an attempt to log in.
Comment: Has one of your containers been compromised? It could be someone trying to break out of it.
Comment: There is no evidence to suggest that. It seems like a very automated (i.e., bot-like) process. I get 50 or so of these messages over the course of a few minutes, usually early in the morning UK time, then nothing for hours or days.
Answer: You need to get the IP is using HTTP_X_FORWARDED_FOR as is explained here. This is because the request is forwarded to the App Engine instance. I really think that you are pulling the App Engine load balancer IP or another internal IP (For security purposes, some headers are sanitized or amended by intermediate proxies before they reach the application), and for this reason you can not block this one (Client IP -> Firewall rule -> IP sanitized (That is the one that you are blocking)-> Instance) since the IP that your are getting in the method is not the real IP that is calling your app.
Another way to verify the IP is in Stackdriver Logging. Search the request and the IP is in the field  IP :) I really hope that this information helps you.
Comment: Haven't been able to fully verify this yet but it sounds logical! Thanks very much.


How to emulate a domain name - Webmin Setup

Question: I am currently working on a client project where they are using a custom CMS which relies on having the specific domains configured for it to work properly.
When I try running the site on my test environment, the entire website fails because it isn't located on the primary domain (and I'm pretty sure the domain is hard coded since there's no control panel to adjust the file locations).
Is it possible to use my test environment URL but have Apache and the DNS emulate my clients website URL locally, rather than calling the actual name servers?
Right now I have a virtual host setup in Apache but I am not sure where to go from there.
Answer: Just add a line to your hosts file. If you're on a Unix-y system, that file is /etc/hosts. If your server IP was 10.0.0.10 and the client domain name is example.com, then you'd add this line:
10.0.0.10 example.com

If you're on windows, the location is %SystemRoot%\system32\drivers\etc\hosts.


dirichlet likelihood simplified

Question: I am looking for derivation of eqn 5 in C.Moody's paper
https://arxiv.org/pdf/1605.02019.pdf
where it says the loss function coming from dirichlet enforcement of sparsity is
$L^d=\lambda\sum_{jk}(\alpha-1)logp_{jk}$
When you look up a formal paper, such as https://tminka.github.io/papers/dirichlet/minka-dirichlet.pdf eqn 4
that term is only part of the whole formula. Can someone explain how the Moody is able to eliminate the two Gamma terms?
Answer: Equation $4$ from Minka's paper is
$$\log P(D|\alpha) = N\log\Gamma\left( \sum_k \alpha_k \right)-N\sum_k\log\Gamma\left(  \alpha_k \right)+N\sum_k (\alpha_k - 1)\log \bar{p_k}$$
If $\alpha$ is fixed and the optimization variables are $\bar{p_k}$, the first two terms are just constant and they can be dropped for the purpose of such optimization, after all.
Comment: that was easy, and makes sense.

dirichlet likelihood simplified


Não estou conseguindo instanciar um objeto

Question: Não estou conseguindo instanciar um objeto da classe Aluno
Classe Aluno
public class Aluno extends Pessoa
{
    private int matricula;

    public Aluno(int id, String nome, String endereco, String telefone, String email, int matricula) {
        super(id, nome, endereco, telefone, email);
        this.setMatricula(matricula);
    }

    public Aluno()
    {

    }

    public int getMatricula() {
        return matricula;
    }

    public void setMatricula(int matricula) {
        this.matricula = matricula;
    }
}

Classe Pessoa
abstract public class Pessoa
{
    private int id;
    private String nome;
    private String endereco;
    private String telefone;
    private String email;

    public Pessoa(int id, String nome, String endereco, String telefone, String email) {
        this.id = id;
        this.nome = nome;
        this.endereco = endereco;
        this.telefone = telefone;
        this.email = email;
    }

    public Pessoa() {
        super();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getEndereco() {
        return endereco;
    }

    public void setEndereco(String endereco) {
        this.endereco = endereco;
    }

    public String getTelefone() {
        return telefone;
    }

    public void setTelefone(String telefone) {
        this.telefone = telefone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

Como estou tentanto instanciar um objeto da classe Aluno porém sem êxito
                    System.out.println("ID aluno:");
                    int id = input.nextInt();
                    System.out.println("Nome:");
                    String nome = input.next();
                    System.out.println("Endereço:");
                    String endereco = input.next();
                    System.out.println("Número:");
                    String numero = input.next();
                    System.out.println("Email:");
                    String email = input.next();
                    System.out.println("Matrícula:");
                    int matricula = input.nextInt();
                    aluno = new Aluno(id,nome,endereco,numero,email,matricula);
                    System.out.println("Deseja cadastrar um novo aluno?(1-Sim/2-Não):");
                    op = input.nextInt();
                    AL.add(aluno);

Comment: Favor [edit] a pergunta e colocar qual é o erro que ocorre, se é erro de compilação, algum `exception` que ocorre durante a execução (qual a mensagem e quais os dados que causaram o erro), etc.
Answer: Em java você deve informar qual o tipo do objeto que se esta criando, então deve ser feito assim:
Aluno aluno = new Aluno(id,nome,endereco,numero,email,matricula);

Comment: Não é assim não amigo
Comment: @CássioElias e qual o erro que te retorna?


outlook vsto sending mail

Question: I've been struggling with this for a while now and I can't get an answer anywhere.
I made an outlook add in which has a ribbon and two buttons, The one button opens up a mailitem where you can compose your mail and then the 2nd button sends the mail.
In the background it takes all of the recipients and adds it to the bcc field and sends the mail in batches for instance if there are 100 recipients it will send to 25 people at time.
So my problem is that it works perfectly on the developer PC but the send button doesn't work on the end user PC. The add in loads registries are fine and it targets the right .Net framework everything!
<code> private void CreateEmailItem(Outlook.Recipient strRecipientAddressTo)
        {
            string strFilePath = @"c:\temp\OutlookAttachments";
            string[] strFiles = Directory.GetFiles(strFilePath);
            bool bFileExists = Directory.Exists(strFilePath);
            Outlook.MailItem eMail = (Outlook.MailItem)
                        Globals.ThisAddIn.Application.CreateItem(Outlook.OlItemType.olMailItem);
            Outlook.MailItem mailItem = Globals.ThisAddIn.Application.ActiveInspector().CurrentItem as Outlook.MailItem;
            eMail.Subject = mailItem.Subject;
            eMail.BCC = mailItem.To;
            eMail.Body = mailItem.Body;
            if (bFileExists)
            {
                foreach (string file in strFiles)
                {
                    File.SetAttributes(file, FileAttributes.Normal);
                    eMail.Attachments.Add(file);
                }
            }
            ((Outlook._MailItem)eMail).Send();
        }
</code>
When the send button on the ribbon is clicked this method is called, but on end user the button just doensn't fire .. can this be permissions ? or any advice would be very much appreciated !!!!
Answer: It is hard to suggest there but did you add any logging there. There can be chances that you are getting some crash in following line..
 email.Attachments.Add(file)
And thats why it is not reaching until send statement. You can check the event logs on user's system as well. They might help you.

outlook vsto sending mail


Does having the IIS log header in the log file mean that IIS was reset during the day?

Question: When I'm viewing IIS log files I can see various times during the day where the header line is written out to the log file. The only time I've seen this is happening is when IIS resets; or starts up.
For example the header line below;
<code>#Software: Microsoft Internet Information Services 6.0
#Version: 1.0
#Date: 2010-10-18 07:28:06
#Fields: date time s-sitename s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) sc-status sc-substatus sc-win32-status
</code>
The customer is saying there is no IIS resets happening; but does this entry in the log file mean that IIS was definitely reset for some reason which may be outside of the customers control.
Answer: Eventually figured in out in the wee hours of the morning. If you have W3C logging enabled for different web sites/services, but have different fields configured for those web sites/services then when site1 is hit it output the list of fields and later on when site2 is hit it appends any different fields onto the list of the 1st fields and outputs the combined set of fields.
So having multiple sets of the # directives in the log file does not necessarily means that IIS was reset.
Comment: This is a great answer, do you have any references to documentation on this?
Comment: Sorry Alex, no documentation references, this is purely from manual observation of the behaviours in these circumstances.
Comment: @Bigtoe: The thread here http://forums.iis.net/t/1172464.aspx appears to cover the issue above but an extra comment has been added suggesting the IIS header is being caused by the app pool recycling. Could you confirm your latest view on this issue?
Answer: According to Dean Cron (Microsoft engineer working in IIS team) the logging headers are re-written on:

IIS reset
Server reboot
App Pool recycling
If you've added or removed one or more logging fields in the logging configuration.
If a site doesn't receive requests for a set period of time (15 minutes), the handle to the associated log file is closed. The next time a request comes in, the log file is re-opened and the log headers written.

You can find more details in Dean's blog post.
So no, the header appearing in the log file does not mean that IIS was reset.


Fix background and put panel over it

Question: Good evening,
I'm very new to html and was searching for a solution but I did not found any. So what I'm trying to do is to fix the background and put something like a panel over it, where I do the rest of the site like text etc. I have an example website: https://420cheats.com
I don't know if I am right but I think I have to add a second class and put this somehow over the background
Thanks in advance.
Ps: I did the background as a class in the css file.
Answer: You will need to set the background as fixed and create a DOM element to lay on top of your background image.

body {
 background: url('https://cdn-image.travelandleisure.com/sites/default/files/styles/1600x1000/public/1507062474/hotel-everest-namche-nepal-mountain-lodge-MOUNTAIN1017.jpg?itok=g-S4SL9n') no-repeat fixed;
 background-size: cover;

}

div {
 padding: 20px;
 width: 400px;
 height: 1200px;
 background: rgba(0,0,0,.5);
}

test

Answer: You can just set a fixed background-image on your body element. Both the  and  tag need a set height of 100% for this to work.

body, html {
  height: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-image: url('https://cdn.cnn.com/cnnnext/dam/assets/170407220921-07-iconic-mountains-pitons-restricted.jpg');
  height: 100%;
  background-attachment: fixed;
}

.content {
  background-color: rgba(204,204,204,0.5);
  width: 80%;
  margin: 20px auto 20px auto; /* top right bottom left */
  height: 1500px; /* remove this, just here to show that it works */
}

Content

Comment: Thanks for your answer! The code works perfectly but there is just one little thing... When I'm changing the opacity for the class it will automatically change for the header to. I think I have to do a third class or something like that and tie it on the content class.
Comment: @tableware Which is? :)
Comment: I didn't know that when you press enter it will automatically send it haha. I posted the problem above.
Comment: @tableware This is a stupid thing in css, opacity cannot be removed from child elements without some hacky solutions. Using rgb for the background color with a fourth parameter (which is the opacity) will be the easier solution. You'll have to convert hex to rgb which you can do [here](https://www.rgbtohex.net/hextorgb/). Answer is updated.
Comment: Nope, in the CSS `background-color: #ccc` is changed to `background-color: rgba(204,204,204,0.5);` (0.5 being the opacity of the div)
Comment: Yes you right, did it and it's works perfectly, thank you very much
Comment: No problem, glad to help :)

Fix background and put panel over it


How to synthesize non-pitched sounds? How pitched is a sound in general?

Question: Non pitched sounds are sounds which are not only composed of a fundamental frequency and a distribution of its harmonics. For instance, a sound composed of a sum of a sin wave at 440Hz and a sin at 500Hz would be considered as non-pitched if I understand well.
As a consequence, these sounds are non periodics. Let's forget about envelopes and LFOs, as they make your sound non periodic, but on much longer timescales.
How is it possible to synthesize these kind of sounds? Obviously, additive synthesis (and unison which I think of a subset of additive synthesis) would work, but not subtractive synthesis. I guess FM would work also if modulator and carrier frequencies do not share a common divider.
Are there other methods to synthesize such kind of sounds?
Also (and my main interest in there), is there a criteria for how "pitched" such a sound would sound? Unison is done by adding waves which very close in pitches, thus sounding as the average pitch, but for more extreme cases (for instance A*sin @ 440 + B*sin @ 500) would sound as a A if B is small compared to A. How long would that stands when increasing B?
Edit: let's change 500 Hz to sqrt(2)*440, then these two frequencies do not have a common divider and the sum of the two is non-periodical.
Comment: You are wrong:  a sum of  440 and 500 Hz produces  440, 500,  60, and 940 Hz components.  They are periodic.   I don't see any strict definition of "non-pitched", tho' often things like the white-ish noise blast from a cymbal qualifies.   As to how to synthesize --  a noisy analog tank circuit is a good source, or an untuned-FM receiver.
Comment: Many non-pitched sounds are combinations of all frequencies,, eg white noise.
Comment: @Tom_C   That pattern most certainly does repeat.  I'm not sure where you're getting your information from.  We are talking about Fourier Transform, not a Fourier Series expansion.
Comment: @CarlWitthoft For even a clearer case, take `f0` and `sqrt(2)*f0`. There is no way a sum of two sin waves at these frequencies can repeat.
Comment: Note that in the well tempered system, all intervals other than octaves are irrational and hence non-periodic.  In particular, multiplying by sqrt(2) will raise the note by an augmented fourth / diminished fifth.  So, play A4 and D#4 and you will get 440Hz and 440*sqrt(2) Hz.  This is a fairly dissonant interval but it is not unpitched.  Unpitched instruments, such as many percussion ones, are not just non-periodic but a broad spread of frequencies.
Comment: @Peter Oh yes, i forgot about those!
Comment: @Tom_C "Making this decomposition is a Fourier Transform" No, in fact it's not. Fourier Transform is a continuous analogue of Fourier series. It will decompose a signal into a continuous function of frequency, NOT just the harmonics. Your example will have a Fourier Transform of two spikes at 440 hz and 440*sqrt(2) hz (and the same spikes for the negative frequencies as well, but that's mostly irrelevant). As such, the Fourier Transform can (and often does) operate on non-periodic signals, as long as they satisfy the convergence criteria.
Comment: @AlexanderJ93 My whole point was: if it is not composed of harmonic contents, then it is not periodic. What you say is true and my definition only holds for periodic signals, which I admit is rather limited (but not in time).
Answer:
Non pitched sounds are sounds which are not only composed of a fundamental frequency and a distribution of its harmonics.

That's quite a strict definition of 'non-pitched'. Most sounds that are essentially perceived as pitched by humans nevertheless contain energy at frequencies that are not exactly at the multiples of a fundamental - possibly because the harmonics are stretched (often the case with strings), or because there's some aspect of the driving mechanism that causes turbulent or chaotic behavior (e.g. flutes).

For instance, a sound composed of a sum of a sin wave at 440Hz and a sin at 500Hz would be considered as non-pitched if I understand well.
As a consequence, these sounds are non periodics.

Well, a sound consisting of a sin wave at 440Hz and a sin at 500Hz is definitely periodic - the highest common factor of those sine waves is 20Hz, so that's the frequency of the repeating waveform. Would your example would actually be heard as a pitched sound at 20Hz with only the 22nd and 25th harmonics? that frequency difference is on the edge of being within the critical band - if I generate those two tones, I can hear it as two tones (if I try), or indeed as a kind of rough sound of indeterminate pitch.
But imagine that you had sines of 40, 60, 80.... and so on. That would essentially be a similar example, but I'd imagine that would be heard as a sound at 20Hz.

How is it possible to synthesize these kind of sounds? Obviously, additive synthesis (and unison which I think of a subset of additive synthesis) would work, but not subtractive synthesis.

Subtractive synthesis doesn't help you if you are limited to one periodic oscillator, but if you have multiple detunable oscillators, it seems that you can move towards your definition of 'non-pitched' - especially if you have ring mod, FM, oscillator sync etc. available, which will generate more 'inharmonic' partials.

Also (and my main interest in there), is there a criteria for how "pitched" such a sound would sound? Unison is done by adding waves which very close in pitches, thus sounding as the average pitch, but for more extreme cases (for instance Asin @ 440 + Bsin @ 500) would sound as a A if B is small compared to A. How long would that stands when increasing B?

I think the simplest answer is that 'pitchedness' isn't a very well-defined concept, so there isn't really a strict criteria. It's not a single-dimensional problem either, because you are dealing not only with how 'pitched' something sounds, but also how distinguishable two different sounds are - again, see https://en.wikipedia.org/wiki/Critical_band/.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/109818/discussion-on-answer-by-topo-reinstate-monica-how-to-synthesize-non-pitched-soun).
Answer: I think you are confusing multiple concepts.  As piiperi Reinstate Monica stated, the example you give would be 2 pitches rather than a non-pitched sound.
The term non-pitched usually refers to percussion instruments, percussive sounds, scratching, and other "sounds" for which it is difficult to define a fundamental.  I think you got that part right.  But the example of two sine waves would be perceived as an interval not a non pitched sound.  This is because our brain is capable of doing FFT, or some equivalent process, and discovering the "tones" present in a complex signal.  Actually the ear may have something to do with the process too, as the nerves within it are probably "tuned" to pick up specific frequencies.
To address your question about how two tones would be perceived when they have different amplitudes I'd ask you how you perceive the instruments in a band or orchestra when one is playing quiet while the other is loud?  You would hear two things, two tones, at two volumes.  This is a common experience.  Using MATLAB, SCILAB, or any other off the shelf high level programming language you can make a wave file from sample of
A1 * sin(2pi f1 t) + A2 * sin(2pi f2 t)
sampling t as time.  You can adjust the A1, and A2 as well as f1 and f2 as answer your own question.  Humans have limits to their detection abilities.  When one amplitude is too small perhaps that tone will not be picked up by the ear.  When the two tones are close in frequency you will likely not be able to distinguish them at all, you may hear beats from the amplitude modulation.  You cannot not stop the envelop from forming with sig proc tricks.  Your synthesis will generate the envelope.  If f2 is a multiple of f1 you may not hear an interval but your brain might start to form the perception that this is a single tone with different timbre.  this is a tricky phenomenon to evaluate.  Many musicians in their training are exposed to the art of listening for harmonics (I have been indoctrinated to that).  With practice it is alleged that the trained ear can separate the harmonics in a complex tone.  I am NOT talking about distinguishing 440Hz from 500Hz which is probably easy if it is bigger than a 1/2 step, but hearing the octave, octave and a 5th, etc, in a single plucked guitar note, or hammered piano note.  I'd be curious to hear from others here if they are successful in doing this.  In the case when two notes are closer than the pitch discrimination ability of the listener we typically hear the average tone, sum tone.  And this is NOT a non-pitched sound, it is very well pitched.
Moving on to timbre and tone.  What makes a guitar sound like a guitar and a violin sound like a violin (and not each other) is the harmonic content of the wave produced.  In both cases that is "likely" dominated by the physics string.  The body construction can dampen or amplify various harmonics by the starting point is the string.  The key feature for any instrument is the method of attack.  This is what produces the initial set of harmonics in the wave form.  Bowed, hammered, plucked, at various locations with various angles and pressures all produce different tones.  Without the attack everything would be a dull sine wave buzz.  Even turning on a sine wave generator producing an infinite series of harmonics due to the hard edge rise of the wave at t = 0.  Once the tone is produced by the instrument damping will cause the harmonics to decay over time, usually higher harmonics decay faster because the damping force is proportional to velocity, which is proportional to frequency in the frequency domain.  Thus, over time any instrument excited in any manner will eventually ring at the fundamental, or lowest note in the excitation spectrum (may not be the true fundamental).  The rate of decay depends on several factors but lone story short each instrument will have a characteristic decay profile.  Thus, any "pitched" sound from an instrument will have an attack, sustain, and decay portion to the envelope.
If you wanted to synthesize two guitars playing a two part harmony, an interval, then you would need to generate the full spectrum for each guitar given its fundamental, then add the two results.
Anyone can do a fairly accurate job these days synthesizing musical instruments using Fourier analysis and some type of computer s/w.  You need to know enough physics to model it correctly without data, but you can get real data and use that as a characteristic sample to measure key parameters.  A very poor person's version of a synthesized guitar string would just be the FFT of a plucked string over the entire duration of the sound.  This would sound like crap!  Because the synthesis mixes all the physics of attack, sustain, and decay into one wave that is constant over time.  To do the job correctly one needs to chop the time domain window up in to small slices and analyze the content of each window, building up a time dependent set of parameters.  If you have a really high fidelity model of the instrument you can predict this behavior in time.  I have done this in my career, synthesizing sound from sources based on physics based simulations.
So, why describe all this?  Because I think that the parameters of your question make it unanswerable.  You want us to ignore the envelope for now and just focus on the tone within it.  One could argue that the initial "Attack" of any instrument (the first few milliseconds or hundredths of a second) are always non-pitched.  By the same token everything has natural resonance frequencies.  If you whack a bar the initial "POP" sound of that whack is "non-pitched" but in time you may hear the faint ringing of a resonance frequency left over, which is in fact pitched.  Non-pitched sounds are, by their very nature, broad band in the frequency domain.  So you CANNOT ignore the envelop.  If your desire is to synthesize percussive instruments, or scratching of a bow on a cello, or the sound of an over driven woodwind instrument then I'd say you can absolutely do that with FFT and iFFT techniques, but it would require detailed analysis of the time evolution of the envelop.  The initial rise is very important for this.
Comment: Harmonic content is a function of time.
Comment: *What makes a guitar sound like a guitar and a violin sound like a violin (and not each other) is the harmonic content of the wave produced.* This is not true, as you say yourself a couple of paragraphs later. If this were true, then a cheap keyboard from 1980 would have a violin timbre that actually sounded like a violin.
Answer: Simultaneous sine waves at 440 Hz and 500 Hz are some kind of a two-note chord, or an interval at least, something like a major second. It's definitely pitched, because there are two distinct constant pitches.
If you cannot identify a pitch, then the sound is unpitched. I don't know if silence counts as a sound, even though there's a song about it, but at least the following are unpitched:

very short transient snaps
wide-range noises where the spectrum is filled with frequencies
fast wide sweeps up or down (but not repeating up-and-down)

Periodic repeating sweeping frequencies such as a vibrato are pitched, and the pitch of such a sound is identified somewhere in the middle of the sweeping range.
For short transient snaps and sweeps, use fast envelopes. If your synth has a noise genarator, use that to get noise.
You can synthesize a wide-band noise in an FM synth with operator feedback modulation, if the feedback level can be set high enough. Even a simple sine wave becomes a chaotic noise if you crank the feedback, like in some Yamaha OPL chips you can have 200% or 400% feedback (if I understood the meaning of the settings correctly).
Comment: @ggcg - it's certainly not music to my ears!
Comment: How would you classify Gage's 4:33?
Comment: @Tim, right on.  But from what I've read the performances get very loud!
Comment: I'd forgotten about the dynamics markings. Sorry.
Comment: I think the dynamics were improvised.


How to Self Reference an Object when "this" Refers to Something Else

Question: I'm trying to create a modular series of element handlers for an app that has pages with varieties of configurations (eg: 'Hex T' config has elements 'A' thru 'O' that each has at least 1 DOM element that can be modified in different ways, but 'Square Pad' only has 'A' thru 'E' and the same lettered elements don't always refer to the same type of element, be it a dropdown or number input).
So what I've done is made classes like LengthElement that has 2 number inputs, one for Feet and one for Inches, and so LengthElement holds the value in inches, and then whenever one of the elements, Feet or Inches, gets updated, it registers that change to the inches value and then changes the Feet and Inches elements to properly display the correct measurement (eg: 10ft 0in => 10ft -1in => 9ft 11in).
There's also a config array that holds the list of all the various configurations the app can have, and what order the elements are in and what they are. I ID active inputs as 'input' and disabled inputs as 'box', it just helps me keep things straight. So, a Hex T active input pair for 'A' would have elements foot: '#ht-a-ft-input' and inch: '#ht-a-in-input'. I did this so I don't have to write out all the IDs for every single possible element (there are currently over 100 on just this page) more than once.
There's also an app requirement where certain lengths have to be divisible by 7, and I've got the logic in here. It's probably not relevant but I figured that I'd include it as it is just in case. Finally, there's an OnChange() function that gets passed into each object instance, that's a function with a callback that appears elsewhere that's working just fine so I don't think it matters.
Here's the class code in its entirety:
class LengthElement {
    inches;     //Value of the Two Elements in Inches
    foot;       //String of the Foot Element
    inch;       //String of the Inch Element
    div7;       //Flag to determine if change needs to be Divisible by 7
    OnChange;   //Function specific to the instance to be called whenever the input changes

    constructor(i, cfg, abrv, oC) {
        this.inches = i;

        if (cfg.foot == 'input') {
            this.foot = '#' + abrv + '-' + cfg.name + '-ft-input';
            $(this.foot).on('input', this.InputVal);
        }
        else {
            this.foot = '#' + abrv + '-' + cfg.name + '-ft-box';
        }
        if (cfg.inch == 'input') {
            this.inch = '#' + abrv + '-' + cfg.name + '-in-input';
            $(this.inch).on('input', this.InputVal);
        }
        else {
            this.inch = '#' + abrv + '-' + cfg.name + '-in-box';
        }

        this.div7 = cfg.div7;
        this.OnChange = oC;
    }

    GetFeet(i) {
        return Math.floor(i / 12);
    }

    GetInches(i) {
        return i % 12;
    }

    GetDiv7(i) {
        if (i % 7 > 5) {
            return i + (7 - (i % 7));
        }
        else {
            return i - (i % 7);
        }
    }

    GetVal() {
        return this.inches;
    }

    UpdateVal(i) {
        if (this.div7) {
            this.inches = this.GetDiv7(i);
        }
        else {
            this.inches = i;
        }

        $(this.foot).val(this.GetFeet(this.inches));
        $(this.inch).val(this.GetInches(this.inches));
    }

    InputVal() {
        var newInches = ($(this.foot).val() * 12) + $(this.inch).val();
        var change = newInches - this.inches;

        if (this.div7) {
            if (change > 0) {
                newInches = this.inches + ((Math.floor(change / 7) * 7) + 7);
            }
            else if (change < 0) {
                newInches = this.inches - ((Math.floor(change / 7) * 7) + 7);
            }
            else {
                newInches = this.GetDiv7(newInches);
            }
        }

        this.UpdateVal(newInches);
        this.OnChange();
    }
}

So what's the problem?
Whenever InputVal() gets called, this refers to a jQuery object, and not the object it's inside of. I believe the critical lines are the $(this.foot).on('input', this.InputVal); lines, but I'm not sure what exactly is wrong with them.
Again, this is to avoid writing out every single element's ID more than the one time where it's declared in the HTML, so any alternatives that I can use to perform the same task are appreciated.
I am about 4 months into solo development so I can't change frameworks off of jQuery. I would have an aneurysm.
Comment: Could you provide a [mcve] ? It should allow us to follow along.
Answer: you could try inserting this at the top of your constructor
this.InputVal = this.InputVal.bind(this)

so that this inside of the InputVal function always refers to LengthElement
Answer: the simple trick for that you should declare a variable name self, in constructor you binding self = this, in other method or callback you can using self instead of this
Comment: This unfortunately broke a lot more than it fixed, thanks for the trick tho! I might try that later.


Virtual Keyboard Bug on iOS6 (using FPC)

Question: I have a problem with the Virtual Keyboard which only occurs on iOS 6.
I have a UITextField which I use to catch keyboard imput from the Virtual
Keyboard, but on iOS 6 it only shows once, after the keyboard closes for
the first time it is not show anymore.
Here is the code I use to show the TextField with the Keyboard.
if not Assigned( keysTextField ) Then
begin
  keysTextFrame := wndHandle.frame;
  keysTextField := zglCiOSTextField.alloc().initWithFrame(keysTextFrame );
  keysTextTraits := keysTextField;
  with keysTextField, keysTextTraits do
    begin
      setDelegate( appDelegate );
      setAutocapitalizationType( UITextAutocapitalizationTypeNone );
      setAutocorrectionType( UItextAutocorrectionTypeNo );
      setKeyboardAppearance( UIKeyboardAppearanceDefault );
      setReturnKeyType( UIReturnKeyDone );
      setSecureTextEntry( FALSE );
      addTarget_action_forControlEvents( appDelegate, objcselector('textFieldEditingChanged' ), UIControlEventEditingChanged );
    end;
  keysTextField.setText( utf8_GetNSString( Text ) );
  wndHandle.addSubview( keysTextField );
end;

if appFlags and APP_USE_ENGLISH_INPUT > 0 Then
  keysTextTraits.setKeyboardType( UIKeyboardTypeASCIICapable )
else
  keysTextTraits.setKeyboardType( UIKeyboardTypeDefault );

wndHandle.addSubview( keysTextField );
keysTextField.becomeFirstResponder();

and here is the code to dismiss it :
if Assigned( keysTextField ) Then
  keysTextField.removeFromSuperview();

Anybody have any ideia of what I can try to solve this problem?
I checked, the second time, keyTextField.isFirstResponder() returns true,
so it should be working (And works in iOS < 6).
Thanks
Cezar Wagenheimer
Answer: Fixed changing the command
keysTextField.resignFirstResponder(); from textFieldShouldEndEditing to textFieldDidEndEditing!


Is $\mathbb{R} \backslash \mathbb{Q}$ locally compact?

Question: So I believe the answer is no, because the answer is no for rationals. I feel that every word in the proof of rationals not being locally compact can be changed to irrationals. But I wasn't totally confident since I am a beginner student of topology.
Comment: What proof have you for $\Bbb Q$?
Comment: In fact if $D$ is dense in $\Bbb R$ such that $\Bbb R\setminus D$ is also dense, then $D$ is not locally compact. This fact applies to $\Bbb Q$ and $\Bbb P$.
Answer: You're right, $\Bbb P$ (the irrationals) are a non-locally compact space, and the proof can be similar to a proof as given for $\Bbb Q$ (but for the latter we can also say it's not Baire so cannot be locally compact, but $\Bbb P$ is actually Baire so that particular argument does not translate).
You can use that irrational sequences can converge to rational points, e.g.


Criar vários clientes de uma classe Clientes

Question: Como eu poderia adicionar uma lista de clientes na classe Clientes?
class Clientes():
    def __init__(self, nome, cpf):
        self.nome = nome
        self.cpf = cpf

listaClientes = ['cliente1', 'cliente2', 'cliente3']

Se eu fizer um for, ele só vai gravar o último cliente por cima dos clientes anteriores.
for x in listaClientes:
    x = Clientes('nome','cpf')

Assim ele só registra o cliente 3 e perde os clientes 1 e 2.
Comment: qual vai ser a referencia dos objetos na memoria? x temporariamente vai ser o cliente 1, depois o cliente 2, e por ultimo o cliente 3, ficando este ultimo no x. os dois primeiros seram apagados
Comment: É exatamente esse o problema, não estou sabendo fazer essa referencia.
Comment: Pra que serve `listaClientes`, são os nomes dos clientes? E de onde virão os CPF's? E o que vc quer afinal, criar uma lista de `Clientes`? Aproveitando, o nome da classe não é bom, porque estando no plural dá a entender que ela representa vários clientes, quando na verdade ela representa apenas um...
Answer: vc precisa de uma lista para isso
class Clientes():
        def __init__(self, nome, cpf):
            self.nome = nome
            self.cpf = cpf

    listaClientes = ['cliente1', 'cliente2', 'cliente3']

    cliente =[]
    for i in listaClientes:
        c = Clientes('nome','cpf')
        cliente.append(c)

for k in  cliente:
    print(k.nome,k.cpf)


SQL Server 2008R2 - data in perm table but not in temp table

Question: I am not sure why this is happening... the actual table has data yet when trying to pull data from the actual table into the temp table, there is no data...
IF object_id('DI_Temp.di.Holly') IS NOT NULL
   DROP TABLE DI_Temp.di.Holly

CREATE TABLE DI_Temp.di.Holly
(
Toys varchar(20)
,Meals varchar(100)
,Breaks varchar(20)
)

Insert DI_Temp.DI.Holly
   Select
      Toys, Meals, Breaks
   from toysarefun.dbo.crazytoys (nolock)
   where status = 'active'

--Select * from di_temp.di.holly

IF OBJECT_ID('tempdb.dbo.#Toys') IS NOT NULL
   DROP TABLE tempdb.dbo.#Toys

SELECT *
INTO #Toys
FROM DI_Temp.di.Holly (NOLOCK)
WHERE Toys like 'H*'

Select *
from tempdb.dbo.#Toys

Thanks :)
Answer: Firstly, you are not comparing apples with apples. Your test select should include the SAME filter as the INSERT..SELECT query
Secondly, it's best to minimize the time spent on SELECT.. INTO. Better to create the temporary table first.
Thirdly, don't use tempdb.dbo.#Toys. # is implicitly in tempdb.  You will get this warning anyway

Database name 'tempdb' ignored, referencing object in tempdb.

The changed portions:
-- uncomment first to check if there are any matches
--Select * from di_temp.di.holly WHERE Toys like 'H*'

IF OBJECT_ID('tempdb.dbo.#Toys') IS NOT NULL
DROP TABLE #Toys;

SELECT *
INTO #Toys
FROM DI_Temp.di.Holly (NOLOCK)
WHERE 1=0;

INSERT INTO #Toys
SELECT *
FROM DI_Temp.di.Holly (NOLOCK)
WHERE Toys like 'H*';

Comment: Thank you Richard! Since I am learning SQL coding - can you kindly explain to me what WHERE 1=0; means. It's working. Just needing to know what that meant. :)
Comment: The WHERE clause is a condition (filter) for the query. `WHERE 1=0` is a condition that can never be true, just as `WHERE 'a'='b'` is false. Since the condition is never true, no rows will be inserted into #toys on creation. Yet the statement itself achieves the creation of the table.


How do I count this piece?

Question: I'm only used to standard groupings of notes (like triplets, sixteenth notes, sixteenth note triplets in 4/4) but I don't know how to read/interpret n-lets such as the ones below.

How would I count these groupings to a metronome? What is the correct way to interpret groupings such as these? Note: Time signature for this is 12/8.
Comment: That sounds like a dupe of this: https://music.stackexchange.com/questions/62667/how-are-very-long-tuplets-in-romantic-music-played-in-practice ...
Answer: This will not be expected to be played in exact measure. Get a metronome and work out which beat each new run/phrase begins and then play all the notes in that 'run' before the next phrase is due to begin and you will automatically be playing in time.
Answer: This is just a bit of 'widdley'.  Don't worry about precise counting.  Get the notes in, with impressive speed and attitude!
Answer: Well if you actually do want to count that and play it accurately, you'll need to divide the count up. The 10-plet in the start of your example could for example be split into a 6+4 count, from looking at what you play there, or even 2+2+2+4.
Also if you have no experience with quintuplets, septuplets and so on, learn those first to get a feel for larger tuplets.

How do I count this piece?