Which hook or tpl file controls the output of a view (to manipulate the results)?

Question: I am creating a recurring events views page, but currently the output of my view is displaying multiple references of the same date event. I am also not using Fields as an output, I am using content|teaser.
I have come up with 2 methods of resolving this issue, but wanted to clarify which is best and how to go about it.

Find a hook that outputs the Views rows and then write a conditional to compare each row and delete the duplicates.
Create a tpl file and do a preg_replace() on the views output to delete duplicate rows of the same data.

Now the question is how do i go about finding this hook or what to name the Views tpl file as? I only want it specific to this events page.
Answer: Views Template Suggestion
All views templates can be overridden with a variety of names, using the view, the display ID of the view, the display type of the view, or some combination thereof.
Below are different template suggestions you can use for overriding the defaults.
Let consider a example View, named foobar. Style: unformatted. Row style: Fields. Display: Page.
Display output: This controls the structure of the overall view, including the position of and code around the view administrative links, header, exposed filters, pager, "more" link, footer and feed icon. This template also controls the position of and code around the primary view content, empty content, and attached views.
views-view--foobar--page.tpl.php
views-view--page.tpl.php
views-view--foobar.tpl.php
views-view.tpl.php

Style output: This controls the structure of this particular view display's style, e.g. HTML List, Table, Unformatted, etc. This includes the view title and the code surrounding each row (item in your view) of the given style.
views-view-unformatted--foobar--page.tpl.php
views-view-unformatted--page.tpl.php
views-view-unformatted--foobar.tpl.php
views-view-unformatted.tpl.php

Row style output: This controls the internal structure of each row (item in your view), including the label and the content for each field.
views-view-fields--foobar--page.tpl.php
views-view-fields--page.tpl.php
views-view-fields--foobar.tpl.php
views-view-fields.tpl.php

Fields: There will be one entry for each field in your display, allowing you to control the structure and code for each. If your row style is set to "Node," there won't be any field entries, and the view will use the node's template file instead.
Lets take you have added Title field in the field list, then below are the suggestion to theme title field
views-view-field.tpl.php
views-view-field--title.tpl.php
views-view-field--foobar.tpl.php
views-view-field--foobar--title.tpl.php
views-view-field--page.tpl.php
views-view-field--page--title.tpl.phpfoobar
views-view-field--foobar--page.tpl.php
views-view-field--foobar--page--title.tpl.php
views-view-field--page-1.tpl.php
views-view-field--page-1--title.tpl.php
views-view-field--foobar--page-1.tpl.php
views-view-field--foobar--page-1--title.tpl.php

Views Preprocessors suggestion
If you want to alter the display of any view with preprocess functions, then you can use the below suggestions to modify the display of any view.

Altering Views result
To alter the result of the view itself(i.e modifying the results before its being rendered) you can use any of the following hook,

hook_views_pre_render
hook_views_post_execute

For using these hooks, you can refer the answer by jimajamma.
References

https://api.drupal.org/api/views/theme!theme.inc/group/views_templates/7
http://www.ostraining.com/blog/drupal/views-templates/
http://webpartners.es/en/drupal-7-views-templates-and-preprocess
https://api.drupal.org/api/views/theme!theme.inc/7
https://drupal.org/node/352970
Why doesn't adding results in hook_views_pre_render work?
Comment: Yep.  And you can easily find (and add/change) the templates used by the View by clicking on the `Theme: Information` link in the Views UI.
Answer: The hook you are most probably looking for is views_pre_render(), eg, something along the lines of...
function YOURMODULE_views_pre_render(&$view) {

  if ($view->name == 'THE_VIEW_YOU_ARE_LOOKING_FOR') {

    // modify $view->result per whatever logic you require

  }

}

...where $view->result is an array of all the rows in your View.  Given that you are displaying nodes instead of fields in your View, this should just be an array of objects pointing to nids, eg, something like this:
Array
(
  [0] => stdClass Object
    (
        [nid] => 1
    )

  [1] => stdClass Object
    (
        [nid] => 2
    )

  [2] => stdClass Object
    (
        [nid] => 3
    )

  [3] => stdClass Object
    (
        [nid] => 18
    )
)

Answer: To use a specialized template, name the template file "views-view-youreventsview.tpl.php" where youreventsview is the name of your view.
Comment: which views tpl do i copy from the views folder?
Comment: I usually start with views-view-unformatted.tpl
Answer: I know this is an old thread. But if anyone is struggling to theme the admin views, it will be helpful.
To theme admin view, if we simply goto Theme: Information and create the suggested template file in our template folder of the theme, views won't simply pick up them for the themes like seven or Adminimal Theme. And it is not a good idea to modify the contributed themes also.
So, what will be the solution?
It is so simple...!
We can implement hook_views_api in a custom module.
/**
 * Implements hook_views_api().
 */
function mymodule_views_api() {
  $path = drupal_get_path('module', 'mymodule');
  return array(
    'api' => 3,
    'template path' => $path . '/templates',
  );
}

Once you have cleared the drupal cache, views will start looking into the module's templates folder and will apply the defined templates.
I've written a detailed explanation here.
All done.
Enjoy the theme!.


Finding original function of $1/x$ by using a step function

Question: Is it technically possible to show, that the area under $1/x$ in the interval $[1,a]$ equals $\log a$ without using any kind of differentiation, but only step functions.
I tried this, but without success.
Thank you
Comment: A definition of $\log a$ would be necessary, perhaps as the sum of some series...
Answer: One can get a closed form for an upper (by that meaning right endpoint) Riemann sum $R_n$ by using, instead of the partition of $[1,a]$ into $n$ equal parts, the partition
$$x_0=a^{0/n}=1,\ x_1=a^{1/n},\ \ldots \ x_n=a^{n/n}=a.$$
Then the $k$th subinterval $[x_{k-1},x_k]$ has length $a^{(k/n)}-a^{(k-1)/n},$ and for a right endpoint sample point at $x_k$ of the function $y=1/x$ this interval length is to be multiplied by $1/x_k=1/a^{k/n}$ for its contribution to the sum $R_n$. The "nice" thing here is that the $k$ cancels and the $k$th sum contribution is $1-\frac{1}{a^{1/n}}.$ This is then summed over $k,$ and since here are no remaining $k$ in the expression the right sum $R_n$ for this partition (into $n$ unequal parts) of $[1,a]$ for the integral $\int_0^a (1/x) dx$ is
$$R_n=n\cdot (1-\frac{1}{a^\frac1n}).$$
The latter can be shown to approach $\ln a$ by various means such as L'Hospital, though without knowing what is an "acceptable" definition of $\ln a$ it needs some more work, since the question said "without using any kind of differentiation" which would seem to rule out L'Hospital.
Added later: If one puts $h=1/n$ then the above expression for $R_n$ becomes $(a^0-a^{-h})/h,$ which is the left-hand difference quotient for the derivative of $g(x)=a^x$ at $x=0.$ Then  $g'(x)=\ln(a)\cdot a^x,$ which is $\ln a$ at $x=0.$ So no need for LHospital, only the derivative formula for exponentials.
I do find it interesting that, using this unequal partition, a closed form could be obtained for a Riemann sum. [Note: it needs to be checked that, as $n \to \infty,$ the mesh size of this partition goes to $0,$ but that's straightforward.]
Comment: Thank you! It was a very interesting and a new idea to me!
Comment: @Eu2718 Yes, it seems interesting to me because all the rectangles (in this case above the curve since $1/x$ is decreasing) have the same area with this partition. I think I saw this approach done once somewhere, but didn't recall the details so worked it out again.
Comment: [ oops, the right-endpoint rectangles lie below the curve when the function is decreasing.. :(
Comment: great, that you mention it, but I had to realize, that there are more ways to approach the problem.you helped me. thank you once again


Illegal character causes spring boot microservice build to fail during creation of docker image

Question: I am establishing inter communication with Micro services in a Spring boot application. The response is generated in JSON format and logged in log file using logback.xml. This is further leveraged on ELK side with docker-maven plugins. While performing mvn clean install, it throws exception during creation of docker image through pom.xml
Error stack :

Caused by: com.spotify.docker.client.exceptions.DockerException:
com.spotify.docker.client.shaded.com.fasterxml.jackson.core.JsonParseException:
Illegal character ((CTRL-CHAR, code 0)): only regular white space (\r,
\n, \t) is allowed between tokens
at [Source: (File); line: 1, column: 2]
at com.spotify.docker.client.auth.ConfigFileRegistryAuthSupplier.authForBuild
(ConfigFileRegistryAuthSupplier.java:108)
at com.spotify.docker.client.auth.MultiRegistryAuthSupplier.authForBuild
(MultiRegistryAuthSupplier.java:77)
at com.spotify.docker.client.DefaultDockerClient.build (DefaultDockerClient.java:1483)
at com.spotify.docker.client.DefaultDockerClient.build (DefaultDockerClient.java:1460)
at com.spotify.plugin.dockerfile.BuildMojo.buildImage (BuildMojo.java:240)
at com.spotify.plugin.dockerfile.BuildMojo.execute (BuildMojo.java:135)
at com.spotify.plugin.dockerfile.AbstractDockerMojo.tryExecute (AbstractDockerMojo.java:265)
at com.spotify.plugin.dockerfile.AbstractDockerMojo.execute (AbstractDockerMojo.java:254)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo
(DefaultBuildPluginManager.java:137)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)

pom.xml:

            <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>dockerfile-maven-plugin</artifactId>
                <version>1.4.11</version>
                <configuration>
                    <repository>${docker.image.prefix}/${project.artifactId}</repository>
                </configuration>
                <executions>
                    <execution>
                        <id>default</id>
                        <phase>install</phase>
                        <goals>
                            <goal>build</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

I debugged code and found the cause of error. This is caused in below method at line highlighted:
private List<Comment> findCommentsForFeed(Feeds feed) {
        log.info("Finding comments of feed with id {}", feed.getId());

        String url = UriComponentsBuilder.fromHttpUrl(commentServiceBaseUrl).path("comments")
                .queryParam("feedId", feed.getId()).toUriString();

        // ** THIS LINE CAUSES ERROR... **
        ResponseEntity<List<Comment>> response = restTemplate.exchange(url, HttpMethod.GET, null,
                new ParameterizedTypeReference<List<Comment>>() {
                });

        List<Comment> comments = Objects.isNull(response.getBody()) ? new ArrayList<>() : response.getBody();
        log.info("Found {} comment(s) of feed with id {}", comments.size(), feed.getId());
        return comments;
    }

My controller looks like :
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/feeds", produces = MediaType.APPLICATION_JSON_VALUE)
public class FeedController {

    @Autowired
    private final FeedService service;

    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<List<Feeds>> getFeeds() {
        List<Feeds> feeds = service.getFeeds();
        return ResponseEntity.ok(feeds);
    }

    @GetMapping(path = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<FeedWithComment> getFeed(@PathVariable Long id) {
        FeedWithComment feedWithComments = service.getFeed(id).orElseThrow(ResourceNotFoundException::new);
        return ResponseEntity.ok(feedWithComments);
    }

My logback.xml file for json output appears like:
<springProfile name="docker">

    <appender name="jsonConsoleAppender"
        class="ch.qos.logback.core.ConsoleAppender">
        <encoder
            class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
            <providers>
                <timestamp>
                    <timeZone>UTC</timeZone>
                </timestamp>
                <version />
                <logLevel />
                <message />
                <loggerName />
                <threadName />
                <context />
                <pattern>
                    <omitEmptyFields>true</omitEmptyFields>
                    <pattern>
                        {
                        "trace": {
                        "trace_id": "%mdc{X-B3-TraceId}",
                        "span_id":
                        "%mdc{X-B3-SpanId}",
                        "parent_span_id": "%mdc{X-B3-ParentSpanId}",
                        "exportable": "%mdc{X-Span-Export}"
                        }
                        }
                    </pattern>
                </pattern>
                <mdc>
                    <excludeMdcKeyName>traceId</excludeMdcKeyName>
                    <excludeMdcKeyName>spanId</excludeMdcKeyName>
                    <excludeMdcKeyName>parentId</excludeMdcKeyName>
                    <excludeMdcKeyName>spanExportable</excludeMdcKeyName>
                    <excludeMdcKeyName>X-B3-TraceId</excludeMdcKeyName>
                    <excludeMdcKeyName>X-B3-SpanId</excludeMdcKeyName>
                    <excludeMdcKeyName>X-B3-ParentSpanId</excludeMdcKeyName>
                    <excludeMdcKeyName>X-Span-Export</excludeMdcKeyName>
                </mdc>
                <stackTrace />
            </providers>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="jsonConsoleAppender" />
    </root>

</springProfile>

Answer: I did some analysis and found the issue is because of Spring boot version. There has been changes in directory structure of Spring boot after the introduction of Springboot 2.3.0. I am using Spring boot version 2.3.3.  I did some changes in dockerfile and it worked. Maven docker plugin successfully created the image.
Dockerfile :
FROM adoptopenjdk/openjdk14 as builder

WORKDIR application
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} application.jar
RUN java -Djarmode=layertools -jar application.jar extract

FROM adoptopenjdk/openjdk14
WORKDIR application
COPY --from=builder application/dependencies/ ./
COPY --from=builder application/snapshot-dependencies/ ./
COPY --from=builder application/spring-boot-loader/ ./
COPY --from=builder application/application/ ./
ENTRYPOINT ["java", "-Dspring.profiles.active=docker", "org.springframework.boot.loader.JarLauncher"]


Montar combinações possíveis

Question: Tenho as seguintes classes:
public class Categoria
{
    public int Id { get; set; }
    public string Nome { get; set; }
    public bool Primeiro { get; set; }
}

public class Opcao
{
    public int Id { get; set; }
    public string Nome { get; set; }
    public virtual Categoria CategoriaProxima { get; set; }
    public virtual Categoria Categoria { get; set; }
    public bool Ultima { get; set; }
}

Exemplo de dados:
Categoria                           Opcao

Escolha o que deseja tratar         Rugas
Escolha o que deseja tratar         Manchas
Escolha o que deseja tratar         Olheiras
Escolha o que deseja tratar         Fotoproteção
Escolha o que deseja tratar         Flacidez

Selecione seu tipo de pele          Pele Normal
Selecione seu tipo de pele          Pele Oleosa
Selecione seu tipo de pele          Pele Seca
Selecione seu tipo de pele          Pele Extra Seca

Selecione seu tipo de ruga          Rugas Finas
Selecione seu tipo de ruga          Rugas Médias
Selecione seu tipo de ruga          Rugas Profundas

Selecione seu fototipo              Fototipo 1
Selecione seu fototipo              Fototipo 2
Selecione seu fototipo              Fototipo 3
Selecione seu fototipo              Fototipo 4

Gostaria de obter o seguinte resultado:
Rugas - Pele Normal - Rugas Finas - Fototipo 1
Rugas - Pele Normal - Rugas Finas - Fototipo 2
Rugas - Pele Normal - Rugas Finas - Fototipo 3
Rugas - Pele Normal - Rugas Finas - Fototipo 4

Rugas - Pele Normal - Rugas Médias - Fototipo 1
Rugas - Pele Normal - Rugas Médias - Fototipo 2
Rugas - Pele Normal - Rugas Médias - Fototipo 3
Rugas - Pele Normal - Rugas Médias - Fototipo 4
(...)

Ou seja TODAS as combinações possíveis.
Comecei a fazer, mas não consegui evoluir:
foreach (var opcao in opcoes.Where(x => x.Categoria.Primeiro == true))
{
    // Pular Linha
    opcao.Nome //Exibir Opcao
    while(opcao.Ultima==false){
        // Pular Linha
    }

    proximaCategoria = opcao.CategoriaProxima;
    foreach(var proximaOpcao in opcoes.Where(x=>x.CategoriaProxima.Id == proximaCategoria.Id)){

    }

[VIEW]
@model IEnumerable<Dominio.Categoria>
@{
    var opcoes = ViewData["Opcoes"] as IEnumerable<Dominio.Opcao>;
}

        @foreach (var categoria in Model)
        {

               @categoria.Nome

         }

        @foreach (var opcao in opcoes.Where(x=>x.Categoria.Primeiro == true)) {
            (...)
        }

Answer: Vamos dar uma trabalhada nesse Model Categoria, colocando a propriedade inversa de opções:
public class Categoria
{
    public int Id { get; set; }
    public string Nome { get; set; }
    public bool Primeiro { get; set; }

    public virtual ICollection<Opcao> Opcoes { get; set; }
}

Eu faria duas funções, sendo uma recursiva:
public IEnumerable<String> MontarListaDeOpcoes(List<Categoria> categorias)
{
    foreach (var categoria in categorias)
    {
        foreach (var opcao in categoria.Opcoes)
        {
            if (!opcao.Ultima)
            {
                yield return opcao.Nome + " - " + MontarListaDeOpcoes(opcao.CategoriaProxima);
            } else {
                yield return opcao.Nome;
            }
        }
    }
}

public IEnumerable<String> MontarListaDeOpcoes(Categoria categoria)
{
    foreach (var opcao in categoria.Opcoes)
    {
        if (!opcao.Ultima)
        {
            yield return opcao.Nome + " - " + MontarListaDeOpcoes(opcao.CategoriaProxima);
        } else {
            yield return opcao.Nome;
        }
    }
}

View
@model IEnumerable<String>

               Opções

        @foreach (var opcao in Model)
        {

                    @opcao

        }

Comment: E como eu faria para exibir isso em uma table, por exemplo?
Comment: @DiegoZanardo Coloca um pedaço da View que eu melhoro a resposta.
Comment: Adicionado Cigano!
Comment: @DiegoZanardo Atualizei a resposta. Não entendi bem como você quer construir essa tabela, mas acredito que trabalhando o código da resposta você chegue no resultado esperado.
Comment: T dando esse erro na assinatura do método, "cannot be an iterator block because List' is not an iterator interface type"
Comment: @DiegoZanardo Foi mal! Verdade. `List` não pode ser devolvido por `yield`. Veja agora.
Comment: Agora tem outro erro rsrsrs, CategoriaProxima, é uma categoria e não uma lista de categoria... então ta dando erro no opcao.CategoriaProxima
Comment: Tentei ao inves de receber uma list de categorias, receber apenas uma categoria, mas sem sucesso!
Comment: @DiegoZanardo Escrevi esse código sem testar direito. Atualizei. Repare que fiz agora duas funções com polimorfismo pra que a chamada faça sentido.
Answer: Uma outra forma de gerar esse arranjo seria utilizando o SelectMany.
Veja uma implementação:
// Não utilizei objeto criado por você para facilitar o exemplo.
var categoriaA = new[] { "Rugas","Manchas","Olheiras","Fotoproteção","Flacidez"};
var categoriaB = new[] { "Pele Normal","Pele Oleosa","Pele Seca","Pele Extra Seca"};
var categoriaC = new[] { "Rugas Finas","Rugas Médias","Rugas Profundas"};
var categoriaD = new[] { "Fototipo 1","Fototipo 2","Fototipo 3","Fototipo 4"};

// Escolhe todas as categorias, onde a ordem importa.
var arranjos =
    from a in categoriaA
    from b in categoriaB
    from c in categoriaC
    from d in categoriaD
    select new { a,b,c,d,Descricao = string.Format("{0} - {1} - {2} - {3}", a,b,c,d) };

ViewData["Opcoes"] = arranjos;

View

            a
            b
            c
            d
            Descrição

        @foreach (var item in ViewData["Opcoes"])
        {

                @item.a
                @item.b
                @item.c
                @item.d
                @item.Descricao

        }

A meu ver, você não precisaria das propriedades Ultima, Proxima, etc. se gerar o arranjo separado.
Comment: Mas existem opções que apontam para diferentes categorias. Por exemplo na categoria A a opção rugas pode apontar para a categoria C e as outras opções da categoria A apontem para a categoria B

Montar combinações possíveis


Is possible set order by bool in QSortFilterProxyModel with setSortRole()?

Question: Hello i have a class Filtro(in english is Filter) that is QSortFilterProxyModel , i have setted her sourceModel with myModel class. myModel class is a QAbstractListModel in this class i have a
QList<Tile> m_recipes;

Tile class is this:
class Tile {

public :
    Tile (const QString &nameRecipe,const QString &color,const int &duration,const bool &userRecipe);
    QString nameRecipe()const;
    QString color() const;
    int duration() const;
    bool userRecipe() const;

private:

   QString m_nameRecipe;
   QString m_color;
   int     m_duration;
   bool    m_UserRecipe;
};

Now when i filter the list with the class Filtro, i want to show in qml before all the elements with m_UserRecipe == true and after all the elements with m_UserRecipe == false .
So my question is : in  QSortFilterProxyModel  is possible set order with a role that rapresents a bool value ??
QHash<int, QByteArray> myModel::roleNames() const
{

    QHash <int,QByteArray> roles;
    roles[NameRecipe]="NameRecipe";
    roles[Color]="Color";
    roles[Duration]="Duration";
    roles[UserRecipe]="userRecipe";
    return roles;

}

filtro.h :
class Filtro : public QSortFilterProxyModel
{
    Q_OBJECT

public:
    Filtro(QObject* parent=0);
     ~Filtro();

    Q_INVOKABLE void setStringaFiltro(QString string);
    Q_PROPERTY(bool  showOnlyUserRic READ showOnlyUserRic WRITE setshowOnlyUserRic NOTIFY showOnlyUserRicChanged)
    Q_PROPERTY(QString string READ string WRITE setstring NOTIFY stringChanged)

public slots:

    void setshowOnlyUserRic(bool showOnlyUserRic);
    bool showOnlyUserRic() const;

    QString string() const;
    void setstring(QString string);

signals:
    void showOnlyUserRicChanged();
    void oggettiFiltChanged();

    void stringChanged();

private:

    bool m_showOnlyUserRic;
    int m_oggettiFilt;

    QString m_string;

protected:
    bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const;

};

filtro.cpp
Filtro::Filtro(QObject *parent): QSortFilterProxyModel(parent)
      , m_showOnlyUserRic(false)
      ,m_oggettiFilt(0)
      ,m_string("")
    {
       this->setSourceModel(&myModel);

    }

    Filtro::~Filtro()
    {

    }

    void Filtro::setStringaFiltro(QString string)
    {
        this->setFilterCaseSensitivity(Qt::CaseInsensitive); // lo rendo case insensitive
        this->setFilterFixedString(string);
    }

    QString Filtro::string() const
    {
        return m_string;
    }

    void Filtro::setstring(QString string)
    {
        if (m_string == string)
            return;

        m_string = string;
        emit stringChanged();
        invalidateFilter();  // fa rivalutare il filtro e quindi entra di nuovo in filterAcceptsRows()
    }

    bool Filtro::showOnlyUserRic() const
    {
        return m_showOnlyUserRic;
    }

    void Filtro::setshowOnlyUserRic(bool showOnlyUserRic)
    {
        if (m_showOnlyUserRic == showOnlyUserRic)
            return;

        m_showOnlyUserRic = showOnlyUserRic;
        emit showOnlyUserRicChanged();

        invalidateFilter();  // fa rivalutare il filtro e quindi entra di nuovo in filterAcceptsRows()

    }

    bool Filtro::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
    {

        QRegExp regEx("*"+string()+"*");
        regEx.setPatternSyntax(QRegExp::Wildcard);
        regEx.setCaseSensitivity(Qt::CaseInsensitive);

        if(showOnlyUserRic()==true) {
         // se devo visualizzare solo
         QModelIndex ricUtente = sourceModel()->index(source_row,0, source_parent); // vado a leggere singolarmente ogni riga del modello
         QString stringaConfronto=sourceModel()->data(ricUtente,modello::NomeRicetta).toString();

         if(sourceModel()->data(ricUtente,modello::RicettaUtente)==true && stringaConfronto.contains(regEx)==true)
         {
             // se è ricetta utente
             return true;
         }
         else{

             return false;
         }

       }
        else{

            QModelIndex ricUtente = sourceModel()->index(source_row,0, source_parent); // vado a leggere singolarmente ogni riga del modello
            QString stringaConfronto=sourceModel()->data(ricUtente,modello::NomeRicetta).toString();
            if(stringaConfronto.contains(regEx))
                return true;
    //        if(sourceModel()->data(ricUtente,modello::NomeRicetta)== string() )  //confronto il roles ricetta utene x filtrare il
    //        {
    //            return true;
    //        }
            return false;
   }
}

Comment: let's say that it has 2 values with True, what should be the criteria for one to be before another?
Comment: the nameRecipe value..  i want all the elements with true value order by name and after all the elements with false value order by name , i hope that is more clear
Comment: Test my answer, what is the role that returns m_UserRecipe?
Answer: If you want to have an order of that type you just have to overwrite the lessThan method:
bool Filtro::lessThan(const QModelIndex &left, const QModelIndex &right) const
{
    bool leftData = sourceModel()->data(left, modello::UserRecipe).toBool();
    bool rightData = sourceModel()->data(right,  modello::UserRecipe).toBool();

    if(leftData != rightData){
        return leftData;
    }
    else
        return QSortFilterProxyModel::lessThan(left, right);
}

Update:
you must call sort(0)(the number does not matter since it is made for a multi-column model, but in your case it is not.), also enable the dynamicSortFilter, and for the last one in your case, you must set the sorting role to modello::NomeRicetta:
Filtro::Filtro(QObject *parent): QSortFilterProxyModel(parent)
  , m_showOnlyUserRic(false)
  ,m_oggettiFilt(0)
  ,m_string("")
{
    setFilterRole(modello::RicettaUtente);
    setSortRole(modello::NomeRicetta);
    setDynamicSortFilter(true);
    sort(0);
}

The complete example can be found on this link
Comment: Yes modello::UserRecipe is the role associated with m_UserRecipe. I tested the code but when i put  a breakpoint inside the method , the breakpoint don't work...
Comment: @pablodepas87 What does it mean that it does not work?
Comment: when i am in debug, the code don't stop at breakpoint  at the line: bool leftData = sourceModel()->data(left, modello::UserRecipe).toBool();
Comment: @pablodepas87 I have tried it in other projects and it works, you could share a code to me to reproduce and then I will review what the problem is.
Comment: @pablodepas87 you could print something in that function, for example: qDebug () << "lessThan"; sometimes debuggers have problems
Comment: ok i share the project on github and after i will give you  the link just some minutes
Comment: @pablodepas87 okay, I'll wait for you
Comment: this is the link https://github.com/pablodepas87/GridPaginationTwoFilter/
Comment: It work how i want!!! :) great job!!! Thanks for help me once again!! :) :)


Fechar menu ao clicar em outro

Question: Tenho o seguinte MENU:

    <img style="position: relative;right:45px;bottom:39px" src="<?= base_url('assets/img/menu-topo.png') ?>" width="340px"/>

            <a href="<?= base_url('/') ?>"> Painel

        <?php
        echo '
';
        echo '   Gerenciar';
        echo '
';
        if ($this->session->userdata('id_perfil') == 1):
            echo '
Administradores
';
            echo '
Assinantes
';
            echo '
Componentes
';
            echo '
Formas de Pagamento
';
            echo '
Tipos de Contato
';
        endif;
        if ($this->session->userdata('id_perfil') == 2):
           /* echo '
Assinantes Secundários
';*/
            echo '
Fornecedores
';
            echo '
Clientes
'
            . '
Pacotes
'
            . '
Template Convite
';
            echo '
Tipos de Contato
';
            echo '
Tipos de Fornecedor
';
        endif;
        echo '
';
        echo '
';
        if ($this->session->userdata('id_perfil') == 2):
            echo ''
            . '
'
            . '   Agenda'
            . '
'
            . '
Configurações
'
            . '
Calendário
'
            . '
Convidados
'
            . '
'
            . '
'
            . '
'
            . '   Financeiro/Custos'
            . '
'
            . '
Fixos
'
            . '
Evento
'
            . '
'
            . '
';
        endif;
        ?>

E o jQuery:
$('.submenu').click(function () {
    if ($(this).attr('data-action') == 'open') {
        $(this).attr('data-action', 'close');
        $(this).find('a span').removeClass('fa-chevron-left');
        $(this).find('a span').addClass('fa-chevron-down');
    } else {
        $(this).attr('data-action', 'open');
        $(this).find('a span').removeClass('fa-chevron-down');
        $(this).find('a span').addClass('fa-chevron-left');
    }
    $(this).find('ul').slideToggle();
});

Funciona perfeitamente, porém, gostaria que ao clicar em um item principal, fechasse o item anterior, para que não ficasse todos os itens abertos conforme forem clicando...
Comment: Seria legal se colocasse num fiddle para testarmos. Mas uma coisa que funciona é o seguinte: você fecha todos (mesmo os que já estão fechados) e abre apenas o que clicou.
Answer: Adiciona isso no seu código acima do código:
$('ul.list-submenu').slideUp(); // Essa linha
$(this).find('ul').slideToggle();

Comment: Perfeito, era isso mesmo. Obrigado, bom dia ai! :)

Fechar menu ao clicar em outro


Run a bash script after EC2 instance boots

Question: I have a script on an EC2 instance that remotely starts another instance.
Once this instance has fully loaded (finished booting) I want it to automatically run a bash script, what would be the best way to do this?
I need everything to be fully started, basically the bash script runs a image conversion script (using ImageMagick and executes the "wget" command a few times)
Currently, the script is located here:

/home/root/beginProcess.sh

And I can start it manually by executing

bash beginProcess.sh

RHEL-6.2-Starter-EBS-i386
Also there is an EBS volume attached to this, if that helps, Thanks!
Answer: I'd suggest just using the user-data option to ec2-run-instances. It lets you give a script of some sort to the VM which will be run on first boot. If you're using ubuntu or debian, you can use cloud-init, which puts some nice polish on the process. If using cloud-init, you can use the [runcmd] section of the config file to specify arbitrary commands to run after boot.
Thanks to SF user Eric Hammond for the user-data page. Check out his site - it has a wealth of information on AWS.
Edit: After re-reading, it's not clear whether you wanted to run a command on initial boot or on every boot. The above instructions only apply to the initial boot. If you want to run a command on every boot, you have a couple options - you can run a command via the @reboot cron directive, or alternatively you can add the script to /etc/rc.local, which will be run each time the system boots.
Comment: Awesome thanks for the response, to clarify I wanted it to run each time the system boots, `/etc/rc.local` is working wonderfully, cheers
Answer: If you were using an AMI that had the cloud-init package installed (like Amazon Linux or Ubuntu) then you could simply pass the bash script (which starts with #!) as the user-data-file and it would run automatically at the end of the boot process.
For example, it could be as simple as:
ec2-run-instances                             \
  --user-data-file /home/root/beginProcess.sh \
  --key $USER                                 \
  ami-XXXXXXXX

Here's the article where I introduced the user-data script concept, now available in major EC2 AMIs like Amazon Linux and Ubuntu: http://alestic.com/2009/06/ec2-user-data-scripts
Unfortunately, it looks like you're wanting to use a RHEL AMI.  I ran a copy of that and could not find any references to cloud-init or running user-data scripts on first boot, nor did a test of the same work.
I'm not saying you should switch Linux distros just for this, but Amazon Linux is based on RHEL, so that might work for you.
Here's an article I wrote that might help you debug your user-data script if it doesn't work the first time: http://alestic.com/2010/12/ec2-user-data-output
Comment: Offtopic, but thank you for creating such an invaluable too. Three cheers.
Answer: This is an old question but I could not find a good answer to this anywhere. My use case was needing to re-run some commands on an existing instance due to the instance being shut down and started up again on a schedule.
The typical answer is to use EC2 User Data, but this doesn't seem to work for me. Either it's because User Data is only for running commands on newly created instances (such as bootstrapping instances for scaling), or because the documentation is out of date. Not sure which, but I was having no luck getting anything to work. There is apparently some method for running commands each time an existing instance starts shown here: How to make EC2 user data script run again on startup?, but this simply doesn't work for me at all. Nothing happens.
After bumbling around for a while, I took a shot in the dark and just modified the .bashrc file on my EC2 instance, and lo and behold, it works exactly as expected and runs my commands on instance startup. This is almost too obvious, but it's a little remarkable it's not mentioned anywhere.
Answer: The authoritative source for how to use EC2 UserData to run a script each time your instance boots is here. In short, I create a script on the instance (make sure to make it executable), then I use the following userdata script:
Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0

--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"

#cloud-config
cloud_final_modules:
- [scripts-user, always]

--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"

/path/to/script.sh
--//

You only need to change the second-to-last line to point to your script.
Another trick I found is that if you were already playing around with this and had some other UserData script on the instance, it is cached on the machine and does not update when you change the UserData script. To force the new UserData script to actually be used, you need to run cloud-init clean on the instance to clear the UserData cache.
Comment: Nice to have an official answer from AWS! There are so many differing approaches proposed in various forums
Comment: What would be the file extension for mime type script and how do we make it executable?
Comment: @Brooke I set this UserData script via the AWS Console web API, not as a file on the instance. The only thing you need to put on the instance is the `/path/to/script.sh` (and probably make it executable).


Screen flashes when changing background image (hover)

Question: Simple idea. Page has a background image. When user hovers over some link, the image changes.
Here's the implementations: http://www.goel.io/ (hover over social links)
You'll notice a flash. I know that's because data transfer and rendering takes a small but noticeable time. Also, you can notice that during the image change, the new image is it's own original size and then resizes to the full screen.

This is the code for setting the background image:
.bg {
    content: "";
    z-index: -1;
    position: fixed;
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
    height: 100%;
    width: 100%;
    background-image: url(/images/schemes/orange.svg);
    -moz-transition: all 0.4s linear;
    -o-transition: all 0.4s linear;
    -webkit-transition: all 0.4s linear;
    transition: all 0.4s linear
}

And here's the code that changes the bg:
$(".btn-blog").mouseover(function(e) {
    $(".bg").css("background-image", "url(/images/schemes/orange.svg)");
});

I've tried a bunch of stuff and looked at a bunch of things. Nothing seemed relevant.
Any ideas on how to fix these 2 issues?
Answer: Try using .fadeTo() , Array.prototype.concat() Array.prototype.splice()

$(function() {
  $.fx.interval = 0;
  (function(bg, btn) {
    btn.mouseover(function(e) {
      bg.fadeTo(75, 0.9, "linear", function() {
        bg.fadeTo(75, 1.0, "linear", function() {
          var img = bg.css("backgroundImage").split(", ");
          img = img.concat(img[0]).splice(1, 4).join(",");
          bg.css("backgroundImage", img)
        });
      })
    })
  }($(".bg"), $(".btn-blog")));
})
.bg {
  width: 100%;
  /* 100% */
  height: 100%;
  /* 100% */
  display: block;
  opacity: 1.0;
  z-index: -1;
  position: fixed;
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100%, 0px, 0px, 0px;
  background-image: url("http://lorempixel.com/300/300/nature"), url("http://lorempixel.com/300/300/cats"), url("http://lorempixel.com/300/300/sports"), url("http://lorempixel.com/300/300/technics");
  -webkit-transition: background-image -150ms linear;
  -moz-transition: background-image -150ms linear;
  -ms-transition: background-image -150ms linear;
  -o-transition: background-image -150ms linear;
  transition: background-image -150ms linear;
}
.btn-blog {
  font-size: 36px;
  text-align: center;
  border: 1px solid #fff;
  display: block;
  position: relative;
  left: 39%;
  top: 10px;
  width: 120px;
}
.btn-blog:hover {
  cursor: wait;
}

  hover

Answer: You can use Link prefetching
<link rel="prefetch" href="/images/schemes/orange.svg">

But it doesn't work cross browser, so a safer way might be to load them as part of the page but hidden with css, if you do not wish to have the "flashing"
Comment: But `prefetch` would work only if all the images are in the DOM on page load. But in my case, it's not.
Comment: look at the example in the page, ``, it's purpose is to fetch future resources during idle time, that can even be the next html page that users are most likely to visit. But if it's not done correctly, you are wasting user's bandwidth
Comment: I went with hiding the image in DOM. But there's still the issue where image is it's real size and then switches to the full screen size. http://i.imgur.com/zcMXWRF.gif
Answer: Why don't you make use of a css sprite and change the background image on :hover?


How do you solve the equation $ (z^2-1)^2 = 4 ? $

Question: $ (z^2-1)^2 = 4  \iff $$z_1 = 3 $ and $ z_2=-1$
$arg(z_1)= 0 ,  arg(z_2) = \pi$
$$ z_1 = \sqrt{3} \left(\cos\left(\frac{2\pi k}{2}\right) + i\sin\left(\frac{2\pi k}{2}\right)\right)$$
$$z_2 = i \left(\cos\left(\frac{2\pi k}{2} +\pi\right) + i\sin\left(\frac{2\pi k}{2} +\pi\right)\right) \mid k= \{ 0,1 \}$$
$$ z = \{ \sqrt{3}, -\sqrt{3}, i, -i \}$$
Is this correct?
Comment: You mean $z_1^2=3$ and so on
Comment: Yes, it seems right.
Answer: $(z^2-1)^2=4\iff$
$z^2-1=2,-2\iff$
$z^2=3,-1\iff$
$z=\sqrt{3},-\sqrt{3},\sqrt{-1},-\sqrt{-1}\iff$
$z=\sqrt{3},-\sqrt{3},i,-i$
Comment: @user1511417 Google "roots of unity". Have fun! I recommend the (e-)book by Brown and Churchill
Comment: This is nice and simple. I hardly can believe this is "legal". Can you really handle complex powers like with real-numbers??
Comment: @user1511417: Yes.
Comment: Caveat: When you take the $n$th root of both sides, you will have $n$ solutions, some of which you will have ignored with real numbers.
Comment: @GFauxPas: True, but in the case above I have not ignored any such solution.
Comment: @GFauxPas: Computing the $n$th root yields $n$ solutions. Here, we have $n=2$, hence $2$ solutions. If it was a different case, then I would use a more general method in order to compute all $n$ solutions.
Comment: It was just a warning to "can you really handle...," question, not a critique of your answer.
Comment: @GFauxPas: Oh, I understand now. Good point, thanks :)
Comment: And a "more general method" would be with sin/cos for example (like above) ?
Answer: $(z^2-1)^2=4\Leftrightarrow (z^2-1)^2-2^2=0\Leftrightarrow (z^2-1-2)(z^2-1+2)=0\Leftrightarrow(z^2-3)(z^2+1)=0\Leftrightarrow (z-\sqrt 3)(z+\sqrt 3)(z-i)(z+i)=0$
It follows that $z\in\{\sqrt 3, -\sqrt 3, i,-i\}$
.


Where are the Kubernetes kubelet logs located?

Question: I installed Kubernetes on my Ubuntu machine. For some debugging purposes I need to look at the kubelet log file (if there is any such file).
I have looked in /var/logs but I couldn't find a such file. Where could that be?
Comment: For a Windows node, in case someone stumbles on this question, they are found in `C:\k`  you'll see `kubelet.out.log` and `kubelet.err.log`; that's depending on how you set up your node.
Answer: If you run kubelet using systemd, then you could use the following method to see kubelet's logs:
# journalctl -u kubelet

Comment: This is the case for Amazon EKS - just found kubelet logs thanks to this comment
Comment: It is also true for Microsoft's AKS.
Comment: Works for GKE too, but you might have to set password for your VM user and add it to `systemd-journal` group. Set password using `sudo passwd` and add yourself to the group using `sudo gpasswd -a  systemd-journal`, logout and login and the above command should work.
Comment: How can i store this log in specific PATH ?
I want to ship my Kubelet logs to ELK stack
Answer: It depends how it was installed. I installed Kubernetes on some Ubuntu machines following the Docker-MultiNode instructions.
With this install, I find the logs using the logs command like this.

Find your container ID.
$ docker ps | egrep kubelet

Use that container ID to view the logs
$ docker logs `<container-id>`

Comment: The kubelet is normally a process in the host, not a pod.
Comment: I installed Kubernetes by running kube-up.sh script in cluster directory and I have a single node running as both master and minion
Answer: If you are trying to go directly to the file you can find the kubelet logs in /var/log/syslog directory. This is for ubuntu 16.04 and above.
Answer: Finally I could find it in /var/log/upstart directory. Kubernetes in my machine is started using upstart. That's why those log files are in upstart directory
Answer: I installed Kubernetes by kind (Kubernetes in docker).

find docker container of kind to enter

$ docker container ps
CONTAINER ID        IMAGE                         COMMAND                  CREATED             STATUS                 PORTS                                                          NAMES
62588e4d284b        kindest/node:v1.17.0          "/usr/local/bin/entr…"   2 weeks ago         Up 2 weeks             127.0.0.1:32769->6443/tcp                                      kind2-control-plane

$ docker container exec -it kind2-control-plane bash
root@kind2-control-plane:/#

Inside container kind2-control-plane, you could find logfiles in two place:

/var/log/containers/
/var/log/pods/

And then,you will find they are the same, you can see the example below:
root@kind2-control-plane:/# cat /var/log/containers/redis-master-7db7f6579f-scw95_default_master-f6374281c2c6afcfcd0ee1214d9bd51c1684c0b6c0ba1056295246ecd055563c.log | tail -n 5
2020-04-08T12:09:29.824252114Z stdout F
2020-04-08T12:09:29.824372278Z stdout F [1] 08 Apr 12:09:29.822 # Server started, Redis version 2.8.19
2020-04-08T12:09:29.824440661Z stdout F [1] 08 Apr 12:09:29.823 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
2020-04-08T12:09:29.824459317Z stdout F [1] 08 Apr 12:09:29.823 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
2020-04-08T12:09:29.82446451Z stdout F [1] 08 Apr 12:09:29.824 * The server is now ready to accept connections on port 6379

root@kind2-control-plane:/# cat /var/log/pods/default_redis-master-7db7f6579f-scw95_094824e1-25aa-4e1e-ab23-d4bae861988a/master/0.log  | tail -n 5
2020-04-08T12:09:29.824252114Z stdout F
2020-04-08T12:09:29.824372278Z stdout F [1] 08 Apr 12:09:29.822 # Server started, Redis version 2.8.19
2020-04-08T12:09:29.824440661Z stdout F [1] 08 Apr 12:09:29.823 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
2020-04-08T12:09:29.824459317Z stdout F [1] 08 Apr 12:09:29.823 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
2020-04-08T12:09:29.82446451Z stdout F [1] 08 Apr 12:09:29.824 * The server is now ready to accept connections on port 6379

root@kind2-control-plane:/# ls -l /var/log/containers/ | grep redis
lrwxrwxrwx 1 root root 101 Apr  8 12:09 redis-master-7db7f6579f-scw95_default_master-f6374281c2c6afcfcd0ee1214d9bd51c1684c0b6c0ba1056295246ecd055563c.log -> /var/log/pods/default_redis-master-7db7f6579f-scw95_094824e1-25aa-4e1e-ab23-d4bae861988a/master/0.log

If you want to know more in detail about the directories, you can see 2019-2-merge-request in Github.


Arquivos na pasta public utilizando o Laravel 4.2 estão inacessíveis

Question: Olá,
tenho uma aplicação onde são criados alguns arquivos na pasta public do Laravel 4.2, envio então um e-mail para o usuário com as URL's para efetuar o download destes arquivos, porém ocorre um erro ao tentar efetuar o download.

Inicialmente parece envolver as rotas do Laravel, a questão é, se é necessário criar rotas para cada download que vou disponibilizar? Como posso estar fazendo isso? E se não é necessário, qual configuração devo efetuar para que os arquivos da pasta public possam ser acessados por outros usuários?
Agradeço pela atenção.
Answer: Não é preciso definir as rotas para cada download. Você pode acessar os arquivos estáticos usando o Laravel 4 normalmente.
Você primeiramente deve ter em mente que a raiz de uma aplicação Laravel 4 não está na pasta onde se encontra os arquivos da sua aplicação, mas sim a pasta public.
O apontamento do Apache (ou qualquer outro servidor que você use) Deve ser feito para a pasta public.
Sendo assim, se você tem um arquivo estático no caminho public/imagens/0001.png, você não vai conseguir acessá-lo com meusite.com.br/public/imagens/0001.png, pois a pasta public é a pasta raiz da aplicação.
O caminho correto no exemplo acima seria: meusite.com.br/imagens/0001.png.
Lembre-se: Se sua aplicação Laravel 4 está dentro de uma pasta chamada meusite o apontamento do Apache deve ser feito para meusite/public.
Uma boa forma de testar se sua aplicação foi configurada corretamente é colocando esse código em `routes.php'
dd($_SERVER['DOCUMENT_ROOT']);

Se exibir o caminho com public no final, significa que está com a configuração correta (ou digamos, o padrão do Laravel).
Comment: Realmente passou despercebido a questão da pasta public, agradeço a ajuda, o problema foi solucionado.
Comment: Se precisar de alguma coisa sobre Laravel, pode contar com a gente :p


False positive rate at K recall

Question: I just stumbled upon a new metric I've never heard about called False Positive rate at K recall (FPR-K).
Searching the internet I just managed to find more papers using the metric but none of them actually explain how is it calculated.
The paper was on matching feature points in multi-modal images.
I know what is AP@K, used in tasks involving some thresholding (i.e. image detection where we're using intersection over union to calculate our TP/FP etc).
My assumption regarding FPR-95 is that there's some thresholding involved as well (else why the "at K" term?), and as with thresholds, they control the precision / recall rate. So we set a threshold causing 95% recall, and now we calculate the FP rate (FP / FP + TN).
Can anyone validate or invalidate my assumption?
Answer: I've found the answer in some paper.
FPR at 95% TPR can be interpreted as the probability that a negative (out-of-distribution) example is misclassified as positive (in-distribution) when the true positive rate (TPR) is as high as 95%.
True positive rate can be computed by TPR = TP / (TP+FN), where TP and FN denote true positives and false negatives respectively.
The false positive rate (FPR) can be computed by FPR = FP / (FP+TN), where FP and TN denote false positives and true negatives respectively.
Comment: How is it calculated? I mean given TPR of 95% what's the FPR?

False positive rate at K recall


Performance fright while playing in front of public, a teacher, an examiner, even a couple of colleagues

Question: I have been fighting with this for sometimes and I am afraid I will have to give up. I don't know exactly what it is but when I play at home, I can perfectly and smoothly play any piece I know from the beginning to end without any major mistakes, providing all required phrasing, articulation, dynamics. I can remember all notes without hesitation.
When only I have to play in front of someone, even people I know who I am 100% certain would not judge me, so would not my teacher, I turn into something like badly prepared student, forgetting notes, playing only with half skills I could normally present etc. yesterday, I couldn't start a piece I know by heart. There were like three attempts and I almost gave up. Eventually, I got through quite well but it scares me that there is something wrong.
As last option, I would like to ask any of you who has similar problem like me. What should I do to manage it and cope with the performance fright? If you have managed to overcome it, what kind of things helped you to beat it? Have you eventually started to enjoy playing in front of friends, colleagues etc.?
This is truly killing me,honestly, I enjoy playing at home but I wish I could some day show how I could improve. And because the fright I feel, it seems something is being taken away from me, all the pleasure I hold when playing the instrument is fading. I even consider meeting with sort of professional to perhaps understand the problem.
Thanks
Comment: You're me, aren't you? Seriously, I can even feel my performance ability drop the second I hit "Record" on the Soundcloud app I use to save sketches. It's like the phone is watching me. I wish I could help more, but I can't wait for the answers myself. Don't be too down, I have recently become better at playing in front of trusted people; first, find someone who you know really appreciates you AS A PERSON (for me, it's my wife) so you KNOW, in your bones they will be non-judgemental. And try to work on from there.
Comment: I actually find playing in front of my more musical friends easier; I know they appreciate the work involved.
Comment: I have already played a couple of times in front of audience but this is always the same. I could be relaxed 15 mins, 10 mins before performance but somehow at the time I've got to play every feeling like panicking, fright, etc. comes back and take over! I feel it's really bad and I feel a little bit hopeless.
Comment: A related question is "why on earth do finger tips need to sweat?" I can see no evolutionary advantage to this and the only time it seems to happen is when I'm about to play in front of an audience.
Answer: What you have is hardly rare. It's a phenomenon that seems to occur more in some adults than children. Having run an examination centre periodically, I've heard far more grown-ups say "I really don't know why I'm doing this", as nerves kick in. It's probably due to the fact that kids are doing test and exams day in, day out, whereas adults hardly ever do, apart from driving test or interviews.
But that doesn't help you. One remedy is to immerse yourself in performing. The more you do, the easier it gets. It won't feel like it for a long time, but by playing in front of people often, AND making the occasional mistake, but shrugging it off, the syndrome will gradually diminish.
Recording efforts is also stressful, as one wants to produce a good take each time. So try that, but don't beat yourself up when you make mistakes.
If at all possible, try to play with others. It gives confidence, makes you less centre stage, is fun and gives someone else to blame for mistakes !! You will also be concentrating on being part of a team, which means you won't be thinking about any audience so much.
Someone once said, when faced with a viscious boss - imagine them naked. Works well for an audience, too. When you worry about making mistakes, that's what you'll do. So concentrate on your best previous performance not one of your worst.
Answer: Record yourself.  Once you can create a usable audio recording, make a video, with the intent to put it up on some video platform (be sure to use material that is not under copyright in order to avoid the pesky rightholder corporations barging down your door).
You'll be surprised at the level of focus and self-consciousness and number of retakes it takes to even create a single useful recording.
That will give you a bunch to work on without involving others, thus leaving at least the embarrassment angle of the problem to be tackled later separately.
Answer: Being nervous about playing music in front of others is not that uncommon. I really don't think that you should meet with a professional to understand the problem. Unfortunately the solution to this issue is to put yourself in uncomfortable positions where you're forced to play in front of others so that you can overcome the nervousness. Familiarity breeds comfort.
No one is perfect. You will make mistakes, plenty of successful musicians have made mistakes and will continue to make mistakes. Unless your mistake is incredibly jarring or the piece is incredibly well known, a lot of non musical people might not notice small mistakes. Seek to play in front of people and friends that will not sugar coat the truth. Sometimes it is better to receive negative feedback, than to receive insincere positive feedback from friends and family members.
Your question has a tag of piano, so I'm assuming that piano is your main instrument. Piano is a great instrument that can be played at open mics (a keyboard in that case). I suggest finding a couple of open mics and preparing some pieces to play with your musical friends, so that you have an unbiased audience where you can sharpen up your performance skills and get rid of or minimize the nervousness.


How to fix not accurate the two datetime using php

Question: I have question regarding to my module, I found out that my the two date and time is not accurate well, The first date time has a value however the second has no value, so if that is the case, the result will be null or i't can't show any value in my table data.
To demonstrate well, I will show you guys the sample output that I already coded.

$datetime1 = new DateTime($res_parent->created_store1);
$datetime2 = new DateTime($res_parent->arl_approved);
$interval = $datetime1->diff($datetime2);

$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');

In my database output it look like this,
Answer: Assuming the values of $res_parent are correct, there is nothing wrong with the above code, although you may want to check if the dates are set before performing operations on the dates, and set a default string if the date values are not available:
if(!empty($res_parent->arl_approved) && !empty($res_parent->created_store1){
  $datetime1 = new DateTime('2019-04-11 16:20:03');
  $datetime2 = new DateTime('2019-04-11 16:19:30');
  $interval = $datetime1->diff($datetime2);
  $elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
}else{
  $elapsed = "Not Available";
}

Gives us the result:
"0 years 0 months 0 days 0 hours 0 minutes 33 seconds"

Or
"Not Available"

Please check and ensure your $res_parent object is set correctly.
Hope that helps,
Comment: HI @Miroslav , what do you mean for that ?


Where does apache store the location of php?

Question: I have compiled PHP 5.3 on ubuntu about two months ago following Brandon Savages guide (I think). It works. Now I wanted to see in what file apache stored the location of the PHP binary but I can't find it, it's not in any configuration file. Does apxs2 has something to do with that?
edit:
cat /etc/apache2/mods-available/php5.load

gives
LoadModule php5_module /usr/lib/apache2/modules/libphp5.so

Answer: Try this:
cat /etc/apache2/mods-available/php5.load

Comment: When PHP is built/used as a module the PHP interpreter is loaded into the Apache server (via that LoadModule directive).  The web server and the PHP interpreter run in the same process - think Kirby eating critters and gaining their powers :)
Comment: Thanks. The output: "LoadModule php5_module /usr/lib/apache2/modules/libphp5.so"

I've seen this but couldn't connect it to a php binary. How does this file load PHP?
Comment: Is this file created and added to the apache dir by the make/make install?


Is there any generic motivation for building scales which are supersets of the desired key(s)?

Question: In conventional music, the octave is divided into the twelve frequency Chromatic Scale, but then only subsets of those twelve frequencies form the key used at any given time.  I understand why the twelve frequencies are a good choice, as their overtones line up nicely, but suppose I want to choose my own set of frequencies to serve as notes for some music.  Perhaps lining up the overtones cleanly is less important or even undesirable in this context.
Is there any reason I should want to build a larger set of notes, analogous to the Chromatic Scale, and then derive keys from it as subsets, rather than simply building a key directly from frequencies every time I need one?  Is it valuable to have a few (such as twelve) repeated frequencies utilized from song to song and key change to key change, or is the only reason for such a restriction the overtone math and physical instrument logistics?
Answer: You wrote your question from the perspective of modern Western music based on 12-tone equal temperament (12TET). The main advantage of this choice is that all intervals in all keys have the same size. This allows to use complex harmonies and modulations. However, the "lining up of the overtones" in 12TET is only approximate, and some people dislike its sound for this reason.
You are asking about creativity, and since you want to depart from conventions, it's totally up to you what you can do. What I however can recommend is to study music that departs from 12TET. Learning about what has been explored may help you to make your choices. Example directions to explore could be baroque music, contemporary classical music, or traditional/classical music of cultures other than Western.


Distanciar imagem do texto em Button

Question: tenho esse Buttoncom uma imagem  e texto

xml
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/notificacao"
    android:drawableLeft="@drawable/alarm"
    android:background="@null"
    android:id="@+id/btNotificacao"
    android:layout_gravity="center_horizontal" />

tava querendo distânciar o reloginho do texto , tentei colocar um espaço antes do texto mais ignora o espaço
Answer: Achei a solução.
android:drawablePadding="8dp"

Distanciar imagem do texto em Button


Accessing another route in IIS returns error

Question: Scenario:
I'm using React to be able to do my project.
I'm also using the react-router-dom to route the application. For this routes I have the following code:
import React from 'react'
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom'
import isAuthenticated from '~/services/auth/auth'
import history from './history'

import Login from '~/pages/login'
import Menu from '~/pages/menumain'

/* *** SISTEMA *** */
/* Permissões */
import Permissions from '~/pages/sistema/permissoes/permissoes'
import AddPermission from '~/pages/sistema/permissoes/addpermission'

/* *** CADASTRO *** */
/* Usuário */
import ReadUsers from '~/pages/cadastro/usuario/listusers'
import CreateUser from '~/pages/cadastro/usuario/cadusers'
import UpdateUser from '~/pages/cadastro/usuario/edituser'
/* Empresa */
import ReadCompany from '~/pages/cadastro/empresa/listEmpresa'
import CreateCompany from '~/pages/cadastro/empresa/cadEmpresa'
import UpdateCompany from '~/pages/cadastro/empresa/editEmpresa'
/* Contas */
import ReadAccount from '~/pages/cadastro/contas/index'
import CreateAccounts from '~/pages/cadastro/contas/create'
import UpdateAccounts from '~/pages/cadastro/contas/update'
/* Fechamento */
import ReadClosure from '~/pages/cadastro/fechamento/index'
/* *** FLUXO DE CAIXA *** */
import FluxoCaixa from '~/pages/fluxoCaixa/index'

/* *** Ajuda ** */
import Sobre from '~/pages/ajuda/sobre'

/* *** Erro *** */
import Error from '~/pages/error'

import PermissonStatus from '~/pages/getpermissions'

const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
    {...rest}
    render={props => {
    const isAuth = isAuthenticated()
    return isAuth ? (
        <Component {...props} />
    ) : (
        <Redirect
        to={{ pathname: '/login', state: { from: props.location } }}
        />
    )
    }}
/>
)

const Routes = () => (
<BrowserRouter history={history}>
    <Switch>
    <Route exact path="/login" component={Login} />
    <Route exact path="/fluxocaixa" component={FluxoCaixa} />
    <PrivateRoute exact path="/" component={Menu} />

    {/* *** SISTEMA *** */}
    {/* Permissões */}
    <PrivateRoute exact path="/permissions" component={Permissions} />
    <PrivateRoute exact path="/permissionModels" component={AddPermission} />
    {/* Usuário */}
    <PrivateRoute exact path="/readusers" component={ReadUsers} />
    <PrivateRoute exact path="/createuser" component={CreateUser} />
    <PrivateRoute exact path="/updateuser" component={UpdateUser} />
    {/* Empresa */}
    <PrivateRoute exact path="/readcompany" component={ReadCompany} />
    <PrivateRoute exact path="/createcompany" component={CreateCompany} />
    <PrivateRoute exact path="/updatecompany" component={UpdateCompany} />
    {/* Contas */}
    <PrivateRoute exact path="/readaccounts" component={ReadAccount} />
    <PrivateRoute exact path="/createaccounts" component={CreateAccounts} />
    <PrivateRoute exact path="/updateaccounts" component={UpdateAccounts} />
    {/* Fechamento */}
    <PrivateRoute exact path="/readclosure" component={ReadClosure} />

    {/* *** Ajuda *** */}
    {/* Sobre */}
    <PrivateRoute exact path="/about" component={Sobre} />

    <PrivateRoute exact path="/permstatus" component={PermissonStatus} />

    <Route component={Error} />
    <Route exact path="/teste" component={Permissions} />
    </Switch>
</BrowserRouter>
)
export default Routes

Goal:

I post this code in IIS 8.5 and if I acess the route http//localhost:3000 , it returns the desired route.

Problem:
when i acess http//localhost:3000/fluxocaixa i received this error:

Anything solution for this error?
Comment: https://medium.com/@mateioprea/setting-up-a-react-app-with-react-router-in-iis-71cb86aee376 Lesson 101.
Answer: To fix this issue you first need to install the URL rewrite module.
download link:
https://www.iis.net/downloads/microsoft/url-rewrite
add below rule in your web.config file(if not then create web.config file first)
<?xml version="1.0"?>
<configuration>
 <system.webServer>
 <rewrite>
 <rules>
 <rule name="React Routes" stopProcessing="true">
 <match url=".*" />
 <conditions logicalGrouping="MatchAll">
 <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
 <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
 <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
 </conditions>
 <action type="Rewrite" url="/" />
 </rule>
 </rules>
 </rewrite>
 </system.webServer>
</configuration>

Again build the application in prod mode and browse.


how to get the window title of a process using vb.net

Question: I am looking to go from the process name to the windows title.
e.g
'winamp.exe' -> '1. Britney Spears - Hit me baby one more time'
Thanks
Solution:
Dim p As Process

For Each p In Process.GetProcessesByName("winamp")

    MsgBox(p.MainWindowTitle.ToString)

Next

Comment: The `ToString` is utterly redundant in your code. `MainWindowTitle` is *already* a string!
Comment: Upvote for the window title.
Answer: Have a look at the System.Diagnostics.Process class:
Process p = <Get process>
Console.WriteLine(p.MainWindowTitle)

Comment: Thanks.. the MainWindowTitle was what I needed :)
Answer: Here's how to get the Filename as displayed in the Main Title Bar. This is the filename without the extension. Let's say that my Excel Workbook was named "ThisWorks.xlsx" This code returns "ThisWorks" without the file extension.
Function OpenAppFileNames(ByVal exeName As String) As String

    Dim p() As Process = System.Diagnostics.Process.GetProcessesByName(exeName)
    Dim i As Integer = 0
    Dim x As Integer = UBound(p) + 1
    Dim Index As Long = 0
    Dim Title As String = ""
    Dim Result As String = ""
    Debug.Print(x)
    Do
        If i = x Then
            Exit Do
        End If
        Title = p(i).MainWindowTitle
        Result += vbNewLine & "Index " & Index + i & " = " & Title
        i = i + 1
        'MsgBox(Result)
    Loop Until i = x

    Return Result

End Function

p returns an array of integers starting at 0 (zero). If you know which order the processes are in, you can return the Title/Filename of the desired target.
Hope this helps... took me 3 weeks to find this answer.
Comment: Something to note, though, is that some apps only open a single instance, like MS Word and MS Excel, but that single instance may have multiple workbooks open.


Update Akka-version: ClusterClient is not a member of package akka.contrib.pattern

Question: I used akka-2.3.9 and akka.contrib.pattern.ClusterClient.
Having updated the version akka-2.3.9 -> akka-2.4.9 I've got the following mistake:
ClusterClient is not a member of package akka.contrib.pattern

Should I use akka.cluster.client.ClusterClient instead of previous akka.contrib.pattern.ClusterClient ?
Answer: Yes. See 2.4.9 API vs 2.3.9 API.
Comment: Thanks! Also I've found the following migration guide: http://doc.akka.io/docs/akka/2.4.1/project/migration-guide-2.3.x-2.4.x.html#ClusterClient_construction


Divide arc in pieces of equal length

Question: I have an object described by the parametric equations $x = x\left(t\right)$ and $y = y\left(t\right)$. I want to divide the arc into $n$ pieces of equal length.
I know that the arc-length is defined by
$$l =\int_{0}^{2\pi}\sqrt{\left(x\left(t\right)'\right)^2+\left(y\left(t\right)'\right)^2 }\cdot dt.$$
I know that I need, for the $i$-th sub-arc, to solve the equation
$$ l_i=\frac{i}{n}l \overset{!}{=}\int_{0}^{t_i}\sqrt{\left(x\left(t\right)'\right)^2+\left(y\left(t\right)'\right)^2 }\cdot dt $$
for $t_i$.
However, the integral is of a form that, in general, can only be evaluated numerically.
Is there any way to solve for $t_i$ without knowing the analytic result of the integration?
Comment: It would strongly help your cause to post what your $x(t)$ and $y(t)$ are
Comment: They are both continuous and differentiable.
Answer: You can't solve for it analytically, but you are well set up for numerical root finding.  Given a $t$ you can compute the arc length up to $t$ and the derivative of the arc length with respect to $t$ is $\sqrt{\left(x\left(t\right)'\right)^2+\left(y\left(t\right)'\right)^2 }$ which you already know how to calculate.  This is perfect for Newton's method.
Comment: But what would be a suited initial guess for the approximation?
Comment: Absent better info, I would start with $\frac {2\pi}n$

Divide arc in pieces of equal length


Aplicativo Desktop + DB Online (Hospedagem)

Question: Boa tarde,
Galera, minha dúvida é a seguinte, na minha conexão de uma aplicativo desktop com banco de dados online:
1ª pergunta: Qual a melhor maneira de permanecer seguro a conexão realizada com o servidor de hospedagem?
2ª pergunta: Quais os riscos que irei correr e quais são as medidas que deveria tomar para eliminar ou diminuir esses riscos?
3ª pergunta: Tenho estas preocupações: Corrompimento de dados, invasões, queda de conexões e perca de dados. O que posso fazer para previnir este tipo de problema?
O meu aplicativo é feito em Delphi e meu banco de dados é Online (Servidor de Hospedagem).
Comment: Normalmente você não acessa o Banco no aplicativo desktop. O certo é acessar um serviço web, com autenticação etc. É muito dificil dizer qual a melhor técnica sem saber os detalhes do seu aplicativo, mas nunca se deve expor o banco de dados diretamente.
Comment: Exatamente isso que comente com meu chefe, mas como é aquele tipo de pessoa que quer o que pede, então pelo menos posso tentar diminuir os riscos de acesso.
Answer: Bom, vamos por ordem.

1: Como manter a comunicação segura: acessando diretamente o banco pelo seu aplicativo, não tem como (explicação abaixo). Como seria feita essa comunicação de forma segura: um serviço web no servidor do banco de dados, expondo chamadas de alto nível, com autenticação etc.

2: Riscos:
2.1: O seu banco de dados deve ter usuário/senha. Isso de forma alguma significa segurança através de uma rede. Pense assim: seu aplicativo precisa manter essas informações. Qualquer um com acesso ao aplicativo poderia extrair esses dados e comprometer o Banco. Você poderia limitar os IPs que acessam o banco, mas isso reduz pouco o problema.
2.2: Se o seu aplicativo acessa o banco diretamente, um erro no aplicativo poderia comprometer os dados. A integridade deve ser mantida o mais próximo possível do banco de dados.
2.3: Se o seu aplicativo acessa o banco de dados diretamente, não há nada entre os dois. Isso significa que você está expondo um banco de dados que aceita qualquer comando, qualquer instrução.

3: Sinceramente não tenho experiência em uma arquitetura onde o aplicativo desktop acessa diretamente o banco. Além da segurança para acesso, talvez com VPN, é imprescindível usar stored procedures no banco de dados para expor somente chamadas completas. Jamais expor o banco de dados de forma aberta.

Outras vantagens de uma camada de abstração (web service):

O serviço envia/recebe dados de mais alto nível do aplicativo, o que reduz comunicação clente/servidor. O web service está no mesmo servidor que o banco de dados, e todas as chamadas e consultas intermediárias ficam locais no servidor. Lembre-se: você paga pelos dados que entram e saem do servidor...
Se você precisa mudar o banco de dados, pode mudar o web service e manter tudo funcionando. Será possível atualizar imediatamente todos os aplicativos clientes? O web service você controla, e pode atualizar, oferecendo os mesmos métodos para os clientes, que nem vêm a alteração.
Parecido com o item 1, a performance web service-banco de dados é muito maior que cliente-banco de dados. Ciclos de consulta-atualização rápidas se mantidas no mesmo servidor podem levar minutos se houver ida e volta pro cliente.
Se uma chamada tiver potencial para alterar muitos registros, você aceita que esses registros sejam enviados para o cliente, atualizados e devolvidos ao servidor? E se cada trip levar 30 segundos?
Comment: Basicamente a forma mais indicada de fazer uma conexão com banco de dados hospedado é via WebService.
Comment: o que me diz, por meio do Cpanel configurar o IP da empresa, e por meio de vpn conectar o sistema ao ip da empresa, melhora um pouco mais?
Comment: Isso reduz o problema de segurança, mas e a quantidade de dados, tempo de ida e volta, e o que acontece se o cliente perder a conexão no meio de uma chamada?
Comment: Eu não sei como te informar como securizar isso, por isso não considero o que ecrevi como resposta completa. Tentei te desencorajar a fazer da forma que você perguntou, esperemos que alguém possa te informar como fazer do jeito que precisa de forma mais segura.
Comment: Na verdade, eu estou desencorajado a fazer isso desde o início, só fiz a pergunta no fórum por que meu chefe insistiu sobre a pesquisa, mesmo eu tendo dito que não é uma boa prática e ninguém faria isso. Indiquei o WebService pq é a forma mais segura que eu encontrei até agora, sei que há outras, mas mesmo assim, é cabeça dura o suficiente para me fazer perguntar coisas inúteis sobre coisas que eu já sei. Indo contra os princípios da segurança de dados.
Comment: Exato... eu postei mais no sentido de te dar munição se quiser debater isso.
Comment: Show de bola, muito obrigado. :D


Apple app site association file on azure app service (Spring Boot + Angular WebApp)

Question: I have a backend hosted on Azure AppService (linux) which is a SpringBoot 3 Application.
I put an apple-app-site-association.json file to /static/ and added a WebMvcConfigurer like that:
override fun addResourceHandlers(registry: ResourceHandlerRegistry) {

        // web in jar
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/")
                .resourceChain(true)
                .addResolver(object : PathResourceResolver() {
                    @Throws(IOException::class)
                    override fun getResource(resourcePath: String, location: Resource): Resource? {
                        val requestedResource = location.createRelative(resourcePath)
                        return if (requestedResource.exists() && requestedResource.isReadable) {
                            requestedResource
                        }
                        // env dependent file for ios universal deeplinks
                        else if (resourcePath == "apple-app-site-association") {
                            ClassPathResource("/static/apple-app-site-association-${environment.activeProfiles.first()}.json")
                        }
                        else {
                            ClassPathResource("/static/web/index.html")
                        }
                    }
                })
    }

I often read that .json should not be included in the filename, however I have some trouble setting the content-type with this resourcehandler and I am not sure if it is also necessary when it is done like this since the https://branch.io/resources/aasa-validator/ validates the domain.
The app gets the error Error getting enterprise-managed associated domains data in the device console when the app gets installed.
Answer: I realised that the problem was not the approach how the file is served but the file itself.
The teamId was missing in the appId field of the file:
{
  "applinks": {
    "details": [
      {
        "appIDs": [
          "<teamId>.app.id.dev"
        ],
        "components": [
          {
            "#": "no_universal_links",
            "exclude": true,
            "comment": "Matches any URL whose fragment equals no_universal_links and instructs the system not to open it as a universal link"
          },
          {
            "/": "/link/*",
            "comment": "comment"
          }
        ]
      }
    ]
  }
}


Drupal 7 Fields CSS

Question: I'm having trouble customizing the CSS for a content type I'm developing. Here's an example of what I'm trying to accomplish:

Field Name = Appetizers
Value 1 = Appetizer1 Name

Value 2 = Appetizer1 Price

Value 3 = Appetizer1 Description

Value 4 = Appetizer2 Name

Value 5 = Appetizer2 Price

Value 6 = Appetizer2 Description

etc...

In this case, if I want to style all Prices, I'd look to style field-item odd but I'd end up styling Name & Description as well.
Ideally, I'd want to have a class for Name, Price and Description. So I changed the field input format to Full HTML and started wrapping the value contents in those classes - but the markup looked pretty sloppy.
Essentially:

In that case I wouldn't have any styling applied to field-item even, so it seems like a waste to even have it in the first place. Why not just have my custom class only?
Is there a best practice for assigning a class on the value level? Preferably where I can override the field-item odd / field-item even assignment.
Answer: I've stumbled across this module, which appears like it could do the job.
http://drupal.org/project/fences
Details from its project page:

Fences is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and Views. You don't have to keep re-configuring the same HTML element over and over again every time you display the field.
Best of all, Fences provides leaner markup than Drupal 7 core! And can get rid of the extraneous classes too!
This kind of tool is needed in order to create semantic HTML5 output from Drupal. Without such a tool, you have to create custom field templates in your theme for every field.
Comment: Actually, the Fences module does not allow the user to set custom CSS classes for the field in the user interface, only the the field wrapper markup structure. However, if you write field templates, you can tell Fences to pick them up and make them selectable in the user interface, but you still have to write your own field templates for adding classes.
Answer: You can implement a field theme function in the template.php file of your theme, like this:
// Assuming that the field name is "field_foo".
THEMENAME_field__field_foo() {
  // Implementation...
}

See the default theme_field implementation as a starting point. In your case, you probably want to give different values to the $classes variable depending on the $delta.
As an alternative, you could implement a custom field template by copying the file modules/field/field.tpl.php to your theme's folder and renaming it to field--field_foo.tpl.php. Again, see the description of theme_field and comments for examples.
Another option: if you hate coding or are in a hurry, use the Field Templates extra functionality bundled with the Display Suite module (even though I don't think it covers your specific need).
Answer: Would using Views to output your content suit your situation?
If so, I suggest using the built-in facilities in Views that can add CSS classes to your fields based on variable-data - i.e. tokens, from the fields.
Follow the usual procedure to create a view to show your content type. Once you have created the view, for my solution to you, you would start from here:
admin/structure/views/view/<insert your view name here>/edit

Under fields, right-click on the field that you want to customise the CSS for. In the pop up you can control the markup output of both the wrapper and/or the content itself and construct CSS class names based on the field name or the content in the field itself.
See my example below:

Here you can see I am adding a CSS class generated from variable data using the tokens that are available - for a full list, expand the 'rewrite results' section, check the box 'rewrite the output of this field' and then click to expand the 'replacement patterns' subsection to see the available tokens. (NOTE: Don't forget to uncheck 'rewrite the output of this field' as you wouldn't be using it for this particular case - it was just to see the available tokens.)
Then in your theme, you can style the content, e.g. in my example, in stylesheet.css for my theme, the fragment of code added to it would be:
.label.label-actualfieldvalue {
    background-color: darkcyan;
}

(where actualfieldvalue is a value that can occur in that field.)
Also, someone else has provided an answer for a similar problem here:  Customizing a View with Taxonomy, color coding and icons

Drupal 7 Fields CSS


What are primitive roots modulo n?

Question: I'm trying to understand what primitive roots are for a given $\bmod\ n$. Wolfram's definition is as follows:

A primitive root of a prime $p$ is an integer $g$ such that $g\ (\bmod\ p)$ has
  multiplicative order $p-1$

The main thing I'm confused about is what "multiplicative order" is. Also, for the notation $g\ (\bmod\ p)$, is it saying $g$ times $\bmod\ p$ or does it have something to do with its congruence?
Sorry for the basic question, any clarification would be great!
Answer: Another equivalent definition of a primitive root mod $n$ is (from Wikipedia),

a number $g$ is a primitive root modulo $n$ if every number coprime to $n$ is congruent to a power of $g$ modulo $n$

For example, $3$ is a primitive root modulo $7$, but not modulo $11$, because
Modulo $7$,
$$3^0\equiv1,\; 3^1\equiv3,\; 3^2\equiv2,\; 3^3\equiv6,\; 3^4\equiv4,\; 3^5\equiv5,\; 3^6\equiv1\pmod{7}$$
And you got all the possible results: $1, 3, 2, 6, 4, 5$.
You can't get a $0$, but $0$ is not coprime to $7$, so it's not a problem. Hence $3$ is a primitive root modulo $7$.
Whereas, modulo $11$,
$$3^0\equiv1,\; 3^1\equiv3,\; 3^2\equiv9,\; 3^3\equiv5,\; 3^4\equiv4,\; 3^5\equiv1\pmod{11}$$
And modulo $11$, you only got the possible values $1, 3, 9, 5, 4$ and the sequence starts repeating after $3^5$, sou you will never get a $3^k\equiv2$, for example. Hence $3$ is not a primitive root modulo $11$.

The sequence $g^k$ is always repeating modulo $n$ after some value of $k$, since it can undertake only a finite number of values (so at least one value appears at least twice, for say $r,s$ and $r>s$ you have $g^r \equiv g^{s}$), and one term depends only on the preceding: $g^{k+1}\equiv g\cdot g^k$. Thus $g^{r+k}\equiv g^{s+k}$ for all $k$.
If $g$ and $n$ are coprime, it gets a bit simpler, because $g^k\equiv g^{k'} \pmod{n}$ for some $k, k'$ with $k>k'$ implies $g^{k-k'}\equiv 1$ (you can take the modular inverse because then all $g^k$ are coprime to $n$), then with $r=k-k'$, you have $g^{k+r}\equiv g^kg^r\equiv g^k$ for all $k$.
If $g$ and $n$ are not coprime, it's not as simple: if $g^r \equiv 0 \pmod{n}$ for some $r$ then $g^{k+r}\equiv g^kg^r\equiv 0$ for all $k$. But you may also have a repeating sequence without any $1$, for example, modulo $15$,
$$3^0\equiv1,\; 3^1\equiv3,\; 3^2\equiv9,\; 3^3\equiv12,\; 3^4\equiv6,\; 3^5\equiv3\pmod{15}$$
And it starts repeating after $3^4$, with numbers not coprime to $15$ since $g=3$ is not coprime to $n$ either. And actually, if $g$ and $n$ are not coprime, you never get a $1$ again after $g^0\equiv1 \pmod{n}$, because all $g^k$ have a common factor with $n$.

Alternately, the multiplicative order of $g$ modulo $n$ is the smallest exponent $k$ such that $g^k\equiv 1\pmod{n}$.
Here you see that the multiplicative order of $3$ modulo $7$ is $6$, and the multiplicative order of $3$ modulo $11$ is $5$, so by your definition, $3$ is indeed a primitive root modulo $7$, but not modulo $11$.
Notice also that the multiplicative order of $g$ modulo a prime $p$ is always less or equal to $p-1$, since Fermat's little theorem states that for a prime $p$ and $a$ not divisible by $p$, $a^{p-1}\equiv 1 \pmod{p}$. Then the multiplicative order is also always a divisor of $p-1$, and it leads to a simple algorithm to look for primitive roots:
To test a possible $g$, take the integer factorization of $p-1$, and for every prime factor $d$ of $p-1$, compute $g^{(p-1)/d}$ modulo $p$. If none of these is $1$, then $g$ is a primitive root modulo $p$, since $k=p-1$ is then the smallest $k$ such that $g^k\equiv 1\pmod{p}$.
For large $p$ and using modular exponentiation by squaring, it's much faster than computing all $g^k$ modulo $p$ for $k=0,1,\ldots,p-1$ and checking if all possible values are there (but you still need an integer factorization).
Comment: Ok, actually, in *"all possible numbers coprime to $n$"*, you need only check numbers below $n$, since as explained the sequence is repeating. For example, modulo $7$, you have $4\equiv 3^4\equiv3^{10}\equiv3^{16}\equiv\ldots$. The *results* are the values of $g^k$ modulo $n$. For example, with $g=3$ and $n=7$, they are $1,3,2,6,4,5$ (for $k=0,1,2,3,4,5$).
Comment: Thank you so much for the answer! It's really descriptive so it'll take some time for me to understand this fully. I'm still a little stuck on the first part. Aren't there infinite coprimes to `n` ?
Comment: Sorry, I don't understand your question (in case it's that, notice that modulo $n$, $g^k$ can only take values in $0, 1 \ldots, n-1$). Also, I corrected a small mistake in the "repeating" part: if $g$ and $n$ are coprime it's quite nice, but if $g$ and $n$ have a common factor, you don't always get a repeating $0$ (I added an example).
Comment: Sorry for the confusion. The phrase where it says " if every number comprime to n", where in the following expression are these coprimes? Also, "all the possible results", what exactly are the results? Thanks again
Comment: This clears things up a lot, thank you so much! If you don't mind, I'm going to ask you later if I get stuck on the other information you've provided.
Comment: Of course you can ask, no problem :-)
Comment: hello again, I had another quick question. Since 0 is not a coprime of 7 why do you raise g to the power of 0? Thanks!
Comment: $g$ is coprime to $a$, but that has nothing to do with exponents. What is interesting here is the values (and the number of distinct values) of $k \to g^k \mod{n}$, and, yes, starting at $k=0$.
Comment: Does there exist a proof somewhere that the sequence _g^k_ mod _n_ definitely repeats after some _k_? Can one not argue that even if the sequence seems to repeat that it could be part of a much larger non-repeating sequence?
Answer: You're wondering about the ring (with additive structure and multiplicative structure) $\mathbb Z$ modulo $n$, often denoted $\mathbb Z/(n)$. You can add and you can multiply modulo $n$, the operations make good sense.
For a general (not necessarily prime) $n$, the multiplicative structure can be fairly ill-behaved. For instance, when $n=8$, you have $4\cdot2=0$, product of two nonzero things coming out to be zero. There are quantities modulo $n$ ("residues mod $n$") that have reciprocals, however: for the case $n=15$, we have $2\cdot8=1$, modulo $15$. The residues that do have reciprocals can be denoted $(\mathbb Z/(n))^*$ or some such, and this system is a multiplicative structure on its own, a "multiplicative group". Under certain circumstances, this multiplicative group is "cyclic", that is, there is one particular element whose powers run through all the things in $(\mathbb Z/(n))^*$. For instance, you can check that the elements of $(\mathbb Z/(9))^*$ are $\{1,2,4,5,7,8\}$, and you can also check that every one of these is a power of two, modulo nine. When there is such a nice residue as $2$ is here, it's called a primitive root, and it's a serious Theorem that when $n$ is a prime, there always is a primitive root. For instance, $n=5$ has $2$ for a p.r., $n=7$ can't use $2$, but $3$ is a good p.r. There are some helpful guidelines for finding a primitive root, but I don't want to go there tonight. The important fact is that the only numbers $n$ that have primitive roots modulo $n$ are of the form $2^\varepsilon p^m$, where $\varepsilon$ is either $0$ or $1$, $p$ is an odd prime, and $m\ge0$

What are primitive roots modulo n?


Unexpected output when trying to print user input through arrays

Question: This code takes in user input into an array and then prints it. Every time I print the user input a random extra character is printed at the end.
#include <stdio.h>
#include <ctype.h>

int main(void)
{
    char arr[100];
    char c;
    printf("Enter a Sentence:");
    int i =0;
    for (i = 0;(c = getchar()) != '\n';++i)
        arr[i] = c;
    arr[++i] = '\n';
    for (int i = 0;arr[i] != '\n';++i)
        putchar(arr[i]);
}

For example I expected the output of
Enter a sentence:abc

to be abc but instead I got abcu.
Comment: Unneeded include: `#include `.
Comment: 1) the posted code has no limit on the number of characters that the user can enter.  This is a potential error.  2) the posted code fails to output the final '\n' so the data will not be actually output until after the program ends
Comment: You should use type `int` for `c`, not type `char`.  That's the type returned by `getchar`, and you will not be able to properly distinguish an `EOF` value if you cast the result to `char` before checking for it.
Comment: This is another example of why the *preincrement* operator (e.g. `++i`) should be avoided in favor of the *postincrement* operator `i++`.
Comment: This code should not compile. You're defining `i` twice: `int i =0;` and `for (int i = 0;arr[i] != '\n';++i)`.
Answer: Change this
arr[++i] = '\n'; /* this skips the current a[i] & put \n into next position which is incorrect */

to
arr[i] = '\n';

as the variable i already incremented in condition part of for loop here
for (i = 0;(c = getchar()) != '\n';++i /* before loop terminating i incremented here */) {
     arr[i] = c;
 }

Also its good to initialize the buffer while declaring itself to avoid getting some junk value. For e.g
char arr[100] = {}; /* zerod whole array */

And also make sure  this (c = getchar()) != '\n' doesn't happen >100 times else buffer overflow happens which cause undefined behavior. One possible way is
for (i = 0; i < sizeof(arr)-1 && (c = getchar()) != '\n';++i) {
     arr[i] = c;
}

Answer: This:
for (i = 0;(c = getchar()) != '\n';++i)
    arr[i] = c;
arr[++i] = '\n'; /* here */

should be this:
for (i = 0;(c = getchar()) != '\n' && i < 100;++i)
    arr[i] = c;
arr[i] = '\n'; /* here */

You're skipping one character of the buffer, as i had been incremented already at the end of the previous loop. This reads uninitialized data from the buffer (presumably originating from the stack).
You're also not stopping past the end of the buffer, which could cause buffer overflow.
Along with that, you should probably initialize the array with this:
char arr[100] = { '\0' };

Answer: Regarding:
arr[++i] = '\n';

This is incrementing i before assigning '\n', so arr[++i] points an extra character into the array.
That is why an unexpected character is being printed.
If you replace that statement with:
arr[i] = '\n';

your code should work.
Comment: @JL2210,  There are many ways that the code can be corrected.  So demanding that the OP fix the code a certain way, as your edit is doing, is very misleading.  That is why my (original) answer 'suggested' rather than demanded a specific fix
Comment: Is that better?
Comment: @JL2210:  Yes, That is much better
Answer: When you read the newline, i has just been increased to 3 by the update expression in the first for loop.
Then arr[++i] = '\n' increases i to 4 and assigns to arr[4]. Nothing ever gets assigned to arr[3], but it appears that this location happened to contain an u when the array was allocated from the stack.


create a circle image with text

Question: I want to create  a circle image with text like a picture, i upload in below

But i create a circle image with text like this show in after correct image

.circles {
  margin: auto;
  height: 73px;
  width: 130px;
  border: 2px solid black;
  display: flex;
  justify-content: center;
  overflow: hidden;
  background-color: black;
  opacity: 50%;
  border-top-right-radius: 50%;
  border-top-left-radius: 50%;
  margin-top: -169px;
}

.tit {
  color: white
}

Title

Answer:

.round {
  background: #fff;
  border: 2px solid #000;
  width: 100px;
  height: 100px;
  border-radius: 50px;
  overflow: hidden;
}
.text {
  background-color: black;
  opacity: 50%;
  color: #fff;
  padding: 10px;
  text-align: center;
  z-index: 999;
  position: relative;
}
.image {
  background-color: #e6baba;
  height: 100px;
  width: 100px;
  position: relative;
  top: -38px;
  z-index: 9;
}

    Text

    Add Image Here

Answer: update your CSS file
.text-container {
  background-color: black;
  opacity: 50%;
  padding: 10px;
  text-align: center;
  z-index: 999;
  color: #fff;
  position: relative;
}
.image-container {
  background-color: #e6baba;
  height: 100px;
  width: 100px;
  z-index: 9;
  position: relative;
  top: -38px;

}
.circle-container {
  background: #fff;
  border: 2px solid #000;
  height: 100px;
  width: 100px;
  overflow: hidden;
  border-radius: 50px;
}

Use HTML as below

    Add Image Here

    Text

create a circle image with text